answer
stringlengths
17
10.2M
package org.scijava.util; import java.math.BigDecimal; import java.math.BigInteger; /** * Useful methods for working with {@link Number} objects. * * @author Curtis Rueden * @author Barry DeZonia */ public final class NumberUtils { private NumberUtils() { // prevent instantiation of utility class } /** * Converts the given object to a {@link Number} of the specified type, or * null if the types are incompatible. */ public static Number toNumber(final Object value, final Class<?> type) { final Object num = ConversionUtils.convert(value, type); return num == null ? null : ConversionUtils.cast(num, Number.class); } public static BigDecimal asBigDecimal(final Number n) { // Using .doubleValue on a long or BigInteger would cause loss of accuracy if(BigInteger.class.isInstance(n)){ return new BigDecimal((BigInteger) n); } else if(Long.class.isInstance(n)){ return new BigDecimal(n.longValue()); } return new BigDecimal(n.doubleValue()); } public static BigInteger asBigInteger(final Number n) { return BigInteger.valueOf(n.longValue()); } public static Number getMinimumNumber(final Class<?> type) { if (ClassUtils.isByte(type)) return Byte.MIN_VALUE; if (ClassUtils.isShort(type)) return Short.MIN_VALUE; if (ClassUtils.isInteger(type)) return Integer.MIN_VALUE; if (ClassUtils.isLong(type)) return Long.MIN_VALUE; if (ClassUtils.isFloat(type)) return -Float.MAX_VALUE; if (ClassUtils.isDouble(type)) return -Double.MAX_VALUE; return null; } public static Number getMaximumNumber(final Class<?> type) { if (ClassUtils.isByte(type)) return Byte.MAX_VALUE; if (ClassUtils.isShort(type)) return Short.MAX_VALUE; if (ClassUtils.isInteger(type)) return Integer.MAX_VALUE; if (ClassUtils.isLong(type)) return Long.MAX_VALUE; if (ClassUtils.isFloat(type)) return Float.MAX_VALUE; if (ClassUtils.isDouble(type)) return Double.MAX_VALUE; return null; } public static Number getDefaultValue(final Number min, final Number max, final Class<?> type) { if (min != null) return min; if (max != null) return max; return toNumber("0", type); } public static Number clampToRange(final Class<?> type, final Number value, final Number min, final Number max) { if (value == null) return getDefaultValue(min, max, type); if (Comparable.class.isAssignableFrom(type)) { @SuppressWarnings("unchecked") final Comparable<Number> cValue = (Comparable<Number>) value; if (min != null && cValue.compareTo(min) < 0) return min; if (max != null && cValue.compareTo(max) > 0) return max; } return value; } }
package gov.nasa.jpl.mbee; import gov.nasa.jpl.mbee.ems.sync.AutosyncStatusConfigurator; import gov.nasa.jpl.mbee.ems.sync.OutputQueueStatusConfigurator; import gov.nasa.jpl.mbee.ems.sync.OutputSyncRunner; import gov.nasa.jpl.mbee.lib.Debug; import gov.nasa.jpl.mbee.patternloader.PatternLoaderConfigurator; import gov.nasa.jpl.mbee.web.sync.ApplicationSyncEventSubscriber; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; import java.util.jar.JarFile; import com.nomagic.magicdraw.actions.ActionsConfiguratorsManager; import com.nomagic.magicdraw.evaluation.EvaluationConfigurator; import com.nomagic.magicdraw.plugins.Plugin; import com.nomagic.magicdraw.uml.DiagramTypeConstants; public class DocGenPlugin extends Plugin { // Variables for running embedded web server for exposing services private DocGenEmbeddedServer embeddedServer; private boolean runEmbeddedServer = false; protected OclEvaluatorPlugin oclPlugin = null; protected ValidateConstraintsPlugin vcPlugin = null; protected AutoSyncPlugin autoSyncPlugin = null; public static ClassLoader extensionsClassloader = null; public DocGenPlugin() { super(); Debug.outln("constructed DocGenPlugin!"); } @Override public boolean close() { if (runEmbeddedServer) { try { embeddedServer.teardown(); } catch (Throwable e) { e.printStackTrace(); } } return true; } @Override public void init() { ActionsConfiguratorsManager acm = ActionsConfiguratorsManager.getInstance(); System.setProperty ("jsse.enableSNIExtension", "false"); DocGenConfigurator dgc = new DocGenConfigurator(); acm.addContainmentBrowserContextConfigurator(dgc); acm.addSearchBrowserContextConfigurator(dgc); acm.addBaseDiagramContextConfigurator(DiagramTypeConstants.UML_ANY_DIAGRAM, dgc); //acm.addBaseDiagramContextConfigurator("Class Diagram", dgc); //acm.addBaseDiagramContextConfigurator("Activity Diagram", dgc); //acm.addBaseDiagramContextConfigurator("SysML Package Diagram", dgc); PatternLoaderConfigurator plc = new PatternLoaderConfigurator(); acm.addBaseDiagramContextConfigurator(DiagramTypeConstants.UML_ANY_DIAGRAM, plc); acm.addMainMenuConfigurator(new MMSConfigurator()); EvaluationConfigurator.getInstance().registerBinaryImplementers(DocGenPlugin.class.getClassLoader()); SRConfigurator srconfig = new SRConfigurator(); acm.addSearchBrowserContextConfigurator(srconfig); acm.addContainmentBrowserContextConfigurator(srconfig); acm.addBaseDiagramContextConfigurator(DiagramTypeConstants.UML_ANY_DIAGRAM, srconfig); acm.addMainToolbarConfigurator(new OutputQueueStatusConfigurator()); acm.addMainToolbarConfigurator(new AutosyncStatusConfigurator()); getOclPlugin().init(); getVcPlugin().init(); getAutoSyncPlugin().init(); (new Thread(new OutputSyncRunner())).start(); //ApplicationSyncEventSubscriber.subscribe(); //really old docweb sync, should remove related code loadExtensionJars(); // people can actaully just create a new plugin and } public OclEvaluatorPlugin getOclPlugin() { if (oclPlugin == null) { oclPlugin = new OclEvaluatorPlugin(); } return oclPlugin; } public ValidateConstraintsPlugin getVcPlugin() { if (vcPlugin == null) { vcPlugin = new ValidateConstraintsPlugin(); } return vcPlugin; } public AutoSyncPlugin getAutoSyncPlugin() { if (autoSyncPlugin == null) { autoSyncPlugin = new AutoSyncPlugin(); } return autoSyncPlugin; } @Override public boolean isSupported() { return true; } /** * Overrides the embedded server flag based on system property being set. */ private void getEmbeddedSystemProperty() { String embedded = System.getProperty("mdk.embeddedserver"); if (embedded != null) { if (embedded.equalsIgnoreCase("true")) { runEmbeddedServer = true; } else if (embedded.equalsIgnoreCase("false")) { runEmbeddedServer = false; } } } private void loadExtensionJars() { File extensionDir = new File(getDescriptor().getPluginDirectory(), "extensions"); if (!extensionDir.exists()) { extensionsClassloader = DocGenPlugin.class.getClassLoader(); return; } List<URL> extensions = new ArrayList<URL>(); try { extensions.add(extensionDir.toURI().toURL()); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (File file: extensionDir.listFiles()) { try { @SuppressWarnings("unused") JarFile jarFile = new JarFile(file); extensions.add(file.toURI().toURL()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } extensionsClassloader = new URLClassLoader(extensions.toArray(new URL[] {}), DocGenPlugin.class.getClassLoader()); } }
package org.vetmeduni.readtools; import htsjdk.samtools.util.Log; import htsjdk.samtools.util.StringUtil; import org.vetmeduni.tools.Tool; import org.vetmeduni.tools.ToolNames; import org.vetmeduni.tools.implemented.TrimFastq; import org.vetmeduni.utils.TimeWatch; import java.io.PrintWriter; import java.util.Arrays; public class Main { // the logger for this class public static Log logger = Log.getInstance(Main.class); /** * Main method * * @param args the args for the command line */ public static void main(String[] args) { if (args.length == 0) { generalHelp(""); } else if (args[0].equals("--debug")) { Log.setGlobalLogLevel(Log.LogLevel.DEBUG); logger.debug("DEBUG mode on"); if (args.length == 1) { logger.debug("Debug mode only works with a tool"); System.exit(1); } args = Arrays.copyOfRange(args, 1, args.length); } else { Log.setGlobalLogLevel(Log.LogLevel.INFO); } try { Tool toRun = ToolNames.getTool(args[0]); TimeWatch elapsed = TimeWatch.start(); int exitStatus = toRun.run(Arrays.copyOfRange(args, 1, args.length)); switch (exitStatus) { case 0: logger.info("Elapsed time for ", toRun.getClass().getSimpleName(), ": ", elapsed); break; case 1: logger.info("Finishing with errors"); logger.debug("Elapsed time to error: ", elapsed); break; default: logger.error("Unexpected error. Please contact with ", ProjectProperties.getContact()); } System.exit(exitStatus); } catch (IllegalArgumentException e) { logger.debug(e.getMessage()); logger.debug(e); generalHelp("Tool '" + args[0] + "' does not exists"); } } /** * Print the program header to the standard error */ public static void printProgramHeader() { String header = String.format("%s (compiled on %s)", ProjectProperties.getFormattedNameWithVersion(), ProjectProperties.getTimestamp()); System.err.println(header); System.err.println(StringUtil.repeatCharNTimes('=', header.length())); } /** * Print the program header to this print writer */ public static void printProgramHeader(PrintWriter writer) { String header = String.format("%s (compiled on %s)", ProjectProperties.getFormattedNameWithVersion(), ProjectProperties.getTimestamp()); writer.println(header); writer.println(StringUtil.repeatCharNTimes('=', header.length())); } /** * Get the usage of the main jar * * @return formatted usage */ public static String usageMain() { return String.format("Usage: java -jar %s.jar", ProjectProperties.getName()); } /** * Print the general help in the standard error * * @param error the standard error */ public static void generalHelp(String error) { printProgramHeader(); System.err.println(); System.err.println(usageMain() + " <tool> [options]"); System.err.println(); System.err.println("Tools:"); for (ToolNames name : ToolNames.values()) { System.err.println("\t" + name + ":\t" + name.shortDescription); } if (!error.equals("")) { System.err.println(); System.err.println("error: " + error); } System.err.println(); System.exit(1); } }
package hudson.plugins.ec2; import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.Util; import hudson.model.Node; import hudson.slaves.SlaveComputer; import java.io.IOException; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import com.amazonaws.AmazonClientException; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.GetConsoleOutputRequest; import com.amazonaws.services.ec2.model.Instance; /** * @author Kohsuke Kawaguchi */ public class EC2Computer extends SlaveComputer { /** * Cached description of this EC2 instance. Lazily fetched. */ private volatile Instance ec2InstanceDescription; public EC2Computer(EC2AbstractSlave slave) { super(slave); } @Override public EC2AbstractSlave getNode() { return (EC2AbstractSlave) super.getNode(); } @CheckForNull public String getInstanceId() { EC2AbstractSlave node = getNode(); return node == null ? null : node.getInstanceId(); } public String getEc2Type() { EC2AbstractSlave node = getNode(); return node == null ? null : node.getEc2Type(); } public String getSpotInstanceRequestId() { EC2AbstractSlave node = getNode(); if (node instanceof EC2SpotSlave) { return ((EC2SpotSlave) node).getSpotInstanceRequestId(); } return ""; } public EC2Cloud getCloud() { EC2AbstractSlave node = getNode(); return node == null ? null : node.getCloud(); } public SlaveTemplate getSlaveTemplate() { EC2AbstractSlave node = getNode(); if (node != null) { return node.getCloud().getTemplate(node.templateDescription); } return null; } /** * Gets the EC2 console output. */ public String getConsoleOutput() throws AmazonClientException { AmazonEC2 ec2 = getCloud().connect(); GetConsoleOutputRequest request = new GetConsoleOutputRequest(getInstanceId()); return ec2.getConsoleOutput(request).getOutput(); } /** * Obtains the instance state description in EC2. * * <p> * This method returns a cached state, so it's not suitable to check {@link Instance#getState()} from the returned * instance (but all the other fields are valid as it won't change.) * * The cache can be flushed using {@link #updateInstanceDescription()} */ public Instance describeInstance() throws AmazonClientException, InterruptedException { if (ec2InstanceDescription == null) ec2InstanceDescription = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); return ec2InstanceDescription; } /** * This will flush any cached description held by {@link #describeInstance()}. */ public Instance updateInstanceDescription() throws AmazonClientException, InterruptedException { return ec2InstanceDescription = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); } /** * Gets the current state of the instance. * * <p> * Unlike {@link #describeInstance()}, this method always return the current status by calling EC2. */ public InstanceState getState() throws AmazonClientException, InterruptedException { ec2InstanceDescription = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); return InstanceState.find(ec2InstanceDescription.getState().getName()); } /** * Number of milli-secs since the instance was started. */ public long getUptime() throws AmazonClientException, InterruptedException { return System.currentTimeMillis() - describeInstance().getLaunchTime().getTime(); } /** * Returns uptime in the human readable form. */ public String getUptimeString() throws AmazonClientException, InterruptedException { return Util.getTimeSpanString(getUptime()); } /** * When the slave is deleted, terminate the instance. */ @Override public HttpResponse doDoDelete() throws IOException { checkPermission(DELETE); EC2AbstractSlave node = getNode(); if (node != null) node.terminate(); return new HttpRedirect(".."); } /** * What username to use to run root-like commands * * @return remote admin or {@code null} if the associated {@link Node} is {@code null} */ @CheckForNull public String getRemoteAdmin() { EC2AbstractSlave node = getNode(); return node == null ? null : node.getRemoteAdmin(); } public int getSshPort() { EC2AbstractSlave node = getNode(); return node == null ? 22 : node.getSshPort(); } public String getRootCommandPrefix() { EC2AbstractSlave node = getNode(); return node == null ? "" : node.getRootCommandPrefix(); } public String getSlaveCommandPrefix() { EC2AbstractSlave node = getNode(); return node == null ? "" : node.getSlaveCommandPrefix(); } public String getSlaveCommandSuffix() { EC2AbstractSlave node = getNode(); return node == null ? "" : node.getSlaveCommandSuffix(); } public void onConnected() { EC2AbstractSlave node = getNode(); if (node != null) { node.onConnected(); } } }
package org.yinwang.pysonar; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.google.common.collect.Lists; import org.jetbrains.annotations.NotNull; import org.yinwang.pysonar.ast.FunctionDef; import org.yinwang.pysonar.ast.Node; import org.yinwang.pysonar.types.Type; import java.io.*; import java.util.*; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; public class JSONDump { private static final int MAX_PATH_LENGTH = 900; private static Logger log = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); private static Set<String> seenDef = new HashSet<>(); private static Set<String> seenRef = new HashSet<>(); private static Set<String> seenDocs = new HashSet<>(); private static String dirname(String path) { return new File(path).getParent(); } private static Indexer newIndexer(String srcpath, String[] inclpaths) throws Exception { Indexer idx = new Indexer(); for (String inclpath : inclpaths) { idx.addPath(inclpath); } idx.loadFileRecursive(srcpath); idx.finish(); if (idx.semanticErrors.size() > 0) { log.info("Indexer errors:"); for (Entry<String, List<Diagnostic>> entry : idx.semanticErrors.entrySet()) { String k = entry.getKey(); log.info(" Key: " + k); List<Diagnostic> diagnostics = entry.getValue(); for (Diagnostic d : diagnostics) { log.info(" " + d); } } } return idx; } private static void writeSymJson(Def def, JsonGenerator json) throws IOException { Binding binding = def.getBinding(); if (def.getStart() < 0) { return; } String name = def.getName(); boolean isExported = !( Binding.Kind.VARIABLE == binding.getKind() || Binding.Kind.PARAMETER == binding.getKind() || Binding.Kind.SCOPE == binding.getKind() || Binding.Kind.ATTRIBUTE == binding.getKind() || (def.hasName() && (name.length() == 0 || name.charAt(0) == '_' || name.startsWith("lambda%")))); // boolean isExported = true; String path = binding.getQname().replace('.', '/').replace("%20", "."); // if (binding.getKind() == Binding.Kind.MODULE) { // Util.msg("module! path: " + path); if (!seenDef.contains(path)) { seenDef.add(path); json.writeStartObject(); json.writeStringField("name", name); json.writeStringField("path", path); json.writeStringField("file", def.getFileOrUrl()); json.writeNumberField("identStart", def.getStart()); json.writeNumberField("identEnd", def.getEnd()); json.writeNumberField("defStart", def.getBodyStart()); json.writeNumberField("defEnd", def.getBodyEnd()); json.writeBooleanField("exported", isExported); json.writeStringField("kind", def.getBinding().getKind().toString()); if (Binding.Kind.FUNCTION == binding.getKind() || Binding.Kind.METHOD == binding.getKind() || Binding.Kind.CONSTRUCTOR == binding.getKind()) { json.writeObjectFieldStart("funcData"); // get args expression String argExpr = null; Type t = def.getBinding().getType(); if (t.isUnionType()) { t = t.asUnionType().firstUseful(); } if (t != null && t.isFuncType()) { FunctionDef func = t.asFuncType().getFunc(); if (func != null) { StringBuilder args = new StringBuilder(); args.append("("); boolean first = true; for (Node n : func.getArgs()) { if (!first) { args.append(", "); } first = false; args.append(n.toDisplay()); } if (func.getVararg() != null) { if (!first) args.append(", "); args.append("*" + func.getVararg().toDisplay()); } if (func.getKwarg() != null) { if (!first) args.append(", "); args.append("**" + func.getKwarg().toDisplay()); } args.append(")"); argExpr = args.toString(); } } String typeExpr = def.getBinding().getType().toString(); json.writeNullField("params"); String signature = argExpr==null? "" : argExpr + "\n" + typeExpr; json.writeStringField("signature", signature); json.writeEndObject(); } json.writeEndObject(); } } private static void writeRefJson(Ref ref, Binding binding, JsonGenerator json) throws IOException { Def def = binding.getSingle(); String path = binding.getQname().replace(".", "/").replace("%20", "."); // Util.msg("path: " + path); if (def.getStart() >= 0 && def.getFile() != null && ref.start() >= 0 && !binding.isBuiltin()) { json.writeStartObject(); json.writeStringField("sym", path); json.writeStringField("file", ref.getFile()); json.writeNumberField("start", ref.start()); json.writeNumberField("end", ref.end()); json.writeBooleanField("builtin", binding.isBuiltin()); json.writeEndObject(); } } private static void writeDocJson(Def def, Indexer idx, JsonGenerator json) throws Exception { String path = def.getBinding().getQname().replace('.', '/').replace("%20", "."); // Util.msg("path: " + path); if (!seenDocs.contains(path)) { seenDocs.add(path); if (def.docstring != null) { json.writeStartObject(); json.writeStringField("sym", path); json.writeStringField("file", def.getFileOrUrl()); json.writeStringField("body", def.docstring); json.writeNumberField("start", def.docstringStart); json.writeNumberField("end", def.docstringEnd); json.writeEndObject(); } else if (def.getBinding().getKind() == Binding.Kind.MODULE) { AstCache.DocstringInfo info = idx.getModuleDocstringInfoForFile(def.getFileOrUrl()); if (info != null) { json.writeStartObject(); json.writeStringField("sym", path); json.writeStringField("file", def.getFileOrUrl()); json.writeStringField("body", info.docstring); json.writeNumberField("start", info.start); json.writeNumberField("end", info.end); json.writeEndObject(); } } } } private static boolean shouldEmit(@NotNull String pathToMaybeEmit, String srcpath) { return Util.unifyPath(pathToMaybeEmit).startsWith(Util.unifyPath(srcpath)); } /* * Precondition: srcpath and inclpaths are absolute paths */ private static void graph(String srcpath, String[] inclpaths, OutputStream symOut, OutputStream refOut, OutputStream docOut) throws Exception { // Compute parent dirs, sort by length so potential prefixes show up first List<String> parentDirs = Lists.newArrayList(inclpaths); parentDirs.add(dirname(srcpath)); Collections.sort(parentDirs, new Comparator<String>() { @Override public int compare(String s1, String s2) { int diff = s1.length() - s2.length(); if (0 == diff) { return s1.compareTo(s2); } return diff; } }); Indexer idx = newIndexer(srcpath, inclpaths); idx.multilineFunType = true; JsonFactory jsonFactory = new JsonFactory(); JsonGenerator symJson = jsonFactory.createGenerator(symOut); JsonGenerator refJson = jsonFactory.createGenerator(refOut); JsonGenerator docJson = jsonFactory.createGenerator(docOut); JsonGenerator[] allJson = {symJson, refJson, docJson}; for (JsonGenerator json : allJson) { json.writeStartArray(); } for (List<Binding> bindings : idx.getAllBindings().values()) { for (Binding b : bindings) { for (Def def : b.getDefs()) { if (def.getFile() != null) { if (shouldEmit(def.getFile(), srcpath)) { writeSymJson(def, symJson); writeDocJson(def, idx, docJson); } } } for (Ref ref : b.getRefs()) { if (ref.getFile() != null) { String key = ref.getFile() + ":" + ref.start(); if (!seenRef.contains(key) && shouldEmit(ref.getFile(), srcpath)) { writeRefJson(ref, b, refJson); seenRef.add(key); } } } } } for (JsonGenerator json : allJson) { json.writeEndArray(); json.close(); } } private static void info(Object msg) { System.out.println(msg); } private static void usage() { info("Usage: java org.yinwang.pysonar.dump <source-path> <include-paths> <out-root> [verbose]"); info(" <source-path> is path to source unit (package directory or module file) that will be graphed"); info(" <include-paths> are colon-separated paths to included libs"); info(" <out-root> is the prefix of the output files. There are 3 output files: <out-root>-doc, <out-root>-sym, <out-root>-ref"); info(" [verbose] if set, then verbose logging is used (optional)"); } public static void main(String[] args) throws Exception { if (args.length < 3 || args.length > 4) { usage(); return; } log.setLevel(Level.SEVERE); if (args.length >= 4) { log.setLevel(Level.ALL); log.info("LOGGING VERBOSE"); log.info("ARGS: " + Arrays.toString(args)); } String srcpath = args[0]; String[] inclpaths = args[1].split(":"); String outroot = args[2]; String symFilename = outroot + "-sym"; String refFilename = outroot + "-ref"; String docFilename = outroot + "-doc"; OutputStream symOut = null, refOut = null, docOut = null; try { docOut = new BufferedOutputStream(new FileOutputStream(docFilename)); symOut = new BufferedOutputStream(new FileOutputStream(symFilename)); refOut = new BufferedOutputStream(new FileOutputStream(refFilename)); Util.msg("graphing: " + srcpath); graph(srcpath, inclpaths, symOut, refOut, docOut); docOut.flush(); symOut.flush(); refOut.flush(); } catch (FileNotFoundException e) { System.err.println("Could not find file: " + e); return; } finally { if (docOut != null) { docOut.close(); } if (symOut != null) { symOut.close(); } if (refOut != null) { refOut.close(); } } log.info("SUCCESS"); } }
package info.faceland.mint; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.nunnerycode.mint.MintPlugin; import java.text.DecimalFormat; import java.util.List; import java.util.UUID; public class MintEconomy implements Economy { private static final DecimalFormat DF = new DecimalFormat(" private MintPlugin plugin; public MintEconomy(MintPlugin plugin) { this.plugin = plugin; } @Override public boolean isEnabled() { return true; } @Override public String getName() { return "Mint"; } @Override public boolean hasBankSupport() { return true; } @Override public int fractionalDigits() { return 0; } @Override public String format(double v) { if (v == 1.00D) { return String.format("%s %s", DF.format(v), currencyNameSingular()); } return String.format("%s %s", DF.format(v), currencyNamePlural()); } @Override public String currencyNamePlural() { return plugin.getSettings().getString("config.currency-plural", "Bits"); } @Override public String currencyNameSingular() { return plugin.getSettings().getString("config.currency-singular", "Bit"); } @Override public boolean hasAccount(String s) { UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } return plugin.getManager().hasPlayerAccount(uuid) || createPlayerAccount(s); } @Override public boolean hasAccount(OfflinePlayer player) { return hasAccount(player.getUniqueId().toString()); } @Override public boolean hasAccount(String s, String s2) { return hasAccount(s); } @Override public boolean hasAccount(OfflinePlayer player, String worldName) { return hasAccount(player); } @Override public double getBalance(String s) { if (!hasAccount(s)) { return 0; } UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } return plugin.getManager().getPlayerBalance(uuid); } @Override public double getBalance(OfflinePlayer player) { return getBalance(player.getUniqueId().toString()); } @Override public double getBalance(String s, String s2) { return getBalance(s); } @Override public double getBalance(OfflinePlayer player, String world) { return getBalance(player); } @Override public boolean has(String s, double v) { return hasAccount(s) && getBalance(s) >= v; } @Override public boolean has(OfflinePlayer player, double amount) { return has(player.getUniqueId().toString(), amount); } @Override public boolean has(String s, String s2, double v) { return has(s, v); } @Override public boolean has(OfflinePlayer player, String worldName, double amount) { return has(player, amount); } @Override public EconomyResponse withdrawPlayer(String s, double v) { if (!hasAccount(s)) { createPlayerAccount(s); } UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } double balance = plugin.getManager().getPlayerBalance(uuid); if (!has(s, v)) { return new EconomyResponse(v, balance, EconomyResponse.ResponseType.FAILURE, null); } plugin.getManager().setPlayerBalance(uuid, balance - Math.abs(v)); Bukkit.getPluginManager().callEvent(new MintEvent(s)); return new EconomyResponse(v, balance - Math.abs(v), EconomyResponse.ResponseType.SUCCESS, null); } @Override public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) { return withdrawPlayer(player.getUniqueId().toString(), amount); } @Override public EconomyResponse withdrawPlayer(String s, String s2, double v) { return withdrawPlayer(s, v); } @Override public EconomyResponse withdrawPlayer(OfflinePlayer player, String worldName, double amount) { return withdrawPlayer(player, amount); } @Override public EconomyResponse depositPlayer(String s, double v) { if (!hasAccount(s)) { createPlayerAccount(s); } UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } double balance = plugin.getManager().getPlayerBalance(uuid); plugin.getManager().setPlayerBalance(uuid, balance + Math.abs(v)); Bukkit.getPluginManager().callEvent(new MintEvent(s)); return new EconomyResponse(v, balance + Math.abs(v), EconomyResponse.ResponseType.SUCCESS, null); } @Override public EconomyResponse depositPlayer(OfflinePlayer player, double amount) { return depositPlayer(player.getUniqueId().toString(), amount); } @Override public EconomyResponse depositPlayer(String s, String s2, double v) { return depositPlayer(s, v); } @Override public EconomyResponse depositPlayer(OfflinePlayer player, String worldName, double amount) { return depositPlayer(player, amount); } @Override public EconomyResponse createBank(String s, String s2) { UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } plugin.getManager().setBankBalance(uuid, 0D); return new EconomyResponse(0D, plugin.getManager().getBankBalance(uuid), EconomyResponse.ResponseType.SUCCESS, null); } @Override public EconomyResponse createBank(String name, OfflinePlayer player) { return createBank(name, player.getUniqueId().toString()); } @Override public EconomyResponse deleteBank(String s) { plugin.getManager().removeBankAccount(UUID.fromString(s)); return new EconomyResponse(0D, 0D, EconomyResponse.ResponseType.SUCCESS, null); } @Override public EconomyResponse bankBalance(String s) { UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } if (plugin.getManager().hasBankAccount(uuid)) { double balance = plugin.getManager().getBankBalance(uuid); return new EconomyResponse(balance, balance, EconomyResponse.ResponseType.SUCCESS, null); } return new EconomyResponse(0D, 0D, EconomyResponse.ResponseType.FAILURE, null); } @Override public EconomyResponse bankHas(String s, double v) { EconomyResponse response = bankBalance(s); if (response.transactionSuccess()) { if (response.balance >= v) { return new EconomyResponse(0D, response.balance, EconomyResponse.ResponseType.SUCCESS, null); } return new EconomyResponse(0D, response.balance, EconomyResponse.ResponseType.FAILURE, null); } return new EconomyResponse(0D, response.balance, EconomyResponse.ResponseType.FAILURE, null); } @Override public EconomyResponse bankWithdraw(String s, double v) { EconomyResponse response = bankBalance(s); UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } double balance = plugin.getManager().getBankBalance(uuid); if (response.transactionSuccess()) { plugin.getManager().setBankBalance(uuid, balance - Math.abs(v)); return new EconomyResponse(v, balance - Math.abs(v), EconomyResponse.ResponseType.SUCCESS, null); } return new EconomyResponse(0D, 0D, EconomyResponse.ResponseType.FAILURE, null); } @Override public EconomyResponse bankDeposit(String s, double v) { EconomyResponse response = bankBalance(s); UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } double balance = plugin.getManager().getBankBalance(uuid); if (response.transactionSuccess()) { plugin.getManager().setBankBalance(uuid, balance + Math.abs(v)); return new EconomyResponse(v, balance + Math.abs(v), EconomyResponse.ResponseType.SUCCESS, null); } return new EconomyResponse(0D, 0D, EconomyResponse.ResponseType.FAILURE, null); } @Override public EconomyResponse isBankOwner(String s, String s2) { if (s.equals(s2)) { return new EconomyResponse(0D, 0D, EconomyResponse.ResponseType.SUCCESS, null); } return new EconomyResponse(0D, 0D, EconomyResponse.ResponseType.FAILURE, null); } @Override public EconomyResponse isBankOwner(String name, OfflinePlayer player) { return isBankOwner(name, player.getUniqueId().toString()); } @Override public EconomyResponse isBankMember(String s, String s2) { return isBankOwner(s, s2); } @Override public EconomyResponse isBankMember(String name, OfflinePlayer player) { return isBankMember(name, player.getUniqueId().toString()); } @Override public List<String> getBanks() { return plugin.getManager().banksAsStrings(); } @Override public boolean createPlayerAccount(String s) { UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } plugin.getManager().setPlayerBalance(uuid, 0D); Bukkit.getPluginManager().callEvent(new MintEvent(s)); return true; } @Override public boolean createPlayerAccount(OfflinePlayer player) { return createPlayerAccount(player.getUniqueId().toString()); } @Override public boolean createPlayerAccount(String s, String s2) { return createPlayerAccount(s); } @Override public boolean createPlayerAccount(OfflinePlayer player, String worldName) { return createPlayerAccount(player); } public EconomyResponse setBalance(OfflinePlayer player, int v) { return setBalance(player.getUniqueId().toString(), v); } public EconomyResponse setBalance(String s, double v) { if (!hasAccount(s)) { createPlayerAccount(s); } UUID uuid; try { uuid = UUID.fromString(s); } catch (IllegalArgumentException e) { uuid = Bukkit.getPlayer(s).getUniqueId(); } double d = plugin.getManager().getPlayerBalance(uuid); plugin.getManager().setPlayerBalance(uuid, v); Bukkit.getPluginManager().callEvent(new MintEvent(s)); return new EconomyResponse(d - v, v, EconomyResponse.ResponseType.SUCCESS, null); } }
package etomica.spin.heisenberg_interacting.heisenberg; import etomica.math.SpecialFunctions; import etomica.util.numerical.BesselFunction; import static etomica.util.numerical.BesselFunction.doCalc; public class FunctionCosIntegral { /** * thetaDot for mean-field mapping of XY model, calculation of correlation function via 2nd free-energy derivative * @return thetaDot, with components for derivative with respect to field in x and y directions, respectively */ public static double[] getValue(double x, double b, double theta0) { double aC0 = cosInt(x-theta0,b)*BesselFunction.I(1,b)/BesselFunction.I(0,b); double C1 = coscosInt(x-theta0,b); double S1 = sincosInt(x-theta0,b); double cosTheta0 = Math.cos(theta0); double sinTheta0 = Math.sin(theta0); double A = Math.exp(-b*Math.cos(x-theta0)); return new double[] {A*(aC0 * cosTheta0 - C1 * cosTheta0 + S1 * sinTheta0), A*(aC0 * sinTheta0 - C1 * sinTheta0 + S1 * cosTheta0)}; } /** * Integral of Exp(b cos(t)) for t from 0 to x, accurate to within 0.01% for all b > 0 and -2Pi < x < 2Pi. */ public static double cosInt(double x, double b) { if(x > 2*Math.PI) throw new IllegalArgumentException("Angle must be between -2Pi and + 2Pi"); // put between 0 and 2Pi if(x < 0) return -cosInt(-x, b); if(b < 0) throw new IllegalArgumentException(("b must be non-negative")); if(b <= 1.0) return cosIntSmallb(x, b); // put between 0 and Pi if(x > Math.PI) return 2*Math.PI*BesselFunction.I(0,b) - cosInt(2*Math.PI - x, b); if(x < 0.5*Math.PI) return cosIntLargebA(x, b); // if we get here, then Pi/2 < x < Pi return cosIntLargebB(x, b); } /** * Integral of sin(t) Exp(b cos(t)) for t from 0 to x, accurate to within 0.01% for all b > 0 and -2Pi < x < 2Pi. */ public static double sincosInt(double x, double b) { return (Math.exp(b) - Math.exp(b*Math.cos(x)))/b; } /** * Integral of cos(t) Exp(b cos(t)) for t from 0 to x, accurate to within 0.01% for all b > 0 and -2Pi < x < 2Pi. */ public static double coscosInt(double x, double b) { if(x > 2*Math.PI) throw new IllegalArgumentException("Angle must be between -2Pi and + 2Pi"); // put between 0 and 2Pi if(x < 0) return -coscosInt(-x, b); if(b < 0) throw new IllegalArgumentException(("b must be non-negative")); if(b <= 1.0) return coscosIntSmallb(x, b); // put between 0 and Pi if(x > Math.PI) return 2*Math.PI*BesselFunction.I(1,b) - coscosInt(2*Math.PI - x, b); if(x < 0.5*Math.PI) return coscosIntLargebA(x, b); // if we get here, then Pi/2 < x < Pi return coscosIntLargebB(x, b); } /** * Integral of cos(t)^2 Exp(b cos(t)) for t from 0 to x. Evaluates via integration by parts using cosInt and coscosInt. * Accurate to within 0.015% for b > 0 and x between 0 and 2pi. */ public static double cos2cosInt(double x, double b) { return cosInt(x,b) - (coscosInt(x,b) - Math.sin(x)*Math.exp(b*Math.cos(x))) / b; } /** * Integral of Exp(b cos(t)) from 0 to x, accurate to within 0.01% for b < 1. * @param x maximum angle, should be in range -2Pi, 2Pi * @param b parameter, should be less than 1 * */ private static double cosIntSmallb(double x, double b) { double sx = Math.sin(x); double cx = Math.cos(x); double sx2 = sx*sx; double cx2 = cx*cx; double s2x = 2 * cx * sx; double s3x = sx*(3*cx2 - sx2); double s4x = 4*cx*sx*(cx2 - sx2); double s5x = sx*(5*cx2*cx2 - 10*cx2*sx2 + sx2*sx2); double s6x = 2*cx*sx*(3*cx2*cx2 - 10*cx2*sx2 + 3*sx2*sx2); return x + b*(sx + b*(0.25*(x + sx*cx) + b*((9*sx + s3x)/72. + b*((12*x + 8*s2x + s4x)/768. + b*((150*sx + 25*s3x + 3*s5x)/28800. + b*((60*x + 45*s2x + 9*s4x + s6x)/138240.)))))); } /** * Integral of cos(t) Exp(b cos(t)) from 0 to x, accurate to within 0.06% for b < 1. * @param x maximum angle, should be in range -2Pi, 2Pi * @param b parameter, should be less than 1 * */ //some duplication of calculation could be removed by combining with cosIntSmallb private static double coscosIntSmallb(double x, double b) { double sx = Math.sin(x); double cx = Math.cos(x); double sx2 = sx*sx; double cx2 = cx*cx; double s2x = 2 * cx * sx; double s3x = sx*(3*cx2 - sx2); double s4x = 4*cx*sx*(cx2 - sx2); double s5x = sx*(5*cx2*cx2 - 10*cx2*sx2 + sx2*sx2); double s6x = 2*cx*sx*(3*cx2*cx2 - 10*cx2*sx2 + 3*sx2*sx2); double b2 = b*b; double b3 = b2*b; double b4 = b2*b2; double b5 = b4*b; return sx + 1./24*b2*(s3x + 9*sx) + ( b4*(25*s3x + 3*s5x + 150*sx))/5760 + 0.5*b*(cx*sx + x) + 1./192*b3*(8*s2x + s4x + 12*x) + ( b5*(45*s2x + 9*s4x + s6x + 60*x))/23040; } /** * Integral of Exp(b cos(t)) from 0 to x, accurate to within 0.01% for b > 1 and -Pi/2 < x < Pi/2. */ private static double cosIntLargebA(double x, double b) { double b2 = b*b; double b4 = b2*b2; double x2 = x*x; double x4 = x2*x2; double x6 = x4*x2; return Math.exp(b)/3628800./b4 * (Math.exp(-b*x*x/2) * x * (945 + 210*b4*b*x6*(-15 + x2) + 315*b*(600 + x2) + 63*b2*(-4050 + 1000*x2 + x4) + 9*b2*b*(-50400 - 9450*x2 + 1400*x4 + x6) + b4*x2*(-151200 - 17010*x2 + 1800*x4 + x6) ) + 945*(-1 - 200*b + 270*b2 + 480*b2*b + 3840*b4)*Math.sqrt(0.5*Math.PI) * (1-SpecialFunctions.erfc(Math.sqrt(0.5*b)*x))/Math.sqrt(b) ); } /** * Integral of cos(t) Exp(b cos(t)) from 0 to x, accurate to within 0.05% for b > 1 and -Pi/2 < x < Pi/2. */ private static double coscosIntLargebA(double x, double b) { double b2 = b*b; double b3 = b2*b; double b4 = b2*b2; double b5 = b4*b; double b6 = b3*b3; double sqrtb = Math.sqrt(b); double x2 = x*x; double x4 = x2*x2; double x6 = x4*x2; double x8 = x4*x4; return 1./(14515200.*b5*sqrtb)*Math.exp(b)*(-2*sqrtb*Math.exp(-b*x2/2)* x * (8505 + 2835*b*(466 + x2) + 210*b6*x6*(30 - 17*x2 + x4) + 189*b2*(-8750 + 2330*x2 + 3*x4) + 9*b3*(-94500 - 61250*x2 + 9786*x4 + 9*x6) + b5*x2*(302400 - 117180*x2 - 14310*x4 + 1378*x6 + x8) + 9*b4*(-302400 - 31500*x2 - 12250*x4 + 1398*x6 + x8)) + 945*(9 + 1398*b - 1750*b2 - 900*b3 - 2880*b4 + 7680*b5)* Math.sqrt(2*Math.PI)*(1.0-SpecialFunctions.erfc(sqrtb*x/Math.sqrt(2)))); //Math.sqrt(2*Math.PI)*(1.0-org.apache.commons.math3.special.Erf.erfc(sqrtb*x/Math.sqrt(2)))); } /** * Integral of Exp(b cos(t)) from 0 to x, accurate to within 0.01% for b > 1 and Pi/2 < x < Pi. */ private static double cosIntLargebB(double x, double b) { double pix = Math.PI - x; double pix2 = pix*pix; double pix4 = pix2*pix2; double pix8 = pix4*pix4; double pi2 = Math.PI*Math.PI; double pi4 = pi2*pi2; double pi3 = pi2*Math.PI; double pi8 = pi4*pi4; double x2 = x*x; double x4 = x2*x2; double b2 = b*b; double b4 = b2*b2; return Math.PI* BesselFunction.I(0, b) + (-(1./39916800)* Math.exp(-b) * pix*(39916800 + 945*b4*b*pix8*pix2 - 1050*b4*pix8*(-11 + 3*pi2 - 6*Math.PI*x + 3*x2) + 15*b2*b*pix4*pix2*(7920 + 147*pi4 - 588*pi3*x - 1540*x2 + 147*x4 + 14*pi2*(-110 + 63*x2) + Math.PI*(3080*x - 588*x2*x)) - 15*b2*pix4*(-66528 + 17*pi4*pi2 - 102*pi3*pi2*x + 7920*x2 - 462*x4 + 17*x2*x4 - 4*pi3*x*(-462 + 85*x2) + 3*pi4*(-154 + 85*x2) - 6*Math.PI*x*(2640 - 308*x2 + 17*x4) + 3*pi2*(2640 - 924*x2 + 85*x4)) + b*pix2*(6652800 + pi8 - 8*pi4*pi3*x - 332640*x2 + 7920*x4 - 110*x4*x2 + x4*x4 + 2*pi4*pi2*(-55 + 14*x2) + pi3*pi2*(660*x - 56*x2*x) - 8*pi3*x*(3960 - 275*x2 + 7*x4) + 10*pi4*(792 - 165*x2 + 7*x4) + 2*pi2*(-166320 + 23760*x2 - 825*x4 + 14*x4*x2) + Math.PI*(665280*x - 31680*x2*x + 660*x4*x - 8*x4*x2*x)))); } /** * Integral of cos(t) Exp(b cos(t)) from 0 to x, accurate to within 0.01% for b > 1 and Pi/2 < x < Pi. */ private static double coscosIntLargebB(double x, double b) { double pix = Math.PI - x; double pix2 = pix*pix; double pix3 = pix2*pix; double pix4 = pix2*pix2; double pix6 = pix4*pix2; double pi2 = Math.PI*Math.PI; double pi4 = pi2*pi2; double x2 = x*x; double x4 = x2*x2; double b2 = b*b; double b3 = b2*b; double b4 = b2*b2; double eb = Math.exp(-b); return -(1./39916800) * eb*pix3*(6652800 + pix2*(-332640 + 7920*pix2 - 110*pix4 + pix6 + 4725*b4*pix6 - 4200*b3*pix4*(-11 + 3*pix2) - 30*b*(-66528 + 7920*pix2 + pix4*(-462 + 17*pix2)) + 45*b2*pix2*(7920 + 7*pix2*(-220 + 21*pix2)))) + (1./39916800)* eb*pix*(39916800 + b*pix2*(6652800 + pix2*(-332640 + 7920*pix2 - 110*pix4 + pix6 + 945*b4*pix6 - 1050*b3*pix4*(-11 + 3*pix2) - 15*b*(-66528 + 7920*pix2 + pix4*(-462 + 17*pix2)) + 15*b2*pix2*(7920 + 7*pix2*(-220 + 21*pix2))))) + Math.PI*BesselFunction.I(1,b); } public static void main(String[] args) { double b = 10; double theta0 = 2*Math.PI; // Print results to check against Mathematica for(double x = 0; x < 2*Math.PI; x+=0.1) { // System.out.println("{" + x + ", " + getValue(x, b,theta0)[0]+"},"); System.out.println("{" + x + ", " + cos2cosInt(x, b)+"},"); } // System.out.println(cosIntSmallb(-5.7, .52)); // System.out.println(cosIntLargebA(1.5, 5.52)); // System.out.println(cosIntLargebB(2.0, 5.5)); //System.out.println(coscosIntLargebA(1.2, 9.52)); //System.out.println(coscosIntLargebB(4.0, 5.5)); System.out.println(coscosIntSmallb(-5.7, 0.52)); } }
// Pythagoras - a collection of geometry classes package pythagoras.f; import pythagoras.util.NoninvertibleTransformException; /** * Implements an affine (3x2 matrix) transform. The transformation matrix has the form: * <pre>{@code * [ m00, m10, tx ] * [ m01, m11, ty ] * [ 0, 0, 1 ] * }</pre> */ public class AffineTransform extends AbstractTransform { /** Identifies the affine transform in {@link #generality}. */ public static final int GENERALITY = 4; /** The scale, rotation and shear components of this transform. */ public float m00, m01, m10, m11; /** The translation components of this transform. */ public float tx, ty; /** Creates an affine transform configured with the identity transform. */ public AffineTransform () { this(1, 0, 0, 1, 0, 0); } /** Creates an affine transform from the supplied scale, rotation and translation. */ public AffineTransform (float scale, float angle, float tx, float ty) { this(scale, scale, angle, tx, ty); } /** Creates an affine transform from the supplied scale, rotation and translation. */ public AffineTransform (float scaleX, float scaleY, float angle, float tx, float ty) { float sina = FloatMath.sin(angle), cosa = FloatMath.cos(angle); this.m00 = cosa * scaleX; this.m01 = sina * scaleY; this.m10 = -sina * scaleX; this.m11 = cosa * scaleY; this.tx = tx; this.ty = ty; } /** Creates an affine transform with the specified transform matrix. */ public AffineTransform (float m00, float m01, float m10, float m11, float tx, float ty) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; this.tx = tx; this.ty = ty; } @Override // from Transform public float getUniformScale () { // the square root of the signed area of the parallelogram spanned by the axis vectors float cp = m00*m11 - m01*m10; return (cp < 0f) ? -FloatMath.sqrt(-cp) : FloatMath.sqrt(cp); } @Override // from Transform public float getScaleX () { return FloatMath.sqrt(m00*m00 + m01*m01); } @Override // from Transform public float getScaleY () { return FloatMath.sqrt(m10*m10 + m11*m11); } @Override // from Transform public float getRotation () { // use the iterative polar decomposition algorithm described by Ken Shoemake: // start with the contents of the upper 2x2 portion of the matrix float n00 = m00, n10 = m10; float n01 = m01, n11 = m11; for (int ii = 0; ii < 10; ii++) { // store the results of the previous iteration float o00 = n00, o10 = n10; float o01 = n01, o11 = n11; // compute average of the matrix with its inverse transpose float det = o00*o11 - o10*o01; if (Math.abs(det) == 0f) { // determinant is zero; matrix is not invertible throw new NoninvertibleTransformException(this.toString()); } float hrdet = 0.5f / det; n00 = +o11 * hrdet + o00*0.5f; n10 = -o01 * hrdet + o10*0.5f; n01 = -o10 * hrdet + o01*0.5f; n11 = +o00 * hrdet + o11*0.5f; // compute the difference; if it's small enough, we're done float d00 = n00 - o00, d10 = n10 - o10; float d01 = n01 - o01, d11 = n11 - o11; if (d00*d00 + d10*d10 + d01*d01 + d11*d11 < FloatMath.EPSILON) { break; } } // now that we have a nice orthogonal matrix, we can extract the rotation return FloatMath.atan2(n01, n00); } @Override // from Transform public float getTx () { return this.tx; } @Override // from Transform public float getTy () { return this.ty; } @Override // from Transform public Transform setUniformScale (float scale) { return setScale(scale, scale); } @Override // from Transform public Transform setScaleX (float scaleX) { // normalize the scale to 1, then re-apply float osx = getScaleX(); m00 /= osx; m01 /= osx; m00 *= scaleX; m01 *= scaleX; return this; } @Override // from Transform public Transform setScaleY (float scaleY) { // normalize the scale to 1, then re-apply float osy = getScaleY(); m10 /= osy; m11 /= osy; m10 *= scaleY; m11 *= scaleY; return this; } @Override // from Transform public Transform setRotation (float angle) { // extract the scale, then reapply rotation and scale together float sx = getScaleX(), sy = getScaleY(); float sina = FloatMath.sin(angle), cosa = FloatMath.cos(angle); m00 = cosa * sx; m01 = sina * sx; m10 = -sina * sy; m11 = cosa * sy; return this; } @Override // from Transform public Transform setTranslation (float tx, float ty) { this.tx = tx; this.ty = ty; return this; } @Override // from Transform public Transform setTx (float tx) { this.tx = tx; return this; } @Override // from Transform public Transform setTy (float ty) { this.ty = ty; return this; } @Override // from Transform public Transform setTransform (float m00, float m01, float m10, float m11, float tx, float ty) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; this.tx = tx; this.ty = ty; return this; } @Override // from Transform public Transform uniformScale (float scale) { return scale(scale, scale); } @Override // from Transform public Transform scaleX (float scaleX) { m00 *= scaleX; m01 *= scaleX; tx *= scaleX; return this; } @Override // from Transform public Transform scaleY (float scaleY) { m10 *= scaleY; m11 *= scaleY; ty *= scaleY; return this; } @Override // from Transform public Transform rotate (float angle) { float sina = FloatMath.sin(angle), cosa = FloatMath.cos(angle); return Transforms.multiply(cosa, sina, -sina, cosa, 0, 0, this, this); } @Override // from Transform public Transform translate (float tx, float ty) { return Transforms.multiply(this, 1, 0, 0, 1, tx, ty, this); } @Override // from Transform public Transform translateX (float tx) { return Transforms.multiply(this, 1, 0, 0, 1, tx, 0, this); } @Override // from Transform public Transform translateY (float ty) { return Transforms.multiply(this, 1, 0, 0, 1, 0, ty, this); } @Override // from Transform public Transform invert () { // compute the determinant, storing the subdeterminants for later use float det = m00*m11 - m10*m01; if (Math.abs(det) == 0f) { // determinant is zero; matrix is not invertible throw new NoninvertibleTransformException(this.toString()); } float rdet = 1f / det; return new AffineTransform( +m11 * rdet, -m10 * rdet, -m01 * rdet, +m00 * rdet, (m10*ty - m11*tx) * rdet, (m01*tx - m00*ty) * rdet); } @Override // from Transform public Transform concatenate (Transform other) { if (generality() < other.generality()) { return other.preConcatenate(this); } if (other instanceof AffineTransform) { return Transforms.multiply(this, (AffineTransform)other, new AffineTransform()); } else { AffineTransform oaff = new AffineTransform(other); return Transforms.multiply(this, oaff, oaff); } } @Override // from Transform public Transform preConcatenate (Transform other) { if (generality() < other.generality()) { return other.concatenate(this); } if (other instanceof AffineTransform) { return Transforms.multiply((AffineTransform)other, this, new AffineTransform()); } else { AffineTransform oaff = new AffineTransform(other); return Transforms.multiply(oaff, this, oaff); } } @Override // from Transform public Transform lerp (Transform other, float t) { if (generality() < other.generality()) { return other.lerp(this, -t); // TODO: is this correct? } AffineTransform ot = (other instanceof AffineTransform) ? (AffineTransform)other : new AffineTransform(other); return new AffineTransform( m00 + t*(ot.m00 - m00), m01 + t*(ot.m01 - m01), m10 + t*(ot.m10 - m10), m11 + t*(ot.m11 - m11), tx + t*(ot.tx - tx ), ty + t*(ot.ty - ty )); } @Override // from Transform public Point transform (IPoint p, Point into) { float x = p.getX(), y = p.getY(); return into.set(m00*x + m10*y + tx, m01*x + m11*y + ty); } @Override // from Transform public void transform (IPoint[] src, int srcOff, Point[] dst, int dstOff, int count) { for (int ii = 0; ii < count; ii++) { transform(src[srcOff++], dst[dstOff++]); } } @Override // from Transform public void transform (float[] src, int srcOff, float[] dst, int dstOff, int count) { for (int ii = 0; ii < count; ii++) { float x = src[srcOff++], y = src[srcOff++]; dst[dstOff++] = m00*x + m10*y + tx; dst[dstOff++] = m01*x + m11*y + ty; } } @Override // from Transform public Point inverseTransform (IPoint p, Point into) { float x = p.getX() - tx, y = p.getY() - ty; float det = m00 * m11 - m01 * m10; if (Math.abs(det) == 0f) { // determinant is zero; matrix is not invertible throw new NoninvertibleTransformException(this.toString()); } float rdet = 1 / det; return into.set((x * m11 - y * m10) * rdet, (y * m00 - x * m01) * rdet); } @Override // from Transform public Vector transform (IVector v, Vector into) { float x = v.getX(), y = v.getY(); return into.set(m00*x + m10*y, m01*x + m11*y); } @Override // from Transform public Vector inverseTransform (IVector v, Vector into) { float x = v.getX(), y = v.getY(); float det = m00 * m11 - m01 * m10; if (Math.abs(det) == 0f) { // determinant is zero; matrix is not invertible throw new NoninvertibleTransformException(this.toString()); } float rdet = 1 / det; return into.set((x * m11 - y * m10) * rdet, (y * m00 - x * m01) * rdet); } @Override // from Transform public Transform clone () { return new AffineTransform(m00, m01, m10, m11, tx, ty); } @Override // from Transform public int generality () { return GENERALITY; } @Override public String toString () { return "affine [" + FloatMath.toString(m00) + " " + FloatMath.toString(m01) + " " + FloatMath.toString(m10) + " " + FloatMath.toString(m11) + " " + getTranslation() + "]"; } // we don't publicize this because it might encourage someone to do something stupid like // create a new AffineTransform from another AffineTransform using this instead of clone() protected AffineTransform (Transform other) { this(other.getScaleX(), other.getScaleY(), other.getRotation(), other.getTx(), other.getTy()); } }
package ru.stqa.selenium.zkgrid; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParametersDelegate; import com.beust.jcommander.internal.Lists; import com.google.common.io.Files; import ru.stqa.selenium.zkgrid.hub.Hub; import ru.stqa.selenium.zkgrid.node.Node; import java.util.List; import java.util.Properties; public class Main { public static void main(String[] args) throws Exception { final Main main = new Main(); new JCommander(main, args); if (main.role == null) { throw new Error("Unknown role " + main.role); } switch (main.role) { case HUB: { Properties properties = new Properties(){{ setProperty("dataDir", Files.createTempDir().getAbsolutePath()); setProperty("clientPort", main.hubParameters.getPort()); setProperty("server.1", "localhost:5444:6444"); }}; Hub hub = new Hub(properties); hub.start(); break; } case NODE: { Node node = new Node(main.nodeParameters.hubConnectionString); node.start(); break; } default: { throw new Error("Unknown role " + main.role); } } } @Parameter(names = "-role", description = "\"hub\" or \"node\"", converter = RoleConverter.class) private Role role; @ParametersDelegate private HubParameters hubParameters = new HubParameters(); @ParametersDelegate private NodeParameters nodeParameters = new NodeParameters(); private enum Role { HUB, NODE } public static class RoleConverter implements IStringConverter<Role> { @Override public Role convert(String s) { return Role.valueOf(s.toUpperCase()); } } }
package io.pivotal.gemfire.demo; import com.gemstone.gemfire.DataSerializer; import com.gemstone.gemfire.cache.EntryEvent; import com.gemstone.gemfire.cache.InterestResultPolicy; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.ClientCacheFactory; import com.gemstone.gemfire.cache.client.ClientRegionFactory; import com.gemstone.gemfire.cache.client.ClientRegionShortcut; import com.gemstone.gemfire.cache.query.*; import com.gemstone.gemfire.cache.util.CacheListenerAdapter; import com.gemstone.gemfire.internal.HeapDataOutputStream; import com.gemstone.gemfire.internal.Version; import com.gemstone.gemfire.internal.concurrent.ConcurrentHashSet; import com.gemstone.gemfire.pdx.JSONFormatter; import com.gemstone.gemfire.pdx.PdxInstance; import com.google.common.collect.Iterables; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.*; import java.util.concurrent.TimeUnit; public class Source { private ClientCache clientCache; private String[] destinationInfo; private Set<MyCacheListener> regionSourceSet = new ConcurrentHashSet<>(); public Source() { } public static void main(String[] args) throws TypeMismatchException, CqException, IOException, FunctionDomainException, QueryInvocationTargetException, NameResolutionException, CqExistsException { String locator = "localhost[10334]"; String regions = ""; String destination = "localhost[50505]"; String userName = null; String password = null; if (args.length > 0) { for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("locator")) { locator = arg.substring(arg.indexOf("=") + 1, arg.length()); } else if (arg.startsWith("regions")) { regions = arg.substring(arg.indexOf("=") + 1, arg.length()); } else if (arg.startsWith("destination")) { destination = arg.substring(arg.indexOf("=") + 1, arg.length()); } else if (arg.startsWith("username")) { userName = arg.substring(arg.indexOf("=") + 1, arg.length()); } else if (arg.startsWith("password")) { password = arg.substring(arg.indexOf("=") + 1, arg.length()); } } Source source = new Source(); source.setDestinationInfo(ToolBox.parseLocatorInfo(destination)); source.setupGemFire(ToolBox.parseLocatorInfo(locator), userName, password); for (String currRegion : regions.split(",")) { source.setUpCQOnRegion(currRegion); } } else { System.out.println("Please provide the following parameters: locator=hostname[port] regions=regionA,regionB <destination>=hostname[50505]"); } } private void setupGemFire(String[] locatorInfo, String userName, String password) throws IOException, CqException, CqExistsException, NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("/gemfire.properties")); ClientCacheFactory factory = new ClientCacheFactory(properties); factory.setPoolSubscriptionEnabled(true); factory.addPoolLocator(locatorInfo[0], Integer.parseInt(locatorInfo[1])); if (userName != null && password != null) { factory.set("security-client-auth-init", "io.pivotal.gemfire.demo.ClientAuthentication.create"); factory.set("security-username", userName); factory.set("security-password", password); } factory.set("name", "source"); factory.set("statistic-archive-file", "source.gfs"); clientCache = factory.create(); ToolBox.addTimerForPdxTypeMetrics(clientCache); } private void setUpCQOnRegion(String regionName) throws CqException, CqExistsException, RegionNotFoundException, IOException { Region region = clientCache.getRegion(regionName); if (region == null) { ClientRegionFactory clientRegionFactory = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY); region = clientRegionFactory.create(regionName); } MyCacheListener regionSource = new MyCacheListener(openSocket(), region, regionName); region.getAttributesMutator().addCacheListener(regionSource); region.registerInterest("ALL_KEYS", InterestResultPolicy.KEYS); Collection keySetOnServer = region.keySetOnServer(); System.out.println("keySetOnServer.size() = " + keySetOnServer.size()); Iterable<Collection> partitionedKeySet = Iterables.partition(keySetOnServer, 100); for (Collection keySubSet : partitionedKeySet) { Map<Object, Object> bulk = region.getAll(keySubSet); } regionSourceSet.add(regionSource); System.out.println("done with regionName = " + regionName); } public void setDestinationInfo(String[] destinationInfo) { this.destinationInfo = destinationInfo; } private Socket openSocket() throws IOException { Socket socket = new Socket(destinationInfo[0], Integer.parseInt(destinationInfo[1])); return socket; } private class MyCacheListener extends CacheListenerAdapter { private DataOutputStream objectOutputStream; private Region region; public MyCacheListener(Socket socket, Region region, String regionName) throws IOException { objectOutputStream = new DataOutputStream(socket.getOutputStream()); //Not possible to have another thread accessing the stream at this point since we are still in the constructor objectOutputStream.writeUTF(regionName); objectOutputStream.flush(); this.region = region; } @Override public void afterCreate(EntryEvent entryEvent) { afterUpdate(entryEvent); } @Override public void afterUpdate(EntryEvent entryEvent) { try { Action action = new Action(entryEvent.getKey(), entryEvent.getNewValue()); action.setPut(true); send(action); } catch (Exception e) { e.printStackTrace(); } } @Override public void afterInvalidate(EntryEvent entryEvent) { afterDestroy(entryEvent); } @Override public void afterDestroy(EntryEvent entryEvent) { try { Action action = new Action(entryEvent.getKey(), entryEvent.getNewValue()); action.setPut(false); send(action); } catch (Exception e) { e.printStackTrace(); } } public void send(Action action) throws IOException { try { if (action.getValue() instanceof PdxInstance) { action.setPDXInstance(true); action.setValue(JSONFormatter.toJSON((PdxInstance) action.getValue())); } write(action); } catch (Exception e) { System.out.println("Had error with " + action.getKey() + " - " + action.getValue()); } } public void write(Object object) throws IOException { HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); DataSerializer.writeObject(object, hdos); byte[] buffer = hdos.toByteArray(); objectOutputStream.writeInt(buffer.length); objectOutputStream.write(buffer); } } }
package seedu.taskitty.logic; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import seedu.taskitty.logic.commands.Command; import static seedu.taskitty.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; //@@author A0139930B public class ToolTip { public static final String TOOLTIP_DELIMITER = " | "; private static final int COMMAND_WORD_POSITION = 0; private static final String COMMAND_WORD_DELIMITER = " "; private static final int COMMAND_WORD_COUNT_NO_MATCH = 0; private static final int COMMAND_WORD_COUNT_SINGLE_MATCH = 1; private static final String TOOLTIP_POSSIBLE_COMMANDS = "These are the possible commands, Meow!"; private static final String TOOLTIP_UNKNOWN_COMMAND = "This does not resemble any command I have, Meow!\n"; private static ToolTip tooltip; private FilteredList<String> commands; private String message; private String description; private ToolTip() { ObservableList<String> commandList = FXCollections.observableArrayList(); commandList.addAll(Command.ALL_COMMAND_WORDS); commands = commandList.filtered(null); clearToolTip(); } /** * Gets the instance of ToolTip to be used */ public static ToolTip getInstance() { if (tooltip == null) { tooltip = new ToolTip(); } return tooltip; } /** * Get the tooltip based on input * * @param input to determine the tooltip to be shown */ public void createToolTip(String input) { clearToolTip(); String[] splitedInput = input.split(COMMAND_WORD_DELIMITER); // only interested in the first word, which is the command word String command = splitedInput[COMMAND_WORD_POSITION]; // filter the commands list to show only commands that match commands.setPredicate(p -> p.startsWith(command)); if (!isCommandWordMatch()) { setToolTip(MESSAGE_UNKNOWN_COMMAND, TOOLTIP_UNKNOWN_COMMAND); } else if (isSingleMatchFound()) { getToolTipForCommand(command); } else { getToolTipForAllCommands(); } } /** * Returns true if there is at least 1 command word that matches */ private boolean isCommandWordMatch() { return commands.size() != COMMAND_WORD_COUNT_NO_MATCH; } /** * Returns true if there is exactly 1 command word that matches */ private boolean isSingleMatchFound() { return commands.size() == COMMAND_WORD_COUNT_SINGLE_MATCH; } /** * Finds the closest matching command and returns the appropriate tooltip * * @param command to determine which command tooltip to show */ private void getToolTipForCommand(String command) { for (int i = 0; i < Command.ALL_COMMAND_WORDS.length; i++) { if (Command.ALL_COMMAND_WORDS[i].startsWith(command)) { setToolTip(Command.ALL_COMMAND_MESSAGE_PARAMETER[i], Command.ALL_COMMAND_MESSAGE_USAGE[i]); return; } } setToolTip(MESSAGE_UNKNOWN_COMMAND, TOOLTIP_UNKNOWN_COMMAND); } /** * Returns a string representing the matched input, * delimitered by TOOLTIP_DELIMITER */ private void getToolTipForAllCommands() { assert commands.size() != COMMAND_WORD_COUNT_NO_MATCH && commands.size() != COMMAND_WORD_COUNT_SINGLE_MATCH; StringBuilder commandBuilder = new StringBuilder(); commandBuilder.append(commands.get(0)); for (int i = 1; i < commands.size(); i++) { commandBuilder.append(TOOLTIP_DELIMITER + commands.get(i)); } setToolTip(commandBuilder.toString(), TOOLTIP_POSSIBLE_COMMANDS); } /** * Set the tooltip and description back to empty string */ private void clearToolTip() { message = ""; description = ""; } public String getMessage() { return message; } public String getDecription() { return description; } public boolean isUserInputValid() { return !isMessageUnknownOrEmpty(); } /** * Returns true if the message of tooltip is null, empty or MESSAGE_UNKNOWN_COMMAND */ private boolean isMessageUnknownOrEmpty() { return this.message == null || this.message.isEmpty() || this.message.equals(MESSAGE_UNKNOWN_COMMAND); } /** * Sets the tooltip and description to the given parameters */ private void setToolTip(String tooltip, String description) { this.message = tooltip; this.description = description; } }
package io.pivotal.gemfire.demo; import com.gemstone.gemfire.cache.Operation; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.cache.client.ClientCache; import com.gemstone.gemfire.cache.client.ClientCacheFactory; import com.gemstone.gemfire.cache.client.ClientRegionShortcut; import com.gemstone.gemfire.cache.query.*; import com.gemstone.gemfire.internal.concurrent.ConcurrentHashSet; import com.gemstone.gemfire.pdx.JSONFormatter; import com.gemstone.gemfire.pdx.PdxInstance; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Properties; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class Source { private ClientCache clientCache; private String[] destinationInfo; private Set<RegionSource> regionSourceSet = new ConcurrentHashSet<>(); public Source() { new Timer().schedule(new TimerTask() { @Override public void run() { regionSourceSet.forEach(source -> { try { source.flush(); } catch (IOException e) { e.printStackTrace(); } }); } }, TimeUnit.SECONDS.toMillis(10), TimeUnit.SECONDS.toMillis(10)); } public static void main(String[] args) throws TypeMismatchException, CqException, IOException, FunctionDomainException, QueryInvocationTargetException, NameResolutionException, CqExistsException { String locator = "localhost[10334]"; String regions = ""; String destination = "localhost[50505]"; String userName = null; String password = null; if (args.length > 0) { for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("locator")) { locator = arg.substring(arg.indexOf("=") + 1, arg.length()); } else if (arg.startsWith("regions")) { regions = arg.substring(arg.indexOf("=") + 1, arg.length()); } else if (arg.startsWith("destination")) { destination = arg.substring(arg.indexOf("=") + 1, arg.length()); } else if (arg.startsWith("username")) { userName = arg.substring(arg.indexOf("=") + 1, arg.length()); } else if (arg.startsWith("password")) { password = arg.substring(arg.indexOf("=") + 1, arg.length()); } } Source source = new Source(); source.setDestinationInfo(ToolBox.parseLocatorInfo(destination)); source.setupGemFire(ToolBox.parseLocatorInfo(locator), userName, password); for (String currRegion : regions.split(",")) { source.setUpCQOnRegion(currRegion); } } else { System.out.println("Please provide the following parameters: locator=hostname[port] regions=regionA,regionB <destination>=hostname[50505]"); } } private void setupGemFire(String[] locatorInfo, String userName, String password) throws IOException, CqException, CqExistsException, NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("/gemfire.properties")); ClientCacheFactory factory = new ClientCacheFactory(properties); factory.setPoolSubscriptionEnabled(true); factory.addPoolLocator(locatorInfo[0], Integer.parseInt(locatorInfo[1])); if (userName != null && password != null) { factory.set("security-client-auth-init", "io.pivotal.gemfire.demo.ClientAuthentication.create"); factory.set("security-username", userName); factory.set("security-password", password); } factory.set("name", "source"); factory.set("statistic-archive-file", "source.gfs"); clientCache = factory.create(); ToolBox.addTimerForPdxTypeMetrics(clientCache); } private void setUpCQOnRegion(String regionName) throws CqException, CqExistsException, RegionNotFoundException, IOException { Region region = clientCache.getRegion(regionName); if (region == null) { region = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(regionName); } QueryService queryService = clientCache.getQueryService(); final CqAttributesFactory cqAttributesFactory = new CqAttributesFactory(); RegionSource regionSource = new RegionSource(openSocket(), region, regionName); cqAttributesFactory.addCqListener(regionSource); CqQuery cq = queryService.newCq("CopyCQ_" + regionName, "select * from /" + regionName + " n", cqAttributesFactory.create()); CqResults results = cq.executeWithInitialResults(); for (Object o : results.asList()) { Struct s = (Struct) o; Action action = new Action(s.get("key"), s.get("value"), true); regionSource.send(action); } regionSourceSet.add(regionSource); regionSource.countDownLatch.countDown(); System.out.println("done with regionName = " + regionName); } public void setDestinationInfo(String[] destinationInfo) { this.destinationInfo = destinationInfo; } private Socket openSocket() throws IOException { Socket socket = new Socket(destinationInfo[0], Integer.parseInt(destinationInfo[1])); return socket; } private class RegionSource implements CqListener { private final ReentrantLock lock = new ReentrantLock(); private CountDownLatch countDownLatch = new CountDownLatch(1); private ObjectOutputStream objectOutputStream; private Region region; public RegionSource(Socket socket, Region region, String regionName) throws IOException { objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream())); //Not possible to have another thread accessing the stream at this point since we are still in the constructor objectOutputStream.writeObject(regionName); this.region = region; } @Override public void onEvent(CqEvent cqEvent) { try { countDownLatch.await(); Action action = new Action(cqEvent.getKey(), cqEvent.getNewValue()); Operation operation = cqEvent.getBaseOperation(); if (operation.isUpdate() || operation.isCreate()) { action.setPut(true); send(action); } else if (operation.isDestroy()) { action.setPut(false); send(action); } else { System.out.println("some other event operation name = " + operation.toString()); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onError(CqEvent cqEvent) { } @Override public void close() { } public void send(Action action) throws IOException { if (action.getValue() instanceof PdxInstance) { action.setPDXInstance(true); action.setValue(JSONFormatter.toJSON((PdxInstance) action.getValue())); } lock.lock(); try { // need to protect the stream just incase the flush from the other thread has a race objectOutputStream.writeObject(action); } finally { lock.unlock(); } } public void flush() throws IOException { lock.lock(); try { // need to protect the stream just incase the flush from the other thread has a race objectOutputStream.flush(); } finally { lock.unlock(); } } } }
package seedu.todo.models; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import seedu.todo.commons.exceptions.CannotRedoException; import seedu.todo.commons.exceptions.CannotUndoException; import seedu.todo.storage.JsonStorage; import seedu.todo.storage.Storage; /** * This class holds the entire persistent database for the TodoList app. * <ul> * <li>This is a singleton class. For obvious reasons, the TodoList app should * not be working with multiple DB instances simultaneously.</li> * <li>Object to object dynamic references should not be expected to survive * serialization.</li> * </ul> * * @author louietyj * */ public class TodoListDB { private static TodoListDB instance = null; private static Storage storage = new JsonStorage(); private Set<Task> tasks = new LinkedHashSet<Task>(); private Set<Event> events = new LinkedHashSet<Event>(); protected TodoListDB() { // Prevent instantiation. } /** * Get a list of Tasks in the DB. * * @return tasks */ public List<Task> getAllTasks() { return new ArrayList<Task>(tasks); } /** * Count tasks which are not marked as complete, where {@code isComplete} is false. * * @return Number of incomplete tasks */ public int countIncompleteTasks() { int count = 0; for (Task task : tasks) { if (!task.isCompleted()) { count++; } } return count; } /** * Count tasks which are overdue, where {@code dueDate} is before the time now. * * @return Number of overdue tasks */ public int countOverdueTasks() { LocalDateTime now = LocalDateTime.now(); int count = 0; for (Task task : tasks) { LocalDateTime dueDate = task.getDueDate(); if (!task.isCompleted() && dueDate != null && dueDate.compareTo(now) < 0) { count++; } } return count; } /** * Get a list of Events in the DB. * * @return events */ public List<Event> getAllEvents() { return new ArrayList<Event>(events); } /** * Count events which are in the future, where {@code startDate} is after the time now. * * @return Number of future events */ public int countFutureEvents() { LocalDateTime now = LocalDateTime.now(); int count = 0; for (Event event : events) { LocalDateTime startDate = event.getStartDate(); if (startDate != null && startDate.compareTo(now) >= 0) { count++; } } return count; } /** * Create a new Task in the DB and return it.<br> * <i>The new record is not persisted until <code>save</code> is explicitly * called.</i> * * @return task */ public Task createTask() { Task task = new Task(); tasks.add(task); return task; } /** * Destroys a Task in the DB and persists the commit. * * @param task * @return true if the save was successful, false otherwise */ public boolean destroyTask(Task task) { tasks.remove(task); return save(); } /** * Create a new Event in the DB and return it.<br> * <i>The new record is not persisted until <code>save</code> is explicitly * called.</i> * * @return event */ public Event createEvent() { Event event = new Event(); events.add(event); return event; } /** * Destroys an Event in the DB and persists the commit. * * @param event * @return true if the save was successful, false otherwise */ public boolean destroyEvent(Event event) { events.remove(event); return save(); } /** * Gets the singleton instance of the TodoListDB. * * @return TodoListDB */ public static TodoListDB getInstance() { if (instance == null) { instance = new TodoListDB(); } return instance; } /** * Explicitly persists the database to disk. * * @return true if the save was successful, false otherwise */ public boolean save() { try { storage.save(this); return true; } catch (IOException e) { return false; } } /** * Explicitly reloads the database from disk. * * @return true if the load was successful, false otherwise */ public boolean load() { try { instance = storage.load(); return true; } catch (IOException e) { return false; } } public void move(String newPath) throws IOException { storage.move(newPath); } /** * Returns the maximum possible number of undos. * * @return undoSize */ public int undoSize() { return storage.undoSize(); } /** * Rolls back the DB by one commit. * * @return true if the rollback was successful, false otherwise */ public boolean undo() { try { instance = storage.undo(); return true; } catch (CannotUndoException | IOException e) { return false; } } /** * Returns the maximum possible number of redos. * * @return redoSize */ public int redoSize() { return storage.redoSize(); } /** * Rolls forward the DB by one undo commit. * * @return true if the redo was successful, false otherwise */ public boolean redo() { try { instance = storage.redo(); return true; } catch (CannotRedoException | IOException e) { return false; } } }
package io.sigpipe.sing.stat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; public class Reservoir<T> { private long count; private int size; private List<Entry> reservoir; private Random random = new Random(); /** * Contains reservoir sample entries, which consist of a double-precision * floating point key and a value object of any type. */ private class Entry implements Comparable<Entry> { public double key; public T value; public Entry(double key, T value) { this.key = key; this.value = value; } @Override public int compareTo(Entry that) { return Double.compare(this.key, that.key); } @Override public String toString() { return "[" + key + "] -> " + value; } } /** * Creates a new Reservoir with the specified sample size. * * @param size the number of sample entries that should be maintained */ public Reservoir(int size) { this.size = size; reservoir = new ArrayList<>(size); } /** * Creates a new Reservoir by merging a collection of existing reservoirs. * The size of the resulting reservoir is detected automatically based on * the input reservoirs. Note that this constructor will merge all the * reservoirs in memory at the same time; if memory constraints prohibit * such an action, see the merge() method. * * @param reservoirs an iterable collection of reservoirs to merge */ public Reservoir(Iterable<Reservoir<T>> reservoirs) { this(reservoirs, 0); } /** * Creates a new Reservoir with a given sample size by merging a collection * of existing reservoirs. Note that this constructor will merge all the * reservoirs in memory at the same time; if memory constraints prohibit * such an action, see the merge() method. * * @param reservoirs an iterable collection of reservoirs to merge * @param size the sample size of the new Reservoir */ public Reservoir(Iterable<Reservoir<T>> reservoirs, int size) { List<Entry> combinedEntries = new ArrayList<>(); long combinedCount = 0; int largestSize = 0; for (Reservoir<T> r : reservoirs) { combinedEntries.addAll(r.reservoir); combinedCount += r.count; if (r.size() > largestSize) { largestSize = r.size(); } } Collections.sort(combinedEntries); if (size <= 0) { size = largestSize; } this.count = combinedCount; this.size = size; this.reservoir = new ArrayList<>(size); for (int i = 0; i < size; ++i) { this.reservoir.add(combinedEntries.get(i)); } } public void put(Iterable<T> items) { for (T item : items) { put(item); } } public void put(T item) { double key = random.nextDouble(); Entry e = new Entry(key, item); if (count < this.size()) { /* The reservoir has not been filled yet; add the item immediately. * Note: we can cast the count to an integer here because the size * of the reservoir is limited to the capacity of a single int. */ reservoir.add((int) count, e); } else { if (key < ((double) this.size() / (count + 1))) { int position = random.nextInt(this.size()); reservoir.set(position, e); } } count++; } public void merge(Reservoir<T> that, int size) { List<Reservoir<T>> reservoirs = Arrays.asList(this, that); Reservoir<T> merged = new Reservoir<T>(reservoirs, size); this.count = merged.count; this.size = size; this.reservoir = merged.reservoir; } public void merge(Reservoir<T> that) { merge(that, this.size()); } /** * Retrieves the total number of items observed by the reservoir. Note that * this is different from the size of the reservoir, which represents the * number of items in the sample. * * @return the total number of items observed by this reservoir instance. */ public long count() { return this.count; } /** * Retrieves the size of the reservoir, which is the number of items * contained in the sample. * * @return reservoir sample size. */ public int size() { return this.size; } public List<Entry> entries() { return new ArrayList<>(this.reservoir); } public List<T> sample() { List<T> l = new ArrayList<>(this.size()); for (Entry e : this.reservoir) { l.add(e.value); } return l; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Entry e : this.reservoir) { sb.append(e.value); sb.append(System.lineSeparator()); } return sb.toString(); } public static void main(String[] args) { Reservoir<Double> rs = new Reservoir<>(20); Reservoir<Double> r2 = new Reservoir<>(20); Random r = new Random(); r.doubles(10000).filter(val -> val < 0.5).forEach(rs::put); r.doubles(10000).filter(val -> val < 0.10).forEach(r2::put); RunningStatistics stats = new RunningStatistics(); for (Reservoir<Double>.Entry e : rs.entries()) { System.out.println(e); stats.put(e.value); } System.out.println(stats); rs.merge(r2); stats = new RunningStatistics(); for (Reservoir<Double>.Entry e : rs.entries()) { System.out.println(e); stats.put(e.value); } System.out.println(stats); } }
package teetime.framework.pipe; import teetime.framework.InputPort; import teetime.framework.OutputPort; import teetime.framework.signal.ISignal; /** * Represents an interface, which should be adapted by all implementations of pipes. */ public interface IPipe { /** * Adds an element to the Pipe. * * @param element * Element which will be added * @return True if the element could be added, false otherwise */ boolean add(Object element); /** * Checks whether the pipe is empty or not. * * @return True if the pipe is empty, false otherwise. */ boolean isEmpty(); /** * Retrieves the number of elements, the pipe is capable to carry at the same time. * * @return Number of elements */ int size(); /** * Retrieves the last element of the pipe and deletes it. * * @return The last element in the pipe. */ Object removeLast(); /** * Reads the pipe's last element, but does not delete it. * * @return The last element in the pipe. */ Object readLast(); /** * Retrieves the receiving port. * * @return InputPort which is connected to the pipe. */ InputPort<?> getTargetPort(); /** * A stage can pass on a signal by executing this method. The signal will be sent to the receiving stage. * * @param signal * The signal which needs to be passed on. */ void sendSignal(ISignal signal); @Deprecated <T> void connectPorts(OutputPort<? extends T> sourcePort, InputPort<T> targetPort); /** * Stages report new elements with this method. */ void reportNewElement(); }
package linenux.control; import java.util.ArrayList; import linenux.command.AddCommand; import linenux.command.Command; import linenux.command.DeleteCommand; import linenux.command.DoneCommand; import linenux.command.EditCommand; import linenux.command.ExitCommand; import linenux.command.HelpCommand; import linenux.command.InvalidCommand; import linenux.command.ListCommand; import linenux.command.result.CommandResult; import linenux.model.Schedule; /** * Assigns commands based on user input. */ public class CommandManager { private ArrayList<Command> commandList; private Schedule schedule; private Command catchAllCommand; public CommandManager(Schedule schedule) { this.schedule = schedule; commandList = new ArrayList<>(); initializeCommands(); } /** * Adds all supported commands to the commandList. */ private void initializeCommands() { commandList.add(new AddCommand(this.schedule)); commandList.add(new ListCommand(this.schedule)); commandList.add(new DeleteCommand(this.schedule)); commandList.add(new DoneCommand(this.schedule)); commandList.add(new EditCommand(this.schedule)); commandList.add(new ExitCommand()); commandList.add(new HelpCommand(this.commandList)); this.catchAllCommand = new InvalidCommand(this.commandList); } /** * Assigns the appropriate command to the user input. Contract: only 1 * command should be awaiting user response at any point in time. */ public CommandResult delegateCommand(String userInput) { for (Command command : commandList) { if (command.awaitingUserResponse()) { return command.userResponse(userInput); } } for (Command command : commandList) { if (command.respondTo(userInput)) { return command.execute(userInput); } } return this.catchAllCommand.execute(userInput); } /** * Sets the reference for the schedule. */ private void setSchedule(Schedule schedule) { this.schedule = schedule; } }
package com.github.timofeevda.gwt.rxjs.interop.observable; import jsinterop.annotations.JsFunction; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsType; import com.github.timofeevda.gwt.rxjs.interop.subject.Subject; import com.github.timofeevda.gwt.rxjs.interop.functions.Action0; import com.github.timofeevda.gwt.rxjs.interop.functions.Action1; import com.github.timofeevda.gwt.rxjs.interop.functions.Func1; import com.github.timofeevda.gwt.rxjs.interop.functions.Func2; import com.github.timofeevda.gwt.rxjs.interop.functions.Func3; import com.github.timofeevda.gwt.rxjs.interop.functions.Func4; import com.github.timofeevda.gwt.rxjs.interop.functions.Func5; import com.github.timofeevda.gwt.rxjs.interop.functions.Func6; import com.github.timofeevda.gwt.rxjs.interop.functions.FuncN; import com.github.timofeevda.gwt.rxjs.interop.functions.Producer; import com.github.timofeevda.gwt.rxjs.interop.scheduler.Scheduler; import com.github.timofeevda.gwt.rxjs.interop.subscription.Subscription; import com.github.timofeevda.gwt.rxjs.interop.functions.ProjectWithArray; import com.google.gwt.dom.client.Element; /** * @author dtimofeev since 20.12.2016. * @param <T> */ @JsType(namespace = "Rx", isNative = true) @SuppressWarnings("unused") public class Observable<T> { @SafeVarargs public native static <R> Observable<R> of(R... args); public native static <R> Observable<R> from(R[] args); public native static <R> Observable<R> fromEvent(Element target, String eventName); public native static <R> Observable<R> fromEvent(Element target, String eventName, boolean useCapture); public native static <R> Observable<R> create(OnSubscribe<? extends R> onSubscribe); public native Observable<T> audit(Observable<?> durationSelector); public native Observable<T> auditTime(int duration); public native Observable<T[]> buffer(Observable closingNotifier); public native Observable<T[]> bufferCount(int bufferSize); public native Observable<T[]> bufferCount(int bufferSize, int startBufferEvery); public native Observable<T[]> bufferTime(int bufferTimeSpan); public native Observable<T[]> bufferTime(int bufferTimeSpan, int bufferCreationInterval); public native Observable<T[]> bufferTime(int bufferTimeSpan, int bufferCreationInterval, int maxBufferSize); public native Observable<T[]> bufferToggle(Observable openings, Observable closingsSelector); public native Observable<T[]> bufferWhen(Observable closingSelector); @JsMethod(name = "catch") public native <R> Observable<R> _catch(Func2<?, Observable<? super T>, Observable<? extends R>> catcher); public native Observable<T> combineAll(); public native <R> Observable<R> combineAll(Func1<T[], ? extends R> mapper); public native static <T1, T2, R> Observable<R> combineLatest(Observable<? extends T1> v1, Observable<? extends T2> v2, Func2<? super T1, ? super T2, ? extends R> combineFunction); public native static <T1, T2, T3, R> Observable<R> combineLatest(Observable<? extends T1> v1, Observable<? extends T2> v2, Observable<? extends T3> v3, Func3<? super T1, ? super T2, ? super T3, ? extends R> combineFunction); public native static <T1, T2, T3, T4, R> Observable<R> combineLatest(Observable<? extends T1> v1, Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> combineFunction); public native static <T, R> Observable<R> combineLatest(Iterable<? extends Observable<? extends T>> observables, FuncN<? extends R> combineFunction); public native static <T> Observable<T> combineLatest(Observable<? extends T>[] observables); public native Observable<T> concat(Observable<? extends T> v1); public native Observable<T> concatAll(); public native static <T> Observable<T> concat(Observable<? extends T> v1, Observable<? extends T> v2); public native static <T> Observable<T> concat(Observable<? extends T> v1, Observable<? extends T> v2, Observable<? extends T> v3); public native static <T> Observable<T> concat(Observable<? extends T> v1, Observable<? extends T> v2, Observable<? extends T> v3, Observable<? extends T> v4); public native static <T> Observable<T> concat(Iterable<? extends Observable<? extends T>> observables); public native static <T> Observable<T> concat(Observable<? extends T>[] observables); public native <R> Observable<R> concatMap(Projector<? super T, R> projector); public native <I, R> Observable<T> concatMap(Projector<? super T, I> projector, ResultSelector<? super T, ? super I, R> resultSelector); public native <I, R> Observable<R> concatMapTo(Observable<I> observable, ResultSelector<? super T, ? super I, R> resultSelector); public native Observable<Integer> count(); public native Observable<Integer> count(Predicate<? super T> predicate); public native Observable<Integer> count(IndexedSourcePredicate<? super T> predicate); public native Observable<T> debounce(Observable<Integer> durationSelector); public native Observable<T> debounceTime(int time); public native <R> Observable<R> defaultIfEmpty(R defaultValue); public native static <T> Observable<T> defer(Producer<Observable<T>> producer); public native Observable<T> delay(int initialDelay); public native Observable<T> delayWhen(Func1<? super T, Observable<?>> delayDurationSelector); public native Observable<T> delayWhen(Func1<? super T, Observable<?>> delayDurationSelector, Observable<?> subscriptionDelay); public native Observable<T> distinct(); public native <K> Observable<T> distinct(KeySelector<? super T, K> keySelector); public native <K> Observable<T> distinct(KeySelector<? super T, K> keySelector, Observable<?> flushes); public native Observable<T> distinctUntilChanged(); public native <K> Observable<T> distinctUntilChanged(KeyComparator<? super T> keyComparator); public native <K> Observable<T> distinctUntilChanged(KeyComparator<? super T> keyComparator, KeySelector<? super T, K> keySelector); @JsMethod(name = "do") public native Observable<T> _do(Action1<T> onNext); @JsMethod(name = "do") public native Observable<T> _do(Action1<T> onNext, Action1<?> onError, Action0 onCompleted); @JsMethod(name = "do") public native Observable<T> _do(Observer<? super T> observer); public native static <T> Observable<T> empty(); public native Observable<T> elementAt(int index); public native <R extends T> Observable<T> elementAt(int index, R defaultValue); public native Observable<T> every(Predicate<? super T> predicate); public native Observable<Boolean> every(IndexedSourcePredicate<T> predicate); @JsMethod(name = "throw") public native static Observable _throw(Object error); @JsMethod(name = "throw") public native static Observable _throw(Object error, Scheduler scheduler); public native Observable<T> exhaust(); public native <R> Observable<T> exhaustMap(Projector<? super T, R> projector); public native <I, R> Observable<T> exhaustMap(Projector<? super T, I> projector, ResultSelector<? super T, ? super I, R> resultSelector); public native <R> Observable<R> expand(Projector<? super T, R> projector); public native <R> Observable<R> expand(Projector<? super T, R> projector, int concurrent); public native <R> Observable<R> expand(Projector<? super T, R> projector, int concurrent, Scheduler scheduler); public native Observable<T> filter(Predicate<? super T> predicate); public native Observable<T> filter(IndexedPredicate<? super T> indexedPredicate); @JsMethod(name = "finally") public native Observable<T> _finally(Action0 action); public native Observable<T> find(Predicate<? super T> predicate); public native Observable<T> find(IndexedPredicate<? super T> indexedPredicate); public native Observable<Integer> findIndex(IndexedSourcePredicate<? super T> predicate); public native Observable<T> first(Predicate<? super T> predicate); public native Observable<T> first(IndexedPredicate<? super T> indexedPredicate); public native <I, R> Observable<R> first(Predicate<? super T> predicate, IndexedResultSelector<? super T, R> resultSelector); public native <I, R> Observable<R> first(IndexedPredicate<? super T> indexedPredicate, IndexedResultSelector<? super T, R> resultSelector); public native <I, R> Observable<R> first(Predicate<? super T> predicate, IndexedResultSelector<? super T, R> resultSelector, R defaultValue); public native <I, R> Observable<R> first(IndexedPredicate<? super T> indexedPredicate, IndexedResultSelector<? super T, R> resultSelector, R defaultValue); public native <K> Observable<GroupedObservable<K, T>> groupBy(KeySelector<? super T, K> keySelector); public native <K, R> Observable<GroupedObservable<K, R>> groupBy(KeySelector<? super T, K> keySelector, ElementSelector<? super T, R> elementSelector); public native Observable<T> ignoreElements(); public native Observable<Boolean> isEmpty(); @JsMethod(name = "if") public native static Observable<Boolean> _if(Producer<Boolean> condition); @JsMethod(name = "if") public native static <T> Observable<Boolean> _if(Producer<Boolean> condition, Observable<T> thenSource); @JsMethod(name = "if") public native static <T> Observable<Boolean> _if(Producer<Boolean> condition, Observable<T> thenSource, Observable<T> elseSource); public native static Observable<Integer> interval(int period); public native static Observable<Integer> interval(int period, Scheduler scheduler); public native Observable<T> last(Predicate<? super T> predicate); public native Observable<T> last(IndexedPredicate<? super T> indexedPredicate); public native <R> Observable<R> last(Predicate<? super T> predicate, IndexedResultSelector<? super T, ? extends R> resultSelector); public native <R> Observable<R> last(IndexedPredicate<? super T> indexedPredicate, IndexedResultSelector<? super T, ? extends R> resultSelector); public native <R> Observable<R> last(Predicate<? super T> predicate, IndexedResultSelector<? super T, ? extends R> resultSelector, R defaultValue); public native <R> Observable<R> last(IndexedPredicate<? super T> indexedPredicate, IndexedResultSelector<? super T, ? extends R> resultSelector, R defaultValue); public native <R> Observable<R> let(Func1<Observable<? super T>, Observable<R>> selector); public native <R> Observable<R> map(Func1<? super T, ? extends R> mapper); public native <R> Observable<R> mapTo(R value); public native Observable<T> max(); public native Observable<T> max(Comparator<? super T> comparator); public native static <T> Observable<T> merge(Observable<T> first, Observable<T> second); public native Observable<T> mergeAll(); public native Observable<T> mergeAll(int concurrent); public native <R> Observable<R> mergeMap(Projector<? super T, ? extends R> projector); public native <R> Observable<R> mergeMap(Projector<? super T, ? extends R> projector, int concurrent); public native <I, R> Observable<R> mergeMap(Projector<? super T, ? extends R> projector, ResultSelector<? super T, ? super I, ? extends R> resultSelector); public native <I, R> Observable<R> mergeMap(Projector<? super T, ? extends R> projector, ResultSelector<? super T, ? super I, ? extends R> resultSelector, int concurrent); public native <R> Observable<R> mergeMapTo(Observable<? extends R> innerObservable); public native <R> Observable<R> mergeMapTo(Observable<? extends R> innerObservable, int concurrent); public native <I, R> Observable<R> mergeMapTo(Observable<? extends R> innerObservable, ResultSelector<? super T, ? super I, ? extends R> resultSelector); public native <I, R> Observable<R> mergeMapTo(Observable<? extends R> innerObservable, ResultSelector<? super T, ? super I, ? extends R> resultSelector, int concurrent); public native <R> Observable<R> mergeScan(Scanner<? extends R, ? super T> scanner, R seed); public native <R> Observable<R> mergeScan(Scanner<? extends R, ? super T> scanner, R seed, int concurrent); public native Observable<T> min(); public native Observable<T> min(Comparator<? super T> comparator); public native ConnectableObservable<T> multicast(Subject<? extends T> subject); public native ConnectableObservable<T> multicast(Factory<Subject<? extends T>> subjectFactory); public native ConnectableObservable<T> multicast(Subject<? extends T> subject, Selector<? super T> selector); public native ConnectableObservable<T> multicast(Factory<Subject<? extends T>> subjectFactory, Selector<? extends T> selector); public native static <T> Observable<T> multicast(SubjectFactory<? extends T> subjectFactory); public native static <T> Observable<T> multicast(SubjectFactory<? extends T> subjectFactory, Selector<? extends T> selector); public native static <T> Observable<T> never(); public native Observable<T> observeOn(Scheduler scheduler); public native Observable<T> observeOn(Scheduler scheduler, int delay); public native Observable<T> onErrorResumeNext(Observable<? extends T> inputObservable); public native Observable<T> onErrorResumeNext(Observable<? extends T> v1, Observable<? extends T> v2); public native Observable<T> onErrorResumeNext(Observable<? extends T> v1, Observable<? extends T> v2, Observable<? extends T> v3); public native Observable<T> onErrorResumeNext(Observable<? extends T> v1, Observable<? extends T> v2, Observable<? extends T> v3, Observable<? extends T> v4); public native Observable<T> onErrorResumeNext(Observable<? extends T> v1, Observable<? extends T> v2, Observable<? extends T> v3, Observable<? extends T> v4, Observable<? extends T> v5); public native Observable<T> onErrorResumeNext(Observable<? extends T> v1, Observable<? extends T> v2, Observable<? extends T> v3, Observable<? extends T> v4, Observable<? extends T> v5, Observable<? extends T> v6); public native static Observable<Object[]> pairs(Object o); public native Observable<T[]> pairwise(); public native Observable<T>[] partition(Func1<? super T, Boolean> predicate); public native ConnectableObservable<T> publish(); public native ConnectableObservable<T> publish(Selector<? super T> selector); public native <R extends T> ConnectableObservable<T> publishBehavior(R value); public native ConnectableObservable<T> publishLast(); public native ConnectableObservable<T> publishReplay(); public native ConnectableObservable<T> publishReplay(int bufferSize); public native ConnectableObservable<T> publishReplay(int bufferSize, int windowTime); public native ConnectableObservable<T> publishReplay(int bufferSize, int windowTime, Scheduler scheduler); public native static <T> Observable<T> race(Observable<? extends T> v1, Observable<? extends T> v2); public native static Observable<Integer> range(int start, int count); public native static Observable<Integer> range(int start, int count, Scheduler scheduler); public native Observable<T> reduce(Accumulator<T> accumulator); public native <R> Observable<R> reduce(TransformingAccumulator<R, T> accumulator); public native <R> Observable<R> reduce(TransformingAccumulator<R, T> accumulator, R seed); public native Observable<T> reduce(Accumulator<T> accumulator, T seed); public native Observable<T[]> reduceArray(Accumulator<T[]> accumulator); public native Observable<T[]> reduceArray(Accumulator<T[]> accumulator, T[] seed); public native Observable<T> repeat(); public native Observable<T> repeat(int count); public native Observable<T> repeatWhen(Observable closingNotifier); public native Observable<T> retry(); public native Observable<T> retry(int count); public native Observable<T> retryWhen(Observable closingNotifier); public native Observable<T> sample(Observable notifier); public native Observable<T> sampleTime(int period); public native Observable<T> sampleTime(int period, Scheduler scheduler); public native Observable<T> scan(Accumulator<T> accumulator); public native <R> Observable<R> scan(TransformingAccumulator<R, T> accumulator); public native <R> Observable<R> scan(TransformingAccumulator<R, T> accumulator, R seed); public native Observable<T> scan(Accumulator<T> accumulator, T seed); public native Observable<T[]> scanArray(Accumulator<T[]> accumulator); public native Observable<T[]> scanArray(Accumulator<T[]> accumulator, T[] seed); public native Observable<Boolean> sequenceEqual(Observable<T> compareTo, Func2<T, T, Boolean> comparer); public native Observable<T> share(); public native Observable<T> single(IndexedSourcePredicate<T> predicate); public native Observable<T> skip(int count); public native Observable<T> skipUntil(Observable notifier); public native Observable<T> skipWhile(Predicate<T> predicate); public native Observable<T> skipWhile(IndexedPredicate<T> indexedPredicate); public native Observable<T> startWith(T v1); public native Observable<T> startWith(T v1, Scheduler scheduler); public native Observable<T> startWith(T v1, T v2); public native Observable<T> startWith(T v1, T v2, Scheduler scheduler); public native Subscription subscribe(Action1<? super T> onNext); public native Subscription subscribe(Action1<? super T> onNext, Action1<?> onError); public native Subscription subscribe(Action1<? super T> onNext, Action1<?> onError, Action0 onCompleted); public native Subscription subscribe(Observer<? super T> observer); public native Observable<T> subscribeOn(Scheduler scheduler); public native Observable<T> subscribeOn(Scheduler scheduler, int delay); @JsMethod(name = "switch") public native Observable<T> _switch(); public native <R> Observable<R> switchMap(Projector<? super T, ? extends R> projection); public native <I, R> Observable<R> switchMap(Projector<? super T, ? extends I> projection, ResultSelector<? super T, ? super I, ? extends R> resultSelector); public native <I, R> Observable<R> switchMapTo(Observable<? extends I> observable, ResultSelector<? super T, ? super I, ? extends R> resultSelector); public native Observable<T> take(int count); public native Observable<T> takeLast(int count); public native Observable<T> takeUntil(Observable closingNotifier); public native Observable<T> takeWhile(Observable notifier); public native Observable<T> throttle(Func1<? super T, Observable<?>> durationSelector); public native Observable<T> throttleTime(int duration); public native Observable<T> throttleTime(int duration, Scheduler scheduler); public native Observable<TimeInterval<T>> timeInterval(); public native Observable<TimeInterval<T>> timeInterval(Scheduler scheduler); public native Observable<T> timeout(int due); public native Observable<T> timeout(int due, Scheduler scheduler); public native Observable<T> timeoutWith(int due, Observable<? extends T> withObservable); public native Observable<T> timeoutWith(int due, Observable<? extends T> withObservable, Scheduler scheduler); public native static Observable<Integer> timer(int initialDelay); public native static Observable<Integer> timer(int initialDelay, int period); public native static Observable<Integer> timer(int initialDelay, int period, Scheduler scheduler); public native Observable<Timestamp<T>> timestamp(); public native Observable<Timestamp<T>> timestamp(Scheduler scheduler); public native Observable<T[]> toArray(); public native Observable<Observable<T>> window(Observable windowBoundaries); public native Observable<Observable<T>> windowCount(int windowSize); public native Observable<Observable<T>> windowCount(int windowSize, int startWindowEvery); public native Observable<Observable<T>> windowTime(int windowTimeSpan); public native Observable<Observable<T>> windowTime(int windowTimeSpan, Scheduler scheduler); public native Observable<Observable<T>> windowTime(int windowTimeSpan, int windowCreationInterval); public native Observable<Observable<T>> windowTime(int windowTimeSpan, int windowCreationInterval, Scheduler scheduler); public native Observable<Observable<T>> windowTime(int windowTimeSpan, int windowCreationInterval, int maxWindowSize); public native Observable<Observable<T>> windowTime(int windowTimeSpan, int windowCreationInterval, int maxWindowSize, Scheduler scheduler); public native <O> Observable<Observable<T>> windowToggle(Observable<O> openings, Func1<O, Observable> closingSelector); public native <O> Observable<Observable<T>> windowWhen(Observable closingSelector); public native <T1, T2, R> Observable<R> withLatestFrom(Observable<? extends T1> v1, Observable<? extends T2> v2, Func2<? super T1, ? super T2, ? extends R> combineFunction); public native <T1, T2, T3, R> Observable<R> withLatestFrom(Observable<? extends T1> v1, Observable<? extends T2> v2, Observable<? extends T3> v3, Func3<? super T1, ? super T2, ? super T3, ? extends R> combineFunction); public native <T1, T2, T3, T4, R> Observable<R> withLatestFrom(Observable<? extends T1> v1, Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> combineFunction); public native <R> Observable<R> zip(Func1<? super T, ? extends R> projectFunction); public native <T2, R> Observable<R> zip(Observable<? extends T2> v2, Func2<? super T, ? super T2, ? extends R> projectFunction); public native <T2, T3, R> Observable<R> zip(Observable<? extends T2> v2, Observable<? extends T3> v3, Func3<? super T, ? super T2, ? super T3, ? extends R> projectFunction); public native <T2, T3, T4, R> Observable<R> zip( Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Func4<? super T, ? super T2, ? super T3, ? super T4, ? extends R> projectFunction); public native <T2, T3, T4, T5, R> Observable<R> zip( Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Observable<? extends T5> v5, Func5<? super T, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> projectFunction); public native <T2, T3, T4, T5, T6, R> Observable<R> zip( Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Observable<? extends T5> v5, Observable<? extends T6> v6, Func6<? super T, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> projectFunction); public native <T2> Observable<T[]> zip(Observable<? extends T2> v2); public native <T2, T3> Observable<T[]> zip(Observable<? extends T2> v2, Observable<? extends T3> v3); public native <T2, T3, T4> Observable<T[]> zip(Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4); public native <T2, T3, T4, T5> Observable<T[]> zip(Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Observable<? extends T5> v5); public native <T2, T3, T4, T5, T6> Observable<T[]> zip(Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Observable<? extends T5> v5, Observable<? extends T6> v6); public native static <T> Observable<T[]> zip(Observable<? extends T>[] values); public native static <T1, T2, R> Observable<R> zip(Observable<? extends T1> v1, Observable<? extends T2> v2, Func2<? super T1, ? super T2, ? extends R> projectFunction); public native static <T1, T2, T3, R> Observable<R> zip(Observable<? extends T1> v1, Observable<? extends T2> v2, Observable<? extends T3> v3, Func3<? super T1, ? super T2, ? super T3, ? extends R> projectFunction); public native static <T1, T2, T3, T4, R> Observable<R> zip(Observable<? extends T1> v1, Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Func4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> projectFunction); public native static <T1, T2, T3, T4, T5, R> Observable<R> zip(Observable<? extends T1> v1, Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Observable<? extends T5> v5, Func5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> projectFunction); public native static <T1, T2, T3, T4, T5, T6, R> Observable<R> zip(Observable<? extends T1> v1, Observable<? extends T2> v2, Observable<? extends T3> v3, Observable<? extends T4> v4, Observable<? extends T5> v5, Observable<? extends T6> v6, Func6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> projectFunction); public native static <T, R> Observable<R> zip(Observable<? extends T>[] values, ProjectWithArray<? extends T, ? extends R> projectFunction); public native Observable<T> zipAll(); public native <R> Observable<R> zipAll(Func1<T[], ? extends R> mapper); @JsFunction public interface Accumulator<T> { T call(T acc, T value, int index); } @JsFunction public interface TransformingAccumulator<R, T> { R call(R acc, T value, int index); } @JsFunction public interface Selector<T> { Observable<T> call(Observable<T> observable); } @JsFunction public interface Factory<T> { T call(); } @JsFunction public interface SubjectFactory<T> { Subject<T> call(Observable<T> observable); } @JsFunction public interface Comparator<T> { int compare(T i1, T i2); } @JsFunction public interface Projector<T, R> { Observable<R> project(T item, int index); } @JsFunction public interface Scanner<R, T> { Observable<R> scan(R acc, T item); } @JsFunction public interface ResultSelector<T, I, R> { R selectResult(T outerValue, I innerValue, int outerIndex, int innerIndex); } @JsFunction public interface IndexedResultSelector<T, R> { R selectResult(T value, int index); } @JsFunction public interface IndexedSourcePredicate<T> { boolean test(T value, int index, Observable<T> source); } @JsFunction public interface IndexedPredicate<T> { boolean test(T value, int index); } @JsFunction public interface Predicate<T> { boolean test(T value); } @JsFunction public interface KeySelector<T, K> { K selectKey(T item); } @JsFunction public interface ElementSelector<T, R> { R selectElement(T element); } @JsFunction public interface KeyComparator<K> { boolean compareKey(K k, K k1); } }
package visitors; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.annotation.processing.ProcessingEnvironment; import annotations.Morph; import checkers.types.AnnotatedTypeFactory; import com.sun.source.tree.Tree.Kind; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Scope; import com.sun.tools.javac.comp.AttrContext; import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.comp.Env; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.comp.Attr; import com.sun.tools.javac.comp.MemberEnter; import com.sun.tools.javac.comp.Resolve; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.*; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.tree.TreeTranslator; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Names; import static com.sun.tools.javac.code.Kinds.*; public class ExpansionTranslator extends TreeTranslator { protected static final String SYN_PREFIX = "__"; protected Context context; private Symtab syms; protected TreeMaker make; protected Names names; protected Enter enter; private Resolve rs; protected MemberEnter memberEnter; protected TreePath path; protected Attr attr; protected Log log; protected AnnotatedTypeFactory atypeFactory; public ExpansionTranslator( ProcessingEnvironment processingEnv, TreePath path) { context = ((JavacProcessingEnvironment) processingEnv).getContext(); syms = Symtab.instance(context); make = TreeMaker.instance(context); names = Names.instance(context); enter = Enter.instance(context); rs = Resolve.instance(context); memberEnter = MemberEnter.instance(context); attr = Attr.instance(context); log = Log.instance(context); } @Override public void visitBlock(JCBlock tree) { System.out.println("# visitBlock: \n" + tree); List<JCStatement> stats; for (stats = tree.stats; stats.tail != null; stats = stats.tail) { JCStatement stat = stats.head; if (isMorphedVariableDeclaration(stat)) { System.out.println("# Found a morphed variable declaration: " + stat); JCVariableDecl varDecl = (JCVariableDecl) stat; printSymbolInfo(varDecl.sym); Env<AttrContext> env = enter.getEnv(varDecl.type.tsym); System.out.println("# old var decl: " + varDecl); makeExpandedVarDeclaration(varDecl); System.out.println("# new var decl: " + varDecl); printEnvInfo(env); attr.attribStat(stat, env); printEnvInfo(env); printSymbolInfo(varDecl.sym); } } System.out.println("# end: \n" + tree); super.visitBlock(tree); } @Override public void visitVarDef(JCVariableDecl tree) { super.visitVarDef(tree); if (isMorphedVariableDeclaration(tree)) { makeExpandedVarDeclaration(tree); } } // Inspired by EnerJ public void enterMember(JCTree member, Env<AttrContext> env) { Method meth = null; try { meth = MemberEnter.class.getDeclaredMethod("memberEnter", JCTree.class, Env.class); } catch (NoSuchMethodException e) { System.out.println("raised only if compiler internal api changes"); } meth.setAccessible(true); Object[] args = {member, env}; try { meth.invoke(memberEnter, args); } catch (IllegalAccessException e) { System.out.println("raised only if compiler internal api changes"); } catch (InvocationTargetException e) { System.out.println("raised only if compiler internal api changes"); } } private void spliceNode (List<JCStatement> statementList, JCStatement oldNode, JCStatement newNode){ List<JCTree.JCStatement> newList = List.<JCTree.JCStatement>of(newNode); newList.tail = statementList.tail; statementList.tail = newList; } private void printSymbolInfo(Symbol sym){ System.out.println("# Symbol: " + sym); if (sym != null) { System.out.println("\tKind: " + sym.getKind()); System.out.println("\tType: " + sym.type); System.out.println("\tMembers: " + sym.members()); System.out.println("\tOwner: " + sym.owner); System.out.println("\tOwner Kind: " + sym.owner.getKind()); System.out.println("\tLocation: " + sym.location()); System.out.println("\tMembers " + sym.members()); System.out.println("\tMembers of Owner: " + sym.owner.members()); } } private void printEnvInfo(Env<?> env) { if (env != null) { System.out.println("# env: " + env); System.out.println("# enclosing method: " + env.enclMethod); } } private void makeExpandedVarDeclaration(JCVariableDecl tree) { List<JCExpression> oldInitializerList = ((JCNewClass) tree.init).args; Name expandedClassName = names.fromString("__Logged$Stack"); Type expandedClassType = tree.sym.enclClass().members().lookup(expandedClassName).sym.type; JCNewClass initExpression = make.NewClass(null, null, make.QualIdent(expandedClassType.tsym), oldInitializerList, null); tree.vartype = make.QualIdent(expandedClassType.tsym); tree.setType(expandedClassType); tree.init = initExpression; tree.sym.type = expandedClassType; } private boolean isMorphedVariableDeclaration(JCTree tree){ return tree.getKind() == Kind.VARIABLE && ((JCVariableDecl) tree).getType().type.tsym.getAnnotation(Morph.class) != null; } private JCExpression stringToExpression(String chain) { String[] symbols = chain.split("\\."); JCExpression node = make.Ident(names.fromString(symbols[0])); for (int i = 1; i < symbols.length; i++) { com.sun.tools.javac.util.Name nextName = names.fromString(symbols[i]); node = make.Select(node, nextName); } return node; } }
package logbook.bean; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import logbook.internal.Operator; import logbook.internal.QuestCollect; import logbook.internal.QuestCollect.Count; import logbook.internal.QuestCollect.Rank; import lombok.Data; @Data public class AppQuestCondition implements Predicate<QuestCollect> { private String resetType; private FilterCondition filter; private List<Condition> conditions = new ArrayList<>(); private Boolean result; // internal use only public boolean isCollectStypeInternal() { for (Condition condition : this.conditions) { if ((condition.result == null || condition.result == false) && (condition.stype != null && !condition.stype.isEmpty())) { return true; } } return false; } @Override public boolean test(QuestCollect t) { Predicate<QuestCollect> predicate = null; for (Condition condition : this.conditions) { condition.test(t); if (predicate == null) { predicate = condition; } else { predicate = predicate.and(condition); } } return this.result = predicate.test(t); } @Data public static class FilterCondition { private Set<String> area; private FleetCondition fleet; } @Data public static class FleetCondition implements Predicate<List<ShipMst>> { private String description; private LinkedHashSet<String> stype; private LinkedHashSet<String> name; private boolean difference; private Integer count; private Integer order; private List<FleetCondition> conditions; /** (AND,OR,NAND,NOR,EQ(),GE(),GT(),LE(),LT(),NE()) */ private String operator; @Override public boolean test(List<ShipMst> ships) { if (this.count == null && this.operator != null) { return this.testOperator(ships); } else { return this.testShip(ships); } } @Override public String toString() { if (this.count == null && this.operator != null) { return this.toStringOperator(); } else { return this.toStringShip(); } } /** * (type=) * * @param ships * @return true */ private boolean testShip(List<ShipMst> ships) { if (this.count != null) { int c = 0; for (int i = 0; i < ships.size(); i++) { if (this.difference ^ this.testShip0(ships.get(i))) { c++; } } return Operator.valueOf(this.operator).compare(c, this.count); } else { if (this.order != null) { if (ships.size() >= this.order) { if (this.difference ^ this.testShip0(ships.get(this.order - 1))) { ships.set(this.order - 1, null); return true; } } } else { for (int i = 0; i < ships.size(); i++) { if (this.difference ^ this.testShip0(ships.get(i))) { ships.set(i, null); return true; } } } } return false; } private boolean testShip0(ShipMst ship) { if (ship == null) { return false; } if (this.stype != null) { String stype = ship.asStype() .map(Stype::getName) .orElse(null); return this.stype.contains(stype); } if (this.name != null) { for (String name : this.name) { if (ship.getName().startsWith(name)) { return true; } } } return false; } /** * () * * @param ships * @return true */ private boolean testOperator(List<ShipMst> ships) { Predicate<List<ShipMst>> predicate = null; for (FleetCondition condition : this.conditions) { if (predicate == null) { predicate = condition; } else { predicate = this.operator.endsWith("AND") ? predicate.and(condition) : predicate.or(condition); } } if ("NAND".equals(this.operator) || "NOR".equals(this.operator)) { predicate = predicate.negate(); } return predicate.test(new ArrayList<>(ships)); } private String toStringShip() { StringBuilder sb = new StringBuilder(); if (this.stype != null) { sb.append(this.stype.stream().collect(Collectors.joining(""))); } if (this.name != null) { sb.append(this.name.stream().collect(Collectors.joining(""))); } if (this.difference) { sb.append(""); } if (this.count != null) { sb.append(""); sb.append(this.count); sb.append(""); Operator ope = Operator.valueOf(this.operator); if (ope == Operator.EQ) { sb.append(""); } sb.append(Operator.valueOf(this.operator).toString()); } else { sb.append(""); if (this.order != null) { if (this.order == 1) { sb.append(""); } else { sb.append("" + this.order + ""); } } else { sb.append(""); } } if (this.description != null) { sb.append("(" + this.description + ")"); } return sb.toString(); } private String toStringOperator() { StringBuilder sb = new StringBuilder(); switch (this.operator) { case "AND": sb.append(""); break; case "OR": sb.append("1"); break; case "NAND": sb.append("1"); break; case "NOR": sb.append(""); break; default: break; } if (this.description != null) { sb.append("(" + this.description + ")"); } return sb.toString(); } } @Data public static class Condition implements Predicate<QuestCollect> { private String description; private LinkedHashSet<String> area; /** (7-217215) */ private String cell; private boolean start; private boolean boss; private LinkedHashSet<String> rank; private LinkedHashSet<String> stype; private int count; private Boolean result; private String current; @Override public boolean test(QuestCollect t) { int count = this.count(t); this.current = String.valueOf(count); return this.result = (count >= this.count); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (this.stype != null && !this.stype.isEmpty()) { sb.append(this.stype.stream().collect(Collectors.joining(""))) .append("") .append(this.count) .append(""); } else { if (this.area != null && !this.area.isEmpty()) { sb.append(this.area.stream().collect(Collectors.joining(""))); } else { sb.append(""); } if (this.cell != null) { sb.append("(" + this.cell + ")"); } if (this.start) { sb.append("").append(this.count).append(""); } else { sb.append(""); if (this.boss) { sb.append(""); } if (this.rank == null || this.rank.isEmpty() || this.rank.contains("E") || this.rank.contains("D")) { sb.append(""); } else if (this.rank.contains("C")) { sb.append("C"); } else if (this.rank.contains("B")) { sb.append("B"); } else if (this.rank.contains("A")) { sb.append("A"); } else { sb.append("S"); } sb.append(this.count).append(""); } } if (this.description != null) { sb.append("(" + this.description + ")"); } if (this.current != null) { sb.append("(:" + this.current + ")"); } return sb.toString(); } /** * * @param t * @return */ private int count(QuestCollect t) { int count = 0; if (this.stype != null) { for (String key : this.stype) { Integer v = t.getStype().get(key); if (v != null) { count += v; } } return count; } Count battleCount = new Count(); if (this.area != null) { for (String key : this.area) { Count areaCount = t.getArea().get(key); if (areaCount == null) { continue; } battleCount.add(areaCount); } } else { battleCount = t.getTotal(); } if (this.start) { return battleCount.getStart(); } else { Rank rank; if (this.cell != null) { rank = battleCount.getCell().computeIfAbsent(this.area.stream().findFirst().get() + "-" + this.cell, i -> new Rank()); } else { if (this.boss) { rank = battleCount.getBoss(); } else { rank = battleCount.getAll(); } } boolean any = (this.rank == null || this.rank.isEmpty()); if (any || this.rank.contains("S")) count += rank.getS(); if (any || this.rank.contains("A")) count += rank.getA(); if (any || this.rank.contains("B")) count += rank.getB(); if (any || this.rank.contains("C")) count += rank.getC(); if (any || this.rank.contains("D")) count += rank.getD(); if (any || this.rank.contains("E")) count += rank.getE(); return count; } } } }
package macaca.client.commands; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import macaca.client.common.DriverCommand; import macaca.client.common.MacacaDriver; import macaca.client.common.Utils; public class Element { private MacacaDriver driver; private Utils utils = new Utils(); public Element(MacacaDriver driver) { this.driver = driver; } public void setValue(JSONObject jsonObject) throws Exception { jsonObject.put("sessionId", driver.getSessionId()); jsonObject.put("elementId", driver.getElementId()); utils.request("POST", DriverCommand.ELEMENT_VALUE, jsonObject); } public void click() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("sessionId", driver.getSessionId()); jsonObject.put("elementId", driver.getElementId()); utils.request("POST", DriverCommand.CLICK_ELEMENT, jsonObject); } public void findElement(JSONObject jsonObject) throws Exception { jsonObject.put("sessionId", driver.getSessionId()); JSONObject response = (JSONObject) utils.request("POST", DriverCommand.FIND_ELEMENT, jsonObject); JSONObject element = (JSONObject) response.get("value"); Object elementId = (Object) element.get("ELEMENT"); driver.setElementId(elementId); } public JSONArray findElements(JSONObject jsonObject) throws Exception { jsonObject.put("sessionId", driver.getSessionId()); JSONArray elements = new JSONArray(); elements = (JSONArray) utils.request("POST", DriverCommand.FIND_ELEMENTS, jsonObject); return elements; } public void swipe(JSONObject jsonObject) throws Exception { jsonObject.put("sessionId", driver.getSessionId()); utils.request("POST", DriverCommand.SWIPE, jsonObject); } public void flick(JSONObject jsonObject) throws Exception { jsonObject.put("sessionId", driver.getSessionId()); utils.request("POST", DriverCommand.TOUCH_FLICK, jsonObject); } public void tap(JSONObject jsonObject) throws Exception { jsonObject.put("sessionId", driver.getSessionId()); utils.request("POST", DriverCommand.TOUCH_CLICK, jsonObject); } public String getText() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("sessionId", driver.getSessionId()); jsonObject.put("elementId", driver.getElementId()); String text = (String) utils.request("GET", DriverCommand.GET_ELEMENT_TEXT, jsonObject); return text; } public void clearText() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("sessionId", driver.getSessionId()); jsonObject.put("elementId", driver.getElementId()); utils.request("POST", DriverCommand.CLEAR_ELEMENT, jsonObject); } public String getAttribute(String name) throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("sessionId", driver.getSessionId()); jsonObject.put("elementId", driver.getElementId()); jsonObject.put("name", name); String attribute = (String) utils.request("GET", DriverCommand.GET_ELEMENT_ATTRIBUTE, jsonObject); return attribute; } public String getProperty(String name) throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("sessionId", driver.getSessionId()); jsonObject.put("elementId", driver.getElementId()); jsonObject.put("name", name); String property = (String) utils.request("GET", DriverCommand.GET_ELEMENT_ATTRIBUTE, jsonObject); return property; } public String getComputedCss(String propertyName) throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("sessionId", driver.getSessionId()); jsonObject.put("elementId", driver.getElementId()); jsonObject.put("propertyName", propertyName); String computedCss = (String) utils.request("GET", DriverCommand.GET_ELEMENT_VALUE_OF_CSS_PROPERTY, jsonObject); return computedCss; } public boolean isDisplayed() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("sessionId", driver.getSessionId()); jsonObject.put("elementId", driver.getElementId()); boolean displayed = Boolean .parseBoolean((String) utils.request("GET", DriverCommand.IS_ELEMENT_DISPLAYED, jsonObject)); return displayed; } public void moveTo(JSONObject jsonObject) throws Exception { jsonObject.put("sessionId", driver.getSessionId()); utils.request("POST", DriverCommand.MOVE_TO, jsonObject); } }
package net.hyperic.sigar; /** * Flag constants for network related ops. */ public class NetFlags { private NetFlags () { } /** * value of unknown or non-existent hardware address */ public final static String NULL_HWADDR = "00:00:00:00:00:00"; /** * interface is up */ public final static int IFF_UP = 0x1; /** * broadcast address valid */ public final static int IFF_BROADCAST = 0x2; /** * debugging is on */ public final static int IFF_DEBUG = 0x4; /** * is a loopback net */ public final static int IFF_LOOPBACK = 0x8; /** * interface has a point-to-point link */ public final static int IFF_POINTOPOINT = 0x10; /** * avoid use of trailers */ public final static int IFF_NOTRAILERS = 0x20; /** * interface is running */ public final static int IFF_RUNNING = 0x40; /** * no ARP protocol */ public final static int IFF_NOARP = 0x80; /** * receive all packets */ public final static int IFF_PROMISC = 0x100; /** * receive all multicast packets */ public final static int IFF_ALLMULTI = 0x200; /** * supports multicast */ public final static int IFF_MULTICAST = 0x800; public final static int CONN_CLIENT = 0x01; public final static int CONN_SERVER = 0x02; public final static int CONN_TCP = 0x10; public final static int CONN_UDP = 0x20; public final static int CONN_RAW = 0x40; public final static int CONN_UNIX = 0x80; public final static int CONN_PROTOCOLS = NetFlags.CONN_TCP | NetFlags.CONN_UDP | NetFlags.CONN_RAW | NetFlags.CONN_UNIX; /** * @param flags network interface flags. * @return String representation of network interface flags. * @see net.hyperic.sigar.NetInterfaceConfig#getFlags */ public static String getIfFlagsString(long flags) { String retval = ""; if (flags == 0) retval += "[NO FLAGS] "; if ((flags & IFF_UP) > 0) retval += "UP "; if ((flags & IFF_BROADCAST) > 0) retval += "BROADCAST "; if ((flags & IFF_DEBUG) > 0) retval += "DEBUG "; if ((flags & IFF_LOOPBACK) > 0) retval += "LOOPBACK "; if ((flags & IFF_POINTOPOINT) > 0) retval += "POINTOPOINT "; if ((flags & IFF_NOTRAILERS) > 0) retval += "NOTRAILERS "; if ((flags & IFF_RUNNING) > 0) retval += "RUNNING "; if ((flags & IFF_NOARP) > 0) retval += "NOARP "; if ((flags & IFF_PROMISC) > 0) retval += "PROMISC "; if ((flags & IFF_ALLMULTI) > 0) retval += "ALLMULTI "; if ((flags & IFF_MULTICAST) > 0) retval += "MULTICAST "; return retval; } }
package me.paulbgd.bgdcore.io; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; public class ZipUtils { public static void writeZip(HashMap<InputStream, String> hashMap, OutputStream outputStream) throws IOException { ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); for (Map.Entry<InputStream, String> entry : hashMap.entrySet()) { if (entry.getKey().available() == 0) { // empty array continue; } zipOutputStream.putNextEntry(new ZipEntry(entry.getValue())); IOUtils.copy(entry.getKey(), zipOutputStream); IOUtils.closeQuietly(entry.getKey()); zipOutputStream.closeEntry(); } zipOutputStream.close(); } public static void zipDirectory(OutputStream outputStream, File directory) throws IOException { if (!directory.isDirectory()) { throw new IllegalArgumentException("Is not directory!"); } else if (directory.listFiles() == null) { return; } HashMap<InputStream, String> hashMap = new HashMap<>(); List<File> files = new ArrayList<>(); getFiles(directory, files); String current = directory.getAbsolutePath(); for (File file : files) { hashMap.put(new FileInputStream(file), file.getAbsolutePath().replace(current, "").substring(1)); } writeZip(hashMap, outputStream); } private static void getFiles(File directory, List<File> files) { if (!directory.isDirectory() || directory.listFiles() == null) { return; } for (File file : directory.listFiles()) { if (file.isDirectory()) { getFiles(file, files); } else { files.add(file); } } } public static HashMap<InputStream, String> readZip(InputStream inputStream) throws IOException { HashMap<InputStream, String> list = new HashMap<>(); ZipInputStream zipInputStream = new ZipInputStream(inputStream); ZipEntry entry = zipInputStream.getNextEntry(); while (entry != null) { if (!entry.isDirectory()) { // todo: load data, look it up because you're a nub } zipInputStream.closeEntry(); entry = zipInputStream.getNextEntry(); } zipInputStream.closeEntry(); zipInputStream.close(); return list; } public static void extractZip(InputStream inputStream, File outputDirectory) throws IOException { HashMap<InputStream, String> extracted = readZip(inputStream); for (Map.Entry<InputStream, String> entry : extracted.entrySet()) { File output = new File(outputDirectory, entry.getValue()); if (!output.getParentFile().exists() && !output.getParentFile().mkdirs()) { throw new IOException("Failed to create directory " + output.getParent() + "!"); } if (!output.createNewFile()) { throw new IOException("Failed to create file " + output + "!"); } FileUtils.copyInputStreamToFile(entry.getKey(), output); } } }
package org.fidonet.binkp; import org.apache.mina.core.service.IoService; import org.apache.mina.core.service.IoServiceListener; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.fidonet.binkp.codec.BinkDataCodecFactory; import org.fidonet.binkp.config.ServerRole; import org.fidonet.binkp.handler.BinkSessionHandler; import java.net.InetSocketAddress; import java.net.SocketAddress; public class Server extends Connector{ private NioSocketAcceptor acceptor; private int port = Connector.BINK_PORT; private Integer userConnected = 0; private static int MAX_USER_CONNECTED = 30; public Server() { } public Server(int port) { this.port = port; } @Override public void run(final SessionContext context) throws Exception { acceptor = new NioSocketAcceptor(); acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new BinkDataCodecFactory())); acceptor.setHandler(new BinkSessionHandler(getEventBus())); acceptor.addListener(new IoServiceListener() { @Override public void serviceActivated(IoService ioService) throws Exception { } @Override public void serviceIdle(IoService ioService, IdleStatus idleStatus) throws Exception { } @Override public void serviceDeactivated(IoService ioService) throws Exception { Server.this.stop(context); } @Override public void sessionCreated(IoSession session) throws Exception { // got new connection to server SessionContext sessionContext = new SessionContext(context); sessionContext.setBusy(context.isBusy()); sessionContext.setServerRole(ServerRole.SERVER); session.setAttribute(SessionContext.SESSION_CONTEXT_KEY, sessionContext); //session.getRemoteAddress() synchronized (userConnected){ userConnected++; } if (!context.isBusy() && userConnected > MAX_USER_CONNECTED) { synchronized (context) { context.setBusy(true); } } } @Override public void sessionDestroyed(IoSession session) throws Exception { SessionContext sessionContext = (SessionContext)session.getAttribute(SessionContext.SESSION_CONTEXT_KEY); if (sessionContext.getState().equals(SessionState.STATE_ERR)) { // TODO log or out error message sessionContext.getLastErrorMessage(); } session.removeAttribute(SessionContext.SESSION_CONTEXT_KEY); synchronized (userConnected){ userConnected } if (context.isBusy() && userConnected < MAX_USER_CONNECTED) { synchronized (context) { context.setBusy(false); } } } }); SocketAddress address = new InetSocketAddress(port); acceptor.bind(address); } @Override public void stop(SessionContext context) { acceptor.dispose(); } }
package me.rkfg.pfe.gui; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class DownloadDialog extends Dialog { private DownloadInfo downloadInfo; private Text tb_hash; private Text tb_saveTo; private Button b_cancel; private Button b_ok; private Shell shell; private Button b_saveTo; public DownloadDialog(Shell parent) { super(parent); } public DownloadInfo open() { return open(null, null); } public DownloadInfo open(String path) { return open(null, path); } public DownloadInfo open(String hash, String path) { Shell shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); shell.setText("Добавить закачку"); shell.setSize(400, 300); Display display = shell.getDisplay(); createUI(shell); if (path == null) { tb_saveTo.setText(Main.HOME); } else { tb_saveTo.setText(path); } setHandlers(); Main.center(shell, true); if (hash != null && !hash.isEmpty() && hash.length() == 32) { tb_hash.setText(hash); tb_hash.setEnabled(false); } shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return downloadInfo; } private void createUI(Shell shell) { this.shell = shell; shell.setLayout(new GridLayout(3, false)); Label lblNewLabel = new Label(shell, SWT.NONE); lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblNewLabel.setText("Код для скачивания"); tb_hash = new Text(shell, SWT.BORDER); GridData gd_text = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); gd_text.minimumWidth = 300; tb_hash.setLayoutData(gd_text); Label label = new Label(shell, SWT.NONE); label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); label.setText("Сохранить в"); tb_saveTo = new Text(shell, SWT.BORDER); tb_saveTo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); b_saveTo = new Button(shell, SWT.NONE); b_saveTo.setText("Обзор..."); Composite c_okCancel = new Composite(shell, SWT.NONE); RowLayout rl_composite = new RowLayout(SWT.HORIZONTAL); c_okCancel.setLayout(rl_composite); c_okCancel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 3, 1)); b_ok = new Button(c_okCancel, SWT.NONE); b_ok.setText("OK"); b_cancel = new Button(c_okCancel, SWT.NONE); b_cancel.setText("Отмена"); shell.pack(); } private void setHandlers() { b_cancel.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { shell.close(); } }); b_ok.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String hash = tb_hash.getText(); if (!Main.validateHash(hash)) { MessageBox messageBox = new MessageBox(getParent()); messageBox.setText("Ошибка"); messageBox.setMessage("Неверно введён код. Он должен содержать ровно 32 символа, цифры от 2 до 7 и буквы от A до Z."); messageBox.open(); return; } downloadInfo = new DownloadInfo(); downloadInfo.hash = hash; downloadInfo.path = tb_saveTo.getText(); shell.close(); } }); b_saveTo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DirectoryDialog directoryDialog = new DirectoryDialog(shell, SWT.SAVE); directoryDialog.setText("Выберите папку"); directoryDialog.setMessage("Выберите папку для скачивания"); directoryDialog.setFilterPath(tb_saveTo.getText()); String selected = directoryDialog.open(); if (selected == null) { return; } tb_saveTo.setText(selected); } }); } }
package top.cardone.configuration.service.impl; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.collections.CollectionUtils; import org.springframework.data.domain.Page; import org.springframework.transaction.annotation.Transactional; import top.cardone.cache.Cache; import top.cardone.configuration.dao.DictionaryDao; import top.cardone.configuration.service.DictionaryService; import top.cardone.context.ApplicationContextHolder; import top.cardone.context.util.MapUtils; import top.cardone.context.util.StringUtils; import top.cardone.data.service.impl.PageServiceImpl; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * * * @author yao hai tao */ @Transactional(readOnly = true) public class DictionaryServiceImpl extends PageServiceImpl<DictionaryDao> implements top.cardone.configuration.service.DictionaryService { @Override public Page<Map<String, Object>> pageCache(Object page) { return this.page(page); } @Override public <P> Page<P> pageCache(Class<P> mappedClass, Object page) { return this.page(mappedClass, page); } @Override public <P> List<P> findListCache(Class<P> mappedClass, Object findList) { return this.findList(mappedClass, findList); } @Override public <P> P findOneCache(Class<P> mappedClass, Object findOne) { return this.findOne(mappedClass, findOne); } @Override public <R> List<R> readListCache(Class<R> requiredType, Object readList) { return this.readList(requiredType, readList); } @Override public <R> R readOneCache(Class<R> requiredType, Object readOne) { return this.readOne(requiredType, readOne); } @Override @Transactional public int deleteCache(Object delete) { return this.delete(delete); } @Override @Transactional public int deleteAllCache() { return this.deleteAll(); } @Override @Transactional public int deleteByIdsCache(Object ids) { return this.deleteByIds(ids); } @Override @Transactional public int[] deleteListCache(List<Object> deleteList) { return this.deleteList(deleteList); } @Override public List<Map<String, Object>> findListCache(Object findList) { return this.findList(findList); } @Override public Map<String, Object> findOneCache(Object findOne) { return this.findOne(findOne); } @Override @Transactional public int insertCache(Object insert) { return this.insert(insert); } @Override @Transactional public int insertByNotExistsCache(Object insert) { return this.insertByNotExists(insert); } @Override @Transactional public int[] insertListCache(List<Object> insertList) { return this.insertList(insertList); } @Override @Transactional public int[] insertListByNotExistsCache(List<Object> insertList) { return this.insertListByNotExists(insertList); } @Override public List<Object> readListCache(Object readList) { return this.readList(readList); } @Override public Object readOneCache(Object readOne) { return this.readOne(readOne); } @Override @Transactional public Integer saveCache(Object save) { return this.save(save); } @Override @Transactional public int updateCache(Object update) { return this.update(update); } @Override @Transactional public int[] updateListCache(List<Object> updateList) { return this.updateList(updateList); } @Override public Page<Map<String, Object>> pageByCode(Map<String, Object> page) { return this.dao.pageByCode(page); } @Override public List<Map<String, Object>> findListByDictionaryTypeCode(String dictionaryTypeCode) { return this.dao.findlistByDictionaryTypeCode(dictionaryTypeCode); } @Override public Map<String, Object> findOneByDictionaryId(Map<String, Object> findOne) { return this.dao.findOneByDictionaryId(findOne); } @Override public List<Map<String, Object>> findListByKeyword(Map<String, Object> findList) { return this.dao.findListByKeyword(findList); } @Override public String readOneNameByCode(String dictionaryTypeCode, String dictionaryCode, String defaultValue) { return this.readOneByCode(dictionaryTypeCode, dictionaryCode, defaultValue, "name"); } private String readOneByCode(String dictionaryTypeCode, String dictionaryCode, String defaultValue, String objectId) { Map<String, Object> readOne = Maps.newHashMap(); readOne.put("dictionaryTypeCode", dictionaryTypeCode); readOne.put("dictionaryCode", dictionaryCode); readOne.put("object_id", objectId); return this.readOneByCode(readOne, defaultValue); } private String readOneByCode(Map<String, Object> readOne, String defaultValue) { String str = this.dao.readOne(String.class, readOne); if (StringUtils.isBlank(str)) { Set<Map<String, Object>> insertDictionarySet = ApplicationContextHolder.getBean(Cache.class).get("init-data", "insertDictionarySet", () -> Sets.newHashSet()); Map<String,Object> insert = Maps.newHashMap(readOne); insert.put(MapUtils.getString(readOne, "object_id"), defaultValue); insertDictionarySet.add(insert); ApplicationContextHolder.getBean(Cache.class).put("init-data", "insertDictionarySet", insertDictionarySet); } return StringUtils.defaultIfBlank(str, defaultValue); } @Override public String readOneValueByCode(String dictionaryTypeCode, String dictionaryCode, String defaultValue) { return this.readOneByCode(dictionaryTypeCode, dictionaryCode, defaultValue, "value"); } @Override public String readOneRemarkByCode(String dictionaryTypeCode, String dictionaryCode, String defaultValue) { return this.readOneByCode(dictionaryTypeCode, dictionaryCode, defaultValue, "remark"); } @Override public String readOneExplainByCode(String dictionaryTypeCode, String dictionaryCode, String defaultValue) { return this.readOneByCode(dictionaryTypeCode, dictionaryCode, defaultValue, "explain"); } @Override public String readOneExplainByCodeCache(String dictionaryTypeCode, String dictionaryCode, String defaultValue) { return this.readOneExplainByCode(dictionaryTypeCode, dictionaryCode, defaultValue); } @Override public List<Map<String, Object>> findListByDictionaryTypeCodes(String dictionaryTypeCodes) { String[] dictionaryTypeCodeArray = StringUtils.split(dictionaryTypeCodes, ","); for (String dictionaryTypeCode : dictionaryTypeCodeArray) { List<Map<String, Object>> mapList = ApplicationContextHolder.getBean(DictionaryService.class).findListByDictionaryTypeCode(dictionaryTypeCode); if (!CollectionUtils.isEmpty(mapList)) { return mapList; } } return Lists.newArrayList(); } @Override public List<Map<String, Object>> findListByDictionaryTypeCodesCache(String dictionaryTypeCodes) { return this.findListByDictionaryTypeCodes(dictionaryTypeCodes); } @Override public Object readOneByDictionaryTypeCodes(Map<String, Object> readOne) { String[] dictionaryTypeCodeArray = StringUtils.split(MapUtils.getString(readOne, "dictionaryTypeCodes"), ","); if (dictionaryTypeCodeArray == null) { return null; } for (String dictionaryTypeCode : dictionaryTypeCodeArray) { readOne.put("dictionaryTypeCode", dictionaryTypeCode); Object obj = this.readOneByCode(readOne, null); if (!Objects.isNull(obj)) { return obj; } } return null; } }
// jTDS JDBC Driver for Microsoft SQL Server and Sybase // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sourceforge.jtds.jdbc; import java.io.*; import java.sql.*; import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import net.sourceforge.jtds.util.*; /** * This class implements the Sybase / Microsoft TDS protocol. * <p> * Implementation notes: * <ol> * <li>This class, together with TdsData, encapsulates all of the TDS specific logic * required by the driver. * <li>This is a ground up reimplementation of the TDS protocol and is rather * simpler, and hopefully easier to understand, than the original. * <li>The layout of the various Login packets is derived from the original code * and freeTds work, and incorporates changes including the ability to login as a TDS 5.0 user. * <li>All network I/O errors are trapped here, reported to the log (if active) * and the parent Connection object is notified that the connection should be considered * closed. * <li>Rather than having a large number of classes one for each token, useful information * about the current token is gathered together in the inner TdsToken class. * <li>As the rest of the driver interfaces to this code via higher-level method calls there * should be know need for knowledge of the TDS protocol to leak out of this class. * It is for this reason that all the TDS Token constants are private. * </ol> * * @author Mike Hutchinson * @author Matt Brinkley * @author Alin Sinpalean * @author freeTDS project * @version $Id: TdsCore.java,v 1.63 2005-01-06 16:39:29 alin_sinpalean Exp $ */ public class TdsCore { /** * Inner static class used to hold information about TDS tokens read. */ private static class TdsToken { /** The current TDS token byte. */ byte token; /** The status field from a DONE packet. */ byte status; /** The operation field from a DONE packet. */ byte operation; /** The update count from a DONE packet. */ int updateCount; /** The nonce from an NTLM challenge packet. */ byte[] nonce; /** NTLM authentication message. */ byte[] ntlmMessage; /** The dynamicID from the last TDS_DYNAMIC token. */ String dynamicId; /** The TDS token that preceded the dynamic parameter data. */ int previousToken; /** The dynamic parameters from the last TDS_DYNAMIC token. */ ColInfo[] dynamParamInfo; /** The dynamic parameter data from the last TDS_DYNAMIC token. */ Object[] dynamParamData; /** * Retrieve the update count status. * * @return <code>boolean</code> true if the update count is valid. */ boolean isUpdateCount() { return isEndToken() && (status & DONE_ROW_COUNT) != 0; } /** * Retrieve the DONE token status. * * @return <code>boolean</code> true if the current token is a DONE packet. */ boolean isEndToken() { return token == TDS_DONE_TOKEN || token == TDS_DONEINPROC_TOKEN || token == TDS_DONEPROC_TOKEN; } /** * Retrieve the NTLM challenge status. * * @return <code>boolean</code> true if the current token is an NTLM challenge. */ boolean isAuthToken() { return token == TDS_AUTH_TOKEN; } /** * Retrieve the results pending status. * * @return <code>boolean</code> true if more results in input. */ boolean resultsPending() { return !isEndToken() || ((status & DONE_MORE_RESULTS) != 0); } /** * Retrieve the result set status. * * @return <code>boolean</code> true if the current token is a result set. */ boolean isResultSet() { return token == TDS_COLFMT_TOKEN || token == TDS7_RESULT_TOKEN || token == TDS_RESULT_TOKEN || token == TDS5_WIDE_RESULT || token == TDS_COLINFO_TOKEN || token == TDS_ROW_TOKEN; } /** * Retrieve the row data status. * * @return <code>boolean</code> true if the current token is a result row. */ public boolean isRowData() { return token == TDS_ROW_TOKEN; } } /** * Inner static class used to hold table meta data. */ private static class TableMetaData { /** Table catalog (database) name. */ String catalog; /** Table schema (user) name. */ String schema; /** Table name. */ String name; } /** * Simple timer class used to implement query timeouts. * <p>When the timer expires a cancel packet is sent causing * the server to abort the request. */ private static class QueryTimer extends Thread { private int timeout; private TdsCore tds; private boolean exitNow; private boolean cancelled; QueryTimer(TdsCore tds, int timeout) { this.timeout = timeout; this.tds = tds; } public void run() { while (!exitNow) { try { sleep(timeout * 1000); cancelled = true; tds.cancel(); return; } catch (java.lang.InterruptedException e) { // nop } } } void stopTimer() { exitNow = true; this.interrupt(); } boolean wasCancelled() { return this.cancelled; } } // Package private constants /** Minimum network packet size. */ public static final int MIN_PKT_SIZE = 512; /** Default minimum network packet size for TDS 7.0 and newer. */ public static final int DEFAULT_MIN_PKT_SIZE_TDS70 = 4096; /** Maximum network packet size. */ public static final int MAX_PKT_SIZE = 32768; /** The size of the packet header. */ static final int PKT_HDR_LEN = 8; /** TDS 4.2 or 7.0 Query packet. */ static final byte QUERY_PKT = 1; /** TDS 4.2 or 5.0 Login packet. */ static final byte LOGIN_PKT = 2; /** TDS Remote Procedure Call. */ static final byte RPC_PKT = 3; /** TDS Reply packet. */ static final byte REPLY_PKT = 4; /** TDS Cancel packet. */ static final byte CANCEL_PKT = 6; /** TDS MSDTC packet. */ static final byte MSDTC_PKT = 14; /** TDS 5.0 Query packet. */ static final byte SYBQUERY_PKT = 15; /** TDS 7.0 Login packet. */ static final byte MSLOGIN_PKT = 16; /** TDS 7.0 NTLM Authentication packet. */ static final byte NTLMAUTH_PKT = 17; // Sub packet types /** TDS 5.0 Parameter format token. */ private static final byte TDS5_PARAMFMT2_TOKEN = (byte) 32; // 0x20 /** TDS 5.0 Language token. */ private static final byte TDS_LANG_TOKEN = (byte) 33; // 0x21 /** TSD 5.0 Wide result set token. */ private static final byte TDS5_WIDE_RESULT = (byte) 97; // 0x61 /** TDS 5.0 Close token. */ private static final byte TDS_CLOSE_TOKEN = (byte) 113; // 0x71 /** TDS DBLIB Offsets token. */ private static final byte TDS_OFFSETS_TOKEN = (byte) 120; // 0x78 /** TDS Procedure call return status token. */ private static final byte TDS_RETURNSTATUS_TOKEN= (byte) 121; // 0x79 /** TDS Procedure ID token. */ private static final byte TDS_PROCID = (byte) 124; // 0x7C /** TDS 7.0 Result set column meta data token. */ private static final byte TDS7_RESULT_TOKEN = (byte) 129; // 0x81 /** TDS 7.0 Computed Result set column meta data token. */ private static final byte TDS7_COMP_RESULT_TOKEN= (byte) 136; // 0x88 /** TDS 4.2 Column names token. */ private static final byte TDS_COLNAME_TOKEN = (byte) 160; // 0xA0 /** TDS 4.2 Column meta data token. */ private static final byte TDS_COLFMT_TOKEN = (byte) 161; // 0xA1 /** TDS Table name token. */ private static final byte TDS_TABNAME_TOKEN = (byte) 164; // 0xA4 /** TDS Cursor results column infomation token. */ private static final byte TDS_COLINFO_TOKEN = (byte) 165; // 0xA5 /** TDS Optional command token. */ private static final byte TDS_OPTIONCMD_TOKEN = (byte) 166; // 0xA6 /** TDS Computed result set names token. */ private static final byte TDS_COMP_NAMES_TOKEN = (byte) 167; // 0xA7 /** TDS Computed result set token. */ private static final byte TDS_COMP_RESULT_TOKEN = (byte) 168; // 0xA8 /** TDS Order by columns token. */ private static final byte TDS_ORDER_TOKEN = (byte) 169; // 0xA9 /** TDS error result token. */ private static final byte TDS_ERROR_TOKEN = (byte) 170; // 0xAA /** TDS Information message token. */ private static final byte TDS_INFO_TOKEN = (byte) 171; // 0xAB /** TDS Output parameter value token. */ private static final byte TDS_PARAM_TOKEN = (byte) 172; // 0xAC /** TDS Login acknowledgement token. */ private static final byte TDS_LOGINACK_TOKEN = (byte) 173; // 0xAD /** TDS control token. */ private static final byte TDS_CONTROL_TOKEN = (byte) 174; // 0xAE /** TDS Result set data row token. */ private static final byte TDS_ROW_TOKEN = (byte) 209; // 0xD1 /** TDS Computed result set data row token. */ private static final byte TDS_ALTROW = (byte) 211; // 0xD3 /** TDS 5.0 parameter value token. */ private static final byte TDS5_PARAMS_TOKEN = (byte) 215; // 0xD7 /** TDS 5.0 capabilities token. */ private static final byte TDS_CAP_TOKEN = (byte) 226; // 0xE2 /** TDS environment change token. */ private static final byte TDS_ENVCHANGE_TOKEN = (byte) 227; // 0xE3 /** TDS 5.0 message token. */ private static final byte TDS_MSG50_TOKEN = (byte) 229; // 0xE5 /** TDS 5.0 RPC token. */ private static final byte TDS_DBRPC_TOKEN = (byte) 230; // 0xE6 /** TDS 5.0 Dynamic SQL token. */ private static final byte TDS5_DYNAMIC_TOKEN = (byte) 231; // 0xE7 /** TDS 5.0 parameter descriptor token. */ private static final byte TDS5_PARAMFMT_TOKEN = (byte) 236; // 0xEC /** TDS 7.0 NTLM authentication challenge token. */ private static final byte TDS_AUTH_TOKEN = (byte) 237; // 0xED /** TDS 5.0 Result set column meta data token. */ private static final byte TDS_RESULT_TOKEN = (byte) 238; // 0xEE /** TDS done token. */ private static final byte TDS_DONE_TOKEN = (byte) 253; // 0xFD DONE /** TDS done procedure token. */ private static final byte TDS_DONEPROC_TOKEN = (byte) 254; // 0xFE DONEPROC /** TDS done in procedure token. */ private static final byte TDS_DONEINPROC_TOKEN = (byte) 255; // 0xFF DONEINPROC // Environment change payload codes /** Environment change: database changed. */ private static final byte TDS_ENV_DATABASE = (byte) 1; /** Environment change: language changed. */ private static final byte TDS_ENV_LANG = (byte) 2; /** Environment change: charset changed. */ private static final byte TDS_ENV_CHARSET = (byte) 3; /** Environment change: network packet size changed. */ private static final byte TDS_ENV_PACKSIZE = (byte) 4; /** Environment change: locale changed. */ private static final byte TDS_ENV_LCID = (byte) 5; /** Environment change: TDS 8 collation changed. */ private static final byte TDS_ENV_SQLCOLLATION = (byte) 7; // TDS8 Collation // Static variables used only for performance /** Used to optimize the {@link #getParameters()} call */ private static final ParamInfo[] EMPTY_PARAMETER_INFO = new ParamInfo[0]; // End token status bytes /** Done: more results are expected. */ private static final byte DONE_MORE_RESULTS = (byte) 0x01; /** Done: command caused an error. */ private static final byte DONE_ERROR = (byte) 0x02; /** Done: There is a valid row count. */ private static final byte DONE_ROW_COUNT = (byte) 0x10; /** Done: Cancel acknowledgement. */ static final byte DONE_CANCEL = (byte) 0x20; /** * Done: Response terminator (if more than one request packet is sent, each * response is terminated by a DONE packet with this flag set). */ private static final byte DONE_END_OF_RESPONSE = (byte) 0x80; // Prepared SQL types /** Do not prepare SQL */ public static final int UNPREPARED = 0; /** Prepare SQL using temporary stored procedures */ public static final int TEMPORARY_STORED_PROCEDURES = 1; /** Prepare SQL using sp_executesql */ public static final int EXECUTE_SQL = 2; /** Prepare SQL using sp_prepare and sp_execute */ public static final int PREPARE = 3; /** Prepare SQL using sp_prepexec and sp_execute */ public static final int PREPEXEC = 4; // Sybase capability flags /** Sybase char and binary > 255.*/ static final int SYB_LONGDATA = 1; /** Sybase date and time data types.*/ static final int SYB_DATETIME = 2; /** Sybase nullable bit type.*/ static final int SYB_BITNULL = 4; /** Sybase extended column meta data.*/ static final int SYB_EXTCOLINFO = 8; /** Sybase univarchar etc. */ static final int SYB_UNICODE = 16; // Class variables /** Name of the client host (it can take quite a while to find it out if DNS is configured incorrectly). */ private static String hostName = null; // Instance variables /** The Connection object that created this object. */ private ConnectionJDBC2 connection; /** The TDS version being supported by this connection. */ private int tdsVersion; /** The make of SQL Server (Sybase/Microsoft). */ private int serverType; /** The Shared network socket object. */ private SharedSocket socket; /** The output server request stream. */ private RequestStream out; /** The input server response stream. */ private ResponseStream in; /** True if the server response is fully read. */ private boolean endOfResponse = true; /** True if the current result set is at end of file. */ private boolean endOfResults = true; /** The array of column meta data objects for this result set. */ private ColInfo[] columns; /** The array of column data objects in the current row. */ private Object[] rowData; /** The array of table names associated with this result. */ private TableMetaData[] tables; /** The descriptor object for the current TDS token. */ private TdsToken currentToken = new TdsToken(); /** The stored procedure return status. */ private Integer returnStatus; /** The return parameter meta data object for the current procedure call. */ private ParamInfo returnParam; /** The array of parameter meta data objects for the current procedure call. */ private ParamInfo[] parameters; /** The index of the next output parameter to populate. */ private int nextParam = -1; /** The head of the diagnostic messages chain. */ private SQLDiagnostic messages; /** Indicates that this object is closed. */ private boolean isClosed; /** Indicates reading results from READTEXT command. */ private boolean readTextMode; /** A reference to ntlm.SSPIJNIClient. */ private SSPIJNIClient sspiJNIClient; /** Flag that indicates if logon() should try to use Windows Single Sign On using SSPI. */ private boolean ntlmAuthSSO; /** Indicates that a fatal error has occured and the connection will close. */ private boolean fatalError; /** Mutual exclusion lock on connection. */ private Semaphore connectionLock; /** Indicates processing a batch. */ private boolean inBatch; /** * Construct a TdsCore object. * * @param connection The connection which owns this object. * @param messages The SQLDiagnostic messages chain. */ TdsCore(ConnectionJDBC2 connection, SQLDiagnostic messages) { this.connection = connection; this.socket = connection.getSocket(); this.messages = messages; serverType = connection.getServerType(); tdsVersion = socket.getTdsVersion(); out = socket.getRequestStream(); in = socket.getResponseStream(out); out.setBufferSize(connection.getNetPacketSize()); out.setMaxPrecision(connection.getMaxPrecision()); } /** * Check that the connection is still open. * * @throws SQLException */ private void checkOpen() throws SQLException { if (connection.isClosed()) { throw new SQLException( Messages.get("error.generic.closed", "Connection"), "HY010"); } } /** * Retrieve the TDS protocol version. * * @return The protocol version as an <code>int</code>. */ int getTdsVersion() { return tdsVersion; } /** * Retrieve the current result set column descriptors. * * @return The column descriptors as a <code>ColInfo[]</code>. */ ColInfo[] getColumns() { return columns; } /** * Retrieve the parameter meta data from a Sybase prepare. * * @return The parameter descriptors as a <code>ParamInfo[]</code>. */ ParamInfo[] getParameters() { if (currentToken.dynamParamInfo != null) { ParamInfo[] params = new ParamInfo[currentToken.dynamParamInfo.length]; for (int i = 0; i < params.length; i++) { ColInfo ci = currentToken.dynamParamInfo[i]; params[i] = new ParamInfo(ci, ci.realName, null, 0); } return params; } return EMPTY_PARAMETER_INFO; } /** * Retrieve the current result set data items. * * @return the row data as an <code>Object</code> array */ Object[] getRowData() { return rowData; } /** * Login to the SQL Server. * * @param serverName The server host name. * @param database The required database. * @param user The user name. * @param password The user password. * @param domain The Windows NT domain (or null). * @param charset The required server character set. * @param appName The application name. * @param progName The program name. * @param language The language to use for server messages. * @param macAddress The client network MAC address. * @param packetSize The required network packet size. * @throws SQLException */ void login(final String serverName, final String database, final String user, final String password, final String domain, final String charset, final String appName, final String progName, final String language, final String macAddress, final int packetSize) throws SQLException { try { if (tdsVersion >= Driver.TDS70) { sendMSLoginPkt(serverName, database, user, password, domain, appName, progName, language, macAddress, packetSize); } else if (tdsVersion == Driver.TDS50) { send50LoginPkt(serverName, user, password, charset, appName, progName, language, packetSize); } else { send42LoginPkt(serverName, user, password, charset, appName, progName, language, packetSize); } nextToken(); while (!endOfResponse) { if (currentToken.isAuthToken()) { sendNtlmChallengeResponse(currentToken.nonce, user, password, domain); } nextToken(); } messages.checkErrors(); } catch (IOException ioe) { throw Support.linkException( new SQLException( Messages.get( "error.generic.ioerror", ioe.getMessage()), "08S01"), ioe); } } /** * Get the next result set or update count from the TDS stream. * * @return <code>boolean</code> if the next item is a result set. * @throws SQLException */ boolean getMoreResults() throws SQLException { checkOpen(); nextToken(); while (!endOfResponse && !currentToken.isUpdateCount() && !currentToken.isResultSet()) { nextToken(); } messages.checkErrors(); // Cursor opens are followed by TDS_TAB_INFO and TDS_COL_INFO // Process these now so that the column descriptors are updated. // Sybase wide result set headers are followed by a TDS_CONTROL_TOKEN // skip that as well. if (currentToken.isResultSet()) { byte saveToken = currentToken.token; try { byte x = (byte) in.peek(); while ( x == TDS_TABNAME_TOKEN || x == TDS_COLINFO_TOKEN || x == TDS_CONTROL_TOKEN) { nextToken(); x = (byte)in.peek(); } } catch (IOException e) { connection.setClosed(); throw Support.linkException( new SQLException( Messages.get( "error.generic.ioerror", e.getMessage()), "08S01"), e); } currentToken.token = saveToken; } messages.checkErrors(); return currentToken.isResultSet(); } /** * Retrieve the status of the next result item. * * @return <code>boolean</code> true if the next item is a result set. */ boolean isResultSet() { return currentToken.isResultSet(); } /** * Retrieve the status of the next result item. * * @return <code>boolean</code> true if the next item is row data. */ boolean isRowData() { return currentToken.isRowData(); } /** * Retrieve the status of the next result item. * * @return <code>boolean</code> true if the next item is an update count. */ boolean isUpdateCount() { return currentToken.isUpdateCount(); } /** * Retrieve the update count from the current TDS token. * * @return The update count as an <code>int</code>. */ int getUpdateCount() { if (currentToken.isEndToken()) { return currentToken.updateCount; } return -1; } /** * Retrieve the status of the response stream. * * @return <code>boolean</code> true if the response has been entirely consumed */ boolean isEndOfResponse() { return endOfResponse; } /** * Empty the server response queue. * * @throws SQLException if an error occurs */ void clearResponseQueue() throws SQLException { checkOpen(); while (!endOfResponse) { nextToken(); } } /** * Consume packets from the server response queue up to (and including) the * first response terminator. * * @throws SQLException if an error occurs */ void consumeOneResponse() throws SQLException { checkOpen(); while (!endOfResponse) { nextToken(); // If it's a response terminator, return if (currentToken.isEndToken() && (currentToken.status & DONE_END_OF_RESPONSE) != 0) { return; } } messages.checkErrors(); } /** * Retrieve the next data row from the result set. * * @return <code>boolean</code> - <code>false</code> if at end of results. */ boolean getNextRow() throws SQLException { if (endOfResponse || endOfResults) { return false; } checkOpen(); nextToken(); // Will either be first or next data row or end. while (!currentToken.isRowData() && !currentToken.isEndToken()) { nextToken(); // Could be messages } messages.checkErrors(); return currentToken.isRowData(); } /** * Retrieve the status of result set. * <p> * This does a quick read ahead and is needed to support the isLast() * method in the ResultSet. * * @return <code>boolean</code> - <code>true</code> if there is more data * in the result set. */ boolean isDataInResultSet() throws SQLException { byte x; checkOpen(); try { x = (endOfResponse) ? TDS_DONE_TOKEN : (byte) in.peek(); while (x != TDS_ROW_TOKEN && x != TDS_DONE_TOKEN && x != TDS_DONEINPROC_TOKEN && x != TDS_DONEPROC_TOKEN) { nextToken(); x = (byte) in.peek(); } messages.checkErrors(); } catch (IOException e) { connection.setClosed(); throw Support.linkException( new SQLException( Messages.get( "error.generic.ioerror", e.getMessage()), "08S01"), e); } return x == TDS_ROW_TOKEN; } /** * Retrieve the return status for the current stored procedure. * * @return The return status as an <code>Integer</code>. */ Integer getReturnStatus() { return this.returnStatus; } /** * Inform the server that this connection is closing. * <p> * Used by Sybase a no-op for Microsoft. */ synchronized void closeConnection() { try { if (tdsVersion == Driver.TDS50) { out.setPacketType(SYBQUERY_PKT); out.write((byte)TDS_CLOSE_TOKEN); out.write((byte)0); out.flush(); endOfResponse = false; clearResponseQueue(); } } catch (Exception e) { // Ignore any exceptions as this connection // is closing anyway. } } /** * Close the TDSCore connection object and associated streams. * * @throws SQLException */ void close() throws SQLException { if (!isClosed) { try { clearResponseQueue(); out.close(); in.close(); } finally { isClosed = true; } } } /** * Send a cancel packet to the server. */ void cancel() { Semaphore mutex = null; try { mutex = connection.getMutex(); mutex.acquire(); socket.cancel(out.getStreamId()); } catch (InterruptedException e) { mutex = null; } finally { if (mutex != null) { mutex.release(); } } } /** * Submit a simple SQL statement to the server and process all output. * * @param sql the statement to execute * @throws SQLException if an error is returned by the server */ void submitSQL(String sql) throws SQLException { checkOpen(); if (sql.length() == 0) { throw new IllegalArgumentException("submitSQL() called with empty SQL String"); } executeSQL(sql, null, null, false, 0, -1, true); clearResponseQueue(); messages.checkErrors(); } /** * Send an SQL statement with optional parameters to the server. * * @param sql SQL statement to execute * @param procName stored procedure to execute or <code>null</code> * @param parameters parameters for call or null * @param noMetaData suppress meta data for cursor calls * @param timeOut optional query timeout or 0 * @param maxRows the maximum number of data rows to return * @param sendNow whether to send the request now or not * @throws SQLException if an error occurs */ synchronized void executeSQL(String sql, String procName, ParamInfo[] parameters, boolean noMetaData, int timeOut, int maxRows, boolean sendNow) throws SQLException { boolean sendFailed = true; // Used to ensure mutex is released. try { // Obtain a lock on the connection giving exclusive access // to the network connection for this thread if (connectionLock == null) { connectionLock = connection.getMutex(); try { connectionLock.acquire(); } catch (InterruptedException e) { connectionLock = null; throw new IllegalStateException("Connection synchronization failed"); } } checkOpen(); clearResponseQueue(); messages.exceptions = null; if (sendNow) { // Need to know we are sending a batch inBatch = true; } // Set the connection row count if required. // Once set this will not be changed within a // batch so execution of the set rows query will // only occur once a the start of a batch. // No other thread can send until this one has finished. setRowCount(maxRows); messages.clearWarnings(); this.returnStatus = null; // Normalize the parameters argument to simplify later checks if (parameters != null && parameters.length == 0) { parameters = null; } this.parameters = parameters; // Normalise the procName argument as well if (procName != null && procName.length() == 0) { procName = null; } if (parameters != null && parameters[0].isRetVal) { returnParam = parameters[0]; nextParam = 0; } else { returnParam = null; nextParam = -1; } if (parameters != null) { if (procName == null && sql.startsWith("EXECUTE ")) { // If this is a callable statement that could not be fully parsed // into an RPC call convert to straight SQL now. // An example of non RPC capable SQL is {?=call sp_example('literal', ?)} for (int i = 0; i < parameters.length; i++){ // Output parameters not allowed. if (!parameters[i].isRetVal && parameters[i].isOutput){ throw new SQLException(Messages.get("error.prepare.nooutparam", Integer.toString(i + 1)), "07000"); } } sql = Support.substituteParameters(sql, parameters, getTdsVersion()); parameters = null; } else { // Check all parameters are either output or have values set for (int i = 0; i < parameters.length; i++){ if (!parameters[i].isSet && !parameters[i].isOutput){ throw new SQLException(Messages.get("error.prepare.paramnotset", Integer.toString(i + 1)), "07000"); } parameters[i].clearOutValue(); TdsData.getNativeType(connection, parameters[i]); } } } try { switch (tdsVersion) { case Driver.TDS42: executeSQL42(sql, procName, parameters, noMetaData, sendNow); break; case Driver.TDS50: executeSQL50(sql, procName, parameters); break; case Driver.TDS70: case Driver.TDS80: case Driver.TDS81: executeSQL70(sql, procName, parameters, noMetaData, sendNow); break; default: throw new IllegalStateException("Unknown TDS version " + tdsVersion); } if (sendNow) { out.flush(); connectionLock.release(); connectionLock = null; sendFailed = false; endOfResponse = false; endOfResults = true; wait(timeOut); } else { sendFailed = false; } } catch (IOException ioe) { connection.setClosed(); throw Support.linkException( new SQLException( Messages.get( "error.generic.ioerror", ioe.getMessage()), "08S01"), ioe); } } finally { if ((sendNow || sendFailed) && connectionLock != null) { connectionLock.release(); connectionLock = null; } // Clear the in batch flag inBatch = false; } } /** * Prepares the SQL for use with Microsoft server. * * @param sql the SQL statement to prepare. * @param params the actual parameter list * @param resultSetType value of the resultSetType parameter when * the Statement was created * @param resultSetConcurrency value of the resultSetConcurrency parameter * whenthe Statement was created * @return name of the procedure or prepared statement handle. * @exception SQLException */ String microsoftPrepare(String sql, ParamInfo[] params, int resultSetType, int resultSetConcurrency) throws SQLException { int prepareSql = connection.getPrepareSql(); if (prepareSql == TEMPORARY_STORED_PROCEDURES) { StringBuffer spSql = new StringBuffer(sql.length() + 32 + params.length * 15); String procName = connection.getProcName(); spSql.append("create proc "); spSql.append(procName); spSql.append(' '); for (int i = 0; i < params.length; i++) { spSql.append("@P"); spSql.append(i); spSql.append(' '); spSql.append(params[i].sqlType); if (i + 1 < params.length) { spSql.append(','); } } // continue building proc spSql.append(" as "); spSql.append(Support.substituteParamMarkers(sql, params)); try { submitSQL(spSql.toString()); } catch (SQLException e) { if ("08S01".equals(e.getSQLState())) { // Serious error, rethrow throw e; } // This exception probably caused by failure to prepare // Return false; return null; } return procName; } else if (prepareSql == PREPARE) { boolean needCursor = resultSetType != ResultSet.TYPE_FORWARD_ONLY || resultSetConcurrency != ResultSet.CONCUR_READ_ONLY; int scrollOpt, ccOpt; ParamInfo prepParam[] = new ParamInfo[needCursor ? 6 : 4]; // Setup prepare handle param prepParam[0] = new ParamInfo(Types.INTEGER, null, ParamInfo.OUTPUT); // Setup parameter descriptor param prepParam[1] = new ParamInfo(Types.LONGVARCHAR, Support.getParameterDefinitions(params), ParamInfo.UNICODE); // Setup sql statemement param prepParam[2] = new ParamInfo(Types.LONGVARCHAR, Support.substituteParamMarkers(sql, params), ParamInfo.UNICODE); // Setup options param prepParam[3] = new ParamInfo(Types.INTEGER, new Integer(1), ParamInfo.INPUT); if (needCursor) { // Select the correct type of Server side cursor to // match the scroll and concurrency options. scrollOpt = MSCursorResultSet.getCursorScrollOpt(resultSetType, true); ccOpt = MSCursorResultSet.getCursorConcurrencyOpt(resultSetConcurrency); // Setup scroll options parameter prepParam[4] = new ParamInfo(Types.INTEGER, new Integer(scrollOpt), ParamInfo.OUTPUT); // Setup concurrency options parameter prepParam[5] = new ParamInfo(Types.INTEGER, new Integer(ccOpt), ParamInfo.OUTPUT); // TODO Implement support for preparing cursors (including SP support) // Don't forget to include scrollability and concurrency into // the prepared statement key and to remove the // sp_cursorunprepare call from MSCursorResultSet (in the // current implementation this would unprepare the statement // when the first result set is closed, but leave the statement // in the cache, causing problems on reuse). return null; } columns = null; // Will be populated if preparing a select executeSQL(null, needCursor ? "sp_cursorprepare" : "sp_prepare", prepParam, false, 0, -1, true); clearResponseQueue(); // columns will now hold meta data for select statements Integer prepareHandle = (Integer) prepParam[0].getOutValue(); if (prepareHandle != null) { return prepareHandle.toString(); } } return null; } /** * Create a light weight stored procedure on a Sybase server. * * @param sql The SQL statement to prepare. * @param params The actual parameter list * @return name of the procedure. * @throws SQLException */ synchronized String sybasePrepare(String sql, ParamInfo[] params) throws SQLException { checkOpen(); if (sql == null || sql.length() == 0) { throw new IllegalArgumentException( "sql parameter must be at least 1 character long."); } String procName = connection.getProcName(); if (procName == null || procName.length() != 11) { throw new IllegalArgumentException( "procName parameter must be 11 characters long."); } // TODO Check if output parameters are handled ok // Check no text/image parameters for (int i = 0; i < params.length; i++) { if (params[i].sqlType.equals("text") || params[i].sqlType.equals("image")) { return null; // Sadly no way } } try { out.setPacketType(SYBQUERY_PKT); out.write((byte)TDS5_DYNAMIC_TOKEN); byte buf[] = Support.encodeString(connection.getCharset(), sql); out.write((short) (buf.length + 41)); out.write((byte) 1); out.write((byte) 0); out.write((byte) 10); out.writeAscii(procName.substring(1)); out.write((short) (buf.length + 26)); out.writeAscii("create proc "); out.writeAscii(procName.substring(1)); out.writeAscii(" as "); out.write(buf); out.flush(); endOfResponse = false; clearResponseQueue(); messages.checkErrors(); } catch (IOException ioe) { connection.setClosed(); throw Support.linkException( new SQLException( Messages.get( "error.generic.ioerror", ioe.getMessage()), "08S01"), ioe); } catch (SQLException e) { if (e.getSQLState() != null && e.getSQLState().equals("08S01")) { // Serious error rethrow throw e; } // This exception probably caused by failure to prepare // Return null; return null; } return procName; } /** * Read text or image data from the server using readtext. * * @param tabName The parent table for this column. * @param colName The name of the text or image column. * @param textPtr The text pointer structure. * @param offset The starting offset in the text object. * @param length The number of bytes or characters to read. * @return A returned <code>String</code> or <code>byte[]</code>. * @throws SQLException */ Object readText(String tabName, String colName, TextPtr textPtr, int offset, int length) throws SQLException { checkOpen(); if (colName == null || colName.length() == 0 || tabName == null || tabName.length() == 0) { throw new SQLException(Messages.get("error.tdscore.badtext"), "HY000"); } if (textPtr == null) { throw new SQLException( Messages.get("error.tdscore.notextptr", tabName + "." + colName), "HY000"); } Object results = null; StringBuffer sql = new StringBuffer(256); sql.append("set textsize "); sql.append((length + 1) * 2); sql.append("\r\nreadtext "); sql.append(tabName); sql.append('.'); sql.append(colName); sql.append(" 0x"); sql.append(Support.toHex(textPtr.ptr)); sql.append(' '); sql.append(offset); sql.append(' '); sql.append(length); sql.append("\r\nset textsize 1"); if (Logger.isActive()) { Logger.println(sql.toString()); } executeSQL(sql.toString(), null, null, false, 0, -1, true); readTextMode = true; if (getMoreResults()) { if (getNextRow()) { // FIXME - this will not be valid since a Blob/Clob is returned instead of byte[]/String results = rowData[0]; } } clearResponseQueue(); messages.checkErrors(); return results; } /** * Retrieve the length of a text or image column. * * @param tabName The parent table for this column. * @param colName The name of the text or image column. * @return The length of the column as a <code>int</code>. * @throws SQLException */ int dataLength(String tabName, String colName) throws SQLException { checkOpen(); if (colName == null || colName.length() == 0 || tabName == null || tabName.length() == 0) { throw new SQLException(Messages.get("error.tdscore.badtext"), "HY000"); } Object results = null; StringBuffer sql = new StringBuffer(128); sql.append("select datalength("); sql.append(colName); sql.append(") from "); sql.append(tabName); executeSQL(sql.toString(), null, null, false, 0, -1, true); if (getMoreResults()) { if (getNextRow()) { results = rowData[0]; } } clearResponseQueue(); messages.checkErrors(); if (!(results instanceof Number)) { throw new SQLException( Messages.get("error.tdscore.badlen", tabName + "." + colName), "HY000"); } return ((Number) results).intValue(); } /** * Enlist the current connection in a distributed transaction or request the location of the * MSDTC instance controlling the server we are connected to. * * @param type set to 0 to request TM address or 1 to enlist connection * @param oleTranID the 40 OLE transaction ID * @return a <code>byte[]</code> array containing the TM address data * @throws SQLException */ synchronized byte[] enlistConnection(int type, byte[] oleTranID) throws SQLException { Semaphore mutex = null; try { try { mutex = connection.getMutex(); mutex.acquire(); } catch (InterruptedException e) { mutex = null; throw new IllegalStateException("Connection synchronization failed"); } out.setPacketType(MSDTC_PKT); out.write((short)type); switch (type) { case 0: // Get result set with location of MSTDC out.write((short)0); break; case 1: // Set OLE transaction ID if (oleTranID != null) { out.write((short)oleTranID.length); out.write(oleTranID); } else { // Delist the connection from all transactions. out.write((short)0); } break; } out.flush(); endOfResponse = false; endOfResults = true; } catch (IOException ioe) { connection.setClosed(); throw Support.linkException( new SQLException( Messages.get( "error.generic.ioerror", ioe.getMessage()), "08S01"), ioe); } finally { if (mutex != null) { mutex.release(); } } byte[] tmAddress = null; if (getMoreResults() && getNextRow()) { if (rowData.length == 1) { Object x = rowData[0]; if (x instanceof byte[]) { tmAddress = (byte[])x; } } } clearResponseQueue(); messages.checkErrors(); return tmAddress; } /** * Obtain the counts from a batch of SQL updates. * <p> * If an error occurs Sybase will continue processing a batch whilst SQL * Server will stop. This method returns the JDBC3 * <code>EXECUTE_FAILED</code> constant in the counts array when a * statement fails with an error. * * @return the update counts as an <code>int[]</code> */ int[] getBatchCounts() throws BatchUpdateException { ArrayList counts = new ArrayList(); Integer lastCount = JtdsStatement.SUCCESS_NO_INFO; BatchUpdateException batchEx = null; try { checkOpen(); while (!endOfResponse) { nextToken(); if (currentToken.isResultSet()) { throw new SQLException( Messages.get( "error.statement.batchnocount"),"07000"); } // Analyse type of end token and try to extract correct // update count when calling stored procs. switch (currentToken.token) { case TDS_DONE_TOKEN: if ((currentToken.status & DONE_ERROR) != 0) { counts.add(JtdsStatement.EXECUTE_FAILED); } else { if (currentToken.isUpdateCount()) { counts.add(new Integer(currentToken.updateCount)); } else { counts.add(lastCount); } } lastCount = JtdsStatement.SUCCESS_NO_INFO; break; case TDS_DONEINPROC_TOKEN: if ((currentToken.status & DONE_ERROR) != 0) { lastCount = JtdsStatement.EXECUTE_FAILED; } else if (currentToken.isUpdateCount()) { lastCount = new Integer(currentToken.updateCount); } break; case TDS_DONEPROC_TOKEN: if ((currentToken.status & DONE_ERROR) != 0) { counts.add(JtdsStatement.EXECUTE_FAILED); } else { counts.add(lastCount); } lastCount = JtdsStatement.SUCCESS_NO_INFO; break; } } messages.checkErrors(); } catch (SQLException e) { // A server error has been reported // return a BatchUpdateException // Create partial response count array int results[] = new int[counts.size()]; for (int i = 0; i < results.length; i++) { results[i] = ((Integer)counts.get(i)).intValue(); } batchEx = new BatchUpdateException(e.getMessage(), e.getSQLState(), e.getErrorCode(), results); throw batchEx; } finally { while (!endOfResponse) { // Flush rest of response try { nextToken(); } catch (SQLException ex) { // Chain any exceptions to the BatchUpdateException if (batchEx != null) { batchEx.setNextException(ex); } } } } // Batch completed OK return full count array int results[] = new int[counts.size()]; for (int i = 0; i < results.length; i++) { results[i] = ((Integer)counts.get(i)).intValue(); } return results; } /** * Write a TDS login packet string. Text followed by padding followed * by a byte sized length. */ private void putLoginString(String txt, int len) throws IOException { byte[] tmp = Support.encodeString(connection.getCharset(), txt); out.write(tmp, 0, len); out.write((byte) (tmp.length < len ? tmp.length : len)); } /** * TDS 4.2 Login Packet. * <P> * @param serverName The server host name. * @param user The user name. * @param password The user password. * @param charset The required server character set. * @param appName The application name. * @param progName The program name. * @param language The server language for messages * @param packetSize The required network packet size. * @throws IOException */ private void send42LoginPkt(final String serverName, final String user, final String password, final String charset, final String appName, final String progName, final String language, final int packetSize) throws IOException { final byte[] empty = new byte[0]; out.setPacketType(LOGIN_PKT); putLoginString(getHostName(), 30); // Host name putLoginString(user, 30); // user name putLoginString(password, 30); // password putLoginString("00000123", 30); // hostproc (offset 93 0x5d) out.write((byte) 3); // type of int2 out.write((byte) 1); // type of int4 out.write((byte) 6); // type of char out.write((byte) 10);// type of flt out.write((byte) 9); // type of date out.write((byte) 1); // notify of use db out.write((byte) 1); // disallow dump/load and bulk insert out.write((byte) 0); // sql interface type out.write((byte) 0); // type of network connection out.write(empty, 0, 7); putLoginString(appName, 30); // appname putLoginString(serverName, 30); // server name out.write((byte)0); // remote passwords out.write((byte)password.length()); byte[] tmp = Support.encodeString(connection.getCharset(), password); out.write(tmp, 0, 253); out.write((byte) (tmp.length + 2)); out.write((byte) 4); // tds version out.write((byte) 2); out.write((byte) 0); out.write((byte) 0); putLoginString(progName, 10); // prog name out.write((byte) 6); // prog version out.write((byte) 0); out.write((byte) 0); out.write((byte) 0); out.write((byte) 0); // auto convert short out.write((byte) 0x0D); // type of flt4 out.write((byte) 0x11); // type of date4 putLoginString(language, 30); // language out.write((byte) 1); // notify on lang change out.write((short) 0); // security label hierachy out.write((byte) 0); // security encrypted out.write(empty, 0, 8); // security components out.write((short) 0); // security spare putLoginString(charset, 30); // Character set out.write((byte) 1); // notify on charset change putLoginString(String.valueOf(packetSize), 6); // length of tds packets out.write(empty, 0, 8); // pad out to a longword out.flush(); // Send the packet endOfResponse = false; } /** * TDS 5.0 Login Packet. * <P> * @param serverName The server host name. * @param user The user name. * @param password The user password. * @param charset The required server character set. * @param appName The application name. * @param progName The program name. * @param language The server language for messages * @param packetSize The required network packet size. * @throws IOException */ private void send50LoginPkt(final String serverName, final String user, final String password, final String charset, final String appName, final String progName, final String language, final int packetSize) throws IOException { final byte[] empty = new byte[0]; out.setPacketType(LOGIN_PKT); putLoginString(getHostName(), 30); // Host name putLoginString(user, 30); // user name putLoginString(password, 30); // password putLoginString("00000123", 30); // hostproc (offset 93 0x5d) out.write((byte) 3); // type of int2 out.write((byte) 1); // type of int4 out.write((byte) 6); // type of char out.write((byte) 10);// type of flt out.write((byte) 9); // type of date out.write((byte) 1); // notify of use db out.write((byte) 1); // disallow dump/load and bulk insert out.write((byte) 0); // sql interface type out.write((byte) 0); // type of network connection out.write(empty, 0, 7); putLoginString(appName, 30); // appname putLoginString(serverName, 30); // server name out.write((byte)0); // remote passwords out.write((byte)password.length()); byte[] tmp = Support.encodeString(connection.getCharset(), password); out.write(tmp, 0, 253); out.write((byte) (tmp.length + 2)); out.write((byte) 5); // tds version out.write((byte) 0); out.write((byte) 0); out.write((byte) 0); putLoginString(progName, 10); // prog name out.write((byte) 5); // prog version out.write((byte) 0); out.write((byte) 0); out.write((byte) 0); out.write((byte) 0); // auto convert short out.write((byte) 0x0D); // type of flt4 out.write((byte) 0x11); // type of date4 putLoginString(language, 30); // language out.write((byte) 1); // notify on lang change out.write((short) 0); // security label hierachy out.write((byte) 0); // security encrypted out.write(empty, 0, 8); // security components out.write((short) 0); // security spare putLoginString(charset, 30); // Character set out.write((byte) 1); // notify on charset change putLoginString(String.valueOf(packetSize), 6); // length of tds packets out.write(empty, 0, 4); // Send capability request byte capString[] = { // Request capabilities (byte)0x01,(byte)0x0A,(byte)0x03,(byte)0x84,(byte)0x0E,(byte)0xEF, (byte)0x65,(byte)0x7F,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xD6, // Response capabilities (byte)0x02,(byte)0x0A,(byte)0x00,(byte)0x02,(byte)0x00,(byte)0x07, (byte)0x9E,(byte)0x06,(byte)0x48,(byte)0x00,(byte)0x00,(byte)0x00 }; out.write(TDS_CAP_TOKEN); out.write((short)capString.length); out.write(capString); out.flush(); // Send the packet endOfResponse = false; } /** * Send a TDS 7 login packet. * <p> * This method incorporates the Windows single sign on code contributed by * Magendran Sathaiah. To invoke single sign on just leave the user name * blank or null. NB. This can only work if the driver is being executed on * a Windows PC and <code>ntlmauth.dll</code> is on the path. * * @param serverName server host name * @param database required database * @param user user name * @param password user password * @param domain Windows NT domain (or <code>null</code>) * @param appName application name * @param progName program name * @param language server language for messages * @param macAddress client network MAC address * @param netPacketSize TDS packet size to use * @throws IOException if an I/O error occurs */ private void sendMSLoginPkt(final String serverName, final String database, final String user, final String password, final String domain, final String appName, final String progName, final String language, final String macAddress, final int netPacketSize) throws IOException, SQLException { final byte[] empty = new byte[0]; final String clientName = getHostName(); boolean ntlmAuth = false; byte[] ntlmMessage = null; if (user == null || user.length() == 0) { // See if executing on a Windows platform and if so try and // use the single sign on native library. if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { ntlmAuthSSO = true; ntlmAuth = true; } else { throw new SQLException(Messages.get("error.connection.sso"), "08001"); } } else if (domain != null && domain.length() > 0) { // Assume we want to use Windows authentication with // supplied user and password. ntlmAuth = true; } if (ntlmAuthSSO) { try { // Create the NTLM request block using the native library sspiJNIClient = SSPIJNIClient.getInstance(); ntlmMessage = sspiJNIClient.invokePrepareSSORequest(); } catch (Exception e) { throw new IOException("SSO Failed: " + e.getMessage()); } } //mdb:begin-change short packSize = (short) (86 + 2 * (clientName.length() + appName.length() + serverName.length() + progName.length() + database.length() + language.length())); final short authLen; //NOTE(mdb): ntlm includes auth block; sql auth includes uname and pwd. if (ntlmAuth) { if (ntlmAuthSSO && ntlmMessage != null) { authLen = (short) ntlmMessage.length; } else { authLen = (short) (32 + domain.length()); } packSize += authLen; } else { authLen = 0; packSize += (2 * (user.length() + password.length())); } //mdb:end-change out.setPacketType(MSLOGIN_PKT); out.write((int)packSize); // TDS version if (tdsVersion == Driver.TDS70) { out.write((int)0x70000000); } else { out.write((int)0x71000001); } // Network Packet size requested by client out.write((int)netPacketSize); // Program version? out.write((int)7); // Process ID out.write((int)123); // Connection ID out.write((int)0); byte flags = 0; flags |= 0x80; // enable warning messages if SET LANGUAGE issued flags |= 0x40; // change to initial database must succeed flags |= 0x20; // enable warning messages if USE <database> issued out.write(flags); //mdb: this byte controls what kind of auth we do. flags = 0x03; // ODBC (JDBC) driver if (ntlmAuth) flags |= 0x80; // Use NT authentication out.write(flags); out.write((byte)0); // SQL type flag out.write((byte)0); // Reserved flag // TODO Set Timezone and collation? out.write(empty, 0, 4); // Time Zone out.write(empty, 0, 4); // Collation // Pack up value lengths, positions. short curPos = 86; // Hostname out.write((short)curPos); out.write((short) clientName.length()); curPos += clientName.length() * 2; //mdb: NTLM doesn't send username and password... if (!ntlmAuth) { // Username out.write((short)curPos); out.write((short) user.length()); curPos += user.length() * 2; // Password out.write((short)curPos); out.write((short) password.length()); curPos += password.length() * 2; } else { out.write((short)curPos); out.write((short) 0); out.write((short)curPos); out.write((short) 0); } // App name out.write((short)curPos); out.write((short) appName.length()); curPos += appName.length() * 2; // Server name out.write((short)curPos); out.write((short) serverName.length()); curPos += serverName.length() * 2; // Unknown out.write((short) 0); out.write((short) 0); // Program name out.write((short)curPos); out.write((short) progName.length()); curPos += progName.length() * 2; // Server language out.write((short)curPos); out.write((short) language.length()); curPos += language.length() * 2; // Database out.write((short)curPos); out.write((short) database.length()); curPos += database.length() * 2; // MAC address out.write(getMACAddress(macAddress)); //mdb: location of ntlm auth block. note that for sql auth, authLen==0. out.write((short)curPos); out.write((short)authLen); //"next position" (same as total packet size) out.write((int)packSize); out.write(clientName); // Pack up the login values. //mdb: for ntlm auth, uname and pwd aren't sent up... if (!ntlmAuth) { final String scrambledPw = tds7CryptPass(password); out.write(user); out.write(scrambledPw); } out.write(appName); out.write(serverName); out.write(progName); out.write(language); out.write(database); //mdb: add the ntlm auth info... if (ntlmAuth) { if (ntlmAuthSSO) { // Use the NTLM message generated by the native library out.write(ntlmMessage); } else { // host and domain name are _narrow_ strings. final byte[] domainBytes = domain.getBytes("UTF8"); //byte[] hostBytes = localhostname.getBytes("UTF8"); final byte[] header = {0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00}; out.write(header); //header is ascii "NTLMSSP\0" out.write((int)1); //sequence number = 1 out.write((int)0xb201); //flags (???) //domain info out.write((short) domainBytes.length); out.write((short) domainBytes.length); out.write((int)32); //offset, relative to start of auth block. //host info //NOTE(mdb): not sending host info; hope this is ok! out.write((short) 0); out.write((short) 0); out.write((int)32); //offset, relative to start of auth block. // add the variable length data at the end... out.write(domainBytes); } } out.flush(); // Send the packet endOfResponse = false; } /** * Send the response to the NTLM authentication challenge. * @param nonce The secret to hash with password. * @param user The user name. * @param password The user password. * @param domain The Windows NT Dommain. * @throws java.io.IOException */ private void sendNtlmChallengeResponse(final byte[] nonce, final String user, final String password, final String domain) throws java.io.IOException { out.setPacketType(NTLMAUTH_PKT); // Prepare and Set NTLM Type 2 message appropriately if (ntlmAuthSSO) { byte[] ntlmMessage = currentToken.ntlmMessage; try { // Create the challenge response using the native library ntlmMessage = sspiJNIClient.invokePrepareSSOSubmit(ntlmMessage); } catch (Exception e) { throw new IOException("SSO Failed: " + e.getMessage()); } out.write(ntlmMessage); } else { // host and domain name are _narrow_ strings. //byte[] domainBytes = domain.getBytes("UTF8"); //byte[] user = user.getBytes("UTF8"); final byte[] header = {0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00}; out.write(header); //header is ascii "NTLMSSP\0" out.write((int)3); //sequence number = 3 final int domainLenInBytes = domain.length() * 2; final int userLenInBytes = user.length() * 2; //mdb: not sending hostname; I hope this is ok! final int hostLenInBytes = 0; //localhostname.length()*2; int pos = 64 + domainLenInBytes + userLenInBytes + hostLenInBytes; // lan man response: length and offset out.write((short)24); out.write((short)24); out.write((int)pos); pos += 24; // nt response: length and offset out.write((short)24); out.write((short)24); out.write((int)pos); pos = 64; //domain out.write((short) domainLenInBytes); out.write((short) domainLenInBytes); out.write((int)pos); pos += domainLenInBytes; //user out.write((short) userLenInBytes); out.write((short) userLenInBytes); out.write((int)pos); pos += userLenInBytes; //local hostname out.write((short) hostLenInBytes); out.write((short) hostLenInBytes); out.write((int)pos); pos += hostLenInBytes; //unknown out.write((short) 0); out.write((short) 0); out.write((int)pos); //flags out.write((int)0x8201); //flags (???) //variable length stuff... out.write(domain); out.write(user); //Not sending hostname...I hope this is OK! //comm.appendChars(localhostname); //the response to the challenge... final byte[] lmAnswer = NtlmAuth.answerLmChallenge(password, nonce); final byte[] ntAnswer = NtlmAuth.answerNtChallenge(password, nonce); out.write(lmAnswer); out.write(ntAnswer); } out.flush(); } /** * Read the next TDS token from the response stream. * * @throws SQLException if an I/O or protocol error occurs */ private void nextToken() throws SQLException { checkOpen(); if (endOfResponse) { currentToken.token = TDS_DONE_TOKEN; currentToken.status = 0; return; } try { currentToken.token = (byte)in.read(); switch (currentToken.token) { case TDS5_PARAMFMT2_TOKEN: tds5ParamFmt2Token(); break; case TDS_LANG_TOKEN: tdsInvalidToken(); break; case TDS5_WIDE_RESULT: tds5WideResultToken(); break; case TDS_CLOSE_TOKEN: tdsInvalidToken(); break; case TDS_RETURNSTATUS_TOKEN: tdsReturnStatusToken(); break; case TDS_PROCID: tdsProcIdToken(); break; case TDS_OFFSETS_TOKEN: tdsOffsetsToken(); break; case TDS7_RESULT_TOKEN: tds7ResultToken(); break; case TDS7_COMP_RESULT_TOKEN: tdsInvalidToken(); break; case TDS_COLNAME_TOKEN: tds4ColNamesToken(); break; case TDS_COLFMT_TOKEN: tds4ColFormatToken(); break; case TDS_TABNAME_TOKEN: tdsTableNameToken(); break; case TDS_COLINFO_TOKEN: tdsColumnInfoToken(); break; case TDS_COMP_NAMES_TOKEN: tdsInvalidToken(); break; case TDS_COMP_RESULT_TOKEN: tdsInvalidToken(); break; case TDS_ORDER_TOKEN: tdsOrderByToken(); break; case TDS_ERROR_TOKEN: case TDS_INFO_TOKEN: tdsErrorToken(); break; case TDS_PARAM_TOKEN: tdsOutputParamToken(); break; case TDS_LOGINACK_TOKEN: tdsLoginAckToken(); break; case TDS_CONTROL_TOKEN: tdsControlToken(); break; case TDS_ROW_TOKEN: tdsRowToken(); break; case TDS_ALTROW: tdsInvalidToken(); break; case TDS5_PARAMS_TOKEN: tds5ParamsToken(); break; case TDS_CAP_TOKEN: tdsCapabilityToken(); break; case TDS_ENVCHANGE_TOKEN: tdsEnvChangeToken(); break; case TDS_MSG50_TOKEN: tds5ErrorToken(); break; case TDS5_DYNAMIC_TOKEN: tds5DynamicToken(); break; case TDS5_PARAMFMT_TOKEN: tds5ParamFmtToken(); break; case TDS_AUTH_TOKEN: tdsNtlmAuthToken(); break; case TDS_RESULT_TOKEN: tds5ResultToken(); break; case TDS_DONE_TOKEN: case TDS_DONEPROC_TOKEN: case TDS_DONEINPROC_TOKEN: tdsDoneToken(); break; default: throw new ProtocolException( "Invalid packet type 0x" + Integer.toHexString((int) currentToken.token & 0xFF)); } } catch (IOException ioe) { connection.setClosed(); throw Support.linkException( new SQLException( Messages.get( "error.generic.ioerror", ioe.getMessage()), "08S01"), ioe); } catch (ProtocolException pe) { connection.setClosed(); throw Support.linkException( new SQLException( Messages.get( "error.generic.tdserror", pe.getMessage()), "08S01"), pe); } } /** * Report unsupported TDS token in input stream. * * @throws IOException */ private void tdsInvalidToken() throws IOException, ProtocolException { in.skip(in.readShort()); throw new ProtocolException("Unsupported TDS token: 0x" + Integer.toHexString((int) currentToken.token & 0xFF)); } /** * Process TDS 5 Sybase 12+ Dynamic results parameter descriptor. * <p>When returning output parameters this token will be followed * by a TDS5_PARAMS_TOKEN with the actual data. * @throws IOException * @throws ProtocolException */ private void tds5ParamFmt2Token() throws IOException, ProtocolException { in.readInt(); // Packet length int paramCnt = in.readShort(); ColInfo[] params = new ColInfo[paramCnt]; for (int i = 0; i < paramCnt; i++) { // Get the parameter details using the // ColInfo class as the server format is the same. ColInfo col = new ColInfo(); int colNameLen = in.read(); col.realName = in.readNonUnicodeString(colNameLen); int column_flags = in.readInt(); /* Flags */ col.isCaseSensitive = false; col.nullable = ((column_flags & 0x20) != 0)? ResultSetMetaData.columnNullable: ResultSetMetaData.columnNoNulls; col.isWriteable = (column_flags & 0x10) != 0; col.isIdentity = (column_flags & 0x40) != 0; col.isKey = (column_flags & 0x02) != 0; col.isHidden = (column_flags & 0x01) != 0; col.userType = in.readInt(); TdsData.readType(in, col); // Skip locale information in.skip(1); params[i] = col; } currentToken.previousToken = TDS5_PARAMFMT2_TOKEN; currentToken.dynamParamInfo = params; currentToken.dynamParamData = new Object[paramCnt]; } /** * Process Sybase 12+ wide result token which provides enhanced * column meta data. * * @throws IOException */ private void tds5WideResultToken() throws IOException, ProtocolException { in.readInt(); // Packet length int colCnt = in.readShort(); this.columns = new ColInfo[colCnt]; this.rowData = new Object[colCnt]; this.tables = null; for (int colNum = 0; colNum < colCnt; ++colNum) { ColInfo col = new ColInfo(); // Get the alias name int nameLen = in.read(); col.name = in.readNonUnicodeString(nameLen); // Get the catalog name nameLen = in.read(); col.catalog = in.readNonUnicodeString(nameLen); // Get the schema name nameLen = in.read(); col.schema = in.readNonUnicodeString(nameLen); // Get the table name nameLen = in.read(); col.tableName = in.readNonUnicodeString(nameLen); // Get the column name nameLen = in.read(); col.realName = in.readNonUnicodeString(nameLen); if (col.name == null || col.name.length() == 0) { col.name = col.realName; } int column_flags = in.readInt(); /* Flags */ col.isCaseSensitive = false; col.nullable = ((column_flags & 0x20) != 0)? ResultSetMetaData.columnNullable: ResultSetMetaData.columnNoNulls; col.isWriteable = (column_flags & 0x10) != 0; col.isIdentity = (column_flags & 0x40) != 0; col.isKey = (column_flags & 0x02) != 0; col.isHidden = (column_flags & 0x01) != 0; col.userType = in.readInt(); TdsData.readType(in, col); // Skip locale information in.skip(1); columns[colNum] = col; } endOfResults = false; } /** * Process stored procedure return status token. * * @throws IOException */ private void tdsReturnStatusToken() throws IOException, SQLException { returnStatus = new Integer(in.readInt()); if (this.returnParam != null) { returnParam.setOutValue(Support.convert(this.connection, returnStatus, returnParam.jdbcType, connection.getCharset())); } } /** * Process procedure ID token. * <p> * Used by DBLIB to obtain the object id of a stored procedure. */ private void tdsProcIdToken() throws IOException { in.skip(8); } /** * Process offsets token. * <p> * Used by DBLIB to return the offset of various keywords in a statement. * This saves the client from having to parse a SQL statement. Enabled with * <code>&quot;set offsets from on&quot;</code>. */ private void tdsOffsetsToken() throws IOException { /*int keyword =*/ in.read(); /*int unknown =*/ in.read(); /*int offset =*/ in.readShort(); } /** * Process a TDS 7.0 result set token. * * @throws IOException * @throws ProtocolException */ private void tds7ResultToken() throws IOException, ProtocolException, SQLException { endOfResults = false; int colCnt = in.readShort(); if (colCnt < 0) { // Short packet returned by TDS8 when the column meta data is // supressed on cursor fetch etc. // NB. With TDS7 no result set packet is returned at all. return; } this.columns = new ColInfo[colCnt]; this.rowData = new Object[colCnt]; this.tables = null; for (int i = 0; i < colCnt; i++) { ColInfo col = new ColInfo(); col.userType = in.readShort(); int flags = in.readShort(); col.nullable = ((flags & 0x01) != 0) ? ResultSetMetaData.columnNullable : ResultSetMetaData.columnNoNulls; col.isCaseSensitive = (flags & 0X02) != 0; col.isIdentity = (flags & 0x10) != 0; col.isWriteable = (flags & 0x0C) != 0; TdsData.readType(in, col); // Set the charsetInfo field of col if (tdsVersion >= Driver.TDS80 && col.collation != null) { TdsData.setColumnCharset(col, connection.getCollation(), connection.getCharsetInfo()); } int clen = in.read(); col.realName = in.readUnicodeString(clen); col.name = col.realName; this.columns[i] = col; } } /** * Process a TDS 4.2 column names token. * <p> * Note: Will be followed by a COL_FMT token. * * @throws IOException */ private void tds4ColNamesToken() throws IOException { ArrayList colList = new ArrayList(); final int pktLen = in.readShort(); this.tables = null; int bytesRead = 0; while (bytesRead < pktLen) { ColInfo col = new ColInfo(); int nameLen = in.read(); String name = in.readNonUnicodeString(nameLen); // FIXME This will not work for multi-byte charsets bytesRead = bytesRead + 1 + nameLen; col.realName = name; col.name = name; colList.add(col); } int colCnt = colList.size(); this.columns = (ColInfo[]) colList.toArray(new ColInfo[colCnt]); this.rowData = new Object[colCnt]; } /** * Process a TDS 4.2 column format token. * * @throws IOException * @throws ProtocolException */ private void tds4ColFormatToken() throws IOException, ProtocolException { final int pktLen = in.readShort(); int bytesRead = 0; int numColumns = 0; while (bytesRead < pktLen) { if (numColumns > columns.length) { throw new ProtocolException("Too many columns in TDS_COL_FMT packet"); } ColInfo col = columns[numColumns]; if (serverType == Driver.SQLSERVER) { col.userType = in.readShort(); int flags = in.readShort(); col.nullable = ((flags & 0x01) != 0)? ResultSetMetaData.columnNullable: ResultSetMetaData.columnNoNulls; col.isCaseSensitive = (flags & 0x02) != 0; col.isWriteable = (flags & 0x0C) != 0; col.isIdentity = (flags & 0x10) != 0; } else { // Sybase does not send column flags col.isCaseSensitive = false; col.isWriteable = true; if (col.nullable == ResultSetMetaData.columnNoNulls) { col.nullable = ResultSetMetaData.columnNullableUnknown; } col.userType = in.readInt(); } bytesRead += 4; bytesRead += TdsData.readType(in, col); numColumns++; } if (numColumns != columns.length) { throw new ProtocolException("Too few columns in TDS_COL_FMT packet"); } endOfResults = false; } /** * Process a table name token. * <p> Sent by select for browse or cursor functions. * * @throws IOException */ private void tdsTableNameToken() throws IOException, ProtocolException { final int pktLen = in.readShort(); int bytesRead = 0; ArrayList tableList = new ArrayList(); while (bytesRead < pktLen) { int nameLen; String tabName; TableMetaData table; if (tdsVersion >= Driver.TDS81) { // TDS8.1 supplies the database.owner.table as three separate // components which allows us to have names with embedded // periods. // Can't think why anyone would want that! table = new TableMetaData(); bytesRead++; switch (in.read()) { case 3: nameLen = in.readShort(); bytesRead += nameLen * 2 + 2; table.catalog = in.readUnicodeString(nameLen); case 2: nameLen = in.readShort(); bytesRead += nameLen * 2 + 2; table.schema = in.readUnicodeString(nameLen); case 1: nameLen = in.readShort(); bytesRead += nameLen * 2 + 2; table.name = in.readUnicodeString(nameLen); case 0: break; default: throw new ProtocolException("Invalid table TAB_NAME_TOKEN"); } } else { if (tdsVersion >= Driver.TDS70) { nameLen = in.readShort(); bytesRead += nameLen * 2 + 2; tabName = in.readUnicodeString(nameLen); } else { // TDS 4.2 or TDS 5.0 nameLen = in.read(); bytesRead++; if (nameLen == 0) { break; // Sybase/SQL 6.5 use a zero length name to terminate list } tabName = in.readString(nameLen); // FIXME This will not work for multi-byte charsets bytesRead += nameLen; } table = new TableMetaData(); // tabName can be a fully qualified name int dotPos = tabName.lastIndexOf('.'); if (dotPos > 0) { table.name = tabName.substring(dotPos + 1); int nextPos = tabName.lastIndexOf('.', dotPos-1); if (nextPos + 1 < dotPos) { table.schema = tabName.substring(nextPos + 1, dotPos); } dotPos = nextPos; nextPos = tabName.lastIndexOf('.', dotPos-1); if (nextPos + 1 < dotPos) { table.catalog = tabName.substring(nextPos + 1, dotPos); } } else { table.name = tabName; } } tableList.add(table); } if (tableList.size() > 0) { this.tables = (TableMetaData[]) tableList.toArray(new TableMetaData[tableList.size()]); } } /** * Process a column infomation token. * <p>Sent by select for browse or cursor functions. * @throws IOException * @throws ProtocolException */ private void tdsColumnInfoToken() throws IOException, ProtocolException { final int pktLen = in.readShort(); int bytesRead = 0; int columnIndex = 0; // In some cases (e.g. if the user calls 'CREATE CURSOR', the // TDS_TABNAME packet seems to be missing. Weird. if (tables == null) { in.skip(pktLen); } else { while (bytesRead < pktLen) { // Seems like all columns are always returned in the COL_INFO // packet and there might be more than 255 columns, so we'll // just increment a counter instead. // Ignore the column index. in.read(); if (columnIndex >= columns.length) { throw new ProtocolException("Column index " + (columnIndex + 1) + " invalid in TDS_COLINFO packet"); } ColInfo col = columns[columnIndex++]; int tableIndex = in.read(); if (tableIndex > tables.length) { throw new ProtocolException("Table index " + tableIndex + " invalid in TDS_COLINFO packet"); } byte flags = (byte)in.read(); // flags bytesRead += 3; if (tableIndex != 0) { TableMetaData table = tables[tableIndex-1]; col.catalog = table.catalog; col.schema = table.schema; col.tableName = table.name; } col.isKey = (flags & 0x08) != 0; col.isHidden = (flags & 0x10) != 0; // If bit 5 is set, we have a column name if ((flags & 0x20) != 0) { final int nameLen = in.read(); bytesRead += 1; final String colName = in.readString(nameLen); // FIXME This won't work with multi-byte charsets bytesRead += (tdsVersion >= Driver.TDS70)? nameLen * 2: nameLen; col.realName = colName; } } } } /** * Process an order by token. * <p>Sent to describe columns in an order by clause. * @throws IOException */ private void tdsOrderByToken() throws IOException { // Skip this packet type int pktLen = in.readShort(); in.skip(pktLen); } /** * Process a TD4/TDS7 error or informational message. * * @throws IOException */ private void tdsErrorToken() throws IOException { int pktLen = in.readShort(); // Packet length int sizeSoFar = 6; int number = in.readInt(); int state = in.read(); int severity = in.read(); int msgLen = in.readShort(); String message = in.readString(msgLen); sizeSoFar += 2 + ((tdsVersion >= Driver.TDS70)? msgLen * 2: msgLen); final int srvNameLen = in.read(); String server = in.readString(srvNameLen); sizeSoFar += 1 + ((tdsVersion >= Driver.TDS70)? srvNameLen * 2: srvNameLen); final int procNameLen = in.read(); String procName = in.readString(procNameLen); sizeSoFar += 1 + ((tdsVersion >= Driver.TDS70)? procNameLen * 2: procNameLen); int line = in.readShort(); sizeSoFar += 2; // FIXME This won't work with multi-byte charsets // Skip any EED information to read rest of packet if (pktLen - sizeSoFar > 0) in.skip(pktLen - sizeSoFar); if (currentToken.token == TDS_ERROR_TOKEN) { if (severity < 10) { severity = 11; // Ensure treated as error } if (severity >= 20) { // A fatal error has occured, the connection will be closed by // the server immediately after the last TDS_DONE packet fatalError = true; } } else { if (severity > 9) { severity = 9; // Ensure treated as warning } } messages.addDiagnostic(number, state, severity, message, server, procName, line); } /** * Process output parameters. * * @throws IOException * @throws ProtocolException */ private void tdsOutputParamToken() throws IOException, ProtocolException, SQLException { in.readShort(); // Packet length in.skipString(in.read()); // Column Name in.skip(5); ColInfo col = new ColInfo(); TdsData.readType(in, col); // Set the charsetInfo field of col if (tdsVersion >= Driver.TDS80 && col.collation != null) { TdsData.setColumnCharset(col, connection.getCollation(), connection.getCharsetInfo()); } Object value = TdsData.readData(connection, in, col, false); if (parameters != null) { if (tdsVersion >= Driver.TDS80 && returnParam != null && !returnParam.isSetOut) { // TDS 8 Allows function return values of types other than int if (value != null) { parameters[nextParam].setOutValue( Support.convert(connection, value, parameters[nextParam].jdbcType, connection.getCharset())); parameters[nextParam].collation = col.collation; parameters[nextParam].charsetInfo = col.charsetInfo; } else { parameters[nextParam].setOutValue(null); } } else { // Look for next output parameter in list while (++nextParam < parameters.length) { if (parameters[nextParam].isOutput) { if (value != null) { parameters[nextParam].setOutValue( Support.convert(connection, value, parameters[nextParam].jdbcType, connection.getCharset())); parameters[nextParam].collation = col.collation; parameters[nextParam].charsetInfo = col.charsetInfo; } else { parameters[nextParam].setOutValue(null); } break; } } } } } /** * Process a login acknowledgement packet. * * @throws IOException */ private void tdsLoginAckToken() throws IOException { String product; int major, minor, build = 0; in.readShort(); // Packet length int ack = in.read(); // Ack TDS 5 = 5 for OK 6 for fail, 1/0 for the others // Update the TDS protocol version in this TdsCore and in the Socket. // The Connection will update itself immediately after this call. // As for other objects containing a TDS version value, there are none // at this point (we're just constructing the Connection). tdsVersion = TdsData.getTdsVersion(((int) in.read() << 24) | ((int) in.read() << 16) | ((int) in.read() << 8) | (int) in.read()); socket.setTdsVersion(tdsVersion); product = in.readString(in.read()); if (tdsVersion >= Driver.TDS70) { major = in.read(); minor = in.read(); build = in.read() << 8; build += in.read(); } else { if (product.toLowerCase().startsWith("microsoft")) { in.skip(1); major = in.read(); minor = in.read(); } else { major = in.read(); minor = in.read() * 10; minor += in.read(); } in.skip(1); } if (product.length() > 1 && -1 != product.indexOf('\0')) { product = product.substring(0, product.indexOf('\0')); } connection.setDBServerInfo(product, major, minor, build); if (tdsVersion == Driver.TDS50 && ack != 5) { // Login rejected by server create SQLException messages.addDiagnostic(4002, 0, 14, "Login failed", "", "", 0); currentToken.token = TDS_ERROR_TOKEN; } } /** * Process a control token (function unknown). * * @throws IOException */ private void tdsControlToken() throws IOException { int pktLen = in.readShort(); in.skip(pktLen); } /** * Process a row data token. * * @throws IOException * @throws ProtocolException */ private void tdsRowToken() throws IOException, ProtocolException { for (int i = 0; i < columns.length; i++) { rowData[i] = TdsData.readData(connection, in, columns[i], readTextMode); } endOfResults = false; readTextMode = false; } /** * Process TDS 5.0 Params Token. * Stored procedure output parameters or data returned in parameter format * after a TDS Dynamic packet or as extended error information. * <p>The type of the preceding token is inspected to determine if this packet * contains output parameter result data. A TDS5_PARAMFMT2_TOKEN is sent before * this one in Sybase 12 to introduce output parameter results. * A TDS5_PARAMFMT_TOKEN is sent before this one to introduce extended error * information. * * @throws IOException */ private void tds5ParamsToken() throws IOException, ProtocolException, SQLException { if (currentToken.dynamParamInfo == null) { throw new ProtocolException( "TDS 5 Param results token (0xD7) not preceded by param format (0xEC or 0X20)."); } for (int i = 0; i < currentToken.dynamParamData.length; i++) { currentToken.dynamParamData[i] = TdsData.readData(connection, in, currentToken.dynamParamInfo[i], false); if (parameters != null) { // Sybase 12+ this token used to set output parameter results while (++nextParam < parameters.length) { if (parameters[nextParam].isOutput) { Object value = currentToken.dynamParamData[i]; if (value != null) { parameters[nextParam].setOutValue( Support.convert(connection, value, parameters[nextParam].jdbcType, connection.getCharset())); } else { parameters[nextParam].setOutValue(null); } break; } } } } } /** * Process a TDS 5.0 capability token. * <p> * Sent after login to describe the server's capabilities. * * @throws IOException */ private void tdsCapabilityToken() throws IOException, ProtocolException { in.readShort(); // Packet length if (in.read() != 1) { throw new ProtocolException("TDS_CAPABILITY: expected request string"); } int capLen = in.read(); if (capLen != 10) { throw new ProtocolException("TDS_CAPABILITY: byte count not 10"); } byte capRequest[] = new byte[10]; in.read(capRequest); if (in.read() != 2) { throw new ProtocolException("TDS_CAPABILITY: expected response string"); } capLen = in.read(); if (capLen != 10) { throw new ProtocolException("TDS_CAPABILITY: byte count not 10"); } byte capResponse[] = new byte[10]; in.read(capResponse); // jTDS sends 01 0A 03 84 0E EF 65 7F FF FF FF D6 // Sybase 11.92 01 0A 00 00 00 23 61 41 CF FF FF C6 // Sybase 12.52 01 0A 03 84 0A E3 61 41 FF FF FF C6 // JTDS sends 02 0A 00 02 00 07 9E 06 48 00 00 00 // Sybase 11.92 02 0A 00 00 00 00 00 06 00 00 00 00 // Sybase 12.52 02 0A 00 00 00 00 00 06 00 00 00 00 // Now set the correct attributes for this connection. // See the CT_LIB documentation for details on the bit // positions. int capMask = 0; if ((capRequest[6] & 0x30) == 0x30) { capMask |= SYB_LONGDATA; } if ((capRequest[0] & 0x03) == 0x03) { capMask |= SYB_DATETIME; } if ((capRequest[2] & 0x02) == 0x02) { capMask |= SYB_EXTCOLINFO; } if ((capRequest[3] & 0x04) == 0x04) { capMask |= SYB_BITNULL; } if ((capRequest[1] & 0x80) == 0x80) { capMask |= SYB_UNICODE; } connection.setSybaseInfo(capMask); } /** * Process an environment change packet. * * @throws IOException * @throws SQLException */ private void tdsEnvChangeToken() throws IOException, SQLException { int len = in.readShort(); int type = in.read(); switch (type) { case TDS_ENV_DATABASE: { int clen = in.read(); final String newDb = in.readString(clen); clen = in.read(); final String oldDb = in.readString(clen); connection.setDatabase(newDb, oldDb); break; } case TDS_ENV_LANG: { int clen = in.read(); String language = in.readString(clen); clen = in.read(); String oldLang = in.readString(clen); if (Logger.isActive()) { Logger.println("Language changed from " + oldLang + " to " + language); } break; } case TDS_ENV_CHARSET: { final int clen = in.read(); final String charset = in.readString(clen); if (tdsVersion >= Driver.TDS70) { in.skip(len - 2 - clen * 2); } else { in.skip(len - 2 - clen); } connection.setServerCharset(charset); break; } case TDS_ENV_PACKSIZE: { final int blocksize; final int clen = in.read(); blocksize = Integer.parseInt(in.readString(clen)); if (tdsVersion >= Driver.TDS70) { in.skip(len - 2 - clen * 2); } else { in.skip(len - 2 - clen); } this.connection.setNetPacketSize(blocksize); out.setBufferSize(blocksize); if (Logger.isActive()) { Logger.println("Changed blocksize to " + blocksize); } } break; case TDS_ENV_LCID: // Only sent by TDS 7 // In TDS 8 replaced by column specific collation info. // TODO Make use of this for character set conversions? in.skip(len - 1); break; case TDS_ENV_SQLCOLLATION: { int clen = in.read(); byte collation[] = new byte[5]; if (clen == 5) { in.read(collation); connection.setCollation(collation); if (Logger.isActive()) { Logger.println("Collation changed to 0x" + Support.toHex(collation)); } } else { in.skip(clen); } clen = in.read(); in.skip(clen); break; } default: { if (Logger.isActive()) { Logger.println("Unknown environment change type 0x" + Integer.toHexString(type)); } in.skip(len - 1); break; } } } /** * Process a TDS 5 error or informational message. * * @throws IOException */ private void tds5ErrorToken() throws IOException { int pktLen = in.readShort(); // Packet length int sizeSoFar = 6; int number = in.readInt(); int state = in.read(); int severity = in.read(); // Discard text state int stateLen = in.read(); in.readNonUnicodeString(stateLen); in.read(); // == 1 if extended error data follows // Discard status and transaction state in.readShort(); sizeSoFar += 4 + stateLen; int msgLen = in.readShort(); String message = in.readNonUnicodeString(msgLen); sizeSoFar += 2 + msgLen; final int srvNameLen = in.read(); String server = in.readNonUnicodeString(srvNameLen); sizeSoFar += 1 + srvNameLen; final int procNameLen = in.read(); String procName = in.readNonUnicodeString(procNameLen); sizeSoFar += 1 + procNameLen; int line = in.readShort(); sizeSoFar += 2; // FIXME This won't work with multi-byte charsets // Skip any EED information to read rest of packet if (pktLen - sizeSoFar > 0) in.skip(pktLen - sizeSoFar); if (severity > 10) { messages.addDiagnostic(number, state, severity, message, server, procName, line); } else { messages.addDiagnostic(number, state, severity, message, server, procName, line); } } /** * Process TDS5 dynamic SQL aknowledgements. * * @throws IOException */ private void tds5DynamicToken() throws IOException { int pktLen = in.readShort(); byte type = (byte)in.read(); /*byte status = (byte)*/in.read(); pktLen -= 2; if (type == (byte)0x20) { // Only handle aknowledgements for now int len = in.read(); currentToken.dynamicId = in.readNonUnicodeString(len); pktLen -= len+1; } // FIXME This won't work with multi-byte charsets in.skip(pktLen); } /** * Process TDS 5 Dynamic results parameter descriptors. * <p> * With Sybase 12+ this has been superseded by the TDS5_PARAMFMT2_TOKEN * except when used to return extended error information. * * @throws IOException * @throws ProtocolException */ private void tds5ParamFmtToken() throws IOException, ProtocolException { in.readShort(); // Packet length int paramCnt = in.readShort(); ColInfo[] params = new ColInfo[paramCnt]; for (int i = 0; i < paramCnt; i++) { // Get the parameter details using the // ColInfo class as the server format is the same. ColInfo col = new ColInfo(); int colNameLen = in.read(); col.realName = in.readNonUnicodeString(colNameLen); int column_flags = in.read(); /* Flags */ col.isCaseSensitive = false; col.nullable = ((column_flags & 0x20) != 0)? ResultSetMetaData.columnNullable: ResultSetMetaData.columnNoNulls; col.isWriteable = (column_flags & 0x10) != 0; col.isIdentity = (column_flags & 0x40) != 0; col.isKey = (column_flags & 0x02) != 0; col.isHidden = (column_flags & 0x01) != 0; col.userType = in.readInt(); if ((byte)in.peek() == TDS_DONE_TOKEN) { // Sybase 11.92 bug data type missing! currentToken.dynamParamInfo = null; currentToken.dynamParamData = null; // error trapped in sybasePrepare(); messages.addDiagnostic(9999, 0, 16, "Prepare failed", "", "", 0); return; // Give up } TdsData.readType(in, col); // Skip locale information in.skip(1); params[i] = col; } currentToken.previousToken = TDS5_PARAMFMT_TOKEN; currentToken.dynamParamInfo = params; currentToken.dynamParamData = new Object[paramCnt]; } /** * Process a NTLM Authentication challenge. * * @throws IOException * @throws ProtocolException */ private void tdsNtlmAuthToken() throws IOException, ProtocolException { int pktLen = in.readShort(); // Packet length int hdrLen = 40; if (pktLen < hdrLen) throw new ProtocolException("NTLM challenge: packet is too small:" + pktLen); byte[] ntlmMessage = new byte[pktLen]; in.read(ntlmMessage); int b1 = ((int) ntlmMessage[8] & 0xff); int b2 = ((int) ntlmMessage[9] & 0xff) << 8; int b3 = ((int) ntlmMessage[10] & 0xff) << 16; int b4 = ((int) ntlmMessage[11] & 0xff) << 24; final int seq =b4 | b3 | b2 | b1; if (seq != 2) throw new ProtocolException("NTLM challenge: got unexpected sequence number:" + seq); currentToken.nonce = new byte[8]; currentToken.ntlmMessage = ntlmMessage; System.arraycopy(ntlmMessage, 24, currentToken.nonce, 0, 8); } /** * Process a TDS 5.0 result set packet. * * @throws IOException * @throws ProtocolException */ private void tds5ResultToken() throws IOException, ProtocolException { in.readShort(); // Packet length int colCnt = in.readShort(); this.columns = new ColInfo[colCnt]; this.rowData = new Object[colCnt]; this.tables = null; for (int colNum = 0; colNum < colCnt; ++colNum) { // Get the column name ColInfo col = new ColInfo(); int colNameLen = in.read(); col.realName = in.readNonUnicodeString(colNameLen); col.name = col.realName; int column_flags = in.read(); /* Flags */ col.isCaseSensitive = false; col.nullable = ((column_flags & 0x20) != 0)? ResultSetMetaData.columnNullable: ResultSetMetaData.columnNoNulls; col.isWriteable = (column_flags & 0x10) != 0; col.isIdentity = (column_flags & 0x40) != 0; col.isKey = (column_flags & 0x02) != 0; col.isHidden = (column_flags & 0x01) != 0; col.userType = in.readInt(); TdsData.readType(in, col); // Skip locale information in.skip(1); columns[colNum] = col; } endOfResults = false; } /** * Process a DONE, DONEINPROC or DONEPROC token. * * @throws IOException */ private void tdsDoneToken() throws IOException { currentToken.status = (byte)in.read(); in.skip(1); currentToken.operation = (byte)in.read(); in.skip(1); currentToken.updateCount = in.readInt(); if (!endOfResults) { // This will eliminate the select row count for sybase currentToken.status &= ~DONE_ROW_COUNT; endOfResults = true; } if ((currentToken.status & DONE_MORE_RESULTS) == 0) { // There are no more results or pending cancel packets // to process. endOfResponse = true; if (fatalError) { // A fatal error has occured, the server has closed the // connection connection.setClosed(); } } if (serverType == Driver.SQLSERVER) { // MS SQL Server provides additional information we // can use to return special row counts for DDL etc. if (currentToken.operation == (byte) 0xC1) { currentToken.status &= ~DONE_ROW_COUNT; } } if ((currentToken.status & DONE_CANCEL) != 0) { // Indicates cancel packet messages.addDiagnostic(9999, 0, 14, "Request cancelled", "", "", 0); } } /** * Execute SQL using TDS 4.2 protocol. * * @param sql The SQL statement to execute. * @param procName Stored procedure to execute or null. * @param parameters Parameters for call or null. * @param noMetaData Suppress meta data for cursor calls. * @throws SQLException */ private void executeSQL42(String sql, String procName, ParamInfo[] parameters, boolean noMetaData, boolean sendNow) throws IOException, SQLException { if (procName != null) { // RPC call out.setPacketType(RPC_PKT); byte[] buf = Support.encodeString(connection.getCharset(), procName); out.write((byte) buf.length); out.write(buf); out.write((short) (noMetaData ? 2 : 0)); if (parameters != null) { for (int i = nextParam + 1; i < parameters.length; i++) { if (parameters[i].name != null) { buf = Support.encodeString(connection.getCharset(), parameters[i].name); out.write((byte) buf.length); out.write(buf); } else { out.write((byte) 0); } out.write((byte) (parameters[i].isOutput ? 1 : 0)); TdsData.writeParam(out, connection.getCharsetInfo(), null, parameters[i]); } } if (!sendNow) { // Send end of packet byte to batch RPC out.write((byte) DONE_END_OF_RESPONSE); } } else if (sql.length() > 0) { if (parameters != null) { sql = Support.substituteParameters(sql, parameters, tdsVersion); } out.setPacketType(QUERY_PKT); out.write(sql); if (!sendNow) { // Batch SQL statements out.write("\r\n"); } } } /** * Execute SQL using TDS 5.0 protocol. * * @param sql The SQL statement to execute. * @param procName Stored procedure to execute or null. * @param parameters Parameters for call or null. * @throws SQLException */ private void executeSQL50(String sql, String procName, ParamInfo[] parameters) throws IOException, SQLException { boolean haveParams = parameters != null; boolean useParamNames = false; currentToken.previousToken = 0; currentToken.dynamParamInfo = null; currentToken.dynamParamData = null; // Sybase does not allow text or image parameters for (int i = 0; haveParams && i < parameters.length; i++) { if (parameters[i].sqlType.equals("text") || parameters[i].sqlType.equals("image")) { if (procName != null && procName.length() > 0) { // Call to store proc nothing we can do if (parameters[i].sqlType.equals("text")) { throw new SQLException( Messages.get("error.chartoolong"), "HY000"); } throw new SQLException( Messages.get("error.bintoolong"), "HY000"); } // prepared statement substitute parameters into SQL sql = Support.substituteParameters(sql, parameters, tdsVersion); haveParams = false; procName = null; break; } } out.setPacketType(SYBQUERY_PKT); if (procName == null) { // Use TDS_LANGUAGE TOKEN with optional parameters out.write((byte)TDS_LANG_TOKEN); if (haveParams) { sql = Support.substituteParamMarkers(sql, parameters); } if (connection.isWideChar()) { // Need to preconvert string to get correct length byte[] buf = Support.encodeString(connection.getCharset(), sql); out.write((int) buf.length + 1); out.write((byte)(haveParams ? 1 : 0)); out.write(buf); } else { out.write((int) sql.length() + 1); out.write((byte) (haveParams ? 1 : 0)); out.write(sql); } } else if (procName.startsWith("#jtds")) { // Dynamic light weight procedure call out.write((byte) TDS5_DYNAMIC_TOKEN); out.write((short) (procName.length() + 4)); out.write((byte) 2); out.write((byte) (haveParams ? 1 : 0)); out.write((byte) (procName.length() - 1)); out.write(procName.substring(1)); out.write((short) 0); } else { byte buf[] = Support.encodeString(connection.getCharset(), procName); // RPC call out.write((byte) TDS_DBRPC_TOKEN); out.write((short) (buf.length + 3)); out.write((byte) buf.length); out.write(buf); out.write((short) (haveParams ? 2 : 0)); useParamNames = true; } // Output any parameters if (haveParams) { // First write parameter descriptors out.write((byte) TDS5_PARAMFMT_TOKEN); int len = 2; for (int i = nextParam + 1; i < parameters.length; i++) { len += TdsData.getTds5ParamSize(connection.getCharset(), connection.isWideChar(), parameters[i], useParamNames); } out.write((short) len); out.write((short) ((nextParam < 0) ? parameters.length : parameters.length - 1)); for (int i = nextParam + 1; i < parameters.length; i++) { TdsData.writeTds5ParamFmt(out, connection.getCharset(), connection.isWideChar(), parameters[i], useParamNames); } // Now write the actual data out.write((byte) TDS5_PARAMS_TOKEN); for (int i = nextParam + 1; i < parameters.length; i++) { TdsData.writeTds5Param(out, connection.getCharset(), parameters[i]); } } } /** * Map of system stored procedures that have shortcuts in TDS8. */ private static HashMap tds8SpNames = new HashMap(); static { tds8SpNames.put("sp_cursor", new Integer(1)); tds8SpNames.put("sp_cursoropen", new Integer(2)); tds8SpNames.put("sp_cursorprepare", new Integer(3)); tds8SpNames.put("sp_cursorexecute", new Integer(4)); tds8SpNames.put("sp_cursorprepexec", new Integer(5)); tds8SpNames.put("sp_cursorunprepare", new Integer(6)); tds8SpNames.put("sp_cursorfetch", new Integer(7)); tds8SpNames.put("sp_cursoroption", new Integer(8)); tds8SpNames.put("sp_cursorclose", new Integer(9)); tds8SpNames.put("sp_executesql", new Integer(10)); tds8SpNames.put("sp_prepare", new Integer(11)); tds8SpNames.put("sp_execute", new Integer(12)); tds8SpNames.put("sp_prepexec", new Integer(13)); tds8SpNames.put("sp_prepexecrpc", new Integer(14)); tds8SpNames.put("sp_unprepare", new Integer(15)); } /** * Returns <code>true</code> if the specified <code>procName</code> * is a sp_prepare or sp_prepexec handle; returns <code>false</code> * otherwise. * * @param procName Stored procedure to execute or <code>null</code>. * @return <code>true</code> if the specified <code>procName</code> * is a sp_prepare or sp_prepexec handle; <code>false</code> * otherwise. */ public static boolean isPreparedProcedureName(final String procName) { if (procName != null && procName.length() > 0 && Character.isDigit(procName.charAt(0))) { return true; } return false; } /** * Execute SQL using TDS 7.0 protocol. * * @param sql The SQL statement to execute. * @param procName Stored procedure to execute or <code>null</code>. * @param parameters Parameters for call or <code>null</code>. * @param noMetaData Suppress meta data for cursor calls. * @throws SQLException */ private void executeSQL70(String sql, String procName, ParamInfo[] parameters, boolean noMetaData, boolean sendNow) throws IOException, SQLException { int prepareSql = connection.getPrepareSql(); if (parameters == null && (prepareSql == EXECUTE_SQL || prepareSql == PREPARE || prepareSql == PREPEXEC)) { // Downgrade EXECUTE_SQL, PREPARE and PREPEXEC to UNPREPARED // if there are no parameters. // Should we downgrade TEMPORARY_STORED_PROCEDURES as well? // No it may be a complex select with no parameters but costly to // evaluate for each execution. prepareSql = UNPREPARED; } if (inBatch) { // For batch execution with parameters // we need to be consistant and use // execute SQL prepareSql = EXECUTE_SQL; } if (isPreparedProcedureName(procName)) { // If the procedure is a prepared handle then redefine the // procedure name as sp_execute with the handle as a parameter. ParamInfo params[]; if (parameters != null) { params = new ParamInfo[1 + parameters.length]; System.arraycopy(parameters, 0, params, 1, parameters.length); } else { params = new ParamInfo[1]; } params[0] = new ParamInfo(Types.INTEGER, new Integer(procName), ParamInfo.INPUT); TdsData.getNativeType(connection, params[0]); parameters = params; // Use sp_execute approach procName = "sp_execute"; } else if (procName == null) { if (prepareSql == PREPEXEC) { // TODO: Make this option work with batch execution! ParamInfo params[] = new ParamInfo[3 + parameters.length]; System.arraycopy(parameters, 0, params, 3, parameters.length); // Setup prepare handle param params[0] = new ParamInfo(Types.INTEGER, null, ParamInfo.OUTPUT); TdsData.getNativeType(connection, params[0]); // Setup parameter descriptor param params[1] = new ParamInfo(Types.LONGVARCHAR, Support.getParameterDefinitions(parameters), ParamInfo.UNICODE); TdsData.getNativeType(connection, params[1]); // Setup sql statemement param params[2] = new ParamInfo(Types.LONGVARCHAR, Support.substituteParamMarkers(sql, parameters), ParamInfo.UNICODE); TdsData.getNativeType(connection, params[2]); parameters = params; // Use sp_prepexec approach procName = "sp_prepexec"; } else if (prepareSql != TdsCore.UNPREPARED && parameters != null) { ParamInfo[] params; params = new ParamInfo[2 + parameters.length]; System.arraycopy(parameters, 0, params, 2, parameters.length); params[0] = new ParamInfo(Types.LONGVARCHAR, Support.substituteParamMarkers(sql, parameters), ParamInfo.UNICODE); TdsData.getNativeType(connection, params[0]); params[1] = new ParamInfo(Types.LONGVARCHAR, Support.getParameterDefinitions(parameters), ParamInfo.UNICODE); TdsData.getNativeType(connection, params[1]); parameters = params; // Use sp_executesql approach procName = "sp_executesql"; } } if (procName != null) { // RPC call out.setPacketType(RPC_PKT); Integer shortcut; if (tdsVersion >= Driver.TDS80 && (shortcut = (Integer) tds8SpNames.get(procName)) != null) { // Use the shortcut form of procedure name for TDS8 out.write((short) -1); out.write((short) shortcut.shortValue()); } else { out.write((short) procName.length()); out.write(procName); } out.write((short) (noMetaData ? 2 : 0)); if (parameters != null) { for (int i = nextParam + 1; i < parameters.length; i++) { if (parameters[i].name != null) { out.write((byte) parameters[i].name.length()); out.write(parameters[i].name); } else { out.write((byte) 0); } out.write((byte) (parameters[i].isOutput ? 1 : 0)); TdsData.writeParam(out, connection.getCharsetInfo(), connection.getCollation(), parameters[i]); } } if (!sendNow) { // Append RPC packets out.write((byte) DONE_END_OF_RESPONSE); } } else if (sql.length() > 0) { if (parameters != null) { sql = Support.substituteParameters(sql, parameters, tdsVersion); } // Simple query out.setPacketType(QUERY_PKT); out.write(sql); if (!sendNow) { // Append SQL packets out.write("\r\n"); } } } /** * Set the server row count used to limit the number of rows in a result set. * * @param rowCount the number of rows to return or 0 for no limit or -1 to * leave as is * @throws SQLException if an error is returned by the server */ private void setRowCount(int rowCount) throws SQLException { if (rowCount >= 0 && rowCount != connection.getRowCount()) { try { out.setPacketType(QUERY_PKT); out.write("SET ROWCOUNT " + rowCount); out.flush(); endOfResponse = false; endOfResults = true; wait(0); clearResponseQueue(); messages.checkErrors(); connection.setRowCount(rowCount); } catch (IOException ioe) { throw new SQLException( Messages.get("error.generic.ioerror", ioe.getMessage()), "08S01"); } } } /** * Wait for the first byte of the server response. * * @param timeOut The time out period in seconds or 0. */ private void wait(int timeOut) throws IOException, SQLException { QueryTimer timer = null; try { if (timeOut > 0) { // Start a login timer timer = new QueryTimer(this, timeOut); timer.start(); } in.peek(); } finally { if (timer != null) { // Cancel QueryTimer timer.stopTimer(); if (timer.wasCancelled()) { // Query timed out throw new SQLException( Messages.get("error.generic.timeout"), "HYT00"); } } } } /** * Convert a user supplied MAC address into a byte array. * * @param macString The MAC address as a hex string. * @return The MAC address as a <code>byte[]</code>. */ private static byte[] getMACAddress(String macString) { byte[] mac = new byte[6]; boolean ok = false; if (macString != null && macString.length() == 12) { try { for (int i = 0, j = 0; i < 6; i++, j += 2) { mac[i] = (byte) Integer.parseInt( macString.substring(j, j + 2), 16); } ok = true; } catch (Exception ex) { // Ignore it. ok will be false. } } if (!ok) { Arrays.fill(mac, (byte) 0); } return mac; } /** * Try to figure out what client name we should identify ourselves as. Get * the hostname of this machine, * * @return name we will use as the client. */ private static String getHostName() { if (hostName != null) { return hostName; } String name; try { name = java.net.InetAddress.getLocalHost().getHostName().toUpperCase(); } catch (java.net.UnknownHostException e) { hostName = "UNKNOWN"; return hostName; } int pos = name.indexOf('.'); if (pos >= 0) { name = name.substring(0, pos); } if (name.length() == 0) { hostName = "UNKNOWN"; return hostName; } try { Integer.parseInt(name); // All numbers probably an IP address hostName = "UNKNOWN"; return hostName; } catch (NumberFormatException e) { // Bit tacky but simple check for all numbers } hostName = name; return name; } /** * This is a <B>very</B> poor man's "encryption." * * @param pw password to encrypt * @return encrypted password */ private static String tds7CryptPass(final String pw) { final int xormask = 0x5A5A; final int len = pw.length(); final char[] chars = new char[len]; for (int i = 0; i < len; ++i) { final int c = (int) (pw.charAt(i)) ^ xormask; final int m1 = (c >> 4) & 0x0F0F; final int m2 = (c << 4) & 0xF0F0; chars[i] = (char) (m1 | m2); } return new String(chars); } }
package mousio.hbase.async; import com.google.protobuf.RpcCallback; import com.google.protobuf.RpcController; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.filter.BinaryComparator; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.ipc.AsyncPayloadCarryingRpcController; import org.apache.hadoop.hbase.ipc.AsyncRpcChannel; import org.apache.hadoop.hbase.ipc.AsyncRpcClient; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.RequestConverter; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos; import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos; import org.apache.hadoop.hbase.util.Bytes; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.apache.hadoop.hbase.protobuf.ProtobufUtil.toResult; import static org.apache.hadoop.hbase.protobuf.RequestConverter.buildGetRequest; import static org.apache.hadoop.hbase.protobuf.RequestConverter.buildMutateRequest; /** * Hbase client. */ public class HbaseClient extends AbstractHbaseClient implements Closeable { private final AsyncRpcClient client; /** * Constructor * * @param connection to Hbase * @throws java.io.IOException if HConnection could not be set up */ public HbaseClient(HConnection connection) throws IOException { super(connection); this.client = new AsyncRpcClient(connection, this.clusterId, null); } /** * Send a Get * * @param table to run get on * @param get to fetch * @param handler on response * @return the handler with the result */ public <H extends ResponseHandler<Result>> H get(TableName table, Get get, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, get.getRow(), false); client.getClientService(location).get( client.newRpcController(handler), buildGetRequest( location.getRegionInfo().getRegionName(), get ), new RpcCallback<ClientProtos.GetResponse>() { @Override public void run(ClientProtos.GetResponse response) { handler.onSuccess(toResult(response.getResult())); } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } /** * Send a Get * * @param table to run get on * @param gets to fetch * @param handler on response * @return the handler with the result */ public <H extends ResponseHandler<Result[]>> H get(TableName table, List<Get> gets, final H handler) { final Result[] results = new Result[gets.size()]; final AtomicInteger counter = new AtomicInteger(0); final AtomicBoolean complete = new AtomicBoolean(false); for (int i = 0; i < gets.size(); i++) { this.get(table, gets.get(i), new ResultListener<Result>(i) { @Override public void onSuccess(Result response) { if (!complete.get()) { synchronized (results) { results[this.index] = response; if (counter.incrementAndGet() == results.length) { handler.onSuccess(results); } } } } @Override public void onFailure(IOException e) { if (!complete.get()) { handler.onFailure(e); complete.set(true); } } }); } return handler; } /** * Send a scan and get a cell scanner * * @param table to get scanner from * @param scan to perform * @return the handler with the ResponseHandler if successful */ public AsyncResultScanner getScanner(TableName table, Scan scan) { if (scan.isReversed()) { if (scan.isSmall()) { return new AsyncClientSmallReversedScanner(this.client, scan, table); } else { return new AsyncReversedClientScanner(this.client, scan, table); } } if (scan.isSmall()) { return new AsyncClientSmallScanner(this.client, scan, table); } else { return new AsyncClientScanner(this.client, scan, table); } } /** * Send a put * * @param table to send Put to * @param put to send * @param handler to handle exceptions * @param <H> Type of Handler * @return handler */ public <H extends ResponseHandler<Void>> H put(TableName table, Put put, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, put.getRow(), false); client.getClientService(location).mutate( client.newRpcController(handler), buildMutateRequest( location.getRegionInfo().getRegionName(), put ), new RpcCallback<ClientProtos.MutateResponse>() { @Override public void run(ClientProtos.MutateResponse response) { handler.onSuccess(null); } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } /** * Send a list of puts to the server * * @param table to send puts to * @param puts to send * @param handler to handle exceptions * @param <H> Handler to handle any exceptions * @return handler */ public <H extends ResponseHandler<Void>> H put(TableName table, List<Put> puts, final H handler) { final int size = puts.size(); final AtomicInteger counter = new AtomicInteger(0); for (Put put : puts) { this.put(table, put, new ResponseHandler<Void>() { @Override public void onSuccess(Void response) { if (counter.incrementAndGet() == size) { handler.onSuccess(null); } } @Override public void onFailure(IOException e) { if (counter.get() < size) { handler.onFailure(e); counter.set(size); } } }); } return handler; } /** * Atomically checks if a row/family/qualifier value matches the expected * value. If it does, it adds the put. If the passed value is null, the check * is for the lack of column (ie: non-existance) * * @param table to check on and send put to * @param row to check * @param family column family to check * @param qualifier column qualifier to check * @param value the expected value * @param put data to put if check succeeds * @param handler to handle exceptions * @param <H> Handler to handle any exceptions * @return true if the new put was executed, false otherwise */ public <H extends ResponseHandler<Boolean>> H checkAndPut(TableName table, byte[] row, byte[] family, byte[] qualifier, byte[] value, Put put, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, put.getRow(), false); client.getClientService(location).mutate( client.newRpcController(handler), buildMutateRequest( location.getRegionInfo().getRegionName(), row, family, qualifier, new BinaryComparator(value), HBaseProtos.CompareType.EQUAL, put ), new RpcCallback<ClientProtos.MutateResponse>() { @Override public void run(ClientProtos.MutateResponse response) { handler.onSuccess(response.getProcessed()); } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } /** * Deletes the specified cells/row. * * @param table to send delete to * @param delete The object that specifies what to delete. * @param handler to handle exceptions * @param <H> Handler to handle any exceptions * @return handler of responses and exceptions */ public <H extends ResponseHandler<Void>> H delete(TableName table, Delete delete, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, delete.getRow(), false); client.getClientService(location).mutate( client.newRpcController(handler), buildMutateRequest( location.getRegionInfo().getRegionName(), delete ), new RpcCallback<ClientProtos.MutateResponse>() { @Override public void run(ClientProtos.MutateResponse response) { handler.onSuccess(null); } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } public <H extends ResponseHandler<Void>> H delete(TableName table, List<Delete> deletes, final H handler) { final int size = deletes.size(); final AtomicInteger counter = new AtomicInteger(0); for (Delete delete : deletes) { this.delete(table, delete, new ResponseHandler<Void>() { @Override public void onSuccess(Void response) { if (counter.incrementAndGet() == size) { handler.onSuccess(null); } } @Override public void onFailure(IOException e) { if (counter.get() < size) { handler.onFailure(e); counter.set(size); } } }); } return handler; } /** * Atomically checks if a row/family/qualifier value matches the expected * value. If it does, it adds the delete. If the passed value is null, the * check is for the lack of column (ie: non-existance) * * @param table to send check and delete to * @param row to check * @param family column family to check * @param qualifier column qualifier to check * @param value the expected value * @param delete data to delete if check succeeds * @param handler to handle exceptions * @param <H> Handler to handle any exceptions * @return true if the new delete was executed, false otherwise */ public <H extends ResponseHandler<Boolean>> H checkAndDelete(TableName table, byte[] row, byte[] family, byte[] qualifier, byte[] value, Delete delete, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, delete.getRow(), false); client.getClientService(location).mutate( client.newRpcController(handler), buildMutateRequest( location.getRegionInfo().getRegionName(), row, family, qualifier, new BinaryComparator(value), HBaseProtos.CompareType.EQUAL, delete ), new RpcCallback<ClientProtos.MutateResponse>() { @Override public void run(ClientProtos.MutateResponse response) { handler.onSuccess(response.getProcessed()); } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } /** * Performs multiple mutations atomically on a single row. Currently * {@link Put} and {@link Delete} are supported. * * @param table to mutate row on * @param rm object that specifies the set of mutations to perform atomically * @param handler to handle exceptions * @param <H> Handler to handle any exceptions * @return response handler */ public <H extends ResponseHandler<Void>> H mutateRow(TableName table, final RowMutations rm, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, rm.getRow(), false); ClientProtos.RegionAction.Builder regionMutationBuilder = RequestConverter.buildRegionAction( location.getRegionInfo().getRegionName(), rm); regionMutationBuilder.setAtomic(true); ClientProtos.MultiRequest request = ClientProtos.MultiRequest.newBuilder().addRegionAction(regionMutationBuilder.build()).build(); client.getClientService(location).multi( client.newRpcController(handler), request, new RpcCallback<ClientProtos.MultiResponse>() { @Override public void run(ClientProtos.MultiResponse response) { handler.onSuccess(null); } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } /** * Appends values to one or more columns within a single row. * <p/> * This operation does not appear atomic to readers. Appends are done * under a single row lock, so write operations to a row are synchronized, but * readers do not take row locks so get and scan operations can see this * operation partially completed. * * @param table to append to * @param append object that specifies the columns and amounts to be used * for the increment operations * @param handler to handle exceptions * @param <H> Handler to handle any exceptions * @return handler with Result on success */ public <H extends ResponseHandler<Result>> H append(TableName table, final Append append, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, append.getRow(), false); NonceGenerator ng = this.client.getNonceGenerator(); final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce(); final AsyncPayloadCarryingRpcController controller = client.newRpcController(handler); client.getClientService(location).mutate( controller, buildMutateRequest( location.getRegionInfo().getRegionName(), append, nonceGroup, nonce ), new RpcCallback<ClientProtos.MutateResponse>() { @Override public void run(ClientProtos.MutateResponse response) { try { handler.onSuccess(ProtobufUtil.toResult(response.getResult(), controller.cellScanner())); } catch (IOException e) { handler.onFailure(e); } } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } /** * Increments one or more columns within a single row. * <p/> * This operation does not appear atomic to readers. Increments are done * under a single row lock, so write operations to a row are synchronized, but * readers do not take row locks so get and scan operations can see this * operation partially completed. * * @param table to increment on * @param increment object that specifies the columns and amounts to be used * for the increment operations * @param handler to handle exceptions * @param <H> Handler to handle any exceptions * @return handler with on success the values of columns after the increment */ public <H extends ResponseHandler<Result>> H increment(TableName table, final Increment increment, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, increment.getRow(), false); NonceGenerator ng = this.client.getNonceGenerator(); final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce(); final AsyncPayloadCarryingRpcController controller = client.newRpcController(handler); client.getClientService(location).mutate( controller, buildMutateRequest( location.getRegionInfo().getRegionName(), increment, nonceGroup, nonce ), new RpcCallback<ClientProtos.MutateResponse>() { @Override public void run(ClientProtos.MutateResponse response) { try { handler.onSuccess(ProtobufUtil.toResult(response.getResult(), controller.cellScanner())); } catch (IOException e) { handler.onFailure(e); } } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } /** * See {@link #incrementColumnValue(TableName, byte[], byte[], byte[], long, Durability, ResponseHandler)} * <p/> * The {@link Durability} is defaulted to {@link Durability#SYNC_WAL}. * * @param table to increment column value on * @param row The row that contains the cell to increment. * @param family The column family of the cell to increment. * @param qualifier The column qualifier of the cell to increment. * @param amount The amount to increment the cell with (or decrement, if the * amount is negative). * @param handler to handle response * @param <H> Handler to handle any exceptions * @return Response handler: on success The new value, post increment. */ public <H extends ResponseHandler<Long>> H incrementColumnValue(TableName table, byte[] row, byte[] family, byte[] qualifier, long amount, final H handler) { return incrementColumnValue(table, row, family, qualifier, amount, Durability.SYNC_WAL, handler); } /** * Atomically increments a column value. If the column value already exists * and is not a big-endian long, this could throw an exception. If the column * value does not yet exist it is initialized to <code>amount</code> and * written to the specified column. * <p/> * <p>Setting durability to {@link Durability#SKIP_WAL} means that in a fail * scenario you will lose any increments that have not been flushed. * * @param table to increment column value on * @param row The row that contains the cell to increment. * @param family The column family of the cell to increment. * @param qualifier The column qualifier of the cell to increment. * @param amount The amount to increment the cell with (or decrement, if the * amount is negative). * @param durability The persistence guarantee for this increment. * @param handler to handle response * @param <H> Handler to handle any exceptions * @return Response handler: on success The new value, post increment. */ public <H extends ResponseHandler<Long>> H incrementColumnValue(TableName table, byte[] row, final byte[] family, final byte[] qualifier, long amount, Durability durability, final H handler) { NullPointerException npe = null; if (row == null) { npe = new NullPointerException("row is null"); } else if (family == null) { npe = new NullPointerException("family is null"); } else if (qualifier == null) { npe = new NullPointerException("qualifier is null"); } if (npe != null) { handler.onFailure(new IOException( "Invalid arguments to incrementColumnValue", npe)); } else { try { HRegionLocation location = this.client.getRegionLocation(table, row, false); NonceGenerator ng = this.client.getNonceGenerator(); final long nonceGroup = ng.getNonceGroup(), nonce = ng.newNonce(); ClientProtos.MutateRequest request = RequestConverter.buildIncrementRequest( location.getRegionInfo().getRegionName(), row, family, qualifier, amount, durability, nonceGroup, nonce); final AsyncPayloadCarryingRpcController controller = client.newRpcController(handler); client.getClientService(location).mutate( controller, request, new RpcCallback<ClientProtos.MutateResponse>() { @Override public void run(ClientProtos.MutateResponse response) { try { Result result = ProtobufUtil.toResult(response.getResult(), controller.cellScanner()); handler.onSuccess(Bytes.toLong(result.getValue(family, qualifier))); } catch (IOException e) { handler.onFailure(e); } } } ); } catch (IOException e) { handler.onFailure(e); } } return handler; } /** * Atomically checks if a row/family/qualifier value matches the expected val * If it does, it performs the row mutations. If the passed value is null, t * is for the lack of column (ie: non-existence) * * @param table to check and mutate * @param row to check * @param family column family to check * @param qualifier column qualifier to check * @param compareOp the comparison operator * @param value the expected value * @param mutation mutations to perform if check succeeds * @param handler for the response * @param <H> Handler to handle any exceptions * @return handler with response: true if the new put was executed, false otherwise */ public <H extends ResponseHandler<Boolean>> H checkAndMutate(TableName table, byte[] row, byte[] family, byte[] qualifier, CompareFilter.CompareOp compareOp, byte[] value, RowMutations mutation, final H handler) { try { HRegionLocation location = this.client.getRegionLocation(table, mutation.getRow(), false); client.getClientService(location).multi( client.newRpcController(handler), buildMutateRequest( location.getRegionInfo().getRegionName(), row, family, qualifier, new BinaryComparator(value), HBaseProtos.CompareType.valueOf(compareOp.name()), mutation ), new RpcCallback<ClientProtos.MultiResponse>() { @Override public void run(ClientProtos.MultiResponse response) { handler.onSuccess(response.getProcessed()); } } ); } catch (IOException e) { handler.onFailure(e); } return handler; } /** * Creates and returns a {@link com.google.protobuf.RpcChannel} instance connected to the * table region containing the specified row. The row given does not actually have * to exist. Whichever region would contain the row based on start and end keys will * be used. Note that the {@code row} parameter is also not passed to the * coprocessor handler registered for this protocol, unless the {@code row} * is separately passed as an argument in the service request. The parameter * here is only used to locate the region used to handle the call. * <p/> * <p> * The obtained {@link com.google.protobuf.RpcChannel} instance can be used to access a published * coprocessor {@link com.google.protobuf.Service} using standard protobuf service invocations: * </p> * <p/> * <div style="background-color: #cccccc; padding: 2px"> * <blockquote><pre> * CoprocessorRpcChannel channel = myTable.coprocessorService(rowkey); * MyService.BlockingInterface service = MyService.newBlockingStub(channel); * MyCallRequest request = MyCallRequest.newBuilder() * ... * .build(); * MyCallResponse response = service.myCall(null, request); * </pre></blockquote></div> * * @param table to get service from * @param row The row key used to identify the remote region location * @return A CoprocessorRpcChannel instance * @throws java.io.IOException when there was an error creating connection or getting location */ public AsyncRpcChannel coprocessorService(TableName table, byte[] row) throws IOException { HRegionLocation location = this.client.getRegionLocation(table, row, false); return client.getConnection( ClientProtos.ClientService.getDescriptor(), location ); } /** * Get a new promise chained to event loop of internal netty client * * @param <T> Type of response to return * @return Hbase Response Promise */ public <T> HbaseResponsePromise<T> newPromise() { return new HbaseResponsePromise<>(client.getEventLoop()); } @Override public void close() throws IOException { client.close(); } /** * Get a new Rpc controller * * @param promise to handle result * @return new RpcController */ public RpcController newRpcController(HbaseResponsePromise<?> promise) { return this.client.newRpcController(promise); } /** * Listens for results with an index * * @param <R> Type of result listened to */ private abstract class ResultListener<R> implements ResponseHandler<R> { protected int index; /** * Constructor * * @param i index for result */ public ResultListener(int i) { this.index = i; } } }
package net.imagej.updater; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.zip.ZipException; import net.imagej.updater.Conflicts.Conflict; import net.imagej.updater.Conflicts.Resolution; import net.imagej.updater.Conflicts.Conflict.Severity; import net.imagej.updater.FileObject.Status; import net.imagej.updater.util.AbstractProgressable; import net.imagej.updater.util.Progress; import net.imagej.updater.util.UpdaterUtil; /** * A class to checksum and timestamp all the files shown in the Updater's UI. * * @author Johannes Schindelin * @author Yap Chin Kiet */ public class Checksummer extends AbstractProgressable { private FilesCollection files; private int counter, total; private Map<String, FileObject.Version> cachedChecksums; private boolean isWindows; // time tax for Redmond private Map<String, List<StringAndFile>> queue; public Checksummer(final FilesCollection files, final Progress progress) { this.files = files; if (progress != null) addProgress(progress); setTitle("Checksummer"); isWindows = UpdaterUtil.getPlatform().startsWith("win"); } protected static class StringAndFile { private String path; private File file; public long timestamp; public String checksum; protected StringAndFile(final String path, final File file) { this.path = path; this.file = file; } @Override public String toString() { return "{" + path + " - " + file + "}"; } } public Map<String, FileObject.Version> getCachedChecksums() { return cachedChecksums; } /* follows symlinks */ protected boolean exists(final File file) { try { return file.getCanonicalFile().exists(); } catch (final IOException e) { files.log.error(e); } return false; } public void queueDir(final String[] dirs, final String[] extensions) { final Set<String> set = new HashSet<String>(); for (final String extension : extensions) set.add(extension); for (final String dir : dirs) queueDir(dir, set); } public void queueDir(final String dir, final Set<String> extensions) { File file = files.prefix(dir); if (!exists(file)) return; for (final String item : file.list()) { final String path = dir + "/" + item; file = files.prefix(path); if (item.startsWith(".")) continue; if (file.isDirectory()) { queueDir(path, extensions); continue; } if (!extensions.contains("")) { final int dot = item.lastIndexOf('.'); if (dot < 0 || !extensions.contains(item.substring(dot))) continue; } if (exists(file)) queue(path, file); } } protected void queueIfExists(final String path) { final File file = files.prefix(path); if (file.exists()) queue(path, file); } protected void queue(final String path) { queue(path, files.prefix(path)); } protected void queue(final String path, final File file) { String unversioned = FileObject.getFilename(path, true); if (!queue.containsKey(unversioned)) queue.put(unversioned, new ArrayList<StringAndFile>()); queue.get(unversioned).add(new StringAndFile(path, file)); } /** * Handle a single component, adding conflicts if there are multiple * versions. * * @param unversioned * the unversioned name of the component */ protected void handle(final String unversioned) { final List<StringAndFile> pairs = queue.get(unversioned); for (final StringAndFile pair : pairs) { addItem(pair.path); if (pair.file.exists()) try { pair.timestamp = UpdaterUtil.getTimestamp(pair.file); pair.checksum = getDigest(pair.path, pair.file, pair.timestamp); } catch (final ZipException e) { files.log.error("Problem digesting " + pair.file); } catch (final Exception e) { files.log.error(e); } counter += (int) pair.file.length(); itemDone(pair.path); setCount(counter, total); } if (pairs.size() == 1) { handle(pairs.get(0)); return; } // there are multiple versions of the same component; StringAndFile pair = null; FileObject object = files.get(unversioned); if (object == null || object.isObsolete()) { // the component is local-only; fall back to using the newest one for (StringAndFile p : pairs) if (pair == null || (p.file.lastModified() > pair.file.lastModified() && pair.path.equals(FileObject.getFilename(pair.path, true)))) pair = p; final List<File> obsoletes = new ArrayList<File>(); for (StringAndFile p : pairs) if (p != pair) obsoletes.add(p.file); if (pair != null) addConflict(pair.path, "", false, obsoletes); } else { // let's find out whether there are obsoletes or locally-modified versions final List<StringAndFile> upToDates = new ArrayList<StringAndFile>(); final List<StringAndFile> obsoletes = new ArrayList<StringAndFile>(); final List<StringAndFile> locallyModifieds = new ArrayList<StringAndFile>(); for (final StringAndFile p : pairs) { if (object.current.checksum.equals(p.checksum)) upToDates.add(p); else if (object.hasPreviousVersion(p.checksum)) obsoletes.add(p); else locallyModifieds.add(p); } Comparator<StringAndFile> comparator = new Comparator<StringAndFile>() { @Override public int compare(StringAndFile a, StringAndFile b) { long diff = a.file.lastModified() - b.file.lastModified(); return diff < 0 ? +1 : diff > 0 ? -1 : 0; } }; Collections.sort(upToDates, comparator); Collections.sort(obsoletes, comparator); Collections.sort(locallyModifieds, comparator); if (upToDates.size() > 0) pair = pickNewest(upToDates); else if (obsoletes.size() > 0) pair = pickNewest(obsoletes); else pair = pickNewest(locallyModifieds); if (locallyModifieds.size() > 0) addConflict(pair.path, "locally-modified", true, convert(locallyModifieds)); if (obsoletes.size() > 0) addConflict(pair.path, "obsolete", false, convert(obsoletes)); if (upToDates.size() > 0) addConflict(pair.path, "up-to-date", false, convert(upToDates)); } handle(pair); } protected static StringAndFile pickNewest(final List<StringAndFile> list) { int index = 0; if (list.size() > 1) { final String filename = list.get(0).path; if (filename.equals(FileObject.getFilename(filename, true))) index++; } final StringAndFile result = list.get(index); list.remove(index); return result; } protected static List<File> convert(final List<StringAndFile> pairs) { final List<File> result = new ArrayList<File>(); for (final StringAndFile pair : pairs) result.add(pair.file); return result; } protected void addConflict(final String filename, String adjective, boolean isCritical, final List<File> toDelete) { if (!adjective.equals("") && !adjective.endsWith(" ")) adjective += " "; String conflictMessage = "Multiple " + adjective + "versions of " + filename + " exist: " + UpdaterUtil.join(", ", toDelete); Resolution ignore = new Resolution("Ignore for now") { @Override public void resolve() { removeConflict(filename); } }; Resolution delete = new Resolution("Delete!") { @Override public void resolve() { for (final File file : toDelete) { if (!file.delete()) { final String prefix = files.prefix("").getAbsolutePath() + File.separator; final String absolute = file.getAbsolutePath(); if (absolute.startsWith(prefix)) try { FileObject.touch(files.prefixUpdate(absolute.substring(prefix .length()))); } catch (IOException e) { files.log.error(e); file.deleteOnExit(); } else { file.deleteOnExit(); } } } removeConflict(filename); } }; files.conflicts.add(new Conflict(isCritical ? Severity.CRITICAL_ERROR : Severity.ERROR, filename, conflictMessage, ignore, delete)); } protected void removeConflict(final String filename) { if (files.conflicts == null) return; Iterator<Conflict> iterator = files.conflicts.iterator(); while (iterator.hasNext()) { Conflict conflict = iterator.next(); if (conflict.filename.equals(filename)) { iterator.remove(); return; } } } protected void handle(final StringAndFile pair) { if (pair.checksum != null) { FileObject object = files.get(pair.path); if (object == null) { object = new FileObject(null, pair.path, pair.file.length(), pair.checksum, pair.timestamp, Status.LOCAL_ONLY); object.localFilename = pair.path; object.localChecksum = pair.checksum; object.localTimestamp = pair.timestamp; if ((!isWindows && UpdaterUtil.canExecute(pair.file)) || pair.path.endsWith(".exe")) object.executable = true; tryToGuessPlatform(object); files.add(object); } else { final FileObject.Version obsoletes = cachedChecksums.get(":" + pair.checksum); if (!object.hasPreviousVersion(pair.checksum)) { if (obsoletes != null) { for (final String obsolete : obsoletes.checksum.split(":")) { if (object.hasPreviousVersion(obsolete)) { pair.checksum = obsolete; break; } } } } else if (object.current != null && obsoletes != null && (":" + obsoletes.checksum + ":").indexOf(":" + object.current.checksum + ":") >= 0) { // if the recorded checksum is an obsolete equivalent of the current one, use the obsolete one pair.checksum = object.current.checksum; } object.setLocalVersion(pair.path, pair.checksum, pair.timestamp); if (object.getStatus() == Status.OBSOLETE_UNINSTALLED) object .setStatus(Status.OBSOLETE); } if (pair.path.endsWith((".jar"))) try { POMParser.fillMetadataFromJar(object, pair.file); } catch (Exception e) { files.log.error("Could not read pom.xml from " + pair.path); } } else { final FileObject object = files.get(pair.path); if (object != null) { switch (object.getStatus()) { case OBSOLETE: case OBSOLETE_MODIFIED: object.setStatus(Status.OBSOLETE_UNINSTALLED); break; case INSTALLED: case MODIFIED: case UPDATEABLE: object.setStatus(Status.NOT_INSTALLED); break; case LOCAL_ONLY: files.remove(pair.path); break; case NEW: case NOT_INSTALLED: case OBSOLETE_UNINSTALLED: // leave as-is break; default: throw new RuntimeException("Unhandled status!"); } } } } protected void handleQueue() { total = 0; for (final String unversioned : queue.keySet()) for (final StringAndFile pair : queue.get(unversioned)) total += (int) pair.file.length(); counter = 0; for (final String unversioned : queue.keySet()) handle(unversioned); done(); writeCachedChecksums(); } public void updateFromLocal(final List<String> files) { queue = new LinkedHashMap<String, List<StringAndFile>>(); for (final String file : files) queue(file); handleQueue(); } protected boolean tryToGuessPlatform(final FileObject file) { // Look for platform names as subdirectories of lib/ and mm/ String platform; if (file.executable) { platform = UpdaterUtil.platformForLauncher(file.filename); if (platform == null) return false; } else { if (file.filename.startsWith("lib/")) { platform = file.filename.substring(4); } else if (file.filename.startsWith("mm/")) { platform = file.filename.substring(3); } else return false; final int slash = platform.indexOf('/'); if (slash < 0) return false; platform = platform.substring(0, slash); } if (platform.equals("linux")) platform = "linux32"; for (final String valid : files.util.platforms) if (platform.equals(valid)) { file.addPlatform(platform); return true; } return false; } public static final String[][] directories = { { "jars", "retro", "misc" }, { ".jar", ".class" }, { "plugins" }, { ".jar", ".class", ".txt", ".ijm", ".py", ".rb", ".clj", ".js", ".bsh" }, { "scripts" }, { ".py", ".rb", ".clj", ".js", ".bsh", ".m" }, { "macros" }, { ".txt", ".ijm" }, { "luts" }, { ".lut" }, { "images" }, { ".png" }, { "Contents" }, { ".icns", ".plist" }, { "lib" }, { "" }, { "mm" }, { "" }, { "mmautofocus" }, { "" }, { "mmplugins" }, { "" } }; protected static final Map<String, Set<String>> extensions; static { extensions = new HashMap<String, Set<String>>(); for (int i = 0; i < directories.length; i += 2) { final Set<String> set = new HashSet<String>(); for (final String extension : directories[i + 1]) set.add(extension); for (final String dir : directories[i + 1]) extensions.put(dir, set); } } public boolean isCandidate(String path) { path = path.replace('\\', '/'); // Microsoft time toll final int slash = path.indexOf('/'); if (slash < 0) return files.util.isLauncher(path); final Set<String> exts = extensions.get(path.substring(0, slash)); final int dot = path.lastIndexOf('.'); return exts == null || dot < 0 ? false : exts.contains(path.substring(dot)); } protected void initializeQueue() { queue = new LinkedHashMap<String, List<StringAndFile>>(); queueIfExists("README.md"); queueIfExists("WELCOME.md"); queueIfExists("ImageJ.sh"); for (final String launcher : files.util.launchers) queueIfExists(launcher); for (int i = 0; i < directories.length; i += 2) queueDir(directories[i], directories[i + 1]); for (final FileObject file : files) if (!queue.containsKey(file.getFilename(true))) queue(file.getFilename()); } public void updateFromLocal() { initializeQueue(); handleQueue(); } protected void readCachedChecksums() { cachedChecksums = new TreeMap<String, FileObject.Version>(); final File file = files.prefix(".checksums"); if (!file.exists()) return; try { final BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) try { final int space = line.indexOf(' '); if (space < 0) continue; final String checksum = line.substring(0, space); final int space2 = line.indexOf(' ', space + 1); if (space2 < 0) continue; final long timestamp = Long.parseLong(line.substring(space + 1, space2)); final String filename = line.substring(space2 + 1); cachedChecksums.put(filename, new FileObject.Version(checksum, timestamp)); } catch (final NumberFormatException e) { /* ignore line */ } reader.close(); } catch (final IOException e) { // ignore } } protected void writeCachedChecksums() { if (cachedChecksums == null) return; final File file = files.prefix(".checksums"); // file.canWrite() not applicable, as the file need not exist try { final Writer writer = new FileWriter(file); for (final String filename : cachedChecksums.keySet()) if (filename.startsWith(":") || files.prefix(filename).exists()) { final FileObject.Version version = cachedChecksums.get(filename); writer.write(version.checksum + " " + version.timestamp + " " + filename + "\n"); } writer.close(); } catch (final IOException e) { // ignore } } protected String getDigest(final String path, final File file, final long timestamp) throws IOException, NoSuchAlgorithmException, ZipException { if (cachedChecksums == null) readCachedChecksums(); FileObject.Version version = cachedChecksums.get(path); if (version == null || timestamp != version.timestamp) { final String checksum = path.equals("plugins/Fiji_Updater.jar") ? UpdaterUtil.getJarDigest(file, false, false, false) : UpdaterUtil.getDigest(path, file); version = new FileObject.Version(checksum, timestamp); cachedChecksums.put(path, version); } if (!cachedChecksums.containsKey(":" + version.checksum)) { final List<String> obsoletes = UpdaterUtil.getObsoleteDigests(path, file); if (obsoletes != null) { final StringBuilder builder = new StringBuilder(); for (final String obsolete : obsoletes) { if (builder.length() > 0) builder.append(':'); builder.append(obsolete); } cachedChecksums.put(":" + version.checksum, new FileObject.Version( builder.toString(), timestamp)); } } return version.checksum; } }
package nl.pvanassen.ns; import java.util.Date; import nl.pvanassen.ns.model.stations.Stations; import nl.pvanassen.ns.model.storingen.Storingen; import nl.pvanassen.ns.model.vertrektijden.ActueleVertrekTijden; public class RequestBuilder { // Only one instance possible. Pre-instantiating this private static final StationsRequest INSTANCE = new StationsRequest(); /** * Hiding utility class constructor */ private RequestBuilder() { super(); } public static ApiRequest<ActueleVertrekTijden> getActueleVertrektijden(String station) { return new ActueleVertrekTijdenRequest(station); } public static ApiRequest<Stations> getStations() { return INSTANCE; } /** * Builds a request to return all 'Actuele storingen' * * @return All 'Actuele storingen' request */ public static ApiRequest<Storingen> getActueleStoringen() { return new StoringenEnWerkzaamhedenRequest(null, Boolean.TRUE, null); } /** * Builds a request that will return all 'Geplande werkzaamheden' * * @return All 'Geplanden werkzaamheden' request */ public static ApiRequest<Storingen> getGeplandeWerkzaamheden() { return new StoringenEnWerkzaamhedenRequest(null, null, Boolean.TRUE); } /** * Builds a request that will return all 'Geplande werkzaamheden' * * @return All 'Geplanden werkzaamheden' request */ public static ApiRequest<Storingen> getActueleStoringen(String station) { return new StoringenEnWerkzaamhedenRequest(station, null, null); } public static ReisadviesRequestBuilder getReisadviesRequestBuilder(String fromStation, String toStation) { return new ReisadviesRequestBuilder(fromStation, toStation); } public static class ReisadviesRequestBuilder { private final String fromStation; private final String toStation; private String viaStation; private Integer previousAdvices; private Integer nextAdvices; private Date dateTime; private Boolean departure; private Boolean hslAllowed; private Boolean yearCard; ReisadviesRequestBuilder(String fromStation, String toStation) { this.fromStation = fromStation; this.toStation = toStation; } public ReisadviesRequestBuilder viaStation(String station) { this.viaStation = station; return this; } public ReisadviesRequestBuilder forDepartureTime(Date dateTime) { if (this.dateTime != null) { throw new IllegalArgumentException("Cannot set departure time, arival time already set"); } this.dateTime = dateTime; this.departure = true; return this; } public ReisadviesRequestBuilder forArivalTime(Date dateTime) { if (this.dateTime != null) { throw new IllegalArgumentException("Cannot set arival time, departure time already set"); } this.dateTime = dateTime; this.departure = false; return this; } public ReisadviesRequestBuilder includePastAdvices(int previousAdvices) { this.previousAdvices = previousAdvices; return this; } public ReisadviesRequestBuilder includeFutureAdvices(int nextAdvices) { this.nextAdvices = nextAdvices; return this; } public ReisadviesRequestBuilder withHsl() { this.hslAllowed = Boolean.TRUE; return this; } public ReisadviesRequestBuilder withoutHsl() { this.hslAllowed = Boolean.FALSE; return this; } public ReisadviesRequestBuilder userHasYearCard() { this.yearCard = Boolean.TRUE; return this; } public ReisadviesRequestBuilder userHasNoYearCard() { this.yearCard = Boolean.FALSE; return this; } public ReisadviesRequest build() { return new ReisadviesRequest(fromStation, toStation, viaStation, previousAdvices, nextAdvices, dateTime, departure, hslAllowed, yearCard); } } }
package org.amc.dao; import org.amc.DAOException; import org.amc.game.chessserver.ServerChessGame; import org.amc.game.chessserver.observers.ObserverFactoryChain; import org.apache.log4j.Logger; import java.util.HashSet; import java.util.Set; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; /** * A DAO for ServerChessGames persisted to a database * * @author Adrian Mclaughlin * */ public class ServerChessGameDAO extends DAO<ServerChessGame> { private static final Logger logger = Logger.getLogger(ServerChessGameDAO.class); private static final String GET_SERVERCHESSGAME_QUERY = "serverChessGameByUid"; private static final String NATIVE_OBSERVERS_QUERY = "Select uid,observers from serverChessGames where uid = ?1"; private ObserverFactoryChain chain; public ServerChessGameDAO() { super(ServerChessGame.class); } public Set<Long> getGameUids() { EntityManager entityManager = getEntityManager(); Query query = entityManager.createQuery("Select x.uid from " + getEntityClass().getSimpleName() + " x ORDER BY x.uid"); Set<Long> gameUidsSet = new HashSet<Long>(query.getResultList()); return gameUidsSet; } private void addObservers(ServerChessGame serverChessGame) throws DAOException { EntityManager entityManager = getEntityManager(); if(serverChessGame.getNoOfObservers() == 0) { Query query = entityManager.createNativeQuery(NATIVE_OBSERVERS_QUERY, SCGObservers.class); query.setParameter(1, serverChessGame.getUid()); try { SCGObservers scgObervers = (SCGObservers)query.getSingleResult(); chain.addObserver(scgObervers.getObservers(), serverChessGame); } catch(NoResultException nre) { logger.error(nre); } } } /** * * @param uid unique identifier of the ServerChessGame to be retrieved * @return ServerChessGame with Observers attached * @throws DAOException if the ServerChessGame can't be retrieved */ public ServerChessGame getServerChessGame(long uid) throws DAOException { EntityManager entityManager = getEntityManager(); Query query = entityManager.createNamedQuery(GET_SERVERCHESSGAME_QUERY); query.setParameter(1, uid); ServerChessGame scg = null; try { scg = (ServerChessGame)query.getSingleResult(); addObservers(scg); return scg; } catch(NoResultException nre) { logger.error(nre); } return scg; } @Resource(name="defaultObserverFactoryChain") public void setObserverFactoryChain(ObserverFactoryChain chain) { this.chain = chain; } /** * Helper Class to retrieve the list of observers in String * format in the database * @author Adrian Mclaughlin * */ public static class SCGObservers { private String observers; private Long uid; public String getObservers() { return observers; } public Long getUid() { return uid; } public void setObservers(String observers) { this.observers = observers; } public void setUid(Long uid) { this.uid = uid; } } }
package org.apdplat.word; import java.io.*; import java.nio.charset.Charset; import java.util.*; import org.apdplat.word.segmentation.SegmentationAlgorithm; import org.apdplat.word.segmentation.SegmentationFactory; import org.apdplat.word.recognition.StopWord; import org.apdplat.word.segmentation.Word; import org.apdplat.word.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * * * @author */ public class WordSegmenter { private static final Logger LOGGER = LoggerFactory.getLogger(WordSegmenter.class); /** * * * @param text * @param segmentationAlgorithm * @return */ public static List<Word> segWithStopWords(String text, SegmentationAlgorithm segmentationAlgorithm){ return SegmentationFactory.getSegmentation(segmentationAlgorithm).seg(text); } /** * * * @param text * @return */ public static List<Word> segWithStopWords(String text){ return SegmentationFactory.getSegmentation(SegmentationAlgorithm.MaxNgramScore).seg(text); } /** * * * @param text * @param segmentationAlgorithm * @return */ public static List<Word> seg(String text, SegmentationAlgorithm segmentationAlgorithm){ List<Word> words = SegmentationFactory.getSegmentation(segmentationAlgorithm).seg(text); StopWord.filterStopWords(words); return words; } /** * * * @param text * @return */ public static List<Word> seg(String text){ List<Word> words = SegmentationFactory.getSegmentation(SegmentationAlgorithm.MaxNgramScore).seg(text); StopWord.filterStopWords(words); return words; } /** * * * @param input * @param output * @param segmentationAlgorithm * @throws Exception */ public static void segWithStopWords(File input, File output, SegmentationAlgorithm segmentationAlgorithm) throws Exception{ Utils.seg(input, output, false, segmentationAlgorithm); } /** * * * @param input * @param output * @throws Exception */ public static void segWithStopWords(File input, File output) throws Exception{ Utils.seg(input, output, false, SegmentationAlgorithm.MaxNgramScore); } /** * * * @param input * @param output * @param segmentationAlgorithm * @throws Exception */ public static void seg(File input, File output, SegmentationAlgorithm segmentationAlgorithm) throws Exception{ Utils.seg(input, output, true, segmentationAlgorithm); } /** * * * @param input * @param output * @throws Exception */ public static void seg(File input, File output) throws Exception{ Utils.seg(input, output, true, SegmentationAlgorithm.MaxNgramScore); } private static void demo(){ long start = System.currentTimeMillis(); List<String> sentences = new ArrayList<>(); sentences.add("APDPlat"); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(","); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add("wordysc"); sentences.add(",,,, google,"); sentences.add("24"); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); sentences.add(""); int i=1; for(String sentence : sentences){ List<Word> words = segWithStopWords(sentence); LOGGER.info((i++)+": "+sentence); LOGGER.info(" "+words); } long cost = System.currentTimeMillis() - start; LOGGER.info(": "+cost+" "); } public static void processCommand(String... args) { if(args == null || args.length < 1){ LOGGER.info(""); return; } try{ switch(args[0].trim().charAt(0)){ case 'd': demo(); break; case 't': if(args.length < 2){ showUsage(); }else{ StringBuilder str = new StringBuilder(); for(int i=1; i<args.length; i++){ str.append(args[i]).append(" "); } List<Word> words = segWithStopWords(str.toString()); LOGGER.info(""+str.toString()); LOGGER.info(""+words.toString()); } break; case 'f': if(args.length != 3){ showUsage(); }else{ segWithStopWords(new File(args[1]), new File(args[2])); } break; default: StringBuilder str = new StringBuilder(); for(String a : args){ str.append(a).append(" "); } List<Word> words = segWithStopWords(str.toString()); LOGGER.info(""+str.toString()); LOGGER.info(""+words.toString()); break; } }catch(Exception e){ showUsage(); } } private static void run(String encoding) { try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, encoding))){ String line = null; while((line = reader.readLine()) != null){ if("exit".equals(line)){ System.exit(0); LOGGER.info(""); return; } if(line.trim().equals("")){ continue; } processCommand(line.split(" ")); showUsage(); } } catch (IOException ex) { LOGGER.error("", ex); } } private static void showUsage(){ LOGGER.info(""); LOGGER.info("********************************************"); LOGGER.info(": command [text] [input] [output]"); LOGGER.info("commanddemotextfile"); LOGGER.info("d t ftext"); LOGGER.info("demo"); LOGGER.info("text APDPlat"); LOGGER.info("file d:/text.txt d:/word.txt"); LOGGER.info("exit"); LOGGER.info("********************************************"); LOGGER.info(""); } public static void main(String[] args) { String encoding = "utf-8"; if(args==null || args.length == 0){ showUsage(); run(encoding); }else if(Charset.isSupported(args[0])){ showUsage(); run(args[0]); }else{ processCommand(args); //JVM System.exit(0); } } }
package org.gitlab4j.api.models; import java.util.Date; import java.util.List; import org.gitlab4j.api.utils.JacksonJson; public class Commit { private Author author; private Date authoredDate; private String authorEmail; private String authorName; private Date committedDate; private String committerEmail; private String committerName; private Date createdAt; private String id; private String message; private List<String> parentIds; private String shortId; private CommitStats stats; private String status; private Date timestamp; private String title; private String url; private Pipeline lastPipeline; public Author getAuthor() { return author; } public void setAuthor(Author author) { this.author = author; } public Date getAuthoredDate() { return authoredDate; } public void setAuthoredDate(Date authoredDate) { this.authoredDate = authoredDate; } public String getAuthorEmail() { return authorEmail; } public void setAuthorEmail(String authorEmail) { this.authorEmail = authorEmail; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public Date getCommittedDate() { return committedDate; } public void setCommittedDate(Date committedDate) { this.committedDate = committedDate; } public String getCommitterEmail() { return committerEmail; } public void setCommitterEmail(String committerEmail) { this.committerEmail = committerEmail; } public String getCommitterName() { return committerName; } public void setCommitterName(String committerName) { this.committerName = committerName; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<String> getParentIds() { return parentIds; } public void setParentIds(List<String> parentIds) { this.parentIds = parentIds; } public String getShortId() { return shortId; } public void setShortId(String shortId) { this.shortId = shortId; } public CommitStats getStats() { return stats; } public void setStats(CommitStats stats) { this.stats = stats; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Pipeline getLastPipeline() { return lastPipeline; } public void setLastPipeline(Pipeline lastPipeline) { this.lastPipeline = lastPipeline; } public Commit withAuthor(Author author) { this.author = author; return this; } public Commit withAuthoredDate(Date authoredDate) { this.authoredDate = authoredDate; return this; } public Commit withAuthorEmail(String authorEmail) { this.authorEmail = authorEmail; return this; } public Commit withAuthorName(String authorName) { this.authorName = authorName; return this; } public Commit withCommittedDate(Date committedDate) { this.committedDate = committedDate; return this; } public Commit withCommitterEmail(String committerEmail) { this.committerEmail = committerEmail; return this; } public Commit withCommitterName(String committerName) { this.committerName = committerName; return this; } public Commit withCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public Commit withId(String id) { this.id = id; return this; } public Commit withMessage(String message) { this.message = message; return this; } public Commit withParentIds(List<String> parentIds) { this.parentIds = parentIds; return this; } public Commit withShorwId(String shortId) { this.shortId = shortId; return this; } public Commit withStats(CommitStats stats) { this.stats = stats; return this; } public Commit withStatus(String status) { this.status = status; return this; } public Commit withTimestamp(Date timestamp) { this.timestamp = timestamp; return this; } public Commit withTitle(String title) { this.title = title; return this; } public Commit withUrl(String url) { this.url = url; return this; } @Override public String toString() { return (JacksonJson.toJsonString(this)); } }
package org.jbake.launcher; import java.io.File; import java.net.MalformedURLException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.configuration.CompositeConfiguration; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.resource.Resource; import org.jbake.app.ConfigUtil.Keys; import org.jbake.app.Oven; import org.jbake.app.Renderer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides Jetty server related functions * * @author Jonathan Bullock <jonbullock@gmail.com> * */ public class JettyServer { private final static Logger LOGGER = LoggerFactory.getLogger(JettyServer.class); /** * Run Jetty web server serving out supplied path on supplied port * * @param path * @param port */ public static void run(String path, String port, Oven oven) { // Initi database. oven.crawl(); watch(oven); Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(Integer.parseInt(port)); server.addConnector(connector); ServletContextHandler servletHandler = new ServletContextHandler(null, "/", true, false); CompositeConfiguration config = oven.getConfig(); if (config.getBoolean(Keys.RENDER_INDEX)) { String uri = uri(config.getString(Keys.INDEX_FILE)); servletHandler.addServlet(new ServletHolder(new IndexServlet(oven)), "/" + uri); } if (config.getBoolean(Keys.RENDER_TAGS)) { String tagUri = uri(config.getString(Keys.TAG_PATH)); servletHandler.addServlet(new ServletHolder(new TagServlet(oven)), "/" + tagUri); } if (config.getBoolean(Keys.RENDER_ARCHIVE)) { String uri = uri(config.getString(Keys.ARCHIVE_FILE)); servletHandler.addServlet(new ServletHolder(new ArchiveServlet(oven)), "/" + uri); } if (config.getBoolean(Keys.RENDER_FEED)) { String uri = uri(config.getString(Keys.FEED_FILE)); servletHandler.addServlet(new ServletHolder(new FeedServlet(oven)), "/" + uri); } if (config.getBoolean(Keys.RENDER_SITEMAP)) { String uri = uri(config.getString(Keys.SITEMAP_FILE)); servletHandler.addServlet(new ServletHolder(new SitemapServlet(oven)), "/" + uri); } DefaultServlet sourceServlet = new DefaultServlet(); ServletHolder sourceHolder = new ServletHolder(sourceServlet); sourceHolder.setInitParameter("resourceBase", oven.getContentsPath().getAbsolutePath()); sourceHolder.setInitParameter("pathInfoOnly", "true"); sourceHolder.setInitParameter("cacheControl", "public, max-age=0, s-maxage=0"); /** * Reset the {@link Renderer} whenever the templates change in the filesystem. * * <p> * Note: With Java 7, this could be formulated more efficiently using the Path API. * </p> * * @param oven The {@link Oven} to watch. */ private static void watch(final Oven oven) { Thread watcher = new Thread("Filesystem watcher") { long _timestamp = System.currentTimeMillis(); @Override public void run() { while (true) { if (check(oven.getTemplatesPath())) { LOGGER.info("Templates changed, resetting renderer."); _timestamp = System.currentTimeMillis(); oven.resetRenderer(); } try { Thread.sleep(3000); } catch (InterruptedException ex) { break; } } } private boolean check(File path) { for (File file : path.listFiles()) { if (file.getName().startsWith(".")) { continue; } if (file.isDirectory()) { if (check(file)) { return true; } } else { long lastModified = file.lastModified(); if (lastModified > _timestamp) { return true; } } } return false; } }; watcher.setDaemon(true); watcher.start(); } private static String uri(String path) { return path.replace('\\', '/'); } }
package org.jsapar.convert; import org.jsapar.compose.Composer; import org.jsapar.concurrent.ConcurrentConsumer; import org.jsapar.error.JSaParException; import org.jsapar.model.Line; import org.jsapar.parse.ParseTask; import java.io.IOException; import java.io.UncheckedIOException; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Function; /** * Reads from supplied parseTask and outputs each line to the composer. By adding * a transformer you are able to make modifications of each line before it is written to the * output. * <p> * For each line, the line type of the parsed line is * considered when choosing the line type of the output schema line. This means that lines with a * type that does not exist in the output schema will be discarded in the output. */ public class ConvertTask { private ParseTask parseTask; /** * Creates a convert task with supplied parse task and composer. * @param parseTask The parse task to use. * @param composer The composer to use. * @param errorConsumer The error consumer to use. */ protected ConvertTask(ParseTask parseTask, Composer composer, Consumer<Line> lineConsumer, Consumer<JSaParException> errorConsumer) { Objects.requireNonNull(parseTask); Objects.requireNonNull(composer); Objects.requireNonNull(lineConsumer); Objects.requireNonNull(errorConsumer); this.parseTask = parseTask; this.parseTask.setLineConsumer(lineConsumer); this.parseTask.setErrorConsumer(errorConsumer); composer.setErrorConsumer(errorConsumer); } public static ConvertTask of(ParseTask parseTask, Composer composer, Consumer<JSaParException> errorConsumer){ return new ConvertTask(parseTask, composer, composer::composeLine, errorConsumer); } public static ConvertTask of(ParseTask parseTask, Composer composer, Consumer<JSaParException> errorConsumer, List<LineManipulator> lineManipulators){ Objects.requireNonNull(lineManipulators, "Transformer cannot be null"); return new ConvertTask(parseTask, composer, makeManipulateAndComposeConsumer(composer, lineManipulators), errorConsumer); } public static Consumer<Line> makeManipulateAndComposeConsumer(Composer composer, List<LineManipulator> lineManipulators) { if(lineManipulators.isEmpty()){ return composer::composeLine; } if(lineManipulators.size() == 1){ final LineManipulator manipulator = lineManipulators.get(0); return line->{ if(manipulator.manipulate(line)) composer.composeLine(line); }; } return line->{ for (LineManipulator manipulator : lineManipulators) { if (!manipulator.manipulate(line)) return; } composer.composeLine(line); }; } public static ConvertTask of(ParseTask parseTask, Composer composer, Consumer<JSaParException> errorConsumer, Function<Line, List<Line>> transformer){ Objects.requireNonNull(transformer, "Transformer cannot be null"); return new ConvertTask(parseTask, composer, line-> transformer.apply(line).forEach(composer::composeLine), errorConsumer); } /** * @return Number of converted lines. * @throws IOException In case of IO error. */ public long execute() throws IOException { try { return parseTask.execute(); }catch (UncheckedIOException e){ throw e.getCause() != null ? e.getCause() : new IOException(e); } } public ParseTask getParseTask() { return parseTask; } }
package org.jsoup.select; import org.jsoup.helper.Validate; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.select.NodeFilter.FilterResult; /** * Depth-first node traversor. Use to iterate through all nodes under and including the specified root node. * <p> * This implementation does not use recursion, so a deep DOM does not risk blowing the stack. * </p> */ public class NodeTraversor { private NodeVisitor visitor; /** * Create a new traversor. * @param visitor a class implementing the {@link NodeVisitor} interface, to be called when visiting each node. * @deprecated Just use the static {@link NodeTraversor#filter(NodeFilter, Node)} method. */ public NodeTraversor(NodeVisitor visitor) { this.visitor = visitor; } /** * Start a depth-first traverse of the root and all of its descendants. * @param root the root node point to traverse. * @deprecated Just use the static {@link NodeTraversor#filter(NodeFilter, Node)} method. */ public void traverse(Node root) { traverse(visitor, root); } /** * Start a depth-first traverse of the root and all of its descendants. * @param visitor Node visitor. * @param root the root node point to traverse. */ public static void traverse(NodeVisitor visitor, Node root) { Node node = root; int depth = 0; while (node != null) { visitor.head(node, depth); if (node.childNodeSize() > 0) { node = node.childNode(0); depth++; } else { while (node.nextSibling() == null && depth > 0) { visitor.tail(node, depth); node = node.parentNode(); depth } visitor.tail(node, depth); if (node == root) break; node = node.nextSibling(); } } } /** * Start a depth-first traverse of all elements. * @param visitor Node visitor. * @param elements Elements to filter. */ public static void traverse(NodeVisitor visitor, Elements elements) { Validate.notNull(visitor); Validate.notNull(elements); for (Element el : elements) traverse(visitor, el); } /** * Start a depth-first filtering of the root and all of its descendants. * @param filter Node visitor. * @param root the root node point to traverse. * @return The filter result of the root node, or {@link FilterResult#STOP}. */ public static FilterResult filter(NodeFilter filter, Node root) { Node node = root; int depth = 0; while (node != null) { FilterResult result = filter.head(node, depth); if (result == FilterResult.STOP) return result; // Descend into child nodes: if (result == FilterResult.CONTINUE && node.childNodeSize() > 0) { node = node.childNode(0); ++depth; continue; } // No siblings, move upwards: while (node.nextSibling() == null && depth > 0) { // 'tail' current node: if (result == FilterResult.CONTINUE || result == FilterResult.SKIP_CHILDREN) { result = filter.tail(node, depth); if (result == FilterResult.STOP) return result; } Node prev = node; // In case we need to remove it below. node = node.parentNode(); depth if (result == FilterResult.REMOVE) prev.remove(); // Remove AFTER finding parent. result = FilterResult.CONTINUE; // Parent was not pruned. } // 'tail' current node, then proceed with siblings: if (result == FilterResult.CONTINUE || result == FilterResult.SKIP_CHILDREN) { result = filter.tail(node, depth); if (result == FilterResult.STOP) return result; } if (node == root) return result; Node prev = node; // In case we need to remove it below. node = node.nextSibling(); if (result == FilterResult.REMOVE) prev.remove(); // Remove AFTER finding sibling. } // root == null? return FilterResult.CONTINUE; } /** * Start a depth-first filtering of all elements. * @param filter Node filter. * @param elements Elements to filter. */ public static void filter(NodeFilter filter, Elements elements) { Validate.notNull(filter); Validate.notNull(elements); for (Element el : elements) if (filter(filter, el) == FilterResult.STOP) break; } }
package org.lightmare.jpa; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import org.lightmare.utils.StringUtils; import org.lightmare.utils.fs.codecs.ArchiveUtils; /** * For getting resources from persistence.xml path * * @author Levan * @since 0.0.16-SNAPSHOT */ public class ConfigLoader { //Path for ORM configuration file public static final String XML_PATH = "META-INF/persistence.xml"; private String shortPath; public String getShortPath() { return shortPath; } /** * Converts passed to {@link Enumeration} to build persistence configuration * * @see Ejb3ConfigurationImpl#configure(String, java.util.Map) * * @param path * @return Enumeration<{@link URL}> * @throws IOException */ public Enumeration<URL> readURL(final URL url) { Enumeration<URL> xmls = new Enumeration<URL>() { private boolean nextElement = Boolean.TRUE; @Override public boolean hasMoreElements() { return nextElement; } @Override public URL nextElement() { nextElement = Boolean.FALSE; return url; } }; shortPath = StringUtils .concat(ArchiveUtils.ARCHIVE_URL_DELIM, XML_PATH); return xmls; } /** * Reads {@link URL} from passed path {@link String} for build persistence * configuration * * @see Ejb3ConfigurationImpl#configure(String, java.util.Map) * * @param path * @return Enumeration<{@link URL} > * @throws IOException */ public Enumeration<URL> readFile(String path) throws IOException { if (path == null || path.isEmpty()) { throw new IOException( String.format("path is not provided %s", path)); } File file = new File(path); if (!file.exists()) { throw new IOException(String.format( "could not find persistence.xml file at path %s", path)); } shortPath = file.getName(); final URL url = file.toURI().toURL(); Enumeration<URL> xmls = readURL(url); return xmls; } }
package org.myrobotlab.service; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.io.FilenameUtils; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.Status; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.inmoov.Utils; import org.myrobotlab.inmoov.Vision; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.opencv.OpenCVData; import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis.Voice; import org.myrobotlab.service.data.JoystickData; import org.myrobotlab.service.data.Locale; import org.myrobotlab.service.data.Pin; import org.myrobotlab.service.interfaces.JoystickListener; import org.myrobotlab.service.interfaces.PinArrayControl; import org.myrobotlab.service.interfaces.LocaleProvider; import org.myrobotlab.service.interfaces.ServoControl; import org.myrobotlab.service.interfaces.Simulator; import org.myrobotlab.service.interfaces.SpeechRecognizer; import org.myrobotlab.service.interfaces.SpeechSynthesis; import org.myrobotlab.service.interfaces.TextListener; import org.myrobotlab.service.interfaces.TextPublisher; import org.slf4j.Logger; public class InMoov2 extends Service implements TextListener, TextPublisher, JoystickListener, LocaleProvider { public final static Logger log = LoggerFactory.getLogger(InMoov2.class); public static LinkedHashMap<String, String> lpVars = new LinkedHashMap<String, String>(); // FIXME - why static boolean RobotCanMoveRandom = true; private static final long serialVersionUID = 1L; static String speechRecognizer = "WebkitSpeechRecognition"; /** * This static method returns all the details of the class without it having to * be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(InMoov2.class); meta.addDescription("InMoov2 Service"); meta.addCategory("robot"); meta.sharePeer("mouthControl.mouth", "mouth", "MarySpeech", "shared Speech"); meta.addPeer("eye", "OpenCV", "eye"); meta.addPeer("servomixer", "ServoMixer", "for making gestures"); meta.addPeer("ultraSonicRight", "UltrasonicSensor", "measure distance"); meta.addPeer("ultraSonicLeft", "UltrasonicSensor", "measure distance"); meta.addPeer("pir", "Pir", "infrared sensor"); // the two legacy controllers .. :( meta.addPeer("left", "Arduino", "legacy controller"); meta.addPeer("right", "Arduino", "legacy controller"); meta.addPeer("controller3", "Arduino", "legacy controller"); meta.addPeer("controller4", "Arduino", "legacy controller"); meta.addPeer("htmlFilter", "HtmlFilter", "filter speaking html"); meta.addPeer("brain", "ProgramAB", "brain"); meta.addPeer("simulator", "JMonkeyEngine", "simulator"); meta.addPeer("head", "InMoov2Head", "head"); meta.addPeer("torso", "InMoov2Torso", "torso"); // meta.addPeer("eyelids", "InMoovEyelids", "eyelids"); meta.addPeer("leftArm", "InMoov2Arm", "left arm"); meta.addPeer("leftHand", "InMoov2Hand", "left hand"); meta.addPeer("rightArm", "InMoov2Arm", "right arm"); meta.addPeer("rightHand", "InMoov2Hand", "right hand"); meta.addPeer("mouthControl", "MouthControl", "MouthControl"); // meta.addPeer("imageDisplay", "ImageDisplay", "image display service"); meta.addPeer("mouth", "MarySpeech", "InMoov speech service"); meta.addPeer("ear", speechRecognizer, "InMoov webkit speech recognition service"); meta.addPeer("headTracking", "Tracking", "Head tracking system"); meta.sharePeer("headTracking.opencv", "eye", "OpenCV", "shared head OpenCV"); // meta.sharePeer("headTracking.controller", "left", "Arduino", "shared head // Arduino"); NO !!!! meta.sharePeer("headTracking.x", "head.rothead", "Servo", "shared servo"); meta.sharePeer("headTracking.y", "head.neck", "Servo", "shared servo"); // Global - undecorated by self name meta.addRootPeer("python", "Python", "shared Python service"); // latest - not ready until repo is ready meta.addDependency("fr.inmoov", "inmoov2", null, "zip"); return meta; } /** * This method will load a python file into the python interpreter. */ public static boolean loadFile(String file) { File f = new File(file); Python p = (Python) Runtime.getService("python"); log.info("Loading Python file {}", f.getAbsolutePath()); if (p == null) { log.error("Python instance not found"); return false; } String script = null; try { script = FileIO.toString(f.getAbsolutePath()); } catch (IOException e) { log.error("IO Error loading file : ", e); return false; } // evaluate the scripts in a blocking way. boolean result = p.exec(script, true); if (!result) { log.error("Error while loading file {}", f.getAbsolutePath()); return false; } else { log.debug("Successfully loaded {}", f.getAbsolutePath()); } return true; } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); Platform.setVirtual(true); // Runtime.main(new String[] { "--install", "InMoov2" }); // Runtime.main(new String[] { "--interactive", "--id", "inmoov", // "--install-dependency","fr.inmoov", "inmoov2", "latest", "zip"}); Runtime.main(new String[] { "--resource-override", "InMoov2=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/InMoov2", "WebGui=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/WebGui", "ProgramAB=/lhome/grperry/github/mrl.develop/myrobotlab/src/main/resources/resource/InMoov2/resource/ProgramAB", "--interactive", "--id", "inmoov" }); String[] langs = java.util.Locale.getISOLanguages(); java.util.Locale[] locales = java.util.Locale.getAvailableLocales(); log.info("{}", locales.length); for (java.util.Locale l : locales) { log.info(" log.info(CodecUtils.toJson(l)); log.info(l.getDisplayLanguage()); log.info(l.getLanguage()); log.info(l.getCountry()); log.info(l.getDisplayCountry()); log.info(CodecUtils.toJson(new Locale(l))); if (l.getLanguage().equals("en")) { log.info("here"); } } InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2"); WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui"); webgui.autoStartBrowser(false); webgui.startService(); boolean done = true; if (done) { return; } i01.startBrain(); i01.startAll("COM3", "COM4"); Runtime.start("python", "Python"); // Runtime.start("log", "Log"); /* * OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV"); cv.setCameraIndex(2); */ // i01.startSimulator(); /* * Arduino mega = (Arduino) Runtime.start("mega", "Arduino"); * mega.connect("/dev/ttyACM0"); */ } catch (Exception e) { log.error("main threw", e); } } boolean autoStartBrowser = false; transient ProgramAB brain; Set<String> configs = null; String currentConfigurationName = "default"; transient SpeechRecognizer ear; transient OpenCV eye; transient Tracking eyesTracking; // waiting controable threaded gestures we warn user boolean gestureAlreadyStarted = false; // FIXME - what the hell is this for ? Set<String> gestures = new TreeSet<String>(); transient InMoov2Head head; transient Tracking headTracking; transient HtmlFilter htmlFilter; transient UltrasonicSensor ultraSonicRight; transient UltrasonicSensor ultraSonicLeft; transient Pir pir; private PinArrayControl pirArduino; public Integer pirPin = null; // transient ImageDisplay imageDisplay; /** * simple booleans to determine peer state of existence FIXME - should be an * auto-peer variable */ boolean isBrainActivated = false; boolean isEarActivated = false; boolean isEyeActivated = false; boolean isEyeLidsActivated = false; boolean isHeadActivated = false; boolean isLeftArmActivated = false; boolean isLeftHandActivated = false; boolean isMouthActivated = false; boolean isRightArmActivated = false; boolean isRightHandActivated = false; boolean isSimulatorActivated = false; boolean isTorsoActivated = false; boolean isNeopixelActivated = false; boolean isPirActivated = false; boolean isUltraSonicRightActivated = false; boolean isUltraSonicLeftActivated = false; boolean isServoMixerActivated = false; // TODO - refactor into a Simulator interface when more simulators are borgd transient JMonkeyEngine jme; String lastGestureExecuted; Long lastPirActivityTime; transient InMoov2Arm leftArm; // transient LanguagePack languagePack = new LanguagePack(); // transient InMoovEyelids eyelids; eyelids are in the head transient InMoov2Hand leftHand; Locale locale; /** * supported locales */ Map<String, Locale> locales = null; int maxInactivityTimeSeconds = 120; transient SpeechSynthesis mouth; // FIXME ugh - new MouthControl service that uses AudioFile output transient public MouthControl mouthControl; boolean mute = false; transient NeoPixel neopixel; transient ServoMixer servomixer; transient Python python; transient InMoov2Arm rightArm; transient InMoov2Hand rightHand; /** * used to remember/serialize configuration the user's desired speech type */ String speechService = "MarySpeech"; transient InMoov2Torso torso; @Deprecated public Vision vision; // FIXME - remove all direct references // transient private HashMap<String, InMoov2Arm> arms = new HashMap<>(); protected List<Voice> voices = null; protected String voiceSelected; transient WebGui webgui; public InMoov2(String n, String id) { super(n, id); // by default all servos will auto-disable Servo.setAutoDisableDefault(true); locales = Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN", "it-IT", "fi-FI", "pt-PT"); locale = Runtime.getInstance().getLocale(); python = (Python) startPeer("python"); load(locale.getTag()); // get events of new services and shutdown Runtime r = Runtime.getInstance(); subscribe(r.getName(), "shutdown"); listConfigFiles(); // FIXME - Framework should auto-magically auto-start peers AFTER // construction - unless explicitly told not to // peers to start on construction // imageDisplay = (ImageDisplay) startPeer("imageDisplay"); } @Override /* local strong type - is to be avoided - use name string */ public void addTextListener(TextListener service) { // CORRECT WAY ! - no direct reference - just use the name in a subscription addListener("publishText", service.getName()); } @Override public void attachTextListener(TextListener service) { addListener("publishText", service.getName()); } public void attachTextPublisher(String name) { subscribe(name, "publishText"); } @Override public void attachTextPublisher(TextPublisher service) { subscribe(service.getName(), "publishText"); } public void beginCheckingOnInactivity() { beginCheckingOnInactivity(maxInactivityTimeSeconds); } public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) { this.maxInactivityTimeSeconds = maxInactivityTimeSeconds; // speakBlocking("power down after %s seconds inactivity is on", // this.maxInactivityTimeSeconds); log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds); addTask("checkInactivity", 5 * 1000, 0, "checkInactivity"); } public long checkInactivity() { // speakBlocking("checking"); long lastActivityTime = getLastActivityTime(); long now = System.currentTimeMillis(); long inactivitySeconds = (now - lastActivityTime) / 1000; if (inactivitySeconds > maxInactivityTimeSeconds) { // speakBlocking("%d seconds have passed without activity", // inactivitySeconds); powerDown(); } else { // speakBlocking("%d seconds have passed without activity", // inactivitySeconds); info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds); } return lastActivityTime; } public void closeAllImages() { // imageDisplay.closeAll(); log.error("implement webgui.closeAllImages"); } public void cycleGestures() { // if not loaded load - // FIXME - this needs alot of "help" :P // WHY IS THIS DONE ? if (gestures.size() == 0) { loadGestures(); } for (String gesture : gestures) { try { String methodName = gesture.substring(0, gesture.length() - 3); speakBlocking(methodName); log.info("executing gesture {}", methodName); python.eval(methodName + "()"); // wait for finish - or timeout ? } catch (Exception e) { error(e); } } } public void disable() { if (head != null) { head.disable(); } if (rightHand != null) { rightHand.disable(); } if (leftHand != null) { leftHand.disable(); } if (rightArm != null) { rightArm.disable(); } if (leftArm != null) { leftArm.disable(); } if (torso != null) { torso.disable(); } } public void displayFullScreen(String src) { try { // imageDisplay.displayFullScreen(src); log.error("implement webgui.displayFullScreen"); } catch (Exception e) { error("could not display picture %s", src); } } public void enable() { if (head != null) { head.enable(); } if (rightHand != null) { rightHand.enable(); } if (leftHand != null) { leftHand.enable(); } if (rightArm != null) { rightArm.enable(); } if (leftArm != null) { leftArm.enable(); } if (torso != null) { torso.enable(); } } /** * This method will try to launch a python command with error handling */ public String execGesture(String gesture) { lastGestureExecuted = gesture; if (python == null) { log.warn("execGesture : No jython engine..."); return null; } subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); startedGesture(lastGestureExecuted); return python.evalAndWait(gesture); } public void finishedGesture() { finishedGesture("unknown"); } public void finishedGesture(String nameOfGesture) { if (gestureAlreadyStarted) { waitTargetPos(); RobotCanMoveRandom = true; gestureAlreadyStarted = false; log.info("gesture : {} finished...", nameOfGesture); } } public void fullSpeed() { if (head != null) { head.fullSpeed(); } if (rightHand != null) { rightHand.fullSpeed(); } if (leftHand != null) { leftHand.fullSpeed(); } if (rightArm != null) { rightArm.fullSpeed(); } if (leftArm != null) { leftArm.fullSpeed(); } if (torso != null) { torso.fullSpeed(); } } public String get(String param) { if (lpVars.containsKey(param.toUpperCase())) { return lpVars.get(param.toUpperCase()); } return "not yet translated"; } public InMoov2Arm getArm(String side) { if ("left".equals(side)) { return leftArm; } else if ("right".equals(side)) { return rightArm; } else { log.error("can not get arm {}", side); } return null; } public InMoov2Hand getHand(String side) { if ("left".equals(side)) { return leftHand; } else if ("right".equals(side)) { return rightHand; } else { log.error("can not get arm {}", side); } return null; } public InMoov2Head getHead() { return head; } /** * get current language */ public String getLanguage() { return locale.getLanguage(); } /** * finds most recent activity * * @return the timestamp of the last activity time. */ public long getLastActivityTime() { long lastActivityTime = 0; if (leftHand != null) { lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime()); } if (leftArm != null) { lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime()); } if (rightHand != null) { lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime()); } if (rightArm != null) { lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime()); } if (head != null) { lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime()); } if (torso != null) { lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime()); } if (lastPirActivityTime != null) { lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime); } if (lastActivityTime == 0) { error("invalid activity time - anything connected?"); lastActivityTime = System.currentTimeMillis(); } return lastActivityTime; } public InMoov2Arm getLeftArm() { return leftArm; } public InMoov2Hand getLeftHand() { return leftHand; } @Override public Locale getLocale() { return locale; } @Override public Map<String, Locale> getLocales() { return locales; } public InMoov2Arm getRightArm() { return rightArm; } public InMoov2Hand getRightHand() { return rightHand; } public Simulator getSimulator() { return jme; } public InMoov2Torso getTorso() { return torso; } public void halfSpeed() { if (head != null) { head.setSpeed(25.0, 25.0, 25.0, 25.0, -1.0, 25.0); } if (rightHand != null) { rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0); } if (leftHand != null) { leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0); } if (rightArm != null) { rightArm.setSpeed(25.0, 25.0, 25.0, 25.0); } if (leftArm != null) { leftArm.setSpeed(25.0, 25.0, 25.0, 25.0); } if (torso != null) { torso.setSpeed(20.0, 20.0, 20.0); } } public boolean isCameraOn() { if (eye != null) { if (eye.isCapturing()) { return true; } } return false; } public boolean isEyeLidsActivated() { return isEyeLidsActivated; } public boolean isHeadActivated() { return isHeadActivated; } public boolean isLeftArmActivated() { return isLeftArmActivated; } public boolean isLeftHandActivated() { return isLeftHandActivated; } public boolean isMute() { return mute; } public boolean isNeopixelActivated() { return isNeopixelActivated; } public boolean isRightArmActivated() { return isRightArmActivated; } public boolean isRightHandActivated() { return isRightHandActivated; } public boolean isTorsoActivated() { return isTorsoActivated; } public boolean isPirActivated() { return isPirActivated; } public boolean isUltraSonicRightActivated() { return isUltraSonicRightActivated; } public boolean isUltraSonicLeftActivated() { return isUltraSonicLeftActivated; } public boolean isServoMixerActivated() { return isServoMixerActivated; } public Set<String> listConfigFiles() { configs = new HashSet<>(); // data list String configDir = getResourceDir() + fs + "config"; File f = new File(configDir); if (!f.exists()) { f.mkdirs(); } String[] files = f.list(); for (String config : files) { configs.add(config); } // data list configDir = getDataDir() + fs + "config"; f = new File(configDir); if (!f.exists()) { f.mkdirs(); } files = f.list(); for (String config : files) { configs.add(config); } return configs; } /* * iterate over each txt files in the directory */ public void load(String locale) { String extension = "lang"; File dir = Utils.makeDirectory(getResourceDir() + File.separator + "system" + File.separator + "languagePack" + File.separator + locale); if (dir.exists()) { lpVars.clear(); for (File f : dir.listFiles()) { if (f.isDirectory()) { continue; } if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { log.info("Inmoov languagePack load : {}", f.getName()); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8")); for (String line = br.readLine(); line != null; line = br.readLine()) { String[] parts = line.split("::"); if (parts.length > 1) { lpVars.put(parts[0].toUpperCase(), parts[1]); } } } catch (IOException e) { log.error("LanguagePack : {}", e); } } else { log.warn("{} is not a {} file", f.getAbsolutePath(), extension); } } } } // FIXME - what is this for ??? public void loadGestures() { loadGestures(getResourceDir() + fs + "gestures"); } /** * This blocking method will look at all of the .py files in a directory. One by * one it will load the files into the python interpreter. A gesture python file * should contain 1 method definition that is the same as the filename. * * @param directory - the directory that contains the gesture python files. */ public boolean loadGestures(String directory) { speakBlocking(get("STARTINGGESTURES")); // iterate over each of the python files in the directory // and load them into the python interpreter. String extension = "py"; Integer totalLoaded = 0; Integer totalError = 0; File dir = new File(directory); dir.mkdirs(); if (dir.exists()) { for (File f : dir.listFiles()) { if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { if (loadFile(f.getAbsolutePath()) == true) { totalLoaded += 1; String methodName = f.getName().substring(0, f.getName().length() - 3) + "()"; gestures.add(methodName); } else { error("could not load %s", f.getName()); totalError += 1; } } else { log.info("{} is not a {} file", f.getAbsolutePath(), extension); } } } info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError); broadcastState(); if (totalError > 0) { speakAlert(get("GESTURE_ERROR")); return false; } return true; } public void moveArm(String which, double bicep, double rotate, double shoulder, double omoplate) { InMoov2Arm arm = getArm(which); if (arm == null) { info("%s arm not started", which); return; } arm.moveTo(bicep, rotate, shoulder, omoplate); } public void moveEyelids(double eyelidleftPos, double eyelidrightPos) { if (head != null) { head.moveEyelidsTo(eyelidleftPos, eyelidrightPos); } else { log.warn("moveEyelids - I have a null head"); } } public void moveEyes(double eyeX, double eyeY) { if (head != null) { head.moveTo(null, null, eyeX, eyeY, null, null); } else { log.warn("moveEyes - I have a null head"); } } public void moveHand(String which, double thumb, double index, double majeure, double ringFinger, double pinky) { moveHand(which, thumb, index, majeure, ringFinger, pinky, null); } public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { InMoov2Hand hand = getHand(which); if (hand == null) { log.warn("{} hand does not exist"); return; } hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist); } public void moveHead(double neck, double rothead) { moveHead(neck, rothead, null); } public void moveHead(double neck, double rothead, double eyeX, double eyeY, double jaw) { moveHead(neck, rothead, eyeX, eyeY, jaw, null); } public void moveHead(Double neck, Double rothead, Double rollNeck) { moveHead(neck, rothead, null, null, null, rollNeck); } public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) { if (head != null) { head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck); } else { log.error("I have a null head"); } } public void moveHeadBlocking(double neck, double rothead) { moveHeadBlocking(neck, rothead, null); } public void moveHeadBlocking(double neck, double rothead, Double rollNeck) { moveHeadBlocking(neck, rothead, null, null, null, rollNeck); } public void moveHeadBlocking(double neck, double rothead, Double eyeX, Double eyeY, Double jaw) { moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null); } public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) { if (head != null) { head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck); } else { log.error("I have a null head"); } } public void moveTorso(double topStom, double midStom, double lowStom) { if (torso != null) { torso.moveTo(topStom, midStom, lowStom); } else { log.error("moveTorso - I have a null torso"); } } public void moveTorsoBlocking(double topStom, double midStom, double lowStom) { if (torso != null) { torso.moveToBlocking(topStom, midStom, lowStom); } else { log.error("moveTorsoBlocking - I have a null torso"); } } public void onGestureStatus(Status status) { if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) { error("I cannot execute %s, please check logs", lastGestureExecuted); } finishedGesture(lastGestureExecuted); unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); } @Override public void onJoystickInput(JoystickData input) throws Exception { // TODO Auto-generated method stub } public OpenCVData onOpenCVData(OpenCVData data) { return data; } @Override public void onText(String text) { // FIXME - we should be able to "re"-publish text but text is coming from // different sources // some might be coming from the ear - some from the mouth ... - there has // to be a distinction log.info("onText - {}", text); invoke("publishText", text); } // TODO FIX/CHECK this, migrate from python land public void powerDown() { rest(); purgeTasks(); disable(); if (ear != null) { ear.lockOutAllGrammarExcept("power up"); } python.execMethod("power_down"); } // TODO FIX/CHECK this, migrate from python land public void powerUp() { enable(); rest(); if (ear != null) { ear.clearLock(); } beginCheckingOnInactivity(); python.execMethod("power_up"); } /** * all published text from InMoov2 - including ProgramAB */ @Override public String publishText(String text) { return text; } public void releaseService() { try { disable(); releasePeers(); super.releaseService(); } catch (Exception e) { error(e); } } // FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest public void rest() { log.info("InMoov2.rest()"); if (head != null) { head.rest(); } if (rightHand != null) { rightHand.rest(); } if (leftHand != null) { leftHand.rest(); } if (rightArm != null) { rightArm.rest(); } if (leftArm != null) { leftArm.rest(); } if (torso != null) { torso.rest(); } } @Deprecated public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) { InMoov2Arm arm = getArm(which); if (arm == null) { warn("%s hand not started", which); return; } arm.setSpeed(bicep, rotate, shoulder, omoplate); } public void setAutoDisable(Boolean param) { if (head != null) { head.setAutoDisable(param); } if (rightArm != null) { rightArm.setAutoDisable(param); } if (leftArm != null) { leftArm.setAutoDisable(param); } if (leftHand != null) { leftHand.setAutoDisable(param); } if (rightHand != null) { leftHand.setAutoDisable(param); } if (torso != null) { torso.setAutoDisable(param); } /* * if (eyelids != null) { eyelids.setAutoDisable(param); } */ } public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null); } public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { InMoov2Hand hand = getHand(which); if (hand == null) { warn("%s hand not started", which); return; } hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist); } @Deprecated public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null); } @Deprecated public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist); } public void setHeadSpeed(Double rothead, Double neck) { setHeadSpeed(rothead, neck, null, null, null); } public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null); } public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) { if (head == null) { warn("setHeadSpeed - head not started"); return; } head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed); } @Deprecated public void setHeadVelocity(Double rothead, Double neck) { setHeadSpeed(rothead, neck, null, null, null, null); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) { setHeadSpeed(rothead, neck, null, null, null, rollNeck); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed); } /** * TODO : use system locale set language for InMoov service used by chatbot + * * @param code * @return */ @Deprecated /* use setLocale */ public String setLanguage(String code) { setLocale(code); return code; } @Override public void setLocale(String code) { if (code == null) { log.warn("setLocale null"); return; } // filter of the set of supported locales if (!locales.containsKey(code)) { error("InMooov does not support %s only %s", code, locales.keySet()); return; } locale = new Locale(code); speakBlocking("setting language to %s", locale.getDisplayLanguage()); // attempt to set all other language providers to the same language as me List<String> providers = Runtime.getServiceNamesFromInterface(LocaleProvider.class); for (String provider : providers) { if (!provider.equals(getName())) { log.info("{} setting locale to %s", provider, code); send(provider, "setLocale", code); send(provider, "broadcastState"); } } load(locale.getTag()); } public void setMute(boolean mute) { info("Set mute to %s", mute); this.mute = mute; sendToPeer("mouth", "setMute", mute); broadcastState(); } public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) { if (neopixel != null /* && neopixelArduino != null */) { neopixel.setAnimation(animation, red, green, blue, speed); } else { warn("No Neopixel attached"); } } public String setSpeechType(String speechType) { speechService = speechType; setPeer("mouth", speechType); return speechType; } public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.setSpeed(topStom, midStom, lowStom); } else { log.warn("setTorsoSpeed - I have no torso"); } } @Deprecated public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.setVelocity(topStom, midStom, lowStom); } else { log.warn("setTorsoVelocity - I have no torso"); } } /** * overridden setVirtual for InMoov sets "all" services to virtual */ public boolean setVirtual(boolean virtual) { super.setVirtual(virtual); Platform.setVirtual(virtual); return virtual; } public void setVoice(String name) { if (mouth != null) { mouth.setVoice(name); voiceSelected = name; speakBlocking("setting voice to %s", name); } } public void speak(String toSpeak) { sendToPeer("mouth", "speak", toSpeak); } public void speakAlert(String toSpeak) { speakBlocking(get("ALERT")); speakBlocking(toSpeak); } public void speakBlocking(String speak) { speakBlocking(speak, null); } // FIXME - publish text regardless if mouth exists ... public void speakBlocking(String format, Object... args) { if (format == null) { return; } String toSpeak = format; if (args != null) { toSpeak = String.format(format, args); } // FIXME - publish onText when listening invoke("publishText", toSpeak); if (!mute) { // sendToPeer("mouth", "speakBlocking", toSpeak); invokePeer("mouth", "speakBlocking", toSpeak); } } public void startAll() throws Exception { startAll(null, null); } public void startAll(String leftPort, String rightPort) throws Exception { startMouth(); startBrain(); startHeadTracking(); // startEyesTracking(); // startOpenCV(); startEar(); startServos(leftPort, rightPort); // startMouthControl(head.jaw, mouth); speakBlocking("startup sequence completed"); } public ProgramAB startBrain() { try { brain = (ProgramAB) startPeer("brain"); isBrainActivated = true; speakBlocking(get("CHATBOTACTIVATED")); // GOOD EXAMPLE ! - no type, uses name - does a set of subscriptions ! // attachTextPublisher(brain.getName()); /* * not necessary - ear needs to be attached to mouth not brain if (ear != null) * { ear.attachTextListener(brain); } */ brain.attachTextPublisher(ear); // this.attach(brain); FIXME - attach as a TextPublisher - then re-publish // FIXME - deal with language // speakBlocking(get("CHATBOTACTIVATED")); brain.repetitionCount(10); brain.setPath(getResourceDir() + fs + "chatbot"); brain.startSession("default", locale.getTag()); // reset some parameters to default... brain.setPredicate("topic", "default"); brain.setPredicate("questionfirstinit", ""); brain.setPredicate("tmpname", ""); brain.setPredicate("null", ""); // load last user session if (!brain.getPredicate("name").isEmpty()) { if (brain.getPredicate("lastUsername").isEmpty() || brain.getPredicate("lastUsername").equals("unknown")) { brain.setPredicate("lastUsername", brain.getPredicate("name")); } } brain.setPredicate("parameterHowDoYouDo", ""); try { brain.savePredicates(); } catch (IOException e) { log.error("saving predicates threw", e); } // start session based on last recognized person if (!brain.getPredicate("default", "lastUsername").isEmpty() && !brain.getPredicate("default", "lastUsername").equals("unknown")) { brain.startSession(brain.getPredicate("lastUsername")); } htmlFilter = (HtmlFilter) startPeer("htmlFilter");// Runtime.start("htmlFilter", // "HtmlFilter"); brain.attachTextListener(htmlFilter); htmlFilter.attachTextListener((TextListener) getPeer("mouth")); brain.attachTextListener(this); } catch (Exception e) { speak("could not load brain"); error(e.getMessage()); speak(e.getMessage()); } broadcastState(); return brain; } public SpeechRecognizer startEar() { ear = (SpeechRecognizer) startPeer("ear"); isEarActivated = true; ear.attachSpeechSynthesis((SpeechSynthesis) getPeer("mouth")); ear.attachTextListener(brain); speakBlocking(get("STARTINGEAR")); broadcastState(); return ear; } public void startedGesture() { startedGesture("unknown"); } public void startedGesture(String nameOfGesture) { if (gestureAlreadyStarted) { warn("Warning 1 gesture already running, this can break spacetime and lot of things"); } else { log.info("Starting gesture : {}", nameOfGesture); gestureAlreadyStarted = true; RobotCanMoveRandom = false; } } // FIXME - universal (good) way of handling all exceptions - ie - reporting // back to the user the problem in a short concise way but have // expandable detail in appropriate places public OpenCV startEye() throws Exception { speakBlocking(get("STARTINGOPENCV")); eye = (OpenCV) startPeer("eye", "OpenCV"); subscribeTo(eye.getName(), "publishOpenCVData"); isEyeActivated = true; return eye; } public Tracking startEyesTracking() throws Exception { if (head == null) { startHead(); } return startHeadTracking(head.eyeX, head.eyeY); } public Tracking startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception { if (eye == null) { startEye(); } speakBlocking(get("TRACKINGSTARTED")); eyesTracking = (Tracking) this.startPeer("eyesTracking"); eyesTracking.connect(eye, head.eyeX, head.eyeY); return eyesTracking; } public InMoov2Head startHead() throws Exception { return startHead(null, null, null, null, null, null, null, null); } public InMoov2Head startHead(String port) throws Exception { return startHead(port, null, null, null, null, null, null, null); } // legacy inmoov head exposed pins public InMoov2Head startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) { // log.warn(InMoov.buildDNA(myKey, serviceClass)) // speakBlocking(get("STARTINGHEAD") + " " + port); // ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not speakBlocking(get("STARTINGHEAD")); head = (InMoov2Head) startPeer("head"); isHeadActivated = true; if (headYPin != null) { head.setPins(headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin); } // lame assumption - port is specified - it must be an Arduino :( if (port != null) { try { speakBlocking(get(port)); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(head.neck); arduino.attach(head.rothead); arduino.attach(head.eyeX); arduino.attach(head.eyeY); arduino.attach(head.jaw); arduino.attach(head.rollNeck); } catch (Exception e) { error(e); } } speakBlocking(get("STARTINGMOUTHCONTROL")); mouthControl = (MouthControl) startPeer("mouthControl"); mouthControl.attach(head.jaw); mouthControl.attach((Attachable) getPeer("mouth")); mouthControl.setmouth(10, 50);// <-- FIXME - not the right place for // config !!! return head; } public void startHeadTracking() throws Exception { if (eye == null) { startEye(); } if (head == null) { startHead(); } if (headTracking == null) { speakBlocking(get("TRACKINGSTARTED")); headTracking = (Tracking) this.startPeer("headTracking"); headTracking.connect(this.eye, head.rothead, head.neck); } } public Tracking startHeadTracking(ServoControl rothead, ServoControl neck) throws Exception { if (eye == null) { startEye(); } if (headTracking == null) { speakBlocking(get("TRACKINGSTARTED")); headTracking = (Tracking) this.startPeer("headTracking"); headTracking.connect(this.eye, rothead, neck); } return headTracking; } public InMoov2Arm startLeftArm() { return startLeftArm(null); } public InMoov2Arm startLeftArm(String port) { // log.warn(InMoov.buildDNA(myKey, serviceClass)) // speakBlocking(get("STARTINGHEAD") + " " + port); // ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not speakBlocking(get("STARTINGLEFTARM")); leftArm = (InMoov2Arm) startPeer("leftArm"); isLeftArmActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(leftArm.bicep); arduino.attach(leftArm.omoplate); arduino.attach(leftArm.rotate); arduino.attach(leftArm.shoulder); } catch (Exception e) { error(e); } } return leftArm; } public InMoov2Hand startLeftHand() { return startLeftHand(null); } public InMoov2Hand startLeftHand(String port) { speakBlocking(get("STARTINGLEFTHAND")); leftHand = (InMoov2Hand) startPeer("leftHand"); isLeftHandActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left", "Arduino"); arduino.connect(port); arduino.attach(leftHand.thumb); arduino.attach(leftHand.index); arduino.attach(leftHand.majeure); arduino.attach(leftHand.ringFinger); arduino.attach(leftHand.pinky); arduino.attach(leftHand.wrist); } catch (Exception e) { error(e); } } return leftHand; } // TODO - general objective "might" be to reduce peers down to something // that does not need a reference - where type can be switched before creation // and the onnly thing needed is pubs/subs that are not handled in abstracts public SpeechSynthesis startMouth() { mouth = (SpeechSynthesis) startPeer("mouth"); voices = mouth.getVoices(); Voice voice = mouth.getVoice(); if (voice != null) { voiceSelected = voice.getName(); } isMouthActivated = true; if (mute) { mouth.setMute(true); } mouth.attachSpeechRecognizer(ear); // mouth.attach(htmlFilter); // same as brain not needed // this.attach((Attachable) mouth); // if (ear != null) .... broadcastState(); speakBlocking(get("STARTINGMOUTH")); if (Platform.isVirtual()) { speakBlocking("in virtual hardware mode"); } speakBlocking(get("WHATISTHISLANGUAGE")); return mouth; } @Deprecated /* use start eye */ public void startOpenCV() throws Exception { startEye(); } public InMoov2Arm startRightArm() { return startRightArm(null); } public InMoov2Arm startRightArm(String port) { speakBlocking(get("STARTINGRIGHTARM")); rightArm = (InMoov2Arm) startPeer("rightArm"); isRightArmActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("right", "Arduino"); arduino.connect(port); arduino.attach(rightArm.bicep); arduino.attach(rightArm.omoplate); arduino.attach(rightArm.rotate); arduino.attach(rightArm.shoulder); } catch (Exception e) { error(e); } } return rightArm; } public InMoov2Hand startRightHand() { return startRightHand(null); } public InMoov2Hand startRightHand(String port) { speakBlocking(get("STARTINGRIGHTHAND")); rightHand = (InMoov2Hand) startPeer("rightHand"); isRightHandActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("right", "Arduino"); arduino.connect(port); arduino.attach(rightHand.thumb); arduino.attach(rightHand.index); arduino.attach(rightHand.majeure); arduino.attach(rightHand.ringFinger); arduino.attach(rightHand.pinky); arduino.attach(rightHand.wrist); } catch (Exception e) { error(e); } } return rightHand; } public Double getUltraSonicRightDistance() { if (ultraSonicRight != null) { return ultraSonicRight.range(); } else { warn("No UltraSonicRight attached"); return 0.0; } } public Double getUltraSonicLeftDistance() { if (ultraSonicLeft != null) { return ultraSonicLeft.range(); } else { warn("No UltraSonicLeft attached"); return 0.0; } } public void publishPin(Pin pin) { log.info("{} - {}", pin.pin, pin.value); //if (pin.value == 1) { //lastPIRActivityTime = System.currentTimeMillis(); // if its PIR & PIR is active & was sleeping - then wake up ! if (pirPin == pin.pin && startSleep != null && pin.value == 1) { // attach(); // good morning / evening / night... asleep for % hours powerUp(); } } public void startServos(String leftPort, String rightPort) throws Exception { startHead(leftPort); startLeftArm(leftPort); startLeftHand(leftPort); startRightArm(rightPort); startRightHand(rightPort); startTorso(leftPort); } // FIXME .. externalize in a json file included in InMoov2 public Simulator startSimulator() throws Exception { speakBlocking(get("STARTINGVIRTUAL")); if (jme != null) { log.info("start called twice - starting simulator is reentrant"); return jme; } jme = (JMonkeyEngine) startPeer("simulator"); isSimulatorActivated = true; // adding InMoov2 asset path to the jonkey simulator String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName(); File check = new File(assetPath); log.info("loading assets from {}", assetPath); if (!check.exists()) { log.warn("%s does not exist"); } // disable the frustrating servo events ... // Servo.eventsEnabledDefault(false); // jme.loadModels(assetPath); not needed - as InMoov2 unzips the model into // /resource/JMonkeyEngine/assets jme.setRotation(getName() + ".head.jaw", "x"); jme.setRotation(getName() + ".head.neck", "x"); jme.setRotation(getName() + ".head.rothead", "y"); jme.setRotation(getName() + ".head.rollNeck", "z"); jme.setRotation(getName() + ".head.eyeY", "x"); jme.setRotation(getName() + ".head.eyeX", "y"); jme.setRotation(getName() + ".torso.topStom", "z"); jme.setRotation(getName() + ".torso.midStom", "y"); jme.setRotation(getName() + ".torso.lowStom", "x"); jme.setRotation(getName() + ".rightArm.bicep", "x"); jme.setRotation(getName() + ".leftArm.bicep", "x"); jme.setRotation(getName() + ".rightArm.shoulder", "x"); jme.setRotation(getName() + ".leftArm.shoulder", "x"); jme.setRotation(getName() + ".rightArm.rotate", "y"); jme.setRotation(getName() + ".leftArm.rotate", "y"); jme.setRotation(getName() + ".rightArm.omoplate", "z"); jme.setRotation(getName() + ".leftArm.omoplate", "z"); jme.setRotation(getName() + ".rightHand.wrist", "y"); jme.setRotation(getName() + ".leftHand.wrist", "y"); jme.setMapper(getName() + ".head.jaw", 0, 180, -5, 80); jme.setMapper(getName() + ".head.neck", 0, 180, 20, -20); jme.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30); jme.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140); jme.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE there need // to be // two eyeX (left and // right?) jme.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150); jme.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150); jme.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150); jme.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150); jme.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80); jme.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80); jme.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180); jme.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180); jme.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60); jme.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60); jme.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30); jme.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130); jme.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30); jme.attach(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2", getName() + ".leftHand.thumb3"); jme.setRotation(getName() + ".leftHand.thumb1", "y"); jme.setRotation(getName() + ".leftHand.thumb2", "x"); jme.setRotation(getName() + ".leftHand.thumb3", "x"); jme.attach(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2", getName() + ".leftHand.index3"); jme.setRotation(getName() + ".leftHand.index", "x"); jme.setRotation(getName() + ".leftHand.index2", "x"); jme.setRotation(getName() + ".leftHand.index3", "x"); jme.attach(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2", getName() + ".leftHand.majeure3"); jme.setRotation(getName() + ".leftHand.majeure", "x"); jme.setRotation(getName() + ".leftHand.majeure2", "x"); jme.setRotation(getName() + ".leftHand.majeure3", "x"); jme.attach(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3"); jme.setRotation(getName() + ".leftHand.ringFinger", "x"); jme.setRotation(getName() + ".leftHand.ringFinger2", "x"); jme.setRotation(getName() + ".leftHand.ringFinger3", "x"); jme.attach(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2", getName() + ".leftHand.pinky3"); jme.setRotation(getName() + ".leftHand.pinky", "x"); jme.setRotation(getName() + ".leftHand.pinky2", "x"); jme.setRotation(getName() + ".leftHand.pinky3", "x"); // left hand mapping complexities of the fingers jme.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179); jme.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100); jme.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20); jme.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20); // right hand jme.attach(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2", getName() + ".rightHand.thumb3"); jme.setRotation(getName() + ".rightHand.thumb1", "y"); jme.setRotation(getName() + ".rightHand.thumb2", "x"); jme.setRotation(getName() + ".rightHand.thumb3", "x"); jme.attach(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2", getName() + ".rightHand.index3"); jme.setRotation(getName() + ".rightHand.index", "x"); jme.setRotation(getName() + ".rightHand.index2", "x"); jme.setRotation(getName() + ".rightHand.index3", "x"); jme.attach(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure", getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3"); jme.setRotation(getName() + ".rightHand.majeure", "x"); jme.setRotation(getName() + ".rightHand.majeure2", "x"); jme.setRotation(getName() + ".rightHand.majeure3", "x"); jme.attach(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3"); jme.setRotation(getName() + ".rightHand.ringFinger", "x"); jme.setRotation(getName() + ".rightHand.ringFinger2", "x"); jme.setRotation(getName() + ".rightHand.ringFinger3", "x"); jme.attach(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2", getName() + ".rightHand.pinky3"); jme.setRotation(getName() + ".rightHand.pinky", "x"); jme.setRotation(getName() + ".rightHand.pinky2", "x"); jme.setRotation(getName() + ".rightHand.pinky3", "x"); jme.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10); jme.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10); jme.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10); jme.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110); jme.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150); jme.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160); // additional experimental mappings /* * simulator.attach(getName() + ".leftHand.pinky", getName() + * ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb", * getName() + ".leftHand.index3"); simulator.setRotation(getName() + * ".leftHand.index2", "x"); simulator.setRotation(getName() + * ".leftHand.index3", "x"); simulator.setMapper(getName() + ".leftHand.index", * 0, 180, -90, -270); simulator.setMapper(getName() + ".leftHand.index2", 0, * 180, -90, -270); simulator.setMapper(getName() + ".leftHand.index3", 0, 180, * -90, -270); */ return jme; } public InMoov2Torso startTorso() { return startTorso(null); } public InMoov2Torso startTorso(String port) { if (torso == null) { speakBlocking(get("STARTINGTORSO")); isTorsoActivated = true; torso = (InMoov2Torso) startPeer("torso"); if (port != null) { try { speakBlocking(port); Arduino left = (Arduino) startPeer("left"); left.connect(port); left.attach(torso.lowStom); left.attach(torso.midStom); left.attach(torso.topStom); } catch (Exception e) { error(e); } } } return torso; } /** * called with only port - will default with defaulted pins * @param port * @return */ public UltrasonicSensor startUltraSonicRight(String port) { return startUltraSonicRight(port, 64, 63); } /** * called explicitly with pin values * @param port * @param trigPin * @param echoPin * @return */ public UltrasonicSensor startUltraSonicRight(String port, int trigPin, int echoPin) { if (ultraSonicRight == null) { speakBlocking(get("STARTINGULTRASONIC")); isUltraSonicRightActivated = true; ultraSonicRight = (UltrasonicSensor) startPeer("ultraSonicRight"); if (port != null) { try { speakBlocking(port); Arduino right = (Arduino) startPeer("right"); right.connect(port); right.attach(ultraSonicRight, trigPin, echoPin); } catch (Exception e) { error(e); } } } return ultraSonicRight; } public UltrasonicSensor startUltraSonicLeft(String port) { return startUltraSonicLeft(port, 64, 63); } public UltrasonicSensor startUltraSonicLeft(String port, int trigPin, int echoPin) { if (ultraSonicLeft == null) { speakBlocking(get("STARTINGULTRASONIC")); isUltraSonicLeftActivated = true; ultraSonicLeft = (UltrasonicSensor) startPeer("ultraSonicLeft"); if (port != null) { try { speakBlocking(port); Arduino left = (Arduino) startPeer("left"); left.connect(port); left.attach(ultraSonicLeft, trigPin, echoPin); } catch (Exception e) { error(e); } } } return ultraSonicLeft; } public Pir startPir(String port) { return startPir(port, 23); } public Pir startPir(String port, int pin) { if (pir == null) { speakBlocking(get("STARTINGPIR")); isPirActivated = true; pir = (Pir) startPeer("pir"); if (port != null) { try { speakBlocking(port); Arduino right = (Arduino) startPeer("right"); right.connect(port); right.enablePin(pin, pirPin); pirArduino = right; pirPin = pin; right.addListener("publishPin", this.getName(), "publishPin"); } catch (Exception e) { error(e); } } } return pir; } public ServoMixer startServoMixer() { servomixer = (ServoMixer) startPeer("servomixer"); isServoMixerActivated = true; speakBlocking(get("STARTINGSERVOMIXER")); broadcastState(); return servomixer; } public void stop() { if (head != null) { head.stop(); } if (rightHand != null) { rightHand.stop(); } if (leftHand != null) { leftHand.stop(); } if (rightArm != null) { rightArm.stop(); } if (leftArm != null) { leftArm.stop(); } if (torso != null) { torso.stop(); } } public void stopBrain() { speakBlocking(get("STOPCHATBOT")); releasePeer("brain"); isBrainActivated = false; } public void stopHead() { speakBlocking(get("STOPHEAD")); releasePeer("head"); isHeadActivated = false; } public void stopEar() { speakBlocking(get("STOPEAR")); releasePeer("ear"); isEarActivated = false; broadcastState(); } public void stopEye() { speakBlocking(get("STOPOPENCV")); isEyeActivated = false; releasePeer("eye"); } public void stopGesture() { Python p = (Python) Runtime.getService("python"); p.stop(); } public void stopLeftArm() { speakBlocking(get("STOPLEFTARM")); releasePeer("leftArm"); isLeftArmActivated = false; } public void stopLeftHand() { speakBlocking(get("STOPLEFTHAND")); releasePeer("leftHand"); isLeftHandActivated = false; } public void stopMouth() { speakBlocking(get("STOPMOUTH")); releasePeer("mouth"); // TODO - potentially you could set the field to null in releasePeer mouth = null; isMouthActivated = false; } public void stopRightArm() { speakBlocking(get("STOPRIGHTARM")); releasePeer("rightArm"); isRightArmActivated = false; } public void stopRightHand() { speakBlocking(get("STOPRIGHTHAND")); releasePeer("rightHand"); isRightHandActivated = false; } public void stopTorso() { speakBlocking(get("STOPTORSO")); releasePeer("torso"); isTorsoActivated = false; } public void stopSimulator() { speakBlocking(get("STOPVIRTUAL")); releasePeer("simulator"); jme = null; isSimulatorActivated = false; } public void stopUltraSonicRight() { speakBlocking(get("STOPULTRASONIC")); releasePeer("ultraSonicRight"); isUltraSonicRightActivated = false; } public void stopUltraSonicLeft() { speakBlocking(get("STOPULTRASONIC")); releasePeer("ultraSonicLeft"); isUltraSonicLeftActivated = false; } public void stopPir() { speakBlocking(get("STOPPIR")); releasePeer("pir"); isPirActivated = false; if (pirArduino != null && pirPin != null) { pirArduino.disablePin(pirPin); pirPin = null; pirArduino = null; } } public void stopServoMixer() { speakBlocking(get("STOPSERVOMIXER")); releasePeer("servomixer"); isServoMixerActivated = false; } public void waitTargetPos() { if (head != null) { head.waitTargetPos(); } if (leftArm != null) { leftArm.waitTargetPos(); } if (rightArm != null) { rightArm.waitTargetPos(); } if (leftHand != null) { leftHand.waitTargetPos(); } if (rightHand != null) { rightHand.waitTargetPos(); } if (torso != null) { torso.waitTargetPos(); } } }
package org.myrobotlab.service; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.io.FilenameUtils; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.Status; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.inmoov.Vision; import org.myrobotlab.io.FileIO; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.opencv.OpenCVData; import org.myrobotlab.service.abstracts.AbstractSpeechSynthesis.Voice; import org.myrobotlab.service.config.InMoov2Config; import org.myrobotlab.service.config.ServiceConfig; import org.myrobotlab.service.data.JoystickData; import org.myrobotlab.service.data.Locale; import org.myrobotlab.service.interfaces.IKJointAngleListener; import org.myrobotlab.service.interfaces.JoystickListener; import org.myrobotlab.service.interfaces.LocaleProvider; import org.myrobotlab.service.interfaces.ServoControl; import org.myrobotlab.service.interfaces.Simulator; import org.myrobotlab.service.interfaces.SpeechRecognizer; import org.myrobotlab.service.interfaces.SpeechSynthesis; import org.myrobotlab.service.interfaces.TextListener; import org.myrobotlab.service.interfaces.TextPublisher; import org.slf4j.Logger; public class InMoov2 extends Service implements TextListener, TextPublisher, JoystickListener, LocaleProvider, IKJointAngleListener { public final static Logger log = LoggerFactory.getLogger(InMoov2.class); public static LinkedHashMap<String, String> lpVars = new LinkedHashMap<String, String>(); /** * these should be methods like setRobotCanMoveBodyRandom(true) - which do * what they need and then set config NOT STATIC PUBLIC VARS */ @Deprecated public static boolean RobotCanMoveBodyRandom = true; public static boolean isRobotCanMoveBodyRandom() { return RobotCanMoveBodyRandom; } public static void setRobotCanMoveBodyRandom(boolean robotCanMoveBodyRandom) { RobotCanMoveBodyRandom = robotCanMoveBodyRandom; } public static boolean isRobotCanMoveHeadRandom() { return RobotCanMoveHeadRandom; } public static void setRobotCanMoveHeadRandom(boolean robotCanMoveHeadRandom) { RobotCanMoveHeadRandom = robotCanMoveHeadRandom; } public static boolean isRobotCanMoveEyesRandom() { return RobotCanMoveEyesRandom; } public static void setRobotCanMoveEyesRandom(boolean robotCanMoveEyesRandom) { RobotCanMoveEyesRandom = robotCanMoveEyesRandom; } public static boolean isRobotCanMoveRandom() { return RobotCanMoveRandom; } public static void setRobotCanMoveRandom(boolean robotCanMoveRandom) { RobotCanMoveRandom = robotCanMoveRandom; } public static boolean isRobotIsSleeping() { return RobotIsSleeping; } public static void setRobotIsSleeping(boolean robotIsSleeping) { RobotIsSleeping = robotIsSleeping; } public static boolean isRobotIsStarted() { return RobotIsStarted; } public static void setRobotIsStarted(boolean robotIsStarted) { RobotIsStarted = robotIsStarted; } @Deprecated public static boolean RobotCanMoveHeadRandom = true; @Deprecated public static boolean RobotCanMoveEyesRandom = true; @Deprecated public static boolean RobotCanMoveRandom = true; @Deprecated public static boolean RobotIsSleeping = false; @Deprecated public static boolean RobotIsStarted = false; private static final long serialVersionUID = 1L; static String speechRecognizer = "WebkitSpeechRecognition"; protected boolean loadGestures = true; InMoov2Config config = new InMoov2Config(); /** * @param someScriptName * execute a resource script * @return success or failure */ public boolean execScript(String someScriptName) { try { Python p = (Python) Runtime.start("python", "Python"); String script = getResourceAsString(someScriptName); return p.exec(script, true); } catch (Exception e) { error("unable to execute script %s", someScriptName); return false; } } /** * Single place for InMoov2 service to execute arbitrary code - needed * initially to set "global" vars in python * * @param pythonCode * @return */ public boolean exec(String pythonCode) { try { Python p = (Python) Runtime.start("python", "Python"); return p.exec(pythonCode, true); } catch (Exception e) { error("unable to execute script %s", pythonCode); return false; } } /** * Part of service life cycle - a new servo has been started */ public void onStarted(String fullname) { log.info("{} started", fullname); try { ServiceInterface si = Runtime.getService(fullname); if ("Servo".equals(si.getSimpleName())) { log.info("sending setAutoDisable true to {}", fullname); send(fullname, "setAutoDisable", true); // ServoControl sc = (ServoControl)Runtime.getService(name); } } catch (Exception e) { log.error("onStarted threw", e); } } public void startService() { super.startService(); Runtime runtime = Runtime.getInstance(); // FIXME - shouldn't need this anymore runtime.subscribeToLifeCycleEvents(getName()); try { // copy config if it doesn't already exist String resourceBotDir = FileIO.gluePaths(getResourceDir(), "config"); List<File> files = FileIO.getFileList(resourceBotDir); for (File f : files) { String botDir = "data/config/" + f.getName(); File bDir = new File(botDir); if (bDir.exists() || !f.isDirectory()) { log.info("skipping data/config/{}", botDir); } else { log.info("will copy new data/config/{}", botDir); try { FileIO.copy(f.getAbsolutePath(), botDir); } catch (Exception e) { error(e); } } } // copy (if they don't already exist) the chatbots which came with InMoov2 resourceBotDir = FileIO.gluePaths(getResourceDir(), "chatbot/bots"); files = FileIO.getFileList(resourceBotDir); for (File f : files) { String botDir = "data/ProgramAB/" + f.getName(); if (new File(botDir).exists()) { log.info("found data/ProgramAB/{} not copying", botDir); } else { log.info("will copy new data/ProgramAB/{}", botDir); try { FileIO.copy(f.getAbsolutePath(), botDir); } catch (Exception e) { error(e); } } } } catch (Exception e) { error(e); } if (loadGestures) { loadGestures(); } runtime.invoke("publishConfigList"); } public void onCreated(String fullname) { log.info("{} created", fullname); } /** * This method will load a python file into the python interpreter. * * @param file * file to load * @return success/failure */ @Deprecated /* use execScript - this doesn't handle resources correctly */ public static boolean loadFile(String file) { File f = new File(file); Python p = (Python) Runtime.getService("python"); log.info("Loading Python file {}", f.getAbsolutePath()); if (p == null) { log.error("Python instance not found"); return false; } boolean result = false; try { // This will open a gazillion tabs in InMoov // result = p.execFile(f.getAbsolutePath(), true); // old way - not using execFile :( String script = FileIO.toString(f.getAbsolutePath()); result = p.exec(script, true); } catch (IOException e) { log.error("IO Error loading file : ", e); return false; } if (!result) { log.error("Error while loading file {}", f.getAbsolutePath()); return false; } else { log.debug("Successfully loaded {}", f.getAbsolutePath()); } return true; } boolean autoStartBrowser = false; transient ProgramAB chatBot; String currentConfigurationName = "default"; transient SpeechRecognizer ear; transient OpenCV opencv; transient Tracking eyesTracking; // waiting controable threaded gestures we warn user boolean gestureAlreadyStarted = false; // FIXME - what the hell is this for ? Set<String> gestures = new TreeSet<String>(); transient InMoov2Head head; transient Tracking headTracking; transient HtmlFilter htmlFilter; transient UltrasonicSensor ultrasonicRight; transient UltrasonicSensor ultrasonicLeft; transient Pir pir; transient ImageDisplay imageDisplay; /** * simple booleans to determine peer state of existence FIXME - should be an * auto-peer variable * * FIXME - sometime in the future there should just be a single simple * reference to a loaded "config" but at the moment the new UI depends on * these individual values :( * */ boolean isChatBotActivated = false; boolean isEarActivated = false; boolean isOpenCvActivated = false; boolean isEyeLidsActivated = false; boolean isHeadActivated = false; boolean isLeftArmActivated = false; boolean isLeftHandActivated = false; boolean isMouthActivated = false; // adding to the problem :( :( :( boolean isAudioPlayerActivated = true; boolean isRightArmActivated = false; boolean isRightHandActivated = false; boolean isSimulatorActivated = false; boolean isTorsoActivated = false; boolean isNeopixelActivated = false; boolean isPirActivated = false; boolean isUltrasonicRightActivated = false; boolean isUltrasonicLeftActivated = false; boolean isServoMixerActivated = false; boolean isController3Activated = false; // TODO - refactor into a Simulator interface when more simulators are borgd transient JMonkeyEngine simulator; String lastGestureExecuted; Long lastPirActivityTime; transient InMoov2Arm leftArm; transient InMoov2Hand leftHand; /** * supported locales */ Map<String, Locale> locales = null; int maxInactivityTimeSeconds = 120; transient SpeechSynthesis mouth; // FIXME ugh - new MouthControl service that uses AudioFile output transient public MouthControl mouthControl; boolean mute = false; transient NeoPixel neopixel; transient ServoMixer servoMixer; transient Python python; transient InMoov2Arm rightArm; transient InMoov2Hand rightHand; transient InMoov2Torso torso; @Deprecated public Vision vision; // FIXME - remove all direct references // transient private HashMap<String, InMoov2Arm> arms = new HashMap<>(); protected List<Voice> voices = null; protected String voiceSelected; transient WebGui webgui; protected List<String> configList; private boolean isController4Activated; private boolean isLeftHandSensorActivated; private boolean isLeftPortActivated; private boolean isRightHandSensorActivated; private boolean isRightPortActivated; public InMoov2(String n, String id) { super(n, id); // InMoov2 has a huge amount of peers setAutoStartPeers(false); // by default all servos will auto-disable // Servo.setAutoDisableDefault(true); //until peer servo services for // InMoov2 have the auto disable behavior, we should keep this // same as created in runtime - send asyc message to all // registered services, this service has started // find all servos - set them all to autoDisable(true) // onStarted(name) will handle all future created servos List<ServiceInterface> services = Runtime.getServices(); for (ServiceInterface si : services) { if ("Servo".equals(si.getSimpleName())) { send(si.getFullName(), "setAutoDisable", true); } } // dynamically gotten from filesystem/bots ? locales = Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN", "it-IT", "fi-FI", "pt-PT", "tr-TR"); locale = Runtime.getInstance().getLocale(); // REALLY NEEDS TO BE CLEANED UP - no direct references // "publish" scripts which should be executed :( // python = (Python) startPeer("python"); python = (Python) Runtime.start("python", "Python"); // this crud should // stop // load(locale.getTag()); WTH ? // get events of new services and shutdown Runtime r = Runtime.getInstance(); subscribe(r.getName(), "shutdown"); subscribe(r.getName(), "publishConfigList"); // FIXME - Framework should auto-magically auto-start peers AFTER // construction - unless explicitly told not to // peers to start on construction // imageDisplay = (ImageDisplay) startPeer("imageDisplay"); } @Override /* local strong type - is to be avoided - use name string */ public void addTextListener(TextListener service) { // CORRECT WAY ! - no direct reference - just use the name in a subscription addListener("publishText", service.getName()); } @Override public void attachTextListener(TextListener service) { attachTextListener(service.getName()); } /** * comes in from runtime which owns the config list * * @param configList * list of configs */ public void onConfigList(List<String> configList) { this.configList = configList; invoke("publishConfigList"); } /** * "re"-publishing runtime config list, because I don't want to fix the js * subscribeTo :P * * @return list of config names */ public List<String> publishConfigList() { return configList; } public void attachTextPublisher(String name) { subscribe(name, "publishText"); } @Override public void attachTextPublisher(TextPublisher service) { subscribe(service.getName(), "publishText"); } public void beginCheckingOnInactivity() { beginCheckingOnInactivity(maxInactivityTimeSeconds); } public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) { this.maxInactivityTimeSeconds = maxInactivityTimeSeconds; // speakBlocking("power down after %s seconds inactivity is on", // this.maxInactivityTimeSeconds); log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds); addTask("checkInactivity", 5 * 1000, 0, "checkInactivity"); } public long checkInactivity() { // speakBlocking("checking"); long lastActivityTime = getLastActivityTime(); long now = System.currentTimeMillis(); long inactivitySeconds = (now - lastActivityTime) / 1000; if (inactivitySeconds > maxInactivityTimeSeconds) { // speakBlocking("%d seconds have passed without activity", // inactivitySeconds); powerDown(); } else { // speakBlocking("%d seconds have passed without activity", // inactivitySeconds); info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds); } return lastActivityTime; } public void closeAllImages() { // imageDisplay.closeAll(); log.error("implement webgui.closeAllImages"); } public void cycleGestures() { // if not loaded load - // FIXME - this needs alot of "help" :P // WHY IS THIS DONE ? if (gestures.size() == 0) { loadGestures(); } for (String gesture : gestures) { try { String methodName = gesture.substring(0, gesture.length() - 3); speakBlocking(methodName); log.info("executing gesture {}", methodName); python.eval(methodName + "()"); // wait for finish - or timeout ? } catch (Exception e) { error(e); } } } public void disable() { if (head != null) { head.disable(); } if (rightHand != null) { rightHand.disable(); } if (leftHand != null) { leftHand.disable(); } if (rightArm != null) { rightArm.disable(); } if (leftArm != null) { leftArm.disable(); } if (torso != null) { torso.disable(); } } public void displayFullScreen(String src) { try { if (imageDisplay == null) { imageDisplay = (ImageDisplay) startPeer("imageDisplay"); } imageDisplay.displayFullScreen(src); log.error("implement webgui.displayFullScreen"); } catch (Exception e) { error("could not display picture %s", src); } } public void enable() { if (head != null) { head.enable(); } if (rightHand != null) { rightHand.enable(); } if (leftHand != null) { leftHand.enable(); } if (rightArm != null) { rightArm.enable(); } if (leftArm != null) { leftArm.enable(); } if (torso != null) { torso.enable(); } } /** * This method will try to launch a python command with error handling * * @param gesture * the gesture * @return gesture result */ public String execGesture(String gesture) { lastGestureExecuted = gesture; if (python == null) { log.warn("execGesture : No jython engine..."); return null; } subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); startedGesture(lastGestureExecuted); return python.evalAndWait(gesture); } public void finishedGesture() { finishedGesture("unknown"); } public void finishedGesture(String nameOfGesture) { if (gestureAlreadyStarted) { waitTargetPos(); RobotCanMoveRandom = true; gestureAlreadyStarted = false; log.info("gesture : {} finished...", nameOfGesture); } } public void fullSpeed() { if (head != null) { head.fullSpeed(); } if (rightHand != null) { rightHand.fullSpeed(); } if (leftHand != null) { leftHand.fullSpeed(); } if (rightArm != null) { rightArm.fullSpeed(); } if (leftArm != null) { leftArm.fullSpeed(); } if (torso != null) { torso.fullSpeed(); } } public String get(String key) { String ret = localize(key); if (ret != null) { return ret; } return "not yet translated"; } public InMoov2Arm getArm(String side) { if ("left".equals(side)) { return leftArm; } else if ("right".equals(side)) { return rightArm; } else { log.error("can not get arm {}", side); } return null; } public InMoov2Hand getHand(String side) { if ("left".equals(side)) { return leftHand; } else if ("right".equals(side)) { return rightHand; } else { log.error("can not get arm {}", side); } return null; } public InMoov2Head getHead() { return head; } /** * finds most recent activity * * @return the timestamp of the last activity time. */ public long getLastActivityTime() { long lastActivityTime = 0; if (leftHand != null) { lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime()); } if (leftArm != null) { lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime()); } if (rightHand != null) { lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime()); } if (rightArm != null) { lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime()); } if (head != null) { lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime()); } if (torso != null) { lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime()); } if (lastPirActivityTime != null) { lastActivityTime = Math.max(lastActivityTime, lastPirActivityTime); } if (lastActivityTime == 0) { error("invalid activity time - anything connected?"); lastActivityTime = System.currentTimeMillis(); } return lastActivityTime; } public InMoov2Arm getLeftArm() { return leftArm; } public InMoov2Hand getLeftHand() { return leftHand; } @Override public Map<String, Locale> getLocales() { return locales; } public InMoov2Arm getRightArm() { return rightArm; } public InMoov2Hand getRightHand() { return rightHand; } public Simulator getSimulator() { return simulator; } public InMoov2Torso getTorso() { return torso; } public void halfSpeed() { if (head != null) { head.setSpeed(25.0, 25.0, 25.0, 25.0, 100.0, 25.0); } if (rightHand != null) { rightHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0); } if (leftHand != null) { leftHand.setSpeed(30.0, 30.0, 30.0, 30.0, 30.0, 30.0); } if (rightArm != null) { rightArm.setSpeed(25.0, 25.0, 25.0, 25.0); } if (leftArm != null) { leftArm.setSpeed(25.0, 25.0, 25.0, 25.0); } if (torso != null) { torso.setSpeed(20.0, 20.0, 20.0); } } public boolean isCameraOn() { if (opencv != null) { if (opencv.isCapturing()) { return true; } } return false; } public boolean isEyeLidsActivated() { return isEyeLidsActivated; } public boolean isHeadActivated() { return isHeadActivated; } public boolean isLeftArmActivated() { return isLeftArmActivated; } public boolean isLeftHandActivated() { return isLeftHandActivated; } public boolean isMute() { return mute; } public boolean isNeopixelActivated() { return isNeopixelActivated; } public boolean isRightArmActivated() { return isRightArmActivated; } public boolean isRightHandActivated() { return isRightHandActivated; } public boolean isTorsoActivated() { return isTorsoActivated; } public boolean isPirActivated() { return isPirActivated; } public boolean isUltrasonicRightActivated() { return isUltrasonicRightActivated; } public boolean isUltrasonicLeftActivated() { return isUltrasonicLeftActivated; } // by default all servos will auto-disable // TODO: KW : make peer servo services for InMoov2 have the auto disable // behavior. // Servo.setAutoDisableDefault(true); public boolean isServoMixerActivated() { return isServoMixerActivated; } public void loadGestures() { loadGestures(getResourceDir() + fs + "gestures"); } /** * This blocking method will look at all of the .py files in a directory. One * by one it will load the files into the python interpreter. A gesture python * file should contain 1 method definition that is the same as the filename. * * @param directory * - the directory that contains the gesture python files. * @return true/false */ public boolean loadGestures(String directory) { speakBlocking(get("STARTINGGESTURES")); // iterate over each of the python files in the directory // and load them into the python interpreter. String extension = "py"; Integer totalLoaded = 0; Integer totalError = 0; File dir = new File(directory); dir.mkdirs(); if (dir.exists()) { for (File f : dir.listFiles()) { if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) { if (loadFile(f.getAbsolutePath()) == true) { totalLoaded += 1; String methodName = f.getName().substring(0, f.getName().length() - 3) + "()"; gestures.add(methodName); } else { error("could not load %s", f.getName()); totalError += 1; } } else { log.info("{} is not a {} file", f.getAbsolutePath(), extension); } } } info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError); broadcastState(); if (totalError > 0) { speakAlert(get("GESTURE_ERROR")); return false; } return true; } public void cameraOff() { if (opencv != null) { opencv.stopCapture(); opencv.disableAll(); } } public void cameraOn() { try { if (opencv == null) { startOpenCV(); } opencv.capture(); } catch (Exception e) { error(e); } } public void moveLeftArm(Double bicep, Double rotate, Double shoulder, Double omoplate) { moveArm("left", bicep, rotate, shoulder, omoplate); } public void moveRightArm(Double bicep, Double rotate, Double shoulder, Double omoplate) { moveArm("right", bicep, rotate, shoulder, omoplate); } public void moveArm(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) { InMoov2Arm arm = getArm(which); if (arm == null) { info("%s arm not started", which); return; } arm.moveTo(bicep, rotate, shoulder, omoplate); } public void moveEyelids(Double eyelidleftPos, Double eyelidrightPos) { if (head != null) { head.moveEyelidsTo(eyelidleftPos, eyelidrightPos); } else { log.warn("moveEyelids - I have a null head"); } } public void moveEyes(Double eyeX, Double eyeY) { if (head != null) { head.moveTo(null, null, eyeX, eyeY, null, null); } else { log.warn("moveEyes - I have a null head"); } } public void moveRightHand(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { moveHand("right", thumb, index, majeure, ringFinger, pinky, wrist); } public void moveRightHand(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) { moveHand("right", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist); } public void moveLeftHand(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { moveHand("left", thumb, index, majeure, ringFinger, pinky, wrist); } public void moveLeftHand(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) { moveHand("left", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist); } public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { moveHand(which, thumb, index, majeure, ringFinger, pinky, null); } public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { InMoov2Hand hand = getHand(which); if (hand == null) { log.warn("{} hand does not exist", hand); return; } hand.moveTo(thumb, index, majeure, ringFinger, pinky, wrist); } public void moveHead(Double neck, Double rothead) { moveHead(neck, rothead, null, null, null, null); } public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw) { moveHead(neck, rothead, eyeX, eyeY, jaw, null); } public void moveHead(Double neck, Double rothead, Double rollNeck) { moveHead(rollNeck, rothead, null, null, null, rollNeck); } public void moveHead(Integer neck, Integer rothead, Integer rollNeck) { moveHead((double) rollNeck, (double) rothead, null, null, null, (double) rollNeck); } public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) { if (head != null) { head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck); } else { log.error("I have a null head"); } } public void moveHeadBlocking(Double neck, Double rothead) { moveHeadBlocking(neck, rothead, null); } public void moveHeadBlocking(Double neck, Double rothead, Double rollNeck) { moveHeadBlocking(neck, rothead, null, null, null, rollNeck); } public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw) { moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null); } public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) { if (head != null) { head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck); } else { log.error("I have a null head"); } } public void moveTorso(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.moveTo(topStom, midStom, lowStom); } else { log.error("moveTorso - I have a null torso"); } } public void moveTorsoBlocking(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.moveToBlocking(topStom, midStom, lowStom); } else { log.error("moveTorsoBlocking - I have a null torso"); } } public void onGestureStatus(Status status) { if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) { error("I cannot execute %s, please check logs", lastGestureExecuted); } finishedGesture(lastGestureExecuted); unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus"); } @Override public void onJoystickInput(JoystickData input) throws Exception { // TODO Auto-generated method stub } public OpenCVData onOpenCVData(OpenCVData data) { return data; } @Override public void onText(String text) { // FIXME - we should be able to "re"-publish text but text is coming from // different sources // some might be coming from the ear - some from the mouth ... - there has // to be a distinction log.info("onText - {}", text); invoke("publishText", text); } // TODO FIX/CHECK this, migrate from python land public void powerDown() { rest(); purgeTasks(); disable(); if (ear != null) { ear.lockOutAllGrammarExcept("power up"); } python.execMethod("power_down"); } // TODO FIX/CHECK this, migrate from python land public void powerUp() { enable(); rest(); if (ear != null) { ear.clearLock(); } beginCheckingOnInactivity(); python.execMethod("power_up"); } /** * all published text from InMoov2 - including ProgramAB */ @Override public String publishText(String text) { return text; } public void releaseService() { try { disable(); releasePeers(); super.releaseService(); } catch (Exception e) { error(e); } } // FIXME NO DIRECT REFERENCES - publishRest --> (onRest) --> rest public void rest() { log.info("InMoov2.rest()"); if (head != null) { head.rest(); } if (rightHand != null) { rightHand.rest(); } if (leftHand != null) { leftHand.rest(); } if (rightArm != null) { rightArm.rest(); } if (leftArm != null) { leftArm.rest(); } if (torso != null) { torso.rest(); } } public void setLeftArmSpeed(Double bicep, Double rotate, Double shoulder, Double omoplate) { setArmSpeed("left", bicep, rotate, shoulder, omoplate); } public void setLeftArmSpeed(Integer bicep, Integer rotate, Integer shoulder, Integer omoplate) { setArmSpeed("left", (double) bicep, (double) rotate, (double) shoulder, (double) omoplate); } public void setRightArmSpeed(Double bicep, Double rotate, Double shoulder, Double omoplate) { setArmSpeed("right", bicep, rotate, shoulder, omoplate); } public void setRightArmSpeed(Integer bicep, Integer rotate, Integer shoulder, Integer omoplate) { setArmSpeed("right", (double) bicep, (double) rotate, (double) shoulder, (double) omoplate); } public void setArmSpeed(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) { InMoov2Arm arm = getArm(which); if (arm == null) { warn("%s arm not started", which); return; } arm.setSpeed(bicep, rotate, shoulder, omoplate); } @Deprecated public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) { setArmSpeed(which, bicep, rotate, shoulder, omoplate); } public void setAutoDisable(Boolean param) { if (head != null) { head.setAutoDisable(param); } if (rightArm != null) { rightArm.setAutoDisable(param); } if (leftArm != null) { leftArm.setAutoDisable(param); } if (leftHand != null) { leftHand.setAutoDisable(param); } if (rightHand != null) { leftHand.setAutoDisable(param); } if (torso != null) { torso.setAutoDisable(param); } /* * if (eyelids != null) { eyelids.setAutoDisable(param); } */ } public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null); } public void setLeftHandSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { setHandSpeed("left", thumb, index, majeure, ringFinger, pinky, wrist); } public void setLeftHandSpeed(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) { setHandSpeed("left", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist); } public void setRightHandSpeed(Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { setHandSpeed("right", thumb, index, majeure, ringFinger, pinky, wrist); } public void setRightHandSpeed(Integer thumb, Integer index, Integer majeure, Integer ringFinger, Integer pinky, Integer wrist) { setHandSpeed("right", (double) thumb, (double) index, (double) majeure, (double) ringFinger, (double) pinky, (double) wrist); } public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { InMoov2Hand hand = getHand(which); if (hand == null) { warn("%s hand not started", which); return; } hand.setSpeed(thumb, index, majeure, ringFinger, pinky, wrist); } @Deprecated public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null); } @Deprecated public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) { setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, wrist); } public void setHeadSpeed(Double rothead, Double neck) { setHeadSpeed(rothead, neck, null, null, null); } public void setHeadSpeed(Double rothead, Double neck, Double rollNeck) { setHeadSpeed(rothead, neck, null, null, null, rollNeck); } public void setHeadSpeed(Integer rothead, Integer neck, Integer rollNeck) { setHeadSpeed((double) rothead, (double) neck, null, null, null, (double) rollNeck); } public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null); } public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) { if (head == null) { warn("setHeadSpeed - head not started"); return; } head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed); } @Deprecated public void setHeadVelocity(Double rothead, Double neck) { setHeadSpeed(rothead, neck, null, null, null, null); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) { setHeadSpeed(rothead, neck, null, null, null, rollNeck); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null); } @Deprecated public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) { setHeadSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed); } @Override public void setLocale(String code) { if (code == null) { log.warn("setLocale null"); return; } // filter of the set of supported locales if (!Locale.hasLanguage(locales, code)) { error("InMoov does not support %s only %s", code, locales.keySet()); return; } super.setLocale(code); for (ServiceInterface si : Runtime.getLocalServices().values()) { if (!si.equals(this)) { si.setLocale(code); } } } public void setMute(boolean mute) { info("Set mute to %s", mute); this.mute = mute; sendToPeer("mouth", "setMute", mute); broadcastState(); } public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) { if (neopixel != null) { neopixel.setAnimation(animation, red, green, blue, speed); } else { warn("No Neopixel attached"); } } public String setSpeechType(String speechType) { serviceType.setPeer("mouth", speechType); broadcastState(); return speechType; } public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.setSpeed(topStom, midStom, lowStom); } else { log.warn("setTorsoSpeed - I have no torso"); } } public void setTorsoSpeed(Integer topStom, Integer midStom, Integer lowStom) { setTorsoSpeed((double) topStom, (double) midStom, (double) lowStom); } @Deprecated public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) { if (torso != null) { torso.setVelocity(topStom, midStom, lowStom); } else { log.warn("setTorsoVelocity - I have no torso"); } } public boolean setAllVirtual(boolean virtual) { Runtime.setAllVirtual(virtual); speakBlocking(get("STARTINGVIRTUALHARD")); return virtual; } public void setVoice(String name) { if (mouth != null) { mouth.setVoice(name); voiceSelected = name; speakBlocking(String.format("%s %s", get("SETLANG"), name)); } } public void speak(String toSpeak) { sendToPeer("mouth", "speak", toSpeak); } public void speakAlert(String toSpeak) { speakBlocking(get("ALERT")); speakBlocking(toSpeak); } public void speakBlocking(String speak) { speakBlocking(speak, (Object[]) null); } // FIXME - publish text regardless if mouth exists ... public void speakBlocking(String format, Object... args) { if (format == null) { return; } String toSpeak = format; if (args != null) { toSpeak = String.format(format, args); } // FIXME - publish onText when listening invoke("publishText", toSpeak); if (!mute && isPeerStarted("mouth")) { // sendToPeer("mouth", "speakBlocking", toSpeak); invokePeer("mouth", "speakBlocking", toSpeak); } } public void startAll() throws Exception { startAll(null, null); } public void startAll(String leftPort, String rightPort) throws Exception { startMouth(); startChatBot(); // startHeadTracking(); // startEyesTracking(); // startOpenCV(); startEar(); startServos(leftPort, rightPort); // startMouthControl(head.jaw, mouth); speakBlocking(get("STARTINGSEQUENCE")); } /** * start servos - no controllers * * @throws Exception * boom */ public void startServos() throws Exception { startServos(null, null); } public ProgramAB startChatBot() { try { chatBot = (ProgramAB) startPeer("chatBot"); isChatBotActivated = true; if (locale != null) { chatBot.setCurrentBotName(locale.getTag()); } speakBlocking(get("CHATBOTACTIVATED")); chatBot.attachTextPublisher(ear); // this.attach(chatBot); FIXME - attach as a TextPublisher - then // re-publish // FIXME - deal with language // speakBlocking(get("CHATBOTACTIVATED")); chatBot.repetitionCount(10); // chatBot.setPath(getResourceDir() + fs + "chatbot"); chatBot.setPath(getDataDir() + fs + "chatbot"); chatBot.startSession("default", locale.getTag()); // reset some parameters to default... chatBot.setPredicate("topic", "default"); chatBot.setPredicate("questionfirstinit", ""); chatBot.setPredicate("tmpname", ""); chatBot.setPredicate("null", ""); // load last user session if (!chatBot.getPredicate("name").isEmpty()) { if (chatBot.getPredicate("lastUsername").isEmpty() || chatBot.getPredicate("lastUsername").equals("unknown")) { chatBot.setPredicate("lastUsername", chatBot.getPredicate("name")); } } chatBot.setPredicate("parameterHowDoYouDo", ""); try { chatBot.savePredicates(); } catch (IOException e) { log.error("saving predicates threw", e); } // start session based on last recognized person // if (!chatBot.getPredicate("default", "lastUsername").isEmpty() && // !chatBot.getPredicate("default", "lastUsername").equals("unknown")) { // chatBot.startSession(chatBot.getPredicate("lastUsername")); if (!chatBot.getPredicate("Friend", "firstinit").isEmpty() && !chatBot.getPredicate("Friend", "firstinit").equals("unknown") && !chatBot.getPredicate("Friend", "firstinit").equals("started")) { chatBot.getResponse("FIRST_INIT"); } else { chatBot.getResponse("WAKE_UP"); } htmlFilter = (HtmlFilter) startPeer("htmlFilter");// Runtime.start("htmlFilter", // "HtmlFilter"); chatBot.attachTextListener(htmlFilter); htmlFilter.attachTextListener((TextListener) getPeer("mouth")); chatBot.attachTextListener(this); } catch (Exception e) { speak("could not load chatBot"); error(e.getMessage()); speak(e.getMessage()); } broadcastState(); return chatBot; } public SpeechRecognizer startEar() { ear = (SpeechRecognizer) startPeer("ear"); isEarActivated = true; ear.attachSpeechSynthesis((SpeechSynthesis) getPeer("mouth")); ear.attachTextListener(chatBot); speakBlocking(get("STARTINGEAR")); broadcastState(); return ear; } public void startedGesture() { startedGesture("unknown"); } public void startedGesture(String nameOfGesture) { if (gestureAlreadyStarted) { warn("Warning 1 gesture already running, this can break spacetime and lot of things"); } else { log.info("Starting gesture : {}", nameOfGesture); gestureAlreadyStarted = true; RobotCanMoveRandom = false; } } // FIXME - universal (good) way of handling all exceptions - ie - reporting // back to the user the problem in a short concise way but have // expandable detail in appropriate places public OpenCV startOpenCV() throws Exception { speakBlocking(get("STARTINGOPENCV")); opencv = (OpenCV) startPeer("opencv"); subscribeTo(opencv.getName(), "publishOpenCVData"); isOpenCvActivated = true; return opencv; } public OpenCV getOpenCV() { return opencv; } public void setOpenCV(OpenCV opencv) { this.opencv = opencv; } public Tracking startEyesTracking() throws Exception { if (head == null) { startHead(); } // TODO: pass the PID values for the eye tracking return startHeadTracking(head.eyeX, head.eyeY); } public Tracking startEyesTracking(ServoControl eyeX, ServoControl eyeY) throws Exception { if (opencv == null) { startOpenCV(); } speakBlocking(get("TRACKINGSTARTED")); eyesTracking = (Tracking) this.startPeer("eyesTracking"); eyesTracking.attach(opencv.getName()); eyesTracking.attachPan(head.eyeX.getName()); eyesTracking.attachTilt(head.eyeY.getName()); return eyesTracking; } public InMoov2Head startHead() throws Exception { return startHead(null, null, null, null, null, null, null, null); } public InMoov2Head startHead(String port) throws Exception { return startHead(port, null, null, null, null, null, null, null); } // legacy inmoov head exposed pins public InMoov2Head startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) { speakBlocking(get("STARTINGHEAD")); head = (InMoov2Head) startPeer("head"); isHeadActivated = true; if (headYPin != null) { head.setPins(headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin); } // lame assumption - port is specified - it must be an Arduino :( if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left"); arduino.connect(port); arduino.attach(head.neck); arduino.attach(head.rothead); arduino.attach(head.eyeX); arduino.attach(head.eyeY); arduino.attach(head.jaw); // FIXME rollNeck and eyelids must be connected to right controller // arduino.attach(head.rollNeck); // arduino.attach(head.eyelidLeft); // arduino.attach(head.eyelidRight); } catch (Exception e) { error(e); } } speakBlocking(get("STARTINGMOUTHCONTROL")); mouthControl = (MouthControl) startPeer("mouthControl"); mouthControl.attach(head.jaw); mouthControl.attach((Attachable) getPeer("mouth")); mouthControl.setmouth(10, 50);// <-- FIXME - not the right place for // config !!! return head; } public void startHeadTracking() throws Exception { if (opencv == null) { startOpenCV(); } if (head == null) { startHead(); } if (headTracking == null) { speakBlocking(get("TRACKINGSTARTED")); headTracking = (Tracking) this.startPeer("headTracking"); headTracking.attach(opencv.getName()); headTracking.attachPan(head.rothead.getName()); headTracking.attachTilt(head.neck.getName()); // TODO: where are the PID values? } } public Tracking startHeadTracking(ServoControl rothead, ServoControl neck) throws Exception { if (opencv == null) { startOpenCV(); } if (headTracking == null) { speakBlocking(get("TRACKINGSTARTED")); headTracking = (Tracking) this.startPeer("headTracking"); headTracking.attach(opencv.getName()); headTracking.attachPan(rothead.getName()); headTracking.attachTilt(neck.getName()); // TODO: where are the PID values? } return headTracking; } public InMoov2Arm startLeftArm() { return startLeftArm(null); } public InMoov2Arm startLeftArm(String port) { // log.warn(InMoov.buildDNA(myKey, serviceClass)) // speakBlocking(get("STARTINGHEAD") + " " + port); // ??? SHOULD THERE BE REFERENCES AT ALL ??? ... probably not speakBlocking(get("STARTINGLEFTARM")); leftArm = (InMoov2Arm) startPeer("leftArm"); isLeftArmActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left"); arduino.connect(port); arduino.attach(leftArm.bicep); arduino.attach(leftArm.omoplate); arduino.attach(leftArm.rotate); arduino.attach(leftArm.shoulder); } catch (Exception e) { error(e); } } return leftArm; } public InMoov2Hand startLeftHand() { return startLeftHand(null); } public InMoov2Hand startLeftHand(String port) { speakBlocking(get("STARTINGLEFTHAND")); leftHand = (InMoov2Hand) startPeer("leftHand"); isLeftHandActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("left"); arduino.connect(port); arduino.attach(leftHand.thumb); arduino.attach(leftHand.index); arduino.attach(leftHand.majeure); arduino.attach(leftHand.ringFinger); arduino.attach(leftHand.pinky); arduino.attach(leftHand.wrist); } catch (Exception e) { error(e); } } return leftHand; } // TODO - general objective "might" be to reduce peers down to something // that does not need a reference - where type can be switched before creation // and the only thing needed is pubs/subs that are not handled in abstracts public SpeechSynthesis startMouth() { // FIXME - bad to have a reference, should only need the "name" of the // service !!! mouth = (SpeechSynthesis) startPeer("mouth"); voices = mouth.getVoices(); Voice voice = mouth.getVoice(); if (voice != null) { voiceSelected = voice.getName(); } isMouthActivated = true; if (mute) { mouth.setMute(true); } mouth.attachSpeechRecognizer(ear); // mouth.attach(htmlFilter); // same as chatBot not needed // this.attach((Attachable) mouth); // if (ear != null) .... broadcastState(); speakBlocking(get("STARTINGMOUTH")); if (Platform.isVirtual()) { speakBlocking(get("STARTINGVIRTUALHARD")); } speakBlocking(get("WHATISTHISLANGUAGE")); return mouth; } public InMoov2Arm startRightArm() { return startRightArm(null); } public InMoov2Arm startRightArm(String port) { speakBlocking(get("STARTINGRIGHTARM")); rightArm = (InMoov2Arm) startPeer("rightArm"); isRightArmActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("right"); arduino.connect(port); arduino.attach(rightArm.bicep); arduino.attach(rightArm.omoplate); arduino.attach(rightArm.rotate); arduino.attach(rightArm.shoulder); } catch (Exception e) { error(e); } } return rightArm; } public InMoov2Hand startRightHand() { return startRightHand(null); } public InMoov2Hand startRightHand(String port) { speakBlocking(get("STARTINGRIGHTHAND")); rightHand = (InMoov2Hand) startPeer("rightHand"); isRightHandActivated = true; if (port != null) { try { speakBlocking(port); Arduino arduino = (Arduino) startPeer("right"); arduino.connect(port); arduino.attach(rightHand.thumb); arduino.attach(rightHand.index); arduino.attach(rightHand.majeure); arduino.attach(rightHand.ringFinger); arduino.attach(rightHand.pinky); arduino.attach(rightHand.wrist); } catch (Exception e) { error(e); } } return rightHand; } public Double getUltrasonicRightDistance() { if (ultrasonicRight != null) { return ultrasonicRight.range(); } else { warn("No UltrasonicRight attached"); return 0.0; } } public Double getUltrasonicLeftDistance() { if (ultrasonicLeft != null) { return ultrasonicLeft.range(); } else { warn("No UltrasonicLeft attached"); return 0.0; } } // public void publishPin(Pin pin) { // log.info("{} - {}", pin.pin, pin.value); // if (pin.value == 1) { // lastPIRActivityTime = System.currentTimeMillis(); /// if its PIR & PIR is active & was sleeping - then wake up ! // if (pin == pin.pin && startSleep != null && pin.value == 1) { // powerUp(); public void startServos(String leftPort, String rightPort) throws Exception { startHead(leftPort); startLeftArm(leftPort); startLeftHand(leftPort); startRightArm(rightPort); startRightHand(rightPort); startTorso(leftPort); } // FIXME .. externalize in a json file included in InMoov2 public Simulator startSimulator() throws Exception { speakBlocking(get("STARTINGVIRTUAL")); if (simulator != null) { log.info("start called twice - starting simulator is reentrant"); return simulator; } simulator = (JMonkeyEngine) startPeer("simulator"); // DEPRECATED - should just user peer info isSimulatorActivated = true; // adding InMoov2 asset path to the jmonkey simulator String assetPath = getResourceDir() + fs + JMonkeyEngine.class.getSimpleName(); File check = new File(assetPath); log.info("loading assets from {}", assetPath); if (!check.exists()) { log.warn("%s does not exist"); } // disable the frustrating servo events ... // Servo.eventsEnabledDefault(false); // jme.loadModels(assetPath); not needed - as InMoov2 unzips the model into // /resource/JMonkeyEngine/assets simulator.loadModels(assetPath); simulator.setRotation(getName() + ".head.jaw", "x"); simulator.setRotation(getName() + ".head.neck", "x"); simulator.setRotation(getName() + ".head.rothead", "y"); simulator.setRotation(getName() + ".head.rollNeck", "z"); simulator.setRotation(getName() + ".head.eyeY", "x"); simulator.setRotation(getName() + ".head.eyeX", "y"); //simulator.setRotation(getName() + ".head.eyelidLeft", "x");FIXME we need to modelize them in Blender //simulator.setRotation(getName() + ".head.eyelidRight", "x");FIXME we need to modelize them in Blender simulator.setRotation(getName() + ".torso.topStom", "z"); simulator.setRotation(getName() + ".torso.midStom", "y"); simulator.setRotation(getName() + ".torso.lowStom", "x"); simulator.setRotation(getName() + ".rightArm.bicep", "x"); simulator.setRotation(getName() + ".leftArm.bicep", "x"); simulator.setRotation(getName() + ".rightArm.shoulder", "x"); simulator.setRotation(getName() + ".leftArm.shoulder", "x"); simulator.setRotation(getName() + ".rightArm.rotate", "y"); simulator.setRotation(getName() + ".leftArm.rotate", "y"); simulator.setRotation(getName() + ".rightArm.omoplate", "z"); simulator.setRotation(getName() + ".leftArm.omoplate", "z"); simulator.setRotation(getName() + ".rightHand.wrist", "y"); simulator.setRotation(getName() + ".leftHand.wrist", "y"); simulator.setMapper(getName() + ".head.jaw", 0, 180, -5, 80); simulator.setMapper(getName() + ".head.neck", 0, 180, 20, -20); simulator.setMapper(getName() + ".head.rollNeck", 0, 180, 30, -30); simulator.setMapper(getName() + ".head.eyeY", 0, 180, 40, 140); simulator.setMapper(getName() + ".head.eyeX", 0, 180, -10, 70); // HERE // there // need // to be // two eyeX (left and // right?) //simulator.setMapper(getName() + ".head.eyelidLeft", 0, 180, 40, 140);FIXME we need to modelize them in Blender //simulator.setMapper(getName() + ".head.eyelidRight", 0, 180, 40, 140);FIXME we need to modelize them in Blender simulator.setMapper(getName() + ".rightArm.bicep", 0, 180, 0, -150); simulator.setMapper(getName() + ".leftArm.bicep", 0, 180, 0, -150); simulator.setMapper(getName() + ".rightArm.shoulder", 0, 180, 30, -150); simulator.setMapper(getName() + ".leftArm.shoulder", 0, 180, 30, -150); simulator.setMapper(getName() + ".rightArm.rotate", 0, 180, 80, -80); simulator.setMapper(getName() + ".leftArm.rotate", 0, 180, -80, 80); simulator.setMapper(getName() + ".rightArm.omoplate", 0, 180, 10, -180); simulator.setMapper(getName() + ".leftArm.omoplate", 0, 180, -10, 180); simulator.setMapper(getName() + ".rightHand.wrist", 0, 180, -20, 60); simulator.setMapper(getName() + ".leftHand.wrist", 0, 180, 20, -60); simulator.setMapper(getName() + ".torso.topStom", 0, 180, -30, 30); simulator.setMapper(getName() + ".torso.midStom", 0, 180, 50, 130); simulator.setMapper(getName() + ".torso.lowStom", 0, 180, -30, 30); simulator.multiMap(getName() + ".leftHand.thumb", getName() + ".leftHand.thumb1", getName() + ".leftHand.thumb2", getName() + ".leftHand.thumb3"); simulator.setRotation(getName() + ".leftHand.thumb1", "y"); simulator.setRotation(getName() + ".leftHand.thumb2", "x"); simulator.setRotation(getName() + ".leftHand.thumb3", "x"); simulator.multiMap(getName() + ".leftHand.index", getName() + ".leftHand.index", getName() + ".leftHand.index2", getName() + ".leftHand.index3"); simulator.setRotation(getName() + ".leftHand.index", "x"); simulator.setRotation(getName() + ".leftHand.index2", "x"); simulator.setRotation(getName() + ".leftHand.index3", "x"); simulator.multiMap(getName() + ".leftHand.majeure", getName() + ".leftHand.majeure", getName() + ".leftHand.majeure2", getName() + ".leftHand.majeure3"); simulator.setRotation(getName() + ".leftHand.majeure", "x"); simulator.setRotation(getName() + ".leftHand.majeure2", "x"); simulator.setRotation(getName() + ".leftHand.majeure3", "x"); simulator.multiMap(getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger", getName() + ".leftHand.ringFinger2", getName() + ".leftHand.ringFinger3"); simulator.setRotation(getName() + ".leftHand.ringFinger", "x"); simulator.setRotation(getName() + ".leftHand.ringFinger2", "x"); simulator.setRotation(getName() + ".leftHand.ringFinger3", "x"); simulator.multiMap(getName() + ".leftHand.pinky", getName() + ".leftHand.pinky", getName() + ".leftHand.pinky2", getName() + ".leftHand.pinky3"); simulator.setRotation(getName() + ".leftHand.pinky", "x"); simulator.setRotation(getName() + ".leftHand.pinky2", "x"); simulator.setRotation(getName() + ".leftHand.pinky3", "x"); // left hand mapping complexities of the fingers simulator.setMapper(getName() + ".leftHand.index", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.index2", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.index3", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.majeure", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.majeure2", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.majeure3", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.ringFinger", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.ringFinger2", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.ringFinger3", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.pinky", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.pinky2", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.pinky3", 0, 180, -110, -179); simulator.setMapper(getName() + ".leftHand.thumb1", 0, 180, -30, -100); simulator.setMapper(getName() + ".leftHand.thumb2", 0, 180, 80, 20); simulator.setMapper(getName() + ".leftHand.thumb3", 0, 180, 80, 20); // right hand simulator.multiMap(getName() + ".rightHand.thumb", getName() + ".rightHand.thumb1", getName() + ".rightHand.thumb2", getName() + ".rightHand.thumb3"); simulator.setRotation(getName() + ".rightHand.thumb1", "y"); simulator.setRotation(getName() + ".rightHand.thumb2", "x"); simulator.setRotation(getName() + ".rightHand.thumb3", "x"); simulator.multiMap(getName() + ".rightHand.index", getName() + ".rightHand.index", getName() + ".rightHand.index2", getName() + ".rightHand.index3"); simulator.setRotation(getName() + ".rightHand.index", "x"); simulator.setRotation(getName() + ".rightHand.index2", "x"); simulator.setRotation(getName() + ".rightHand.index3", "x"); simulator.multiMap(getName() + ".rightHand.majeure", getName() + ".rightHand.majeure", getName() + ".rightHand.majeure2", getName() + ".rightHand.majeure3"); simulator.setRotation(getName() + ".rightHand.majeure", "x"); simulator.setRotation(getName() + ".rightHand.majeure2", "x"); simulator.setRotation(getName() + ".rightHand.majeure3", "x"); simulator.multiMap(getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger", getName() + ".rightHand.ringFinger2", getName() + ".rightHand.ringFinger3"); simulator.setRotation(getName() + ".rightHand.ringFinger", "x"); simulator.setRotation(getName() + ".rightHand.ringFinger2", "x"); simulator.setRotation(getName() + ".rightHand.ringFinger3", "x"); simulator.multiMap(getName() + ".rightHand.pinky", getName() + ".rightHand.pinky", getName() + ".rightHand.pinky2", getName() + ".rightHand.pinky3"); simulator.setRotation(getName() + ".rightHand.pinky", "x"); simulator.setRotation(getName() + ".rightHand.pinky2", "x"); simulator.setRotation(getName() + ".rightHand.pinky3", "x"); simulator.setMapper(getName() + ".rightHand.index", 0, 180, 65, -10); simulator.setMapper(getName() + ".rightHand.index2", 0, 180, 70, -10); simulator.setMapper(getName() + ".rightHand.index3", 0, 180, 70, -10); simulator.setMapper(getName() + ".rightHand.majeure", 0, 180, 65, -10); simulator.setMapper(getName() + ".rightHand.majeure2", 0, 180, 70, -10); simulator.setMapper(getName() + ".rightHand.majeure3", 0, 180, 70, -10); simulator.setMapper(getName() + ".rightHand.ringFinger", 0, 180, 65, -10); simulator.setMapper(getName() + ".rightHand.ringFinger2", 0, 180, 70, -10); simulator.setMapper(getName() + ".rightHand.ringFinger3", 0, 180, 70, -10); simulator.setMapper(getName() + ".rightHand.pinky", 0, 180, 65, -10); simulator.setMapper(getName() + ".rightHand.pinky2", 0, 180, 70, -10); simulator.setMapper(getName() + ".rightHand.pinky3", 0, 180, 60, -10); simulator.setMapper(getName() + ".rightHand.thumb1", 0, 180, 30, 110); simulator.setMapper(getName() + ".rightHand.thumb2", 0, 180, -100, -150); simulator.setMapper(getName() + ".rightHand.thumb3", 0, 180, -100, -160); // We set the correct location view simulator.cameraLookAt(getName() + ".torso.lowStom"); // additional experimental mappings /* * simulator.attach(getName() + ".leftHand.pinky", getName() + * ".leftHand.index2"); simulator.attach(getName() + ".leftHand.thumb", * getName() + ".leftHand.index3"); simulator.setRotation(getName() + * ".leftHand.index2", "x"); simulator.setRotation(getName() + * ".leftHand.index3", "x"); simulator.setMapper(getName() + * ".leftHand.index", 0, 180, -90, -270); simulator.setMapper(getName() + * ".leftHand.index2", 0, 180, -90, -270); simulator.setMapper(getName() + * ".leftHand.index3", 0, 180, -90, -270); */ return simulator; } public InMoov2Torso startTorso() { return startTorso(null); } public InMoov2Torso startTorso(String port) { if (torso == null) { speakBlocking(get("STARTINGTORSO")); isTorsoActivated = true; torso = (InMoov2Torso) startPeer("torso"); if (port != null) { try { speakBlocking(port); Arduino left = (Arduino) startPeer("left"); left.connect(port); left.attach(torso.lowStom); left.attach(torso.midStom); left.attach(torso.topStom); } catch (Exception e) { error(e); } } } return torso; } /** * called with only port - will default with defaulted pins * * @param port * port for the sensor * @return the ultrasonic sensor service */ public UltrasonicSensor startUltrasonicRight(String port) { return startUltrasonicRight(port, 64, 63); } /** * called explicitly with pin values * * @param port * p * @param trigPin * trigger pin * @param echoPin * echo pin * @return the ultrasonic sensor * */ public UltrasonicSensor startUltrasonicRight(String port, int trigPin, int echoPin) { if (ultrasonicRight == null) { speakBlocking(get("STARTINGULTRASONICRIGHT")); isUltrasonicRightActivated = true; ultrasonicRight = (UltrasonicSensor) startPeer("ultrasonicRight"); if (port != null) { try { speakBlocking(port); Arduino right = (Arduino) startPeer("right"); right.connect(port); right.attach(ultrasonicRight, trigPin, echoPin); } catch (Exception e) { error(e); } } } return ultrasonicRight; } public UltrasonicSensor startUltrasonicLeft() { return startUltrasonicLeft(null, 64, 63); } public UltrasonicSensor startUltrasonicRight() { return startUltrasonicRight(null, 64, 63); } public UltrasonicSensor startUltrasonicLeft(String port) { return startUltrasonicLeft(port, 64, 63); } public UltrasonicSensor startUltrasonicLeft(String port, int trigPin, int echoPin) { if (ultrasonicLeft == null) { speakBlocking(get("STARTINGULTRASONICLEFT")); isUltrasonicLeftActivated = true; ultrasonicLeft = (UltrasonicSensor) startPeer("ultrasonicLeft"); if (port != null) { try { speakBlocking(port); Arduino left = (Arduino) startPeer("left"); left.connect(port); left.attach(ultrasonicLeft, trigPin, echoPin); } catch (Exception e) { error(e); } } } return ultrasonicLeft; } public Pir startPir(String port) { return startPir(port, 23); } public Pir startPir(String port, int pin) { if (pir == null) { speakBlocking(get("STARTINGPIR")); isPirActivated = true; pir = (Pir) startPeer("pir"); if (port != null) { try { speakBlocking(port); Arduino right = (Arduino) startPeer("right"); right.connect(port); right.attachPinListener(pir, pin); } catch (Exception e) { error(e); } } } return pir; } /** * config delegated startPir ... hopefully * * @return */ public Pir startPir() { if (pir == null) { speakBlocking(get("STARTINGPIR")); isPirActivated = true; pir = (Pir) startPeer("pir"); try { pir.load(); // will this work ? // would be great if it did - offloading configuration // to the i01.pir.yml } catch (Exception e) { error(e); } } return pir; } public ServoMixer startServoMixer() { servoMixer = (ServoMixer) startPeer("servoMixer"); isServoMixerActivated = true; speakBlocking(get("STARTINGSERVOMIXER")); broadcastState(); return servoMixer; } public void stop() { if (head != null) { head.stop(); } if (rightHand != null) { rightHand.stop(); } if (leftHand != null) { leftHand.stop(); } if (rightArm != null) { rightArm.stop(); } if (leftArm != null) { leftArm.stop(); } if (torso != null) { torso.stop(); } } public void stopChatBot() { speakBlocking(get("STOPCHATBOT")); releasePeer("chatBot"); isChatBotActivated = false; } public void stopHead() { speakBlocking(get("STOPHEAD")); releasePeer("head"); releasePeer("mouthControl"); isHeadActivated = false; } public void stopEar() { speakBlocking(get("STOPEAR")); releasePeer("ear"); isEarActivated = false; broadcastState(); } public void stopOpenCV() { speakBlocking(get("STOPOPENCV")); isOpenCvActivated = false; releasePeer("opencv"); } public void stopGesture() { Python p = (Python) Runtime.getService("python"); p.stop(); } public void stopLeftArm() { speakBlocking(get("STOPLEFTARM")); releasePeer("leftArm"); isLeftArmActivated = false; } public void stopLeftHand() { speakBlocking(get("STOPLEFTHAND")); releasePeer("leftHand"); isLeftHandActivated = false; } public void stopMouth() { speakBlocking(get("STOPMOUTH")); releasePeer("mouth"); // TODO - potentially you could set the field to null in releasePeer mouth = null; isMouthActivated = false; } public void stopRightArm() { speakBlocking(get("STOPRIGHTARM")); releasePeer("rightArm"); isRightArmActivated = false; } public void stopRightHand() { speakBlocking(get("STOPRIGHTHAND")); releasePeer("rightHand"); isRightHandActivated = false; } public void stopTorso() { speakBlocking(get("STOPTORSO")); releasePeer("torso"); isTorsoActivated = false; } public void stopSimulator() { speakBlocking(get("STOPVIRTUAL")); releasePeer("simulator"); simulator = null; isSimulatorActivated = false; } public void stopUltrasonicRight() { speakBlocking(get("STOPULTRASONIC")); releasePeer("ultrasonicRight"); isUltrasonicRightActivated = false; } public void stopUltrasonicLeft() { speakBlocking(get("STOPULTRASONIC")); releasePeer("ultrasonicLeft"); isUltrasonicLeftActivated = false; } public void stopPir() { speakBlocking(get("STOPPIR")); releasePeer("pir"); isPirActivated = false; } public void stopNeopixelAnimation() { if (neopixel != null) { neopixel.clear(); } else { warn("No Neopixel attached"); } } public void stopServoMixer() { speakBlocking(get("STOPSERVOMIXER")); releasePeer("servoMixer"); isServoMixerActivated = false; } public void waitTargetPos() { if (head != null) { head.waitTargetPos(); } if (leftArm != null) { leftArm.waitTargetPos(); } if (rightArm != null) { rightArm.waitTargetPos(); } if (leftHand != null) { leftHand.waitTargetPos(); } if (rightHand != null) { rightHand.waitTargetPos(); } if (torso != null) { torso.waitTargetPos(); } } public NeoPixel startNeopixel() { return startNeopixel(getName() + ".right", 2, 16); } public NeoPixel startNeopixel(String controllerName) { return startNeopixel(controllerName, 2, 16); } public NeoPixel startNeopixel(String controllerName, int pin, int numPixel) { if (neopixel == null) { try { neopixel = (NeoPixel) startPeer("neopixel"); speakBlocking(get("STARTINGNEOPIXEL")); // FIXME - lame use peers isNeopixelActivated = true; neopixel.attach(Runtime.getService(controllerName)); } catch (Exception e) { error(e); } } return neopixel; } @Override public void attachTextListener(String name) { addListener("publishText", name); } public Tracking getEyesTracking() { return eyesTracking; } public Tracking getHeadTracking() { return headTracking; } public void startBrain() { startChatBot(); } public void startMouthControl() { speakBlocking(get("STARTINGMOUTHCONTROL")); mouthControl = (MouthControl) startPeer("mouthControl"); mouthControl.attach(head.jaw); mouthControl.attach((Attachable) getPeer("mouth")); } @Deprecated /* wrong function name should be startPir */ public void startPIR(String port, int pin) { startPir(port, pin); } // These are methods added that were in InMoov1 that we no longer had in // InMoov2. // From original InMoov1 so we don't loose the @Override public void onJointAngles(Map<String, Double> angleMap) { log.info("onJointAngles {}", angleMap); // here we can make decisions on what ik sets we want to use and // what body parts are to move for (String name : angleMap.keySet()) { ServiceInterface si = Runtime.getService(name); if (si != null && si instanceof ServoControl) { ((Servo) si).moveTo(angleMap.get(name)); } } } @Override public ServiceConfig getConfig() { InMoov2Config config = new InMoov2Config(); // config.isController3Activated = isController3Activated; // config.isController4Activated = isController4Activated; // config.enableEyelids = isEyeLidsActivated; config.enableHead = isHeadActivated; config.enableLeftArm = isLeftArmActivated; config.enableLeftHand = isLeftHandActivated; config.enableLeftHandSensor = isLeftHandSensorActivated; // config.isLeftPortActivated = isLeftPortActivated; config.enableNeoPixel = isNeopixelActivated; config.enableOpenCV = isOpenCvActivated; config.enablePir = isPirActivated; config.enableUltrasonicRight = isUltrasonicRightActivated; config.enableUltrasonicLeft = isUltrasonicLeftActivated; config.enableRightArm = isRightArmActivated; config.enableRightHand = isRightHandActivated; config.enableRightHandSensors = isRightHandSensorActivated; // config.isRightPortActivated = isRightPortActivated; // config.enableSimulator = isSimulatorActivated; return config; } public void startAudioPlayer() { startPeer("audioPlayer"); } public void stopAudioPlayer() { releasePeer("audioPlayer"); } public ServiceConfig load(ServiceConfig c) { InMoov2Config config = (InMoov2Config) c; try { if (config.locale != null) { Runtime.setAllLocales(config.locale); } if (config.enableAudioPlayer) { startAudioPlayer(); } else { stopAudioPlayer(); } /** * <pre> * FIXME - * - there simply should be a single reference to the entire config object in InMoov * e.g. InMoov2Config config member * - if these booleans are symmetric - there should be corresponding functionality of "stopping/releasing" since they * are currently starting * </pre> */ /* * FIXME - very bad - need some coordination with this * * if (config.isController3Activated) { startPeer("controller3"); // FIXME * ... this kills me :P exec("isController3Activated = True"); } * * if (config.isController4Activated) { startPeer("controller4"); // FIXME * ... this kills me :P exec("isController4Activated = True"); } */ /* * if (config.enableEyelids) { // the hell if I know ? } */ if (config.enableHead) { startHead(); } else { stopHead(); } if (config.enableLeftArm) { startLeftArm(); } else { stopLeftArm(); } if (config.enableLeftHand) { startLeftHand(); } else { stopLeftHand(); } if (config.enableLeftHandSensor) { // the hell if I know ? } /* * if (config.isLeftPortActivated) { // the hell if I know ? is this an * Arduino ? startPeer("left"); } // else release peer ? * * if (config.enableNeoPixel) { startNeopixel(); } else { // * stopNeopixelAnimation(); } */ if (config.enableOpenCV) { startOpenCV(); } else { stopOpenCV(); } /* * if (config.enablePir) { startPir(); } else { stopPir(); } */ if (config.enableRightArm) { startRightArm(); } else { stopRightArm(); } if (config.enableRightHand) { startRightHand(); } else { stopRightHand(); } if (config.enableRightHandSensors) { // the hell if I know ? } /* * if (config.isRightPortActivated) { // the hell if I know ? is this an * Arduino ? } */ if (config.enableServoMixer) { startServoMixer(); } else { stopServoMixer(); } if (config.enableTorso) { startTorso(); } else { stopTorso(); } if (config.enableUltrasonicLeft) { startUltrasonicLeft(); } else { stopUltrasonicLeft(); } if (config.enableUltrasonicRight) { startUltrasonicRight(); } else { stopUltrasonicRight(); } if (config.enablePir) { startPir(); } else { stopPir(); } if (config.enableNeoPixel) { startNeopixel(); } else { stopNeopixelAnimation(); } if (config.loadGestures) { loadGestures = true; loadGestures(); // will load in startService } if (config.enableSimulator) { startSimulator(); } } catch (Exception e) { error(e); } return c; } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); Platform.setVirtual(true); // Runtime.start("s01", "Servo"); Runtime.start("intro", "Intro"); WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui"); webgui.autoStartBrowser(false); webgui.startService(); Random random = (Random) Runtime.start("random", "Random"); InMoov2 i01 = (InMoov2) Runtime.start("i01", "InMoov2"); random.addRandom(3000, 8000, "i01", "setLeftArmSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0); random.addRandom(3000, 8000, "i01", "setRightArmSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0); random.addRandom(3000, 8000, "i01", "moveRightArm", 0.0, 5.0, 85.0, 95.0, 25.0, 30.0, 10.0, 15.0); random.addRandom(3000, 8000, "i01", "moveLeftArm", 0.0, 5.0, 85.0, 95.0, 25.0, 30.0, 10.0, 15.0); random.addRandom(3000, 8000, "i01", "setLeftHandSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0); random.addRandom(3000, 8000, "i01", "setRightHandSpeed", 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0, 8.0, 25.0); random.addRandom(3000, 8000, "i01", "moveRightHand", 10.0, 160.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 130.0, 175.0); random.addRandom(3000, 8000, "i01", "moveLeftHand", 10.0, 160.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 10.0, 60.0, 5.0, 40.0); random.addRandom(200, 1000, "i01", "setHeadSpeed", 8.0, 20.0, 8.0, 20.0, 8.0, 20.0); random.addRandom(200, 1000, "i01", "moveHead", 70.0, 110.0, 65.0, 115.0, 70.0, 110.0); random.addRandom(200, 1000, "i01", "setTorsoSpeed", 2.0, 5.0, 2.0, 5.0, 2.0, 5.0); random.addRandom(200, 1000, "i01", "moveTorso", 85.0, 95.0, 88.0, 93.0, 70.0, 110.0); random.save(); boolean done = true; if (done) { return; } // i01.setVirtual(false); // i01.getConfig(); // i01.save(); // Runtime.start("s02", "Servo"); i01.startChatBot(); i01.startAll("COM3", "COM4"); Runtime.start("python", "Python"); // Runtime.start("log", "Log"); /* * OpenCV cv = (OpenCV) Runtime.start("cv", "OpenCV"); * cv.setCameraIndex(2); */ // i01.startSimulator(); /* * Arduino mega = (Arduino) Runtime.start("mega", "Arduino"); * mega.connect("/dev/ttyACM0"); */ } catch (Exception e) { log.error("main threw", e); } } }
package org.myrobotlab.service; import static org.myrobotlab.service.data.Mpu6050Data.dmpAddress1; import static org.myrobotlab.service.data.Mpu6050Data.dmpAddress2; import static org.myrobotlab.service.data.Mpu6050Data.dmpAddress3; import static org.myrobotlab.service.data.Mpu6050Data.dmpAddress4; import static org.myrobotlab.service.data.Mpu6050Data.dmpAddress5; import static org.myrobotlab.service.data.Mpu6050Data.dmpAddress6; import static org.myrobotlab.service.data.Mpu6050Data.dmpAddress7; import static org.myrobotlab.service.data.Mpu6050Data.dmpBank1; import static org.myrobotlab.service.data.Mpu6050Data.dmpBank2; import static org.myrobotlab.service.data.Mpu6050Data.dmpBank3; import static org.myrobotlab.service.data.Mpu6050Data.dmpBank4; import static org.myrobotlab.service.data.Mpu6050Data.dmpBank5; import static org.myrobotlab.service.data.Mpu6050Data.dmpBank6; import static org.myrobotlab.service.data.Mpu6050Data.dmpBank7; import static org.myrobotlab.service.data.Mpu6050Data.dmpConfig; import static org.myrobotlab.service.data.Mpu6050Data.dmpMemory; import static org.myrobotlab.service.data.Mpu6050Data.dmpUpdates1; import static org.myrobotlab.service.data.Mpu6050Data.dmpUpdates2; import static org.myrobotlab.service.data.Mpu6050Data.dmpUpdates3; import static org.myrobotlab.service.data.Mpu6050Data.dmpUpdates4; import static org.myrobotlab.service.data.Mpu6050Data.dmpUpdates5; import static org.myrobotlab.service.data.Mpu6050Data.dmpUpdates6; import static org.myrobotlab.service.data.Mpu6050Data.dmpUpdates7; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.myrobotlab.framework.Registration; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.interfaces.Attachable; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.data.Orientation; import org.myrobotlab.service.interfaces.I2CControl; import org.myrobotlab.service.interfaces.I2CController; import org.myrobotlab.service.interfaces.OrientationListener; import org.myrobotlab.service.interfaces.OrientationPublisher; import org.slf4j.Logger; public class Mpu6050 extends Service implements I2CControl, OrientationPublisher { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Mpu6050.class); StringBuilder debugRX = new StringBuilder(); transient HashSet<OrientationListener> listeners = new HashSet<OrientationListener>(); transient OrientationPublisher publisher; public transient I2CController controller; public List<String> deviceAddressList = Arrays.asList("0x68", "0x69"); public String deviceAddress = "0x68"; public List<String> deviceBusList = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8"); public String deviceBus = "1"; public static final int MPU6050_ADDRESS_AD0_LOW = 0x68; // address pin low // (GND), default // for // InvenSense // evaluation board public static final int MPU6050_ADDRESS_AD0_HIGH = 0x69; // address pin high // (VCC) public static final int MPU6050_DEFAULT_ADDRESS = MPU6050_ADDRESS_AD0_LOW; public static final int MPU6050_RA_XG_OFFS_TC = 0x00; // [7] PWR_MODE, [6:1] // XG_OFFS_TC, [0] // OTP_BNK_VLD public static final int MPU6050_RA_YG_OFFS_TC = 0x01; // [7] PWR_MODE, [6:1] // YG_OFFS_TC, [0] // OTP_BNK_VLD public static final int MPU6050_RA_ZG_OFFS_TC = 0x02; // [7] PWR_MODE, [6:1] // ZG_OFFS_TC, [0] // OTP_BNK_VLD public static final int MPU6050_RA_X_FINE_GAIN = 0x03; // [7:0] X_FINE_GAIN public static final int MPU6050_RA_Y_FINE_GAIN = 0x04; // [7:0] Y_FINE_GAIN public static final int MPU6050_RA_Z_FINE_GAIN = 0x05; // [7:0] Z_FINE_GAIN public static final int MPU6050_RA_XA_OFFS_H = 0x06; // [15:0] XA_OFFS public static final int MPU6050_RA_XA_OFFS_L_TC = 0x07; public static final int MPU6050_RA_YA_OFFS_H = 0x08; // [15:0] YA_OFFS public static final int MPU6050_RA_YA_OFFS_L_TC = 0x09; public static final int MPU6050_RA_ZA_OFFS_H = 0x0A; // [15:0] ZA_OFFS public static final int MPU6050_RA_ZA_OFFS_L_TC = 0x0B; public static final int MPU6050_RA_SELF_TEST_X = 0x0D; // XA_TEST[4-2], // XG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_Y = 0x0E; // YA_TEST[4-2], // YG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_Z = 0x0F; // ZA_TEST[4-2], // ZG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_A = 0x10; // XA_TEST[1-0], // YA_TEST[1-0], // ZA_TEST[1-0] public static final int MPU6050_RA_XG_OFFS_USRH = 0x13; // [15:0] // XG_OFFS_USR public static final int MPU6050_RA_XG_OFFS_USRL = 0x14; public static final int MPU6050_RA_YG_OFFS_USRH = 0x15; // [15:0] // YG_OFFS_USR public static final int MPU6050_RA_YG_OFFS_USRL = 0x16; public static final int MPU6050_RA_ZG_OFFS_USRH = 0x17; // [15:0] // ZG_OFFS_USR public static final int MPU6050_RA_ZG_OFFS_USRL = 0x18; public static final int MPU6050_RA_SMPLRT_DIV = 0x19; public static final int MPU6050_RA_CONFIG = 0x1A; public static final int MPU6050_RA_GYRO_CONFIG = 0x1B; public static final int MPU6050_RA_ACCEL_CONFIG = 0x1C; public static final int MPU6050_RA_FF_THR = 0x1D; public static final int MPU6050_RA_FF_DUR = 0x1E; public static final int MPU6050_RA_MOT_THR = 0x1F; public static final int MPU6050_RA_MOT_DUR = 0x20; public static final int MPU6050_RA_ZRMOT_THR = 0x21; public static final int MPU6050_RA_ZRMOT_DUR = 0x22; public static final int MPU6050_RA_FIFO_EN = 0x23; public static final int MPU6050_RA_I2C_MST_CTRL = 0x24; public static final int MPU6050_RA_I2C_SLV0_ADDR = 0x25; public static final int MPU6050_RA_I2C_SLV0_REG = 0x26; public static final int MPU6050_RA_I2C_SLV0_CTRL = 0x27; public static final int MPU6050_RA_I2C_SLV1_ADDR = 0x28; public static final int MPU6050_RA_I2C_SLV1_REG = 0x29; public static final int MPU6050_RA_I2C_SLV1_CTRL = 0x2A; public static final int MPU6050_RA_I2C_SLV2_ADDR = 0x2B; public static final int MPU6050_RA_I2C_SLV2_REG = 0x2C; public static final int MPU6050_RA_I2C_SLV2_CTRL = 0x2D; public static final int MPU6050_RA_I2C_SLV3_ADDR = 0x2E; public static final int MPU6050_RA_I2C_SLV3_REG = 0x2F; public static final int MPU6050_RA_I2C_SLV3_CTRL = 0x30; public static final int MPU6050_RA_I2C_SLV4_ADDR = 0x31; public static final int MPU6050_RA_I2C_SLV4_REG = 0x32; public static final int MPU6050_RA_I2C_SLV4_DO = 0x33; public static final int MPU6050_RA_I2C_SLV4_CTRL = 0x34; public static final int MPU6050_RA_I2C_SLV4_DI = 0x35; public static final int MPU6050_RA_I2C_MST_STATUS = 0x36; public static final int MPU6050_RA_INT_PIN_CFG = 0x37; public static final int MPU6050_RA_INT_ENABLE = 0x38; public static final int MPU6050_RA_DMP_INT_STATUS = 0x39; public static final int MPU6050_RA_INT_STATUS = 0x3A; public static final int MPU6050_RA_ACCEL_XOUT_H = 0x3B; public static final int MPU6050_RA_ACCEL_XOUT_L = 0x3C; public static final int MPU6050_RA_ACCEL_YOUT_H = 0x3D; public static final int MPU6050_RA_ACCEL_YOUT_L = 0x3E; public static final int MPU6050_RA_ACCEL_ZOUT_H = 0x3F; public static final int MPU6050_RA_ACCEL_ZOUT_L = 0x40; public static final int MPU6050_RA_TEMP_OUT_H = 0x41; public static final int MPU6050_RA_TEMP_OUT_L = 0x42; public static final int MPU6050_RA_GYRO_XOUT_H = 0x43; public static final int MPU6050_RA_GYRO_XOUT_L = 0x44; public static final int MPU6050_RA_GYRO_YOUT_H = 0x45; public static final int MPU6050_RA_GYRO_YOUT_L = 0x46; public static final int MPU6050_RA_GYRO_ZOUT_H = 0x47; public static final int MPU6050_RA_GYRO_ZOUT_L = 0x48; public static final int MPU6050_RA_EXT_SENS_DATA_00 = 0x49; public static final int MPU6050_RA_EXT_SENS_DATA_01 = 0x4A; public static final int MPU6050_RA_EXT_SENS_DATA_02 = 0x4B; public static final int MPU6050_RA_EXT_SENS_DATA_03 = 0x4C; public static final int MPU6050_RA_EXT_SENS_DATA_04 = 0x4D; public static final int MPU6050_RA_EXT_SENS_DATA_05 = 0x4E; public static final int MPU6050_RA_EXT_SENS_DATA_06 = 0x4F; public static final int MPU6050_RA_EXT_SENS_DATA_07 = 0x50; public static final int MPU6050_RA_EXT_SENS_DATA_08 = 0x51; public static final int MPU6050_RA_EXT_SENS_DATA_09 = 0x52; public static final int MPU6050_RA_EXT_SENS_DATA_10 = 0x53; public static final int MPU6050_RA_EXT_SENS_DATA_11 = 0x54; public static final int MPU6050_RA_EXT_SENS_DATA_12 = 0x55; public static final int MPU6050_RA_EXT_SENS_DATA_13 = 0x56; public static final int MPU6050_RA_EXT_SENS_DATA_14 = 0x57; public static final int MPU6050_RA_EXT_SENS_DATA_15 = 0x58; public static final int MPU6050_RA_EXT_SENS_DATA_16 = 0x59; public static final int MPU6050_RA_EXT_SENS_DATA_17 = 0x5A; public static final int MPU6050_RA_EXT_SENS_DATA_18 = 0x5B; public static final int MPU6050_RA_EXT_SENS_DATA_19 = 0x5C; public static final int MPU6050_RA_EXT_SENS_DATA_20 = 0x5D; public static final int MPU6050_RA_EXT_SENS_DATA_21 = 0x5E; public static final int MPU6050_RA_EXT_SENS_DATA_22 = 0x5F; public static final int MPU6050_RA_EXT_SENS_DATA_23 = 0x60; public static final int MPU6050_RA_MOT_DETECT_STATUS = 0x61; public static final int MPU6050_RA_I2C_SLV0_DO = 0x63; public static final int MPU6050_RA_I2C_SLV1_DO = 0x64; public static final int MPU6050_RA_I2C_SLV2_DO = 0x65; public static final int MPU6050_RA_I2C_SLV3_DO = 0x66; public static final int MPU6050_RA_I2C_MST_DELAY_CTRL = 0x67; public static final int MPU6050_RA_SIGNAL_PATH_RESET = 0x68; public static final int MPU6050_RA_MOT_DETECT_CTRL = 0x69; public static final int MPU6050_RA_USER_CTRL = 0x6A; public static final int MPU6050_RA_PWR_MGMT_1 = 0x6B; public static final int MPU6050_RA_PWR_MGMT_2 = 0x6C; public static final int MPU6050_RA_BANK_SEL = 0x6D; public static final int MPU6050_RA_MEM_START_ADDR = 0x6E; public static final int MPU6050_RA_MEM_R_W = 0x6F; public static final int MPU6050_RA_DMP_CFG_1 = 0x70; public static final int MPU6050_RA_DMP_CFG_2 = 0x71; public static final int MPU6050_RA_FIFO_COUNTH = 0x72; public static final int MPU6050_RA_FIFO_COUNTL = 0x73; public static final int MPU6050_RA_FIFO_R_W = 0x74; public static final int MPU6050_RA_WHO_AM_I = 0x75; public static final int MPU6050_SELF_TEST_XA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_XA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_XA_2_BIT = 0x05; public static final int MPU6050_SELF_TEST_XA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_YA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_YA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_YA_2_BIT = 0x03; public static final int MPU6050_SELF_TEST_YA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_ZA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_ZA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_ZA_2_BIT = 0x01; public static final int MPU6050_SELF_TEST_ZA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_XG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_XG_1_LENGTH = 0x05; public static final int MPU6050_SELF_TEST_YG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_YG_1_LENGTH = 0x05; public static final int MPU6050_SELF_TEST_ZG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_ZG_1_LENGTH = 0x05; public static final int MPU6050_TC_PWR_MODE_BIT = 7; public static final int MPU6050_TC_OFFSET_BIT = 6; public static final int MPU6050_TC_OFFSET_LENGTH = 6; public static final int MPU6050_TC_OTP_BNK_VLD_BIT = 0; public static final int MPU6050_VDDIO_LEVEL_VLOGIC = 0; public static final int MPU6050_VDDIO_LEVEL_VDD = 1; public static final int MPU6050_CFG_EXT_SYNC_SET_BIT = 5; public static final int MPU6050_CFG_EXT_SYNC_SET_LENGTH = 3; public static final int MPU6050_CFG_DLPF_CFG_BIT = 2; public static final int MPU6050_CFG_DLPF_CFG_LENGTH = 3; public static final int MPU6050_EXT_SYNC_DISABLED = 0x0; public static final int MPU6050_EXT_SYNC_TEMP_OUT_L = 0x1; public static final int MPU6050_EXT_SYNC_GYRO_XOUT_L = 0x2; public static final int MPU6050_EXT_SYNC_GYRO_YOUT_L = 0x3; public static final int MPU6050_EXT_SYNC_GYRO_ZOUT_L = 0x4; public static final int MPU6050_EXT_SYNC_ACCEL_XOUT_L = 0x5; public static final int MPU6050_EXT_SYNC_ACCEL_YOUT_L = 0x6; public static final int MPU6050_EXT_SYNC_ACCEL_ZOUT_L = 0x7; public static final int MPU6050_DLPF_BW_256 = 0x00; public static final int MPU6050_DLPF_BW_188 = 0x01; public static final int MPU6050_DLPF_BW_98 = 0x02; public static final int MPU6050_DLPF_BW_42 = 0x03; public static final int MPU6050_DLPF_BW_20 = 0x04; public static final int MPU6050_DLPF_BW_10 = 0x05; public static final int MPU6050_DLPF_BW_5 = 0x06; public static final int MPU6050_GCONFIG_FS_SEL_BIT = 4; public static final int MPU6050_GCONFIG_FS_SEL_LENGTH = 2; public static final int MPU6050_GYRO_FS_250 = 0x00; public static final int MPU6050_GYRO_FS_500 = 0x01; public static final int MPU6050_GYRO_FS_1000 = 0x02; public static final int MPU6050_GYRO_FS_2000 = 0x03; public static final int MPU6050_ACONFIG_XA_ST_BIT = 7; public static final int MPU6050_ACONFIG_YA_ST_BIT = 6; public static final int MPU6050_ACONFIG_ZA_ST_BIT = 5; public static final int MPU6050_ACONFIG_AFS_SEL_BIT = 4; public static final int MPU6050_ACONFIG_AFS_SEL_LENGTH = 2; public static final int MPU6050_ACONFIG_ACCEL_HPF_BIT = 2; public static final int MPU6050_ACONFIG_ACCEL_HPF_LENGTH = 3; public static final int MPU6050_ACCEL_FS_2 = 0x00; public static final int MPU6050_ACCEL_FS_4 = 0x01; public static final int MPU6050_ACCEL_FS_8 = 0x02; public static final int MPU6050_ACCEL_FS_16 = 0x03; public static final int MPU6050_DHPF_RESET = 0x00; public static final int MPU6050_DHPF_5 = 0x01; public static final int MPU6050_DHPF_2P5 = 0x02; public static final int MPU6050_DHPF_1P25 = 0x03; public static final int MPU6050_DHPF_0P63 = 0x04; public static final int MPU6050_DHPF_HOLD = 0x07; public static final int MPU6050_TEMP_FIFO_EN_BIT = 7; public static final int MPU6050_XG_FIFO_EN_BIT = 6; public static final int MPU6050_YG_FIFO_EN_BIT = 5; public static final int MPU6050_ZG_FIFO_EN_BIT = 4; public static final int MPU6050_ACCEL_FIFO_EN_BIT = 3; public static final int MPU6050_SLV2_FIFO_EN_BIT = 2; public static final int MPU6050_SLV1_FIFO_EN_BIT = 1; public static final int MPU6050_SLV0_FIFO_EN_BIT = 0; public static final int MPU6050_MULT_MST_EN_BIT = 7; public static final int MPU6050_WAIT_FOR_ES_BIT = 6; public static final int MPU6050_SLV_3_FIFO_EN_BIT = 5; public static final int MPU6050_I2C_MST_P_NSR_BIT = 4; public static final int MPU6050_I2C_MST_CLK_BIT = 3; public static final int MPU6050_I2C_MST_CLK_LENGTH = 4; public static final int MPU6050_CLOCK_DIV_348 = 0x0; public static final int MPU6050_CLOCK_DIV_333 = 0x1; public static final int MPU6050_CLOCK_DIV_320 = 0x2; public static final int MPU6050_CLOCK_DIV_308 = 0x3; public static final int MPU6050_CLOCK_DIV_296 = 0x4; public static final int MPU6050_CLOCK_DIV_286 = 0x5; public static final int MPU6050_CLOCK_DIV_276 = 0x6; public static final int MPU6050_CLOCK_DIV_267 = 0x7; public static final int MPU6050_CLOCK_DIV_258 = 0x8; public static final int MPU6050_CLOCK_DIV_500 = 0x9; public static final int MPU6050_CLOCK_DIV_471 = 0xA; public static final int MPU6050_CLOCK_DIV_444 = 0xB; public static final int MPU6050_CLOCK_DIV_421 = 0xC; public static final int MPU6050_CLOCK_DIV_400 = 0xD; public static final int MPU6050_CLOCK_DIV_381 = 0xE; public static final int MPU6050_CLOCK_DIV_364 = 0xF; public static final int MPU6050_I2C_SLV_RW_BIT = 7; public static final int MPU6050_I2C_SLV_ADDR_BIT = 6; public static final int MPU6050_I2C_SLV_ADDR_LENGTH = 7; public static final int MPU6050_I2C_SLV_EN_BIT = 7; public static final int MPU6050_I2C_SLV_BYTE_SW_BIT = 6; public static final int MPU6050_I2C_SLV_REG_DIS_BIT = 5; public static final int MPU6050_I2C_SLV_GRP_BIT = 4; public static final int MPU6050_I2C_SLV_LEN_BIT = 3; public static final int MPU6050_I2C_SLV_LEN_LENGTH = 4; public static final int MPU6050_I2C_SLV4_RW_BIT = 7; public static final int MPU6050_I2C_SLV4_ADDR_BIT = 6; public static final int MPU6050_I2C_SLV4_ADDR_LENGTH = 7; public static final int MPU6050_I2C_SLV4_EN_BIT = 7; public static final int MPU6050_I2C_SLV4_INT_EN_BIT = 6; public static final int MPU6050_I2C_SLV4_REG_DIS_BIT = 5; public static final int MPU6050_I2C_SLV4_MST_DLY_BIT = 4; public static final int MPU6050_I2C_SLV4_MST_DLY_LENGTH = 5; public static final int MPU6050_MST_PASS_THROUGH_BIT = 7; public static final int MPU6050_MST_I2C_SLV4_DONE_BIT = 6; public static final int MPU6050_MST_I2C_LOST_ARB_BIT = 5; public static final int MPU6050_MST_I2C_SLV4_NACK_BIT = 4; public static final int MPU6050_MST_I2C_SLV3_NACK_BIT = 3; public static final int MPU6050_MST_I2C_SLV2_NACK_BIT = 2; public static final int MPU6050_MST_I2C_SLV1_NACK_BIT = 1; public static final int MPU6050_MST_I2C_SLV0_NACK_BIT = 0; public static final int MPU6050_INTCFG_INT_LEVEL_BIT = 7; public static final int MPU6050_INTCFG_INT_OPEN_BIT = 6; public static final int MPU6050_INTCFG_LATCH_INT_EN_BIT = 5; public static final int MPU6050_INTCFG_INT_RD_CLEAR_BIT = 4; public static final int MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT = 3; public static final int MPU6050_INTCFG_FSYNC_INT_EN_BIT = 2; public static final int MPU6050_INTCFG_I2C_BYPASS_EN_BIT = 1; public static final int MPU6050_INTCFG_CLKOUT_EN_BIT = 0; public static final int MPU6050_INTMODE_ACTIVEHIGH = 0x00; public static final int MPU6050_INTMODE_ACTIVELOW = 0x01; public static final int MPU6050_INTDRV_PUSHPULL = 0x00; public static final int MPU6050_INTDRV_OPENDRAIN = 0x01; public static final int MPU6050_INTLATCH_50USPULSE = 0x00; public static final int MPU6050_INTLATCH_WAITCLEAR = 0x01; public static final int MPU6050_INTCLEAR_STATUSREAD = 0x00; public static final int MPU6050_INTCLEAR_ANYREAD = 0x01; public static final int MPU6050_INTERRUPT_FF_BIT = 7; public static final int MPU6050_INTERRUPT_MOT_BIT = 6; public static final int MPU6050_INTERRUPT_ZMOT_BIT = 5; public static final int MPU6050_INTERRUPT_FIFO_OFLOW_BIT = 4; public static final int MPU6050_INTERRUPT_I2C_MST_INT_BIT = 3; public static final int MPU6050_INTERRUPT_PLL_RDY_INT_BIT = 2; public static final int MPU6050_INTERRUPT_DMP_INT_BIT = 1; public static final int MPU6050_INTERRUPT_DATA_RDY_BIT = 0; // TODO: figure out what these actually do // UMPL source code is not very obivous public static final int MPU6050_DMPINT_5_BIT = 5; public static final int MPU6050_DMPINT_4_BIT = 4; public static final int MPU6050_DMPINT_3_BIT = 3; public static final int MPU6050_DMPINT_2_BIT = 2; public static final int MPU6050_DMPINT_1_BIT = 1; public static final int MPU6050_DMPINT_0_BIT = 0; public static final int MPU6050_MOTION_MOT_XNEG_BIT = 7; public static final int MPU6050_MOTION_MOT_XPOS_BIT = 6; public static final int MPU6050_MOTION_MOT_YNEG_BIT = 5; public static final int MPU6050_MOTION_MOT_YPOS_BIT = 4; public static final int MPU6050_MOTION_MOT_ZNEG_BIT = 3; public static final int MPU6050_MOTION_MOT_ZPOS_BIT = 2; public static final int MPU6050_MOTION_MOT_ZRMOT_BIT = 0; public static final int MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT = 7; public static final int MPU6050_DELAYCTRL_I2C_SLV4_DLY_EN_BIT = 4; public static final int MPU6050_DELAYCTRL_I2C_SLV3_DLY_EN_BIT = 3; public static final int MPU6050_DELAYCTRL_I2C_SLV2_DLY_EN_BIT = 2; public static final int MPU6050_DELAYCTRL_I2C_SLV1_DLY_EN_BIT = 1; public static final int MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT = 0; public static final int MPU6050_PATHRESET_GYRO_RESET_BIT = 2; public static final int MPU6050_PATHRESET_ACCEL_RESET_BIT = 1; public static final int MPU6050_PATHRESET_TEMP_RESET_BIT = 0; public static final int MPU6050_DETECT_ACCEL_ON_DELAY_BIT = 5; public static final int MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH = 2; public static final int MPU6050_DETECT_FF_COUNT_BIT = 3; public static final int MPU6050_DETECT_FF_COUNT_LENGTH = 2; public static final int MPU6050_DETECT_MOT_COUNT_BIT = 1; public static final int MPU6050_DETECT_MOT_COUNT_LENGTH = 2; public static final int MPU6050_DETECT_DECREMENT_RESET = 0x0; public static final int MPU6050_DETECT_DECREMENT_1 = 0x1; public static final int MPU6050_DETECT_DECREMENT_2 = 0x2; public static final int MPU6050_DETECT_DECREMENT_4 = 0x3; public static final int MPU6050_USERCTRL_DMP_EN_BIT = 7; public static final int MPU6050_USERCTRL_FIFO_EN_BIT = 6; public static final int MPU6050_USERCTRL_I2C_MST_EN_BIT = 5; public static final int MPU6050_USERCTRL_I2C_IF_DIS_BIT = 4; public static final int MPU6050_USERCTRL_DMP_RESET_BIT = 3; public static final int MPU6050_USERCTRL_FIFO_RESET_BIT = 2; public static final int MPU6050_USERCTRL_I2C_MST_RESET_BIT = 1; public static final int MPU6050_USERCTRL_SIG_COND_RESET_BIT = 0; public static final int MPU6050_PWR1_DEVICE_RESET_BIT = 7; public static final int MPU6050_PWR1_SLEEP_BIT = 6; public static final int MPU6050_PWR1_CYCLE_BIT = 5; public static final int MPU6050_PWR1_TEMP_DIS_BIT = 3; public static final int MPU6050_PWR1_CLKSEL_BIT = 2; public static final int MPU6050_PWR1_CLKSEL_LENGTH = 3; public static final int MPU6050_CLOCK_INTERNAL = 0x00; public static final int MPU6050_CLOCK_PLL_XGYRO = 0x01; public static final int MPU6050_CLOCK_PLL_YGYRO = 0x02; public static final int MPU6050_CLOCK_PLL_ZGYRO = 0x03; public static final int MPU6050_CLOCK_PLL_EXT32K = 0x04; public static final int MPU6050_CLOCK_PLL_EXT19M = 0x05; public static final int MPU6050_CLOCK_KEEP_RESET = 0x07; public static final int MPU6050_PWR2_LP_WAKE_CTRL_BIT = 7; public static final int MPU6050_PWR2_LP_WAKE_CTRL_LENGTH = 2; public static final int MPU6050_PWR2_STBY_XA_BIT = 5; public static final int MPU6050_PWR2_STBY_YA_BIT = 4; public static final int MPU6050_PWR2_STBY_ZA_BIT = 3; public static final int MPU6050_PWR2_STBY_XG_BIT = 2; public static final int MPU6050_PWR2_STBY_YG_BIT = 1; public static final int MPU6050_PWR2_STBY_ZG_BIT = 0; public static final int MPU6050_WAKE_FREQ_1P25 = 0x0; public static final int MPU6050_WAKE_FREQ_2P5 = 0x1; public static final int MPU6050_WAKE_FREQ_5 = 0x2; public static final int MPU6050_WAKE_FREQ_10 = 0x3; public static final int MPU6050_BANKSEL_PRFTCH_EN_BIT = 6; public static final int MPU6050_BANKSEL_CFG_USER_BANK_BIT = 5; public static final int MPU6050_BANKSEL_MEM_SEL_BIT = 4; public static final int MPU6050_BANKSEL_MEM_SEL_LENGTH = 5; public static final int MPU6050_WHO_AM_I_BIT = 6; public static final int MPU6050_WHO_AM_I_LENGTH = 6; public static final int MPU6050_DMP_MEMORY_BANKS = 8; public static final int MPU6050_DMP_MEMORY_BANK_SIZE = 256; public static final int MPU6050_DMP_MEMORY_CHUNK_SIZE = 16; // public static final byte ACCEL_XOUT_H = 0x3B; // Raw data values read by getRaw public int accelX; public int accelY; public int accelZ; public int temperature; public int gyroX; public int gyroY; public int gyroZ; // Accel values converted to G // Temperature converted to Celcius // Gyro values converted degrees/s public double accelGX = 0; public double accelGY = 0; public double accelGZ = 0; public double temperatureC = 0; public double gyroDegreeX = 0; public double gyroDegreeY = 0; public double gyroDegreeZ = 0; public List<String> controllers; public String controllerName; // complementaryFiltered angles public double filtered_x_angle; public double filtered_y_angle; public double filtered_z_angle; public class OrientationPublisher extends Thread { public boolean isRunning = false; public void run() { isRunning = true; while (isRunning) { refresh(); invoke("publishOrientation", new Orientation(filtered_x_angle, filtered_y_angle, filtered_z_angle)); } } } public Mpu6050(String n, String id) { super(n, id); refreshControllers(); subscribeToRuntime("registered"); } public void onRegistered(Registration s) { refreshControllers(); broadcastState(); } public List<String> refreshControllers() { controllers = Runtime.getServiceNamesFromInterface(I2CController.class); return controllers; } @Override public void setDeviceBus(String deviceBus) { this.deviceBus = deviceBus; broadcastState(); } @Override public void setDeviceAddress(String deviceAddress) { this.deviceAddress = deviceAddress; broadcastState(); } /** * This method reads all the 7 raw values in one go accelX accelY accelZ * temperature ( In degrees Celcius ) gyroX gyroY gyroZ * */ /** * TODO Make the way it should be Currently only used for test of data binding * to the webgui */ public void refresh() { getRaw(); complementaryFilter(gyroX, gyroY, gyroZ, accelX, accelY, accelZ); broadcastState(); } public void getRaw() { // Set the start address to read from byte[] writebuffer = { MPU6050_RA_ACCEL_XOUT_H }; controller.i2cWrite(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), writebuffer, writebuffer.length); // The Arduino example executes a request_from() // Not sure if this will do the trick // Request 14 bytes from the MPU-6050 byte[] readbuffer = new byte[14]; controller.i2cRead(this, Integer.parseInt(deviceBus), Integer.decode(deviceAddress), readbuffer, readbuffer.length); // Fill the variables with the result from the read operation accelX = (byte) readbuffer[0] << 8 | readbuffer[1] & 0xFF; accelY = (byte) readbuffer[2] << 8 | readbuffer[3] & 0xFF; accelZ = (byte) readbuffer[4] << 8 | readbuffer[5] & 0xFF; temperature = (byte) readbuffer[6] << 8 | readbuffer[7] & 0xFF; gyroX = (byte) readbuffer[8] << 8 | readbuffer[9] & 0xFF; gyroY = (byte) readbuffer[10] << 8 | readbuffer[11] & 0xFF; gyroZ = (byte) readbuffer[12] << 8 | readbuffer[13] & 0xFF; // Convert acceleration to G assuming min-max 2G as set in initialize() accelGX = accelX / 16384.0; accelGY = accelY / 16384.0; accelGZ = accelZ / 16384.0; // Convert temp to degrees Celcius temperatureC = (temperature / 340.0) + 36.53; // Convert gyro to degrees/s ( assuming max +-250 degrees/s ) as set in // initialize() gyroDegreeX = gyroX / 131; gyroDegreeY = gyroY / 131; gyroDegreeZ = gyroZ / 131; // broadcastState(); } double lastnow = 0; void complementaryFilter(double gyro_x, double gyro_y, double gyro_z, double acc_x, double acc_y, double acc_z) { // All angles are calculatd in radians long now = System.currentTimeMillis(); if (lastnow == 0) { lastnow = now - .05; } double dt = (now - lastnow) / 1000; lastnow = now; double gyroPortion = .90; double accPortion = 1 - gyroPortion; // Calculate the rotations from the accelerometer double acc_x_angle = Math.atan(acc_x / Math.sqrt((acc_y * acc_y) + (acc_z * acc_z))); double acc_y_angle = Math.atan(acc_y / Math.sqrt((acc_x * acc_x) + (acc_z * acc_z))); double acc_z_angle = Math.atan(Math.sqrt((acc_x * acc_x) + (acc_y * acc_y)) / acc_z); // Calculate the change in direction from the Gyro double gyro_x_angle = filtered_x_angle + (dt * gyro_x / 131) * (Math.PI / 180); double gyro_y_angle = filtered_y_angle + (dt * gyro_y / 131) * (Math.PI / 180); double gyro_z_angle = filtered_z_angle + (dt * gyro_z / 131) * (Math.PI / 180); filtered_x_angle = gyroPortion * gyro_x_angle + accPortion * acc_x_angle; filtered_y_angle = gyroPortion * gyro_y_angle + accPortion * acc_y_angle; filtered_z_angle = gyroPortion * gyro_z_angle + accPortion * acc_z_angle; } public int dmpInitialize() { // reset device log.info("Resetting MPU6050..."); reset(); delay(30); // wait after reset // disable sleep mode log.info("Disabling sleep mode..."); setSleepEnabled(false); // get MPU hardware revision log.info("Selecting user bank 16..."); setMemoryBank(0x10, true, true); log.info("Selecting memory byte 6..."); setMemoryStartAddress(0x06); log.info("Checking hardware revision..."); log.info(String.format("Revision @ user[16][6] = x%02X", readMemoryByte())); log.info("Resetting memory bank selection to 0..."); setMemoryBank(0, false, false); // check OTP bank valid log.info("Reading OTP bank valid flag..."); log.info("OTP bank is {}", getOTPBankValid()); // get X/Y/Z gyro offsets log.info("Reading gyro offset TC values..."); int xgOffsetTC = getXGyroOffsetTC(); int ygOffsetTC = getYGyroOffsetTC(); int zgOffsetTC = getZGyroOffsetTC(); log.info("X gyro offset = {}", xgOffsetTC); log.info("Y gyro offset = {}", ygOffsetTC); log.info("Z gyro offset = {}", zgOffsetTC); // setup weird slave stuff (?) log.info("Setting slave 0 address to 0x7F..."); setSlaveAddress(0, 0x7F); log.info("Disabling I2C Master mode..."); setI2CMasterModeEnabled(false); log.info("Setting slave 0 address to 0x68 (self)..."); setSlaveAddress(0, 0x68); log.info("Resetting I2C Master control..."); resetI2CMaster(); delay(20); // load DMP code into memory banks log.info("Writing DMP code to MPU memory banks ({}) bytes", dmpMemory.length); if (writeProgMemoryBlock(dmpMemory, dmpMemory.length)) { log.info("Success! DMP code written and verified."); // write DMP configuration log.info("Writing DMP configuration to MPU memory banks ({} bytes in config def)", dmpConfig.length); if (writeProgDMPConfigurationSet(dmpConfig, dmpConfig.length)) { log.info("Success! DMP configuration written and verified."); log.info("Setting clock source to Z Gyro..."); setClockSource(MPU6050_CLOCK_PLL_ZGYRO); log.info("Setting DMP and FIFO_OFLOW interrupts enabled..."); setIntEnabled(0x12); log.info("Setting sample rate to 200Hz..."); setRate(4); // 1khz / (1 + 4) = 200 Hz log.info("Setting external frame sync to TEMP_OUT_L[0]..."); setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L); log.info("Setting DLPF bandwidth to 42Hz..."); setDLPFMode(MPU6050_DLPF_BW_42); log.info("Setting gyro sensitivity to +/- 2000 deg/sec..."); setFullScaleGyroRange(MPU6050_GYRO_FS_2000); log.info("Setting DMP configuration bytes (function unknown)..."); setDMPConfig1(0x03); setDMPConfig2(0x00); log.info("Clearing OTP Bank flag..."); setOTPBankValid(false); log.info("Setting X/Y/Z gyro offset TCs to previous values..."); setXGyroOffsetTC(xgOffsetTC); setYGyroOffsetTC(ygOffsetTC); setZGyroOffsetTC(zgOffsetTC); // log.info("Setting X/Y/Z gyro user offsets to zero...")); // setXGyroOffset(0); // setYGyroOffset(0); // setZGyroOffset(0); log.info("Writing final memory update 1/7 (function unknown)..."); writeMemoryBlock(dmpUpdates1, dmpUpdates1.length, dmpBank1, dmpAddress1, true); log.info("Writing final memory update 2/7 (function unknown)..."); writeMemoryBlock(dmpUpdates2, dmpUpdates2.length, dmpBank2, dmpAddress2, true); log.info("Resetting FIFO..."); resetFIFO(); log.info("Reading FIFO count..."); int fifoCount = getFIFOCount(); int[] fifoBuffer = new int[128]; log.info("Current FIFO count={}", fifoCount); getFIFOBytes(fifoBuffer, fifoCount); log.info("Setting motion detection threshold to 2..."); setMotionDetectionThreshold(2); log.info("Setting zero-motion detection threshold to 156..."); setZeroMotionDetectionThreshold(156); log.info("Setting motion detection duration to 80..."); setMotionDetectionDuration(80); log.info("Setting zero-motion detection duration to 0..."); setZeroMotionDetectionDuration(0); log.info("Resetting FIFO..."); resetFIFO(); log.info("Enabling FIFO..."); setFIFOEnabled(true); log.info("Enabling DMP..."); setDMPEnabled(true); log.info("Resetting DMP..."); resetDMP(); log.info("Writing final memory update 3/7 (function unknown)..."); writeMemoryBlock(dmpUpdates3, dmpUpdates3.length, dmpBank3, dmpAddress3, true); log.info("Writing final memory update 4/7 (function unknown)..."); writeMemoryBlock(dmpUpdates4, dmpUpdates4.length, dmpBank4, dmpAddress4, true); log.info("Writing final memory update 5/7 (function unknown)..."); writeMemoryBlock(dmpUpdates5, dmpUpdates5.length, dmpBank5, dmpAddress5, true); // Added extra FIFO reset ( not sure why needed, but I get index // out of // range otherwise log.info("Resetting FIFO..."); resetFIFO(); log.info("Waiting for FIFO count > 2..."); while ((fifoCount = getFIFOCount()) < 3) ; log.info("Current FIFO count={}", fifoCount); log.info("Reading FIFO data..."); getFIFOBytes(fifoBuffer, fifoCount); log.info("Reading interrupt status..."); log.info(String.format("Current interrupt status=x%02X", getIntStatus())); log.info("Reading final memory update 6/7 (function unknown)..."); writeMemoryBlock(dmpUpdates6, dmpUpdates6.length, dmpBank6, dmpAddress6, true); // Added extra FIFO reset ( not sure why needed, but I get index // out of // range otherwise log.info("Resetting FIFO..."); resetFIFO(); log.info("Waiting for FIFO count > 2..."); while ((fifoCount = getFIFOCount()) < 3) ; log.info("Current FIFO count={}", fifoCount); log.info("Reading FIFO data..."); getFIFOBytes(fifoBuffer, fifoCount); log.info("Reading interrupt status..."); log.info(String.format("Current interrupt status=x%02X", getIntStatus())); log.info("Writing final memory update 7/7 (function unknown)..."); writeMemoryBlock(dmpUpdates7, dmpUpdates7.length, dmpBank7, dmpAddress7, true); log.info("DMP is good to go! Finally."); log.info("Disabling DMP (you turn it on later)..."); setDMPEnabled(false); log.info("Setting up internal 42-byte (default) DMP packet buffer..."); // int dmpPacketSize = 42; /* * if ((dmpPacketBuffer = (int *)malloc(42)) == 0) { return 3; // TODO: * proper error code for no memory } */ log.info("Resetting FIFO and clearing INT status one last time..."); resetFIFO(); getIntStatus(); } else { log.info("ERROR! DMP configuration verification failed."); return 2; // configuration block loading failed } } else { log.info("ERROR! DMP code verification failed."); return 1; // main binary block loading failed } return 0; } public void delay(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { // TODO Auto-generated catch block Logging.logError(e); } // wait after reset } public void initialize() { setClockSource(MPU6050_CLOCK_PLL_XGYRO); setFullScaleGyroRange(MPU6050_GYRO_FS_250); setFullScaleAccelRange(MPU6050_ACCEL_FS_2); setSleepEnabled(false); // thanks to Jack Elston for pointing this one // out! } /** * Verify the I2C connection. Make sure the device is connected and responds * as expected. * * @return True if connection is valid, false otherwise */ public boolean testConnection() { return getDeviceID() == 0x34; } // AUX_VDDIO register (InvenSense demo code calls this RA_*G_OFFS_TC) /** * Get the auxiliary I2C supply voltage level. When set to 1, the auxiliary * I2C bus high logic level is VDD. When cleared to 0, the auxiliary I2C bus * high logic level is VLOGIC. This does not apply to the MPU-6000, which does * not have a VLOGIC pin. * * @return I2C supply voltage level (0=VLOGIC, 1=VDD) */ public int getAuxVDDIOLevel() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_YG_OFFS_TC, MPU6050_TC_PWR_MODE_BIT) ? 1 : 0; } /** * Set the auxiliary I2C supply voltage level. When set to 1, the auxiliary * I2C bus high logic level is VDD. When cleared to 0, the auxiliary I2C bus * high logic level is VLOGIC. This does not apply to the MPU-6000, which does * not have a VLOGIC pin. * * @param level * I2C supply voltage level (0=VLOGIC, 1=VDD) */ void setAuxVDDIOLevel(int level) { boolean bitbuffer = (level != 0); I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_YG_OFFS_TC, MPU6050_TC_PWR_MODE_BIT, bitbuffer); } // SMPLRT_DIV register /** * Get gyroscope output rate divider. The sensor register output, FIFO output, * DMP sampling, Motion detection, Zero Motion detection, and Free Fall * detection are all based on the Sample Rate. The Sample Rate is generated by * dividing the gyroscope output rate by SMPLRT_DIV: * * Sample Rate = Gyroscope Output Rate / (1 + SMPLRT_DIV) * * where Gyroscope Output Rate = 8kHz when the DLPF is disabled (DLPF_CFG = 0 * or 7), and 1kHz when the DLPF is enabled (see Register 26). * * Note: The accelerometer output rate is 1kHz. This means that for a Sample * Rate greater than 1kHz, the same accelerometer sample may be output to the * FIFO, DMP, and sensor registers more than once. * * For a diagram of the gyroscope and accelerometer signal paths, see Section * 8 of the MPU-6000/MPU-6050 Product Specification document. * * @return Current sample rate * @see MPU6050_RA_SMPLRT_DIV */ int getRate() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_SMPLRT_DIV); } /** * Set gyroscope sample rate divider. * * @param rate * New sample rate divider see getRate() * @see MPU6050_RA_SMPLRT_DIV */ void setRate(int rate) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_SMPLRT_DIV, rate); } // CONFIG register int getExternalFrameSync() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_CONFIG, MPU6050_CFG_EXT_SYNC_SET_BIT, MPU6050_CFG_EXT_SYNC_SET_LENGTH); } /** * Set external FSYNC configuration. * * see getExternalFrameSync() * * @see MPU6050_RA_CONFIG * @param sync * New FSYNC configuration value */ void setExternalFrameSync(int sync) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_CONFIG, MPU6050_CFG_EXT_SYNC_SET_BIT, MPU6050_CFG_EXT_SYNC_SET_LENGTH, sync); } int getDLPFMode() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_CONFIG, MPU6050_CFG_DLPF_CFG_BIT, MPU6050_CFG_DLPF_CFG_LENGTH); } /** * Set digital low-pass filter configuration. * * @param mode * New DLFP configuration setting see getDLPFBandwidth() * @see MPU6050_DLPF_BW_256 * @see MPU6050_RA_CONFIG * @see MPU6050_CFG_DLPF_CFG_BIT * @see MPU6050_CFG_DLPF_CFG_LENGTH */ void setDLPFMode(int mode) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_CONFIG, MPU6050_CFG_DLPF_CFG_BIT, MPU6050_CFG_DLPF_CFG_LENGTH, mode); } // GYRO_CONFIG register /** * Get full-scale gyroscope range. The FS_SEL parameter allows setting the * full-scale range of the gyro sensors, as described in the table below. * * <pre> * 0 = +/- 250 degrees/sec * 1 = +/- 500 degrees/sec * 2 = +/- 1000 degrees/sec * 3 = +/- 2000 degrees/sec * </pre> * * @return Current full-scale gyroscope range setting * @see MPU6050_GYRO_FS_250 * @see MPU6050_RA_GYRO_CONFIG * @see MPU6050_GCONFIG_FS_SEL_BIT * @see MPU6050_GCONFIG_FS_SEL_LENGTH */ int getFullScaleGyroRange() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_GYRO_CONFIG, MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH); } /** * Set full-scale gyroscope range. * * @param range * New full-scale gyroscope range value see getFullScaleRange() * @see MPU6050_GYRO_FS_250 * @see MPU6050_RA_GYRO_CONFIG * @see MPU6050_GCONFIG_FS_SEL_BIT * @see MPU6050_GCONFIG_FS_SEL_LENGTH */ void setFullScaleGyroRange(int range) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_GYRO_CONFIG, MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH, range); } // SELF TEST FACTORY TRIM VALUES /** * Get self-test factory trim value for accelerometer X axis. * * @return factory trim value * @see MPU6050_RA_SELF_TEST_X */ int getAccelXSelfTestFactoryTrim() { int selftestX = I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_SELF_TEST_X); int selftestA = I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_SELF_TEST_A); return (byte) selftestA >> 3 | ((selftestX >> 4) & 0x03); } /** * Get self-test factory trim value for accelerometer Y axis. * * @return factory trim value * @see MPU6050_RA_SELF_TEST_Y */ int getAccelYSelfTestFactoryTrim() { int selftestY = I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_SELF_TEST_Y); int selftestA = I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_SELF_TEST_A); return (byte) selftestY >> 3 | ((selftestA >> 2) & 0x03); } /** * Get self-test factory trim value for accelerometer Z axis. * * @return factory trim value * @see MPU6050_RA_SELF_TEST_Z */ int getAccelZSelfTestFactoryTrim() { int[] readBuffer = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_SELF_TEST_Z, 2, readBuffer); return (byte) readBuffer[0] >> 3 | (readBuffer[1] & 0x03); } /** * Get self-test factory trim value for gyro X axis. * * @return factory trim value * @see MPU6050_RA_SELF_TEST_X */ int getGyroXSelfTestFactoryTrim() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_SELF_TEST_X) & 0xff; } /** * Get self-test factory trim value for gyro Y axis. * * @return factory trim value * @see MPU6050_RA_SELF_TEST_Y */ int getGyroYSelfTestFactoryTrim() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_SELF_TEST_Y) & 0xff; } /** * Get self-test factory trim value for gyro Z axis. * * @return factory trim value * @see MPU6050_RA_SELF_TEST_Z */ int getGyroZSelfTestFactoryTrim() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_SELF_TEST_Z) & 0x1F; } // ACCEL_CONFIG register /** * Get self-test enabled setting for accelerometer X axis. * * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelXSelfTest() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_XA_ST_BIT); } /** * Get self-test enabled setting for accelerometer X axis. * * @param enabled * Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelXSelfTest(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_XA_ST_BIT, enabled); } /** * Get self-test enabled value for accelerometer Y axis. * * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelYSelfTest() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_YA_ST_BIT); } /** * Get self-test enabled value for accelerometer Y axis. * * @param enabled * Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelYSelfTest(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_YA_ST_BIT, enabled); } /** * Get self-test enabled value for accelerometer Z axis. * * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelZSelfTest() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ZA_ST_BIT); } /** * Set self-test enabled value for accelerometer Z axis. * * @param enabled * Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelZSelfTest(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ZA_ST_BIT, enabled); } /** * Get full-scale accelerometer range. The FS_SEL parameter allows setting the * full-scale range of the accelerometer sensors, as described in the table * below. * * <pre> * 0 = +/- 2g * 1 = +/- 4g * 2 = +/- 8g * 3 = +/- 16g * </pre> * * @return Current full-scale accelerometer range setting * @see MPU6050_ACCEL_FS_2 * @see MPU6050_RA_ACCEL_CONFIG * @see MPU6050_ACONFIG_AFS_SEL_BIT * @see MPU6050_ACONFIG_AFS_SEL_LENGTH */ int getFullScaleAccelRange() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH); } /** * Set full-scale accelerometer range. * * @param range * New full-scale accelerometer range setting see * getFullScaleAccelRange() */ void setFullScaleAccelRange(int range) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH, range); } int getDHPFMode() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ACCEL_HPF_BIT, MPU6050_ACONFIG_ACCEL_HPF_LENGTH); } /** * Set the high-pass filter configuration. * * @param bandwidth * New high-pass filter configuration see setDHPFMode() * @see MPU6050_DHPF_RESET * @see MPU6050_RA_ACCEL_CONFIG */ void setDHPFMode(int bandwidth) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ACCEL_HPF_BIT, MPU6050_ACONFIG_ACCEL_HPF_LENGTH, bandwidth); } // FF_THR register /** * Get free-fall event acceleration threshold. This register configures the * detection threshold for Free Fall event detection. The unit of FF_THR is * 1LSB = 2mg. Free Fall is detected when the absolute value of the * accelerometer measurements for the three axes are each less than the * detection threshold. This condition increments the Free Fall duration * counter (Register 30). The Free Fall interrupt is triggered when the Free * Fall duration counter reaches the time specified in FF_DUR. * * For more details on the Free Fall detection interrupt, see Section 8.2 of * the MPU-6000/MPU-6050 Product Specification document as well as Registers * 56 and 58 of this document. * * @return Current free-fall acceleration threshold value (LSB = 2mg) * @see MPU6050_RA_FF_THR */ int getFreefallDetectionThreshold() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_FF_THR); } /** * Get free-fall event acceleration threshold. * * @param threshold * New free-fall acceleration threshold value (LSB = 2mg) see * getFreefallDetectionThreshold() * @see MPU6050_RA_FF_THR */ void setFreefallDetectionThreshold(int threshold) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_FF_THR, threshold); } // FF_DUR register /** * Get free-fall event duration threshold. This register configures the * duration counter threshold for Free Fall event detection. The duration * counter ticks at 1kHz, therefore FF_DUR has a unit of 1 LSB = 1 ms. * * The Free Fall duration counter increments while the absolute value of the * accelerometer measurements are each less than the detection threshold * (Register 29). The Free Fall interrupt is triggered when the Free Fall * duration counter reaches the time specified in this register. * * For more details on the Free Fall detection interrupt, see Section 8.2 of * the MPU-6000/MPU-6050 Product Specification document as well as Registers * 56 and 58 of this document. * * @return Current free-fall duration threshold value (LSB = 1ms) * @see MPU6050_RA_FF_DUR */ int getFreefallDetectionDuration() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_FF_DUR); } /** * Get free-fall event duration threshold. * * @param duration * New free-fall duration threshold value (LSB = 1ms) see * getFreefallDetectionDuration() * @see MPU6050_RA_FF_DUR */ void setFreefallDetectionDuration(int duration) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_FF_DUR, duration); } // MOT_THR register /** * Get motion detection event acceleration threshold. This register configures * the detection threshold for Motion interrupt generation. The unit of * MOT_THR is 1LSB = 2mg. Motion is detected when the absolute value of any of * the accelerometer measurements exceeds this Motion detection threshold. * This condition increments the Motion detection duration counter (Register * 32). The Motion detection interrupt is triggered when the Motion Detection * counter reaches the time count specified in MOT_DUR (Register 32). * * The Motion interrupt will indicate the axis and polarity of detected motion * in MOT_DETECT_STATUS (Register 97). * * For more details on the Motion detection interrupt, see Section 8.3 of the * MPU-6000/MPU-6050 Product Specification document as well as Registers 56 * and 58 of this document. * * @return Current motion detection acceleration threshold value (LSB = 2mg) * @see MPU6050_RA_MOT_THR */ int getMotionDetectionThreshold() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_MOT_THR); } /** * Set motion detection event acceleration threshold. * * @param threshold * New motion detection acceleration threshold value (LSB = 2mg) see * getMotionDetectionThreshold() * @see MPU6050_RA_MOT_THR */ void setMotionDetectionThreshold(int threshold) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_MOT_THR, threshold); } // MOT_DUR register /** * Get motion detection event duration threshold. This register configures the * duration counter threshold for Motion interrupt generation. The duration * counter ticks at 1 kHz, therefore MOT_DUR has a unit of 1LSB = 1ms. The * Motion detection duration counter increments when the absolute value of any * of the accelerometer measurements exceeds the Motion detection threshold * (Register 31). The Motion detection interrupt is triggered when the Motion * detection counter reaches the time count specified in this register. * * For more details on the Motion detection interrupt, see Section 8.3 of the * MPU-6000/MPU-6050 Product Specification document. * * @return Current motion detection duration threshold value (LSB = 1ms) * @see MPU6050_RA_MOT_DUR */ int getMotionDetectionDuration() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_MOT_DUR); } /** * Set motion detection event duration threshold. * * @param duration * New motion detection duration threshold value (LSB = 1ms) see * getMotionDetectionDuration() * @see MPU6050_RA_MOT_DUR */ void setMotionDetectionDuration(int duration) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_MOT_DUR, duration); } // ZRMOT_THR register /** * Get zero motion detection event acceleration threshold. This register * configures the detection threshold for Zero Motion interrupt generation. * The unit of ZRMOT_THR is 1LSB = 2mg. Zero Motion is detected when the * absolute value of the accelerometer measurements for the 3 axes are each * less than the detection threshold. This condition increments the Zero * Motion duration counter (Register 34). The Zero Motion interrupt is * triggered when the Zero Motion duration counter reaches the time count * specified in ZRMOT_DUR (Register 34). * * Unlike Free Fall or Motion detection, Zero Motion detection triggers an * interrupt both when Zero Motion is first detected and when Zero Motion is * no longer detected. * * When a zero motion event is detected, a Zero Motion Status will be * indicated in the MOT_DETECT_STATUS register (Register 97). When a * motion-to-zero-motion condition is detected, the status bit is set to 1. * When a zero-motion-to- motion condition is detected, the status bit is set * to 0. * * For more details on the Zero Motion detection interrupt, see Section 8.4 of * the MPU-6000/MPU-6050 Product Specification document as well as Registers * 56 and 58 of this document. * * @return Current zero motion detection acceleration threshold value (LSB = * 2mg) * @see MPU6050_RA_ZRMOT_THR */ int getZeroMotionDetectionThreshold() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_ZRMOT_THR); } /** * Set zero motion detection event acceleration threshold. * * @param threshold * New zero motion detection acceleration threshold value (LSB = 2mg) * see getZeroMotionDetectionThreshold() * @see MPU6050_RA_ZRMOT_THR */ void setZeroMotionDetectionThreshold(int threshold) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_ZRMOT_THR, threshold); } // ZRMOT_DUR register /** * Get zero motion detection event duration threshold. This register * configures the duration counter threshold for Zero Motion interrupt * generation. The duration counter ticks at 16 Hz, therefore ZRMOT_DUR has a * unit of 1 LSB = 64 ms. The Zero Motion duration counter increments while * the absolute value of the accelerometer measurements are each less than the * detection threshold (Register 33). The Zero Motion interrupt is triggered * when the Zero Motion duration counter reaches the time count specified in * this register. * * For more details on the Zero Motion detection interrupt, see Section 8.4 of * the MPU-6000/MPU-6050 Product Specification document, as well as Registers * 56 and 58 of this document. * * @return Current zero motion detection duration threshold value (LSB = 64ms) * @see MPU6050_RA_ZRMOT_DUR */ int getZeroMotionDetectionDuration() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_ZRMOT_DUR); } /** * Set zero motion detection event duration threshold. * * @param duration * New zero motion detection duration threshold value (LSB = 1ms) see * getZeroMotionDetectionDuration() * @see MPU6050_RA_ZRMOT_DUR */ void setZeroMotionDetectionDuration(int duration) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_ZRMOT_DUR, duration); } // FIFO_EN register /** * Get temperature FIFO enabled value. When set to 1, this bit enables * TEMP_OUT_H and TEMP_OUT_L (Registers 65 and 66) to be written into the FIFO * buffer. * * @return Current temperature FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getTempFIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_TEMP_FIFO_EN_BIT); } /** * Set temperature FIFO enabled value. * * @param enabled * New temperature FIFO enabled value see getTempFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setTempFIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_TEMP_FIFO_EN_BIT, enabled); } /** * Get gyroscope X-axis FIFO enabled value. When set to 1, this bit enables * GYRO_XOUT_H and GYRO_XOUT_L (Registers 67 and 68) to be written into the * FIFO buffer. * * @return Current gyroscope X-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getXGyroFIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_XG_FIFO_EN_BIT); } /** * Set gyroscope X-axis FIFO enabled value. * * @param enabled * New gyroscope X-axis FIFO enabled value see getXGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setXGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_XG_FIFO_EN_BIT, enabled); } /** * Get gyroscope Y-axis FIFO enabled value. When set to 1, this bit enables * GYRO_YOUT_H and GYRO_YOUT_L (Registers 69 and 70) to be written into the * FIFO buffer. * * @return Current gyroscope Y-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getYGyroFIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_YG_FIFO_EN_BIT); } /** * Set gyroscope Y-axis FIFO enabled value. * * @param enabled * New gyroscope Y-axis FIFO enabled value see getYGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setYGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_YG_FIFO_EN_BIT, enabled); } /** * Get gyroscope Z-axis FIFO enabled value. When set to 1, this bit enables * GYRO_ZOUT_H and GYRO_ZOUT_L (Registers 71 and 72) to be written into the * FIFO buffer. * * @return Current gyroscope Z-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getZGyroFIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_ZG_FIFO_EN_BIT); } /** * Set gyroscope Z-axis FIFO enabled value. * * @param enabled * New gyroscope Z-axis FIFO enabled value see getZGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setZGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_ZG_FIFO_EN_BIT, enabled); } /** * Get accelerometer FIFO enabled value. When set to 1, this bit enables * ACCEL_XOUT_H, ACCEL_XOUT_L, ACCEL_YOUT_H, ACCEL_YOUT_L, ACCEL_ZOUT_H, and * ACCEL_ZOUT_L (Registers 59 to 64) to be written into the FIFO buffer. * * @return Current accelerometer FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getAccelFIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_ACCEL_FIFO_EN_BIT); } /** * Set accelerometer FIFO enabled value. * * @param enabled * New accelerometer FIFO enabled value see getAccelFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setAccelFIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_ACCEL_FIFO_EN_BIT, enabled); } /** * Get Slave 2 FIFO enabled value. When set to 1, this bit enables * EXT_SENS_DATA registers (Registers 73 to 96) associated with Slave 2 to be * written into the FIFO buffer. * * @return Current Slave 2 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave2FIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_SLV2_FIFO_EN_BIT); } /** * Set Slave 2 FIFO enabled value. * * @param enabled * New Slave 2 FIFO enabled value see getSlave2FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave2FIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_SLV2_FIFO_EN_BIT, enabled); } /** * Get Slave 1 FIFO enabled value. When set to 1, this bit enables * EXT_SENS_DATA registers (Registers 73 to 96) associated with Slave 1 to be * written into the FIFO buffer. * * @return Current Slave 1 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave1FIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_SLV1_FIFO_EN_BIT); } /** * Set Slave 1 FIFO enabled value. * * @param enabled * New Slave 1 FIFO enabled value see getSlave1FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave1FIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_SLV1_FIFO_EN_BIT, enabled); } /** * Get Slave 0 FIFO enabled value. When set to 1, this bit enables * EXT_SENS_DATA registers (Registers 73 to 96) associated with Slave 0 to be * written into the FIFO buffer. * * @return Current Slave 0 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave0FIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_SLV0_FIFO_EN_BIT); } /** * Set Slave 0 FIFO enabled value. * * @param enabled * New Slave 0 FIFO enabled value see getSlave0FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave0FIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_FIFO_EN, MPU6050_SLV0_FIFO_EN_BIT, enabled); } // I2C_MST_CTRL register /** * Get multi-master enabled value. Multi-master capability allows multiple I2C * masters to operate on the same bus. In circuits where multi-master * capability is required, set MULT_MST_EN to 1. This will increase current * drawn by approximately 30uA. * * In circuits where multi-master capability is required, the state of the I2C * bus must always be monitored by each separate I2C Master. Before an I2C * Master can assume arbitration of the bus, it must first confirm that no * other I2C Master has arbitration of the bus. When MULT_MST_EN is set to 1, * the MPU-60X0's bus arbitration detection logic is turned on, enabling it to * detect when the bus is available. * * @return Current multi-master enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getMultiMasterEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_MULT_MST_EN_BIT); } /** * Set multi-master enabled value. * * @param enabled * New multi-master enabled value see getMultiMasterEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setMultiMasterEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_MULT_MST_EN_BIT, enabled); } /** * Get wait-for-external-sensor-data enabled value. When the WAIT_FOR_ES bit * is set to 1, the Data Ready interrupt will be delayed until External Sensor * data from the Slave Devices are loaded into the EXT_SENS_DATA registers. * This is used to ensure that both the internal sensor data (i.e. from gyro * and accel) and external sensor data have been loaded to their respective * data registers (i.e. the data is synced) when the Data Ready interrupt is * triggered. * * @return Current wait-for-external-sensor-data enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getWaitForExternalSensorEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_WAIT_FOR_ES_BIT); } /** * Set wait-for-external-sensor-data enabled value. * * @param enabled * New wait-for-external-sensor-data enabled value see * getWaitForExternalSensorEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setWaitForExternalSensorEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_WAIT_FOR_ES_BIT, enabled); } /** * Get Slave 3 FIFO enabled value. When set to 1, this bit enables * EXT_SENS_DATA registers (Registers 73 to 96) associated with Slave 3 to be * written into the FIFO buffer. * * @return Current Slave 3 FIFO enabled value * @see MPU6050_RA_MST_CTRL */ boolean getSlave3FIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_SLV_3_FIFO_EN_BIT); } /** * Set Slave 3 FIFO enabled value. * * @param enabled * New Slave 3 FIFO enabled value see getSlave3FIFOEnabled() * @see MPU6050_RA_MST_CTRL */ void setSlave3FIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_SLV_3_FIFO_EN_BIT, enabled); } /** * Get slave read/write transition enabled value. The I2C_MST_P_NSR bit * configures the I2C Master's transition from one slave read to the next * slave read. If the bit equals 0, there will be a restart between reads. If * the bit equals 1, there will be a stop followed by a start of the following * read. When a write transaction follows a read transaction, the stop * followed by a start of the successive write will be always used. * * @return Current slave read/write transition enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getSlaveReadWriteTransitionEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_P_NSR_BIT); } /** * Set slave read/write transition enabled value. * * @param enabled * New slave read/write transition enabled value see * getSlaveReadWriteTransitionEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setSlaveReadWriteTransitionEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_P_NSR_BIT, enabled); } int getMasterClockSpeed() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_CLK_BIT, MPU6050_I2C_MST_CLK_LENGTH); } /** * Set I2C master clock speed. * * @reparam speed Current I2C master clock speed * @see MPU6050_RA_I2C_MST_CTRL */ void setMasterClockSpeed(int speed) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_CLK_BIT, MPU6050_I2C_MST_CLK_LENGTH, speed); } // I2C_SLV* registers (Slave 0-3) /** * Get the I2C address of the specified slave (0-3). Note that Bit 7 (MSB) * controls read/write mode. If Bit 7 is set, it's a read operation, and if it * is cleared, then it's a write operation. The remaining bits (6-0) are the * 7-bit device address of the slave device. * * In read mode, the result of the read is placed in the lowest available * EXT_SENS_DATA register. For further information regarding the allocation of * read results, please refer to the EXT_SENS_DATA register description * (Registers 73 - 96). * * The MPU-6050 supports a total of five slaves, but Slave 4 has unique * characteristics, and so it has its own functions (getSlave4* and * setSlave4*). * * I2C data transactions are performed at the Sample Rate, as defined in * Register 25. The user is responsible for ensuring that I2C data * transactions to and from each enabled Slave can be completed within a * single period of the Sample Rate. * * The I2C slave access rate can be reduced relative to the Sample Rate. This * reduced access rate is determined by I2C_MST_DLY (Register 52). Whether a * slave's access rate is reduced relative to the Sample Rate is determined by * I2C_MST_DELAY_CTRL (Register 103). * * The processing order for the slaves is fixed. The sequence followed for * processing the slaves is Slave 0, Slave 1, Slave 2, Slave 3 and Slave 4. If * a particular Slave is disabled it will be skipped. * * Each slave can either be accessed at the sample rate or at a reduced sample * rate. In a case where some slaves are accessed at the Sample Rate and some * slaves are accessed at the reduced rate, the sequence of accessing the * slaves (Slave 0 to Slave 4) is still followed. However, the reduced rate * slaves will be skipped if their access rate dictates that they should not * be accessed during that particular cycle. For further information regarding * the reduced access rate, please refer to Register 52. Whether a slave is * accessed at the Sample Rate or at the reduced rate is determined by the * Delay Enable bits in Register 103. * * @param num * Slave number (0-3) * @return Current address for specified slave * @see MPU6050_RA_I2C_SLV0_ADDR */ int getSlaveAddress(int num) { if (num > 3) return 0; return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_ADDR + num * 3); } /** * Set the I2C address of the specified slave (0-3). * * @param num * Slave number (0-3) * @param address * New address for specified slave see getSlaveAddress() * @see MPU6050_RA_I2C_SLV0_ADDR */ void setSlaveAddress(int num, int address) { if (num > 3) return; I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_ADDR + num * 3, address); } /** * Get the active internal register for the specified slave (0-3). Read/write * operations for this slave will be done to whatever internal register * address is stored in this MPU register. * * The MPU-6050 supports a total of five slaves, but Slave 4 has unique * characteristics, and so it has its own functions. * * @param num * Slave number (0-3) * @return Current active register for specified slave * @see MPU6050_RA_I2C_SLV0_REG */ int getSlaveRegister(int num) { if (num > 3) return 0; return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_REG + num * 3); } /** * Set the active internal register for the specified slave (0-3). * * @param num * Slave number (0-3) * @param reg * New active register for specified slave see getSlaveRegister() * @see MPU6050_RA_I2C_SLV0_REG */ void setSlaveRegister(int num, int reg) { if (num > 3) return; I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_REG + num * 3, reg); } /** * Get the enabled value for the specified slave (0-3). When set to 1, this * bit enables Slave 0 for data transfer operations. When cleared to 0, this * bit disables Slave 0 from data transfer operations. * * @param num * Slave number (0-3) * @return Current enabled value for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveEnabled(int num) { if (num > 3) return false; return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_EN_BIT); } /** * Set the enabled value for the specified slave (0-3). * * @param num * Slave number (0-3) * @param enabled * New enabled value for specified slave see getSlaveEnabled() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveEnabled(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_EN_BIT, enabled); } /** * Get word pair byte-swapping enabled for the specified slave (0-3). When set * to 1, this bit enables byte swapping. When byte swapping is enabled, the * high and low bytes of a word pair are swapped. Please refer to I2C_SLV0_GRP * for the pairing convention of the word pairs. When cleared to 0, bytes * transferred to and from Slave 0 will be written to EXT_SENS_DATA registers * in the order they were transferred. * * @param num * Slave number (0-3) * @return Current word pair byte-swapping enabled value for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWordByteSwap(int num) { if (num > 3) return false; return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_BYTE_SW_BIT); } /** * Set word pair byte-swapping enabled for the specified slave (0-3). * * @param num * Slave number (0-3) * @param enabled * New word pair byte-swapping enabled value for specified slave see * getSlaveWordByteSwap() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWordByteSwap(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_BYTE_SW_BIT, enabled); } /** * Get write mode for the specified slave (0-3). When set to 1, the * transaction will read or write data only. When cleared to 0, the * transaction will write a register address prior to reading or writing data. * This should equal 0 when specifying the register address within the Slave * device to/from which the ensuing data transaction will take place. * * @param num * Slave number (0-3) * @return Current write mode for specified slave (0 = register address + * data, 1 = data only) * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWriteMode(int num) { if (num > 3) return false; return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_REG_DIS_BIT); } /** * Set write mode for the specified slave (0-3). * * @param num * Slave number (0-3) * @param mode * New write mode for specified slave (0 = register address + data, 1 * = data only) see getSlaveWriteMode() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWriteMode(int num, boolean mode) { if (num > 3) return; I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_REG_DIS_BIT, mode); } /** * Get word pair grouping order offset for the specified slave (0-3). This * sets specifies the grouping order of word pairs received from registers. * When cleared to 0, bytes from register addresses 0 and 1, 2 and 3, etc * (even, then odd register addresses) are paired to form a word. When set to * 1, bytes from register addresses are paired 1 and 2, 3 and 4, etc. (odd, * then even register addresses) are paired to form a word. * * @param num * Slave number (0-3) * @return Current word pair grouping order offset for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWordGroupOffset(int num) { if (num > 3) return false; return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_GRP_BIT); } /** * Set word pair grouping order offset for the specified slave (0-3). * * @param num * Slave number (0-3) * @param enabled * New word pair grouping order offset for specified slave see * getSlaveWordGroupOffset() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWordGroupOffset(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_GRP_BIT, enabled); } /** * Get number of bytes to read for the specified slave (0-3). Specifies the * number of bytes transferred to and from Slave 0. Clearing this bit to 0 is * equivalent to disabling the register by writing 0 to I2C_SLV0_EN. * * @param num * Slave number (0-3) * @return Number of bytes to read for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ int getSlaveDataLength(int num) { if (num > 3) return 0; return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_LEN_BIT, MPU6050_I2C_SLV_LEN_LENGTH); } /** * Set number of bytes to read for the specified slave (0-3). * * @param num * Slave number (0-3) * @param length * Number of bytes to read for specified slave see * getSlaveDataLength() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveDataLength(int num, int length) { if (num > 3) return; I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_CTRL + num * 3, MPU6050_I2C_SLV_LEN_BIT, MPU6050_I2C_SLV_LEN_LENGTH, length); } // I2C_SLV* registers (Slave 4) /** * Get the I2C address of Slave 4. Note that Bit 7 (MSB) controls read/write * mode. If Bit 7 is set, it's a read operation, and if it is cleared, then * it's a write operation. The remaining bits (6-0) are the 7-bit device * address of the slave device. * * @return Current address for Slave 4 see getSlaveAddress() * @see MPU6050_RA_I2C_SLV4_ADDR */ int getSlave4Address() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_ADDR); } /** * Set the I2C address of Slave 4. * * @param address * New address for Slave 4 see getSlave4Address() * @see MPU6050_RA_I2C_SLV4_ADDR */ void setSlave4Address(int address) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_ADDR, address); } /** * Get the active internal register for the Slave 4. Read/write operations for * this slave will be done to whatever internal register address is stored in * this MPU register. * * @return Current active register for Slave 4 * @see MPU6050_RA_I2C_SLV4_REG */ int getSlave4Register() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_REG); } /** * Set the active internal register for Slave 4. * * @param reg * New active register for Slave 4 see getSlave4Register() * @see MPU6050_RA_I2C_SLV4_REG */ void setSlave4Register(int reg) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_REG, reg); } /** * Set new byte to write to Slave 4. This register stores the data to be * written into the Slave 4. If I2C_SLV4_RW is set 1 (set to read), this * register has no effect. * * @param data * New byte to write to Slave 4 * @see MPU6050_RA_I2C_SLV4_DO */ void setSlave4OutputByte(int data) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_DO, data); } /** * Get the enabled value for the Slave 4. When set to 1, this bit enables * Slave 4 for data transfer operations. When cleared to 0, this bit disables * Slave 4 from data transfer operations. * * @return Current enabled value for Slave 4 * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4Enabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_EN_BIT); } /** * Set the enabled value for Slave 4. * * @param enabled * New enabled value for Slave 4 see getSlave4Enabled() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4Enabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_EN_BIT, enabled); } /** * Get the enabled value for Slave 4 transaction interrupts. When set to 1, * this bit enables the generation of an interrupt signal upon completion of a * Slave 4 transaction. When cleared to 0, this bit disables the generation of * an interrupt signal upon completion of a Slave 4 transaction. The interrupt * status can be observed in Register 54. * * @return Current enabled value for Slave 4 transaction interrupts. * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4InterruptEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_INT_EN_BIT); } /** * Set the enabled value for Slave 4 transaction interrupts. * * @param enabled * New enabled value for Slave 4 transaction interrupts. see * getSlave4InterruptEnabled() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4InterruptEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_INT_EN_BIT, enabled); } /** * Get write mode for Slave 4. When set to 1, the transaction will read or * write data only. When cleared to 0, the transaction will write a register * address prior to reading or writing data. This should equal 0 when * specifying the register address within the Slave device to/from which the * ensuing data transaction will take place. * * @return Current write mode for Slave 4 (0 = register address + data, 1 = * data only) * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4WriteMode() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_REG_DIS_BIT); } /** * Set write mode for the Slave 4. * * @param mode * New write mode for Slave 4 (0 = register address + data, 1 = data * only) see getSlave4WriteMode() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4WriteMode(boolean mode) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_REG_DIS_BIT, mode); } /** * Get Slave 4 master delay value. This configures the reduced access rate of * I2C slaves relative to the Sample Rate. When a slave's access rate is * decreased relative to the Sample Rate, the slave is accessed every: * * 1 / (1 + I2C_MST_DLY) samples * * This base Sample Rate in turn is determined by SMPLRT_DIV (register 25) and * DLPF_CFG (register 26). Whether a slave's access rate is reduced relative * to the Sample Rate is determined by I2C_MST_DELAY_CTRL (register 103). For * further information regarding the Sample Rate, please refer to register 25. * * @return Current Slave 4 master delay value * @see MPU6050_RA_I2C_SLV4_CTRL */ int getSlave4MasterDelay() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_MST_DLY_BIT, MPU6050_I2C_SLV4_MST_DLY_LENGTH); } /** * Set Slave 4 master delay value. * * @param delay * New Slave 4 master delay value see getSlave4MasterDelay() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4MasterDelay(int delay) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_MST_DLY_BIT, MPU6050_I2C_SLV4_MST_DLY_LENGTH, delay); } /** * Get last available byte read from Slave 4. This register stores the data * read from Slave 4. This field is populated after a read transaction. * * @return Last available byte read from to Slave 4 * @see MPU6050_RA_I2C_SLV4_DI */ int getSlate4InputByte() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV4_DI); } // I2C_MST_STATUS register /** * Get FSYNC interrupt status. This bit reflects the status of the FSYNC * interrupt from an external device into the MPU-60X0. This is used as a way * to pass an external interrupt through the MPU-60X0 to the host application * processor. When set to 1, this bit will cause an interrupt if FSYNC_INT_EN * is asserted in INT_PIN_CFG (Register 55). * * @return FSYNC interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getPassthroughStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_PASS_THROUGH_BIT); } /** * Get Slave 4 transaction done status. Automatically sets to 1 when a Slave 4 * transaction has completed. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted and if the * SLV_4_DONE_INT bit is asserted in the I2C_SLV4_CTRL register (Register 52). * * @return Slave 4 transaction done status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave4IsDone() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV4_DONE_BIT); } /** * Get master arbitration lost status. This bit automatically sets to 1 when * the I2C Master has lost arbitration of the auxiliary I2C bus (an error * condition). This triggers an interrupt if the I2C_MST_INT_EN bit in the * INT_ENABLE register (Register 56) is asserted. * * @return Master arbitration lost status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getLostArbitration() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_LOST_ARB_BIT); } /** * Get Slave 4 NACK status. This bit automatically sets to 1 when the I2C * Master receives a NACK in a transaction with Slave 4. This triggers an * interrupt if the I2C_MST_INT_EN bit in the INT_ENABLE register (Register * 56) is asserted. * * @return Slave 4 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave4Nack() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV4_NACK_BIT); } /** * Get Slave 3 NACK status. This bit automatically sets to 1 when the I2C * Master receives a NACK in a transaction with Slave 3. This triggers an * interrupt if the I2C_MST_INT_EN bit in the INT_ENABLE register (Register * 56) is asserted. * * @return Slave 3 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave3Nack() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV3_NACK_BIT); } /** * Get Slave 2 NACK status. This bit automatically sets to 1 when the I2C * Master receives a NACK in a transaction with Slave 2. This triggers an * interrupt if the I2C_MST_INT_EN bit in the INT_ENABLE register (Register * 56) is asserted. * * @return Slave 2 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave2Nack() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV2_NACK_BIT); } /** * Get Slave 1 NACK status. This bit automatically sets to 1 when the I2C * Master receives a NACK in a transaction with Slave 1. This triggers an * interrupt if the I2C_MST_INT_EN bit in the INT_ENABLE register (Register * 56) is asserted. * * @return Slave 1 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave1Nack() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV1_NACK_BIT); } /** * Get Slave 0 NACK status. This bit automatically sets to 1 when the I2C * Master receives a NACK in a transaction with Slave 0. This triggers an * interrupt if the I2C_MST_INT_EN bit in the INT_ENABLE register (Register * 56) is asserted. * * @return Slave 0 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave0Nack() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV0_NACK_BIT); } // INT_PIN_CFG register /** * Get interrupt logic level mode. Will be set 0 for active-high, 1 for * active-low. * * @return Current interrupt mode (0=active-high, 1=active-low) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_LEVEL_BIT */ boolean getInterruptMode() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_LEVEL_BIT); } /** * Set interrupt logic level mode. * * @param mode * New interrupt mode (0=active-high, 1=active-low) see * getInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_LEVEL_BIT */ void setInterruptMode(boolean mode) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_LEVEL_BIT, mode); } /** * Get interrupt drive mode. Will be set 0 for push-pull, 1 for open-drain. * * @return Current interrupt drive mode (0=push-pull, 1=open-drain) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_OPEN_BIT */ boolean getInterruptDrive() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_OPEN_BIT); } /** * Set interrupt drive mode. * * @param drive * New interrupt drive mode (0=push-pull, 1=open-drain) see * getInterruptDrive() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_OPEN_BIT */ void setInterruptDrive(boolean drive) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_OPEN_BIT, drive); } /** * Get interrupt latch mode. Will be set 0 for 50us-pulse, 1 for * latch-until-int-cleared. * * @return Current latch mode (0=50us-pulse, 1=latch-until-int-cleared) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_LATCH_INT_EN_BIT */ boolean getInterruptLatch() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_LATCH_INT_EN_BIT); } /** * Set interrupt latch mode. * * @param latch * New latch mode (0=50us-pulse, 1=latch-until-int-cleared) see * getInterruptLatch() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_LATCH_INT_EN_BIT */ void setInterruptLatch(boolean latch) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_LATCH_INT_EN_BIT, latch); } /** * Get interrupt latch clear mode. Will be set 0 for status-read-only, 1 for * any-register-read. * * @return Current latch clear mode (0=status-read-only, 1=any-register-read) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_RD_CLEAR_BIT */ boolean getInterruptLatchClear() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_RD_CLEAR_BIT); } /** * Set interrupt latch clear mode. * * @param clear * New latch clear mode (0=status-read-only, 1=any-register-read) see * getInterruptLatchClear() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_RD_CLEAR_BIT */ void setInterruptLatchClear(boolean clear) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_RD_CLEAR_BIT, clear); } /** * Get FSYNC interrupt logic level mode. * * @return Current FSYNC interrupt mode (0=active-high, 1=active-low) see * getFSyncInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT */ boolean getFSyncInterruptLevel() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT); } /** * Set FSYNC interrupt logic level mode. * * @param mode * New FSYNC interrupt mode (0=active-high, 1=active-low) see * getFSyncInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT */ void setFSyncInterruptLevel(boolean level) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT, level); } /** * Get FSYNC pin interrupt enabled setting. Will be set 0 for disabled, 1 for * enabled. * * @return Current interrupt enabled setting * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_EN_BIT */ boolean getFSyncInterruptEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_EN_BIT); } /** * Set FSYNC pin interrupt enabled setting. * * @param enabled * New FSYNC pin interrupt enabled setting see * getFSyncInterruptEnabled() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_EN_BIT */ void setFSyncInterruptEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_EN_BIT, enabled); } /** * Get I2C bypass enabled status. When this bit is equal to 1 and I2C_MST_EN * (Register 106 bit[5]) is equal to 0, the host application processor will be * able to directly access the auxiliary I2C bus of the MPU-60X0. When this * bit is equal to 0, the host application processor will not be able to * directly access the auxiliary I2C bus of the MPU-60X0 regardless of the * state of I2C_MST_EN (Register 106 bit[5]). * * @return Current I2C bypass enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_I2C_BYPASS_EN_BIT */ boolean getI2CBypassEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_I2C_BYPASS_EN_BIT); } /** * Set I2C bypass enabled status. When this bit is equal to 1 and I2C_MST_EN * (Register 106 bit[5]) is equal to 0, the host application processor will be * able to directly access the auxiliary I2C bus of the MPU-60X0. When this * bit is equal to 0, the host application processor will not be able to * directly access the auxiliary I2C bus of the MPU-60X0 regardless of the * state of I2C_MST_EN (Register 106 bit[5]). * * @param enabled * New I2C bypass enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_I2C_BYPASS_EN_BIT */ void setI2CBypassEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_I2C_BYPASS_EN_BIT, enabled); } /** * Get reference clock output enabled status. When this bit is equal to 1, a * reference clock output is provided at the CLKOUT pin. When this bit is * equal to 0, the clock output is disabled. For further information regarding * CLKOUT, please refer to the MPU-60X0 Product Specification document. * * @return Current reference clock output enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_CLKOUT_EN_BIT */ boolean getClockOutputEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_CLKOUT_EN_BIT); } /** * Set reference clock output enabled status. When this bit is equal to 1, a * reference clock output is provided at the CLKOUT pin. When this bit is * equal to 0, the clock output is disabled. For further information regarding * CLKOUT, please refer to the MPU-60X0 Product Specification document. * * @param enabled * New reference clock output enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_CLKOUT_EN_BIT */ void setClockOutputEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_CLKOUT_EN_BIT, enabled); } // INT_ENABLE register /** * Get full interrupt enabled status. Full register byte for all interrupts, * for quick reading. Each bit will be set 0 for disabled, 1 for enabled. * * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ int getIntEnabled() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE); } /** * Set full interrupt enabled status. Full register byte for all interrupts, * for quick reading. Each bit should be set 0 for disabled, 1 for enabled. * * @param enabled * New interrupt enabled status see getIntFreefallEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ void setIntEnabled(int enabled) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, enabled); } /** * Get Free Fall interrupt enabled status. Will be set 0 for disabled, 1 for * enabled. * * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ boolean getIntFreefallEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FF_BIT); } /** * Set Free Fall interrupt enabled status. * * @param enabled * New interrupt enabled status see getIntFreefallEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ void setIntFreefallEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FF_BIT, enabled); } /** * Get Motion Detection interrupt enabled status. Will be set 0 for disabled, * 1 for enabled. * * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_MOT_BIT **/ boolean getIntMotionEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_MOT_BIT); } /** * Set Motion Detection interrupt enabled status. * * @param enabled * New interrupt enabled status see getIntMotionEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_MOT_BIT **/ void setIntMotionEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_MOT_BIT, enabled); } /** * Get Zero Motion Detection interrupt enabled status. Will be set 0 for * disabled, 1 for enabled. * * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_ZMOT_BIT **/ boolean getIntZeroMotionEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_ZMOT_BIT); } /** * Set Zero Motion Detection interrupt enabled status. * * @param enabled * New interrupt enabled status see getIntZeroMotionEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_ZMOT_BIT **/ void setIntZeroMotionEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_ZMOT_BIT, enabled); } /** * Get FIFO Buffer Overflow interrupt enabled status. Will be set 0 for * disabled, 1 for enabled. * * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT **/ boolean getIntFIFOBufferOverflowEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FIFO_OFLOW_BIT); } /** * Set FIFO Buffer Overflow interrupt enabled status. * * @param enabled * New interrupt enabled status see getIntFIFOBufferOverflowEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT **/ void setIntFIFOBufferOverflowEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FIFO_OFLOW_BIT, enabled); } /** * Get I2C Master interrupt enabled status. This enables any of the I2C Master * interrupt sources to generate an interrupt. Will be set 0 for disabled, 1 * for enabled. * * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT **/ boolean getIntI2CMasterEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_I2C_MST_INT_BIT); } /** * Set I2C Master interrupt enabled status. * * @param enabled * New interrupt enabled status see getIntI2CMasterEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT **/ void setIntI2CMasterEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_I2C_MST_INT_BIT, enabled); } /** * Get Data Ready interrupt enabled setting. This event occurs each time a * write operation to all of the sensor registers has been completed. Will be * set 0 for disabled, 1 for enabled. * * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ boolean getIntDataReadyEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DATA_RDY_BIT); } /** * Set Data Ready interrupt enabled status. * * @param enabled * New interrupt enabled status see getIntDataReadyEnabled() * @see MPU6050_RA_INT_CFG * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ void setIntDataReadyEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DATA_RDY_BIT, enabled); } // INT_STATUS register /** * Get full set of interrupt status bits. These bits clear to 0 after the * register has been read. Very useful for getting multiple INT statuses, * since each single bit read clears all of them because it has to read the * whole byte. * * @return Current interrupt status * @see MPU6050_RA_INT_STATUS */ int getIntStatus() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS); } /** * Get Free Fall interrupt status. This bit automatically sets to 1 when a * Free Fall interrupt has been generated. The bit clears to 0 after the * register has been read. * * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_FF_BIT */ boolean getIntFreefallStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_FF_BIT); } /** * Get Motion Detection interrupt status. This bit automatically sets to 1 * when a Motion Detection interrupt has been generated. The bit clears to 0 * after the register has been read. * * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_MOT_BIT */ boolean getIntMotionStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_MOT_BIT); } /** * Get Zero Motion Detection interrupt status. This bit automatically sets to * 1 when a Zero Motion Detection interrupt has been generated. The bit clears * to 0 after the register has been read. * * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_ZMOT_BIT */ boolean getIntZeroMotionStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_ZMOT_BIT); } /** * Get FIFO Buffer Overflow interrupt status. This bit automatically sets to 1 * when a Free Fall interrupt has been generated. The bit clears to 0 after * the register has been read. * * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT */ boolean getIntFIFOBufferOverflowStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_FIFO_OFLOW_BIT); } /** * Get I2C Master interrupt status. This bit automatically sets to 1 when an * I2C Master interrupt has been generated. For a list of I2C Master * interrupts, please refer to Register 54. The bit clears to 0 after the * register has been read. * * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT */ boolean getIntI2CMasterStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_I2C_MST_INT_BIT); } /** * Get Data Ready interrupt status. This bit automatically sets to 1 when a * Data Ready interrupt has been generated. The bit clears to 0 after the * register has been read. * * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ boolean getIntDataReadyStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_DATA_RDY_BIT); } void getAcceleration(int[] x, int[] y, int[] z) { int readBuffer[] = new int[6]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_XOUT_H, 6, readBuffer); x[0] = ((byte) readBuffer[0] << 8) | readBuffer[1] & 0xff; y[0] = ((byte) readBuffer[2] << 8) | readBuffer[3] & 0xff; z[0] = ((byte) readBuffer[4] << 8) | readBuffer[5] & 0xff; } /** * Get X-axis accelerometer reading. * * @return X-axis acceleration measurement in 16-bit 2's complement format see * getMotion6() * @see MPU6050_RA_ACCEL_XOUT_H */ int getAccelerationX() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_XOUT_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } /** * Get Y-axis accelerometer reading. * * @return Y-axis acceleration measurement in 16-bit 2's complement format see * getMotion6() * @see MPU6050_RA_ACCEL_YOUT_H */ int getAccelerationY() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_YOUT_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } /** * Get Z-axis accelerometer reading. * * @return Z-axis acceleration measurement in 16-bit 2's complement format see * getMotion6() * @see MPU6050_RA_ACCEL_ZOUT_H */ int getAccelerationZ() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_ACCEL_ZOUT_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } // TEMP_OUT_* registers /** * Get current internal temperature. * * @return Temperature reading in 16-bit 2's complement format * @see MPU6050_RA_TEMP_OUT_H */ double getTemperatureCelcius() { double rawTemp = getTemperature(); double tempCelcius = (rawTemp / 340.0) + 36.53; return tempCelcius; } /** * Get current internal temperature. * * @return Temperature reading in 16-bit 2's complement format * @see MPU6050_RA_TEMP_OUT_H */ int getTemperature() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_TEMP_OUT_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } // GYRO_*OUT_* registers void getRotation(int x[], int y[], int z[]) { int readBuffer[] = new int[6]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_GYRO_XOUT_H, 6, readBuffer); x[0] = (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; y[0] = (byte) readBuffer[2] << 8 | readBuffer[3] & 0xff; z[0] = (byte) readBuffer[4] << 8 | readBuffer[5] & 0xff; } /** * Get X-axis gyroscope reading. * * @return X-axis rotation measurement in 16-bit 2's complement format see * getMotion6() * @see MPU6050_RA_GYRO_XOUT_H */ int getRotationX() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_GYRO_XOUT_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } /** * Get Y-axis gyroscope reading. * * @return Y-axis rotation measurement in 16-bit 2's complement format see * getMotion6() * @see MPU6050_RA_GYRO_YOUT_H */ int getRotationY() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_GYRO_YOUT_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } /** * Get Z-axis gyroscope reading. * * @return Z-axis rotation measurement in 16-bit 2's complement format see * getMotion6() * @see MPU6050_RA_GYRO_ZOUT_H */ int getRotationZ() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_GYRO_ZOUT_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } // EXT_SENS_DATA_* registers /** * Read single byte from external sensor data register. These registers store * data read from external sensors by the Slave 0, 1, 2, and 3 on the * auxiliary I2C interface. Data read by Slave 4 is stored in I2C_SLV4_DI * (Register 53). * * External sensor data is written to these registers at the Sample Rate as * defined in Register 25. This access rate can be reduced by using the Slave * Delay Enable registers (Register 103). * * External sensor data registers, along with the gyroscope measurement * registers, accelerometer measurement registers, and temperature measurement * registers, are composed of two sets of registers: an internal register set * and a user-facing read register set. * * The data within the external sensors' internal register set is always * updated at the Sample Rate (or the reduced access rate) whenever the serial * interface is idle. This guarantees that a burst read of sensor registers * will read measurements from the same sampling instant. Note that if burst * reads are not used, the user is responsible for ensuring a set of single * byte reads correspond to a single sampling instant by checking the Data * Ready interrupt. * * Data is placed in these external sensor data registers according to * I2C_SLV0_CTRL, I2C_SLV1_CTRL, I2C_SLV2_CTRL, and I2C_SLV3_CTRL (Registers * 39, 42, 45, and 48). When more than zero bytes are read (I2C_SLVx_LEN > 0) * from an enabled slave (I2C_SLVx_EN = 1), the slave is read at the Sample * Rate (as defined in Register 25) or delayed rate (if specified in Register * 52 and 103). During each Sample cycle, slave reads are performed in order * of Slave number. If all slaves are enabled with more than zero bytes to be * read, the order will be Slave 0, followed by Slave 1, Slave 2, and Slave 3. * * Each enabled slave will have EXT_SENS_DATA registers associated with it by * number of bytes read (I2C_SLVx_LEN) in order of slave number, starting from * EXT_SENS_DATA_00. Note that this means enabling or disabling a slave may * change the higher numbered slaves' associated registers. Furthermore, if * fewer total bytes are being read from the external sensors as a result of * such a change, then the data remaining in the registers which no longer * have an associated slave device (i.e. high numbered registers) will remain * in these previously allocated registers unless reset. * * If the sum of the read lengths of all SLVx transactions exceed the number * of available EXT_SENS_DATA registers, the excess bytes will be dropped. * There are 24 EXT_SENS_DATA registers and hence the total read lengths * between all the slaves cannot be greater than 24 or some bytes will be * lost. * * Note: Slave 4's behavior is distinct from that of Slaves 0-3. For further * information regarding the characteristics of Slave 4, please refer to * Registers 49 to 53. * * EXAMPLE: Suppose that Slave 0 is enabled with 4 bytes to be read * (I2C_SLV0_EN = 1 and I2C_SLV0_LEN = 4) while Slave 1 is enabled with 2 * bytes to be read so that I2C_SLV1_EN = 1 and I2C_SLV1_LEN = 2. In such a * situation, EXT_SENS_DATA _00 through _03 will be associated with Slave 0, * while EXT_SENS_DATA _04 and 05 will be associated with Slave 1. If Slave 2 * is enabled as well, registers starting from EXT_SENS_DATA_06 will be * allocated to Slave 2. * * If Slave 2 is disabled while Slave 3 is enabled in this same situation, * then registers starting from EXT_SENS_DATA_06 will be allocated to Slave 3 * instead. * * REGISTER ALLOCATION FOR DYNAMIC DISABLE VS. NORMAL DISABLE: If a slave is * disabled at any time, the space initially allocated to the slave in the * EXT_SENS_DATA register, will remain associated with that slave. This is to * avoid dynamic adjustment of the register allocation. * * The allocation of the EXT_SENS_DATA registers is recomputed only when (1) * all slaves are disabled, or (2) the I2C_MST_RST bit is set (Register 106). * * This above is also true if one of the slaves gets NACKed and stops * functioning. * * @param position * Starting position (0-23) * @return Byte read from register */ int getExternalSensorByte(int position) { return (byte) I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_EXT_SENS_DATA_00 + position) & 0xff; } /** * Read word (2 bytes) from external sensor data registers. * * @param position * Starting position (0-21) * @return Word read from register see getExternalSensorByte() */ int getExternalSensorWord(int position) { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_EXT_SENS_DATA_00 + position, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1]; } /** * Read double word (4 bytes) from external sensor data registers. * * @param position * Starting position (0-20) * @return Double word read from registers see getExternalSensorByte() */ int getExternalSensorDWord(int position) { int readBuffer[] = new int[4]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_EXT_SENS_DATA_00 + position, 4, readBuffer); return (((byte) readBuffer[0]) << 24) | (((byte) readBuffer[1]) << 16) | (((byte) readBuffer[2]) << 8) | readBuffer[3] & 0xff; } // MOT_DETECT_STATUS register /** * Get full motion detection status register content (all bits). * * @return Motion detection status byte * @see MPU6050_RA_MOT_DETECT_STATUS */ int getMotionStatus() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_STATUS); } /** * Get X-axis negative motion detection interrupt status. * * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_XNEG_BIT */ boolean getXNegMotionDetected() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_XNEG_BIT); } /** * Get X-axis positive motion detection interrupt status. * * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_XPOS_BIT */ boolean getXPosMotionDetected() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_XPOS_BIT); } /** * Get Y-axis negative motion detection interrupt status. * * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_YNEG_BIT */ boolean getYNegMotionDetected() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_YNEG_BIT); } /** * Get Y-axis positive motion detection interrupt status. * * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_YPOS_BIT */ boolean getYPosMotionDetected() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_YPOS_BIT); } /** * Get Z-axis negative motion detection interrupt status. * * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZNEG_BIT */ boolean getZNegMotionDetected() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZNEG_BIT); } /** * Get Z-axis positive motion detection interrupt status. * * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZPOS_BIT */ boolean getZPosMotionDetected() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZPOS_BIT); } /** * Get zero motion detection interrupt status. * * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZRMOT_BIT */ boolean getZeroMotionDetected() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZRMOT_BIT); } // I2C_SLV*_DO register /** * Write byte to Data Output container for specified slave. This register * holds the output data written into Slave when Slave is set to write mode. * For further information regarding Slave control, please refer to Registers * 37 to 39 and immediately following. * * @param num * Slave number (0-3) * @param data * Byte to write * @see MPU6050_RA_I2C_SLV0_DO */ void setSlaveOutputByte(int num, int data) { if (num > 3) return; I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_I2C_SLV0_DO + num, data); } // I2C_MST_DELAY_CTRL register /** * Get external data shadow delay enabled status. This register is used to * specify the timing of external sensor data shadowing. When DELAY_ES_SHADOW * is set to 1, shadowing of external sensor data is delayed until all data * has been received. * * @return Current external data shadow delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT */ boolean getExternalShadowDelayEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_DELAY_CTRL, MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT); } /** * Set external data shadow delay enabled status. * * @param enabled * New external data shadow delay enabled status. see * getExternalShadowDelayEnabled() * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT */ void setExternalShadowDelayEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_DELAY_CTRL, MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT, enabled); } /** * Get slave delay enabled status. When a particular slave delay is enabled, * the rate of access for the that slave device is reduced. When a slave's * access rate is decreased relative to the Sample Rate, the slave is accessed * every: * * 1 / (1 + I2C_MST_DLY) Samples * * This base Sample Rate in turn is determined by SMPLRT_DIV (register * 25) * and DLPF_CFG (register 26). * * For further information regarding I2C_MST_DLY, please refer to register 52. * For further information regarding the Sample Rate, please refer to register * 25. * * @param num * Slave number (0-4) * @return Current slave delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT */ boolean getSlaveDelayEnabled(int num) { // MPU6050_DELAYCTRL_I2C_SLV4_DLY_EN_BIT is 4, SLV3 is 3, etc. if (num > 4) return false; return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_DELAY_CTRL, num); } /** * Set slave delay enabled status. * * @param num * Slave number (0-4) * @param enabled * New slave delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT */ void setSlaveDelayEnabled(int num, boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_I2C_MST_DELAY_CTRL, num, enabled); } // SIGNAL_PATH_RESET register /** * Reset gyroscope signal path. The reset will revert the signal path analog * to digital converters and filters to their power up configurations. * * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_GYRO_RESET_BIT */ void resetGyroscopePath() { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_GYRO_RESET_BIT, true); } /** * Reset accelerometer signal path. The reset will revert the signal path * analog to digital converters and filters to their power up configurations. * * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_ACCEL_RESET_BIT */ void resetAccelerometerPath() { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_ACCEL_RESET_BIT, true); } /** * Reset temperature sensor signal path. The reset will revert the signal path * analog to digital converters and filters to their power up configurations. * * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_TEMP_RESET_BIT */ void resetTemperaturePath() { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_TEMP_RESET_BIT, true); } // MOT_DETECT_CTRL register /** * Get accelerometer power-on delay. The accelerometer data path provides * samples to the sensor registers, Motion detection, Zero Motion detection, * and Free Fall detection modules. The signal path contains filters which * must be flushed on wake-up with new samples before the detection modules * begin operations. The default wake-up delay, of 4ms can be lengthened by up * to 3ms. This additional delay is specified in ACCEL_ON_DELAY in units of 1 * LSB = 1 ms. The user may select any value above zero unless instructed * otherwise by InvenSense. Please refer to Section 8 of the MPU-6000/MPU-6050 * Product Specification document for further information regarding the * detection modules. * * @return Current accelerometer power-on delay * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_ACCEL_ON_DELAY_BIT */ int getAccelerometerPowerOnDelay() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_ACCEL_ON_DELAY_BIT, MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH); } /** * Set accelerometer power-on delay. * * @param delay * New accelerometer power-on delay (0-3) see * getAccelerometerPowerOnDelay() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_ACCEL_ON_DELAY_BIT */ void setAccelerometerPowerOnDelay(int delay) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_ACCEL_ON_DELAY_BIT, MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH, delay); } int getFreefallDetectionCounterDecrement() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_FF_COUNT_BIT, MPU6050_DETECT_FF_COUNT_LENGTH); } /** * Set Free Fall detection counter decrement configuration. * * @param decrement * New decrement configuration value see * getFreefallDetectionCounterDecrement() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_FF_COUNT_BIT */ void setFreefallDetectionCounterDecrement(int decrement) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_FF_COUNT_BIT, MPU6050_DETECT_FF_COUNT_LENGTH, decrement); } int getMotionDetectionCounterDecrement() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_MOT_COUNT_BIT, MPU6050_DETECT_MOT_COUNT_LENGTH); } /** * Set Motion detection counter decrement configuration. * * @param decrement * New decrement configuration value see * getMotionDetectionCounterDecrement() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_MOT_COUNT_BIT */ void setMotionDetectionCounterDecrement(int decrement) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_MOT_COUNT_BIT, MPU6050_DETECT_MOT_COUNT_LENGTH, decrement); } // USER_CTRL register /** * Get FIFO enabled status. When this bit is set to 0, the FIFO buffer is * disabled. The FIFO buffer cannot be written to or read from while disabled. * The FIFO buffer's state does not change unless the MPU-60X0 is power * cycled. * * @return Current FIFO enabled status * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_EN_BIT */ boolean getFIFOEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_EN_BIT); } /** * Set FIFO enabled status. * * @param enabled * New FIFO enabled status see getFIFOEnabled() * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_EN_BIT */ void setFIFOEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_EN_BIT, enabled); } /** * Get I2C Master Mode enabled status. When this mode is enabled, the MPU-60X0 * acts as the I2C Master to the external sensor slave devices on the * auxiliary I2C bus. When this bit is cleared to 0, the auxiliary I2C bus * lines (AUX_DA and AUX_CL) are logically driven by the primary I2C bus (SDA * and SCL). This is a precondition to enabling Bypass Mode. For further * information regarding Bypass Mode, please refer to Register 55. * * @return Current I2C Master Mode enabled status * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_EN_BIT */ boolean getI2CMasterModeEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_EN_BIT); } /** * Set I2C Master Mode enabled status. * * @param enabled * New I2C Master Mode enabled status see getI2CMasterModeEnabled() * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_EN_BIT */ void setI2CMasterModeEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_EN_BIT, enabled); } /** * Switch from I2C to SPI mode (MPU-6000 only) If this is set, the primary SPI * interface will be enabled in place of the disabled primary I2C interface. */ void switchSPIEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_IF_DIS_BIT, enabled); } /** * Reset the FIFO. This bit resets the FIFO buffer when set to 1 while FIFO_EN * equals 0. This bit automatically clears to 0 after the reset has been * triggered. * * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_RESET_BIT */ void resetFIFO() { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_RESET_BIT, true); } /** * Reset the I2C Master. This bit resets the I2C Master when set to 1 while * I2C_MST_EN equals 0. This bit automatically clears to 0 after the reset has * been triggered. * * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_RESET_BIT */ void resetI2CMaster() { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_RESET_BIT, true); } /** * Reset all sensor registers and signal paths. When set to 1, this bit resets * the signal paths for all sensors (gyroscopes, accelerometers, and * temperature sensor). This operation will also clear the sensor registers. * This bit automatically clears to 0 after the reset has been triggered. * * When resetting only the signal path (and not the sensor registers), please * use Register 104, SIGNAL_PATH_RESET. * * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_SIG_COND_RESET_BIT */ void resetSensors() { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_SIG_COND_RESET_BIT, true); } // PWR_MGMT_1 register /** * Trigger a full device reset. A small delay of ~50ms may be desirable after * triggering a reset. * * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_DEVICE_RESET_BIT */ void reset() { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_DEVICE_RESET_BIT, true); } /** * Get sleep mode status. Setting the SLEEP bit in the register puts the * device into very low power sleep mode. In this mode, only the serial * interface and internal registers remain active, allowing for a very low * standby current. Clearing this bit puts the device back into normal mode. * To save power, the individual standby selections for each of the gyros * should be used if any gyro axis is not used by the application. * * @return Current sleep mode enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_SLEEP_BIT */ boolean getSleepEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_SLEEP_BIT); } /** * Set sleep mode status. * * @param enabled * New sleep mode enabled status see getSleepEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_SLEEP_BIT */ void setSleepEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_SLEEP_BIT, enabled); } /** * Get wake cycle enabled status. When this bit is set to 1 and SLEEP is * disabled, the MPU-60X0 will cycle between sleep mode and waking up to take * a single sample of data from active sensors at a rate determined by * LP_WAKE_CTRL (register 108). * * @return Current sleep mode enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CYCLE_BIT */ boolean getWakeCycleEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CYCLE_BIT); } /** * Set wake cycle enabled status. * * @param enabled * New sleep mode enabled status see getWakeCycleEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CYCLE_BIT */ void setWakeCycleEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CYCLE_BIT, enabled); } /** * Get temperature sensor enabled status. Control the usage of the internal * temperature sensor. * * Note: this register stores the *disabled* value, but for consistency with * the rest of the code, the function is named and used with standard * true/false values to indicate whether the sensor is enabled or disabled, * respectively. * * @return Current temperature sensor enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_TEMP_DIS_BIT */ boolean getTempSensorEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_TEMP_DIS_BIT); // 1 is actually disabled here } /** * Set temperature sensor enabled status. Note: this register stores the * *disabled* value, but for consistency with the rest of the code, the * function is named and used with standard true/false values to indicate * whether the sensor is enabled or disabled, respectively. * * @param enabled * New temperature sensor enabled status see getTempSensorEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_TEMP_DIS_BIT */ void setTempSensorEnabled(boolean enabled) { // 1 is actually disabled here I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_TEMP_DIS_BIT, !enabled); } /** * Get clock source setting. * * @return Current clock source setting * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CLKSEL_BIT * @see MPU6050_PWR1_CLKSEL_LENGTH */ int getClockSource() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CLKSEL_BIT, MPU6050_PWR1_CLKSEL_LENGTH); } void setClockSource(int source) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CLKSEL_BIT, MPU6050_PWR1_CLKSEL_LENGTH, source); } // PWR_MGMT_2 register int getWakeFrequency() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_LP_WAKE_CTRL_BIT, MPU6050_PWR2_LP_WAKE_CTRL_LENGTH); } /** * Set wake frequency in Accel-Only Low Power Mode. * * @param frequency * New wake frequency * @see MPU6050_RA_PWR_MGMT_2 */ void setWakeFrequency(int frequency) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_LP_WAKE_CTRL_BIT, MPU6050_PWR2_LP_WAKE_CTRL_LENGTH, frequency); } /** * Get X-axis accelerometer standby enabled status. If enabled, the X-axis * will not gather or report data (or use power). * * @return Current X-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XA_BIT */ boolean getStandbyXAccelEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XA_BIT); } /** * Set X-axis accelerometer standby enabled status. * * @param New * X-axis standby enabled status see getStandbyXAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XA_BIT */ void setStandbyXAccelEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XA_BIT, enabled); } /** * Get Y-axis accelerometer standby enabled status. If enabled, the Y-axis * will not gather or report data (or use power). * * @return Current Y-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YA_BIT */ boolean getStandbyYAccelEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YA_BIT); } /** * Set Y-axis accelerometer standby enabled status. * * @param New * Y-axis standby enabled status see getStandbyYAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YA_BIT */ void setStandbyYAccelEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YA_BIT, enabled); } /** * Get Z-axis accelerometer standby enabled status. If enabled, the Z-axis * will not gather or report data (or use power). * * @return Current Z-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZA_BIT */ boolean getStandbyZAccelEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZA_BIT); } /** * Set Z-axis accelerometer standby enabled status. * * @param New * Z-axis standby enabled status see getStandbyZAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZA_BIT */ void setStandbyZAccelEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZA_BIT, enabled); } /** * Get X-axis gyroscope standby enabled status. If enabled, the X-axis will * not gather or report data (or use power). * * @return Current X-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XG_BIT */ boolean getStandbyXGyroEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XG_BIT); } /** * Set X-axis gyroscope standby enabled status. * * @param New * X-axis standby enabled status see getStandbyXGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XG_BIT */ void setStandbyXGyroEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XG_BIT, enabled); } /** * Get Y-axis gyroscope standby enabled status. If enabled, the Y-axis will * not gather or report data (or use power). * * @return Current Y-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YG_BIT */ boolean getStandbyYGyroEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YG_BIT); } /** * Set Y-axis gyroscope standby enabled status. * * @param New * Y-axis standby enabled status see getStandbyYGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YG_BIT */ void setStandbyYGyroEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YG_BIT, enabled); } /** * Get Z-axis gyroscope standby enabled status. If enabled, the Z-axis will * not gather or report data (or use power). * * @return Current Z-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZG_BIT */ boolean getStandbyZGyroEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZG_BIT); } /** * Set Z-axis gyroscope standby enabled status. * * @param New * Z-axis standby enabled status see getStandbyZGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZG_BIT */ void setStandbyZGyroEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZG_BIT, enabled); } // FIFO_COUNT* registers /** * Get current FIFO buffer size. This value indicates the number of bytes * stored in the FIFO buffer. This number is in turn the number of bytes that * can be read from the FIFO buffer and it is directly proportional to the * number of samples available given the set of sensor data bound to be stored * in the FIFO (register 35 and 36). * * @return Current FIFO buffer size */ int getFIFOCount() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_FIFO_COUNTH, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } // FIFO_R_W register /** * Get byte from FIFO buffer. This register is used to read and write data * from the FIFO buffer. Data is written to the FIFO in order of register * number (from lowest to highest). If all the FIFO enable flags (see below) * are enabled and all External Sensor Data registers (Registers 73 to 96) are * associated with a Slave device, the contents of registers 59 through 96 * will be written in order at the Sample Rate. * * The contents of the sensor data registers (Registers 59 to 96) are written * into the FIFO buffer when their corresponding FIFO enable flags are set to * 1 in FIFO_EN (Register 35). An additional flag for the sensor data * registers associated with I2C Slave 3 can be found in I2C_MST_CTRL * (Register 36). * * If the FIFO buffer has overflowed, the status bit FIFO_OFLOW_INT is * automatically set to 1. This bit is located in INT_STATUS (Register 58). * When the FIFO buffer has overflowed, the oldest data will be lost and new * data will be written to the FIFO. * * If the FIFO buffer is empty, reading this register will return the last * byte that was previously read from the FIFO until new data is available. * The user should check FIFO_COUNT to ensure that the FIFO buffer is not read * when empty. * * @return Byte from FIFO buffer */ int getFIFOByte() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_FIFO_R_W); } void getFIFOBytes(int[] data, int length) { if (length > 0) { I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_FIFO_R_W, length, data); } else { data = new int[0]; } } /** * Write byte to FIFO buffer. * * see getFIFOByte() * * @see MPU6050_RA_FIFO_R_W */ void setFIFOByte(int data) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_FIFO_R_W, data); } // WHO_AM_I register /** * Get Device ID. This register is used to verify the identity of the device * (0b110100, 0x34). * * @return Device ID (6 bits only! should be 0x34) * @see MPU6050_RA_WHO_AM_I * @see MPU6050_WHO_AM_I_BIT * @see MPU6050_WHO_AM_I_LENGTH */ int getDeviceID() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_WHO_AM_I, MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH); } /** * Set Device ID. Write a new ID into the WHO_AM_I register (no idea why this * should ever be necessary though). * * @param id * New device ID to set. see getDeviceID() * @see MPU6050_RA_WHO_AM_I * @see MPU6050_WHO_AM_I_BIT * @see MPU6050_WHO_AM_I_LENGTH */ void setDeviceID(int id) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_WHO_AM_I, MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH, id); } // XG_OFFS_TC register boolean getOTPBankValid() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OTP_BNK_VLD_BIT); } void setOTPBankValid(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OTP_BNK_VLD_BIT, enabled); } int getXGyroOffsetTC() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH); } void setXGyroOffsetTC(int offset) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // YG_OFFS_TC register int getYGyroOffsetTC() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_YG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH); } void setYGyroOffsetTC(int offset) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_YG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // ZG_OFFS_TC register int getZGyroOffsetTC() { return I2CdevReadBits(Integer.decode(deviceAddress), MPU6050_RA_ZG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH); } void setZGyroOffsetTC(int offset) { I2CdevWriteBits(Integer.decode(deviceAddress), MPU6050_RA_ZG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // X_FINE_GAIN register int getXFineGain() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_X_FINE_GAIN); } void setXFineGain(int gain) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_X_FINE_GAIN, gain); } // Y_FINE_GAIN register int getYFineGain() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_Y_FINE_GAIN); } void setYFineGain(int gain) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_Y_FINE_GAIN, gain); } // Z_FINE_GAIN register int getZFineGain() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_Z_FINE_GAIN); } void setZFineGain(int gain) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_Z_FINE_GAIN, gain); } // XA_OFFS_* registers int getXAccelOffset() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_XA_OFFS_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } void setXAccelOffset(int offset) { I2CdevWriteWord(Integer.decode(deviceAddress), MPU6050_RA_XA_OFFS_H, offset); } // YA_OFFS_* register int getYAccelOffset() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_YA_OFFS_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } void setYAccelOffset(int offset) { I2CdevWriteWord(Integer.decode(deviceAddress), MPU6050_RA_YA_OFFS_H, offset); } // ZA_OFFS_* register int getZAccelOffset() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_ZA_OFFS_H, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } void setZAccelOffset(int offset) { I2CdevWriteWord(Integer.decode(deviceAddress), MPU6050_RA_ZA_OFFS_H, offset); } // XG_OFFS_USR* registers int getXGyroOffset() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_XG_OFFS_USRH, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } void setXGyroOffset(int offset) { I2CdevWriteWord(Integer.decode(deviceAddress), MPU6050_RA_XG_OFFS_USRH, offset); } // YG_OFFS_USR* register int getYGyroOffset() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_YG_OFFS_USRH, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } void setYGyroOffset(int offset) { I2CdevWriteWord(Integer.decode(deviceAddress), MPU6050_RA_YG_OFFS_USRH, offset); } // ZG_OFFS_USR* register int getZGyroOffset() { int readBuffer[] = new int[2]; I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_ZG_OFFS_USRH, 2, readBuffer); return (byte) readBuffer[0] << 8 | readBuffer[1] & 0xff; } void setZGyroOffset(int offset) { I2CdevWriteWord(Integer.decode(deviceAddress), MPU6050_RA_ZG_OFFS_USRH, offset); } // INT_ENABLE register (DMP functions) boolean getIntPLLReadyEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_PLL_RDY_INT_BIT); } void setIntPLLReadyEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_PLL_RDY_INT_BIT, enabled); } boolean getIntDMPEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DMP_INT_BIT); } void setIntDMPEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DMP_INT_BIT, enabled); } // DMP_INT_STATUS boolean getDMPInt5Status() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_5_BIT); } boolean getDMPInt4Status() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_4_BIT); } boolean getDMPInt3Status() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_3_BIT); } boolean getDMPInt2Status() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_2_BIT); } boolean getDMPInt1Status() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_1_BIT); } boolean getDMPInt0Status() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_0_BIT); } // INT_STATUS register (DMP functions) boolean getIntPLLReadyStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_PLL_RDY_INT_BIT); } boolean getIntDMPStatus() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_DMP_INT_BIT); } // USER_CTRL register (DMP functions) boolean getDMPEnabled() { return I2CdevReadBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_EN_BIT); } void setDMPEnabled(boolean enabled) { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_EN_BIT, enabled); } void resetDMP() { I2CdevWriteBit(Integer.decode(deviceAddress), MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_RESET_BIT, true); } // BANK_SEL register void setMemoryBank(int bank, boolean prefetchEnabled, boolean userBank) { bank = bank & 0x1F; if (userBank) bank |= 0x20; if (prefetchEnabled) bank |= 0x40; I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_BANK_SEL, bank); } void setMemoryBank(int bank) { setMemoryBank(bank, false, false); } // MEM_START_ADDR register void setMemoryStartAddress(int address) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_MEM_START_ADDR, address); } // MEM_R_W register int readMemoryByte() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_MEM_R_W); } void writeMemoryByte(int data) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_MEM_R_W, data); } void readMemoryBlock(int[] data, int dataSize, int bank, int address) { setMemoryBank(bank); setMemoryStartAddress(address); int chunkSize; for (int i = 0; i < dataSize;) { // determine correct chunk size according to bank position and data // size chunkSize = MPU6050_DMP_MEMORY_CHUNK_SIZE; // make sure we don't go past the data size if (i + chunkSize > dataSize) chunkSize = dataSize - i; // make sure this chunk doesn't go past the bank boundary (256 // bytes) if (chunkSize > 256 - address) chunkSize = 256 - address; // read the chunk of data as specified I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_MEM_R_W, chunkSize, data); // increase byte index by [chunkSize] i += chunkSize; // int automatically wraps to 0 at 256 address += chunkSize; // if we aren't done, update bank (if necessary) and address if (i < dataSize) { if (address == 0) bank++; setMemoryBank(bank); setMemoryStartAddress(address); } } } boolean writeMemoryBlock(int[] data, int dataSize, int bank, int address, boolean verify) { setMemoryBank(bank); setMemoryStartAddress(address); int chunkSize; int[] verifyBuffer; int[] progBuffer; int i; int j; if (verify) { verifyBuffer = new int[MPU6050_DMP_MEMORY_CHUNK_SIZE]; } else { verifyBuffer = new int[0]; } for (i = 0; i < dataSize;) { // determine correct chunk size according to bank position and data // size chunkSize = MPU6050_DMP_MEMORY_CHUNK_SIZE; // make sure we don't go past the data size if (i + chunkSize > dataSize) { log.info("i + chunkSize > dataSize: i={}, chunkSize={}, dataSize={}", i, chunkSize, dataSize); chunkSize = dataSize - i; log.info("New chunkSize={}", chunkSize); } // make sure this chunk doesn't go past the bank boundary (256 // bytes) if (chunkSize > (256 - address)) { log.info("chunkSize > 256 - address. chunkSize={}, address ={}", chunkSize, address); chunkSize = 256 - address; log.info("New chunkSize={}", chunkSize); } // write the chunk of data as specified // progBuffer = (int *)data + i; progBuffer = new int[chunkSize]; for (j = 0; j < chunkSize; j++) { progBuffer[j] = data[i + j]; } log.info("writeMemoryBlock: Block start: {}, ChunkSize {}", i, chunkSize); I2CdevWriteBytes(Integer.decode(deviceAddress), MPU6050_RA_MEM_R_W, chunkSize, progBuffer); // verify data if needed if (verify && (verifyBuffer.length > 0)) { setMemoryBank(bank); setMemoryStartAddress(address); I2CdevReadBytes(Integer.decode(deviceAddress), MPU6050_RA_MEM_R_W, chunkSize, verifyBuffer); if (memcmp(progBuffer, verifyBuffer, chunkSize) != 0) { /* * Serial.print("Block write verification error, bank "); * Serial.print(bank, DEC); Serial.print(", address "); * Serial.print(address, DEC); Serial.print("!\nExpected:"); for (j = * 0; j < chunkSize; j++) { Serial.print(" 0x"); if (progBuffer[j] < * 16) Serial.print("0"); Serial.print(progBuffer[j], HEX); } * Serial.print("\nReceived:"); for (int j = 0; j < chunkSize; j++) { * Serial.print(" 0x"); if (verifyBuffer[i + j] < 16) * Serial.print("0"); Serial.print(verifyBuffer[i + j], HEX); } * Serial.print("\n"); */ // * free(verifyBuffer); return false; // uh oh. } } // increase byte index by [chunkSize] i += chunkSize; // int automatically wraps to 0 at 256 address = (address + chunkSize) & 0xff; // if we aren't done, update bank (if necessary) and address if (i < dataSize) { if (address == 0) bank++; setMemoryBank(bank); setMemoryStartAddress(address); } } // * if (verify) free(verifyBuffer); return true; } boolean writeProgMemoryBlock(int[] data, int dataSize, int bank, int address, boolean verify) { return writeMemoryBlock(data, dataSize, bank, address, verify); } boolean writeProgMemoryBlock(int[] data, int dataSize) { return writeMemoryBlock(data, dataSize, 0, 0, true); } boolean writeDMPConfigurationSet(int[] data, int dataSize) { int[] progBuffer; int special; boolean success = false; int i; // config set data is a long string of blocks with the following // structure: // [bank] [offset] [length] [byte[0], byte[1], ..., byte[length]] int bank, offset, length; for (i = 0; i < dataSize;) { bank = data[i++]; offset = data[i++]; length = data[i++]; // write data or perform special action if (length > 0) { // regular block of data to write /* * Serial.print("Writing config block to bank "); Serial.print(bank); * Serial.print(", offset "); Serial.print(offset); Serial.print( * ", length="); Serial.println(length); */ // progBuffer = (int *)data + i; progBuffer = new int[length]; for (int k = 0; k < length; k++) { progBuffer[k] = data[i + k]; } success = writeMemoryBlock(progBuffer, length, bank, offset, true); i += length; } else { // special instruction // NOTE: this kind of behavior (what and when to do certain // things) // is totally undocumented. This code is in here based on // observed // behavior only, and exactly why (or even whether) it has to be // here // is anybody's guess for now. special = data[i++]; /* * Serial.print("Special command code "); Serial.print(special, HEX); * Serial.println(" found..."); */ if (special == 0x01) { // enable DMP-related interrupts // setIntZeroMotionEnabled(true); // setIntFIFOBufferOverflowEnabled(true); // setIntDMPEnabled(true); I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_INT_ENABLE, 0x32); // single // operation success = true; } else { // unknown special command success = false; } } if (!success) { return false; // uh oh } } return true; } boolean writeProgDMPConfigurationSet(int[] data, int dataSize) { return writeDMPConfigurationSet(data, dataSize); } // DMP_CFG_1 register int getDMPConfig1() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_DMP_CFG_1); } void setDMPConfig1(int config) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_DMP_CFG_1, config); } // DMP_CFG_2 register int getDMPConfig2() { return I2CdevReadByte(Integer.decode(deviceAddress), MPU6050_RA_DMP_CFG_2); } void setDMPConfig2(int config) { I2CdevWriteByte(Integer.decode(deviceAddress), MPU6050_RA_DMP_CFG_2, config); } // * Compare the content of two buffers // Returns 0 if the two buffers have the same content otherwise 1 int memcmp(int[] buffer1, int[] buffer2, int length) { int result = 0; for (int i = 0; i < length; i++) { if (buffer1[i] != buffer2[i]) { result = 1; } } return result; } int pgm_read_byte(int a) { return 0; } /* * Start of I2CDEV section. Most of this code could be moved to and * implemented in the I2CControl interface. */ /** * Read a single bit from an 8-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * Register regAddr to read from * @param bitNum * Bit position to read (0-7) * @return Status of read operation (true = success) */ boolean I2CdevReadBit(int devAddr, int regAddr, int bitNum) { int bitmask = 1; int byteValue = I2CdevReadByte(devAddr, regAddr); int bitValue = byteValue & (bitmask << bitNum); return (bitValue != 0); } /** * Read multiple bits from an 8-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * Register regAddr to read from * @param bitStart * First bit position to read (0-7) * @param length * Number of bits to read (not more than 8) * @return right-aligned value (i.e. '101' read from any bitStart position * will equal 0x05) */ int I2CdevReadBits(int devAddr, int regAddr, int bitStart, int length) { // 01101001 read byte // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 010 masked // -> 010 shifted int b = I2CdevReadByte(devAddr, regAddr); if (b != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); b &= mask; b >>= (bitStart - length + 1); } return b; } /** * Read single byte from an 8-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * Register regAddr to read from * @return content of the read Register */ int I2CdevReadByte(int devAddr, int regAddr) { int readBuffer[] = new int[1]; I2CdevReadBytes(devAddr, regAddr, 1, readBuffer); return readBuffer[0] & 0xff; } /** * Read single word from a 16-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * Register regAddr to read from * @param data * Container for word value read from device * @return Status of read operation (true = success) */ int I2CdevReadWord(int devAddr, int regAddr, int data) { int[] readbuffer = { data }; int status = I2CdevReadWords(devAddr, regAddr, 1, readbuffer); data = readbuffer[0]; return status; } /** * Read multiple words from a 16-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * First register regAddr to read from * @param length * Number of words to read * @param data * Buffer to store read data in * @return Number of words read (-1 indicates failure) */ int I2CdevReadWords(int devAddr, int regAddr, int length, int[] data) { byte bytebuffer[] = new byte[length * 2]; controller.i2cRead(this, Integer.parseInt(deviceBus), devAddr, bytebuffer, bytebuffer.length); for (int i = 0; i < bytebuffer.length; i++) { data[i] = bytebuffer[i * 2] << 8 + bytebuffer[i * 2 + 1] & 0xff; } return length; } /** * Read multiple bytes from an 8-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * First register regAddr to read from * @param length * Number of bytes to read * @param data * Buffer to store read data in * @return Number of bytes read (-1 indicates failure) */ // TODO Return the correct length int I2CdevReadBytes(int devAddr, int regAddr, int length, int[] data) { byte[] writebuffer = new byte[] { (byte) (regAddr & 0xff) }; byte[] readbuffer = new byte[length]; controller.i2cWrite(this, Integer.parseInt(deviceBus), devAddr, writebuffer, writebuffer.length); controller.i2cRead(this, Integer.parseInt(deviceBus), devAddr, readbuffer, readbuffer.length); for (int i = 0; i < length; i++) { data[i] = readbuffer[i] & 0xff; } return length; } /** * Write multiple bits in an 8-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * Register regAddr to write to * @param bitStart * First bit position to write (0-7) * @param length * Number of bits to write (not more than 8) * @param data * Right-aligned value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBits(int devAddr, int regAddr, int bitStart, int length, int data) { // 010 value to write // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 00011100 mask byte // 10101111 original value (sample) // 10100011 original & ~mask // 10101011 masked | value int b = I2CdevReadByte(devAddr, regAddr); if (b != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct // position data &= mask; // zero all non-important bits in data b &= ~(mask); // zero all important bits in existing byte b |= data; // combine data with existing byte return I2CdevWriteByte(devAddr, regAddr, b); } else { return false; } } /** * Write multiple bits in a 16-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * Register regAddr to write to * @param bitStart * First bit position to write (0-15) * @param length * Number of bits to write (not more than 16) * @param data * Right-aligned value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBitsW(int devAddr, int regAddr, int bitStart, int length, int data) { // 010 value to write // fedcba9876543210 bit numbers // xxx args: bitStart=12, length=3 // 0001110000000000 mask word // 1010111110010110 original value (sample) // 1010001110010110 original & ~mask // 1010101110010110 masked | value int w = 0; if (I2CdevReadWord(devAddr, regAddr, w) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct // position data &= mask; // zero all non-important bits in data w &= ~(mask); // zero all important bits in existing word w |= data; // combine data with existing word return I2CdevWriteWord(devAddr, regAddr, w); } else { return false; } } /** * write a single bit in an 8-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * Register regAddr to write to * @param bitNum * Bit position to write (0-7) * @param value * New bit value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBit(int devAddr, int regAddr, int bitNum, boolean data) { int b = 0; int newbyte = 0; int bitmask = 1; b = I2CdevReadByte(devAddr, regAddr); // Set the specified bit to 1 if (data) { newbyte = b | (bitmask << bitNum); } // Set the specified bit to 0 else { newbyte = (b & ~(bitmask << bitNum)); } return I2CdevWriteByte(devAddr, regAddr, newbyte); } boolean I2CdevWriteByte(int devAddr, int regAddr, int data) { int[] writebuffer = { data }; return I2CdevWriteBytes(devAddr, regAddr, 1, writebuffer); } boolean I2CdevWriteWord(int devAddr, int regAddr, int data) { int[] writebuffer = { data }; return I2CdevWriteWords(devAddr, regAddr, 1, writebuffer); } /** * Write multiple bytes to an 8-bit device register. * * @param devAddr * I2C slave device address * @param regAddr * First register address to write to * @param length * Number of bytes to write * @param data * Buffer to copy new data from * @return Status of operation (true = success) */ boolean I2CdevWriteBytes(int devAddr, int regAddr, int length, int[] data) { byte[] writebuffer = new byte[length + 1]; writebuffer[0] = (byte) (regAddr & 0xff); for (int i = 0; i < length; i++) { writebuffer[i + 1] = (byte) (data[i] & 0xff); } controller.i2cWrite(this, Integer.parseInt(deviceBus), devAddr, writebuffer, writebuffer.length); return true; } // TODO finish development boolean I2CdevWriteWords(int devAddr, int regAddr, int length, int[] data) { byte[] writebuffer = new byte[length * 2 + 1]; writebuffer[0] = (byte) (regAddr & 0xff); for (int i = 0; i < length; i++) { writebuffer[i * 2 + 1] = (byte) (data[i] << 8); // MSByte writebuffer[i * 2 + 2] = (byte) (data[i] & 0xff); // LSByte } controller.i2cWrite(this, Integer.parseInt(deviceBus), devAddr, writebuffer, writebuffer.length); return true; } /* * End of I2CDEV section. */ @Override public Orientation publishOrientation(Orientation data) { return data; } @Override public void startOrientationTracking() { if (publisher == null) { publisher = new OrientationPublisher(); publisher.start(); } } @Override public void stopOrientationTracking() { if (publisher != null) { publisher.isRunning = false; publisher = null; } } @Override public void attach(OrientationListener listener) { listeners.add(listener); } @Override public void detach(OrientationListener listener) { listeners.remove(listener); } public void attach(I2CController controller) { attachI2CController(controller, deviceBus, deviceAddress); } public void attach(I2CController controller, String deviceBus, String deviceAddress) { attachI2CController(controller, deviceBus, deviceAddress); } public void attachI2CController(I2CController controller, String deviceBus, String deviceAddress) { if (controller.equals(this.controller)) { // already attached return; } if (deviceBus != null) { this.deviceBus = deviceBus; } if (deviceAddress != null) { this.deviceAddress = deviceAddress; } this.controllerName = controller.getName(); this.controller = controller; controller.attachI2CControl(this); log.info("Attached {} device on bus: {} address {}", controllerName, deviceBus, deviceAddress); } // This section contains all the new detach logic // TODO: This default code could be in Attachable @Override public void detach(String service) { detach((Attachable) Runtime.getService(service)); } @Override public void detach(Attachable service) { if (I2CController.class.isAssignableFrom(service.getClass())) { detachI2CController((I2CController) service); return; } } @Override public void detachI2CController(I2CController controller) { if (!isAttached(controller)) return; controller.detachI2CControl(this); broadcastState(); } // This section contains all the methods used to query / show all attached // methods /** * Returns all the currently attached services */ @Override public Set<String> getAttached() { HashSet<String> ret = new HashSet<String>(); if (controller != null) { ret.add(controller.getName()); } return ret; } @Override public String getDeviceBus() { return this.deviceBus; } @Override public String getDeviceAddress() { return this.deviceAddress; } @Override public boolean isAttached(Attachable instance) { if (instance.getName().equals(controllerName)) { return true; } return false; } public static void main(String[] args) { LoggingFactory.init("info"); try { /* * Mpu6050 mpu6050 = (Mpu6050) Runtime.start("mpu6050", "Mpu6050"); * Runtime.start("gui", "SwingGui"); */ /* * Arduino arduino = (Arduino) Runtime.start("Arduino","Arduino"); * arduino.connect("COM4"); mpu6050.setController(arduino); */ /* * RasPi raspi = (RasPi) Runtime.start("RasPi","RasPi"); * mpu6050.setController(raspi); mpu6050.dmpInitialize(); */ int[] buffer = new int[] { (int) 0xff, (int) 0xd0 }; int a = (byte) buffer[0] << 8 | buffer[1] & 0xff; log.info("0xffd0 should be -48 is = {}", a); } catch (Exception e) { Logging.logError(e); } } @Override public void attachI2CController(I2CController controller) { // TODO Auto-generated method stub } }
package polyglot.ext.jl5.types; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import polyglot.ast.ClassLit; import polyglot.ast.Expr; import polyglot.ast.NullLit; import polyglot.ast.Term; import polyglot.ext.jl5.JL5Options; import polyglot.ext.jl5.ast.AnnotationElem; import polyglot.ext.jl5.ast.ElementValueArrayInit; import polyglot.ext.jl5.ast.EnumConstant; import polyglot.ext.jl5.types.inference.InferenceSolver; import polyglot.ext.jl5.types.inference.InferenceSolver_c; import polyglot.ext.jl5.types.inference.LubType; import polyglot.ext.jl5.types.inference.LubType_c; import polyglot.ext.jl5.types.reflect.JL5ClassFileLazyClassInitializer; import polyglot.ext.param.types.PClass; import polyglot.ext.param.types.ParamTypeSystem_c; import polyglot.ext.param.types.Subst; import polyglot.frontend.Source; import polyglot.main.Report; import polyglot.types.ArrayType; import polyglot.types.ClassType; import polyglot.types.ConstructorInstance; import polyglot.types.Context; import polyglot.types.FieldInstance; import polyglot.types.Flags; import polyglot.types.ImportTable; import polyglot.types.LazyClassInitializer; import polyglot.types.LocalInstance; import polyglot.types.MemberInstance; import polyglot.types.MethodInstance; import polyglot.types.NoMemberException; import polyglot.types.NullType; import polyglot.types.Package; import polyglot.types.ParsedClassType; import polyglot.types.PrimitiveType; import polyglot.types.ProcedureInstance; import polyglot.types.ReferenceType; import polyglot.types.SemanticException; import polyglot.types.Type; import polyglot.types.reflect.ClassFile; import polyglot.types.reflect.ClassFileLazyClassInitializer; import polyglot.util.InternalCompilerError; import polyglot.util.Position; import polyglot.util.UniqueID; public class JL5TypeSystem_c extends ParamTypeSystem_c<TypeVariable, ReferenceType> implements JL5TypeSystem { protected ClassType ENUM_; protected ClassType ANNOTATION_; protected ClassType OVERRIDE_ANNOTATION_; protected ClassType TARGET_ANNOTATION_; protected ClassType RETENTION_ANNOTATION_; protected ClassType ELEMENT_TYPE_; // this is for extended for protected ClassType ITERABLE_; protected ClassType ITERATOR_; @Override public ClassType Enum() { if (ENUM_ != null) { return ENUM_; } else { return ENUM_ = load("java.lang.Enum"); } } @Override public ClassType Annotation() { if (ANNOTATION_ != null) { return ANNOTATION_; } else { return ANNOTATION_ = load("java.lang.annotation.Annotation"); } } @Override public ClassType OverrideAnnotation() { if (OVERRIDE_ANNOTATION_ != null) { return OVERRIDE_ANNOTATION_; } else { return OVERRIDE_ANNOTATION_ = load("java.lang.Override"); } } @Override public ClassType TargetAnnotation() { if (TARGET_ANNOTATION_ != null) { return TARGET_ANNOTATION_; } else { return TARGET_ANNOTATION_ = load("java.lang.annotation.Target"); } } @Override public ClassType RetentionAnnotation() { if (RETENTION_ANNOTATION_ != null) { return RETENTION_ANNOTATION_; } else { return RETENTION_ANNOTATION_ = load("java.lang.annotation.Retention"); } } @Override public ClassType AnnotationElementType() { if (ELEMENT_TYPE_ != null) { return ELEMENT_TYPE_; } else { return ELEMENT_TYPE_ = load("java.lang.annotation.ElementType"); } } @Override public ClassType Iterable() { if (ITERABLE_ != null) { return ITERABLE_; } else { return ITERABLE_ = load("java.lang.Iterable"); } } @Override public ClassType Iterator() { if (ITERATOR_ != null) { return ITERATOR_; } else { return ITERATOR_ = load("java.util.Iterator"); } } @Override public LazyClassInitializer defaultClassInitializer() { return new JL5SchedulerClassInitializer(this); } @Override public boolean accessibleFromPackage(Flags flags, Package pkg1, Package pkg2) { return super.accessibleFromPackage(flags, pkg1, pkg2); } @Override public ClassType wrapperClassOfPrimitive(PrimitiveType t) { try { return (ClassType) this.typeForName(t.wrapperTypeString(this)); } catch (SemanticException e) { throw new InternalCompilerError("Couldn't find primitive wrapper " + t.wrapperTypeString(this), e); } } @Override public PrimitiveType primitiveTypeOfWrapper(Type l) { try { if (l.equals(this.typeForName("java.lang.Boolean"))) return this.Boolean(); if (l.equals(this.typeForName("java.lang.Character"))) return this.Char(); if (l.equals(this.typeForName("java.lang.Byte"))) return this.Byte(); if (l.equals(this.typeForName("java.lang.Short"))) return this.Short(); if (l.equals(this.typeForName("java.lang.Integer"))) return this.Int(); if (l.equals(this.typeForName("java.lang.Long"))) return this.Long(); if (l.equals(this.typeForName("java.lang.Float"))) return this.Float(); if (l.equals(this.typeForName("java.lang.Double"))) return this.Double(); if (l.equals(this.typeForName("java.lang.Void"))) return this.Void(); } catch (SemanticException e) { throw new InternalCompilerError("Couldn't find wrapper class"); } return null; } @Override public boolean isPrimitiveWrapper(Type l) { if (primitiveTypeOfWrapper(l) != null) { return true; } else { return false; } } protected final Flags TOP_LEVEL_CLASS_FLAGS = JL5Flags.setAnnotation(JL5Flags.setEnum(super.TOP_LEVEL_CLASS_FLAGS)); protected final Flags MEMBER_CLASS_FLAGS = JL5Flags.setAnnotation(JL5Flags.setEnum(super.MEMBER_CLASS_FLAGS)); @Override public void checkTopLevelClassFlags(Flags f) throws SemanticException { if (!f.clear(TOP_LEVEL_CLASS_FLAGS).equals(Flags.NONE)) { throw new SemanticException("Cannot declare a top-level class with flag(s) " + f.clear(TOP_LEVEL_CLASS_FLAGS) + "."); } if (f.isFinal() && f.isInterface()) { throw new SemanticException("Cannot declare a final interface."); } checkAccessFlags(f); } @Override public void checkMemberClassFlags(Flags f) throws SemanticException { if (!f.clear(MEMBER_CLASS_FLAGS).equals(Flags.NONE)) { throw new SemanticException("Cannot declare a member class with flag(s) " + f.clear(MEMBER_CLASS_FLAGS) + "."); } if (f.isStrictFP() && f.isInterface()) { throw new SemanticException("Cannot declare a strictfp interface."); } if (f.isFinal() && f.isInterface()) { throw new SemanticException("Cannot declare a final interface."); } checkAccessFlags(f); } @Override public ConstructorInstance defaultConstructor(Position pos, ClassType container) { assert_(container); Flags access = Flags.NONE; if (container.flags().isPrivate() || JL5Flags.isEnum(container.flags())) { access = access.Private(); } if (container.flags().isProtected()) { access = access.Protected(); } if (container.flags().isPublic() && !JL5Flags.isEnum(container.flags())) { access = access.Public(); } return constructorInstance(pos, container, access, Collections.<Type> emptyList(), Collections.<Type> emptyList(), Collections.<TypeVariable> emptyList()); } @Override public ParsedClassType createClassType(LazyClassInitializer init, Source fromSource) { return new JL5ParsedClassType_c(this, init, fromSource); } @Override protected PrimitiveType createPrimitive(PrimitiveType.Kind kind) { return new JL5PrimitiveType_c(this, kind); } @Override protected NullType createNull() { return new JL5NullType_c(this); } @Override public EnumInstance findEnumConstant(ReferenceType container, String name, Context c) throws SemanticException { ClassType ct = null; if (c != null) ct = c.currentClass(); return findEnumConstant(container, name, ct); } @Override public EnumInstance findEnumConstant(ReferenceType container, String name, ClassType currClass) throws SemanticException { Collection<EnumInstance> enumConstants = findEnumConstants(container, name); if (enumConstants.size() == 0) { throw new NoMemberException(JL5NoMemberException.ENUM_CONSTANT, "Enum Constant: \"" + name + "\" not found in type \"" + container + "\"."); } Iterator<EnumInstance> i = enumConstants.iterator(); EnumInstance ei = i.next(); if (i.hasNext()) { EnumInstance ei2 = i.next(); throw new SemanticException("Enum Constant \"" + name + "\" is ambiguous; it is defined in both " + ei.container() + " and " + ei2.container() + "."); } if (currClass != null && !isAccessible(ei, currClass) && !isInherited(ei, currClass)) { throw new SemanticException("Cannot access " + ei + "."); } return ei; } @Override public EnumInstance findEnumConstant(ReferenceType container, String name) throws SemanticException { return findEnumConstant(container, name, (ClassType) null); } @Override public EnumInstance findEnumConstant(ReferenceType container, long ordinal) throws SemanticException { assert_(container); if (container == null) { throw new InternalCompilerError("Cannot access enum constant within a null container type."); } if (!container.isClass()) { throw new InternalCompilerError("Cannot access enum constant within a non-class container type."); } JL5ClassType ct = (JL5ClassType) container; for (EnumInstance ec : ct.enumConstants()) { if (ec.ordinal() == ordinal) { return ec; } } return null; } public Set<EnumInstance> findEnumConstants(ReferenceType container, String name) { assert_(container); if (container == null) { throw new InternalCompilerError("Cannot access enum constant \"" + name + "\" within a null container type."); } EnumInstance ei = null; if (container instanceof JL5ClassType) { ei = ((JL5ClassType) container).enumConstantNamed(name); } if (ei != null) { return Collections.singleton(ei); } return new HashSet<EnumInstance>(); } @Override public EnumInstance enumInstance(Position pos, ClassType ct, Flags f, String name, long ordinal) { assert_(ct); return new EnumInstance_c(this, pos, ct, f, name, ordinal); } @Override public Context createContext() { return new JL5Context_c(this); } @Override public FieldInstance findFieldOrEnum(ReferenceType container, String name, ClassType currClass) throws SemanticException { FieldInstance fi = null; try { fi = findField(container, name, currClass); } catch (NoMemberException e) { fi = findEnumConstant(container, name, currClass); } return fi; } @Override public MethodInstance methodInstance(Position pos, ReferenceType container, Flags flags, Type returnType, String name, List<? extends Type> argTypes, List<? extends Type> excTypes) { return methodInstance(pos, container, flags, returnType, name, argTypes, excTypes, Collections.<TypeVariable> emptyList()); } @Override public JL5MethodInstance methodInstance(Position pos, ReferenceType container, Flags flags, Type returnType, String name, List<? extends Type> argTypes, List<? extends Type> excTypes, List<TypeVariable> typeParams) { assert_(container); assert_(returnType); assert_(argTypes); assert_(excTypes); assert_(typeParams); return new JL5MethodInstance_c(this, pos, container, flags, returnType, name, argTypes, excTypes, typeParams); } @Override public ConstructorInstance constructorInstance(Position pos, ClassType container, Flags flags, List<? extends Type> argTypes, List<? extends Type> excTypes) { return constructorInstance(pos, container, flags, argTypes, excTypes, Collections.<TypeVariable> emptyList()); } @Override public JL5ConstructorInstance constructorInstance(Position pos, ClassType container, Flags flags, List<? extends Type> argTypes, List<? extends Type> excTypes, List<TypeVariable> typeParams) { assert_(container); assert_(argTypes); assert_(excTypes); assert_(typeParams); return new JL5ConstructorInstance_c(this, pos, container, flags, argTypes, excTypes, typeParams); } @Override public LocalInstance localInstance(Position pos, Flags flags, Type type, String name) { return new JL5LocalInstance_c(this, pos, flags, type, name); } @Override public JL5FieldInstance fieldInstance(Position pos, ReferenceType container, Flags flags, Type type, String name) { assert_(container); assert_(type); return new JL5FieldInstance_c(this, pos, container, flags, type, name); } @Override public TypeVariable typeVariable(Position pos, String name, ReferenceType upperBound) { // System.err.println("JL5TS_c typevar created " + name + " " + bounds); return new TypeVariable_c(this, pos, name, upperBound); } protected UnknownTypeVariable unknownTypeVar = null; @Override public UnknownTypeVariable unknownTypeVariable(Position position) { if (unknownTypeVar == null) unknownTypeVar = new UnknownTypeVariable_c(this); return unknownTypeVar; } @Override public boolean isBaseCastValid(Type fromType, Type toType) { if (toType.isArray()) { Type base = ((ArrayType) toType).base(); assert_(base); return isImplicitCastValid(fromType, base); } return false; } @Override public boolean numericConversionBaseValid(Type t, Object value) { if (t.isArray()) { return super.numericConversionValid(((ArrayType) t).base(), value); } return false; } @Override public Flags flagsForBits(int bits) { Flags f = super.flagsForBits(bits); if ((bits & JL5Flags.ENUM_MOD) != 0) { f = JL5Flags.setEnum(f); } if ((bits & JL5Flags.VARARGS_MOD) != 0) { f = JL5Flags.setVarArgs(f); } if ((bits & JL5Flags.ANNOTATION_MOD) != 0) { f = JL5Flags.setAnnotation(f); } return f; } @Override public ClassFileLazyClassInitializer classFileLazyClassInitializer( ClassFile clazz) { //return new ClassFileLazyClassInitializer(clazz, this); return new JL5ClassFileLazyClassInitializer(clazz, this); } @Override public ImportTable importTable(String sourceName, polyglot.types.Package pkg) { assert_(pkg); return new JL5ImportTable(this, pkg, sourceName); } @Override public ImportTable importTable(polyglot.types.Package pkg) { assert_(pkg); return new JL5ImportTable(this, pkg); } protected ArrayType createArrayType(Position pos, Type type, boolean isVarargs) { JL5ArrayType at = new JL5ArrayType_c(this, pos, type, isVarargs); return at; } @Override public ArrayType arrayOf(Position position, Type type, boolean isVarargs) { return arrayType(position, type, isVarargs); } /** * Factory method for ArrayTypes. */ @Override protected ArrayType createArrayType(Position pos, Type type) { return new JL5ArrayType_c(this, pos, type, false); } Map<Type, ArrayType> varargsArrayTypeCache = new HashMap<Type, ArrayType>(); protected ArrayType arrayType(Position pos, Type type, boolean isVarargs) { if (isVarargs) { ArrayType t = varargsArrayTypeCache.get(type); if (t == null) { t = createArrayType(pos, type, isVarargs); varargsArrayTypeCache.put(type, t); } return t; } else { return super.arrayType(pos, type); } } /*@Override protected Collection findMostSpecificProcedures(List acceptable) throws SemanticException { throw new InternalCompilerError("Unimplemented"); }*/ /** * Populates the list acceptable with those MethodInstances which are * Applicable and Accessible as defined by JLS 15.12.2 */ @Override protected List<? extends MethodInstance> findAcceptableMethods( ReferenceType container, String name, List<? extends Type> argTypes, ClassType currClass) throws SemanticException { return findAcceptableMethods(container, name, argTypes, Collections.<ReferenceType> emptyList(), currClass); } protected List<? extends MethodInstance> findAcceptableMethods( ReferenceType container, String name, List<? extends Type> argTypes, List<? extends ReferenceType> actualTypeArgs, ClassType currClass) throws SemanticException { return findAcceptableMethods(container, name, argTypes, actualTypeArgs, currClass, null); } protected List<? extends MethodInstance> findAcceptableMethods( ReferenceType container, String name, List<? extends Type> argTypes, List<? extends ReferenceType> actualTypeArgs, ClassType currClass, Type expectedReturnType) throws SemanticException { assert_(container); assert_(argTypes); SemanticException error = null; // List of methods accessible from curClass that have valid method // calls without boxing/unboxing conversion or variable arity and // are not overridden by an unaccessible method List<MethodInstance> phase1methods = new ArrayList<MethodInstance>(); // List of methods accessible from curClass that have a valid method // call relying on boxing/unboxing conversion List<MethodInstance> phase2methods = new ArrayList<MethodInstance>(); // List of methods accessible from curClass that have a valid method // call relying on boxing/unboxing conversion and variable arity List<MethodInstance> phase3methods = new ArrayList<MethodInstance>(); // A list of unacceptable methods, where the method call is valid, but // the method is not accessible. This list is needed to make sure that // the acceptable methods are not overridden by an unacceptable method. List<MethodInstance> inaccessible = new ArrayList<MethodInstance>(); // A set of all the methods that methods in phase[123]methods override. // Used to make sure we don't mistakenly add in overridden methods // (since overridden methods aren't inherited from superclasses). Set<MethodInstance> phase1overridden = new HashSet<MethodInstance>(); Set<MethodInstance> phase2overridden = new HashSet<MethodInstance>(); Set<MethodInstance> phase3overridden = new HashSet<MethodInstance>(); Set<Type> visitedTypes = new HashSet<Type>(); LinkedList<Type> typeQueue = new LinkedList<Type>(); typeQueue.addLast(container); // System.err.println("JL5TS: findAcceptableMethods for " + name + " in " + container); while (!typeQueue.isEmpty()) { Type type = typeQueue.remove(); // System.err.println(" looking at type " + type + " " + type.getClass()); // Make sure each type is considered only once if (visitedTypes.contains(type)) continue; visitedTypes.add(type); if (Report.should_report(Report.types, 2)) { Report.report(2, "Searching type " + type + " for method " + name + "(" + listToString(argTypes) + ")"); } if (!type.isReference()) { throw new SemanticException("Cannot call method in " + " non-reference type " + type + "."); } @SuppressWarnings("unchecked") List<JL5MethodInstance> methods = (List<JL5MethodInstance>) type.toReference().methods(); for (JL5MethodInstance mi : methods) { if (Report.should_report(Report.types, 3)) Report.report(3, "Trying " + mi); // Method name must match if (!mi.name().equals(name)) continue; // System.err.println(" checking " + mi); JL5MethodInstance substMi = methodCallValid(mi, name, argTypes, actualTypeArgs, expectedReturnType); JL5MethodInstance origMi = mi; if (substMi != null) { mi = substMi; if (isAccessible(mi, container, currClass)) { if (Report.should_report(Report.types, 3)) { Report.report(3, "->acceptable: " + mi + " in " + mi.container()); } if (varArgsRequired(mi)) { if (!phase3overridden.contains(mi) && !phase3overridden.contains(origMi)) { phase3overridden.addAll(mi.implemented()); phase3overridden.addAll(origMi.implemented()); phase3methods.removeAll(mi.implemented()); phase3methods.removeAll(origMi.implemented()); phase3methods.add(mi); } } else if (boxingRequired(mi, argTypes)) { if (!phase2overridden.contains(mi) && !phase2overridden.contains(origMi)) { phase2overridden.addAll(mi.implemented()); phase2overridden.addAll(origMi.implemented()); phase2methods.removeAll(mi.implemented()); phase2methods.removeAll(origMi.implemented()); phase2methods.add(mi); } } else { if (!phase1overridden.contains(mi) && !phase1overridden.contains(origMi)) { phase1overridden.addAll(mi.implemented()); phase1overridden.addAll(origMi.implemented()); phase1methods.removeAll(mi.implemented()); phase1methods.removeAll(origMi.implemented()); phase1methods.add(mi); } } } else { // method call is valid but the method is unaccessible inaccessible.add(mi); if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "Method " + mi.signature() + " in " + container + " is inaccessible."); } } } else { if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "Method " + mi.signature() + " in " + container + " cannot be called with arguments " + "(" + listToString(argTypes) + ")."); } } } if (type instanceof JL5ClassType) { for (Type superT : ((JL5ClassType) type).superclasses()) { if (superT != null && superT.isReference()) { typeQueue.addLast(superT.toReference()); } } } else { Type superT = type.toReference().superType(); if (superT != null && superT.isReference()) { typeQueue.addLast(superT.toReference()); } } typeQueue.addAll(type.toReference().interfaces()); } if (error == null) { error = new NoMemberException(NoMemberException.METHOD, "No valid method call found for " + name + "(" + listToString(argTypes) + ")" + " in " + container + "."); } // remove any methods that are overridden by an inaccessible method for (MethodInstance mi : inaccessible) { phase1methods.removeAll(mi.overrides()); phase2methods.removeAll(mi.overrides()); phase3methods.removeAll(mi.overrides()); } // System.err.println("JL5ts_c: acceptable methods for " + name + argTypes // + " is " + phase1methods); // System.err.println(" " + phase2methods); // System.err.println(" " + phase3methods); // System.err.println(" phase1overridden is " + phase1overridden); // System.err.println(" phase2overridden is " + phase2overridden); // System.err.println(" phase3overridden is " + phase3overridden); if (!phase1methods.isEmpty()) return phase1methods; if (!phase2methods.isEmpty()) return phase2methods; if (!phase3methods.isEmpty()) return phase3methods; // No acceptable accessible methods were found throw error; } @Override public boolean methodCallValid(MethodInstance mi, String name, List<? extends Type> argTypes) { return this.methodCallValid((JL5MethodInstance) mi, name, argTypes, null, null) != null; } @Override public JL5MethodInstance methodCallValid(JL5MethodInstance mi, String name, List<? extends Type> argTypes, List<? extends ReferenceType> actualTypeArgs, Type expectedReturnType) { if (actualTypeArgs == null) { actualTypeArgs = Collections.emptyList(); } // First check that the number of arguments is reasonable if (argTypes.size() != mi.formalTypes().size()) { // the actual args don't match the number of the formal args. if (!(mi.isVariableArity() && argTypes.size() >= mi.formalTypes() .size() - 1)) { // the last (variable) argument can consume 0 or more of the actual arguments. return null; } } JL5Subst subst = null; if (!mi.typeParams().isEmpty() && actualTypeArgs.isEmpty()) { // need to perform type inference subst = inferTypeArgs(mi, argTypes, expectedReturnType); } else if (!mi.typeParams().isEmpty() && !actualTypeArgs.isEmpty()) { Map<TypeVariable, ReferenceType> m = new HashMap<TypeVariable, ReferenceType>(); Iterator<? extends ReferenceType> iter = actualTypeArgs.iterator(); for (TypeVariable tv : mi.typeParams()) { m.put(tv, iter.next()); } subst = (JL5Subst) this.subst(m); } JL5MethodInstance mj = mi; if (!mi.typeParams().isEmpty() && subst != null) { //mj = (JL5MethodInstance) this.instantiate(mi.position(), mi, actualTypeArgs); mj = subst.substMethod(mi); } // System.err.println("JL5TS methocall valid to " + mi + " with argtypes " + argTypes + " and actuals " + actualTypeArgs); // System.err.println(" subst is " + subst); // System.err.println(" Call to mi " + mi + " after inference is " + mj); // System.err.println(" super.methodCallValid ? " + super.methodCallValid(mj, name, argTypes)); if (super.methodCallValid(mj, name, argTypes)) { return mj; } return null; } @Override public boolean callValid(ProcedureInstance mi, List<? extends Type> argTypes) { return this.callValid((JL5ProcedureInstance) mi, argTypes, null) != null; } @Override public JL5ProcedureInstance callValid(JL5ProcedureInstance mi, List<? extends Type> argTypes, List<? extends ReferenceType> actualTypeArgs) { if (actualTypeArgs == null) { actualTypeArgs = Collections.emptyList(); } JL5Subst subst = null; if (!mi.typeParams().isEmpty() && actualTypeArgs.isEmpty()) { // need to perform type inference subst = inferTypeArgs(mi, argTypes, null); } else if (!mi.typeParams().isEmpty() && !actualTypeArgs.isEmpty()) { Map<TypeVariable, ReferenceType> m = new HashMap<TypeVariable, ReferenceType>(); Iterator<? extends ReferenceType> iter = actualTypeArgs.iterator(); for (TypeVariable tv : mi.typeParams()) { m.put(tv, iter.next()); } subst = (JL5Subst) this.subst(m); } JL5ProcedureInstance mj = mi; if (!mi.typeParams().isEmpty() && subst != null) { // check that the substitution satisfies the bounds for (TypeVariable tv : subst.substitutions().keySet()) { Type a = subst.substitutions().get(tv); if (!isSubtype(a, tv.upperBound())) { return null; } } mj = subst.substProcedure(mi); } if (super.callValid(mj, argTypes)) { return mj; } return null; } /** * Infer type arguments for mi, when it is called with arguments of type argTypes * @param mi * @param argTypes * @return */ private JL5Subst inferTypeArgs(JL5ProcedureInstance mi, List<? extends Type> argTypes, Type expectedReturnType) { InferenceSolver s = new InferenceSolver_c(mi, argTypes, this); Map<TypeVariable, ReferenceType> m = s.solve(expectedReturnType); if (m == null) return null; JL5Subst subst = (JL5Subst) this.subst(m); return subst; } @Override public ClassType instantiate(Position pos, PClass<TypeVariable, ReferenceType> base, List<? extends ReferenceType> actuals) throws SemanticException { JL5ParsedClassType clazz = (JL5ParsedClassType) base.clazz(); return instantiate(pos, clazz, actuals); } @Override public ClassType instantiate(Position pos, JL5ParsedClassType clazz, ReferenceType... actuals) throws SemanticException { return this.instantiate(pos, clazz, Arrays.asList(actuals)); } @Override public ClassType instantiate(Position pos, JL5ParsedClassType clazz, List<? extends ReferenceType> actuals) throws SemanticException { if (clazz.typeVariables().isEmpty() || (actuals == null || actuals.isEmpty())) { return clazz; } boolean allNull = true; for (ReferenceType t : actuals) { if (t != null) { allNull = false; break; } } if (allNull) { return clazz; } return super.instantiate(pos, clazz.pclass(), actuals); } @Override public JL5ProcedureInstance instantiate(Position pos, JL5ProcedureInstance mi, List<? extends ReferenceType> actuals) { Map<TypeVariable, ReferenceType> m = new LinkedHashMap<TypeVariable, ReferenceType>(); Iterator<? extends ReferenceType> iter = actuals.iterator(); for (TypeVariable tv : mi.typeParams()) { m.put(tv, iter.next()); } JL5Subst subst = (JL5Subst) this.subst(m); JL5ProcedureInstance ret = subst.substProcedure(mi); ret.setContainer(mi.container()); return ret; } private boolean boxingRequired(JL5ProcedureInstance pi, List<? extends Type> paramTypes) { int numFormals = pi.formalTypes().size(); for (int i = 0; i < numFormals - 1; i++) { Type formal = pi.formalTypes().get(i); Type actual = paramTypes.get(i); if (formal.isPrimitive() ^ actual.isPrimitive()) return true; } if (pi.isVariableArity()) { Type lastParams = ((JL5ArrayType) pi.formalTypes().get(numFormals - 1)).base(); for (int i = numFormals - 1; i < paramTypes.size() - 1; i++) { if (lastParams.isPrimitive() ^ paramTypes.get(i).isPrimitive()) return true; } } else if (numFormals > 0) { Type formal = pi.formalTypes().get(numFormals - 1); Type actual = paramTypes.get(numFormals - 1); if (formal.isPrimitive() ^ actual.isPrimitive()) return true; } return false; } private boolean varArgsRequired(JL5ProcedureInstance pi) { return pi.isVariableArity(); } @Override public List<ReferenceType> allAncestorsOf(ReferenceType rt) { Set<ReferenceType> ancestors = new LinkedHashSet<ReferenceType>(); ancestors.add(rt); Set<? extends Type> superClasses; if (rt.isClass()) { superClasses = ((JL5ClassType) rt).superclasses(); } else { superClasses = Collections.singleton(rt.superType()); } for (Type superT : superClasses) { if (superT.isReference()) { ancestors.add((ReferenceType) superT); ancestors.addAll(allAncestorsOf((ReferenceType) superT)); } } for (ReferenceType inter : rt.interfaces()) { ancestors.add(inter); ancestors.addAll(allAncestorsOf(inter)); } return new ArrayList<ReferenceType>(ancestors); } public static String listToString(List<?> l) { StringBuffer sb = new StringBuffer(); for (Iterator<?> i = l.iterator(); i.hasNext();) { Object o = i.next(); sb.append(o.toString()); if (i.hasNext()) { sb.append(", "); } } return sb.toString(); } @Override public Subst<TypeVariable, ReferenceType> subst( Map<TypeVariable, ? extends ReferenceType> substMap) { return new JL5Subst_c(this, substMap); } @Override public boolean hasSameSignature(JL5MethodInstance mi, JL5MethodInstance mj) { return hasSameSignature(mi, mj, false); } protected boolean hasSameSignature(JL5MethodInstance mi, JL5MethodInstance mj, boolean eraseMj) { if (!mi.name().equals(mj.name())) { return false; } if (mi.formalTypes().size() != mj.formalTypes().size()) { return false; } if (eraseMj && !mi.typeParams().isEmpty()) { // we are erasing mj, so it has no type parameters. // so mi better have no type parameters return false; } else if (!eraseMj && mi.typeParams().size() != mj.typeParams().size()) { // we are not erasing mj, so it and mi better // have the same number of type parameters. return false; } // replace the type variables of mj with the type variables of mi if (!eraseMj && !mi.typeParams().isEmpty()) { Map<TypeVariable, ReferenceType> substm = new LinkedHashMap<TypeVariable, ReferenceType>(); for (int i = 0; i < mi.typeParams().size(); i++) { substm.put(mj.typeParams().get(i), mi.typeParams().get(i)); } Subst<TypeVariable, ReferenceType> subst = this.subst(substm); mj = subst.substMethod(mj); } // now check that the types match Iterator<? extends Type> typesi = mi.formalTypes().iterator(); Iterator<? extends Type> typesj = mj.formalTypes().iterator(); while (typesi.hasNext()) { Type ti = typesi.next(); Type tj = typesj.next(); if (eraseMj) { tj = this.erasureType(tj); } if (!ti.equals(tj)) { return false; } } return true; } @Override public boolean isSubSignature(JL5MethodInstance mi, JL5MethodInstance mj) { if (hasSameSignature(mi, mj)) { return true; } // check if the signature of mi is the same as the erasure of mj. return hasSameSignature(mi, mj, true); } @Override public boolean areOverrideEquivalent(JL5MethodInstance mi, JL5MethodInstance mj) { return isSubSignature(mi, mj) || isSubSignature(mj, mi); } @Override public boolean isUncheckedConversion(Type fromType, Type toType) { if (fromType instanceof JL5ClassType && toType instanceof JL5ClassType) { JL5ClassType from = (JL5ClassType) fromType; JL5ClassType to = (JL5ClassType) toType; if (from.isRawClass()) { if (!to.isRawClass() && to instanceof JL5SubstClassType) { JL5SubstClassType tosct = (JL5SubstClassType) to; return from.equals(tosct.base()); } } } return false; } @Override public boolean areReturnTypeSubstitutable(Type ri, Type rj) { if (ri.isPrimitive()) { return ri.equals(rj); } else if (ri.isReference()) { return ri.isSubtype(rj) || this.isUncheckedConversion(ri, rj) || ri.isSubtype(this.erasureType(rj)); } else if (ri.isVoid()) { return rj.isVoid(); } else { throw new InternalCompilerError("Unexpected return type: " + ri); } } @Override public MethodInstance findImplementingMethod(ClassType ct, MethodInstance mi) { ReferenceType curr = ct; while (curr != null) { List<? extends MethodInstance> possible = curr.methodsNamed(mi.name()); for (MethodInstance mj : possible) { if (!mj.flags().isAbstract() && ((isAccessible(mi, ct) && isAccessible(mj, ct)) || isAccessible(mi, mj.container() .toClass()))) { // The method mj may be a suitable implementation of mi. // mj is not abstract, and either mj's container // can access mi (thus mj can really override mi), or // mi and mj are both accessible from ct (e.g., // mi is declared in an interface that ct implements, // and mj is defined in a superclass of ct). if (this.areOverrideEquivalent((JL5MethodInstance) mi, (JL5MethodInstance) mj)) { return mj; } } } if (curr == mi.container()) { // we've reached the definition of the abstract // method. We don't want to look higher in the // hierarchy; this is not an optimization, but is // required for correctness. break; } curr = curr.superType() == null ? null : curr.superType() .toReference(); } return null; } @Override public Type erasureType(Type t) { return this.erasureType(t, new HashSet<TypeVariable>()); } protected Type erasureType(Type t, Set<TypeVariable> visitedTypeVariables) { if (t.isArray()) { ArrayType at = t.toArray(); return at.base(this.erasureType(at.base(), visitedTypeVariables)); } if (t instanceof TypeVariable) { TypeVariable tv = (TypeVariable) t; if (!visitedTypeVariables.add(tv)) { // tv was already in visitedTypeVariables // whoops, we're in some kind of recursive type return this.Object(); } return this.erasureType(tv.upperBound(), visitedTypeVariables); } if (t instanceof IntersectionType) { IntersectionType it = (IntersectionType) t; ClassType ct = null; ClassType iface = null; boolean subtypes = true; // Find the most specific class for (ReferenceType rt : it.bounds()) { ClassType next = (ClassType) rt; if (equals(Object(), next)) continue; if (!next.toClass().flags().isInterface()) { // Is next more specific than ct? if (ct == null || next.descendsFrom(ct)) ct = next; } else if (subtypes) { // Is next a more specific subtype than iface? if (iface == null || next.descendsFrom(iface)) iface = next; // Is iface a subtype of next? else if (!iface.descendsFrom(next)) { subtypes = false; } } } // Return the most-specific class, if there is one if (ct != null) return erasureType(ct, visitedTypeVariables); // Otherwise if the interfaces are all subtypes, return iface if (subtypes && iface != null) return erasureType(iface, visitedTypeVariables); return Object(); } if (t instanceof WildCardType) { WildCardType tv = (WildCardType) t; if (tv.upperBound() == null) { return this.Object(); } return this.erasureType(tv.upperBound(), visitedTypeVariables); } if (t instanceof JL5SubstType) { JL5SubstType jst = (JL5SubstType) t; return this.erasureType(jst.base(), visitedTypeVariables); } if (t instanceof JL5ParsedClassType) { return this.toRawType(t); } return t; } @Override public JL5Subst erasureSubst(JL5ProcedureInstance pi) { List<TypeVariable> typeParams = pi.typeParams(); Map<TypeVariable, ReferenceType> m = new LinkedHashMap<TypeVariable, ReferenceType>(); for (TypeVariable tv : typeParams) { m.put(tv, tv.erasureType()); } if (m.isEmpty()) { return null; } return new JL5Subst_c(this, m); } @Override public JL5Subst erasureSubst(JL5ParsedClassType base) { Map<TypeVariable, ReferenceType> m = new LinkedHashMap<TypeVariable, ReferenceType>(); JL5ParsedClassType t = base; while (t != null) { for (TypeVariable tv : t.typeVariables()) { m.put(tv, tv.erasureType()); } if (!(t.outer() instanceof JL5ParsedClassType)) { // no more type variables that we care about! break; } t = (JL5ParsedClassType) t.outer(); } if (m.isEmpty()) { return null; } return new JL5RawSubst_c(this, m, base); } @Override public boolean isContained(Type fromType, Type toType) { if (toType instanceof WildCardType) { WildCardType wTo = (WildCardType) toType; if (fromType instanceof WildCardType) { WildCardType wFrom = (WildCardType) fromType; // JLS 3rd ed 4.5.1.1 if (wFrom.isExtendsConstraint() && wTo.isExtendsConstraint()) { if (isSubtype(wFrom.upperBound(), wTo.upperBound())) { return true; } } if (wFrom.isSuperConstraint() && wTo.isSuperConstraint()) { if (isSubtype(wTo.lowerBound(), wFrom.lowerBound())) { return true; } } } if (wTo.isSuperConstraint()) { if (isImplicitCastValid(wTo.lowerBound(), fromType)) { return true; } } else if (wTo.isExtendsConstraint()) { if (isImplicitCastValid(fromType, wTo.upperBound())) { return true; } } return false; } else { return this.typeEquals(fromType, toType); } } @Override public boolean descendsFrom(Type child, Type ancestor) { // System.err.println("jl5TS_C: descends from: " + child + " descended from " + ancestor); boolean b = super.descendsFrom(child, ancestor); if (b) return true; // System.err.println(" : descends from 0"); if (ancestor instanceof TypeVariable) { TypeVariable tv = (TypeVariable) ancestor; // See JLS 3rd ed 4.10.2: type variable is a direct supertype of its lowerbound. if (tv.hasLowerBound()) { // System.err.println(" : descends from 1"); return isSubtype(child, tv.lowerBound()); } } if (ancestor instanceof WildCardType) { WildCardType w = (WildCardType) ancestor; // See JLS 3rd ed 4.10.2: type variable is a direct supertype of its lowerbound. if (w.hasLowerBound()) { // System.err.println(" : descends from 2"); return isSubtype(child, w.lowerBound()); } } if (ancestor instanceof LubType) { LubType lub = (LubType) ancestor; // LUB is a supertype of each of its elements for (ReferenceType rt : lub.lubElements()) { if (descendsFrom(child, rt)) return true; } } // System.err.println(" : descends from 3"); return false; } @Override public boolean isSubtype(Type t1, Type t2) { if (super.isSubtype(t1, t2)) { return true; } if (t2 instanceof WildCardType) { WildCardType wct = (WildCardType) t2; if (wct.hasLowerBound() && isSubtype(t1, wct.lowerBound())) { return true; } } if (t2 instanceof TypeVariable) { TypeVariable tv = (TypeVariable) t2; if (tv.hasLowerBound() && isSubtype(t1, tv.lowerBound())) { return true; } } if (t2 instanceof IntersectionType) { IntersectionType it = (IntersectionType) t2; // t1 is a substype of u1&u2&...&un if there is some ui such // that t1 is a subtype of ui. for (Type t : it.bounds()) { if (isSubtype(t1, t)) { return true; } } } if (t2 instanceof LubType) { LubType lub = (LubType) t2; // t2 is an upper bound of several types. If t1 is a subtype of any of them, // then t2 is a subtype of lub. for (ReferenceType upperBound : lub.lubElements()) { if (isSubtype(t1, upperBound)) { return true; } } } return false; } @Override public boolean isImplicitCastValid(Type fromType, Type toType) { LinkedList<Type> chain = isImplicitCastValidChain(fromType, toType); // Try an unchecked conversion, if toType is a parameterized type. if (chain == null && toType instanceof JL5SubstClassType) { JL5SubstClassType toSubstCT = (JL5SubstClassType) toType; chain = isImplicitCastValidChain(fromType, this.rawClass(toSubstCT.base(), toSubstCT.base() .position())); if (chain != null) { // success! chain.addLast(toType); } } if (chain == null) { return false; } // check whether "the chain of conversions contains two parameterized types that are not not in the subtype relation." // See JLS 3rd ed 5.2 and 5.3. for (int i = 0; i < chain.size(); i++) { Type t = chain.get(i); if (t instanceof JL5SubstClassType) { for (int j = i + 1; j < chain.size(); j++) { Type u = chain.get(j); if (u instanceof JL5SubstClassType) { if (!t.isSubtype(u)) { return false; } } } } } return true; } @Override public LinkedList<Type> isImplicitCastValidChain(Type fromType, Type toType) { assert_(fromType); assert_(toType); if (fromType == null || toType == null) { throw new IllegalArgumentException("isImplicitCastValidChain: " + fromType + " " + toType); } LinkedList<Type> chain = null; if (fromType instanceof JL5ClassType) { chain = ((JL5ClassType) fromType).isImplicitCastValidChainImpl(toType); } else if (fromType.isImplicitCastValidImpl(toType)) { chain = new LinkedList<Type>(); chain.add(fromType); chain.add(toType); } return chain; } @Override public boolean numericConversionValid(Type type, long value) { // Optional support for allowing a boxing conversion when using a literal // in an initializer for compatibility with with "javac -source 1.5" JL5Options opts = (JL5Options) extInfo.getOptions(); if (opts.morePermissiveCasts && isPrimitiveWrapper(type)) { return super.numericConversionValid(primitiveTypeOfWrapper(type), value); } else { return super.numericConversionValid(type, value); } } @Override public boolean numericConversionValid(Type type, Object value) { // Optional support for allowing a boxing conversion when using a literal // in an initializer for compatibility with with "javac -source 1.5" JL5Options opts = (JL5Options) extInfo.getOptions(); if (opts.morePermissiveCasts && isPrimitiveWrapper(type)) { return super.numericConversionValid(primitiveTypeOfWrapper(type), value); } else { return super.numericConversionValid(type, value); } } @Override public boolean isCastValid(Type fromType, Type toType) { if (super.isCastValid(fromType, toType)) { return true; } // Optional support for widening conversion after unboxing for compatibility // with "javac -source 1.5" JL5Options opts = (JL5Options) this.extensionInfo().getOptions(); if (opts.morePermissiveCasts) { if (isPrimitiveWrapper(fromType) && toType.isPrimitive()) { if (this.isImplicitCastValid(this.unboxingConversion(fromType), toType)) { return true; } } } // JLS 3rd ed. Section 5.5 if (fromType.isClass()) { if (!fromType.toClass().flags().isInterface()) { // fromType is class type return isCastValidFromClass(fromType.toClass(), toType); } else { return isCastValidFromInterface(fromType.toClass(), toType); // fromType is an interface } } else if (fromType instanceof TypeVariable) { return isCastValid(((TypeVariable) fromType).upperBound(), toType); } else if (fromType.isArray()) { return isCastValidFromArray(fromType.toArray(), toType); } return false; } protected boolean isCastValidFromClass(ClassType fromType, Type toType) { if (toType instanceof TypeVariable) { return this.isCastValid(fromType, ((TypeVariable) toType).upperBound()); } if (toType.isClass()) { if (!toType.toClass().flags().isInterface()) { // toType is a class type Type erasedFrom = erasureType(fromType); Type erasedTo = erasureType(toType); return (erasedFrom != fromType || erasedTo != toType) && (erasedFrom.isSubtype(erasedTo) || erasedTo.isSubtype(erasedFrom)); // TODO: need to check whether there is a supertype X // of this and Y of toType that have the same erasure // and are provably distinct. } else { // toType is an interface // TODO: need to check whether there is a supertype X // of this and Y of toType that have the same erasure // and are provably distinct. } } return false; } protected boolean isCastValidFromInterface(ClassType fromType, Type toType) { // If T is an array type, then T must implement S, or a compile-time error occurs // This is handled in the super class. if (toType.isClass() && toType.toClass().flags().isFinal()) { // toType is final. if (fromType instanceof RawClass || fromType instanceof JL5SubstClassType) { // S is either a parameterized type that is an invocation of some generic type declaration G, or a raw type corresponding to a generic type declaration G. // Then there must exist a supertype X of T, such that X is an invocation of G, or a compile-time error occurs. JL5ParsedClassType baseClass; if (fromType instanceof RawClass) { baseClass = ((RawClass) fromType).base(); } else { baseClass = ((JL5SubstClassType) fromType).base(); } JL5SubstClassType x = findGenericSupertype(baseClass, toType.toReference()); if (x == null) { return false; } // Furthermore, if S and X are provably distinct parameterized types then a compile-time error occurs. if (fromType instanceof JL5SubstClassType && areProvablyDistinct((JL5SubstClassType) fromType, x)) { return false; } } else { // S is not a parameterized type or a raw type, and T is final // Then T must implement S, and the cast is statically known to be correct, or a compile-time error occurs. if (!isSubtype(toType, fromType)) { // XXX this takes care that T must implement S. Not sure why there is a requirement for the cast to statically known to be correct. That would seem to imply that fromType is a subtype of toType?! return false; } } return true; } else { // T is a type that is not final (8.1.1), and S is an interface // if there exists a supertype X of T, and a supertype Y of S, such that both X and Y are provably distinct parameterized types, // and that the erasures of X and Y are the same, a compile-time error occurs. // Go through the supertypes of each. List<ReferenceType> allY = this.allAncestorsOf(fromType.toReference()); List<ReferenceType> allX = this.allAncestorsOf(toType.toReference()); for (ReferenceType y : allY) { for (ReferenceType x : allX) { if (x instanceof JL5SubstClassType && y instanceof JL5SubstClassType && areProvablyDistinct((JL5SubstClassType) x, (JL5SubstClassType) y) && erasureType(x).equals(erasureType(y))) { return false; } } } return true; } } protected boolean isCastValidFromArray(ArrayType arrayType, Type toType) { if (toType.equals(Object()) || toType.equals(Serializable()) || toType.equals(Cloneable())) { return true; } if (toType instanceof TypeVariable) { TypeVariable tv = (TypeVariable) toType; Type upperBound = tv.upperBound(); if (upperBound.equals(Object()) || upperBound.equals(Serializable()) || upperBound.equals(Cloneable())) { return true; } if (upperBound.isArray()) { return isCastValidFromArray(arrayType, upperBound); } if (upperBound instanceof TypeVariable) { // should we do a recursive call? Check whether there are cycles in the type variables... Set<TypeVariable> visited = new HashSet<TypeVariable>(); visited.add(tv); while (upperBound instanceof TypeVariable) { if (!visited.add((TypeVariable) upperBound)) { break; } upperBound = ((TypeVariable) upperBound).upperBound(); } if (!(upperBound instanceof TypeVariable)) { // no cycle in the upper bounds of type variables! return isCastValidFromArray(arrayType, upperBound); } } return false; } if (toType.isArray()) { ArrayType toArrayType = toType.toArray(); if (arrayType.base().isPrimitive() && arrayType.base().equals(toArrayType.base())) { return true; } if (arrayType.base().isReference() && toArrayType.base().isReference()) { return isCastValid(arrayType.base(), toArrayType.base()); } } return false; } private boolean areProvablyDistinct(JL5SubstClassType s, JL5SubstClassType t) { // See JLS 3rd ed 4.5 // Distinct if either (1) They are invocations of distinct generic type declarations. // or (2) Any of their type arguments are provably distinct JL5SubstClassType x = s; JL5SubstClassType y = t; if (!x.base().equals(y.base())) { return true; } List<ReferenceType> xActuals = x.actuals(); List<ReferenceType> yActuals = y.actuals(); if (xActuals.size() != yActuals.size()) { return true; } for (int i = 0; i < xActuals.size(); i++) { if (areTypArgsProvablyDistinct(xActuals.get(i), xActuals.get(i))) { return true; } } return false; } private boolean areTypArgsProvablyDistinct(ReferenceType s, ReferenceType t) { // JLS 3rd ed 4.5. "Two type arguments are provably distinct if // neither of the arguments is a type variable or wildcard, and // the two arguments are not the same type." return !(s instanceof TypeVariable) && !(t instanceof TypeVariable) && !(s instanceof WildCardType) && !(t instanceof WildCardType) && !s.equals(t); } @Override protected List<ReferenceType> abstractSuperInterfaces(ReferenceType rt) { List<ReferenceType> superInterfaces = new LinkedList<ReferenceType>(); superInterfaces.add(rt); @SuppressWarnings("unchecked") List<JL5ClassType> interfaces = (List<JL5ClassType>) rt.interfaces(); for (JL5ClassType interf : interfaces) { if (interf.isRawClass()) { // it's a raw class, so use the erased version of it interf = (JL5ClassType) this.erasureType(interf); } superInterfaces.addAll(abstractSuperInterfaces(interf)); } if (rt.superType() != null) { JL5ClassType c = (JL5ClassType) rt.superType().toClass(); if (c.flags().isAbstract()) { // the superclass is abstract, so it may contain methods // that must be implemented. superInterfaces.addAll(abstractSuperInterfaces(c)); } else { // the superclass is not abstract, so it must implement // all abstract methods of any interfaces it implements, and // any superclasses it may have. } } return superInterfaces; } @Override public MethodInstance findMethod(ReferenceType container, java.lang.String name, List<? extends Type> argTypes, List<? extends ReferenceType> typeArgs, ClassType currClass, Type expectedReturnType) throws SemanticException { assert_(container); assert_(argTypes); List<? extends MethodInstance> acceptable = findAcceptableMethods(container, name, argTypes, typeArgs, currClass, expectedReturnType); if (acceptable.size() == 0) { throw new NoMemberException(NoMemberException.METHOD, "No valid method call found for " + name + "(" + listToString(argTypes) + ")" + " in " + container + "."); } Collection<? extends MethodInstance> maximal = findMostSpecificProcedures(acceptable); if (maximal.size() > 1) { StringBuffer sb = new StringBuffer(); for (Iterator<? extends MethodInstance> i = maximal.iterator(); i.hasNext();) { MethodInstance ma = i.next(); sb.append(ma.returnType()); sb.append(" "); sb.append(ma.container()); sb.append("."); sb.append(ma.signature()); if (i.hasNext()) { if (maximal.size() == 2) { sb.append(" and "); } else { sb.append(", "); } } } throw new SemanticException("Reference to " + name + " is ambiguous, multiple methods match: " + sb.toString()); } MethodInstance mi = maximal.iterator().next(); return mi; } @Override public ConstructorInstance findConstructor(ClassType container, List<? extends Type> argTypes, ClassType currClass) throws SemanticException { return this.findConstructor(container, argTypes, Collections.<ReferenceType> emptyList(), currClass); } @Override public ConstructorInstance findConstructor(ClassType container, List<? extends Type> argTypes, List<? extends ReferenceType> typeArgs, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); List<ConstructorInstance> acceptable = findAcceptableConstructors(container, argTypes, typeArgs, currClass); if (acceptable.size() == 0) { throw new NoMemberException(NoMemberException.CONSTRUCTOR, "No valid constructor found for " + container + "(" + listToString(argTypes) + ")."); } Collection<ConstructorInstance> maximal = findMostSpecificProcedures(acceptable); if (maximal.size() > 1) { throw new NoMemberException(NoMemberException.CONSTRUCTOR, "Reference to " + container + " is ambiguous, multiple " + "constructors match: " + maximal); } ConstructorInstance ci = maximal.iterator().next(); return ci; } @Override protected List<? extends ConstructorInstance> findAcceptableConstructors( ClassType container, List<? extends Type> argTypes, ClassType currClass) throws SemanticException { return this.findAcceptableConstructors(container, argTypes, Collections.<ReferenceType> emptyList(), currClass); } /** * Populates the list acceptable with those MethodInstances which are * Applicable and Accessible as defined by JLS 15.12.2 * @throws SemanticException */ protected List<ConstructorInstance> findAcceptableConstructors( ClassType container, List<? extends Type> argTypes, List<? extends ReferenceType> actualTypeArgs, ClassType currClass) throws SemanticException { assert_(container); assert_(argTypes); SemanticException error = null; // List of methods accessible from curClass that have valid method // calls without boxing/unboxing conversion or variable arity and // are not overridden by an unaccessible method List<ConstructorInstance> phase1methods = new ArrayList<ConstructorInstance>(); // List of methods accessible from curClass that have a valid method // call relying on boxing/unboxing conversion List<ConstructorInstance> phase2methods = new ArrayList<ConstructorInstance>(); // List of methods accessible from curClass that have a valid method // call relying on boxing/unboxing conversion and variable arity List<ConstructorInstance> phase3methods = new ArrayList<ConstructorInstance>(); if (Report.should_report(Report.types, 2)) Report.report(2, "Searching type " + container + " for constructor " + container + "(" + listToString(argTypes) + ")"); @SuppressWarnings("unchecked") List<JL5ConstructorInstance> constructors = (List<JL5ConstructorInstance>) container.constructors(); for (JL5ConstructorInstance ci : constructors) { if (Report.should_report(Report.types, 3)) Report.report(3, "Trying " + ci); JL5ConstructorInstance substCi = (JL5ConstructorInstance) callValid(ci, argTypes, actualTypeArgs); if (substCi != null) { ci = substCi; if (isAccessible(ci, currClass)) { if (Report.should_report(Report.types, 3)) Report.report(3, "->acceptable: " + ci); if (varArgsRequired(ci)) phase3methods.add(ci); else if (boxingRequired(ci, argTypes)) phase2methods.add(ci); else phase1methods.add(ci); } else { if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "Constructor " + ci.signature() + " is inaccessible."); } } } else { if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "Constructor " + ci.signature() + " cannot be invoked with arguments " + "(" + listToString(argTypes) + ")."); } } } if (!phase1methods.isEmpty()) return phase1methods; if (!phase2methods.isEmpty()) return phase2methods; if (!phase3methods.isEmpty()) return phase3methods; if (error == null) { error = new NoMemberException(NoMemberException.CONSTRUCTOR, "No valid constructor found for " + container + "(" + listToString(argTypes) + ")."); } throw error; } @Override public boolean isAccessible(MemberInstance mi, ReferenceType container, ClassType contextClass) { assert_(mi); ReferenceType target; // does container inherit mi? if (container.descendsFrom(mi.container()) && mi.flags().isPublic()) { target = container; } else { target = mi.container(); } Flags flags = mi.flags(); if (!target.isClass()) { // public members of non-classes are accessible; // non-public members of non-classes are inaccessible return flags.isPublic(); } JL5ClassType targetClass = (JL5ClassType) target.toClass(); if (isAccessible_(flags, targetClass, contextClass)) { return true; } // make sure we strip away any parameters. ClassType targetClassDecl = (ClassType) targetClass.declaration(); if (targetClassDecl != targetClass && isAccessible_(flags, targetClassDecl, contextClass)) { return true; } ClassType contextClassDecl = (ClassType) contextClass.declaration(); if (contextClassDecl != contextClass && isAccessible_(flags, targetClass, contextClassDecl)) { return true; } if (targetClassDecl != targetClass && contextClassDecl != contextClass && isAccessible_(flags, targetClassDecl, contextClassDecl)) { return true; } return false; } protected boolean isAccessible_(Flags flags, ClassType targetClass, ClassType contextClass) { if (!classAccessible(targetClass, contextClass)) { return false; } if (equals(targetClass, contextClass)) return true; // If the current class and the target class are both in the // same class body, then protection doesn't matter, i.e. // protected and private members may be accessed. Do this by // working up through contextClass's containers. if (isEnclosed(contextClass, targetClass) || isEnclosed(targetClass, contextClass)) return true; ClassType ct = contextClass; while (!ct.isTopLevel()) { ct = ct.outer(); if (isEnclosed(targetClass, ct)) return true; } // protected if (flags.isProtected()) { // If the current class is in a // class body that extends/implements the target class, then // protected members can be accessed. Do this by // working up through contextClass's containers. // Use the erasure types so that parameters don't matter. if (descendsFrom(erasureType(contextClass), erasureType(targetClass))) { return true; } ct = contextClass; while (!ct.isTopLevel()) { ct = ct.outer(); if (descendsFrom(erasureType(ct), erasureType(targetClass))) { return true; } } } return accessibleFromPackage(flags, targetClass.package_(), contextClass.package_()); } @Override public boolean isEnclosed(ClassType inner, ClassType outer) { if (inner instanceof JL5ClassType) { inner = (ClassType) inner.declaration(); } if (outer instanceof JL5ClassType) { outer = (ClassType) outer.declaration(); } return inner.isEnclosedImpl(outer); } @Override public boolean hasEnclosingInstance(ClassType inner, ClassType encl) { if (inner instanceof JL5ClassType) { inner = (ClassType) inner.declaration(); } if (encl instanceof JL5ClassType) { encl = (ClassType) encl.declaration(); } return inner.hasEnclosingInstanceImpl(encl); } @Override public WildCardType wildCardType(Position position) { return wildCardType(position, null, null); } @Override public WildCardType wildCardType(Position position, ReferenceType upperBound, ReferenceType lowerBound) { if (upperBound == null) { upperBound = this.Object(); } return new WildCardType_c(this, position, upperBound, lowerBound); } @Override public Type applyCaptureConversion(Type t, Position pos) throws SemanticException { if (!(t instanceof JL5SubstClassType_c)) { return t; } JL5SubstClassType_c ct = (JL5SubstClassType_c) t; JL5ParsedClassType g = ct.base(); List<Type> capturedActuals = new ArrayList<Type>(g.typeVariables().size()); Map<TypeVariable, ReferenceType> substmap = new LinkedHashMap<TypeVariable, ReferenceType>(); // first, set up a subst from the formals to the captured variables. for (TypeVariable a : g.typeVariables()) { ReferenceType ti = (ReferenceType) ct.subst().substType(a); ReferenceType si = ti; if (ti instanceof WildCardType) { si = this.typeVariable(ti.position(), UniqueID.newID("captureConversionFresh"), null); // we'll replace this unknown type soon. } capturedActuals.add(si); substmap.put(a, si); } JL5Subst subst = (JL5Subst) this.subst(substmap); // now go through and substitute the bounds if needed. for (TypeVariable a : g.typeVariables()) { Type ti = ct.subst().substType(a); Type si = subst.substType(a); if (ti instanceof WildCardType) { WildCardType wti = (WildCardType) ti; TypeVariable vsi = (TypeVariable) si; if (wti.isExtendsConstraint()) { ReferenceType wub = wti.upperBound(); ReferenceType substUpperBoundOfA = (ReferenceType) subst.substType(a.upperBound()); ReferenceType glb = this.glb(wub, substUpperBoundOfA, false); vsi.setUpperBound(glb); if (wub.isClass() && !wub.toClass().flags().isInterface() && substUpperBoundOfA.isClass() && !substUpperBoundOfA.toClass() .flags() .isInterface()) { // check that wub is a subtype of substUpperBoundOfA, or vice versa // JLS 3rd ed 5.1.10 if (!isSubtype(wub, substUpperBoundOfA) && !isSubtype(substUpperBoundOfA, wub)) { throw new SemanticException("Cannot capture convert " + t, pos); } } } else { // wti is a super wildcard. vsi.setUpperBound((ReferenceType) subst.substType(a.upperBound())); vsi.setLowerBound(wti.lowerBound()); } } } return subst.substType(g); } @Override public Flags legalLocalFlags() { return JL5Flags.setVarArgs(super.legalLocalFlags()); } @Override public Flags legalConstructorFlags() { return JL5Flags.setVarArgs(super.legalConstructorFlags()); } @Override public Flags legalMethodFlags() { return JL5Flags.setVarArgs(super.legalMethodFlags()); } @Override public Flags legalAbstractMethodFlags() { return JL5Flags.setVarArgs(super.legalAbstractMethodFlags()); } @Override public JL5SubstClassType findGenericSupertype(JL5ParsedClassType base, ReferenceType sub) { List<ReferenceType> ancestors = allAncestorsOf(sub); for (ReferenceType a : ancestors) { if (!(a instanceof JL5SubstClassType)) { continue; } JL5SubstClassType instantiatedType = (JL5SubstClassType) a; JL5ParsedClassType instBase = instantiatedType.base(); if (typeEquals(base, instBase)) { return instantiatedType; } } return null; } @Override public ReferenceType intersectionType(Position pos, List<ReferenceType> types) { if (types.size() == 1) { return types.get(0); } if (types.isEmpty()) { return Object(); } return new IntersectionType_c(this, pos, types); } @Override public boolean checkIntersectionBounds(List<? extends Type> bounds, boolean quiet) throws SemanticException { /* if ((bounds == null) || (bounds.size() == 0)) { if (!quiet) throw new SemanticException("Intersection type can't be empty"); return false; }*/ List<Type> concreteBounds = concreteBounds(bounds); if (concreteBounds.size() == 0) { if (!quiet) throw new SemanticException("Invalid bounds in intersection type."); else return false; } for (int i = 0; i < concreteBounds.size(); i++) for (int j = i + 1; j < concreteBounds.size(); j++) { Type t1 = concreteBounds.get(i); Type t2 = concreteBounds.get(j); // for now, no checks if at least one is an array type if (!t1.isClass() || !t2.isClass()) { return true; } if (!t1.toClass().flags().isInterface() && !t2.toClass().flags().isInterface()) { if ((!isSubtype(t1, t2)) && (!isSubtype(t2, t1))) { if (!quiet) throw new SemanticException("Error in intersection type. Types " + t1 + " and " + t2 + " are not in subtype relation."); else return false; } } if (t1.toClass().flags().isInterface() && t2.toClass().flags().isInterface() && (t1 instanceof JL5SubstClassType) && (t2 instanceof JL5SubstClassType)) { JL5SubstClassType j5t1 = (JL5SubstClassType) t1; JL5SubstClassType j5t2 = (JL5SubstClassType) t2; if (j5t1.base().equals(j5t2.base()) && !j5t1.equals(j5t2)) { if (!quiet) { throw new SemanticException("Error in intersection type. Interfaces " + j5t1 + " and " + j5t2 + "are instantinations of the same generic interface but with different type arguments"); } else { return false; } } } } return true; } //@Override public List<Type> concreteBounds(List<? extends Type> bounds) { Set<Type> included = new LinkedHashSet<Type>(); Set<Type> visited = new LinkedHashSet<Type>(); List<Type> queue = new ArrayList<Type>(bounds); while (!queue.isEmpty()) { Type t = queue.remove(0); if (visited.contains(t)) continue; visited.add(t); if (t instanceof TypeVariable) { TypeVariable tv = (TypeVariable) t; queue.add(tv.upperBound()); } else if (t instanceof IntersectionType) { IntersectionType it = (IntersectionType) t; queue.addAll(it.bounds()); } else { included.add(t); } } return new ArrayList<Type>(included); } @Override public ReferenceType glb(ReferenceType t1, ReferenceType t2) { return this.glb(t1, t2, true); } protected ReferenceType glb(ReferenceType t1, ReferenceType t2, boolean performIntersectionCheck) { List<ReferenceType> l = new ArrayList<ReferenceType>(); l.add(t1); l.add(t2); return glb(Position.compilerGenerated(), l, performIntersectionCheck); } @Override public ReferenceType glb(Position pos, List<ReferenceType> bounds) { return this.glb(pos, bounds, true); } protected ReferenceType glb(Position pos, List<ReferenceType> bounds, boolean performIntersectionCheck) { if (bounds == null || bounds.isEmpty()) { return this.Object(); } try { // XXX also need to check that does not have two classes that are not in a subclass relation? if (performIntersectionCheck && !this.checkIntersectionBounds(bounds, true)) { return this.Object(); } else { return this.intersectionType(pos, bounds); } } catch (SemanticException e) { return this.Object(); } } @Override public UnknownReferenceType unknownReferenceType(Position position) { return unknownReferenceType; } protected UnknownReferenceType unknownReferenceType = new UnknownReferenceType_c(this); @Override public RawClass rawClass(JL5ParsedClassType base) { return this.rawClass(base, base.position()); } @Override public RawClass rawClass(JL5ParsedClassType base, Position pos) { // if (base.typeVariables().isEmpty()) { // throw new InternalCompilerError("Can only create a raw class with a parameterized class"); return new RawClass_c(base, pos); } @Override public Type toRawType(Type t) { if (!t.isReference()) { return t; } if (t instanceof RawClass) { return t; } if (t instanceof JL5ParsedClassType) { JL5ParsedClassType ct = (JL5ParsedClassType) t; if (!classAndEnclosingTypeVariables(ct).isEmpty()) { return this.rawClass(ct, ct.position()); } else { // neither t nor its containers has type variables return t; } } if (t instanceof ArrayType) { ArrayType at = t.toArray(); Type b = this.toRawType(at.base()); return at.base(b); } return t; } /** * Does pct, or a containing class of pct, have type variables? */ @Override public List<TypeVariable> classAndEnclosingTypeVariables( JL5ParsedClassType ct) { List<TypeVariable> l = new ArrayList<TypeVariable>(); classAndEnclosingTypeVariables(ct, l); return l; } protected void classAndEnclosingTypeVariables(JL5ParsedClassType ct, List<TypeVariable> l) { if (!ct.typeVariables().isEmpty()) { l.addAll(ct.typeVariables()); } if (ct.isTopLevel() || !ct.isNested() || !ct.isInnerClass()) { // either ct is top level, not nested, or it's a static nested. // Ignore any type variables contained in outer classes. return; } if (ct.outer() instanceof JL5ParsedClassType) { classAndEnclosingTypeVariables((JL5ParsedClassType) ct.outer(), l); } } @Override public PrimitiveType promote(Type t1, Type t2) throws SemanticException { return super.promote(unboxingConversion(t1), unboxingConversion(t2)); } @Override public Type boxingConversion(Type t) { if (t.isPrimitive()) { return this.wrapperClassOfPrimitive(t.toPrimitive()); } return t; } @Override public Type unboxingConversion(Type t) { Type s = primitiveTypeOfWrapper(t); if (s != null) { return s; } return t; } @Override public LubType lub(Position pos, List<ReferenceType> us) { return new LubType_c(this, pos, us); } @Override public boolean isValidAnnotationValueType(Type t) { // must be one of primitive, String, Class, enum, annotation or // array of one of these if (t.isPrimitive()) return true; if (t.isClass()) { if (JL5Flags.isEnum(t.toClass().flags()) || JL5Flags.isAnnotation(t.toClass().flags()) || String().equals(t) || Class().equals(t)) { return true; } } // XXX More elegant way to check that t is a parameterized invocation of Class? // See JLS 3rd ed. 9.6, clarified in JLS SE7 ed. 9.6.1 if (erasureType(Class()).equals(erasureType(t))) { return true; } if (t.isArray()) { return isValidAnnotationValueType(t.toArray().base()); } return false; } @Override public void checkAnnotationValueConstant(Term value) throws SemanticException { if (value instanceof ElementValueArrayInit) { // check elements for (Term next : ((ElementValueArrayInit) value).elements()) { if (!isAnnotationValueConstant(next)) { throw new SemanticException("Annotation attribute value must be constant", next.position()); } } } else if (value instanceof AnnotationElem) { return; } else if (!isAnnotationValueConstant(value)) { throw new SemanticException("Annotation attribute value must be constant: " + value, value.position()); } } protected boolean isAnnotationValueConstant(Term value) { if (value == null || value instanceof NullLit || value instanceof ClassLit) { // for purposes of annotation elems class lits are constants // we're ok, try the next one. return true; } if (value instanceof Expr) { Expr ev = (Expr) value; if (ev.constantValueSet() && ev.isConstant()) { // value is a constant return true; } if (ev instanceof EnumConstant) { // Enum constants are constants for our purposes. return true; } if (!ev.constantValueSet()) { // the constant value hasn't been set yet... return true; // TODO: should this throw a missing dependency exception? } } return false; } @Override public void checkDuplicateAnnotations(List<AnnotationElem> annotations) throws SemanticException { // check no duplicate annotations used ArrayList<AnnotationElem> l = new ArrayList<AnnotationElem>(annotations); for (int i = 0; i < l.size(); i++) { AnnotationElem ai = l.get(i); for (int j = i + 1; j < l.size(); j++) { AnnotationElem aj = l.get(j); if (ai.typeName().type() == aj.typeName().type()) { throw new SemanticException("Duplicate annotation use: " + aj.typeName(), aj.position()); } } } } @Override public AnnotationTypeElemInstance annotationElemInstance(Position pos, ClassType ct, Flags f, Type type, java.lang.String name, boolean hasDefault) { assert_(ct); assert_(type); return new AnnotationTypeElemInstance_c(this, pos, ct, f, type, name, hasDefault); } @Override public AnnotationTypeElemInstance findAnnotation(ReferenceType container, String name, ClassType currClass) throws SemanticException { Set<AnnotationTypeElemInstance> annotations = findAnnotations(container, name); if (annotations.size() == 0) { throw new NoMemberException(JL5NoMemberException.ANNOTATION, "Annotation: \"" + name + "\" not found in type \"" + container + "\"."); } Iterator<AnnotationTypeElemInstance> i = annotations.iterator(); AnnotationTypeElemInstance ai = i.next(); if (i.hasNext()) { AnnotationTypeElemInstance ai2 = i.next(); throw new SemanticException("Annotation \"" + name + "\" is ambiguous; it is defined in both " + ai.container() + " and " + ai2.container() + "."); } if (currClass != null && !isAccessible(ai, currClass) && !isInherited(ai, currClass)) { throw new SemanticException("Cannot access " + ai + "."); } return ai; } public Set<AnnotationTypeElemInstance> findAnnotations( ReferenceType container, String name) { assert_(container); if (container == null) { throw new InternalCompilerError("Cannot access annotation \"" + name + "\" within a null container type."); } AnnotationTypeElemInstance ai = ((JL5ParsedClassType) container).annotationElemNamed(name); if (ai != null) { return Collections.singleton(ai); } return new HashSet<AnnotationTypeElemInstance>(); } @Override public Type Class(Position pos, ReferenceType type) { try { return this.instantiate(pos, (JL5ParsedClassType) this.Class(), Collections.singletonList(type)); } catch (SemanticException e) { throw new InternalCompilerError("Couldn't create class java.lang.Class<" + type + ">", e); } } @Override public boolean isReifiable(Type t) { if (t.isPrimitive() || t.isNull()) { return true; } if (t instanceof RawClass) { return isContainerReifiable(t.toClass()); } if (t instanceof JL5ParsedClassType) { JL5ParsedClassType pct = (JL5ParsedClassType) t; return pct.typeVariables().isEmpty() && isContainerReifiable(t.toClass()); } if (t instanceof ArrayType) { return isReifiable(((ArrayType) t).base()); } if (t instanceof JL5SubstClassType) { JL5SubstClassType ct = (JL5SubstClassType) t; for (ReferenceType a : ct.actuals()) { if (a instanceof WildCardType) { WildCardType wc = (WildCardType) a; if (!wc.hasLowerBound() && wc.upperBound().equals(Object())) { // the actual is an unbounded wildcard, and so is reifiable continue; } } // actual a is not an unbounded wildcard. This type is not reifiable. return false; } return isContainerReifiable(t.toClass()); } return false; } /** * If ct is an inner class, then check that the container of ct is reifiable. * @param ct * @return */ private boolean isContainerReifiable(ClassType ct) { if (!ct.isInnerClass()) { // we don't care if the container is reifiable return true; } return isReifiable(ct.container()); } @Override public ClassType instantiateInnerClassFromContext(Context c, ClassType ct) { ReferenceType outer = ct.outer(); // Find the container in the context while (c != null) { ClassType fromCtx = c.currentClass(); while (fromCtx != null) { if (fromCtx instanceof JL5SubstClassType) { JL5SubstClassType sct = (JL5SubstClassType) fromCtx; ClassType rawCT = sct.base(); if (outer.equals(rawCT)) { return (ClassType) sct.subst().substType(ct); } } else if (fromCtx instanceof JL5ParsedClassType) { if (outer.equals(fromCtx)) { // nothing to substitute return ct; } } fromCtx = (ClassType) fromCtx.superType(); } c = c.pop(); } // XXX: Couldn't find container, why are we here? return ct; // throw new InternalCompilerError( // "Could not find container of inner class " // + ct + " in current context"); } @Override public Annotations createAnnotations( Map<Type, Map<java.lang.String, AnnotationElementValue>> annotationElems, Position pos) { return new Annotations_c(annotationElems, this, pos); } /** * Given an annotation of type annotationType, should the annotation * be retained in the binary? See JLS 3rd ed, 9.6.1.2 */ @Override public boolean isRetainedAnnotation(Type annotationType) { if (annotationType.isClass() && annotationType.toClass().isSubtype(this.Annotation())) { // well, it's an annotation type at least. // check if there is a retention policy on it. JL5ClassType ct = (JL5ClassType) annotationType.toClass(); Annotations ra = ct.annotations(); if (ra == null) { // by default, use RetentionPolicy.CLASS return true; } AnnotationElementValue v = ra.singleElement(RetentionAnnotation()); if (v == null) { // by default, use RetentionPolicy.CLASS return true; } if (v instanceof AnnotationElementValueConstant) { AnnotationElementValueConstant c = (AnnotationElementValueConstant) v; EnumInstance ei = (EnumInstance) c.constantValue(); if (ei.name().equalsIgnoreCase("CLASS") || ei.name().equalsIgnoreCase("RUNTIME")) { return true; } else { return false; } } return true; } return false; } @Override public Annotations NoAnnotations() { return new Annotations_c(this, Position.compilerGenerated(1)); } @Override public AnnotationElementValueArray AnnotationElementValueArray( Position pos, List<AnnotationElementValue> vals) { return new AnnotationElementValueArray_c(this, pos, vals); } @Override public AnnotationElementValueAnnotation AnnotationElementValueAnnotation( Position pos, Type annotationType, Map<String, AnnotationElementValue> annotationElementValues) { return new AnnotationElementValueAnnotation_c(this, pos, annotationType, annotationElementValues); } @Override public AnnotationElementValueConstant AnnotationElementValueConstant( Position pos, Type type, Object constVal) { return new AnnotationElementValueConstant_c(this, pos, type, constVal); } @Override public Type leastCommonAncestor(Type type1, Type type2) throws SemanticException { if (type1.isPrimitive() && (type2.isReference() || type2.isNull())) { // box type1, i.e. promote to an object return leastCommonAncestor(this.boxingConversion(type1), type2); } if (type2.isPrimitive() && (type1.isReference() || type1.isNull())) { // box type2, i.e. promote to an object return leastCommonAncestor(type1, this.boxingConversion(type2)); } return super.leastCommonAncestor(type1, type2); } }
package org.usfirst.frc.team4828; public class Ports { // PWM public static final int INTAKE = 9; public static final int CLIMBER = 8; public static final int AGITATOR_LEFT = 6; public static final int AGITATOR_RIGHT = 7; // Drivetrain public static final int DT_FRONT_LEFT = 1; public static final int DT_BACK_LEFT = 2; public static final int DT_FRONT_RIGHT = 3; public static final int DT_BACK_RIGHT = 4; // Shooter public static final int SERVO_LEFT_MASTER = 4; public static final int SERVO_LEFT_SLAVE = 5; public static final int SERVO_RIGHT_MASTER = 2; public static final int SERVO_RIGHT_SLAVE = 3; public static final int MOTOR_LEFT = 1; public static final int MOTOR_RIGHT = 2; public static final int INDEXER_RIGHT = 10; // use port 0 on the navx as port 10 public static final int INDEXER_LEFT = 11; // use port 1 on the navx as port 11 // Sensors public static final int IR_CHANNEL = 2; public static final int US_CHANNEL = 0; // Analog private Ports() { throw new AssertionError( "A Summoner has Disconnected.\n" + "(Assertion Error 'cause you instantiated class Ports.\n" + "What part of private don't you understand, Nikhil...\n" + "Sigh.)\n" ); } }
package se.tla.mavenversionbumper; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.*; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.AutoCloseInputStream; import org.jdom.JDOMException; import se.tla.mavenversionbumper.vcs.AbstractVersionControl; import se.tla.mavenversionbumper.vcs.Clearcase; import se.tla.mavenversionbumper.vcs.Git; import se.tla.mavenversionbumper.vcs.VersionControl; import bsh.EvalError; import bsh.Interpreter; /** * Command line interface for the version bumper. */ public class Main { private static final List<Module> modulesLoadedForUpdate = new LinkedList<Module>(); private static String baseDir; private static VersionControl versionControl; private static final Map<String, Class<? extends VersionControl>> versionControllers; static { versionControllers = new HashMap<String, Class<? extends VersionControl>>(); // Only lower case names. versionControllers.put("git", Git.class); versionControllers.put("clearcase", Clearcase.class); } enum Option { DRYRUN("Dry run. Don't modify anything, only validate configuration.", "d", "dry-run"), REVERT("Revert any uncommited changes.", "r", "revert"), PREPARETEST("Prepare module(s) for a test build.", "p", "prepare-test-build"), WARNOFSNAPSHOTS("Searches for any SNAPSHOT dependencies and warns about them. Works great with --dry-run.", "w", "warn-snapshots"), HELP("Show help.", "h", "?", "help"); private final String helpText; private final String[] aliases; Option(String helpText, String... aliases) { this.helpText = helpText; this.aliases = aliases; } public List<String> getAliases() { return Arrays.asList(aliases); } public String getHelpText() { return helpText; } public boolean presentIn(OptionSet o) { return o.has(aliases[0]); } } enum TYPE { NORMAL, DRYRUN, REVERT, PREPARETEST } public static void main(String args[]) { OptionParser parser = new OptionParser() { { acceptsAll(Option.DRYRUN.getAliases(), Option.DRYRUN.getHelpText()); acceptsAll(Option.REVERT.getAliases(), Option.REVERT.getHelpText()); acceptsAll(Option.PREPARETEST.getAliases(), Option.PREPARETEST.getHelpText()); acceptsAll(Option.WARNOFSNAPSHOTS.getAliases(), Option.WARNOFSNAPSHOTS.getHelpText()); acceptsAll(Option.HELP.getAliases(), Option.HELP.getHelpText()); } }; OptionSet options = null; try { options = parser.parse(args); } catch (OptionException e) { System.err.println(e.getMessage()); System.exit(1); } if (Option.HELP.presentIn(options)) { try { parser.printHelpOn(System.out); } catch (IOException e) { System.err.println("Error printing help text: " + e.getMessage()); System.exit(1); } System.exit(0); } if (Option.DRYRUN.presentIn(options) && Option.REVERT.presentIn(options)) { System.err.println("Only one of --dry-run/-d and --revert/-r"); System.exit(1); } List<String> arguments = options.nonOptionArguments(); if (arguments.size() < 2 || arguments.size() > 3) { System.err.println("Usage: [-d | --dry-run] [-r | --revert] [-p | --prepare-test-build] [-w | --warn-snapshot] [-h | --help] <base directory> <scenarioFile> [<VC properties file>]"); System.exit(1); } baseDir = arguments.get(0); String scenarioFileName = arguments.get(1); Properties versionControlProperties; if (arguments.size() == 3) { try { String versionControlParameter = arguments.get(2); versionControlProperties = new Properties(); versionControlProperties.load(new AutoCloseInputStream(new FileInputStream(versionControlParameter))); String versionControlName = versionControlProperties.getProperty(AbstractVersionControl.VERSIONCONTROL, "").toLowerCase(); Class<? extends VersionControl> versionControlClass = versionControllers.get(versionControlName); if (versionControlClass == null) { System.err.println("No such version control: " + versionControlName); System.exit(1); } versionControl = versionControlClass.getConstructor(Properties.class).newInstance(versionControlProperties); } catch (Exception e) { System.err.println("Error starting up the version control"); e.printStackTrace(); System.exit(1); } } File scenarioFile = new File(scenarioFileName); if (!(scenarioFile.isFile() && scenarioFile.canRead())) { System.err.println("Scenario file " + scenarioFileName + " isn't a readable file."); System.exit(1); } if (Option.REVERT.presentIn(options) && versionControl == null) { System.err.println("Version control has to be defined while reverting."); System.exit(1); } TYPE type = TYPE.NORMAL; if (Option.DRYRUN.presentIn(options)) { type = TYPE.DRYRUN; } if (Option.REVERT.presentIn(options)) { type = TYPE.REVERT; } if (Option.PREPARETEST.presentIn(options)) { type = TYPE.PREPARETEST; } try { String scenario = FileUtils.readFileToString(scenarioFile); Interpreter i = new Interpreter(); i.eval("importCommands(\"se.tla.mavenversionbumper.commands\")"); i.eval("import se.tla.mavenversionbumper.Main"); i.eval("import se.tla.mavenversionbumper.Module"); i.eval("import se.tla.mavenversionbumper.ReadonlyModule"); i.eval("baseDir = \"" + baseDir + "\""); i.eval("load(String moduleName) { return Main.load(moduleName, null, null); }"); i.eval("load(String moduleName, String newVersion) { return Main.load(moduleName, newVersion, null); }"); i.eval("load(String moduleName, String newVersion, String label) { return Main.load(moduleName, newVersion, label); }"); i.eval("loadReadOnly(String groupId, String artifactId, String version) { return new ReadonlyModule(groupId, artifactId, version); }"); i.eval(scenario); if (Option.WARNOFSNAPSHOTS.presentIn(options)) { for (Module module : modulesLoadedForUpdate) { List<String> result = module.findSnapshots(); if (result.size() > 0) { System.out.println("SNAPSHOTS found in module " + module.gav()); for (String s : result) { System.out.println(" " + s); } } } } if (type.equals(TYPE.NORMAL) || type.equals(TYPE.PREPARETEST)) { if (versionControl != null) { // Prepare for saving for (Module module : modulesLoadedForUpdate) { versionControl.prepareSave(module); } } // Save for (Module module : modulesLoadedForUpdate) { module.save(); } } if (type.equals(TYPE.NORMAL)) { if (versionControl != null) { // Commit for (Module module : modulesLoadedForUpdate) { versionControl.commit(module); } // Label versionControl.label(modulesLoadedForUpdate); } } if (type.equals(TYPE.REVERT)) { if (versionControl != null) { for (Module module : modulesLoadedForUpdate) { versionControl.restore(module); } } } } catch (EvalError evalError) { evalError.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Create a Module located by this filename that is a directory relative to the baseDir. * * @param moduleDirectoryName Name of base directory for the module. * @param newVersion New version to set directly, of null if no version should be set. * @param label New label to set directly, or null if no labeling should be performed. * @return Newly created Module. * @throws JDOMException If the modules pom.xml couldn't be parsed. * @throws IOException if the modules pom.xml couldn't be read. */ public static Module load(String moduleDirectoryName, String newVersion, String label) throws JDOMException, IOException { Module m = new Module(baseDir, moduleDirectoryName); if (newVersion != null) { System.out.println("ORG: " + m.gav()); m.version(newVersion); } if (label != null) { m.label(label); } if (newVersion != null) { System.out.println("NEW: " + m.gav() + (label != null ? " (" + label + ")" : "")); } modulesLoadedForUpdate.add(m); return m; } }
package seedu.doist.model; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import javafx.collections.transformation.FilteredList; import seedu.doist.commons.core.ComponentManager; import seedu.doist.commons.core.Config; import seedu.doist.commons.core.LogsCenter; import seedu.doist.commons.core.UnmodifiableObservableList; import seedu.doist.commons.events.config.AbsoluteStoragePathChangedEvent; import seedu.doist.commons.events.model.AliasListMapChangedEvent; import seedu.doist.commons.events.model.TodoListChangedEvent; import seedu.doist.commons.util.CollectionUtil; import seedu.doist.commons.util.ConfigUtil; import seedu.doist.commons.util.History; import seedu.doist.commons.util.StringUtil; import seedu.doist.logic.commands.ListCommand.TaskType; import seedu.doist.logic.commands.SortCommand.SortType; import seedu.doist.model.tag.Tag; import seedu.doist.model.tag.UniqueTagList; import seedu.doist.model.task.ReadOnlyTask; import seedu.doist.model.task.ReadOnlyTask.ReadOnlyTaskAlphabetComparator; import seedu.doist.model.task.ReadOnlyTask.ReadOnlyTaskCombinedComparator; import seedu.doist.model.task.ReadOnlyTask.ReadOnlyTaskPriorityComparator; import seedu.doist.model.task.ReadOnlyTask.ReadOnlyTaskTimingComparator; import seedu.doist.model.task.Task; import seedu.doist.model.task.UniqueTaskList; import seedu.doist.model.task.UniqueTaskList.TaskAlreadyFinishedException; import seedu.doist.model.task.UniqueTaskList.TaskAlreadyUnfinishedException; import seedu.doist.model.task.UniqueTaskList.TaskNotFoundException; /** * Represents the in-memory model of the to-do list data. * All changes to any model should be synchronized. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); private final TodoList todoList; private final Config config; private final History<TodoList> todoListHistory = new History<TodoList>(); private final AliasListMap aliasListMap; private final FilteredList<ReadOnlyTask> filteredTasks; //@@author A0140887W /** * Initializes a ModelManager with the given to-do list and userPrefs. */ public ModelManager(ReadOnlyTodoList todoList, ReadOnlyAliasListMap aliasListMap, UserPrefs userPrefs, Config config, boolean isTest) { super(); assert !CollectionUtil.isAnyNull(todoList, aliasListMap, userPrefs, config); logger.fine("Initializing with To-do List: " + todoList + " aliasListMap: " + aliasListMap + " and user prefs " + userPrefs + " and config: " + config); this.todoList = new TodoList(todoList); this.aliasListMap = new AliasListMap(aliasListMap); this.config = config; filteredTasks = new FilteredList<>(this.todoList.getTaskList()); if (!isTest) { updateFilteredListToShowDefault(); sortTasksByDefault(); } saveCurrentToHistory(); } public ModelManager() { this(new TodoList(), new AliasListMap(), new UserPrefs(), new Config(), false); } public ModelManager(ReadOnlyTodoList todoList, ReadOnlyAliasListMap aliasListMap, UserPrefs userPrefs, Config config) { this(todoList, aliasListMap, userPrefs, config, false); } /** Raises an event to indicate the alias list model has changed */ @Override public ReadOnlyAliasListMap getAliasListMap() { return aliasListMap; } @Override public void setAlias(String alias, String commandWord) { aliasListMap.setAlias(alias, commandWord); indicateAliasListMapChanged(); } @Override public void removeAlias(String alias) { aliasListMap.removeAlias(alias); indicateAliasListMapChanged(); } @Override public List<String> getAliasList(String defaultCommandWord) { return aliasListMap.getAliasList(defaultCommandWord); } @Override public List<String> getValidCommandList(String defaultCommandWord) { List<String> list = new ArrayList<String>(aliasListMap.getAliasList(defaultCommandWord)); list.add(defaultCommandWord); return list; } @Override public Set<String> getDefaultCommandWordSet() { return aliasListMap.getDefaultCommandWordSet(); } @Override public void resetToDefaultCommandWords() { aliasListMap.setDefaultAliasListMapping(); } private void indicateAliasListMapChanged() { raise(new AliasListMapChangedEvent(aliasListMap)); } //@@author @Override public void resetData(ReadOnlyTodoList newData) { todoList.resetData(newData); indicateTodoListChanged(); } @Override public ReadOnlyTodoList getTodoList() { return todoList; } /** Raises an event to indicate the model has changed */ private void indicateTodoListChanged() { raise(new TodoListChangedEvent(todoList)); } @Override public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException { todoList.removeTask(target); indicateTodoListChanged(); } //@@author A0140887W @Override public synchronized void finishTask(ReadOnlyTask target) throws TaskNotFoundException, TaskAlreadyFinishedException { assert target != null; try { todoList.changeTaskFinishStatus(target, true); } catch (TaskAlreadyUnfinishedException e) { assert false : "finishTask should not try to unfinish tasks!"; } indicateTodoListChanged(); } @Override public synchronized void unfinishTask(ReadOnlyTask target) throws TaskNotFoundException, TaskAlreadyUnfinishedException { try { todoList.changeTaskFinishStatus(target, false); } catch (TaskAlreadyFinishedException e) { assert false : "unfinishTask should not try to finish tasks!"; } indicateTodoListChanged(); } //@@author @Override public synchronized int addTask(Task task) throws UniqueTaskList.DuplicateTaskException { int index = todoList.addTask(task); updateFilteredListToShowDefault(); indicateTodoListChanged(); return index; } @Override public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask) throws UniqueTaskList.DuplicateTaskException { assert editedTask != null; int todoListIndex = filteredTasks.getSourceIndex(filteredTaskListIndex); todoList.updateTask(todoListIndex, editedTask); updateFilteredListToShowDefault(); indicateTodoListChanged(); } //@@author A0140887W @Override public void sortTasks(List<SortType> sortTypes) { List<Comparator<ReadOnlyTask>> comparatorList = new ArrayList<Comparator<ReadOnlyTask>>(); for (SortType type : sortTypes) { if (type.equals(SortType.PRIORITY)) { comparatorList.add(new ReadOnlyTaskPriorityComparator()); } else if (type.equals(SortType.TIME)) { comparatorList.add(new ReadOnlyTaskTimingComparator()); } else if (type.equals(SortType.ALPHA)) { comparatorList.add(new ReadOnlyTaskAlphabetComparator()); } } todoList.sortTasks(new ReadOnlyTaskCombinedComparator(comparatorList)); } public void sortTasksByDefault() { List<SortType> sortTypes = new ArrayList<SortType>(); sortTypes.add(SortType.TIME); sortTypes.add(SortType.PRIORITY); sortTypes.add(SortType.ALPHA); sortTasks(sortTypes); } //@@author A0147620L public ArrayList<String> getAllNames() { return todoList.getTaskNames(); } //@@author @Override public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() { return new UnmodifiableObservableList<>(filteredTasks); } @Override public void updateFilteredListToShowAll() { filteredTasks.setPredicate(null); } //@@author A0140887W @Override public void updateFilteredListToShowDefault() { filteredTasks.setPredicate(null); Qualifier[] qualifiers = {new TaskTypeQualifier(TaskType.NOT_FINISHED)}; updateFilteredTaskList(new PredicateExpression(qualifiers)); } //@@author @Override public void updateFilteredTaskList(Set<String> keywords) { Qualifier[] qualifiers = {new DescriptionQualifier(keywords)}; updateFilteredTaskList(new PredicateExpression(qualifiers)); } @Override public void updateFilteredTaskList(TaskType type, UniqueTagList tags) { ArrayList<Qualifier> qualifiers = new ArrayList<Qualifier>(); if (type != null) { qualifiers.add(new TaskTypeQualifier(type)); } if (!tags.isEmpty()) { qualifiers.add(new TagQualifier(tags)); } updateFilteredTaskList(new PredicateExpression(qualifiers.toArray(new Qualifier[qualifiers.size()]))); } private void updateFilteredTaskList(Expression expression) { filteredTasks.setPredicate(expression::satisfies); } interface Expression { boolean satisfies(ReadOnlyTask task); String toString(); } private class PredicateExpression implements Expression { private final Qualifier[] qualifiers; PredicateExpression(Qualifier[] qualifiers) { this.qualifiers = qualifiers; } @Override public boolean satisfies(ReadOnlyTask task) { boolean isSatisfied = true; for (Qualifier qualifier : qualifiers) { isSatisfied = isSatisfied && qualifier.run(task); } return isSatisfied; } @Override public String toString() { return qualifiers.toString(); } } interface Qualifier { boolean run(ReadOnlyTask task); String toString(); } private class DescriptionQualifier implements Qualifier { private Set<String> descriptionKeyWords; DescriptionQualifier(Set<String> descKeyWords) { this.descriptionKeyWords = descKeyWords; } @Override public boolean run(ReadOnlyTask task) { return descriptionKeyWords.stream() .filter(keyword -> ((Double.compare(org.apache.commons.lang3.StringUtils. getJaroWinklerDistance(task.getDescription().desc, keyword), 0.90) >= 0) || (StringUtils.containsIgnoreCase(task.getDescription().desc, keyword)))) .findAny() .isPresent(); } @Override public String toString() { return "desc=" + String.join(", ", descriptionKeyWords); } } private class TagQualifier implements Qualifier { private UniqueTagList tags; public TagQualifier(UniqueTagList tags2) { this.tags = tags2; } @Override public boolean run(ReadOnlyTask task) { for (Tag tag : tags) { if (task.getTags().contains(tag)) { return true; } } return false; } } //@@author A0147980U private class TaskTypeQualifier implements Qualifier { private TaskType type; public TaskTypeQualifier(TaskType type) { this.type = type; } @Override public boolean run(ReadOnlyTask task) { switch (type) { case FINISHED: return task.getFinishedStatus().getIsFinished(); case PENDING: return !task.getFinishedStatus().getIsFinished() && !task.isOverdue(); case OVERDUE: return task.isOverdue(); case NOT_FINISHED: return !task.getFinishedStatus().getIsFinished(); default: return true; } } } public void saveCurrentToHistory() { todoListHistory.forgetStatesAfter(); TodoList toSave = new TodoList(); toSave.resetData(todoList); todoListHistory.addToHistory(toSave); } public void recoverPreviousTodoList() { boolean isAtMostRecentState = todoListHistory.isAtMostRecentState(); TodoList previousTodoList = todoListHistory.getPreviousState(); if (previousTodoList != null) { todoList.resetData(previousTodoList); } if (isAtMostRecentState) { recoverPreviousTodoList(); } indicateTodoListChanged(); } public void recoverNextTodoList() { TodoList nextTodoList = todoListHistory.getNextState(); if (nextTodoList != null) { todoList.resetData(nextTodoList); } indicateTodoListChanged(); } @Override public void changeConfigAbsolutePath(Path path) { config.setAbsoluteStoragePath(path.toString()); try { ConfigUtil.saveConfig(config, ConfigUtil.getConfigPath()); indicateAbsoluteStoragePathChanged(); } catch (IOException e) { logger.warning("Failed to save config file : " + StringUtil.getDetails(e)); } } /** Raises an event to indicate the absolute storage path has changed */ private void indicateAbsoluteStoragePathChanged() { raise(new AbsoluteStoragePathChangedEvent(config.getAbsoluteTodoListFilePath(), config.getAbsoluteAliasListMapFilePath(), config.getAbsoluteUserPrefsFilePath())); } }
package sklearn2pmml.decoration; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Collection; import java.util.Collections; import java.util.GregorianCalendar; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.google.common.base.Function; import com.google.common.collect.Lists; import net.razorvine.pickle.objects.ClassDict; import org.dmg.pmml.Counts; import org.dmg.pmml.DataField; import org.dmg.pmml.DataType; import org.dmg.pmml.FieldName; import org.dmg.pmml.InvalidValueTreatmentMethod; import org.dmg.pmml.MissingValueTreatmentMethod; import org.dmg.pmml.OpType; import org.dmg.pmml.Value; import org.jpmml.converter.Feature; import org.jpmml.converter.InvalidValueDecorator; import org.jpmml.converter.MissingValueDecorator; import org.jpmml.converter.PMMLUtil; import org.jpmml.converter.WildcardFeature; import org.jpmml.python.CalendarUtil; import org.jpmml.python.ClassDictUtil; import org.jpmml.python.HasArray; import org.jpmml.sklearn.SkLearnEncoder; import sklearn.Transformer; abstract public class Domain extends Transformer { public Domain(String module, String name){ super(module, name); } @Override public List<Feature> encodeFeatures(List<Feature> features, SkLearnEncoder encoder){ MissingValueTreatmentMethod missingValueTreatment = DomainUtil.parseMissingValueTreatment(getMissingValueTreatment()); Object missingValueReplacement = getMissingValueReplacement(); List<?> missingValues = getMissingValues(); if(missingValueReplacement != null){ if(missingValueTreatment == null){ missingValueTreatment = MissingValueTreatmentMethod.AS_VALUE; } } InvalidValueTreatmentMethod invalidValueTreatment = DomainUtil.parseInvalidValueTreatment(getInvalidValueTreatment()); Object invalidValueReplacement = getInvalidValueReplacement(); if(invalidValueReplacement != null){ if(invalidValueTreatment == null){ invalidValueTreatment = InvalidValueTreatmentMethod.AS_IS; } } List<String> displayName = getDisplayName(); if(displayName != null){ ClassDictUtil.checkSize(features, displayName); } for(int i = 0; i < features.size(); i++){ Feature feature = features.get(i); WildcardFeature wildcardFeature = asWildcardFeature(feature); DataField dataField = wildcardFeature.getField(); DataType dataType = dataField.getDataType(); if(missingValueTreatment != null){ Object pmmlMissingValueReplacement = (missingValueReplacement != null ? standardizeValue(dataType, missingValueReplacement) : null); encoder.addDecorator(dataField, new MissingValueDecorator(missingValueTreatment, pmmlMissingValueReplacement)); } // End if if(missingValues != null){ PMMLUtil.addValues(dataField, standardizeValues(dataType, missingValues), Value.Property.MISSING); } // End if if(invalidValueTreatment != null){ Object pmmlInvalidValueReplacement = (invalidValueReplacement != null ? standardizeValue(dataType, invalidValueReplacement) : null); encoder.addDecorator(dataField, new InvalidValueDecorator(invalidValueTreatment, pmmlInvalidValueReplacement)); } // End if if(displayName != null){ dataField.setDisplayName(displayName.get(i)); } } return features; } @Override public DataField updateDataField(DataField dataField, OpType opType, DataType dataType, SkLearnEncoder encoder){ FieldName name = dataField.getName(); if(encoder.isFrozen(name)){ throw new IllegalArgumentException("Field " + name.getValue() + " is frozen for type information updates"); } dataField .setDataType(dataType) .setOpType(opType); encoder.setDomain(name, this); return dataField; } public Object getDType(){ Object dtype = get("dtype"); if(dtype == null){ return null; } return super.getDType(true); } public String getMissingValueTreatment(){ return getOptionalString("missing_value_treatment"); } public Object getMissingValueReplacement(){ return getOptionalScalar("missing_value_replacement"); } public List<Object> getMissingValues(){ Object missingValues = getOptionalObject("missing_values"); if(missingValues != null){ // SkLearn2PMML 0.38.0 if(!(missingValues instanceof List)){ return Collections.singletonList(missingValues); } // SkLearn2PMML 0.38.1+ return (List)missingValues; } return null; } public String getInvalidValueTreatment(){ return getOptionalString("invalid_value_treatment"); } public Object getInvalidValueReplacement(){ return getOptionalScalar("invalid_value_replacement"); } public Boolean getWithData(){ return getOptionalBoolean("with_data", Boolean.TRUE); } public Boolean getWithStatistics(){ return getOptionalBoolean("with_statistics", Boolean.FALSE); } public List<String> getDisplayName(){ if(!containsKey("display_name")){ return null; } Object object = get("display_name"); if(object == null){ return null; } else // XXX if(object instanceof String){ return Collections.singletonList((String)object); } return getListLike("display_name", String.class); } public Map<String, ?> getCounts(){ return getDict("counts_"); } static public Counts createCounts(Map<String, ?> values){ Counts counts = new Counts() .setTotalFreq(selectValue(values, "totalFreq", 0)) .setMissingFreq(selectValue(values, "missingFreq")) .setInvalidFreq(selectValue(values, "invalidFreq")); return counts; } static protected Map<String, ?> extractMap(Map<String, ?> map, int index){ Map<String, Object> result = new LinkedHashMap<>(); Collection<? extends Map.Entry<String, ?>> entries = map.entrySet(); for(Map.Entry<String, ?> entry : entries){ String key = entry.getKey(); List<?> value = asArray(entry.getValue()); result.put(key, value.get(index)); } return result; } static protected Number selectValue(Map<String, ?> values, String key){ return selectValue(values, key, null); } static protected Number selectValue(Map<String, ?> values, String key, Number defaultValue){ Number value = (Number)values.get(key); if(value == null){ return defaultValue; } return value; } static protected WildcardFeature asWildcardFeature(Feature feature){ if(feature instanceof WildcardFeature){ WildcardFeature wildcardFeature = (WildcardFeature)feature; return wildcardFeature; } throw new IllegalArgumentException("Field " + feature.getName() + " is not decorable"); } static protected List<?> asArray(Object object){ if(object instanceof HasArray){ HasArray hasArray = (HasArray)object; return hasArray.getArrayContent(); } // End if if(object instanceof Number){ return Collections.singletonList(object); } throw new IllegalArgumentException(ClassDictUtil.formatClass(object) + " is not a supported array type"); } static protected Object standardizeValue(DataType dataType, Object value){ switch(dataType){ case DATE: return CalendarUtil.toLocalDate((GregorianCalendar)value); case DATE_TIME: return CalendarUtil.toLocalDateTime((GregorianCalendar)value); default: return checkValue(value); } } static protected List<?> standardizeValues(DataType dataType, List<?> values){ Function<Object, Object> function; switch(dataType){ case DATE: function = new Function<Object, Object>(){ @Override public LocalDate apply(Object object){ return CalendarUtil.toLocalDate((GregorianCalendar)object); } }; break; case DATE_TIME: function = new Function<Object, Object>(){ @Override public LocalDateTime apply(Object object){ return CalendarUtil.toLocalDateTime((GregorianCalendar)object); } }; break; default: function = new Function<Object, Object>(){ @Override public Object apply(Object object){ return checkValue(object); } }; break; } return Lists.transform(values, function); } static public Object checkValue(Object object){ if(object instanceof ClassDict){ ClassDict classDict = (ClassDict)object; throw new IllegalArgumentException("Expected Java primitive value, got Python class " + classDict.getClassName() + " value"); } return object; } }
package starpunk.services; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.utils.Disposable; import java.util.HashMap; import java.util.Map; public final class AssetManager implements Disposable { private final HashMap<String, TextureAtlas.AtlasRegion> _sprites = new HashMap<String, TextureAtlas.AtlasRegion>(); private final HashMap<String, TextureAtlas> _textures = new HashMap<String, TextureAtlas>(); private Texture _background; public void initialize() { final String textureName = "target/assets/game"; final TextureAtlas textureAtlas = new TextureAtlas( Gdx.files.local( textureName ) ); for( final TextureAtlas.AtlasRegion r : textureAtlas.getRegions() ) { _sprites.put( r.name, r ); } _textures.put( textureName, textureAtlas ); _background = new Texture( Gdx.files.local( "assets/images/backgrounds/splash.gif" ) ); _background.setFilter( Texture.TextureFilter.Linear, Texture.TextureFilter.Linear ); } public void dispose() { for( final Map.Entry<String, TextureAtlas> entry : _textures.entrySet() ) { entry.getValue().dispose(); } _textures.clear(); _sprites.clear(); _background.dispose(); } public Texture getBackground() { return _background; } public TextureAtlas.AtlasRegion getSprite( final String name ) { return _sprites.get( name ); } }
package team.unstudio.udpl.util; import javax.annotation.Nullable; import com.google.common.base.Strings; public final class Result { private static final Result SUCCESS_RESULT = new Result(true); public static Result success() { return SUCCESS_RESULT; } public static Result failure() { return new Result(false); } public static Result failure(String message) { return new Result(false, message); } public static Result failure(Throwable throwable) { return new Result(false, throwable); } public static Result failure(String message, Throwable throwable) { return new Result(false, message, throwable); } private final boolean success; private final String message; private final Throwable throwable; private Result(boolean success) { this(success, null, null); } private Result(boolean success, String message) { this(success, message, null); } private Result(boolean success, Throwable throwable) { this(success, null, throwable); } private Result(boolean success, String message, Throwable throwable) { this.success = success; this.message = Strings.nullToEmpty(message); this.throwable = throwable; } public boolean isSuccess() { return success; } public boolean isFailure() { return !success; } public String getMessage() { return message; } @Nullable public Throwable getThrowable() { return throwable; } }
package wasdev.sample.servlet; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URLDecoder; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import biweekly.Biweekly; import biweekly.ICalendar; import biweekly.component.VEvent; import biweekly.property.Classification; import biweekly.property.Method; import biweekly.property.Transparency; import dhbw.timetable.rapla.data.event.Appointment; import dhbw.timetable.rapla.date.DateUtilities; import dhbw.timetable.rapla.exceptions.NoConnectionException; import dhbw.timetable.rapla.network.BaseURL; import dhbw.timetable.rapla.parser.DataImporter; import javax.servlet.annotation.MultipartConfig; @WebServlet("/Rablabla") @MultipartConfig public class Rablabla extends HttpServlet { private static final long serialVersionUID = -8874059585924245331L; private static final String ROOT_PATH = "/home/vcap/app/wlp/usr/servers/defaultServer/apps/Rablabla.war/"; // by Bluemix private static final String ICS_FILENAME = "calendar.ics"; // calendar.ics has highest compatibility private static final File TASKS_FILE = new File(ROOT_PATH, "tasks"); private static final long WORKER_FREQUENCY = 6 * 60 * 60 * 1000; // ms => toogle sync every 6h private static final long MAX_TASK_CALLS = 3000; // Tasks are deleted from list after 3000 generations private Timer worker; /** * Gets appointments of a week in JSON format. The day param should be the monday of the week. * * @param int day * @param int month * @param int year * @param String url */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { assert ForceSSL(request, response) : "SSL/HTTPS Connection error"; response.setContentType("text/html; charset=UTF-8"); // Get request parameters final int day = Integer.parseInt(request.getParameter("day")); final int month = Integer.parseInt(request.getParameter("month")); final int year = Integer.parseInt(request.getParameter("year")); final String url = URLDecoder.decode(request.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); try { LocalDate week = DateUtilities.Normalize(LocalDate.of(year, month, day)); // Load data Map<LocalDate, ArrayList<Appointment>> data = DataImporter.ImportWeekRange(week, week, url); // Push data into JSON response.getWriter().print(JSONUtilities.ToJSONArray(data.get(week)).toString()); } catch (IllegalAccessException | NoConnectionException e) { e.printStackTrace(); } } /** * Generates an .ics file in the web storage. * Every calendar contains * every appointment from the course over one year. * * Example: * * abcdefghijklmnopqrstuvwxyz/calendar.ics * * @param String url */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { assert ForceSSL(request, response) : "SSL/HTTPS Connection error"; response.setContentType("text/html; charset=UTF-8"); // Get request parameters final String url = URLDecoder.decode(request.getParameter("url").replace("+", "%2B"), "UTF-8").replace("%2B", "+"); final String deSuffix = ".de/rapla?", cityPrefix = "dhbw-"; int urlSplit = url.indexOf(deSuffix); final String regularPrefix = url.substring(0, url.indexOf(cityPrefix)); String baseURL = url.substring(regularPrefix.length() + cityPrefix.length(), urlSplit).toUpperCase(), args = url.substring(urlSplit + deSuffix.length()); String key = getParams(args).get("key"); final String fileLocation = baseURL + "/" + key + "/"; try { if (!isICSFilePresent(new String[]{ key, baseURL })) { // Load data System.out.println("Fetching ICS data..."); final Map<LocalDate, ArrayList<Appointment>> data = DataImporter.ImportWeekRange(LocalDate.of(LocalDate.now().getYear(), 1, 1), LocalDate.of(LocalDate.now().getYear(), 12, 31), BaseURL.valueOf(baseURL), args); System.out.println("Done fetching data!"); final File containerFile = new File(ROOT_PATH + fileLocation); containerFile.mkdirs(); final File exportFile = new File(containerFile, ICS_FILENAME); System.out.println("Don't have requested ICS file: " + exportFile.getAbsolutePath() + " - generating..."); // Put it on global list if (!TASKS_FILE.exists()) { TASKS_FILE.createNewFile(); } // Extended tasklist BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(TASKS_FILE, true), "UTF-8")); bw.append(MAX_TASK_CALLS + "\t" + key + "\t" + baseURL + "\n"); bw.close(); generateICSFile(exportFile, data); } else { System.out.println("Already having this ICS file, wait for worker please!"); } System.out.println("Done creating ICS file!"); response.getWriter().println(ONLINE_PATH + fileLocation + ICS_FILENAME); } catch (Exception e) { e.printStackTrace(); } } private static HashMap<String, String> getParams(String args) { HashMap<String, String> params = new HashMap<>(); String[] paramsStrings = args.split("&"); for (String paramsString : paramsStrings) { String[] kvStrings = paramsString.split("="); params.put(kvStrings[0], kvStrings[1]); } return params; } /** * Deletes all .ics files from the web storage. Use for cleanup. * * @param !none */ @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { assert ForceSSL(request, response) : "SSL/HTTPS Connection error"; System.out.print("Cleaning up .ics files..."); response.setContentType("text/html; charset=UTF-8"); final File rootDir = new File(ROOT_PATH); final File[] icsFiles = rootDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().endsWith(".ics"); } }); for(File iFile : icsFiles) { iFile.delete(); } System.out.println("Done!"); } @Override public void init() throws ServletException { super.init(); worker = new Timer(true); worker.schedule(new TimerTask() { @Override public void run() { System.out.println("Executing worker task..."); try { // Read tasks from file for (String[] taskInfo : readTaskList()) { String key = taskInfo[0], baseURL = taskInfo[1]; final String fileLocation = baseURL + "/" + key + "/"; // Load data System.out.println("Fetching ICS data..."); // TODO Fully qualify URL final Map<LocalDate, ArrayList<Appointment>> data = DataImporter.ImportWeekRange( LocalDate.of(LocalDate.now().getYear(), 1, 1), LocalDate.of(LocalDate.now().getYear(), 12, 31), BaseURL.valueOf(baseURL), key); System.out.println("Done fetching data!"); final File containerFile = new File(ROOT_PATH + fileLocation); containerFile.mkdirs(); System.out.println("Done creating ICS file!"); generateICSFile(new File(containerFile, ICS_FILENAME), data); } System.out.println("Done updating calendars!"); } catch (Exception e) { e.printStackTrace(); } } }, 0, WORKER_FREQUENCY); } @Override public void destroy() { super.destroy(); } private boolean isICSFilePresent(String[] taskInfo) { File f = new File(ROOT_PATH + taskInfo[1] + "/" + taskInfo[0] + "/" + ICS_FILENAME); return f.exists() && f.isFile(); } private void generateICSFile(File exportFile, Map<LocalDate, ArrayList<Appointment>> data) throws IOException { final ICalendar ical = new ICalendar(); ical.setMethod(Method.publish()); VEvent event; for (ArrayList<Appointment> week : data.values()) { // Add each event for (Appointment _a : week) { event = new VEvent(); event.setSummary(_a.getTitle()); event.setDescription(_a.getInfo()); event.setDateStart(DateUtilities.ConvertToDate(_a.getStartDate())); event.setDateEnd(DateUtilities.ConvertToDate(_a.getEndDate())); event.setClassification(Classification.PUBLIC); event.setTransparency(Transparency.transparent()); ical.addEvent(event); } } /*final TimezoneInfo t = new TimezoneInfo(); t.setDefaultTimezone(TimezoneAssignment.download(TimeZone.getTimeZone("Europe/Berlin"), true)); ical.setTimezoneInfo(t);*/ // Generate ics output and create file writeOutputToFile(exportFile, Biweekly.write(ical).go()); } @SuppressWarnings("unused") private void generateCSVFile(File containerDir, File exportFile, Map<LocalDate, ArrayList<Appointment>> data) throws IOException { final StringBuilder output = new StringBuilder(); final String escape = "\""; final String seperateColumn = ","; final String seperateRow = "\r\n"; final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy"); final DateTimeFormatter tf = DateTimeFormatter.ofPattern("HH:mm"); output.append("Subject,Start date,Start time,End date,End time,Description,Private\n"); for (ArrayList<Appointment> week : data.values()) { // Add each event for (Appointment _a : week) { output.append(escape).append(_a.getTitle()).append(escape).append(seperateColumn); // "Subject" output.append(dtf.format(_a.getStartDate())).append(seperateColumn); // Start date output.append(tf.format(_a.getStartDate())).append(seperateColumn); // Start time output.append(dtf.format(_a.getEndDate())).append(seperateColumn); // End date output.append(tf.format(_a.getEndDate())).append(seperateColumn); // End time output.append(escape).append(_a.getInfo()).append(escape).append(seperateColumn); // "Description" output.append("TRUE").append(seperateRow); // Private } } writeOutputToFile(exportFile, output.toString()); } private void writeOutputToFile(File exportFile, String output) throws IOException { if(exportFile.exists()) { exportFile.delete(); } exportFile.createNewFile(); // Write content to file BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile), "UTF-8")); bf.write(output.toString()); bf.close(); } private ArrayList<String[]> readTaskList() throws IOException { final ArrayList<String[]> tasks = new ArrayList<>(); if (!TASKS_FILE.exists()) { TASKS_FILE.createNewFile(); return tasks; } BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(TASKS_FILE), "UTF-8")); String line; String[] splittedLine; ArrayList<String> newTasksOutput = new ArrayList<>(); int remainingCalls; while ((line = br.readLine()) != null) { splittedLine = line.split("\t"); remainingCalls = Integer.parseInt(splittedLine[0]); if (--remainingCalls > 0) { String key = splittedLine[1], baseURL = splittedLine[2]; newTasksOutput.add(remainingCalls + "\t" + key + "\t" + baseURL + "\n" ); tasks.add(new String[] { key, baseURL }); } } br.close(); // Clean file TASKS_FILE.delete(); TASKS_FILE.createNewFile(); // Rewrite tasklist BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(TASKS_FILE), "UTF-8")); for (String out : newTasksOutput) { bw.write(out); } bw.close(); return tasks; } public static boolean ForceSSL(HttpServletRequest request, HttpServletResponse response) { if (!(request.getScheme().equals("https") && request.getServerPort() == 443)) { try { response.sendRedirect("https://rablabla.mybluemix.net"); } catch (IOException e) { e.printStackTrace(); return false; } } return true; } }
package edu.iu.grid.oim.model.db; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import javax.security.auth.x500.X500Principal; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.cms.CMSException; import edu.iu.grid.oim.lib.Authorization; import edu.iu.grid.oim.lib.BCrypt; import edu.iu.grid.oim.lib.Footprints; import edu.iu.grid.oim.lib.StaticConfig; import edu.iu.grid.oim.lib.Footprints.FPTicket; import edu.iu.grid.oim.model.CertificateRequestStatus; import edu.iu.grid.oim.model.UserContext; import edu.iu.grid.oim.model.UserContext.MessageType; import edu.iu.grid.oim.model.cert.CertificateManager; import edu.iu.grid.oim.model.cert.GenerateCSR; import edu.iu.grid.oim.model.cert.ICertificateSigner; import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateProviderException; import edu.iu.grid.oim.model.db.record.CertificateRequestUserRecord; import edu.iu.grid.oim.model.db.record.ContactRecord; import edu.iu.grid.oim.model.db.record.DNAuthorizationTypeRecord; import edu.iu.grid.oim.model.db.record.DNRecord; import edu.iu.grid.oim.model.db.record.SCRecord; import edu.iu.grid.oim.model.db.record.VOContactRecord; import edu.iu.grid.oim.model.db.record.VORecord; import edu.iu.grid.oim.model.exceptions.CertificateRequestException; public class CertificateRequestUserModel extends CertificateRequestModelBase<CertificateRequestUserRecord> { static Logger log = Logger.getLogger(CertificateRequestUserModel.class); public CertificateRequestUserModel(UserContext _context) { super(_context, "certificate_request_user"); } //determines if user should be able to view request details, logs, and download certificate (pkcs12 is session specific) public boolean canView(CertificateRequestUserRecord rec) { return true; //let's allow everyone to view. } //empty if not found public ArrayList<ContactRecord> findRAs(CertificateRequestUserRecord rec) throws SQLException { ArrayList<ContactRecord> ras = new ArrayList<ContactRecord>(); VOContactModel model = new VOContactModel(context); ContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { if(crec.contact_type_id.equals(11)) { //11 - ra ContactRecord contactrec = cmodel.get(crec.contact_id); ras.add(contactrec); } } return ras; } //empty if not found public ArrayList<ContactRecord> findSponsors(CertificateRequestUserRecord rec) throws SQLException { ArrayList<ContactRecord> sponsors = new ArrayList<ContactRecord>(); VOContactModel model = new VOContactModel(context); ContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { if(crec.contact_type_id.equals(12) ) { //12 -- sponsor ContactRecord contactrec = cmodel.get(crec.contact_id); sponsors.add(contactrec); } } return sponsors; } //true if user can override CN public boolean canOverrideCN(CertificateRequestUserRecord rec) { if(canApprove(rec) && rec.status.equals(CertificateRequestStatus.REQUESTED)) { return true; } return false; } //true if user can approve request public boolean canApprove(CertificateRequestUserRecord rec) { if(!canView(rec)) return false; if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REQUESTED)) { //RA doesn't *approve* REVOKACTION - RA just click on revoke button if(auth.isUser()) { ContactRecord contact = auth.getContact(); //Is user RA agent for specified vo? VOContactModel model = new VOContactModel(context); //sContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs; try { crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { if(crec.contact_type_id.equals(11)) { //11 - RA if(crec.contact_id.equals(contact.id)) return true; } } } catch (SQLException e1) { log.error("Failed to lookup RA/sponsor information", e1); } } } return false; } public boolean canReject(CertificateRequestUserRecord rec) { return canApprove(rec); //same rule as approval } public boolean canCancel(CertificateRequestUserRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.REQUESTED) || rec.status.equals(CertificateRequestStatus.APPROVED) || //if renew_requesterd > approved cert is canceled, it should really go back to "issued", but currently it doesn't. //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { if(auth.isUser()) { ContactRecord contact = auth.getContact(); //requester can cancel one's own request if(rec.requester_contact_id.equals(contact.id)) return true; //ra can cancel VOContactModel model = new VOContactModel(context); //ContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs; try { crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { if(crec.contact_type_id.equals(11)) { //11 - RA if(crec.contact_id.equals(contact.id)) return true; } } } catch (SQLException e1) { log.error("Failed to lookup RA/sponsor information", e1); } } } return false; } public boolean canCancelWithPass(CertificateRequestUserRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.REQUESTED) || //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { //anyone including guest can cancel guest submitted request with a valid pass if(rec.requester_passphrase != null) { return true; } } return false; } public LogDetail getLastLog(String state, ArrayList<LogDetail> logs) { for(LogDetail log : logs) { if(log.status.equals(state)) { return log; } } return null; } public boolean canRenew(CertificateRequestUserRecord rec, ArrayList<LogDetail> logs) { if(!auth.isUser()) return false; return canRenew(rec, logs, auth.getContact()); } //can a user renew the certificate immediately? public boolean canRenew(CertificateRequestUserRecord rec, ArrayList<LogDetail> logs, ContactRecord contact) { if(!canView(rec)) return false; //only issued request can be renewed if(!rec.status.equals(CertificateRequestStatus.ISSUED)) return false; //original requester? if(!rec.requester_contact_id.equals(contact.id)) return false; //approved within 5 years? LogDetail last = getLastLog(CertificateRequestStatus.APPROVED, logs); if(last == null) return false; //never approved Calendar five_years_ago = Calendar.getInstance(); five_years_ago.add(Calendar.YEAR, -5); if(last.time.before(five_years_ago.getTime())) return false; //will expire in less than 6 month? Calendar six_month_future = Calendar.getInstance(); six_month_future.add(Calendar.MONTH, 6); if(rec.cert_notafter.after(six_month_future.getTime())) { //nope... but, if it's in debug mode, let user(testers) renew it if(!StaticConfig.isDebug()) { return false; } } //email hasn't changed since issue? try { java.security.cert.Certificate[] chain = CertificateManager.parsePKCS7(rec.cert_pkcs7); X509Certificate c0 = (X509Certificate)chain[0]; Collection<List<?>> list = c0.getSubjectAlternativeNames(); Iterator<List<?>> it = list.iterator(); List<?> first = it.next(); String cert_email = (String)first.get(1); if(!cert_email.equals(contact.primary_email) && !cert_email.equals(contact.secondary_email)) { //doesn't match primary nor secondary email return false; } } catch (Exception e) { log.error("CertificateRequestUserModel::canRenw() :: Failed to parse pkcs7 to test email address (skipping this test). id:" + rec.id, e); } //all good return true; } /* public boolean canRequestRenew(CertificateRequestUserRecord rec, ArrayList<LogDetail> logs) { if(!canView(rec)) return false; if(canRenew(rec, logs)) return false;//if user can renew it immediately, then no need for request. if( rec.status.equals(CertificateRequestStatus.ISSUED)) { if(auth.isUser()) { return true; } } return false; } */ public boolean canReRequest(CertificateRequestUserRecord rec) { if(!canView(rec)) return false; /* if( rec.status.equals(CertificateRequestStatus.REJECTED) || rec.status.equals(CertificateRequestStatus.CANCELED) || rec.status.equals(CertificateRequestStatus.REVOKED) || rec.status.equals(CertificateRequestStatus.EXPIRED)) { //requester can re-request if(auth.isUser() && auth.getContact().id.equals(rec.requester_contact_id)) { return true; } } if (rec.status.equals(CertificateRequestStatus.EXPIRED) ) { //guest user needs to be able to re-request expired cert.. return true; } */ if( rec.status.equals(CertificateRequestStatus.REJECTED) || rec.status.equals(CertificateRequestStatus.CANCELED) || rec.status.equals(CertificateRequestStatus.REVOKED) || rec.status.equals(CertificateRequestStatus.EXPIRED)) { //anyone including guest can re-request if the status is one of avobe. //Previously, we only allowed guest to re-request if the certificate was expired. //however, sometime user expires *while* going through the request process. //in that case, RA will cancel the cert, and guest user can re-request //TODO Once everyone transition to DigiCert, I believe we should only allow guest user to re-request if the request is in EXPIRED state. if(auth.isUser()) { //user can re-request his own cert . if(auth.getContact().id.equals(rec.requester_contact_id)) { return true; } //can't re-request someone else's cert return false; } else { //allow guest to renew any cert, provided that RA/sponsor will vet. return true; } } return false; } public boolean canRequestRevoke(CertificateRequestUserRecord rec) { if(!canView(rec)) return false; if(rec.status.equals(CertificateRequestStatus.ISSUED)) { if(auth.isUser() && canRevoke(rec)) { //if user can directly revoke it, no need to request it return false; } //all else, allow return true; } return false; } public boolean canRevoke(CertificateRequestUserRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.ISSUED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { if(auth.isUser()) { //requester oneself can revoke it ContactRecord contact = auth.getContact(); if(rec.requester_contact_id.equals(contact.id)) return true; //ra can revoke it VOContactModel model = new VOContactModel(context); //ContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs; try { crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { //ContactRecord contactrec = cmodel.get(crec.contact_id); if(crec.contact_type_id.equals(11)) { //11 - ra if(crec.contact_id.equals(contact.id)) return true; } } } catch (SQLException e1) { log.error("Failed to lookup RA/sponsor information", e1); } } } return false; } //why can't we just issue certificate after it's been approved? because we might have to create pkcs12 public boolean canIssue(CertificateRequestUserRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.APPROVED)) { //requester oneself can issue if(auth.isUser()) { ContactRecord contact = auth.getContact(); if(rec.requester_contact_id.equals(contact.id)) return true; } else { if(rec.requester_passphrase != null) { //guest user can try entering retrieval passphrase return true; } } } return false; } //NO-AC public void approve(CertificateRequestUserRecord rec) throws CertificateRequestException { //check quota CertificateQuotaModel quota = new CertificateQuotaModel(context); if(!quota.canRequestUserCert(rec.requester_contact_id)) { throw new CertificateRequestException("Exeeding Quota"); } if(rec.status.equals(CertificateRequestStatus.REQUESTED)) { //update request status rec.status = CertificateRequestStatus.APPROVED; try { super.update(get(rec.id), rec); quota.incrementUserCertRequest(rec.requester_contact_id); } catch (SQLException e) { throw new CertificateRequestException("Failed to approve user certificate request: " + rec.id, e); } try { //get requester name ContactModel cmodel = new ContactModel(context); ContactRecord requester = cmodel.get(rec.requester_contact_id); //update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = "Dear " + requester.name + ",\n\n"; ticket.description += "Your user certificate request has been approved.\n\n"; ticket.description += "> " + context.getComment(); ticket.description += "\n\nTo retrieve your certificate please visit " + getTicketUrl(rec.id) + " and click on Issue Certificate button."; ticket.nextaction = "Requester to download certificate"; // NAD will be set 7 days from today by default fp.update(ticket, rec.goc_ticket_id); } catch (SQLException e) { throw new CertificateRequestException("Probably faile to find requester for notification: "+rec.status); } } else { //shouldn't reach here.. throw new CertificateRequestException("Don't know how to approve request which is currently in stauts: "+rec.status); } } //NO-AC public void cancel(CertificateRequestUserRecord rec) throws CertificateRequestException { try { //info.. We can't put RENEW_REQUESTED back to ISSUED - since we've already reset certificate if(rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { rec.status = CertificateRequestStatus.ISSUED; } else { rec.status = CertificateRequestStatus.CANCELED; } super.update(get(rec.id), rec); // All good - now close ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has canceled this certificate request.\n\n"; } else { ticket.description = "guest shouldn't be canceling"; } ticket.description += "> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } catch (SQLException e) { throw new CertificateRequestException("Failed to cancel user certificate request:" + rec.id, e); } } //NO-AC public void reject(CertificateRequestUserRecord rec) throws CertificateRequestException { if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED)|| rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { rec.status = CertificateRequestStatus.ISSUED; } else { //all others rec.status = CertificateRequestStatus.REJECTED; } try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); } catch (SQLException e) { throw new CertificateRequestException("Failed to reject user certificate request:" + rec.id, e); } ContactRecord contact = auth.getContact(); Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = contact.name + " has rejected this certificate request.\n\n"; ticket.description += "> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } /* //NO-AC //reuse previously used csr - only oim user can do this public void requestRenew(CertificateRequestUserRecord rec) throws CertificateRequestException { if(!auth.isUser()) { throw new CertificateRequestException("only oim user can request renew"); } rec.status = CertificateRequestStatus.RENEW_REQUESTED; //clear previously issued cert rec.cert_certificate = null; rec.cert_intermediate = null; rec.cert_pkcs7 = null; rec.cert_serial_id = null; //we don't need passphrase - only requester can renew, and we are not creating private key rec.requester_passphrase = null; rec.requester_passphrase_salt = null; try { super.update(get(rec.id), rec); //create notification ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); prepareNewTicket(ticket, "User Certificate Renew Request", rec, auth.getContact()); rec.goc_ticket_id = fp.open(ticket); context.setComment("Opened GOC Ticket " + rec.goc_ticket_id); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to request user certificate request renewal: " + rec.id); throw new CertificateRequestException("Failed to update request status", e); } } */ //NO-AC public void requestRevoke(CertificateRequestUserRecord rec) throws CertificateRequestException { rec.status = CertificateRequestStatus.REVOCATION_REQUESTED; try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to request revocation of user certificate: " + rec.id); throw new CertificateRequestException("Failed to update request status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); //Update CC ra (it might have been changed since last time request was made) VOContactModel model = new VOContactModel(context); ContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs; String ras = ""; try { crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { ContactRecord contactrec = cmodel.get(crec.contact_id); if(crec.contact_type_id.equals(11)) { //11 - ra ticket.ccs.add(contactrec.primary_email); if(!ras.isEmpty()) { ras += ", "; } ras += contactrec.name; } } } catch (SQLException e1) { log.error("Failed to lookup RA/sponsor information - ignoring", e1); } ticket.description = "Dear "+ras+ " (RAs)\n\n"; Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has requested revocation of this certificate request."; } else { ticket.description = "Guest user with IP:" + context.getRemoteAddr() + " has requested revocation of this certificate request."; } ticket.description += "\n\nRA may revoke this request at " + getTicketUrl(rec.id); ticket.nextaction = "RA to process"; //nad will be set to 7 days from today by default ticket.status = "Engineering"; //probably need to reopen fp.update(ticket, rec.goc_ticket_id); } //NO-AC public void revoke(CertificateRequestUserRecord rec) throws CertificateRequestException { //revoke CertificateManager cm = new CertificateManager(); try { cm.revokeUserCertificate(rec.cert_serial_id); log.info("Revoked " + rec.dn + " with serial id:" + rec.cert_serial_id); //update record try { rec.status = CertificateRequestStatus.REVOKED; //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update user certificate status: " + rec.id, e); throw new CertificateRequestException("Failed to update user certificate status", e); } //disable associated dn (if any) try { DNModel dnmodel = new DNModel(context); DNRecord dnrec = dnmodel.getByDNString(rec.dn); if(rec != null) { log.info("Disabling associated DN record"); dnrec.disable = true; dnmodel.update(dnrec); } } catch (SQLException e) { log.warn("Failed to remove associated DN.. continuing", e); } Authorization auth = context.getAuthorization(); ContactRecord contact = auth.getContact(); Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = contact.name + " has revoked this certificate.\n\n"; ticket.description += "> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } catch (CertificateProviderException e1) { log.error("Failed to revoke user certificate", e1); throw new CertificateRequestException("Failed to revoke user certificate", e1); } } //NO-AC public void cancelWithPass(final CertificateRequestUserRecord rec, final String password) throws CertificateRequestException { //verify passphrase if necessary if(rec.requester_passphrase != null) { String hashed = BCrypt.hashpw(password, rec.requester_passphrase_salt); if(!hashed.equals(rec.requester_passphrase)) { throw new CertificateRequestException("Failed to match password."); } } cancel(rec); } //go directly from ISSUED > ISSUEING public void renew(final CertificateRequestUserRecord rec) throws CertificateRequestException { //check quota CertificateQuotaModel quota = new CertificateQuotaModel(context); if(!quota.canRequestUserCert(rec.requester_contact_id)) { throw new CertificateRequestException("Quota Exceeded"); } //notification -- just make a note on an existing ticket - we don't need to create new goc ticket - there is nobody we need to inform - Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " is renewing user certificate.\n\n"; ticket.description += "> " + context.getComment(); } else { throw new CertificateRequestException("guest can't renew"); } ticket.status = "Engineering";//reopen ticket temporarily fp.update(ticket, rec.goc_ticket_id); /* //clear previously issued cert rec.cert_certificate = null; rec.cert_intermediate = null; rec.cert_pkcs7 = null; rec.cert_serial_id = null; */ //we don't need passphrase - only requester can renew, and we are not creating private key rec.requester_passphrase = null; rec.requester_passphrase_salt = null; //start issuing immediately startissue(rec, null); //increment quota try { quota.incrementUserCertRequest(rec.requester_contact_id); } catch (SQLException e) { log.error("Failed to incremenet quota while renewing request id:"+rec.id); } context.message(MessageType.SUCCESS, "Successfully renewed a certificate. Please download & install your certificate."); } // NO-AC public void startissue(final CertificateRequestUserRecord rec, final String password) throws CertificateRequestException { //verify passphrase (for guest request) to make sure we are issuing cert for person submitted the request if(rec.requester_passphrase != null) { String hashed = BCrypt.hashpw(password, rec.requester_passphrase_salt); if(!hashed.equals(rec.requester_passphrase)) { throw new CertificateRequestException("Failed to match password."); } } // mark the request as "issuing.." try { rec.status = CertificateRequestStatus.ISSUING; super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to issue user certificate for request:" + rec.id); throw new CertificateRequestException("Failed to update certificate request status"); } //Maybe I should use Quartz instead? new Thread(new Runnable() { public void failed(String message) { log.error(message); rec.status = CertificateRequestStatus.FAILED; try { context.setComment(message); CertificateRequestUserModel.super.update(get(rec.id), rec); } catch (SQLException e1) { log.error("Failed to update request status while processing failed condition :" + message, e1); } //update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = "Failed to issue certificate\n\n"; ticket.description += message+"\n\n"; ticket.description += "The alert has been sent to GOC alert for further actions on this issue."; ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.fail.assignee")); ticket.nextaction = "GOC developer to investigate"; fp.update(ticket, rec.goc_ticket_id); } public void failed(String message, Throwable e) { message += " :: " + e.getMessage(); failed(message); log.error(e); } public void run() { try { //if csr is not set, we need to create new one and private key for user if (rec.csr == null) { X500Name name = rec.getX500Name(); GenerateCSR csrgen = new GenerateCSR(name); rec.csr = csrgen.getCSR(); context.setComment("Generated CSR and private key"); CertificateRequestUserModel.super.update(get(rec.id),rec); // store private key in memory to be used to create pkcs12 later HttpSession session = context.getSession(); log.debug("user session ID:" + session.getId()); session.setAttribute("PRIVATE_USER:" + rec.id, csrgen.getPrivateKey()); session.setAttribute("PASS_USER:" + rec.id, password); } //lookup requester contact information ContactModel cmodel = new ContactModel(context); ContactRecord requester = cmodel.get(rec.requester_contact_id); //now we can sign it String cn = rec.getCN();//TODO - check for null? CertificateManager cm = new CertificateManager(); ICertificateSigner.Certificate cert = cm.signUserCertificate(rec.csr, cn, requester.primary_email); rec.cert_certificate = cert.certificate; rec.cert_intermediate = cert.intermediate; rec.cert_pkcs7 = cert.pkcs7; rec.cert_serial_id = cert.serial; log.info("user cert issued by digicert: serial_id:" + cert.serial); log.info("pkcs7:" + cert.pkcs7); //get some information we need from the issued certificate java.security.cert.Certificate[] chain = CertificateManager.parsePKCS7(rec.cert_pkcs7); X509Certificate c0 = (X509Certificate)chain[0]; rec.cert_notafter = c0.getNotAfter(); rec.cert_notbefore = c0.getNotBefore(); //do a bit of validation Calendar today = Calendar.getInstance(); if(Math.abs(today.getTimeInMillis() - rec.cert_notbefore.getTime()) > 1000*3600*24) { log.warn("User certificate issued for request "+rec.id+" has cert_notbefore set too distance from current timestamp"); } long dayrange = (rec.cert_notafter.getTime() - rec.cert_notbefore.getTime()) / (1000*3600*24); if(dayrange < 390 || dayrange > 405) { log.warn("User certificate issued for request "+rec.id+ " has valid range of "+dayrange+" days (too far from 395 days)"); } //update dn with the one returned by DigiCert X500Principal dn = c0.getSubjectX500Principal(); String apache_dn = CertificateManager.X500Principal_to_ApacheDN(dn); rec.dn = apache_dn; //make sure dn starts with correct base String user_dn_base = StaticConfig.conf.getProperty("digicert.user_dn_base"); if(!apache_dn.startsWith(user_dn_base)) { log.warn("User certificate issued for request " + rec.id + " has DN:"+apache_dn+" which doesn't have an expected DN base: "+user_dn_base); } DNModel dnmodel = new DNModel(context); DNRecord dnrec = dnmodel.getByDNString(rec.dn); if(dnrec == null) { //insert a new DN record dnrec = new DNRecord(); dnrec.contact_id = rec.requester_contact_id; dnrec.dn_string = rec.dn; dnrec.disable = false; dnrec.id = dnmodel.insert(dnrec); //TODO - we should aggregate all currently approved authorization types and give the DN access to all of it instead //Give user OSG end user access DNAuthorizationTypeModel dnauthmodel = new DNAuthorizationTypeModel(context); DNAuthorizationTypeRecord dnauthrec = new DNAuthorizationTypeRecord(); dnauthrec.dn_id = dnrec.id; dnauthrec.authorization_type_id = 1; //OSG End User dnauthmodel.insert(dnauthrec); } else { //TODO - -what is the point of this check? just paranoid? if(!dnrec.contact_id.equals(rec.requester_contact_id)) { //this DN belongs to someone else. //dnrec.contact_id = rec.requester_contact_id; log.error("The DN issued " + rec.dn + " is already registered to a different contact:" + dnrec.contact_id + " - updating it to " + rec.requester_contact_id + " this should have never happened"); } dnrec.disable = false; //maybe it was disabled previousl (or expired) dnmodel.update(dnrec); } //TODO - we've moved the timing of enabling contact enable from approve() to here. this means that, we could have 2 requests //that are in APPROVED status and users can issue them both. This could lead to duplicate contacts with identical //email addresses.. to prevent this, we should validate against duplicate email inside //canIssue() again, but I am not sure that it's worth doing it. //enable requeser contact (just in case) requester.disable = false; cmodel.update(requester); //all done at this point rec.status = CertificateRequestStatus.ISSUED; context.setComment("Certificate has been issued by signer. serial number: " + rec.cert_serial_id); CertificateRequestUserModel.super.update(get(rec.id), rec); // update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has issued certificate. Resolving this ticket."; } else { ticket.description = "Guest with IP:" + context.getRemoteAddr() + " has issued certificate. Resolving this ticket."; } ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } catch (ICertificateSigner.CertificateProviderException e) { failed("Failed to sign certificate -- CertificateProviderException ", e); } catch (CMSException e) { //from parsePKCS7 failed("Failed to sign certificate -- can't parse returned pkcs7 for request id:" + rec.id, e); } catch (Exception e) { //probably from parsePKCS7 (like StringIndexOutOfBoundsException) failed("Failed to sign certificate -- can't parse returned pkcs7 request id:" + rec.id, e); } } }).start(); } public PrivateKey getPrivateKey(Integer id) { HttpSession session = context.getSession(); if(session == null) return null; return (PrivateKey)session.getAttribute("PRIVATE_USER:"+id); } public String getPassword(Integer id) { HttpSession session = context.getSession(); if(session == null) return null; return (String)session.getAttribute("PASS_USER:"+id); } //construct pkcs12 using private key stored in session and issued certificate //return null if unsuccessful - errors are logged public KeyStore getPkcs12(CertificateRequestUserRecord rec) { //pull certificate chain from pkcs7 try { java.security.cert.Certificate[] chain = CertificateManager.parsePKCS7(rec.cert_pkcs7); //HttpSession session = context.getSession(); String password = getPassword(rec.id); if(password == null) { log.error("can't retrieve certificate encryption password while creating pkcs12"); /* //experimenet trying to create pkcs12 without private key - doesn't work KeyStore p12 = KeyStore.getInstance("PKCS12"); p12.load(null, null); p12.setCertificateEntry("USER"+rec.id, chain[0]); return p12; */ } else { KeyStore p12 = KeyStore.getInstance("PKCS12"); p12.load(null, null); //not sure what this does. PrivateKey private_key = getPrivateKey(rec.id); p12.setKeyEntry("USER"+rec.id, private_key, password.toCharArray(), chain); return p12; } } catch (IOException e) { log.error("Failed to get encoded byte array from bouncy castle certificate.", e); } catch (CertificateException e) { log.error("Failed to generate java security certificate from byte array", e); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CMSException e) { log.error("Failed to get encoded byte array from bouncy castle certificate.", e); } return null; } //NO-AC public CertificateRequestUserRecord get(int id) throws SQLException { CertificateRequestUserRecord rec = null; ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); if (stmt.execute("SELECT * FROM "+table_name+ " WHERE id = " + id)) { rs = stmt.getResultSet(); if(rs.next()) { rec = new CertificateRequestUserRecord(rs); } } stmt.close(); conn.close(); return rec; } /* //NO-AC public CertificateRequestUserRecord getByDN(String apache_dn) throws SQLException { CertificateRequestUserRecord rec = null; ResultSet rs = null; Connection conn = connectOIM(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM "+table_name+ " WHERE dn = ?"); stmt.setString(1, apache_dn); rs = stmt.executeQuery(); if(rs.next()) { rec = new CertificateRequestUserRecord(rs); } stmt.close(); conn.close(); return rec; } */ public void processExpired() throws SQLException { //search for expired certificates ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND cert_notafter < CURDATE()")) { rs = stmt.getResultSet(); DNModel dnmodel = new DNModel(context); while(rs.next()) { CertificateRequestUserRecord rec = new CertificateRequestUserRecord(rs); rec.status = CertificateRequestStatus.EXPIRED; context.setComment("Certificate is no longer valid."); super.update(get(rec.id), rec); //disable DN (TODO -- Not yet tested..) DNRecord dnrec = dnmodel.getByDNString(rec.dn); if(dnrec != null) { dnrec.disable = true; dnmodel.update(dnrec); } // update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ContactModel cmodel = new ContactModel(context); ContactRecord requester = cmodel.get(rec.requester_contact_id); //send notification ticket.description = "Dear " + requester.name + ",\n\n"; ticket.description += "Your user certificate ("+rec.dn+") has expired. Please visit "+getTicketUrl(rec.id)+" and submit re-request.\n\n"; fp.update(ticket, rec.goc_ticket_id); log.info("sent expiration notification for user certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")"); } } stmt.close(); conn.close(); } public void notifyExpiringIn(Integer days) throws SQLException { final SimpleDateFormat dformat = new SimpleDateFormat(); dformat.setTimeZone(auth.getTimeZone()); ContactModel cmodel = new ContactModel(context); for(CertificateRequestUserRecord rec : findExpiringIn(days)) { ContactRecord requester = cmodel.get(rec.requester_contact_id); Date expiration_date = rec.cert_notafter; //send notification Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = "Dear " + requester.name + ",\n\n"; ticket.description += "Your user certificate ("+rec.dn+") will expire on "+dformat.format(expiration_date)+"\n\n"; //can user renew? ArrayList<CertificateRequestModelBase<CertificateRequestUserRecord>.LogDetail> logs = getLogs(CertificateRequestUserModel.class, rec.id); if(canRenew(rec, logs, requester)) { ticket.description += "Please renew by visiting "+getTicketUrl(rec.id)+"\n\n"; ticket.status = "Engineering"; //reopen it - until user renew } else { ticket.description += "Please request for new user certificate by visiting https://oim.grid.iu.edu/oim/certificaterequestuser\n\n"; } //TODO - clear CC list (or suppress cc-emailing) if(StaticConfig.isDebug()) { log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring user certificate"); log.debug(ticket.description); log.debug(ticket.status); } else { fp.update(ticket, rec.goc_ticket_id); log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring user certificate"); } } } //return requests that I am RA of public ArrayList<CertificateRequestUserRecord> getIApprove(Integer id) throws SQLException { ArrayList<CertificateRequestUserRecord> recs = new ArrayList<CertificateRequestUserRecord>(); //list all vo that user is ra of HashSet<Integer> vo_ids = new HashSet<Integer>(); VOContactModel model = new VOContactModel(context); try { for(VOContactRecord crec : model.getByContactID(id)) { if(crec.contact_type_id.equals(11)) { vo_ids.add(crec.vo_id); } } } catch (SQLException e1) { log.error("Failed to lookup RA information", e1); } if(vo_ids.size() != 0) { ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); String vo_ids_str = StringUtils.join(vo_ids, ","); stmt.execute("SELECT * FROM "+table_name + " WHERE vo_id IN ("+vo_ids_str+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')"); rs = stmt.getResultSet(); while(rs.next()) { recs.add(new CertificateRequestUserRecord(rs)); } stmt.close(); conn.close(); } return recs; } public ArrayList<CertificateRequestUserRecord> getISubmitted(Integer contact_id) throws SQLException { ArrayList<CertificateRequestUserRecord> recs = new ArrayList<CertificateRequestUserRecord>(); ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE requester_contact_id = " + contact_id); rs = stmt.getResultSet(); while(rs.next()) { recs.add(new CertificateRequestUserRecord(rs)); } stmt.close(); conn.close(); return recs; } public ArrayList<CertificateRequestUserRecord> findExpiringIn(Integer days) throws SQLException { ArrayList<CertificateRequestUserRecord> recs = new ArrayList<CertificateRequestUserRecord>(); ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND CURDATE() > DATE_SUB( cert_notafter, INTERVAL "+days+" DAY )"); rs = stmt.getResultSet(); while(rs.next()) { recs.add(new CertificateRequestUserRecord(rs)); } stmt.close(); conn.close(); return recs; } //return requests that guest has submitted public ArrayList<CertificateRequestUserRecord> getGuest() throws SQLException { ArrayList<CertificateRequestUserRecord> ret = new ArrayList<CertificateRequestUserRecord>(); ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE requester_contact_id is NULL"); rs = stmt.getResultSet(); while(rs.next()) { ret.add(new CertificateRequestUserRecord(rs)); } stmt.close(); conn.close(); return ret; } public boolean requestWithCSR(String csr, String fullname, Integer vo_id) throws SQLException { //TODO return false; } public CertificateRequestUserRecord requestUsertWithNOCSR( Integer vo_id, ContactRecord requester, ContactRecord sponsor, String cn, String request_comment) throws SQLException, CertificateRequestException { CertificateRequestUserRecord rec = new CertificateRequestUserRecord(); request(vo_id, rec, requester, sponsor, cn, request_comment); return rec; } //returns insertec request record if successful. if not, null public CertificateRequestUserRecord requestGuestWithNOCSR( Integer vo_id, ContactRecord requester, ContactRecord sponsor, String passphrase, String request_comment) throws SQLException, CertificateRequestException { CertificateRequestUserRecord rec = new CertificateRequestUserRecord(); String salt = BCrypt.gensalt(12);//let's hard code this for now.. rec.requester_passphrase_salt = salt; rec.requester_passphrase = BCrypt.hashpw(passphrase, salt); request(vo_id, rec, requester, sponsor, null, request_comment);//cn is not known until we check the contact return rec; } public X500Name generateDN(String cn) { X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE); //DigiCert overrides the DN, so none of these matters - except CN which is used to send common_name parameter //We are creating this so that we can create private key x500NameBld.addRDN(BCStyle.DC, "com"); x500NameBld.addRDN(BCStyle.DC, "DigiCert-Grid"); if(StaticConfig.isDebug()) { //let's assume debug means we are using digicert pilot x500NameBld.addRDN(BCStyle.O, "OSG Pilot"); } else { x500NameBld.addRDN(BCStyle.O, "Open Science Grid"); } x500NameBld.addRDN(BCStyle.OU, "People"); x500NameBld.addRDN(BCStyle.CN, cn); //don't use "," or "/" which is used for DN delimiter return x500NameBld.build(); } private String getTicketUrl(Integer ticket_id) { String base; if(StaticConfig.isDebug()) { base = "https://oim-itb.grid.iu.edu/oim/"; } else { base = "https://oim.grid.iu.edu/oim/"; } return base + "certificateuser?id=" + ticket_id; } //NO-AC //return true for success private void request(Integer vo_id, CertificateRequestUserRecord rec, ContactRecord requester, ContactRecord sponsor, String cn, String request_comment) throws SQLException, CertificateRequestException { String note = ""; // Check conditions & finalize DN (register contact if needed) DNModel dnmodel = new DNModel(context); if(auth.isUser()) { //generate DN X500Name name = generateDN(cn); rec.dn = CertificateManager.RFC1779_to_ApacheDN(name.toString()); note += "NOTE: Additional user certificate request for OIM user\n"; } else { //Guest request -- check contact record with the same email address ContactModel cmodel = new ContactModel(context); ContactRecord existing_crec = cmodel.getEnabledByemail(requester.primary_email);//this is from the form, so I just have to check against primary_email if(existing_crec == null) { //register new disabled contact (until issued) requester.disable = true; //don't enable until the request gets approved requester.id = cmodel.insert(requester); //and generate dn cn = requester.name + " " + requester.id; X500Name name = generateDN(cn); rec.dn = CertificateManager.RFC1779_to_ApacheDN(name.toString()); note += "NOTE: User is registering OIM contact & requesting new certificate: contact id:"+requester.id+"\n"; } else { //Guest is attempting take over existing contact //generate dn (with existing_crec id) cn = requester.name + " " + existing_crec.id; X500Name name = generateDN(cn); rec.dn = CertificateManager.RFC1779_to_ApacheDN(name.toString()); //find if the existing contact has any DN associated with the contact ArrayList<DNRecord> dnrecs = dnmodel.getEnabledByContactID(existing_crec.id); if(dnrecs.isEmpty()) { //OK for contact record take over //pre-registered contact - just let user associate with this contact id requester.id = existing_crec.id; requester.disable = false; requester.person = true; //update contact information with information that user just gave me //NOTE -- we are updating oim contact from guest submitted info before doing DN //collision test here cmodel.update(requester); note += "NOTE: User is taking over a contact only account with id: "+existing_crec.id+"\n"; } else { //we can't take over contact record that already has DN attached. throw new CertificateRequestException("Provided email address is already associated with existing OIM account. If you are already registered to OIM, please login before making your request. Please contact GOC for more assistance."); } } } //make sure we won't collide with existing dn DNRecord existing_rec = dnmodel.getEnabledByDNString(rec.dn); if(existing_rec != null) { throw new CertificateRequestException("The DN already exist in OIM (contact ID:"+existing_rec.contact_id+"). Please choose different CN, or contact GOC for more assistance."); } note += "NOTE: Requested DN: " + rec.dn + "\n\n"; // Make Request Date current = new Date(); rec.request_time = new Timestamp(current.getTime()); rec.status = CertificateRequestStatus.REQUESTED; rec.requester_contact_id = requester.id; rec.vo_id = vo_id; if(request_comment != null) { note += "Requester Comment: "+request_comment; context.setComment(request_comment); } else { context.setComment("Making Request for " + requester.name); } super.insert(rec); //quota.incrementUserCertRequest(); //create notification ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); prepareNewTicket(ticket, "User Certificate Request", rec, requester, sponsor); ticket.description += "\n\n"+note; rec.goc_ticket_id = fp.open(ticket); context.setComment("Opened GOC Ticket " + rec.goc_ticket_id); super.update(get(rec.id), rec); } private void prepareNewTicket(FPTicket ticket, String title, CertificateRequestUserRecord rec, ContactRecord requester, ContactRecord sponsor) throws SQLException { ticket.name = requester.name; ticket.email = requester.primary_email; ticket.phone = requester.primary_phone; //Create ra & sponsor list String ranames = ""; VOContactModel model = new VOContactModel(context); ContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs; try { //add RAs crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { ContactRecord contactrec = cmodel.get(crec.contact_id); if(crec.contact_type_id.equals(11)) { //11 - ra ticket.ccs.add(contactrec.primary_email); if(ranames.length() != 0) { ranames += ", "; } ranames += contactrec.name; } } } catch (SQLException e1) { log.error("Failed to lookup RA information - ignoring", e1); } //add sponsor email ticket.ccs.add(sponsor.primary_email); //submit goc ticket VOModel vmodel = new VOModel(context); VORecord vrec = vmodel.get(rec.vo_id); ticket.title = title + " for "+requester.name + "(VO:"+vrec.name+")"; String auth_status = "An unauthenticated user; "; if(auth.isUser()) { auth_status = "An OIM Authenticated user; "; } ticket.description = "Dear " + ranames + " (" + vrec.name + " VO RAs),\n\n"; ticket.description += auth_status + requester.name + " <"+requester.primary_email+"> has requested a user certificate. "; ticket.description += "Please determine this request's authenticity, and approve / disapprove at " + getTicketUrl(rec.id) + "\n\n"; //if sponsor id is null, that means it doesn't exist in our contact DB. if(sponsor.id == null) { ticket.description += "User has manually entered sponsor information with name: " + sponsor.name + ". RA must confirm the identify of this sponsor. "; ticket.description += "RA should also consider registering this sponsor for this VO."; } else { ticket.description += "User has selected a registered sponsor: " + sponsor.name + " who has been CC-ed to this request. "; } /* if(StaticConfig.isDebug()) { ticket.assignees.add("hayashis"); } else { ticket.assignees.add("adeximo"); } */ ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.user.assignee")); ticket.ccs.add("osg-ra@opensciencegrid.org"); ticket.nextaction = "RA/Sponsors to verify requester"; //NAD will be set to 7 days in advance by default //set metadata ticket.metadata.put("ASSOCIATED_VO_ID", vrec.id.toString()); ticket.metadata.put("ASSOCIATED_VO_NAME", vrec.name); SCModel scmodel = new SCModel(context); SCRecord screc = scmodel.get(vrec.sc_id); ticket.metadata.put("SUPPORTING_SC_ID", screc.id.toString()); ticket.metadata.put("SUPPORTING_SC_NAME", screc.name); ticket.metadata.put("SUBMITTED_VIA", "OIM/CertManager(user)"); if(auth.isUser()) { ticket.metadata.put("SUBMITTER_DN", auth.getUserDN()); } ticket.metadata.put("SUBMITTER_NAME", requester.name); } //no-ac public boolean rerequest(CertificateRequestUserRecord rec, String guest_passphrase) throws CertificateRequestException { rec.status = CertificateRequestStatus.REQUESTED; rec.csr = null; //this causes issue() to regenerate CSR with new private key if(guest_passphrase != null) { //submitted as guest String salt = BCrypt.gensalt(12);//let's hard code this for now.. rec.requester_passphrase_salt = salt; rec.requester_passphrase = BCrypt.hashpw(guest_passphrase, salt); } else { //need to reset passphrase if there is any rec.requester_passphrase_salt = null; rec.requester_passphrase = null; //only the same user should be able to re-request, but just in case.. rec.requester_contact_id = auth.getContact().id; } try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); //quota.incrementUserCertRequest(); } catch (SQLException e) { log.error("Failed to re-request user certificate request: " + rec.id); return false; } // Notification try { Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); //CC RAs String ranames = ""; VOContactModel model = new VOContactModel(context); ContactModel cmodel = new ContactModel(context); ArrayList<VOContactRecord> crecs; crecs = model.getByVOID(rec.vo_id); for(VOContactRecord crec : crecs) { ContactRecord contactrec = cmodel.get(crec.contact_id); if(crec.contact_type_id.equals(11)) { //11 - ra ticket.ccs.add(contactrec.primary_email); if(ranames.length() != 0) { ranames += ", "; } ranames += contactrec.name; } } //CC sponsor //TODO - need to re-CC sponsor, but I am not sure how. ContactRecord requester = cmodel.get(rec.requester_contact_id); VOModel vmodel = new VOModel(context); VORecord vrec = vmodel.get(rec.vo_id); ticket.description = "Dear " + ranames + " (" + vrec.name + " VO RA/Sponsors),\n\n"; if(guest_passphrase != null) { ticket.description += "A guest user has re-requested this user certificate request. Please contact the original requester; " + requester.name + " <"+requester.primary_email+"> and confirm authenticity of this re-request, and approve / disapprove at" + getTicketUrl(rec.id); } else { ticket.description += "An OIM Authenticated user " + requester.name + " <"+requester.primary_email+"> has re-requested this user certificate request. "; ticket.description += "Please approve / disapprove this request at " + getTicketUrl(rec.id); } ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.user.assignee")); ticket.nextaction = "RA/Sponsors to verify requester"; //NAD will be set to 7 days in advance by default ticket.status = "Engineering"; //I need to reopen resolved ticket. fp.update(ticket, rec.goc_ticket_id); } catch (SQLException e1) { log.error("Failed to create ticket update content - ignoring", e1); } return true; } //prevent low level access - please use model specific actions @Override public Integer insert(CertificateRequestUserRecord rec) throws SQLException { throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)"); } @Override public void update(CertificateRequestUserRecord oldrec, CertificateRequestUserRecord newrec) throws SQLException { throw new UnsupportedOperationException("Please use model specific actions insetead (request, approve, reject, etc..)"); } @Override public void remove(CertificateRequestUserRecord rec) throws SQLException { throw new UnsupportedOperationException("disallowing remove cert request.."); } /* public void _test() { try { CertificateRequestUserRecord rec = get(21); try { java.security.cert.Certificate[] chain = CertificateManager.parsePKCS7(rec.cert_pkcs7); X509Certificate c0 = (X509Certificate)chain[0]; Date not_after = c0.getNotAfter(); Date not_before = c0.getNotBefore(); } catch (CMSException e) { log.error("Failed to lookup certificate information for issued user cert request id:" + rec.id, e); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } */ //NO AC public CertificateRequestUserRecord getBySerialID(String serial_id) throws SQLException { CertificateRequestUserRecord rec = null; ResultSet rs = null; Connection conn = connectOIM(); PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM "+table_name+ " WHERE cert_serial_id = ?"); pstmt.setString(1, serial_id); if (pstmt.executeQuery() != null) { rs = pstmt.getResultSet(); if(rs.next()) { rec = new CertificateRequestUserRecord(rs); } } pstmt.close(); conn.close(); return rec; } //pass null to not filter public ArrayList<CertificateRequestUserRecord> search(String dn_contains, String status, Integer vo_id, Date request_after, Date request_before) throws SQLException { ArrayList<CertificateRequestUserRecord> recs = new ArrayList<CertificateRequestUserRecord>(); ResultSet rs = null; Connection conn = connectOIM(); String sql = "SELECT * FROM "+table_name+" WHERE 1 = 1"; if(dn_contains != null) { sql += " AND dn like \"%"+StringEscapeUtils.escapeSql(dn_contains)+"%\""; } if(status != null) { sql += " AND status = \""+status+"\""; } if(vo_id != null) { sql += " AND vo_id = "+vo_id; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(request_after != null) { sql += " AND request_time >= \""+sdf.format(request_after) + "\""; } if(request_before != null) { sql += " AND request_time <= \""+sdf.format(request_before) + "\""; } PreparedStatement stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); while(rs.next()) { recs.add(new CertificateRequestUserRecord(rs)); } stmt.close(); conn.close(); return recs; } @Override CertificateRequestUserRecord createRecord() throws SQLException { // TODO Auto-generated method stub return null; } }
package edu.washington.escience.myria.operator; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataInput; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.Objects; import java.util.Scanner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import edu.washington.escience.myria.DbException; import edu.washington.escience.myria.Schema; import edu.washington.escience.myria.Type; import edu.washington.escience.myria.storage.TupleBatch; import edu.washington.escience.myria.storage.TupleBatchBuffer; /** * Read and merge Tipsy bin file, iOrder ascii file and group number ascii file. * * @author leelee * */ public class TipsyFileScan extends LeafOperator { /** Required for Java serialization. */ private static final long serialVersionUID = 1L; /** The header size in bytes. */ private static final int H_SIZE = 32; /** The gas record size in bytes. */ private static final int G_SIZE = 48; /** The dark record size in bytes. */ private static final int D_SIZE = 36; /** The star record size in bytes. */ private static final int S_SIZE = 44; /** The data input for bin file. */ private transient DataInput dataInputForBin; /** Scanner used to parse the iOrder file. */ private transient Scanner iOrderScanner = null; /** Scanner used to parse the group number file. */ private transient Scanner grpScanner = null; /** Holds the tuples that are ready for release. */ private transient TupleBatchBuffer buffer; /** The bin file name. */ private final String binFileName; /** The iOrder file name. */ private final String iOrderFileName; /** The group number file name. */ private final String grpFileName; /** The number of gas particle record. */ private long ngas; /** The number of star particle record. */ private long nstar; /** The number of dark particle record. */ private long ndark; /** Which line of the file the scanner is currently on. */ private int lineNumber; /** Schema for all Tipsy files. */ private static final Schema TIPSY_SCHEMA = new Schema(ImmutableList.of(Type.LONG_TYPE, // iOrder Type.FLOAT_TYPE, // mass Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, Type.FLOAT_TYPE, // rho Type.FLOAT_TYPE, // temp Type.FLOAT_TYPE, // hsmooth Type.FLOAT_TYPE, // metals Type.FLOAT_TYPE, // tform Type.FLOAT_TYPE, // eps Type.FLOAT_TYPE, // phi Type.INT_TYPE, // grp Type.STRING_TYPE // type ), ImmutableList.of("iOrder", "mass", "x", "y", "z", "vx", "vy", "vz", "rho", "temp", "hsmooth", "metals", "tform", "eps", "phi", "grp", "type")); /** * Construct a new TipsyFileScan object using the given binary filename, iOrder filename and group number filename. By * default TipsyFileScan will read the given binary file in big endian format. * * @param binFileName The binary file that contains the data for gas, dark, star particles. * @param iOrderFileName The ascii file that contains the data for iOrder. * @param grpFileName The ascii file that contains the data for group number. */ public TipsyFileScan(final String binFileName, final String iOrderFileName, final String grpFileName) { Objects.requireNonNull(binFileName); Objects.requireNonNull(iOrderFileName); Objects.requireNonNull(grpFileName); this.binFileName = binFileName; this.iOrderFileName = iOrderFileName; this.grpFileName = grpFileName; } @Override protected final TupleBatch fetchNextReady() throws DbException { processGasRecords(); processDarkRecords(); processStarRecords(); return buffer.popAny(); } @Override protected final void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { buffer = new TupleBatchBuffer(getSchema()); InputStream iOrderInputStream = openFileOrUrlInputStream(iOrderFileName); InputStream grpInputStream = openFileOrUrlInputStream(grpFileName); int ntot; try { // Create a fileInputStream for the bin file InputStream fStreamForBin = openFileOrUrlInputStream(binFileName); BufferedInputStream bufferedStreamForBin = new BufferedInputStream(fStreamForBin); dataInputForBin = new DataInputStream(bufferedStreamForBin); dataInputForBin.readDouble(); // time ntot = dataInputForBin.readInt(); dataInputForBin.readInt(); ngas = dataInputForBin.readInt(); ndark = dataInputForBin.readInt(); nstar = dataInputForBin.readInt(); dataInputForBin.readInt(); long proposed = H_SIZE + ngas * G_SIZE + ndark * D_SIZE + nstar * S_SIZE; if (ntot != ngas + ndark + nstar) { throw new DbException("header info incorrect"); } if (fStreamForBin instanceof FileInputStream && proposed != ((FileInputStream)fStreamForBin).getChannel().size()) { throw new DbException("binary file size incorrect"); } } catch (IOException e) { throw new DbException(e); } Preconditions.checkArgument(iOrderInputStream != null, "FileScan iOrder input stream has not been set!"); Preconditions.checkArgument(grpInputStream != null, "FileScan group input stream has not been set!"); Preconditions.checkArgument(dataInputForBin != null, "FileScan binary input stream has not been set!"); iOrderScanner = new Scanner(new BufferedReader(new InputStreamReader(iOrderInputStream))); grpScanner = new Scanner(new BufferedReader(new InputStreamReader(grpInputStream))); int numIOrder = iOrderScanner.nextInt(); int numGrp = grpScanner.nextInt(); if (numIOrder != ntot) { throw new DbException("number of iOrder " + numIOrder + " is different from the number of tipsy record " + ntot + "."); } if (numGrp != ntot) { throw new DbException("number of group is different from the number of tipsy record."); } lineNumber = 0; } @Override protected final void cleanup() throws DbException { iOrderScanner = null; grpScanner = null; while (buffer.numTuples() > 0) { buffer.popAny(); } } /** * Construct tuples for gas particle records. The expected gas particles schema in the bin file is mass, x, y, z, vx, * vy, vz, rho, temp, hsmooth, metals, phi. Merge the record in the binary file with iOrder and group number and fill * in the each tuple column accordingly. * * @throws DbException if error reading from file. */ private void processGasRecords() throws DbException { while (ngas > 0 && (buffer.numTuples() < TupleBatch.BATCH_SIZE)) { lineNumber++; try { int count = 0; buffer.putLong(count++, iOrderScanner.nextLong()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); /* * TODO(leelee): Should be null for the next two columns. Put 0 for now as TupleBatchBuffer does not support * null value. */ buffer.putFloat(count++, 0); buffer.putFloat(count++, 0); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putInt(count++, grpScanner.nextInt()); buffer.putString(count++, "gas"); } catch (final IOException e) { throw new DbException(e); } final String iOrderRest = iOrderScanner.nextLine().trim(); if (iOrderRest.length() > 0) { throw new DbException("iOrderFile: Unexpected output at the end of line " + lineNumber + ": " + iOrderRest); } final String grpRest = grpScanner.nextLine().trim(); if (grpRest.length() > 0) { throw new DbException("grpFile: Unexpected output at the end of line " + lineNumber + ": " + grpRest); } ngas } } /** * Construct tuples for gas particle records. The expected dark particles schema in the bin file is mass, x, y, z, vx, * vy, vz, eps, phi. Merge the record in the binary file with iOrder and group number and fill in the each tuple * column accordingly. * * @throws DbException if error reading from file. */ private void processDarkRecords() throws DbException { while (ndark > 0 && (buffer.numTuples() < TupleBatch.BATCH_SIZE)) { lineNumber++; try { int count = 0; buffer.putLong(count++, iOrderScanner.nextLong()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); /* * TODO(leelee): Should be null for the next five columns. Put 0 for now as TupleBatchBuffer does not support * null value. */ buffer.putFloat(count++, 0); buffer.putFloat(count++, 0); buffer.putFloat(count++, 0); buffer.putFloat(count++, 0); buffer.putFloat(count++, 0); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putInt(count++, grpScanner.nextInt()); buffer.putString(count++, "dark"); } catch (final IOException e) { throw new DbException(e); } final String iOrderRest = iOrderScanner.nextLine().trim(); if (iOrderRest.length() > 0) { throw new DbException("iOrderFile: Unexpected output at the end of line " + lineNumber + ": " + iOrderRest); } final String grpRest = grpScanner.nextLine().trim(); if (grpRest.length() > 0) { throw new DbException("grpFile: Unexpected output at the end of line " + lineNumber + ": " + grpRest); } ndark } } /** * Construct tuples for gas particle records. The expected dark particles schema in the bin file is mass, x, y, z, vx, * vy, vz, metals, tform, eps, phi. Merge the record in the binary file with iOrder and group number and fill in the * each tuple column accordingly. * * @throws DbException if error reading from file. */ private void processStarRecords() throws DbException { while (nstar > 0 && (buffer.numTuples() < TupleBatch.BATCH_SIZE)) { lineNumber++; try { int count = 0; buffer.putLong(count++, iOrderScanner.nextLong()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); /* * TODO(leelee): Should be null for the next three columns. Put 0 for now as TupleBatchBuffer does not support * null value. */ buffer.putFloat(count++, 0); buffer.putFloat(count++, 0); buffer.putFloat(count++, 0); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putFloat(count++, dataInputForBin.readFloat()); buffer.putInt(count++, grpScanner.nextInt()); buffer.putString(count++, "star"); } catch (final IOException e) { throw new DbException(e); } final String iOrderRest = iOrderScanner.nextLine().trim(); if (iOrderRest.length() > 0) { throw new DbException("iOrderFile: Unexpected output at the end of line " + lineNumber + ": " + iOrderRest); } final String grpRest = grpScanner.nextLine().trim(); if (grpRest.length() > 0) { throw new DbException("grpFile: Unexpected output at the end of line " + lineNumber + ": " + grpRest); } nstar } } @Override protected Schema generateSchema() { return TIPSY_SCHEMA; } private static InputStream openFileOrUrlInputStream(String filenameOrUrl) throws DbException { try { return new URI(filenameOrUrl).toURL().openConnection().getInputStream(); } catch(URISyntaxException e) { return openFileInputStream(filenameOrUrl); } catch(MalformedURLException e) { return openFileInputStream(filenameOrUrl); } catch(IOException e) { throw new DbException(e); } } private static InputStream openFileInputStream(String filename) throws DbException { try { return new FileInputStream(filename); } catch(FileNotFoundException e) { throw new DbException(e); } } }
package gameEngine.view.gameFrame.inputAndDisplay; import java.awt.Dimension; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.border.Border; import net.miginfocom.swing.MigLayout; import gameEngine.view.Button; import gameEngine.view.Panel; /** * @author lalitamaraj * Panel used to receive user input and execute * user defined behavior on text input * by calling the submit method on inputSender */ public class InputPanel extends Panel { private static final long serialVersionUID = 1L; private static final int TEXTBOX_HEIGHT = 50; private static final int TEXTBOX_WIDTH = 200; private static final String SUBMIT_BUTTON_POSITION = "span 1"; private static final String TEXT_BOX_POSITION = "span 3"; private static final String LAYOUT_WRAP_SETTING = "wrap 4"; protected InputPanel (final InputSender inputSender) { super(); MigLayout layout = new MigLayout(LAYOUT_WRAP_SETTING); this.setLayout(layout); Border valuePanelBorder = BorderFactory.createTitledBorder(""); setBorder(valuePanelBorder); setBorder(valuePanelBorder); Button submit = new Button("Submit"); final JTextArea input = new JTextArea("add_gold"); input.setPreferredSize(new Dimension(TEXTBOX_WIDTH, TEXTBOX_HEIGHT)); this.add(new JScrollPane(input), TEXT_BOX_POSITION); this.add(submit, SUBMIT_BUTTON_POSITION); submit.addMouseListener(new MouseAdapter() { public void mouseClicked (MouseEvent me) { inputSender.submit(input.getText().trim()); input.setText(""); } }); } }
package gov.nih.nci.calab.ui.core; import gov.nih.nci.calab.domain.nano.characterization.Characterization; import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData; import gov.nih.nci.calab.domain.nano.characterization.physical.Morphology; import gov.nih.nci.calab.domain.nano.characterization.physical.Shape; import gov.nih.nci.calab.domain.nano.characterization.physical.Solubility; import gov.nih.nci.calab.domain.nano.characterization.physical.Surface; import gov.nih.nci.calab.domain.nano.characterization.toxicity.Cytotoxicity; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.exception.CalabException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.common.LookupService; import gov.nih.nci.calab.service.search.SearchNanoparticleService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.submit.SubmitNanoparticleService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.SortedSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; /** * This action serves as the base action for all characterization related action * classes. It includes common operations such as download, updateManufacturers. * * @author pansu */ /* * CVS $Id: BaseCharacterizationAction.java,v 1.27 2007/05/15 13:33:05 chenhang * Exp $ */ public abstract class BaseCharacterizationAction extends AbstractDispatchAction { protected CharacterizationBean prepareCreate(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // retrieve file content FileService fileService = new FileService(); for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { if (derivedDataFileBean.getId() != null) { byte[] content = fileService.getFileContent(new Long( derivedDataFileBean.getId())); if (content != null) { derivedDataFileBean.setFileContent(content); } } } // set createdBy and createdDate for the characterization UserBean user = (UserBean) session.getAttribute("user"); Date date = new Date(); charBean.setCreatedBy(user.getLoginName()); charBean.setCreatedDate(date); return charBean; } protected void postCreate(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String charName = theForm.getString("charName"); // save new lookup up types in the database definition tables. SubmitNanoparticleService service = new SubmitNanoparticleService(); service.addNewCharacterizationDataDropdowns(charBean, charName); request.getSession().setAttribute("newCharacterizationCreated", "true"); request.getSession().setAttribute("newCharacterizationSourceCreated", "true"); request.getSession().setAttribute("newInstrumentCreated", "true"); request.getSession().setAttribute("newCharacterizationFileTypeCreated", "true"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); } protected CharacterizationBean[] prepareCopy(HttpServletRequest request, DynaValidatorForm theForm, SubmitNanoparticleService service) throws Exception { CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String origParticleName = theForm.getString("particleName"); charBean.setParticleName(origParticleName); String[] otherParticles = (String[]) theForm.get("otherParticles"); Boolean copyData = (Boolean) theForm.get("copyData"); CharacterizationBean[] charBeans = new CharacterizationBean[otherParticles.length]; int i = 0; for (String particleName : otherParticles) { CharacterizationBean newCharBean = charBean.copy(copyData .booleanValue()); newCharBean.setParticleName(particleName); // reset view title String timeStamp = StringUtils.convertDateToString(new Date(), "MMddyyHHmmssSSS"); String autoTitle = CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX + timeStamp; newCharBean.setViewTitle(autoTitle); List<DerivedBioAssayDataBean> dataList = newCharBean .getDerivedBioAssayDataList(); // replace particleName in path and uri with new particleName for (DerivedBioAssayDataBean derivedBioAssayData : dataList) { String origUri = derivedBioAssayData.getUri(); if (origUri != null) derivedBioAssayData.setUri(origUri.replace( origParticleName, particleName)); } charBeans[i] = newCharBean; i++; } return charBeans; } /** * clear session data from the input form * * @param session * @param theForm * @param mapping * @throws Exception */ protected void clearMap(HttpSession session, DynaValidatorForm theForm) throws Exception { // reset achar and otherParticles theForm.set("otherParticles", new String[0]); theForm.set("copyData", false); theForm.set("achar", new CharacterizationBean()); theForm.set("morphology", new MorphologyBean()); theForm.set("shape", new ShapeBean()); theForm.set("surface", new SurfaceBean()); theForm.set("solubility", new SolubilityBean()); theForm.set("cytotoxicity", new CytotoxicityBean()); cleanSessionAttributes(session); } /** * Prepopulate data for the input form * * @param request * @param theForm * @throws Exception */ protected void initSetup(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); clearMap(session, theForm); String submitType = (String) request.getParameter("submitType"); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); String particleSource = theForm.getString("particleSource"); String charName = theForm.getString("charName"); InitSessionSetup.getInstance().setApplicationOwner(session); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); InitSessionSetup.getInstance().setAllInstruments(session); InitSessionSetup.getInstance().setAllDerivedDataFileTypes(session); InitSessionSetup.getInstance().setAllPhysicalDropdowns(session); InitSessionSetup.getInstance().setAllInvitroDropdowns(session); InitSessionSetup.getInstance().setAllCharacterizationMeasureUnitsTypes( session, charName); // TODO If there are more types of charactizations, add their // corresponding // protocol type here. if (submitType.equalsIgnoreCase("physical")) InitSessionSetup.getInstance().setAllProtocolNameVersionsByType( session, "Physical assay"); else InitSessionSetup.getInstance().setAllProtocolNameVersionsByType( session, "In vitro assay"); // set up other particle names from the same source LookupService service = new LookupService(); UserBean user = (UserBean) request.getSession().getAttribute("user"); SortedSet<String> allOtherParticleNames = service.getOtherParticles( particleSource, particleName, user); session.setAttribute("allOtherParticleNames", allOtherParticleNames); InitSessionSetup.getInstance().setDerivedDatumNames(session, charName); InitSessionSetup.getInstance().setAllCharacterizationDropdowns(session); } /** * Clean the session attribture * * @param sessioin * @throws Exception */ protected void cleanSessionAttributes(HttpSession session) throws Exception { for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { String element = (String) e.nextElement(); if (element.startsWith(CaNanoLabConstants.CHARACTERIZATION_FILE)) { session.removeAttribute(element); } } } /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.getInputForward(); } public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; // update editable dropdowns CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); ShapeBean shape = (ShapeBean) theForm.get("shape"); MorphologyBean morphology = (MorphologyBean) theForm.get("morphology"); CytotoxicityBean cyto = (CytotoxicityBean) theForm.get("cytotoxicity"); SolubilityBean solubility = (SolubilityBean) theForm.get("solubility"); SurfaceBean surface = (SurfaceBean) theForm.get("surface"); HttpSession session = request.getSession(); updateAllCharEditables(session, achar); updateShapeEditable(session, shape); updateMorphologyEditable(session, morphology); updateCytotoxicityEditable(session, cyto); updateSolubilityEditable(session, solubility); // updateSurfaceEditable(session, surface); return mapping.findForward("setup"); } /** * Set up the form for updating existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String characterizationId = request.getParameter("characterizationId"); SearchNanoparticleService service = new SearchNanoparticleService(); Characterization aChar = service .getCharacterizationAndDerivedDataBy(characterizationId); if (aChar == null) { throw new Exception( "This characterization no longer exists in the database. Please log in again to refresh."); } CharacterizationBean charBean = new CharacterizationBean(aChar); theForm.set("achar", charBean); // set characterizations with additional information if (aChar instanceof Shape) { theForm.set("shape", new ShapeBean((Shape) aChar)); } else if (aChar instanceof Morphology) { theForm.set("morphology", new MorphologyBean((Morphology) aChar)); } else if (aChar instanceof Solubility) { theForm.set("solubility", new SolubilityBean((Solubility) aChar)); } else if (aChar instanceof Surface) { theForm.set("surface", new SurfaceBean((Surface) aChar)); } else if (aChar instanceof Solubility) { theForm.set("solubility", new SolubilityBean((Solubility) aChar)); } else if (aChar instanceof Cytotoxicity) { theForm.set("cytotoxicity", new CytotoxicityBean( (Cytotoxicity) aChar)); } UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); UserBean user = (UserBean) request.getSession().getAttribute("user"); // set up charaterization files in the session int fileNumber = 0; for (DerivedBioAssayData obj : aChar.getDerivedBioAssayDataCollection()) { DerivedBioAssayDataBean fileBean = new DerivedBioAssayDataBean(obj); boolean status = userService.checkReadPermission(user, fileBean .getId()); if (status) { List<String> accessibleGroups = userService .getAccessibleGroups(fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); request.getSession().setAttribute( "characterizationFile" + fileNumber, fileBean); } fileNumber++; } return mapping.findForward("setup"); } /** * Prepare the form for viewing existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return setupUpdate(mapping, form, request, response); } /** * Load file action for characterization file loading. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward loadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String particleName = theForm.getString("particleName"); request.setAttribute("particleName", particleName); request.setAttribute("characterizationName", theForm .getString("charName")); request.setAttribute("loadFileForward", mapping.findForward("setup") .getPath()); CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); int fileNum = Integer.parseInt(request.getParameter("fileNumber")); DerivedBioAssayDataBean derivedBioAssayDataBean = achar .getDerivedBioAssayDataList().get(fileNum); request.setAttribute("file", derivedBioAssayDataBean); return mapping.findForward("loadFile"); } /** * Download action to handle characterization file download and viewing * * @param * @return */ public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileId = request.getParameter("fileId"); SubmitNanoparticleService service = new SubmitNanoparticleService(); LabFileBean fileBean = service.getFile(fileId); String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File dFile = new File(fileRoot + File.separator + fileBean.getUri()); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getName()); response.setHeader("cache-control", "Private"); java.io.InputStream in = new FileInputStream(dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { throw new CalabException( "File to download doesn't exist on the server"); } return null; } public ActionForward addFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add((DerivedBioAssayDataBean) origTables.get(i)); } // add a new one tables.add(new DerivedBioAssayDataBean()); achar.setDerivedBioAssayDataList(tables); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return input(mapping, form, request, response); } public ActionForward removeFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileIndexStr = (String) request.getParameter("fileInd"); int fileInd = Integer.parseInt(fileIndexStr); DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add((DerivedBioAssayDataBean) origTables.get(i)); } // remove the one at the index if (origNum > 0) { tables.remove(fileInd); } achar.setDerivedBioAssayDataList(tables); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return input(mapping, form, request, response); } public ActionForward addData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("fileInd"); int fileInd = Integer.parseInt(fileIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } dataList.add(new DatumBean()); derivedBioAssayDataBean.setDatumList(dataList); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return input(mapping, form, request, response); } public ActionForward removeData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("fileInd"); int fileInd = Integer.parseInt(fileIndexStr); String dataIndexStr = (String) request.getParameter("dataInd"); int dataInd = Integer.parseInt(dataIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } if (origNum > 0) dataList.remove(dataInd); derivedBioAssayDataBean.setDatumList(dataList); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return input(mapping, form, request, response); // return mapping.getInputForward(); this gives an // IndexOutOfBoundException in the jsp page } /** * Pepopulate data for the form * * @param request * @param theForm * @throws Exception */ public ActionForward deleteConfirmed(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); String strCharId = theForm.getString("characterizationId"); SubmitNanoparticleService service = new SubmitNanoparticleService(); service.deleteCharacterizations(particleName, particleType, new String[] { strCharId }); // signal the session that characterization has been changed request.getSession().setAttribute("newCharacterizationCreated", "true"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.delete.characterization"); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } // add edited option to all editable dropdowns private void updateAllCharEditables(HttpSession session, CharacterizationBean achar) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getCharacterizationSource(), "characterizationSources"); InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getInstrumentConfigBean().getInstrumentBean().getType(), "allInstrumentTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, achar.getInstrumentConfigBean().getInstrumentBean() .getManufacturer(), "allManufacturers"); for (DerivedBioAssayDataBean derivedBioAssayDataBean : achar .getDerivedBioAssayDataList()) { InitSessionSetup.getInstance().updateEditableDropdown(session, derivedBioAssayDataBean.getType(), "allDerivedDataFileTypes"); if (derivedBioAssayDataBean != null) { for (String category : derivedBioAssayDataBean.getCategories()) { InitSessionSetup.getInstance().updateEditableDropdown( session, category, "derivedDataCategories"); } for (DatumBean datum : derivedBioAssayDataBean.getDatumList()) { InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getName(), "datumNames"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getStatisticsType(), "charMeasureTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getUnit(), "charMeasureUnits"); } } } } // add edited option to all editable dropdowns private void updateShapeEditable(HttpSession session, ShapeBean shape) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, shape.getType(), "allShapeTypes"); } private void updateMorphologyEditable(HttpSession session, MorphologyBean morphology) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, morphology.getType(), "allMorphologyTypes"); } private void updateCytotoxicityEditable(HttpSession session, CytotoxicityBean cyto) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, cyto.getCellLine(), "allCellLines"); } private void updateSolubilityEditable(HttpSession session, SolubilityBean solubility) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, solubility.getSolvent(), "allSolventTypes"); } // private void updateSurfaceEditable(HttpSession session, // SurfaceBean surface) throws Exception { public boolean loginRequired() { return true; } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import java.awt.*; import java.awt.event.*; import javax.swing.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; /** * Wizard step to choose run mode * * @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a> */ public class ModeSelectionPanel extends JPanel { private JRadioButton unannotatedXmiOption, roundtripOption, annotateOption, reviewOption, curateOption, gmeDefaultsOption, gmeCleanupOption; private ButtonGroup group; private JPanel _this = this; private UserSelections userSelections = UserSelections.getInstance(); private UserPreferences prefs = UserPreferences.getInstance(); private JCheckBox privateApiCb = new JCheckBox("Use Private API", prefs.isUsePrivateApi()); public ModeSelectionPanel() { initUI(); } public void addActionListener(ActionListener l) { unannotatedXmiOption.addActionListener(l); roundtripOption.addActionListener(l); annotateOption.addActionListener(l); curateOption.addActionListener(l); reviewOption.addActionListener(l); gmeDefaultsOption.addActionListener(l); gmeCleanupOption.addActionListener(l); } public String getSelection() { return group.getSelection().getActionCommand(); } public boolean usePrivateApi() { return privateApiCb.isSelected(); } private void initUI() { this.setLayout(new BorderLayout()); JPanel infoPanel = new JPanel(); infoPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); infoPanel.setBackground(Color.WHITE); infoPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); infoPanel.add(new JLabel(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("siw-logo3_2.gif")))); JLabel infoLabel = new JLabel("<html>Welcome to the " + PropertyAccessor.getProperty("siw.title") + "</html>"); infoPanel.add(infoLabel); this.add(infoPanel, BorderLayout.NORTH); group = new ButtonGroup(); unannotatedXmiOption = new JRadioButton("1. " + RunMode.UnannotatedXmi.getTitleName() + " (" + RunMode.UnannotatedXmi.getAuthor() + ")"); unannotatedXmiOption.setActionCommand(RunMode.UnannotatedXmi.toString()); roundtripOption = new JRadioButton("2. " + RunMode.Roundtrip.getTitleName() + " (" + RunMode.Roundtrip.getAuthor() + ")"); roundtripOption.setActionCommand(RunMode.Roundtrip.toString()); annotateOption = new JRadioButton("3. " + RunMode.GenerateReport.getTitleName() + " (" + RunMode.GenerateReport.getAuthor() + ")"); annotateOption.setActionCommand(RunMode.GenerateReport.toString()); curateOption = new JRadioButton("4. " + RunMode.Curator.getTitleName() + " (" + RunMode.Curator.getAuthor() + ")"); curateOption.setActionCommand(RunMode.Curator.toString()); reviewOption = new JRadioButton("5. " + RunMode.Reviewer.getTitleName() + " (" + RunMode.Reviewer.getAuthor() + ")"); reviewOption.setActionCommand(RunMode.Reviewer.toString()); gmeDefaultsOption = new JRadioButton("6. " + RunMode.GMEDefaults.getTitleName() + " (" + RunMode.GMEDefaults.getAuthor() + ")"); gmeDefaultsOption.setActionCommand(RunMode.GMEDefaults.toString()); gmeCleanupOption = new JRadioButton("7. " + RunMode.GMECleanup.getTitleName() + " (" + RunMode.GMECleanup.getAuthor() + ")"); gmeCleanupOption.setActionCommand(RunMode.GMECleanup.toString()); // Get the preference setting for mode and set the radio buttons appropriately. RunMode mode = RunMode.UnannotatedXmi; try { mode = RunMode.valueOf(prefs.getModeSelection()); } catch (Exception ex){ // Ignore any exceptions and let "mode" default. } switch (mode) { case AnnotateXMI: reviewOption.setSelected(true); break; case Curator: curateOption.setSelected(true); break; case Roundtrip: reviewOption.setSelected(true); break; case Reviewer: reviewOption.setSelected(true); break; case GMEDefaults: gmeDefaultsOption.setSelected(true); break; case GMECleanup: gmeCleanupOption.setSelected(true); break; default: unannotatedXmiOption.setSelected(true); break; } group.add(unannotatedXmiOption); group.add(roundtripOption); group.add(annotateOption); group.add(curateOption); group.add(reviewOption); group.add(gmeDefaultsOption); group.add(gmeCleanupOption); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(0, 1)); buttonPanel.add (new JLabel("<html>Choose from the following SIW Options:</html>")); buttonPanel.add(unannotatedXmiOption); buttonPanel.add(roundtripOption); buttonPanel.add(annotateOption); buttonPanel.add(curateOption); buttonPanel.add(reviewOption); buttonPanel.add(gmeDefaultsOption); buttonPanel.add(gmeCleanupOption); this.setLayout(new BorderLayout()); this.add(infoPanel, BorderLayout.NORTH); this.add(buttonPanel, BorderLayout.CENTER); Font font = new Font("Serif", Font.PLAIN, 11); privateApiCb.setFont(font); JLabel privateApiLabel = new JLabel("<html><body>The private API is offered as an alternative to the caCORE public API.<br> It requires that the user be inside the NCI network or use VPN.</body></html>"); privateApiLabel.setFont(font); JPanel privateApiPanel = new JPanel(); privateApiPanel.setLayout(new FlowLayout()); privateApiPanel.add(privateApiCb); privateApiPanel.add(privateApiLabel); this.add(privateApiPanel, BorderLayout.SOUTH); } public static void main(String[] args) { JFrame frame = new JFrame("Prototype"); frame.getContentPane().add(new ModeSelectionPanel()); frame.setVisible(true); } }
package module1; import processing.core.PApplet; import processing.core.PImage; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.AbstractMapProvider; import de.fhpotsdam.unfolding.providers.Google; import de.fhpotsdam.unfolding.providers.ImmoScout; import de.fhpotsdam.unfolding.providers.MBTilesMapProvider; import de.fhpotsdam.unfolding.utils.MapUtils; public class HelloWorld extends PApplet { /** Your goal: add code to display second map, zoom in, and customize the background. * Feel free to copy and use this code, adding to it, modifying it, etc. * Don't forget the import lines above. */ // You can ignore this. It's to keep eclipse from reporting a warning private static final long serialVersionUID = 1L; /** This is where to find the local tiles, for working without an Internet connection */ public static String mbTilesString = "blankLight-1-3.mbtiles"; // IF YOU ARE WORKING OFFLINE: Change the value of this variable to true private static final boolean offline = false; /** The map we use to display our home town: La Jolla, CA */ UnfoldingMap map1; /** The map you will use to display your home town */ UnfoldingMap map2; /** The background image */ PImage backgroundImage; public void setup() { size(800, 600, P2D); // Set up the Applet window to be 800x600 // The OPENGL argument indicates to use the // Processing library's 2D drawing // You'll learn more about processing in Module 3 // This sets the background image for the Applet. String url = "http://dbfreebies.co/img/big/1122918-Ambient-Background-FREE-DL.png"; backgroundImage = loadImage(url, "png"); this.background(backgroundImage); // Select a map provider AbstractMapProvider provider = new Google.GoogleTerrainProvider(); // Set a zoom level int zoomLevel = 10; if (offline) { // If you are working offline, you need to use this provider // to work with the maps that are local on your computer. provider = new MBTilesMapProvider(mbTilesString); // 3 is the maximum zoom level for working offline zoomLevel = 3; } // Create a new UnfoldingMap to be displayed in this window. // The 2nd-5th arguments give the map's x, y, width and height // When you create your map we want you to play around with these // arguments to get your second map in the right place. // The 6th argument specifies the map provider. // There are several providers built-in. // Note if you are working offline you must use the MBTilesMapProvider map1 = new UnfoldingMap(this, 30, 50, 350, 500, provider); // The next line zooms in and centers the map at // 32.9 (latitude) and -117.2 (longitude) map1.zoomAndPanTo(zoomLevel, new Location(32.9f, -117.2f)); // This line makes the map interactive MapUtils.createDefaultEventDispatcher(this, map1); // Then you'll modify draw() below // Selects map provider AbstractMapProvider provider2 = new Google.GoogleTerrainProvider(); // Creates a new map map2 = new UnfoldingMap(this, 410, 50, 350, 500, provider2); // Zooms in and centers map2.zoomAndPanTo(zoomLevel, new Location(12.90f, 77.55f)); // Makes the another map interactive MapUtils.createDefaultEventDispatcher(this, map2); } /** Draw the Applet window. */ public void draw() { // Draws both the maps map1.draw(); map2.draw(); } }
package io.myweb; import io.myweb.http.MimeTypes; import io.myweb.http.Response; import java.io.*; public class ResponseWriter { public static final int BUFFER_LENGTH = 32 * 1024; private final OutputStream os; private final String produces; private boolean closed = false; public ResponseWriter(String produces, OutputStream os) throws IOException { this.produces = produces; this.os = os; } public ResponseWriter(OutputStream os) throws IOException { this(MimeTypes.MIME_TEXT_HTML, os); } public void close() throws IOException { close(null); } public synchronized void close(Response r) throws IOException { if (!isClosed()) { os.flush(); closed = true; if (r != null) r.onClose(); } } public boolean isClosed() { return closed; } public void write(Response response) throws IOException { if (!isClosed() && response!=null) { String contentType = response.getContentType(); if (contentType == null) contentType = produces; // if content type is text, make sure charset is specified if (!contentType.contains("charset=") && isTextContent(contentType)) { contentType = contentType + "; charset=" + response.getCharset(); } response.withContentType(contentType); if (response.getBody() instanceof InputStream) writeInputStream(response); else writeObject(response); } } static boolean isTextContent(String content) { return content.contains("text") || content.contains("xml") || content.contains("json"); } private void writeObject(Response response) throws IOException { if (response.getBody() != null) { byte[] body = response.getBody().toString().getBytes(); response.withLength(body.length); os.write(response.toString().getBytes()); os.write(body); } else { response.withLength(0); os.write(response.toString().getBytes()); } } private void writeInputStream(Response response) throws IOException { InputStream is = (InputStream) response.getBody(); final boolean chunked = !response.hasLength(); if (chunked) response.withChunks(); os.write(response.toString().getBytes()); copy(is, os, chunked); is.close(); } private long copy(InputStream from, OutputStream to, boolean chunkEncode) throws IOException { byte[] buf = new byte[BUFFER_LENGTH]; long total = 0; while (true) { int r = -1; try { r = from.read(buf); } catch (IOException e) { e.printStackTrace(); } if (r == -1 || Thread.interrupted()) { if (chunkEncode) to.write("0\r\n\r\n".getBytes()); break; } if(chunkEncode) { to.write((Integer.toHexString(r)+"\r\n").getBytes()); } to.write(buf, 0, r); if(chunkEncode) { to.write("\r\n".getBytes()); } total += r; } return total; } }
package com.matthewtamlin.spyglass.library.default_annotations; import com.matthewtamlin.spyglass.library.default_processors.DefaultToBooleanProcessor; import com.matthewtamlin.spyglass.library.meta_annotations.Default; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Default(processorClass = DefaultToBooleanProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface DefaultToBoolean { boolean value(); }
package info.guardianproject.fakepanicresponder; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListAdapter; import android.widget.TextView; import info.guardianproject.panic.Panic; import info.guardianproject.panic.PanicResponder; import java.util.ArrayList; public class MainActivity extends Activity { public static final String TAG = "FakePanicResponder"; private ConnectedAppEntry NONE; private ConnectedAppEntry DEFAULT; private PackageManager pm; private Button choosePanicTriggerButton; private int iconSize; private int dp20; private int dp10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (PanicResponder.checkForDisconnectIntent(this)) { finish(); return; } Resources r = getResources(); iconSize = r.getDrawable(R.drawable.ic_launcher).getIntrinsicHeight(); float density = r.getDisplayMetrics().density; dp10 = (int) (10 * density); dp20 = (int) (20 * density); pm = getPackageManager(); NONE = new ConnectedAppEntry(this, Panic.PACKAGE_NAME_NONE, R.string.none, android.R.drawable.ic_menu_close_clear_cancel, iconSize); DEFAULT = new ConnectedAppEntry(this, Panic.PACKAGE_NAME_DEFAULT, R.string.default_, android.R.drawable.btn_star, iconSize); setContentView(R.layout.activity_main); choosePanicTriggerButton = (Button) findViewById(R.id.choosePanicTriggerButton); choosePanicTriggerButton.setCompoundDrawablePadding(10); Button configButton = (Button) findViewById(R.id.configButton); configButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, PanicConfigActivity.class); startActivity(intent); } }); } @Override protected void onResume() { super.onResume(); String packageName = PanicResponder.getTriggerPackageName(this); showSelectedApp(packageName); choosePanicTriggerButton.setOnClickListener(new OnClickListener() { private ArrayList<ConnectedAppEntry> list; private int getIndexOfProviderList() { Context context = getApplicationContext(); for (ConnectedAppEntry app : list) { if (app.packageName.equals(PanicResponder.getTriggerPackageName(context))) { return list.indexOf(app); } } return 1; // Default } @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(R.string.choose_panic_trigger); list = new ArrayList<ConnectedAppEntry>(); list.add(0, NONE); list.add(1, DEFAULT); for (ResolveInfo resolveInfo : PanicResponder.resolveTriggerApps(pm)) { if (resolveInfo.activityInfo == null) continue; list.add(new ConnectedAppEntry(pm, resolveInfo.activityInfo, iconSize)); } ListAdapter adapter = new ArrayAdapter<ConnectedAppEntry>(MainActivity.this, android.R.layout.select_dialog_singlechoice, android.R.id.text1, list) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setCompoundDrawables(list.get(position).icon, null, null, null); // margin between image and text textView.setCompoundDrawablePadding(dp10); return view; } }; builder.setSingleChoiceItems(adapter, getIndexOfProviderList(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ConnectedAppEntry entry = list.get(which); PanicResponder.setTriggerPackageName(MainActivity.this, entry.packageName); showSelectedApp(entry); dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.show(); } }); } private void showSelectedApp(String packageName) { if (TextUtils.equals(packageName, NONE.packageName)) { showSelectedApp(NONE); } else { try { PackageInfo pi = pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); showSelectedApp(new ConnectedAppEntry(pm, pi.activities[0], iconSize)); } catch (NameNotFoundException e) { showSelectedApp(NONE); } } } @SuppressLint("NewApi") private void showSelectedApp(final ConnectedAppEntry entry) { choosePanicTriggerButton.setText(entry.simpleName); if (Build.VERSION.SDK_INT >= 17) choosePanicTriggerButton.setCompoundDrawablesRelative(entry.icon, null, null, null); else choosePanicTriggerButton.setCompoundDrawables(entry.icon, null, null, null); choosePanicTriggerButton.setPadding(dp20, dp20, dp20, dp20); choosePanicTriggerButton.setCompoundDrawablePadding(dp10); } }
/* @java.file.header */ package org.gridgain.grid.util.direct; import org.apache.ignite.internal.util.*; import org.apache.ignite.internal.util.direct.*; import org.jetbrains.annotations.*; import sun.misc.*; import sun.nio.ch.*; import java.nio.*; /** * Portable stream based on {@link ByteBuffer}. */ public class GridTcpCommunicationByteBufferStream { private static final Unsafe UNSAFE = GridUnsafe.unsafe(); private static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class); private static final long SHORT_ARR_OFF = UNSAFE.arrayBaseOffset(short[].class); private static final long INT_ARR_OFF = UNSAFE.arrayBaseOffset(int[].class); private static final long LONG_ARR_OFF = UNSAFE.arrayBaseOffset(long[].class); private static final long FLOAT_ARR_OFF = UNSAFE.arrayBaseOffset(float[].class); private static final long DOUBLE_ARR_OFF = UNSAFE.arrayBaseOffset(double[].class); private static final long CHAR_ARR_OFF = UNSAFE.arrayBaseOffset(char[].class); private static final long BOOLEAN_ARR_OFF = UNSAFE.arrayBaseOffset(boolean[].class); private static final byte[] BYTE_ARR_EMPTY = new byte[0]; private static final short[] SHORT_ARR_EMPTY = new short[0]; private static final int[] INT_ARR_EMPTY = new int[0]; private static final long[] LONG_ARR_EMPTY = new long[0]; private static final float[] FLOAT_ARR_EMPTY = new float[0]; private static final double[] DOUBLE_ARR_EMPTY = new double[0]; private static final char[] CHAR_ARR_EMPTY = new char[0]; private static final boolean[] BOOLEAN_ARR_EMPTY = new boolean[0]; private static final ArrayCreator<byte[]> BYTE_ARR_CREATOR = new ArrayCreator<byte[]>() { @Override public byte[] create(int len) { assert len >= 0; switch (len) { case 0: return BYTE_ARR_EMPTY; default: return new byte[len]; } } }; private static final ArrayCreator<short[]> SHORT_ARR_CREATOR = new ArrayCreator<short[]>() { @Override public short[] create(int len) { assert len >= 0; switch (len) { case 0: return SHORT_ARR_EMPTY; default: return new short[len]; } } }; private static final ArrayCreator<int[]> INT_ARR_CREATOR = new ArrayCreator<int[]>() { @Override public int[] create(int len) { assert len >= 0; switch (len) { case 0: return INT_ARR_EMPTY; default: return new int[len]; } } }; private static final ArrayCreator<long[]> LONG_ARR_CREATOR = new ArrayCreator<long[]>() { @Override public long[] create(int len) { assert len >= 0; switch (len) { case 0: return LONG_ARR_EMPTY; default: return new long[len]; } } }; private static final ArrayCreator<float[]> FLOAT_ARR_CREATOR = new ArrayCreator<float[]>() { @Override public float[] create(int len) { assert len >= 0; switch (len) { case 0: return FLOAT_ARR_EMPTY; default: return new float[len]; } } }; private static final ArrayCreator<double[]> DOUBLE_ARR_CREATOR = new ArrayCreator<double[]>() { @Override public double[] create(int len) { assert len >= 0; switch (len) { case 0: return DOUBLE_ARR_EMPTY; default: return new double[len]; } } }; private static final ArrayCreator<char[]> CHAR_ARR_CREATOR = new ArrayCreator<char[]>() { @Override public char[] create(int len) { assert len >= 0; switch (len) { case 0: return CHAR_ARR_EMPTY; default: return new char[len]; } } }; private static final ArrayCreator<boolean[]> BOOLEAN_ARR_CREATOR = new ArrayCreator<boolean[]>() { @Override public boolean[] create(int len) { assert len >= 0; switch (len) { case 0: return BOOLEAN_ARR_EMPTY; default: return new boolean[len]; } } }; private final GridTcpMessageFactory msgFactory; private ByteBuffer buf; private byte[] heapArr; private long baseOff; private int arrOff = -1; private Object tmpArr; private int tmpArrOff; private int tmpArrBytes; private boolean msgTypeDone; private GridTcpCommunicationMessageAdapter msg; private boolean lastFinished; /** * @param msgFactory Message factory. */ public GridTcpCommunicationByteBufferStream(@Nullable GridTcpMessageFactory msgFactory) { this.msgFactory = msgFactory; } /** * @param buf Buffer. */ public void setBuffer(ByteBuffer buf) { assert buf != null; if (this.buf != buf) { this.buf = buf; heapArr = buf.isDirect() ? null : buf.array(); baseOff = buf.isDirect() ? ((DirectBuffer)buf).address() : BYTE_ARR_OFF; } } public int remaining() { return buf.remaining(); } /** * @return Whether last object was fully written or read. */ public boolean lastFinished() { return lastFinished; } /** {@inheritDoc} */ public void writeByte(byte val) { int pos = buf.position(); UNSAFE.putByte(heapArr, baseOff + pos, val); buf.position(pos + 1); } /** {@inheritDoc} */ public void writeByteArray(byte[] val) { assert val != null; lastFinished = writeArray(val, BYTE_ARR_OFF, val.length, val.length); } /** {@inheritDoc} */ public void writeBoolean(boolean val) { int pos = buf.position(); UNSAFE.putBoolean(heapArr, baseOff + pos, val); buf.position(pos + 1); } /** {@inheritDoc} */ public void writeBooleanArray(boolean[] val) { assert val != null; lastFinished = writeArray(val, BOOLEAN_ARR_OFF, val.length, val.length); } /** {@inheritDoc} */ public void writeShort(short val) { int pos = buf.position(); UNSAFE.putShort(heapArr, baseOff + pos, val); buf.position(pos + 2); } /** {@inheritDoc} */ public void writeShortArray(short[] val) { assert val != null; lastFinished = writeArray(val, SHORT_ARR_OFF, val.length, val.length << 1); } /** {@inheritDoc} */ public void writeChar(char val) { int pos = buf.position(); UNSAFE.putChar(heapArr, baseOff + pos, val); buf.position(pos + 2); } /** {@inheritDoc} */ public void writeCharArray(char[] val) { assert val != null; lastFinished = writeArray(val, CHAR_ARR_OFF, val.length, val.length << 1); } /** {@inheritDoc} */ public void writeInt(int val) { int pos = buf.position(); UNSAFE.putInt(heapArr, baseOff + pos, val); buf.position(pos + 4); } /** {@inheritDoc} */ public void writeIntArray(int[] val) { assert val != null; lastFinished = writeArray(val, INT_ARR_OFF, val.length, val.length << 2); } /** {@inheritDoc} */ public void writeFloat(float val) { int pos = buf.position(); UNSAFE.putFloat(heapArr, baseOff + pos, val); buf.position(pos + 4); } /** {@inheritDoc} */ public void writeFloatArray(float[] val) { assert val != null; lastFinished = writeArray(val, FLOAT_ARR_OFF, val.length, val.length << 2); } /** {@inheritDoc} */ public void writeLong(long val) { int pos = buf.position(); UNSAFE.putLong(heapArr, baseOff + pos, val); buf.position(pos + 8); } /** {@inheritDoc} */ public void writeLongArray(long[] val) { assert val != null; lastFinished = writeArray(val, LONG_ARR_OFF, val.length, val.length << 3); } /** {@inheritDoc} */ public void writeDouble(double val) { int pos = buf.position(); UNSAFE.putDouble(heapArr, baseOff + pos, val); buf.position(pos + 8); } /** {@inheritDoc} */ public void writeDoubleArray(double[] val) { assert val != null; lastFinished = writeArray(val, DOUBLE_ARR_OFF, val.length, val.length << 3); } /** * @param msg Message. */ public void writeMessage(GridTcpCommunicationMessageAdapter msg) { assert msg != null; lastFinished = buf.hasRemaining() && msg.writeTo(buf); } /** {@inheritDoc} */ public byte readByte() { assert buf.hasRemaining(); int pos = buf.position(); buf.position(pos + 1); return UNSAFE.getByte(heapArr, baseOff + pos); } /** {@inheritDoc} */ public byte[] readByteArray() { return readArray(BYTE_ARR_CREATOR, 0, BYTE_ARR_OFF); } /** {@inheritDoc} */ public boolean readBoolean() { assert buf.hasRemaining(); int pos = buf.position(); buf.position(pos + 1); return UNSAFE.getBoolean(heapArr, baseOff + pos); } /** {@inheritDoc} */ public boolean[] readBooleanArray() { return readArray(BOOLEAN_ARR_CREATOR, 0, BOOLEAN_ARR_OFF); } /** {@inheritDoc} */ public short readShort() { assert buf.remaining() >= 2; int pos = buf.position(); buf.position(pos + 2); return UNSAFE.getShort(heapArr, baseOff + pos); } /** {@inheritDoc} */ public short[] readShortArray() { return readArray(SHORT_ARR_CREATOR, 1, SHORT_ARR_OFF); } /** {@inheritDoc} */ public char readChar() { assert buf.remaining() >= 2; int pos = buf.position(); buf.position(pos + 2); return UNSAFE.getChar(heapArr, baseOff + pos); } /** {@inheritDoc} */ public char[] readCharArray() { return readArray(CHAR_ARR_CREATOR, 1, CHAR_ARR_OFF); } /** {@inheritDoc} */ public int readInt() { assert buf.remaining() >= 4; int pos = buf.position(); buf.position(pos + 4); return UNSAFE.getInt(heapArr, baseOff + pos); } /** {@inheritDoc} */ public int[] readIntArray() { return readArray(INT_ARR_CREATOR, 2, INT_ARR_OFF); } /** {@inheritDoc} */ public float readFloat() { assert buf.remaining() >= 4; int pos = buf.position(); buf.position(pos + 4); return UNSAFE.getFloat(heapArr, baseOff + pos); } /** {@inheritDoc} */ public float[] readFloatArray() { return readArray(FLOAT_ARR_CREATOR, 2, FLOAT_ARR_OFF); } /** {@inheritDoc} */ public long readLong() { assert buf.remaining() >= 8; int pos = buf.position(); buf.position(pos + 8); return UNSAFE.getLong(heapArr, baseOff + pos); } /** {@inheritDoc} */ public long[] readLongArray() { return readArray(LONG_ARR_CREATOR, 3, LONG_ARR_OFF); } /** {@inheritDoc} */ public double readDouble() { assert buf.remaining() >= 8; int pos = buf.position(); buf.position(pos + 8); return UNSAFE.getDouble(heapArr, baseOff + pos); } /** {@inheritDoc} */ public double[] readDoubleArray() { return readArray(DOUBLE_ARR_CREATOR, 3, DOUBLE_ARR_OFF); } /** * @return Message. */ public GridTcpCommunicationMessageAdapter readMessage() { if (!msgTypeDone) { if (!buf.hasRemaining()) { lastFinished = false; return null; } byte type = readByte(); msg = type == Byte.MIN_VALUE ? null : msgFactory.create(type); msgTypeDone = true; } if (msg == null || msg.readFrom(buf)) { GridTcpCommunicationMessageAdapter msg0 = msg; msgTypeDone = false; msg = null; lastFinished = true; return msg0; } else { lastFinished = false; return null; } } /** * @param arr Array. * @param off Offset. * @param len Length. * @param bytes Length in bytes. * @return Whether array was fully written */ private boolean writeArray(Object arr, long off, int len, int bytes) { assert arr != null; assert arr.getClass().isArray() && arr.getClass().getComponentType().isPrimitive(); assert off > 0; assert len >= 0; assert bytes >= 0; assert bytes >= arrOff; if (arrOff == -1) { if (remaining() < 4) return false; writeInt(len); arrOff = 0; } int toWrite = bytes - arrOff; int pos = buf.position(); int remaining = buf.remaining(); if (toWrite <= remaining) { UNSAFE.copyMemory(arr, off + arrOff, heapArr, baseOff + pos, toWrite); pos += toWrite; buf.position(pos); arrOff = -1; return true; } else { UNSAFE.copyMemory(arr, off + arrOff, heapArr, baseOff + pos, remaining); pos += remaining; buf.position(pos); arrOff += remaining; return false; } } /** * @param creator Array creator. * @param lenShift Array length shift size. * @param off Base offset. * @return Array or special value if it was not fully read. */ private <T> T readArray(ArrayCreator<T> creator, int lenShift, long off) { assert creator != null; if (tmpArr == null) { if (remaining() < 4) { lastFinished = false; return null; } int len = readInt(); switch (len) { case -1: lastFinished = true; return null; case 0: lastFinished = true; return creator.create(0); default: tmpArr = creator.create(len); tmpArrBytes = len << lenShift; } } int toRead = tmpArrBytes - tmpArrOff; int remaining = buf.remaining(); int pos = buf.position(); if (remaining < toRead) { UNSAFE.copyMemory(heapArr, baseOff + pos, tmpArr, off + tmpArrOff, remaining); buf.position(pos + remaining); tmpArrOff += remaining; lastFinished = false; return null; } else { UNSAFE.copyMemory(heapArr, baseOff + pos, tmpArr, off + tmpArrOff, toRead); buf.position(pos + toRead); T arr = (T)tmpArr; tmpArr = null; tmpArrBytes = 0; tmpArrOff = 0; lastFinished = true; return arr; } } /** * Array creator. */ private static interface ArrayCreator<T> { /** * @param len Array length or {@code -1} if array was not fully read. * @return New array. */ public T create(int len); } }
package net.powermatcher.api.data; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * <p> * Bid is an immutable data class specifying a bid curve in either price points * or by an demand array representation. * </p> * * @author FAN * @version 1.0 */ public class Bid { /** * The marketBasis for bids and prices. */ private MarketBasis marketBasis; /** * Demand array for each price step in the market basis. */ private double[] demand; /** * Price points in a bid curve . */ private PricePoint[] pricePoints; /** * Holds the bidNumber. */ private int bidNumber; /** * Constructs an instance of this class from the specified other parameter. * * @param other * The other (<code>Bid</code>) parameter. * @see #Bid(MarketBasis) * @see #Bid(MarketBasis,double[]) * @see #Bid(MarketBasis,PricePoint) * @see #Bid(MarketBasis,PricePoint,PricePoint) * @see #Bid(MarketBasis,PricePoint[]) */ public Bid(final Bid other) { this.marketBasis = other.marketBasis; this.demand = other.demand; this.pricePoints = other.pricePoints; } /** * Constructs an instance of this class from the specified other parameter, * but assign a new bid number. * * @param other * The other (<code>Bid</code>) parameter. * @see #Bid(MarketBasis) * @see #Bid(MarketBasis,double[]) * @see #Bid(MarketBasis,PricePoint) * @see #Bid(MarketBasis,PricePoint,PricePoint) * @see #Bid(MarketBasis,PricePoint[]) */ public Bid(final Bid other, final int newBidNumer) { this(other); this.bidNumber = newBidNumer; } /** * Constructs an instance of this class from the specified market basis * parameter. An zero bid is created. * * @param marketBasis * The market basis (<code>MarketBasis</code>) parameter. * @see #Bid(Bid) * @see #Bid(MarketBasis,double[]) * @see #Bid(MarketBasis,PricePoint) * @see #Bid(MarketBasis,PricePoint,PricePoint) * @see #Bid(MarketBasis,PricePoint[]) */ public Bid(final MarketBasis marketBasis) { this(marketBasis, new PricePoint(0, 0.0d)); } /** * Constructs an instance of this class from the specified market basis and * demand parameters. The demand array will be cloned. * * @param marketBasis * The market basis (<code>MarketBasis</code>) parameter. * @param demand * The demand (<code>double[]</code>) parameter. * @see #Bid(Bid) * @see #Bid(MarketBasis) * @see #Bid(MarketBasis,PricePoint) * @see #Bid(MarketBasis,PricePoint,PricePoint) * @see #Bid(MarketBasis,PricePoint[]) */ public Bid(final MarketBasis marketBasis, final double[] demand) { if (demand == null || marketBasis.getPriceSteps() != demand.length) { throw new InvalidParameterException( "Missing or incorrect number of demand values for market basis."); } double lastDemand = demand[0]; for (int i = 1; i < demand.length; i++) { double currentDemand = demand[i]; if (currentDemand > lastDemand) { throw new InvalidParameterException( "Bid must be strictly descending."); } lastDemand = currentDemand; } this.marketBasis = marketBasis; this.demand = demand.clone(); } /** * Constructs an instance of this class from the specified market basis and * price point parameters. The price point will be cloned. * * @param marketBasis * The market basis (<code>MarketBasis</code>) parameter. * @param pricePoint * The price point (<code>PricePoint</code>) parameter. * @see #Bid(Bid) * @see #Bid(MarketBasis) * @see #Bid(MarketBasis,double[]) * @see #Bid(MarketBasis,PricePoint,PricePoint) * @see #Bid(MarketBasis,PricePoint[]) */ public Bid(final MarketBasis marketBasis, final PricePoint pricePoint) { this.marketBasis = marketBasis; this.pricePoints = new PricePoint[] { new PricePoint(pricePoint) }; } /** * Constructs an instance of this class from the specified market basis, * price point1 and price point2 parameters. The price points will be * cloned. * * @param marketBasis * The market basis (<code>MarketBasis</code>) parameter. * @param pricePoint1 * The price point1 (<code>PricePoint</code>) parameter. * @param pricePoint2 * The price point2 (<code>PricePoint</code>) parameter. * @see #Bid(Bid) * @see #Bid(MarketBasis) * @see #Bid(MarketBasis,double[]) * @see #Bid(MarketBasis,PricePoint) * @see #Bid(MarketBasis,PricePoint[]) */ public Bid(final MarketBasis marketBasis, final PricePoint pricePoint1, final PricePoint pricePoint2) { this(marketBasis, new PricePoint[] { pricePoint1, pricePoint2 }); } /** * Constructs an instance of this class from the specified market basis and * price points parameters. The demand array will not be cloned, so should * not be updated beyond this call. * * @param marketBasis * The market basis (<code>MarketBasis</code>) parameter. * @param bidNumber * The bid number * @param pricePoints * The price points (<code>PricePoint[]</code>) parameter. * @see #Bid(Bid) * @see #Bid(MarketBasis) * @see #Bid(MarketBasis,double[]) * @see #Bid(MarketBasis,PricePoint) * @see #Bid(MarketBasis,PricePoint,PricePoint) */ private Bid(final MarketBasis marketBasis, final int bidNumber, final PricePoint[] pricePoints) { this.marketBasis = marketBasis; this.bidNumber = bidNumber; this.pricePoints = clone(pricePoints); } /** * Constructs an instance of this class from the specified market basis and * price points parameters. The price points array will be cloned. * * @param marketBasis * The market basis (<code>MarketBasis</code>) parameter. * @param pricePoints * The price points (<code>PricePoint[]</code>) parameter. * @see #Bid(Bid) * @see #Bid(MarketBasis) * @see #Bid(MarketBasis,double[]) * @see #Bid(MarketBasis,PricePoint) * @see #Bid(MarketBasis,PricePoint,PricePoint) */ public Bid(final MarketBasis marketBasis, final PricePoint[] pricePoints) { if (pricePoints == null || pricePoints.length < 0) { throw new InvalidParameterException( "Missing or incorrect number of price points."); } if (pricePoints.length > 0) { double lastDemand = pricePoints[0].getDemand(); double lastNormalizedPrice = pricePoints[0].getNormalizedPrice(); for (int i = 1; i < pricePoints.length; i++) { double currentDemand = pricePoints[i].getDemand(); double currentNormalizedPrice = pricePoints[i] .getNormalizedPrice(); if (currentNormalizedPrice < lastNormalizedPrice) { throw new InvalidParameterException( "Price must be strictly ascending."); } if (currentDemand > lastDemand) { throw new InvalidParameterException( "Bid must be strictly descending."); } lastDemand = currentDemand; } } this.marketBasis = marketBasis; this.pricePoints = clone(pricePoints); } /** * Constructs an instance of this class from the specified market basis, bid * number and demand parameters. The demand array will not be cloned, so * should not be updated beyond this call. * * @param marketBasis * The market basis (<code>MarketBasis</code>) parameter. * @param bidNumber * The bid number * @param demand * The demand (<code>double[]</code>) parameter. * @see #Bid() * @see #Bid(Bid) * @see #Bid(MarketBasis) * @see #Bid(MarketBasis,PricePoint) * @see #Bid(MarketBasis,PricePoint,PricePoint) * @see #Bid(MarketBasis,PricePoint[]) */ private Bid(MarketBasis marketBasis, final int bidNumber, double[] demand) { this.marketBasis = marketBasis; this.bidNumber = bidNumber; this.demand = demand; } /** * Aggregate with the specified other parameter. * * @param other * The other (<code>Bid</code>) parameter. * @return A copy of this bid with the other bid aggregated into it. */ public Bid aggregate(final Bid other) { double[] otherDemand = other.toMarketBasis(this.marketBasis) .getUnclonedDemand(); double[] aggregatedDemand = this.getDemand(); for (int i = 0; i < aggregatedDemand.length; i++) { aggregatedDemand[i] += otherDemand[i]; } return new Bid(this.marketBasis, this.bidNumber, aggregatedDemand); } /** * Calculate intersection with the specified target demand and return the * Price result. * * @param targetDemand * The target demand (<code>double</code>) parameter. * @return Results of the intersection (<code>Price</code>) value. */ // TODO The Cyclomatic Complexity of this method "calculateIntersection" is // 12 which is greater than 10 authorized. public Price calculateIntersection(final double targetDemand) { double[] unclonedDemand = getUnclonedDemand(); int leftBound = 0; int rightBound = unclonedDemand.length - 1; int middle = rightBound / 2; while (leftBound < middle) { if (unclonedDemand[middle] > targetDemand) { leftBound = middle; } else { rightBound = middle; } middle = (leftBound + rightBound) / 2; } /* * Find the point where the demand falls below the target */ while (rightBound < unclonedDemand.length && unclonedDemand[rightBound] >= targetDemand) { rightBound += 1; } /* * The index of the point which is just above the intersection is now * stored in the variable 'middle'. This means that middle + 1 is the * index of the point that lies just under the intersection. That means * that the exact intersection is between middle and middle+1, hence a * weighted interpolation is needed. * * Pricing for boundary cases: 1) If the curve is a flat line, if the * demand is positive the price will become the maximum price, or if the * demand is zero or negative, the price will become 0. 2) If the curve * is a single step, the price of the stepping point (the left or the * right boundary). */ int priceStep; // TODO Refactor this code to not nest more than 3 // if/for/while/switch/try statements. if (leftBound > 0 && rightBound < unclonedDemand.length) { /* Interpolate */ double interpolation = ((unclonedDemand[leftBound] - targetDemand) / (unclonedDemand[leftBound] - unclonedDemand[rightBound])) * (rightBound - leftBound); priceStep = leftBound + (int) Math.ceil(interpolation); } else { if (leftBound == 0 && rightBound == unclonedDemand.length) { /* Curve is flat line or single step at leftBound */ if (unclonedDemand[leftBound] != 0) { /* * Curve is flat line for non-zero demand or single step at * leftBound */ if (unclonedDemand[leftBound + 1] == 0) { /* Curve is a single step at leftBound */ priceStep = leftBound + 1; } else { /* Curve is flat line for non-zero demand */ priceStep = rightBound - 1; } } else { /* Curve is flat line for zero demand 0 */ priceStep = this.marketBasis.toPriceStep(0); } } else { /* Curve is a single step at leftBound */ priceStep = unclonedDemand[leftBound] <= targetDemand ? leftBound : leftBound + 1; } } double intersectionPrice = this.marketBasis.toPrice(this.marketBasis .boundPriceStep(priceStep)); return new Price(this.marketBasis, intersectionPrice); } /** * Subtract the other bid curve from this bid curve. Subtract is the inverse * of aggregate. The other bid does not have to be based on the same market * basis. * * @param other * The other (<code>Bid</code>) parameter. * @return A copy of this bid with the other bid subtracted from it. */ public Bid subtract(final Bid other) { double[] otherDemand = other.toMarketBasis(this.marketBasis) .getUnclonedDemand(); double[] newDemand = this.getDemand(); for (int i = 0; i < newDemand.length; i++) { newDemand[i] -= otherDemand[i]; } return new Bid(this.marketBasis, this.bidNumber, newDemand); } /** * Convert this bid to another market basis. * * @param newMarketBasis * The new market basis (<code>MarketBasis</code>) parameter. * @return A copy of this bid converted to the new market basis. * @see #getMarketBasis() */ public Bid toMarketBasis(final MarketBasis newMarketBasis) { if (this.marketBasis.equals(newMarketBasis)) { return this; } else { assert this.marketBasis.getCommodity().equals( newMarketBasis.getCommodity()); assert this.marketBasis.getCurrency().equals( newMarketBasis.getCurrency()); if (this.pricePoints == null) { double[] oldDemand = getUnclonedDemand(); double[] newDemand = new double[newMarketBasis.getPriceSteps()]; for (int i = 0; i < newDemand.length; i++) { double newPrice = this.marketBasis .boundPrice(newMarketBasis.toPrice(i)); int oldPriceStep = this.marketBasis.toPriceStep(newPrice); newDemand[i] = oldDemand[oldPriceStep]; } return new Bid(newMarketBasis, this.bidNumber, newDemand); } else { PricePoint[] newPricePoints = new PricePoint[this.pricePoints.length]; for (int i = 0; i < newPricePoints.length; i++) { PricePoint oldPricePoint = this.pricePoints[i]; double price = this.marketBasis.toPrice(this.marketBasis .toPriceStep(oldPricePoint.getNormalizedPrice())); newPricePoints[i] = new PricePoint( newMarketBasis.toNormalizedPrice(price), oldPricePoint.getDemand()); } return new Bid(newMarketBasis, this.bidNumber, newPricePoints); } } } /** * Transpose the bid curve by adding an offset to the demand. * * @param offset * The offset (<code>double</code>) parameter. */ public Bid transpose(final double offset) { double[] newDemand = this.getDemand(); for (int i = 0; i < newDemand.length; i++) { newDemand[i] += offset; } return new Bid(this.marketBasis, this.bidNumber, newDemand); } /** * Create a new PricePoint corresponding to the demand value at priceSte. * * @param priceStep * The price step (<code>int</code>) parameter. * @return The new (<code>PricePoint</code>). */ private PricePoint newPoint(int priceStep) { return new PricePoint(this.marketBasis.toNormalizedPrice(priceStep), this.demand[priceStep]); } /** * Gets the bid number (int) value. * * @return The bid number (<code>int</code>) value. */ public int getBidNumber() { return this.bidNumber; } /** * Gets the cloned demand (double[]) value. * * @return The cloned demand (<code>double[]</code>) value. * @see #getDemand(double) * @see #getDemand(int) * @see #getMaximumDemand() * @see #getMinimumDemand() */ public double[] getDemand() { return getUnclonedDemand().clone(); } /** * Gets the uncloned demand (double[]) value. * * @return The uncloned demand (<code>double[]</code>) value. * @see #getDemand(double) * @see #getDemand(int) * @see #getMaximumDemand() * @see #getMinimumDemand() */ private double[] getUnclonedDemand() { // TODO Refactor this code to not nest more than 3 // if/for/while/switch/try statements if (this.demand == null && this.pricePoints != null) { int priceSteps = this.marketBasis.getPriceSteps(); double[] newDemand = new double[priceSteps]; int numPoints = this.pricePoints.length; int i = 0; double lastValue = numPoints == 0 ? 0 : this.pricePoints[0] .getDemand(); for (int p = 0; p < numPoints; p++) { PricePoint pricePoint = this.pricePoints[p]; int priceStep = this.marketBasis.toPriceStep(pricePoint .getNormalizedPrice()); priceStep = this.marketBasis.boundPriceStep(priceStep); int steps = priceStep - i + 1; double value = pricePoint.getDemand(); if (steps > 0) { double delta = (value - lastValue) / steps; while (i <= priceStep) { newDemand[i] = value - (priceStep - i) * delta; i += 1; } } else { newDemand[priceStep] = value; } lastValue = value; } while (i < priceSteps) { newDemand[i++] = lastValue; } this.demand = newDemand; } return this.demand; } /** * Get demand with the specified price parameter and return the double * result. * * @param price * The price (<code>double</code>) parameter. * @return Results of the get demand (<code>double</code>) value. * @see #getDemand() * @see #getDemand(int) * @see #getMaximumDemand() * @see #getMinimumDemand() */ public double getDemand(final double price) { return getDemand(this.marketBasis.toPriceStep(price)); } /** * Get demand with the specified price step parameter and return the double * result. * * @param priceStep * The price step (<code>int</code>) parameter. * @return Results of the get demand (<code>double</code>) value. * @see #getDemand() * @see #getDemand(double) * @see #getMaximumDemand() * @see #getMinimumDemand() */ public double getDemand(final int priceStep) { double[] unclonedDemand = getUnclonedDemand(); return unclonedDemand[this.marketBasis.boundPriceStep(priceStep)]; } /** * Gets the market basis value. * * @return The market basis (<code>MarketBasis</code>) value. * @see #toMarketBasis(MarketBasis) */ public MarketBasis getMarketBasis() { return this.marketBasis; } /** * Gets the maximum demand (double) value. * * @return The maximum demand (<code>double</code>) value. */ public double getMaximumDemand() { double maxDemand = 0; if (this.pricePoints != null && this.pricePoints.length > 0) { maxDemand = this.pricePoints[0].getDemand(); } else if (this.demand != null && this.demand.length > 0) { maxDemand = this.demand[0]; } return maxDemand; } /** * Gets the minimum demand (double) value. * * @return The minimum demand (<code>double</code>) value. */ public double getMinimumDemand() { double minDemand = 0; if (this.pricePoints != null && this.pricePoints.length > 0) { minDemand = this.pricePoints[this.pricePoints.length - 1] .getDemand(); } else if (this.demand != null && this.demand.length > 0) { minDemand = this.demand[this.demand.length - 1]; } return minDemand; } /** * Gets the cloned price points (PricePoint[]) value. * * @return The cloned price points (<code>PricePoint[]</code>) value, or * null if the price points have not been calculated or set. * @see #getCalculatedPricePoints() */ public PricePoint[] getPricePoints() { return clone(this.pricePoints); } /** * Gets the cloned calculated price points (PricePoint[]) value. The price * points will be calculated from the demand array, if necessary. * * @return The cloned price points (<code>PricePoint[]</code>) value, or * null if no price points or demand array has been set. * @see #getPricePoints() */ // TODO The Cyclomatic Complexity of this method "getCalculatedPricePoints" // is 18 which is greater than 10 authorized. public PricePoint[] getCalculatedPricePoints() { PricePoint[] calculatedPricePoints = null; if (this.pricePoints != null) { calculatedPricePoints = this.pricePoints.clone(); } else if (this.demand != null) { int priceSteps = this.marketBasis.getPriceSteps(); assert this.demand.length == priceSteps; List<PricePoint> points = new ArrayList<PricePoint>(priceSteps); /* * Flag to indicate if the last price point is the start of a flat * segment. */ boolean flatStart = false; /* * Flag to indicate if the last price point is the end point of a * flat segment. */ boolean flatEnd = false; int i = 0; while (i < priceSteps - 1) { /* * Search for the last price step in the flat segment, if any. * At the end of this loop delta is the difference for the next * demand after the flat segment. */ PricePoint flatEndPoint = null; double delta = 0.0d; while (i < priceSteps - 1 && (delta = this.demand[i] - this.demand[i + 1]) == 0) { i += 1; flatEnd = true; } /* * Add a point at i for the following two cases: 1) If not at * the end of the demand array, add the next point for i and * remember that this point is the end of a flat segment. 2) Add * a final point if past the end of the demand array, but the * previous point was not the beginning of a flat segment. */ if (i < priceSteps - 1 || !flatStart) { flatEndPoint = newPoint(i); points.add(flatEndPoint); flatStart = false; } i += 1; // TODO Refactor this code to not nest more than 3 // if/for/while/switch/try statements. /* * If not at the end of the demand array, check if the following * segment is a step or an inclining segment. */ if (i < priceSteps - 1) { // TODO Test for floating point equality. Not just == if (this.demand[i] - this.demand[i + 1] == delta) { /* * Here i is in a constantly inclining or declining * segment. Search for the last price step in the * segment. */ while (i < priceSteps - 1 && this.demand[i] - this.demand[i + 1] == delta) { i += 1; } /* * If not at the end of the demand array, add the end * point for the segment. */ if (i < priceSteps - 1) { points.add(newPoint(i)); i += 1; } } else if (flatEnd && flatEndPoint != null) { /* * If i is not in a constantly inclining or declining * segment, and the previous segment was flat, then move * the end point of the flat segment one price step * forward to convert it to a straight step. * * This is to preserve the semantics of the straight * step when converting between point and vector * representation and back. */ flatEndPoint.setNormalizedPrice(this.marketBasis .toNormalizedPrice(i)); } } /* * Add a point at i for the following two cases: 1) Add a point * for the start of the next flat segment and loop. 2) Add a * final point if the last step of the demand array the end of * an inclining or declining segment. */ if (i == priceSteps - 1 || (i < priceSteps - 1 && this.demand[i] - this.demand[i + 1] == 0)) { points.add(newPoint(i)); flatStart = true; } } calculatedPricePoints = new PricePoint[points.size()]; points.toArray(calculatedPricePoints); } return calculatedPricePoints; } /** * Get scale factor with the specified max value parameter and return the * double result. * * @param maxValue * The max value (<code>int</code>) parameter. * @return Results of the get scale factor (<code>double</code>) value. */ public double getScaleFactor(final int maxValue) { return Math.max(getMaximumDemand(), -getMinimumDemand()) / maxValue; } /** * Compares the provided object to this instance of the class according to * the equals rules. * * @param obj * The object to compare with. * @return true if this equals the object, false otherwise. */ @Override public boolean equals(final Object obj) { Bid other = (Bid) ((obj instanceof Bid) ? obj : null); if (other == null) return false; if (this == other) return true; return other.bidNumber == this.bidNumber && this.marketBasis.equals(other.marketBasis) && Arrays.equals(other.getUnclonedDemand(), this.getUnclonedDemand()); } /** * Hash code and return the int result. * * @return Results of the hash code (<code>int</code>) value. */ @Override public int hashCode() { final int prime = 31; int result = prime + this.bidNumber; result = prime * result + Arrays.hashCode(getUnclonedDemand()); result = prime * result + ((this.marketBasis == null) ? 0 : this.marketBasis.hashCode()); return result; } /** * Returns the string value. * * @return The string (<code>String</code>) value. */ @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("Bid{bidNumber=").append(this.bidNumber); PricePoint[] points = this.pricePoints; /* * Print price points if available, and if the most compact * representation */ // TODO Refactor this code to not nest more than 3 // if/for/while/switch/try statements. if (points != null && points.length < this.marketBasis.getPriceSteps() / 2) { b.append(", PricePoint[]{"); for (int i = 0; i < points.length; i++) { if (i > 0) { b.append(','); } PricePoint pricePoint = points[i]; int priceStep = this.marketBasis.toPriceStep(pricePoint .getNormalizedPrice()); b.append('(').append( MarketBasis.PRICE_FORMAT.format(this.marketBasis .toPrice(priceStep))); b.append(",") .append(MarketBasis.DEMAND_FORMAT.format(pricePoint .getDemand())); b.append(')'); } b.append("}, "); } else { double[] unclonedDemand = getUnclonedDemand(); if (unclonedDemand != null) { b.append(", demand[]{"); for (int i = 0; i < unclonedDemand.length; i++) { if (i > 0) { b.append(','); } b.append(MarketBasis.DEMAND_FORMAT .format(unclonedDemand[i])); } b.append("}, "); } } b.append(this.marketBasis); b.append('}'); return b.toString(); } /** * Create a deep clone of the price point array. * * @param unclonedPricePoints * The price point array to be cloned, or null. * @return The cloned price point array, or null if unclonedPricePoints is * null. */ private static PricePoint[] clone(PricePoint[] unclonedPricePoints) { if (unclonedPricePoints == null) { // TODO this should return new PricePoint[0], not null. // getCalculatedPricePoints might will have to be refactored return null; } PricePoint[] pricePoints = new PricePoint[unclonedPricePoints.length]; for (int i = 0; i < pricePoints.length; i++) { pricePoints[i] = new PricePoint(unclonedPricePoints[i]); } return pricePoints; } }
package aQute.bnd.osgi; import java.util.*; import aQute.libg.generics.*; public class Descriptors { Map<String,TypeRef> typeRefCache = Create.map(); Map<String,Descriptor> descriptorCache = Create.map(); Map<String,PackageRef> packageCache = Create.map(); // MUST BE BEFORE PRIMITIVES, THEY USE THE DEFAULT PACKAGE!! final static PackageRef DEFAULT_PACKAGE = new PackageRef(); final static PackageRef PRIMITIVE_PACKAGE = new PackageRef(); final static TypeRef VOID = new ConcreteRef("V", "void", PRIMITIVE_PACKAGE); final static TypeRef BOOLEAN = new ConcreteRef("Z", "boolean", PRIMITIVE_PACKAGE); final static TypeRef BYTE = new ConcreteRef("B", "byte", PRIMITIVE_PACKAGE); final static TypeRef CHAR = new ConcreteRef("C", "char", PRIMITIVE_PACKAGE); final static TypeRef SHORT = new ConcreteRef("S", "short", PRIMITIVE_PACKAGE); final static TypeRef INTEGER = new ConcreteRef("I", "int", PRIMITIVE_PACKAGE); final static TypeRef LONG = new ConcreteRef("J", "long", PRIMITIVE_PACKAGE); final static TypeRef DOUBLE = new ConcreteRef("D", "double", PRIMITIVE_PACKAGE); final static TypeRef FLOAT = new ConcreteRef("F", "float", PRIMITIVE_PACKAGE); { packageCache.put("", DEFAULT_PACKAGE); } public interface TypeRef extends Comparable<TypeRef> { String getBinary(); String getFQN(); String getPath(); boolean isPrimitive(); TypeRef getComponentTypeRef(); TypeRef getClassRef(); PackageRef getPackageRef(); String getShortName(); boolean isJava(); boolean isObject(); String getSourcePath(); String getDottedOnly(); } public static class PackageRef implements Comparable<PackageRef> { final String binaryName; final String fqn; final boolean java; PackageRef(String binaryName) { this.binaryName = fqnToBinary(binaryName); this.fqn = binaryToFQN(binaryName); this.java = this.fqn.startsWith("java."); // !this.fqn.equals("java.sql)" // For some reason I excluded java.sql but the classloader will // delegate anyway. So lost the understanding why I did it?? } PackageRef() { this.binaryName = ""; this.fqn = "."; this.java = false; } public PackageRef getDuplicate() { return new PackageRef(binaryName + Constants.DUPLICATE_MARKER); } public String getFQN() { return fqn; } public String getBinary() { return binaryName; } public String getPath() { return binaryName; } public boolean isJava() { return java; } @Override public String toString() { return fqn; } boolean isDefaultPackage() { return this.fqn.equals("."); } boolean isPrimitivePackage() { return this == PRIMITIVE_PACKAGE; } public int compareTo(PackageRef other) { return fqn.compareTo(other.fqn); } @Override public boolean equals(Object o) { assert o instanceof PackageRef; return o == this; } @Override public int hashCode() { return super.hashCode(); } /** * Decide if the package is a metadata package. * * @param pack * @return */ public boolean isMetaData() { if (isDefaultPackage()) return true; for (int i = 0; i < Constants.METAPACKAGES.length; i++) { if (fqn.startsWith(Constants.METAPACKAGES[i])) return true; } return false; } } // We "intern" the private static class ConcreteRef implements TypeRef { final String binaryName; final String fqn; final boolean primitive; final PackageRef packageRef; ConcreteRef(PackageRef packageRef, String binaryName) { if (packageRef.getFQN().length() < 2) System.err.println("in default pack? " + binaryName); this.binaryName = binaryName; this.fqn = binaryToFQN(binaryName); this.primitive = false; this.packageRef = packageRef; } ConcreteRef(String binaryName, String fqn, PackageRef pref) { this.binaryName = binaryName; this.fqn = fqn; this.primitive = true; this.packageRef = pref; } public String getBinary() { return binaryName; } public String getPath() { return binaryName + ".class"; } public String getSourcePath() { return binaryName + ".java"; } public String getFQN() { return fqn; } public String getDottedOnly() { return fqn.replace('$', '.'); } public boolean isPrimitive() { return primitive; } public TypeRef getComponentTypeRef() { return null; } public TypeRef getClassRef() { return this; } public PackageRef getPackageRef() { return packageRef; } public String getShortName() { int n = binaryName.lastIndexOf('/'); return binaryName.substring(n + 1); } public boolean isJava() { return packageRef.isJava(); } @Override public String toString() { return fqn; } public boolean isObject() { return fqn.equals("java.lang.Object"); } @Override public boolean equals(Object other) { assert other instanceof TypeRef; return this == other; } public int compareTo(TypeRef other) { if (this == other) return 0; return fqn.compareTo(other.getFQN()); } @Override public int hashCode() { return super.hashCode(); } } private static class ArrayRef implements TypeRef { final TypeRef component; ArrayRef(TypeRef component) { this.component = component; } public String getBinary() { return "[" + component.getBinary(); } public String getFQN() { return component.getFQN() + "[]"; } public String getPath() { return component.getPath(); } public String getSourcePath() { return component.getSourcePath(); } public boolean isPrimitive() { return false; } public TypeRef getComponentTypeRef() { return component; } public TypeRef getClassRef() { return component.getClassRef(); } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return component.equals(((ArrayRef) other).component); } public PackageRef getPackageRef() { return component.getPackageRef(); } public String getShortName() { return component.getShortName() + "[]"; } public boolean isJava() { return component.isJava(); } @Override public String toString() { return component.toString() + "[]"; } public boolean isObject() { return false; } public String getDottedOnly() { return component.getDottedOnly(); } public int compareTo(TypeRef other) { if (this == other) return 0; return getFQN().compareTo(other.getFQN()); } @Override public int hashCode() { return super.hashCode(); } } public TypeRef getTypeRef(String binaryClassName) { assert !binaryClassName.endsWith(".class"); TypeRef ref = typeRefCache.get(binaryClassName); if (ref != null) return ref; if (binaryClassName.startsWith("[")) { ref = getTypeRef(binaryClassName.substring(1)); ref = new ArrayRef(ref); } else { if (binaryClassName.length() == 1) { switch (binaryClassName.charAt(0)) { case 'V' : return VOID; case 'B' : return BYTE; case 'C' : return CHAR; case 'I' : return INTEGER; case 'S' : return SHORT; case 'D' : return DOUBLE; case 'F' : return FLOAT; case 'J' : return LONG; case 'Z' : return BOOLEAN; } // falls trough for other 1 letter class names } if (binaryClassName.startsWith("L") && binaryClassName.endsWith(";")) { binaryClassName = binaryClassName.substring(1, binaryClassName.length() - 1); } ref = typeRefCache.get(binaryClassName); if (ref != null) return ref; PackageRef pref; int n = binaryClassName.lastIndexOf('/'); if (n < 0) pref = DEFAULT_PACKAGE; else pref = getPackageRef(binaryClassName.substring(0, n)); ref = new ConcreteRef(pref, binaryClassName); } typeRefCache.put(binaryClassName, ref); return ref; } public PackageRef getPackageRef(String binaryPackName) { if (binaryPackName.indexOf('.') >= 0) { binaryPackName = binaryPackName.replace('.', '/'); } PackageRef ref = packageCache.get(binaryPackName); if (ref != null) return ref; ref = new PackageRef(binaryPackName); packageCache.put(binaryPackName, ref); return ref; } public Descriptor getDescriptor(String descriptor) { Descriptor d = descriptorCache.get(descriptor); if (d != null) return d; d = new Descriptor(descriptor); descriptorCache.put(descriptor, d); return d; } public class Descriptor { final TypeRef type; final TypeRef[] prototype; final String descriptor; Descriptor(String descriptor) { this.descriptor = descriptor; int index = 0; List<TypeRef> types = Create.list(); if (descriptor.charAt(index) == '(') { index++; while (descriptor.charAt(index) != ')') { index = parse(types, descriptor, index); } index++; // skip ) prototype = types.toArray(new TypeRef[types.size()]); types.clear(); } else prototype = null; index = parse(types, descriptor, index); type = types.get(0); } int parse(List<TypeRef> types, String descriptor, int index) { char c; StringBuilder sb = new StringBuilder(); while ((c = descriptor.charAt(index++)) == '[') { sb.append('['); } switch (c) { case 'L' : while ((c = descriptor.charAt(index++)) != ';') { // TODO sb.append(c); } break; case 'V' : case 'B' : case 'C' : case 'I' : case 'S' : case 'D' : case 'F' : case 'J' : case 'Z' : sb.append(c); break; default : throw new IllegalArgumentException("Invalid type in descriptor: " + c + " from " + descriptor + "[" + index + "]"); } types.add(getTypeRef(sb.toString())); return index; } public TypeRef getType() { return type; } public TypeRef[] getPrototype() { return prototype; } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return Arrays.equals(prototype, ((Descriptor) other).prototype) && type == ((Descriptor) other).type; } @Override public int hashCode() { return prototype == null ? type.hashCode() : type.hashCode() ^ Arrays.hashCode(prototype); } @Override public String toString() { return descriptor; } } /** * Return the short name of a FQN */ public static String getShortName(String fqn) { assert fqn.indexOf('/') < 0; int n = fqn.lastIndexOf('.'); if (n >= 0) { return fqn.substring(n + 1); } return fqn; } public static String binaryToFQN(String binary) { StringBuilder sb = new StringBuilder(); for (int i = 0, l = binary.length(); i < l; i++) { char c = binary.charAt(i); if (c == '/') sb.append('.'); else sb.append(c); } String result = sb.toString(); assert result.length() > 0; return result; } public static String fqnToBinary(String binary) { return binary.replace('.', '/'); } public static String getPackage(String binaryNameOrFqn) { int n = binaryNameOrFqn.lastIndexOf('/'); if (n >= 0) return binaryNameOrFqn.substring(0, n).replace('/', '.'); n = binaryNameOrFqn.lastIndexOf("."); if (n >= 0) return binaryNameOrFqn.substring(0, n); return "."; } public static String fqnToPath(String s) { return fqnToBinary(s) + ".class"; } public TypeRef getTypeRefFromFQN(String fqn) { if (fqn.equals("boolean")) return BOOLEAN; if (fqn.equals("byte")) return BOOLEAN; if (fqn.equals("char")) return CHAR; if (fqn.equals("short")) return SHORT; if (fqn.equals("int")) return INTEGER; if (fqn.equals("long")) return LONG; if (fqn.equals("float")) return FLOAT; if (fqn.equals("double")) return DOUBLE; return getTypeRef(fqnToBinary(fqn)); } public TypeRef getTypeRefFromPath(String path) { assert path.endsWith(".class"); return getTypeRef(path.substring(0, path.length() - 6)); } }
package miner; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import database.DownloadedFile; import database.FileHandler; import parser.Signature; public class Scorer { private ArrayList<Result> results; public ArrayList<Result> getResults() { return results; } public static void main(String[] args) throws Exception { // testing String inputContent = new String(Files.readAllBytes(Paths.get("input.java")), "UTF-8"); FileHandler fileHandler = new FileHandler("Files"); Scorer scorer = new Scorer(inputContent, fileHandler.readAllDownloadedFiles(), fileHandler.readFile("Boa_output.txt")); ArrayList<Result> results = scorer.getResults(); fileHandler.writeAllResults(results); // Print the top 10 recommended results int top = 10; if (results.size() < 10) top = results.size(); System.out.println("Top " + top + " recommended results:"); for (int i = 0; i < top; i++) System.out.println(results.get(i)); } public Scorer(String inputContent, ArrayList<DownloadedFile> files, String metricsContent) throws IOException { ArrayList<Result> fileContents = new ArrayList<Result>(); // read the metrics for all results HashMap<String, String> metricResults = new HashMap<String, String>(); for (String metricResult : metricsContent.split("\\n")) { String[] splitMetricResult = metricResult.substring(10).split(",", 2); metricResults.put(splitMetricResult[0], splitMetricResult[1]); } // for each result // get the signature of the file Signature inputSignature = new Signature(inputContent); for (DownloadedFile file : files) { // get the content of the file String content = file.getContent(); // extract signature Signature outputSignature = new Signature(content, inputSignature.getClassName()); // calculate the functional score double score = calculateScore(inputSignature, outputSignature); // find the relevant metrics Metrics metrics = new Metrics(metricResults.get(file.getPath())); // calculate the reusability index double qualityScore = metrics.calculateQualityScore(metrics); fileContents.add(new Result(file.getPath(), content, score, metrics, qualityScore)); } // sort the results in descending order (equalities are sorted based on quality score) Collections.sort(fileContents, new Comparator<Result>() { @Override public int compare(Result o1, Result o2) { if (o1.score < o2.score) return 1; else if (o1.score > o2.score) return -1; else return o1.qualityScore < o2.qualityScore ? 1 : (o1.qualityScore > o2.qualityScore ? -1 : 0); } }); results = fileContents; } public float calculateScore(Signature inputSignature, Signature outputSignature) { double classScore = classNameScore(inputSignature.getClassName(), outputSignature.getClassName()); double[] methodScore = methodsScore(inputSignature, outputSignature); double[] scoreVector = new double[methodScore.length + 1]; double[] defaultVector = new double[methodScore.length + 1]; scoreVector[0] = classScore; for (int i = 0; i < methodScore.length; i++) scoreVector[i + 1] = methodScore[i]; for (int i = 0; i < defaultVector.length; i++) defaultVector[i] = 1; float score = TanimotoCoefficient.similarity(defaultVector, scoreVector); // Test the results // System.out.println("score vector: "+Arrays.toString(scoreVector)); // System.out.println("total score: "+score+"\n"); return score; } public double classNameScore(String inputClass, String outputClass) { inputClass = inputClass.replace("\"", ""); outputClass = outputClass.replace("\"", ""); if (inputClass.trim().equals("-1")) return 1.0; String[] inputClassTokens = tokenizeString(inputClass); String[] outputClassTokens = tokenizeString(outputClass); double score = JaccardCoefficient.similarity(inputClassTokens, outputClassTokens); // Test the results // System.out.println("inputClass name: " + inputClass); // System.out.println("outputClass name: " + outputClass); // System.out.println("class name score: " + score); return score; } public double[] methodsScore(Signature inputSignature, Signature outputSignature) { String[] inputMethodsName = inputSignature.getMethodNames().replace("\"", "").split(","); String[] inputMethodsType = inputSignature.getMethodTypes().replace("\"", "").split(","); String[] outputMethodsName = outputSignature.getMethodNames().replace("\"", "").split(","); String[] outputMethodsType = outputSignature.getMethodTypes().replace("\"", "").split(","); String[][] inputMethodArgs = inputSignature.getMethodArgs(); String[][] outputMethodArgs = outputSignature.getMethodArgs(); String[] hasBlock = outputSignature.getBlock().split(","); double[] methodScore = new double[inputMethodsName.length]; // definition of methodVector = [nameScore, typeScore, argScore] double[] methodVector = { 0,0,0 }; double[] defaultVector = { 1,1,1 }; for (int i = 0; i < inputMethodsName.length; i++) { methodScore[i] = 0; } // find the max method score for each method for (int i = 0; i < inputMethodsName.length; i++) { for (int j = 0; j < outputMethodsName.length; j++) { double jaccard = 0; double tanimoto = 0; for (int k = 0; k < methodVector.length; k++) methodVector[k] = 0; String[] inputMethodTokens = tokenizeString(inputMethodsName[i]); String[] outputMethodTokens = tokenizeString(outputMethodsName[j]); jaccard = JaccardCoefficient.similarity(inputMethodTokens, outputMethodTokens); if (hasBlock[j].trim().equals("yes") && jaccard > 0) { methodVector[0] = jaccard; if (inputMethodsType[i].trim().equals(outputMethodsType[j])) methodVector[1] = 1; methodVector[2] = calculateArgsScore(inputMethodArgs,i,outputMethodArgs,j); } tanimoto = TanimotoCoefficient.similarity(methodVector, defaultVector); if (tanimoto > methodScore[i]) { methodScore[i] = tanimoto; } } } // Test the results // System.out.println("method score: " + Arrays.toString(methodScore)); return methodScore; } private double calculateArgsScore(String[][] inputMethodArgs, int a, String[][] outputMethodArgs, int b) { int counter = 0; String[][] inputArgs = inputMethodArgs; String[][] outputArgs = outputMethodArgs; for (int i = 0; i < inputArgs[a].length; i++) { for (int j = 0; j < outputArgs[b].length; j++) { if (inputArgs[a][i].equals(outputArgs[b][j])){ counter++; outputArgs[b][j] = null; } } } double score; if (inputArgs[a].length < outputArgs[b].length) { score = (double) counter / outputArgs[b].length; } else if (inputArgs[a].length > outputArgs[b].length) { score = (double) counter / inputArgs[a].length; } else { if (inputArgs[a].length == 0) score = 1; else score = (double) counter / inputArgs[a].length; } return score; } public String[] tokenizeString(String text) { // Split camelCase or "_" String[] tokens = text.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])|[_]"); for (int i = 0; i < tokens.length; i++) tokens[i] = tokens[i].toLowerCase(); // Remove any empty values List<String> list = new ArrayList<>(); Collections.addAll(list, tokens); list.removeAll(Arrays.asList("")); tokens = list.toArray(new String[list.size()]); return tokens; } }
package org.navalplanner.ws.subcontract.impl; import static org.navalplanner.web.I18nHelper._; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.apache.commons.lang.StringUtils; import org.navalplanner.business.calendars.entities.BaseCalendar; import org.navalplanner.business.common.daos.IConfigurationDAO; import org.navalplanner.business.common.daos.IOrderSequenceDAO; import org.navalplanner.business.common.entities.OrderSequence; import org.navalplanner.business.common.exceptions.InstanceNotFoundException; import org.navalplanner.business.common.exceptions.ValidationException; import org.navalplanner.business.externalcompanies.daos.IExternalCompanyDAO; import org.navalplanner.business.externalcompanies.entities.ExternalCompany; import org.navalplanner.business.orders.daos.IOrderElementDAO; import org.navalplanner.business.orders.entities.Order; import org.navalplanner.business.orders.entities.OrderElement; import org.navalplanner.business.orders.entities.OrderStatusEnum; import org.navalplanner.ws.common.api.InstanceConstraintViolationsDTO; import org.navalplanner.ws.common.api.InstanceConstraintViolationsListDTO; import org.navalplanner.ws.common.api.OrderElementDTO; import org.navalplanner.ws.common.impl.ConfigurationOrderElementConverter; import org.navalplanner.ws.common.impl.ConstraintViolationConverter; import org.navalplanner.ws.common.impl.OrderElementConverter; import org.navalplanner.ws.common.impl.Util; import org.navalplanner.ws.subcontract.api.ISubcontractService; import org.navalplanner.ws.subcontract.api.SubcontractedTaskDataDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * REST-based implementation of {@link ISubcontractService} * * @author Manuel Rego Casasnovas <mrego@igalia.com> */ @Path("/subcontract/") @Produces("application/xml") @Service("subcontractServiceREST") public class SubcontractServiceREST implements ISubcontractService { @Autowired private IOrderElementDAO orderElementDAO; @Autowired private IConfigurationDAO configurationDAO; @Autowired private IExternalCompanyDAO externalCompanyDAO; @Autowired private IOrderSequenceDAO orderSequenceDAO; @Override @POST @Consumes("application/xml") @Transactional public InstanceConstraintViolationsListDTO subcontract( SubcontractedTaskDataDTO subcontractedTaskDataDTO) { List<InstanceConstraintViolationsDTO> instanceConstraintViolationsList = new ArrayList<InstanceConstraintViolationsDTO>(); InstanceConstraintViolationsDTO instanceConstraintViolationsDTO = null; if (StringUtils.isEmpty(subcontractedTaskDataDTO.externalCompanyNif)) { return getErrorMessage(subcontractedTaskDataDTO.subcontractedCode, "external company nif not specified"); } ExternalCompany externalCompany; try { externalCompany = externalCompanyDAO .findUniqueByNif(subcontractedTaskDataDTO.externalCompanyNif); } catch (InstanceNotFoundException e1) { return getErrorMessage(subcontractedTaskDataDTO.externalCompanyNif, "external company not found"); } if (!externalCompany.isClient()) { return getErrorMessage(subcontractedTaskDataDTO.externalCompanyNif, "external company is not registered as client"); } OrderElementDTO orderElementDTO = subcontractedTaskDataDTO.orderElementDTO; if (orderElementDTO == null) { return getErrorMessage(subcontractedTaskDataDTO.subcontractedCode, "order element not specified"); } try { OrderElement orderElement = OrderElementConverter.toEntity( orderElementDTO, ConfigurationOrderElementConverter .noAdvanceMeasurements()); Order order; if (orderElement instanceof Order) { order = (Order) orderElement; } else { order = wrapInOrder(orderElement); } order.moveCodeToExternalCode(); order.setCodeAutogenerated(true); String code = orderSequenceDAO.getNextOrderCode(); if (code == null) { return getErrorMessage( subcontractedTaskDataDTO.orderElementDTO.code, "unable to generate the code for the new order, please try again later"); } order.setCode(code); generateCodes(order); order.setState(OrderStatusEnum.SUBCONTRACTED_PENDING_ORDER); if (subcontractedTaskDataDTO.workDescription != null) { order.setName(subcontractedTaskDataDTO.workDescription); } order.setCustomer(externalCompany); order.setCustomerReference(subcontractedTaskDataDTO.subcontractedCode); order.setWorkBudget(subcontractedTaskDataDTO.subcontractPrice); order.validate(); orderElementDAO.save(order); } catch (ValidationException e) { instanceConstraintViolationsDTO = ConstraintViolationConverter .toDTO(Util.generateInstanceId(1, orderElementDTO.code), e .getInvalidValues()); } catch (InstanceNotFoundException e) { instanceConstraintViolationsDTO = InstanceConstraintViolationsDTO .create(Util.generateInstanceId(1, orderElementDTO.code), e .getMessage()); } if (instanceConstraintViolationsDTO != null) { instanceConstraintViolationsList .add(instanceConstraintViolationsDTO); } return new InstanceConstraintViolationsListDTO( instanceConstraintViolationsList); } private void generateCodes(Order order) { OrderSequence orderSequence = orderSequenceDAO.getActiveOrderSequence(); int numberOfDigits = orderSequence.getNumberOfDigits(); order.generateOrderElementCodes(numberOfDigits); } private Order wrapInOrder(OrderElement orderElement) { if (orderElement instanceof Order) { return (Order) orderElement; } Order order = Order.create(); order.add(orderElement); order.setName(_("Order from client")); order.setInitDate(orderElement.getInitDate()); order.setDeadline(orderElement.getDeadline()); order.setCalendar(getDefaultCalendar()); return order; } private BaseCalendar getDefaultCalendar() { return configurationDAO.getConfiguration().getDefaultCalendar(); } private InstanceConstraintViolationsListDTO getErrorMessage(String code, String message) { // FIXME review errors returned return new InstanceConstraintViolationsListDTO(Arrays .asList(InstanceConstraintViolationsDTO.create(Util .generateInstanceId(1, code), message))); } }
package org.apache.commons.vfs; import org.apache.avalon.excalibur.i18n.ResourceManager; import org.apache.avalon.excalibur.i18n.Resources; import org.apache.commons.vfs.impl.DefaultFileReplicator; import org.apache.commons.vfs.impl.DefaultFileSystemManager; import org.apache.commons.vfs.impl.PrivilegedFileReplicator; import org.apache.commons.vfs.provider.FileProvider; import org.apache.commons.vfs.provider.FileReplicator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class FileSystemManagerFactory { private static final Resources REZ = ResourceManager.getPackageResources( FileSystemManagerFactory.class ); private static FileSystemManager instance; private FileSystemManagerFactory() { } /** * Returns the default {@link FileSystemManager} instance. */ public synchronized static FileSystemManager getManager() throws FileSystemException { if ( instance == null ) { instance = doCreateManager(); } return instance; } /** * Creates a file system manager instance. * * @todo Load manager config from a file. * @todo Ignore missing providers. */ private static FileSystemManager doCreateManager() throws FileSystemException { final DefaultFileSystemManager mgr = new DefaultFileSystemManager(); // Set the logger final Log logger = LogFactory.getLog( FileSystemManagerFactory.class ); mgr.setLogger( logger ); // Set the replicator FileReplicator replicator = new DefaultFileReplicator(); replicator = new PrivilegedFileReplicator( replicator ); mgr.setReplicator( replicator ); // Add the default providers FileProvider provider = createProvider( "org.apache.commons.vfs.provider.local.DefaultLocalFileSystemProvider" ); mgr.addProvider( "file", provider ); provider = createProvider( "org.apache.commons.vfs.provider.zip.ZipFileSystemProvider" ); mgr.addProvider( "zip", provider ); provider = createProvider( "org.apache.commons.vfs.provider.jar.JarFileSystemProvider" ); mgr.addProvider( "jar", provider ); provider = createProvider( "org.apache.commons.vfs.provider.ftp.FtpFileSystemProvider" ); mgr.addProvider( "ftp", provider ); provider = createProvider( "org.apache.commons.vfs.provider.smb.SmbFileSystemProvider" ); mgr.addProvider( "smb", provider ); provider = createProvider( "org.apache.commons.vfs.provider.url.UrlFileProvider" ); mgr.setDefaultProvider( provider ); return mgr; } /** * Creates a provider. */ private static FileProvider createProvider( final String providerClassName ) throws FileSystemException { try { final Class providerClass = Class.forName( providerClassName ); return (FileProvider)providerClass.newInstance(); } catch ( final Exception e ) { final String message = REZ.getString( "create-provider.error", providerClassName ); throw new FileSystemException( message, e ); } } }
package ca.carleton.gcrc.couch.user.agreement; import java.util.Set; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ca.carleton.gcrc.couch.client.CouchDb; import ca.carleton.gcrc.couch.client.CouchDesignDocument; import ca.carleton.gcrc.couch.client.CouchQuery; import ca.carleton.gcrc.couch.client.CouchQueryResults; public class AgreementRobotThread extends Thread { final protected Logger logger = LoggerFactory.getLogger(this.getClass()); private boolean isShuttingDown = false; private String atlasName = null; private CouchDesignDocument documentDbDesignDocument; private CouchDesignDocument userDbDesignDocument; private String agreementRole = null; private String lastAgreementVersion = null; public AgreementRobotThread(AgreementRobotSettings settings) throws Exception { this.atlasName = settings.getAtlasName(); this.documentDbDesignDocument = settings.getDocumentDesignDocument(); this.userDbDesignDocument = settings.getUserDb().getDesignDocument("nunaliit_user"); agreementRole = "nunaliit_agreement_atlas"; if( null != atlasName ){ agreementRole = "nunaliit_agreement_" + atlasName; } } public void shutdown() { logger.info("Shutting down agreement worker thread"); synchronized(this) { isShuttingDown = true; this.notifyAll(); } } @Override public void run() { logger.info("Start agreement worker thread"); boolean done = false; do { synchronized(this) { done = isShuttingDown; } if( false == done ) { activity(); } } while( false == done ); logger.info("Submission worker thread exiting"); } private void activity() { JSONObject agreementDoc = null; try { CouchDb db = documentDbDesignDocument.getDatabase(); agreementDoc = db.getDocument("org.nunaliit.user_agreement"); } catch (Exception e) { logger.error("Error accessing submission database",e); waitMillis(60 * 1000); // wait a minute return; } // Check for work String version = agreementDoc.optString("_rev",null); if( null == version || version.equals(lastAgreementVersion) ){ // Nothing to do, wait 30 secs waitMillis(30 * 1000); return; }; // A new agreement is detected try { logger.info("New user agreement detected: "+version); performWork(agreementDoc); lastAgreementVersion = version; } catch(Exception e) { logger.error("Error handling new user agreement",e); // Try again in 30 secs waitMillis(30 * 1000); return; } } public void performWork(JSONObject agreementDoc) throws Exception { // Perform work only if the agreement is in force boolean agreementEnabled = AgreementUtils.getEnabledFromAgreementDocument(agreementDoc); if( false == agreementEnabled ){ logger.info("User agreement is not enabled. Skip."); return; } // Check users that have agreed to the previous agreement and revoke // privilege CouchQuery query = new CouchQuery(); query.setViewName("roles"); query.setStartKey(agreementRole); query.setEndKey(agreementRole); logger.debug("Looking for users with role: "+agreementRole); CouchQueryResults results = userDbDesignDocument.performQuery(query); if( results.getRows().size() > 0 ) { // Find all acceptable agreements Set<String> agreementContents = AgreementUtils.getContentsFromAgreementDocument(agreementDoc); for(JSONObject row : results.getRows()){ String docId = row.optString("id","<no id>"); try { verifyUser(docId, agreementContents); } catch(Exception e) { logger.error("Unable to process user: "+docId, e); } } } } private void verifyUser(String docId, Set<String> agreementContents) throws Exception { logger.debug("Verifying user: "+docId); // Get user document JSONObject userDoc = userDbDesignDocument.getDatabase().getDocument(docId); // Check if current agreement matches boolean agreementMatches = false; JSONObject acceptedUserAgreements = userDoc.optJSONObject("nunaliit_accepted_user_agreements"); JSONObject atlasInfo = null; if( null != acceptedUserAgreements ){ atlasInfo = acceptedUserAgreements.optJSONObject(atlasName); } String userAcceptedAgreement = null; if( null != atlasInfo ){ userAcceptedAgreement = atlasInfo.optString("content",""); } if( agreementContents.contains(userAcceptedAgreement) ){ agreementMatches = true; } // If the agreements do not match, remove the role from this user boolean roleRemoved = false; if( !agreementMatches ){ JSONArray roles = userDoc.optJSONArray("roles"); JSONArray newRoles = new JSONArray(); if( null != roles ){ for(int i=0,e=roles.length(); i<e; ++i){ String role = roles.getString(i); if( agreementRole.equals(role) ){ roleRemoved = true; } else { newRoles.put(role); } } } if( roleRemoved ){ userDoc.put("roles",newRoles); } } // If role was removed, update user document if( roleRemoved ) { userDbDesignDocument.getDatabase().updateDocument(userDoc); logger.info("User ("+docId+") must accept new agreement for atlas: "+atlasName); } } private boolean waitMillis(int millis) { synchronized(this) { if( true == isShuttingDown ) { return false; } try { this.wait(millis); } catch (InterruptedException e) { // Interrupted return false; } } return true; } }
package org.jdesktop.swingx.plaf.basic; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.SortedSet; import java.util.TimeZone; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.Icon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.KeyStroke; import javax.swing.LookAndFeel; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import org.jdesktop.swingx.JXMonthView; import org.jdesktop.swingx.calendar.CalendarUtils; import org.jdesktop.swingx.calendar.DateSelectionModel; import org.jdesktop.swingx.calendar.DateSelectionModel.SelectionMode; import org.jdesktop.swingx.event.DateSelectionEvent; import org.jdesktop.swingx.event.DateSelectionListener; import org.jdesktop.swingx.plaf.MonthViewUI; /** * Base implementation of the <code>JXMonthView</code> UI.<p> * * <b>Note</b>: The api changed considerably between releases 0.9.1 and 0.9.2. Most of * the old methods are still available but deprecated. It's strongly recommended to * update subclasses soon, because those methods will be removed before 0.9.3. <p> * * The general drift of the change was * <ul> * <li> replace all methods which take/return a date in millis with equivalents taking/returning * a Date object * <li> streamline the painting (to make it understandable for me ;-) See below. * <li> pass-around a calendar object to all painting methods. The general contract is that * methods which receive the calendar must not change it in any way. It's up to the calling * method to loop through the dates if appropriate. * </ul> * * Painting: defined coordinate systems. * * <ul> * <li> Screen coordinates of months/days, accessible via the getXXBounds() methods. These * coordinates are absolute in the system of the monthView. * <li> The grid of visible months with logical row/column coordinates. The logical * coordinates are adjusted to ComponentOrientation. * <li> The grid of days in a month with logical row/column coordinates. The logical * coordinates are adjusted to ComponentOrientation. The columns * are the days of the week, the rows are the weeks in a month. The column header shows * the localized names of the days and has the row coordinate -1. It is shown always. * The row header shows the week number in the year and has the column coordinate -1. It * is shown only if the showingWeekNumber property is true. * </ul> * * * * @author dmouse * @author rbair * @author rah003 * @author Jeanette Winzenburg */ public class BasicMonthViewUI extends MonthViewUI { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(BasicMonthViewUI.class .getName()); /** @deprecated no longer used, no replacement. */ @Deprecated protected static final int LEADING_DAY_OFFSET = 1; /** @deprecated no longer used, no replacement. */ @Deprecated protected static final int NO_OFFSET = 0; /** @deprecated no longer used, no replacement. */ @Deprecated protected static final int TRAILING_DAY_OFFSET = -1; private static final int WEEKS_IN_MONTH = 6; private static final int CALENDAR_SPACING = 10; private static final Point NO_SUCH_CALENDAR = new Point(-1, -1); /** Return value used to identify when the month down button is pressed. */ public static final int MONTH_DOWN = 1; /** Return value used to identify when the month up button is pressed. */ public static final int MONTH_UP = 2; /** Formatter used to format the day of the week to a numerical value. */ protected final SimpleDateFormat dayOfMonthFormatter = new SimpleDateFormat("d"); /** localized names of all months. * protected for testing only! * PENDING: JW - should be property on JXMonthView, for symmetry with * daysOfTheWeek? */ protected String[] monthsOfTheYear; /** the component we are installed for. */ protected JXMonthView monthView; // listeners private PropertyChangeListener propertyChangeListener; private MouseListener mouseListener; private MouseMotionListener mouseMotionListener; private Handler handler; // fields related to visible date range /** start of day of the first visible month. */ private Date firstDisplayedDate; /** first visible month. */ private int firstDisplayedMonth; /** first visible year. */ private int firstDisplayedYear; /** end of day of the last visible month. */ private Date lastDisplayedDate; /** flag indicating keyboard navigation. */ /** For interval selections we need to record the date we pivot around. */ /** * Date span used by the keyboard actions to track the original selection. */ private SortedSet<Date> originalDateSpan; /** Used as the font for flagged days. */ protected Font derivedFont; protected boolean isLeftToRight; protected Icon monthUpImage; protected Icon monthDownImage; private Color weekOfTheYearForeground; private Color unselectableDayForeground; private Color leadingDayForeground; private Color trailingDayForeground; private int arrowPaddingX = 3; private int arrowPaddingY = 3; // PENDING JW: use again? this was used as marker of the single // selected day box ... removed for simplification // private Rectangle dirtyRect = new Rectangle(); private Rectangle bounds = new Rectangle(); /** * Horizontal edge of the first column of displayed months. The edge is * left/right depending on componentOrientation isLeftToRight or not. * * PENDING: JW - really want to adjust here? Need to check in usage * anyway. * @deprecated only read in deprecated methods (but calculation still triggered * in layout, because some of the deprecated are public/protected) */ @Deprecated private int startX; /** * Top of first row of displayed months. * @deprecated only read in deprecated methods (but calculation still triggered * in layout, because some of the deprecated are public/protected) */ @Deprecated private int startY; /** * height of month header of the view, that is the name and the arrows. * initially, it's the same as the day-box-height, adjusted to arrow icon height * and arrow padding if traversable * */ private int monthBoxHeight; /** height of month header including the monthView's box padding. */ private int fullMonthBoxHeight; /** * raw witdth of a "day" box calculated from fontMetrics and "widest" content. * this is the same for days-of-the-week, weeks-of-the-year and days * */ private int boxWidth; /** * raw height of a "day" box calculated from fontMetrics and "widest" content. * this is the same for days-of-the-week, weeks-of-the-year and days * */ private int boxHeight; /** * width of a "day" box including the monthView's box padding * this is the same for days-of-the-week, weeks-of-the-year and days */ private int fullBoxWidth; /** * height of a "day" box including the monthView's box padding * this is the same for days-of-the-week, weeks-of-the-year and days */ private int fullBoxHeight; /** the width of a single month display. */ private int calendarWidth; /** the height of a single month display. */ private int calendarHeight; /** the height of a single month grid cell, including padding. */ private int fullCalendarHeight; /** the width of a single month grid cell, including padding. */ private int fullCalendarWidth; /** The number of calendars displayed vertically. */ private int calendarRowCount = 1; /** The number of calendars displayed horizontally. */ private int calendarColumnCount = 1; /** * The bounding box of the grid of visible months. */ protected Rectangle calendarGrid = new Rectangle(); private Rectangle[] monthStringBounds = new Rectangle[12]; private Rectangle[] yearStringBounds = new Rectangle[12]; private String[] daysOfTheWeek; @SuppressWarnings({"UnusedDeclaration"}) public static ComponentUI createUI(JComponent c) { return new BasicMonthViewUI(); } @Override public void installUI(JComponent c) { monthView = (JXMonthView)c; monthView.setLayout(createLayoutManager()); isLeftToRight = monthView.getComponentOrientation().isLeftToRight(); LookAndFeel.installProperty(monthView, "opaque", Boolean.TRUE); installComponents(); installDefaults(); installKeyboardActions(); installListeners(); } @Override public void uninstallUI(JComponent c) { uninstallListeners(); uninstallKeyboardActions(); uninstallDefaults(); uninstallComponents(); monthView.setLayout(null); monthView = null; } protected void installComponents() {} protected void uninstallComponents() {} protected void installDefaults() { Color background = monthView.getBackground(); if (background == null || background instanceof UIResource) { monthView.setBackground(UIManager.getColor("JXMonthView.background")); } monthView.setBoxPaddingX(UIManager.getInt("JXMonthView.boxPaddingX")); monthView.setBoxPaddingY(UIManager.getInt("JXMonthView.boxPaddingY")); monthView.setMonthStringBackground(UIManager.getColor("JXMonthView.monthStringBackground")); monthView.setMonthStringForeground(UIManager.getColor("JXMonthView.monthStringForeground")); monthView.setDaysOfTheWeekForeground(UIManager.getColor("JXMonthView.daysOfTheWeekForeground")); monthView.setSelectedBackground(UIManager.getColor("JXMonthView.selectedBackground")); monthView.setFlaggedDayForeground(UIManager.getColor("JXMonthView.flaggedDayForeground")); Font f = monthView.getFont(); if (f == null || f instanceof UIResource) { monthView.setFont(UIManager.getFont("JXMonthView.font")); } monthDownImage = UIManager.getIcon("JXMonthView.monthDownFileName"); monthUpImage = UIManager.getIcon("JXMonthView.monthUpFileName"); weekOfTheYearForeground = UIManager.getColor("JXMonthView.weekOfTheYearForeground"); leadingDayForeground = UIManager.getColor("JXMonthView.leadingDayForeground"); trailingDayForeground = UIManager.getColor("JXMonthView.trailingDayForeground"); unselectableDayForeground = UIManager.getColor("JXMonthView.unselectableDayForeground"); derivedFont = createDerivedFont(); // install date/locale related state setFirstDisplayedDay(monthView.getFirstDisplayedDay()); updateLocale(); } protected void uninstallDefaults() {} protected void installKeyboardActions() { // Setup the keyboard handler. // PENDING JW: change to when-ancestor? just to be on the safe side // if we make the title contain active comps installKeyBindings(JComponent.WHEN_FOCUSED); // JW: removed the automatic keybindings in WHEN_IN_FOCUSED // which caused #555-swingx (binding active if not focused) ActionMap actionMap = monthView.getActionMap(); KeyboardAction acceptAction = new KeyboardAction(KeyboardAction.ACCEPT_SELECTION); actionMap.put("acceptSelection", acceptAction); KeyboardAction cancelAction = new KeyboardAction(KeyboardAction.CANCEL_SELECTION); actionMap.put("cancelSelection", cancelAction); actionMap.put("selectPreviousDay", new KeyboardAction(KeyboardAction.SELECT_PREVIOUS_DAY)); actionMap.put("selectNextDay", new KeyboardAction(KeyboardAction.SELECT_NEXT_DAY)); actionMap.put("selectDayInPreviousWeek", new KeyboardAction(KeyboardAction.SELECT_DAY_PREVIOUS_WEEK)); actionMap.put("selectDayInNextWeek", new KeyboardAction(KeyboardAction.SELECT_DAY_NEXT_WEEK)); actionMap.put("adjustSelectionPreviousDay", new KeyboardAction(KeyboardAction.ADJUST_SELECTION_PREVIOUS_DAY)); actionMap.put("adjustSelectionNextDay", new KeyboardAction(KeyboardAction.ADJUST_SELECTION_NEXT_DAY)); actionMap.put("adjustSelectionPreviousWeek", new KeyboardAction(KeyboardAction.ADJUST_SELECTION_PREVIOUS_WEEK)); actionMap.put("adjustSelectionNextWeek", new KeyboardAction(KeyboardAction.ADJUST_SELECTION_NEXT_WEEK)); actionMap.put(JXMonthView.COMMIT_KEY, acceptAction); actionMap.put(JXMonthView.CANCEL_KEY, cancelAction); } /** * @param inputMap */ private void installKeyBindings(int type) { InputMap inputMap = monthView.getInputMap(type); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "acceptSelection"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "cancelSelection"); // @KEEP quickly check #606-swingx: keybindings not working in internalframe // eaten somewhere // inputMap.put(KeyStroke.getKeyStroke("F1"), "selectPreviousDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "selectPreviousDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "selectNextDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "selectDayInPreviousWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "selectDayInNextWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.SHIFT_MASK, false), "adjustSelectionPreviousDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.SHIFT_MASK, false), "adjustSelectionNextDay"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.SHIFT_MASK, false), "adjustSelectionPreviousWeek"); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.SHIFT_MASK, false), "adjustSelectionNextWeek"); } /** * @param inputMap */ private void uninstallKeyBindings(int type) { InputMap inputMap = monthView.getInputMap(type); inputMap.clear(); } protected void uninstallKeyboardActions() {} protected void installListeners() { propertyChangeListener = createPropertyChangeListener(); mouseListener = createMouseListener(); mouseMotionListener = createMouseMotionListener(); monthView.addPropertyChangeListener(propertyChangeListener); monthView.addMouseListener(mouseListener); monthView.addMouseMotionListener(mouseMotionListener); monthView.getSelectionModel().addDateSelectionListener(getHandler()); } protected void uninstallListeners() { monthView.getSelectionModel().removeDateSelectionListener(getHandler()); monthView.removeMouseMotionListener(mouseMotionListener); monthView.removeMouseListener(mouseListener); monthView.removePropertyChangeListener(propertyChangeListener); mouseMotionListener = null; mouseListener = null; propertyChangeListener = null; } /** * Binds/clears the keystrokes in the component input map, * based on the monthView's componentInputMap enabled property. * * @see org.jdesktop.swingx.JXMonthView#isComponentInputMapEnabled() */ protected void updateComponentInputMap() { if (monthView.isComponentInputMapEnabled()) { installKeyBindings(JComponent.WHEN_IN_FOCUSED_WINDOW); } else { uninstallKeyBindings(JComponent.WHEN_IN_FOCUSED_WINDOW); } } /** * Updates month and day names according to specified locale. */ protected void updateLocale() { Locale locale = monthView.getLocale(); monthsOfTheYear = new DateFormatSymbols(locale).getMonths(); // fixed JW: respect property in UIManager if available // PENDING JW: what to do if weekdays had been set // with JXMonthView method? how to detect? daysOfTheWeek = (String[])UIManager.get("JXMonthView.daysOfTheWeek"); if (daysOfTheWeek == null) { daysOfTheWeek = new String[7]; String[] dateFormatSymbols = new DateFormatSymbols(locale) .getShortWeekdays(); daysOfTheWeek = new String[JXMonthView.DAYS_IN_WEEK]; for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) { daysOfTheWeek[i - 1] = dateFormatSymbols[i]; } } // monthView.setDaysOfTheWeek(daysOfTheWeek); monthView.invalidate(); monthView.validate(); } @Override public String[] getDaysOfTheWeek() { String[] days = new String[daysOfTheWeek.length]; System.arraycopy(daysOfTheWeek, 0, days, 0, days.length); return days; } /** * Create a derived font used to when painting various pieces of the * month view component. This method will be called whenever * the font on the component is set so a new derived font can be created. */ protected Font createDerivedFont() { return monthView.getFont().deriveFont(Font.BOLD); } protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } protected LayoutManager createLayoutManager() { return getHandler(); } protected MouseListener createMouseListener() { return getHandler(); } protected MouseMotionListener createMouseMotionListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } public boolean isUsingKeyboard() { return usingKeyboard; } public void setUsingKeyboard(boolean val) { usingKeyboard = val; } /** * Returns the bounds of the day which contains the * given location. The bounds are in monthView screen coordinate system. * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the bounds of the day which contains the location, * or null if outside */ protected Rectangle getDayBoundsAtLocation(int x, int y) { Rectangle days = getMonthDetailsBoundsAtLocation(x, y); if ((days == null) ||(!days.contains(x, y))) return null; int calendarRow = (y - days.y) / fullBoxHeight; int calendarColumn = (x - days.x) / fullBoxWidth; return new Rectangle( days.x + calendarColumn * fullBoxWidth, days.y + calendarRow * fullBoxHeight, fullBoxWidth, fullBoxHeight); } /** * Returns the logical coordinates of the day which contains * the given location. The p.x of the returned value represents the day of week, the * p.y represents the week of the month. The transformation takes * care of ComponentOrientation. <p> * * Mapping pixel to logical grid coordinates. * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the logical coordinates of the day in the grid of days in a * month or null if outside. */ protected Point getDayGridPositionAtLocation(int x, int y) { Rectangle days = getMonthDetailsBoundsAtLocation(x, y); if ((days == null) ||(!days.contains(x, y))) return null; int calendarRow = (y - days.y) / fullBoxHeight; int calendarColumn = (x - days.x) / fullBoxWidth; if (!isLeftToRight) { int start = days.x + days.width; calendarColumn = (start - x) / fullBoxWidth; } if (monthView.isShowingWeekNumber()) { calendarColumn -= 1; } return new Point(calendarColumn, calendarRow - 1); } /** * Returns the given date's position in the grid of the month it is contained in. * * @param date the Date to get the logical position for * @return the logical coordinates of the day in the grid of days in a * month or null if the Date is not visible. */ protected Point getDayGridPosition(Date date) { if (!isVisible(date)) return null; Calendar calendar = getCalendar(date); Date startOfDay = CalendarUtils.startOfDay(calendar, date); // there must be a less ugly way? // columns CalendarUtils.startOfWeek(calendar); int column = 0; while (calendar.getTime().before(startOfDay)) { column++; calendar.add(Calendar.DAY_OF_MONTH, 1); } Date startOfWeek = CalendarUtils.startOfWeek(calendar, date); calendar.setTime(date); CalendarUtils.startOfMonth(calendar); int row = 0; while (calendar.getTime().before(startOfWeek)) { row++; calendar.add(Calendar.WEEK_OF_YEAR, 1); } return new Point(column, row); } /** * Returns the Date at the given location.<p> * * Mapping pixel to calendar day. * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the day at the given location or null if the location * doesn't map to a day */ @Override public Date getDayAtLocation(int x, int y) { Point dayInGrid = getDayGridPositionAtLocation(x, y); if ((dayInGrid == null) || (dayInGrid.x < 0) || (dayInGrid.y < 0)) return null; Date month = getMonthAtLocation(x, y); return getDayInMonth(month, dayInGrid.y, dayInGrid.x); } /** * Returns the bounds of the given day. * The bounds are in monthView coordinate system.<p> * * PENDING JW: this most probably should be public as it is the logical * reverse of getDayAtLocation <p> * * @param date the Date to return the bounds for. Must not be null. * @return the bounds of the given date or null if not visible. */ protected Rectangle getDayBounds(Date date) { if (!isVisible(date)) return null; Point position = getDayGridPosition(date); Rectangle monthBounds = getMonthBounds(date); monthBounds.y += getMonthHeaderHeight() + (position.y + 1) * fullBoxHeight; if (monthView.isShowingWeekNumber()) { position.x++; } if (isLeftToRight) { monthBounds.x += position.x * fullBoxWidth; } else { int start = monthBounds.x + monthBounds.width - fullBoxWidth; monthBounds.x = start - position.x * fullBoxWidth; } monthBounds.width = fullBoxWidth; monthBounds.height = fullBoxHeight; return monthBounds; } /** * Returns a boolean indicating if the given Date is visible. Trailing/leading * dates of the last/first displayed month are considered to be invisible. * * @param date the Date to check for visibility. Must not be null. * @return true if the date is visible, false otherwise. */ private boolean isVisible(Date date) { if (getFirstDisplayedDay().after(date) || getLastDisplayedDay().before(date)) return false; return true; } protected Date getDayInMonth(Date month, int row, int column) { Calendar calendar = getCalendar(month); if (!CalendarUtils.isStartOfMonth(calendar)) throw new IllegalStateException("calendar must be start of month but was: " + month.getTime()); CalendarUtils.startOfWeek(calendar); calendar.add(Calendar.DAY_OF_MONTH, row * JXMonthView.DAYS_IN_WEEK + column); return calendar.getTime(); } /** * Mapping pixel to bounds.<p> * * PENDING JW: define the "action grid". Currently this replaces the old * version to remove all internal usage of deprecated methods. * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the bounds of the active header area in containing the location * or null if outside. */ protected int getTraversableGridPositionAtLocation(int x, int y) { Rectangle headerBounds = getMonthHeaderBoundsAtLocation(x, y); if (headerBounds == null) return -1; if (y < headerBounds.y + arrowPaddingY) return -1; if (y > headerBounds.y + headerBounds.height - arrowPaddingY) return -1; headerBounds.setBounds(headerBounds.x + arrowPaddingX, y, headerBounds.width - 2 * arrowPaddingX, headerBounds.height); if (!headerBounds.contains(x, y)) return -1; Rectangle hitArea = new Rectangle(headerBounds.x, headerBounds.y, monthUpImage.getIconWidth(), monthUpImage.getIconHeight()); if (hitArea.contains(x, y)) { return isLeftToRight ? MONTH_DOWN : MONTH_UP; } hitArea.translate(headerBounds.width - monthUpImage.getIconWidth(), 0); if (hitArea.contains(x, y)) { return isLeftToRight ? MONTH_UP : MONTH_DOWN; } return -1; } /** * Returns the bounds of the month header which contains the * given location. The bounds are in monthView coordinate system. * * <p> * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the bounds of the month which contains the location, * or null if outside */ protected Rectangle getMonthHeaderBoundsAtLocation(int x, int y) { Rectangle header = getMonthBoundsAtLocation(x, y); if (header == null) return null; header.height = getMonthHeaderHeight(); return header; } /** * Returns the bounds of the month details which contains the * given location. The bounds are in monthView coordinate system. * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the bounds of the details grid in the month at * location or null if outside. */ private Rectangle getMonthDetailsBoundsAtLocation(int x, int y) { Rectangle month = getMonthBoundsAtLocation(x, y); if (month == null) return null; int startOfDaysY = month.y + getMonthHeaderHeight(); if (y < startOfDaysY) return null; month.y = startOfDaysY; month.height = month.height - getMonthHeaderHeight(); return month; } /** * Returns the bounds of the month which contains the * given location. The bounds are in monthView coordinate system. * * <p> * * Mapping pixel to bounds. * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the bounds of the month which contains the location, * or null if outside */ protected Rectangle getMonthBoundsAtLocation(int x, int y) { if (!calendarGrid.contains(x, y)) return null; int calendarRow = (y - calendarGrid.y) / fullCalendarHeight; int calendarColumn = (x - calendarGrid.x) / fullCalendarWidth; return new Rectangle( calendarGrid.x + calendarColumn * fullCalendarWidth, calendarGrid.y + calendarRow * fullCalendarHeight, calendarWidth, calendarHeight); } /** * * Returns the logical coordinates of the month which contains * the given location. The p.x of the returned value represents the column, the * p.y represents the row the month is shown in. The transformation takes * care of ComponentOrientation. <p> * * Mapping pixel to logical grid coordinates. * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the logical coordinates of the month in the grid of month shown by * this monthView or null if outside. */ protected Point getMonthGridPositionAtLocation(int x, int y) { if (!calendarGrid.contains(x, y)) return null; int calendarRow = (y - calendarGrid.y) / fullCalendarHeight; int calendarColumn = (x - calendarGrid.x) / fullCalendarWidth; if (!isLeftToRight) { int start = calendarGrid.x + calendarGrid.width; calendarColumn = (start - x) / fullCalendarWidth; } return new Point(calendarColumn, calendarRow); } /** * Returns the Date representing the start of the month which * contains the given location.<p> * * Mapping pixel to calendar day. * * @param x the x position of the location in pixel * @param y the y position of the location in pixel * @return the start of the month which contains the given location or * null if the location is outside the grid of months. */ protected Date getMonthAtLocation(int x, int y) { Point month = getMonthGridPositionAtLocation(x, y); if (month == null) return null; return getMonth(month.y, month.x); } /** * Returns the Date representing the start of the month at the given * logical position in the grid of months. <p> * * Mapping logical grid coordinates to Calendar. * * @param row the rowIndex in the grid of months. * @param column the columnIndex in the grid months. * @return a Date representing the start of the month at the given * logical coordinates. * * @see #getMonthGridPosition(Date) */ protected Date getMonth(int row, int column) { Calendar calendar = getCalendar(); calendar.add(Calendar.MONTH, row * calendarColumnCount + column); return calendar.getTime(); } /** * Returns the logical grid position of the month containing the given date. * The Point's x value is the column in the grid of months, the y value * is the row in the grid of months. * * Mapping Date to logical grid position, this is the reverse of getMonth(int, int). * * @param date the Date to return the bounds for. Must not be null. * @return the postion of the month that contains the given date or null if not visible. * * @see #getMonth(int, int) * @see #getMonthBounds(int, int) */ protected Point getMonthGridPosition(Date date) { if (!isVisible(date)) return null; // start of grid Calendar calendar = getCalendar(); int firstMonth = calendar.get(Calendar.MONTH); int firstYear = calendar.get(Calendar.YEAR); calendar.setTime(date); int month = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); int diffMonths = month - firstMonth + ((year - firstYear) * JXMonthView.MONTHS_IN_YEAR); int row = diffMonths / calendarColumnCount; int column = diffMonths % calendarColumnCount; return new Point(column, row); } /** * Returns the bounds of the month at the given logical coordinates * in the grid of visible months.<p> * * Mapping logical grip position to pixel. * * @param row the rowIndex in the grid of months. * @param column the columnIndex in the grid months. * @return the bounds of the month at the given logical logical position. * * @see #getMonthGridPositionAtLocation(int, int) * @see #getMonthBoundsAtLocation(int, int) */ protected Rectangle getMonthBounds(int row, int column) { int startY = calendarGrid.y + row * fullCalendarHeight; int startX = calendarGrid.x + column * fullCalendarWidth; if (!isLeftToRight) { startX = calendarGrid.x + (calendarColumnCount - 1 - column) * fullCalendarWidth; } return new Rectangle(startX, startY, calendarWidth, calendarHeight); } /** * Returns the bounds of the month containing the given date. * The bounds are in monthView coordinate system.<p> * * Mapping Date to pixel. * * @param date the Date to return the bounds for. Must not be null. * @return the bounds of the month that contains the given date or null if not visible. * * @see #getMonthAtLocation(int, int) */ protected Rectangle getMonthBounds(Date date) { Point position = getMonthGridPosition(date); return position != null ? getMonthBounds(position.y, position.x) : null; } /** * Returns the size of a month. * @return the size of a month. */ protected Dimension getMonthSize() { return new Dimension(calendarWidth, calendarHeight); } /** * Returns the size of a day including the padding. * @return the size of a month. */ protected Dimension getDaySize() { return new Dimension(fullBoxWidth, fullBoxHeight); } /** * Returns the height of the month header. * * @return the height of the month header. */ protected int getMonthHeaderHeight() { return fullMonthBoxHeight; } /** * Called from layout: calculates properties * of grid of months. */ private void calculateMonthGridLayoutProperties() { calculateMonthGridRowColumnCount(); calculateMonthGridBounds(); } /** * Calculates the bounds of the grid of months. * * CalendarRow/ColumnCount and calendarWidth/Height must be * initialized before calling this. */ private void calculateMonthGridBounds() { // PENDING JW: this is the "old way" - keep until the deprecated // methods are removed. calculateStartPositionUnused(); calendarGrid.setBounds(calculateCalendarGridX(), calculateCalendarGridY(), calculateCalendarGridWidth(), calculateCalendarGridHeight()); } private int calculateCalendarGridY() { return (monthView.getHeight() - calculateCalendarGridHeight()) / 2; } private int calculateCalendarGridX() { return (monthView.getWidth() - calculateCalendarGridWidth()) / 2; } private int calculateCalendarGridHeight() { return ((calendarHeight * calendarRowCount) + (CALENDAR_SPACING * (calendarRowCount - 1 ))); } private int calculateCalendarGridWidth() { return ((calendarWidth * calendarColumnCount) + (CALENDAR_SPACING * (calendarColumnCount - 1))); } /** * Calculates and updates the numCalCols/numCalRows that determine the number of * calendars that can be displayed. Updates the last displayed date if * appropriate. * */ private void calculateMonthGridRowColumnCount() { int oldNumCalCols = calendarColumnCount; int oldNumCalRows = calendarRowCount; // Determine how many columns of calendars we want to paint. calendarColumnCount = 1; calendarColumnCount += (monthView.getWidth() - calendarWidth) / (calendarWidth + CALENDAR_SPACING); // Determine how many rows of calendars we want to paint. calendarRowCount = 1; calendarRowCount += (monthView.getHeight() - calendarHeight) / (calendarHeight + CALENDAR_SPACING); if (oldNumCalCols != calendarColumnCount || oldNumCalRows != calendarRowCount) { updateLastDisplayedDay(getFirstDisplayedDay()); } } /** * {@inheritDoc} */ @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); Object oldAAValue = null; Graphics2D g2 = (g instanceof Graphics2D) ? (Graphics2D)g : null; if (g2 != null && monthView.isAntialiased()) { oldAAValue = g2.getRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } Rectangle clip = g.getClipBounds(); Graphics tmp = g.create(); paintBackground(clip, tmp); tmp.dispose(); g.setColor(monthView.getForeground()); // Get a calender set to the first displayed date Calendar cal = getCalendar(); // Center the calendars horizontally/vertically in the available space. for (int row = 0; row < calendarRowCount; row++) { // Check if this row falls in the clip region. for (int column = 0; column < calendarColumnCount; column++) { bounds = getMonthBounds(row, column); if (bounds.intersects(clip)) { paintMonth(g, bounds.x, bounds.y, bounds.width, bounds.height, cal); } // JW: clarified contract for all paint methods: // called methods must not change the calendar, its the responsibility cal.add(Calendar.MONTH, 1); } } if (g2 != null && monthView.isAntialiased()) { g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue); } } /** * Paints a month. It is assumed the given calendar is already set to the * first day of the month to be painted.<p> * * Note: the given calendar must not be changed. * * @param g Graphics object. * @param x x location of month * @param y y location of month * @param width width of month * @param height height of month * @param calendar the calendar specifying the the first day of the month to paint, * must not be null */ @SuppressWarnings({"UnusedDeclaration"}) protected void paintMonth(Graphics g, int x, int y, int width, int height, Calendar calendar) { // PEINDING JW: remove usage of deprecated api // use Date instead of millis // Paint month name background. paintMonthStringBackground(g, x, y, width, fullMonthBoxHeight, calendar); paintMonthStringForeground(g, x, y, width, fullMonthBoxHeight, calendar); // Paint arrow buttons for traversing months if enabled. if (monthView.isTraversable()) { //draw the icons monthDownImage.paintIcon(monthView, g, x + arrowPaddingX, y + ((fullMonthBoxHeight - monthDownImage.getIconHeight()) / 2)); monthUpImage.paintIcon(monthView, g, x + width - arrowPaddingX - monthUpImage.getIconWidth(), y + ((fullMonthBoxHeight - monthDownImage.getIconHeight()) / 2)); } // Paint background of the short names for the days of the week. boolean showingWeekNumber = monthView.isShowingWeekNumber(); int tmpX = isLeftToRight ? x + (showingWeekNumber ? fullBoxWidth : 0) : x; int tmpY = y + fullMonthBoxHeight; int tmpWidth = width - (showingWeekNumber ? fullBoxWidth : 0); paintDayOfTheWeekBackground(g, tmpX, tmpY, tmpWidth, fullBoxHeight, calendar); // Paint short representation of day of the week. int dayIndex = monthView.getFirstDayOfWeek() - 1; Font oldFont = monthView.getFont(); g.setFont(derivedFont); g.setColor(monthView.getDaysOfTheWeekForeground()); FontMetrics fm = monthView.getFontMetrics(derivedFont); String[] daysOfTheWeek = monthView.getDaysOfTheWeek(); for (int i = 0; i < JXMonthView.DAYS_IN_WEEK; i++) { tmpX = isLeftToRight ? x + (i * fullBoxWidth) + monthView.getBoxPaddingX() + (boxWidth / 2) - (fm.stringWidth(daysOfTheWeek[dayIndex]) / 2) : x + width - (i * fullBoxWidth) - monthView.getBoxPaddingX() - (boxWidth / 2) - (fm.stringWidth(daysOfTheWeek[dayIndex]) / 2); if (showingWeekNumber) { tmpX += isLeftToRight ? fullBoxWidth : -fullBoxWidth; } tmpY = y + fullMonthBoxHeight + monthView.getBoxPaddingY() + fm.getAscent(); g.drawString(daysOfTheWeek[dayIndex], tmpX, tmpY); dayIndex++; if (dayIndex == JXMonthView.DAYS_IN_WEEK) { dayIndex = 0; } } g.setFont(oldFont); // new top is below monthBox and daysOfWeek header int yNew = y + fullMonthBoxHeight + fullBoxHeight; // paint the column of week numbers paintWeeksOfYear(g, x, yNew, width, calendar); int xOffset = 0; if (monthView.isShowingWeekNumber()) { xOffset = fullBoxWidth; } if (isLeftToRight) { paintDays(g, x + xOffset, yNew, width - xOffset, calendar); } else { paintDays(g, x , yNew, width - xOffset, calendar); } } /** * * Paints all days in the days' grid, that is the month area below * the daysOfWeek and to the right/left (depending on * the monthView's componentOrientation) of the weekOfYears. * The calendar * represents the first day of the month to paint. <p> * * Note: the calendar must not be changed. * * @param g Graphics object. * @param left the left boundary of the day grid. * @param top the upper boundary of the day grid * @param width the width of the day grid. * @param cal the calendar specifying the the first day of the month to paint, * must not be null */ protected void paintDays(Graphics g, int left, int top, int width, Calendar cal) { Calendar calendar = (Calendar) cal.clone(); CalendarUtils.startOfMonth(calendar); Date startOfMonth = calendar.getTime(); CalendarUtils.endOfMonth(calendar); Date endOfMonth = calendar.getTime(); // reset the clone calendar.setTime(cal.getTime()); // alwaysfill the day grid in the month completely // int weeks = getWeeks(calendar); // adjust to start of week calendar.setTime(cal.getTime()); CalendarUtils.startOfWeek(calendar); Date firstStartOfWeek = calendar.getTime(); // painting a grid of day boxes, all with dimensions // width == fullBoxWidth and height = fullBoxHeight. int topOfDay = top; for (int week = 0; week < WEEKS_IN_MONTH; week++) { // for (int week = 0; week <= weeks; week++) { int leftOfDay = isLeftToRight ? left : left + width - fullBoxWidth; for (int day = 0; day < 7; day++) { if (calendar.getTime().before(startOfMonth)) { // leading paintLeadingDay(g, leftOfDay, topOfDay, calendar); } else if (calendar.getTime().after(endOfMonth)) { paintTrailingDay(g, leftOfDay, topOfDay, calendar); } else { paintDay(g, leftOfDay, topOfDay, calendar); } leftOfDay = isLeftToRight ? leftOfDay + fullBoxWidth : leftOfDay - fullBoxWidth; calendar.add(Calendar.DAY_OF_MONTH, 1); } if (!CalendarUtils.isStartOfWeek(calendar)) { throw new IllegalStateException("started painting at " + firstStartOfWeek + " should still be on the start of a week instead of " + calendar.getTime()); } topOfDay += fullBoxHeight; } } /** * Paints a day the current month, represented by the calendar in a day-box * located at left/top. The size of the day-box is defined by * fullBoxWidth/Height. The appearance of the day depends on its state (like * unselectable, flagged, selected) * <p> * * Note: the given calendar must not be changed. * * @param g the Graphics to paint into. * @param left the left boundary of the day-box to paint. * @param top the upper boundary of the day-box to paint. * @param calendar the calendar specifying the the day to paint, must not be * null */ protected void paintDay(Graphics g, int left, int top, Calendar calendar) { if (monthView.isUnselectableDate(calendar.getTime())) { paintUnselectableDayBackground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); paintUnselectableDayForeground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); } else if (monthView.isFlaggedDate(calendar.getTime())) { paintFlaggedDayBackground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); paintFlaggedDayForeground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); } else { paintDayBackground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); paintDayForeground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); } } /** * Paints a trailing day of the current month, represented by the calendar, * in a day-box located at left/top. The size of the day-box is defined by * fullBoxWidth/Height. Does nothing if the monthView's * isShowingTrailingDates is false. * <p> * * Note: the given calendar must not be changed. * * @param g the Graphics to paint into. * @param left the left boundary of the day-box to paint. * @param top the upper boundary of the day-box to paint. * @param calendar the calendar specifying the the day to paint, must not be * null */ protected void paintTrailingDay(Graphics g, int left, int top, Calendar calendar) { if (!monthView.isShowingTrailingDays()) return; paintTrailingDayBackground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); paintTrailingDayForeground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); } /** * Paints a leading day of the current month, represented by the calendar, * in a day-box located at left/top. The size of the day-box is defined by * fullBoxWidth/Height. Does nothing if the monthView's * isShowingLeadingDates is false. * <p> * * Note: the given calendar must not be changed. * * @param g the Graphics to paint into. * @param left the left boundary of the day-box to paint. * @param top the upper boundary of the day-box to paint. * @param calendar the calendar specifying the the day to paint, must not be * null */ protected void paintLeadingDay(Graphics g, int left, int top, Calendar calendar) { if (!monthView.isShowingLeadingDays()) return; paintLeadingDayBackground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); paintLeadingDayForeground(g, left, top, fullBoxWidth, fullBoxHeight, calendar); } /** * Returns the number of weeks to paint in the current month, as represented * by the given calendar. * * Note: the given calendar must not be changed. * * @param month the calendar specifying the the first day of the month to * paint, must not be null * @return the number of weeks of this month. */ protected int getWeeks(Calendar month) { Date old = month.getTime(); CalendarUtils.startOfWeek(month); int firstWeek = month.get(Calendar.WEEK_OF_YEAR); month.setTime(old); CalendarUtils.endOfMonth(month); int lastWeek = month.get(Calendar.WEEK_OF_YEAR); if (lastWeek < firstWeek) { lastWeek = month.getActualMaximum(Calendar.WEEK_OF_YEAR) + 1; } month.setTime(old); return lastWeek - firstWeek; } /** * Paints the weeks of year if the showingWeek property is true. Does nothing * otherwise. * * It is assumed the given calendar is already set to the * first day of the month. The calendar is unchanged when leaving this method. * * Note: the given calendar must not be changed. * * PENDING JW: this implementation doesn't need the height - should it be given * anyway for symetry in case subclasses need it? * * @param g Graphics object. * @param x x location of month * @param initialY y the upper bound of the "weekNumbers-box" * @param width width of month * @param cal the calendar specifying the the first day of the month to paint, * must not be null */ protected void paintWeeksOfYear(Graphics g, int x, int initialY, int width, Calendar cal) { if (!monthView.isShowingWeekNumber()) return; int tmpX = isLeftToRight ? x : x + width - fullBoxWidth; paintWeekOfYearBackground(g, tmpX, initialY, fullBoxWidth, calendarHeight - (fullMonthBoxHeight + fullBoxHeight), cal); Calendar calendar = (Calendar) cal.clone(); int weeks = getWeeks(calendar); calendar.setTime(cal.getTime()); for (int weekOfYear = 0; weekOfYear <= weeks; weekOfYear++) { paintWeekOfYearForeground(g, tmpX, initialY, fullBoxWidth, fullBoxHeight, calendar); initialY += fullBoxHeight; calendar.add(Calendar.WEEK_OF_YEAR, 1); } } protected void paintDayOfTheWeekBackground(Graphics g, int x, int y, int width, int height, Calendar cal) { int boxPaddingX = monthView.getBoxPaddingX(); g.drawLine(x + boxPaddingX, y + height - 1, x + width - boxPaddingX, y + height - 1); } protected void paintWeekOfYearBackground(Graphics g, int x, int y, int width, int height, Calendar cal) { int boxPaddingY = monthView.getBoxPaddingY(); x = isLeftToRight ? x + width - 1 : x; g.drawLine(x, y + boxPaddingY, x, y + height - boxPaddingY); } /** * Paints the week of the year of the week of the year represented by the * given calendar. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object * @param x x-coordinate of upper left corner. * @param y y-coordinate of upper left corner. * @param width width of bounding box * @param height height of bounding box */ @SuppressWarnings({"UNUSED_SYMBOL", "UnusedDeclaration"}) protected void paintWeekOfYearForeground(Graphics g, int x, int y, int width, int height, Calendar cal) { String str = Integer.toString(cal.get(Calendar.WEEK_OF_YEAR)); FontMetrics fm; g.setColor(weekOfTheYearForeground); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); fm = g.getFontMetrics(); g.drawString(str, isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(str) : x + boxPaddingX + boxWidth - fm.stringWidth(str) - 1, y + boxPaddingY + fm.getAscent()); } protected void paintMonthStringBackground(Graphics g, int x, int y, int width, int height, Calendar cal) { // Modify bounds by the month string insets. Insets monthStringInsets = monthView.getMonthStringInsets(); x = isLeftToRight ? x + monthStringInsets.left : x + monthStringInsets.right; y = y + monthStringInsets.top; width = width - monthStringInsets.left - monthStringInsets.right; height = height - monthStringInsets.top - monthStringInsets.bottom; g.setColor(monthView.getMonthStringBackground()); g.fillRect(x, y, width, height); } /** * Note: the given calendar must not be changed. * * @param g Graphics object to paint to. * @param x x-coordinate of upper left corner. * @param y y-coordinate of upper left corner. * @param width width of the bounding box. * @param height height of the bounding box. * @param cal the calendar specifying the day to use, must not be null */ protected void paintMonthStringForeground(Graphics g, int x, int y, int width, int height, Calendar cal) { // Paint month name. Font oldFont = monthView.getFont(); // TODO: Calculating the bounds of the text dynamically so we can invoke // a popup for selecting the month/year to view. g.setFont(derivedFont); FontMetrics fm = monthView.getFontMetrics(derivedFont); int month = cal.get(Calendar.MONTH); String monthName = monthsOfTheYear[month]; String yearString = Integer.toString(cal.get(Calendar.YEAR)); Rectangle2D rect = fm.getStringBounds(monthName, g); monthStringBounds[month] = new Rectangle((int) rect.getX(), (int) rect.getY(), (int) rect.getWidth(), (int) rect.getHeight()); int spaceWidth = (int) fm.getStringBounds(" ", g).getWidth(); rect = fm.getStringBounds(yearString, g); yearStringBounds[month] = new Rectangle((int) rect.getX(), (int) rect.getY(), (int) rect.getWidth(), (int) rect.getHeight()); // END g.setColor(monthView.getMonthStringForeground()); int tmpX = x + (calendarWidth / 2) - ((monthStringBounds[month].width + yearStringBounds[month].width + spaceWidth) / 2); int tmpY = y + monthView.getBoxPaddingY() + ((monthBoxHeight - boxHeight) / 2) + fm.getAscent(); monthStringBounds[month].x = tmpX; yearStringBounds[month].x = (monthStringBounds[month].x + monthStringBounds[month].width + spaceWidth); paintMonthStringForeground(g,monthName, monthStringBounds[month].x, tmpY, yearString, yearStringBounds[month].x, tmpY, cal); g.setFont(oldFont); } /** * Paints only text for month and year. No calculations made. Used by custom LAFs. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics to paint into. * @param monthName Name of the month. * @param monthX Month string x coordinate. * @param monthY Month string y coordinate. * @param yearName Name (number) of the year. * @param yearX Year string x coordinate. * @param yearY Year string y coordinate. */ protected void paintMonthStringForeground(Graphics g, String monthName, int monthX, int monthY, String yearName, int yearX, int yearY, Calendar cal) { g.drawString(monthName, monthX, monthY); g.drawString(yearName, yearX, yearY); } /** * Paint the background for the day specified by the given calendar. * <p> * * Note: the given calendar must not be changed. * * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null * @see org.jdesktop.swingx.JXMonthView#isSelectedDate * @see #isToday */ protected void paintDayBackground(Graphics g, int x, int y, int width, int height, Calendar cal) { Date date = cal.getTime(); //InMillis(); if (monthView.isSelected(date)) { g.setColor(monthView.getSelectedBackground()); g.fillRect(x, y, width, height); } // If the date is today make sure we draw it's background over the selected // background. if (isToday(date)) { g.setColor(monthView.getTodayBackground()); g.drawRect(x, y, width - 1, height - 1); } } /** * Paint the foreground for the specified day. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintDayForeground(Graphics g, int x, int y, int width, int height, Calendar cal) { String numericDay = dayOfMonthFormatter.format(cal.getTime()); g.setColor(monthView.getDayForeground(cal.get(Calendar.DAY_OF_WEEK))); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); paintDayForeground(g, numericDay, isLeftToRight ? x + boxPaddingX + boxWidth : x + boxPaddingX + boxWidth - 1, y + boxPaddingY, cal); } /** * Paints string of the day. No calculations made. Used by LAFs. * <p> * * Note: the given calendar must not be changed. * @param g Graphics to paint on. * @param numericDay Text representation of the day. * @param x X coordinate of the upper <b>right</b> corner. * @param y Y coordinate of the upper <b>right</b> corner. */ protected void paintDayForeground(Graphics g, String numericDay, int x, int y, Calendar cal) { FontMetrics fm = g.getFontMetrics(); g.drawString(numericDay, x - fm.stringWidth(numericDay), y + fm.getAscent()); } /** * Paint the background for the specified flagged day. The default implementation just calls * <code>paintDayBackground</code>. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintFlaggedDayBackground(Graphics g, int x, int y, int width, int height, Calendar cal) { paintDayBackground(g, x, y, width, height, cal); } /** * Paint the foreground for the specified flagged day. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintFlaggedDayForeground(Graphics g, int x, int y, int width, int height, Calendar cal) { Date date = cal.getTime(); String numericDay = dayOfMonthFormatter.format(date); FontMetrics fm; int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); Font oldFont = monthView.getFont(); g.setColor(monthView.getFlaggedDayForeground()); g.setFont(derivedFont); fm = monthView.getFontMetrics(derivedFont); g.drawString(numericDay, isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(numericDay): x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) - 1, y + boxPaddingY + fm.getAscent()); g.setFont(oldFont); } /** * Paint the foreground for the specified unselectable day. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintUnselectableDayBackground(Graphics g, int x, int y, int width, int height, Calendar cal) { paintDayBackground(g, x, y, width, height, cal); } /** * Paint the foreground for the specified unselectable day. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintUnselectableDayForeground(Graphics g, int x, int y, int width, int height, Calendar cal) { paintDayForeground(g, x, y, width, height, cal); g.setColor(unselectableDayForeground); String numericDay = dayOfMonthFormatter.format(cal.getTime()); FontMetrics fm = monthView.getFontMetrics(derivedFont); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); width = fm.stringWidth(numericDay); height = fm.getAscent(); x = isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) : x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) - 1; y = y + boxPaddingY; g.drawLine(x, y, x + width, y + height); g.drawLine(x + 1, y, x + width + 1, y + height); g.drawLine(x + width, y, x, y + height); g.drawLine(x + width - 1, y, x - 1, y + height); } /** * Paint the background for the specified leading day. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintLeadingDayBackground(Graphics g, int x, int y, int width, int height, Calendar cal) { paintDayBackground(g, x, y, width, height, cal); } /** * Paint the foreground for the specified leading day. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintLeadingDayForeground(Graphics g, int x, int y, int width, int height, Calendar cal) { String numericDay = dayOfMonthFormatter.format(cal.getTime()); FontMetrics fm; g.setColor(leadingDayForeground); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); fm = g.getFontMetrics(); int ltorOffset = x + boxPaddingX + boxWidth - fm.stringWidth(numericDay); g.drawString(numericDay, isLeftToRight ? ltorOffset : ltorOffset - 1, y + boxPaddingY + fm.getAscent()); } /** * Paint the background for the specified trailing day. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintTrailingDayBackground(Graphics g, int x, int y, int width, int height, Calendar cal) { paintLeadingDayBackground(g, x, y, width, height, cal); } /** * Paint the foreground for the specified trailing day. * <p> * * Note: the given calendar must not be changed. * * @param g Graphics object to paint to * @param x x-coordinate of upper left corner * @param y y-coordinate of upper left corner * @param width width of bounding box for the day * @param height height of bounding box for the day * @param cal the calendar specifying the day to paint, must not be null */ protected void paintTrailingDayForeground(Graphics g, int x, int y, int width, int height, Calendar cal) { String numericDay = dayOfMonthFormatter.format(cal.getTime()); FontMetrics fm; g.setColor(trailingDayForeground); int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); fm = g.getFontMetrics(); g.drawString(numericDay, isLeftToRight ? x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) : x + boxPaddingX + boxWidth - fm.stringWidth(numericDay) - 1, y + boxPaddingY + fm.getAscent()); } protected void paintBackground(final Rectangle clip, final Graphics g) { if (monthView.isOpaque()) { g.setColor(monthView.getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); } } private void traverseMonth(int arrowType) { if (arrowType == MONTH_DOWN) { previousMonth(); } else if (arrowType == MONTH_UP) { nextMonth(); } } private void nextMonth() { Date upperBound = monthView.getUpperBound(); if (upperBound == null || upperBound.after(getLastDisplayedDay()) ){ Calendar cal = getCalendar(); cal.add(Calendar.MONTH, 1); monthView.setFirstDisplayedDay(cal.getTime()); } } private void previousMonth() { Date lowerBound = monthView.getLowerBound(); if (lowerBound == null || lowerBound.before(getFirstDisplayedDay())){ Calendar cal = getCalendar(); cal.add(Calendar.MONTH, -1); monthView.setFirstDisplayedDay(cal.getTime()); } } /** * Returns the monthViews calendar configured to the firstDisplayedDate. * * NOTE: it's safe to change the calendar state without resetting because * it's JXMonthView's responsibility to protect itself. * * @return the monthView's calendar, configured with the firstDisplayedDate. */ protected Calendar getCalendar() { return getCalendar(getFirstDisplayedDay()); } /** * Returns the monthViews calendar configured to the given time. * * NOTE: it's safe to change the calendar state without resetting because * it's JXMonthView's responsibility to protect itself. * * @param date the date to configure the calendar with * @return the monthView's calendar, configured with the given date. */ protected Calendar getCalendar(Date date) { Calendar calendar = monthView.getCalendar(); calendar.setTime(date); return calendar; } /** * Updates the lastDisplayedDate property based on the given first and * visible # of months. * * @param first the date of the first visible day. */ private void updateLastDisplayedDay(Date first) { Calendar cal = getCalendar(first); cal.add(Calendar.MONTH, ((calendarColumnCount * calendarRowCount) - 1)); CalendarUtils.endOfMonth(cal); lastDisplayedDate = cal.getTime(); } /** * {@inheritDoc} */ @Override public Date getLastDisplayedDay() { return lastDisplayedDate; } /** * Sets the firstDisplayedDate property to the given value. Must update * dependent state as well. * * Here: updated lastDisplayedDatefirstDisplayedMonth/Year accordingly. * * * @param firstDisplayedDate the firstDisplayedDate to set */ protected void setFirstDisplayedDay(Date firstDisplayedDate) { Calendar calendar = getCalendar(firstDisplayedDate); this.firstDisplayedDate = firstDisplayedDate; this.firstDisplayedMonth = calendar.get(Calendar.MONTH); this.firstDisplayedYear = calendar.get(Calendar.YEAR); updateLastDisplayedDay(firstDisplayedDate); monthView.repaint(); } /** * @return the firstDisplayedDate */ protected Date getFirstDisplayedDay() { return firstDisplayedDate; } /** * @return the firstDisplayedMonth */ protected int getFirstDisplayedMonth() { return firstDisplayedMonth; } /** * @return the firstDisplayedYear */ protected int getFirstDisplayedYear() { return firstDisplayedYear; } /** * @return the selection */ protected SortedSet<Date> getSelection() { return monthView.getSelection(); } /** * @return the start of today. */ protected Date getToday() { return monthView.getToday(); } /** * Returns true if the date passed in is the same as today. * * PENDING JW: really want the exact test? * * @param date long representing the date you want to compare to today. * @return true if the date passed is the same as today. */ protected boolean isToday(Date date) { return date.equals(getToday()); } /** * temporary: removed SelectionMode.NO_SELECTION, replaced * all access by this method to enable easy re-adding, if we want it. * If not - remove. */ private boolean canSelectByMode() { return true; } private class Handler implements MouseListener, MouseMotionListener, LayoutManager, PropertyChangeListener, DateSelectionListener { private boolean armed; private Date startDate; private Date endDate; public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) { // If we were using the keyboard we aren't anymore. setUsingKeyboard(false); if (!monthView.isEnabled()) { return; } if (!monthView.hasFocus() && monthView.isFocusable()) { monthView.requestFocusInWindow(); } // Check if one of the month traverse buttons was pushed. if (monthView.isTraversable()) { int arrowType = getTraversableGridPositionAtLocation(e.getX(), e.getY()); if (arrowType != -1) { traverseMonth(arrowType); return; } } if (!canSelectByMode()) { return; } // long selected = monthView.getDayAt(e.getX(), e.getY()); Date cal = getDayAtLocation(e.getX(), e.getY()); if (cal == null) { return; } // Update the selected dates. startDate = cal; endDate = cal; if (monthView.getSelectionMode() == SelectionMode.SINGLE_INTERVAL_SELECTION || // selectionMode == SelectionMode.WEEK_INTERVAL_SELECTION || monthView.getSelectionMode() == SelectionMode.MULTIPLE_INTERVAL_SELECTION) { pivotDate = startDate; } monthView.getSelectionModel().setAdjusting(true); if (monthView.getSelectionMode() == SelectionMode.MULTIPLE_INTERVAL_SELECTION && e.isControlDown()) { monthView.addSelectionInterval(startDate, endDate); } else { monthView.setSelectionInterval(startDate, endDate); } // Arm so we fire action performed on mouse release. armed = true; } public void mouseReleased(MouseEvent e) { // If we were using the keyboard we aren't anymore. setUsingKeyboard(false); if (!monthView.isEnabled()) { return; } if (!monthView.hasFocus() && monthView.isFocusable()) { monthView.requestFocusInWindow(); } if (armed) { monthView.commitSelection(); } armed = false; } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseDragged(MouseEvent e) { // If we were using the keyboard we aren't anymore. setUsingKeyboard(false); if (!monthView.isEnabled() || !canSelectByMode()) { return; } // long selected = monthView.getDayAt(e.getX(), e.getY()); Date cal = getDayAtLocation(e.getX(), e.getY()); if (cal == null) { return; } Date selected = cal; Date oldStart = startDate; Date oldEnd = endDate; if (monthView.getSelectionMode() == SelectionMode.SINGLE_SELECTION) { if (selected.equals(oldStart)) { return; } startDate = selected; endDate = selected; } else { if (selected.before(pivotDate)) { startDate = selected; endDate = pivotDate; } else if (selected.after(pivotDate)) { startDate = pivotDate; endDate = selected; } } if (startDate.equals(oldStart) && endDate.equals(oldEnd)) { return; } if (monthView.getSelectionMode() == SelectionMode.MULTIPLE_INTERVAL_SELECTION && e.isControlDown()) { monthView.addSelectionInterval(startDate, endDate); } else { monthView.setSelectionInterval(startDate, endDate); } // Set trigger. armed = true; } public void mouseMoved(MouseEvent e) {} private Dimension preferredSize = new Dimension(); public void addLayoutComponent(String name, Component comp) {} public void removeLayoutComponent(Component comp) {} public Dimension preferredLayoutSize(Container parent) { layoutContainer(parent); return new Dimension(preferredSize); } public Dimension minimumLayoutSize(Container parent) { return preferredLayoutSize(parent); } public void layoutContainer(Container parent) { // Loop through year and get largest representation of the month. // Keep track of the longest month so we can loop through it to // determine the width of a date box. int currDays; int longestMonth = 0; int daysInLongestMonth = 0; int currWidth; int longestMonthWidth = 0; // We use a bold font for figuring out size constraints since // it's larger and flaggedDates will be noted in this style. FontMetrics fm = monthView.getFontMetrics(derivedFont); // JW PENDING: relies on calendar being set at least to year? // No, just on the bare calendar - so don't care about actual time Calendar cal = getCalendar(); cal.set(Calendar.MONTH, cal.getMinimum(Calendar.MONTH)); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH)); for (int i = 0; i < cal.getMaximum(Calendar.MONTH); i++) { currWidth = fm.stringWidth(monthsOfTheYear[i]); if (currWidth > longestMonthWidth) { longestMonthWidth = currWidth; } currDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (currDays > daysInLongestMonth) { longestMonth = cal.get(Calendar.MONTH); daysInLongestMonth = currDays; } cal.add(Calendar.MONTH, 1); } // Loop through the days of the week and adjust the box width // accordingly. boxHeight = fm.getHeight(); String[] daysOfTheWeek = monthView.getDaysOfTheWeek(); for (String dayOfTheWeek : daysOfTheWeek) { currWidth = fm.stringWidth(dayOfTheWeek); if (currWidth > boxWidth) { boxWidth = currWidth; } } // Loop through longest month and get largest representation of the day // of the month. cal.set(Calendar.MONTH, longestMonth); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH)); for (int i = 0; i < daysInLongestMonth; i++) { currWidth = fm.stringWidth( dayOfMonthFormatter.format(cal.getTime())); if (currWidth > boxWidth) { boxWidth = currWidth; } cal.add(Calendar.DAY_OF_MONTH, 1); } // If we are displaying week numbers find the largest displayed week number. boolean showingWeekNumber = monthView.isShowingWeekNumber(); if (showingWeekNumber) { int val = cal.getActualMaximum(Calendar.WEEK_OF_YEAR); currWidth = fm.stringWidth(Integer.toString(val)); if (currWidth > boxWidth) { boxWidth = currWidth; } } // If the calendar is traversable, check the icon heights and // adjust the month box height accordingly. monthBoxHeight = boxHeight; if (monthView.isTraversable()) { int newHeight = monthDownImage.getIconHeight() + arrowPaddingY + arrowPaddingY; if (newHeight > monthBoxHeight) { monthBoxHeight = newHeight; } } // Modify boxWidth if month string is longer int boxPaddingX = monthView.getBoxPaddingX(); int boxPaddingY = monthView.getBoxPaddingY(); preferredSize.width = (boxWidth + (2 * boxPaddingX)) * JXMonthView.DAYS_IN_WEEK; if (preferredSize.width < longestMonthWidth) { double diff = longestMonthWidth - preferredSize.width; if (monthView.isTraversable()) { diff += monthDownImage.getIconWidth() + monthUpImage.getIconWidth() + (arrowPaddingX * 4); } boxWidth += Math.ceil(diff / (double)JXMonthView.DAYS_IN_WEEK); } // Keep track of a full box height/width and full month box height fullBoxWidth = boxWidth + boxPaddingX + boxPaddingX; fullBoxHeight = boxHeight + boxPaddingY + boxPaddingY; fullMonthBoxHeight = monthBoxHeight + boxPaddingY + boxPaddingY; // Keep track of calendar width and height for use later. calendarWidth = fullBoxWidth * JXMonthView.DAYS_IN_WEEK; if (showingWeekNumber) { calendarWidth += fullBoxWidth; } fullCalendarWidth = calendarWidth + CALENDAR_SPACING; calendarHeight = (fullBoxHeight * 7) + fullMonthBoxHeight; fullCalendarHeight = calendarHeight + CALENDAR_SPACING; // Calculate minimum width/height for the component. int prefRows = monthView.getPreferredRows(); preferredSize.height = (calendarHeight * prefRows) + (CALENDAR_SPACING * (prefRows - 1)); int prefCols = monthView.getPreferredCols(); preferredSize.width = (calendarWidth * prefCols) + (CALENDAR_SPACING * (prefCols - 1)); // Add insets to the dimensions. Insets insets = monthView.getInsets(); preferredSize.width += insets.left + insets.right; preferredSize.height += insets.top + insets.bottom; calculateMonthGridLayoutProperties(); } public void propertyChange(PropertyChangeEvent evt) { String property = evt.getPropertyName(); if ("componentOrientation".equals(property)) { isLeftToRight = monthView.getComponentOrientation().isLeftToRight(); monthView.revalidate(); } else if (JXMonthView.SELECTION_MODEL.equals(property)) { DateSelectionModel selectionModel = (DateSelectionModel) evt.getOldValue(); selectionModel.removeDateSelectionListener(getHandler()); selectionModel = (DateSelectionModel) evt.getNewValue(); selectionModel.addDateSelectionListener(getHandler()); } else if ("firstDisplayedDay".equals(property)) { setFirstDisplayedDay(((Date) evt.getNewValue())); } else if (JXMonthView.BOX_PADDING_X.equals(property) || JXMonthView.BOX_PADDING_Y.equals(property) || JXMonthView.TRAVERSABLE.equals(property) || JXMonthView.DAYS_OF_THE_WEEK.equals(property) || "border".equals(property) || "showingWeekNumber".equals(property) || "traversable".equals(property) ) { monthView.revalidate(); monthView.repaint(); } else if ("font".equals(property)) { derivedFont = createDerivedFont(); monthView.revalidate(); } else if ("componentInputMapEnabled".equals(property)) { updateComponentInputMap(); } else if ("locale".equals(property)) { // "locale" is bound property updateLocale(); } else if ("timeZone".equals(property)) { dayOfMonthFormatter.setTimeZone((TimeZone) evt.getNewValue()); } else if ("flaggedDates".equals(property) || "showingTrailingDays".equals(property) || "showingLeadingDays".equals(property) || "today".equals(property) || "antialiased".equals(property) ) { monthView.repaint(); } else { // LOG.info("got propertyChange:" + property); } } public void valueChanged(DateSelectionEvent ev) { // repaint old dirty region // monthView.repaint(dirtyRect); // // calculate new dirty region based on selection // calculateDirtyRectForSelection(); // // repaint new selection // monthView.repaint(dirtyRect); monthView.repaint(); } } /** * Class that supports keyboard traversal of the JXMonthView component. */ private class KeyboardAction extends AbstractAction { public static final int ACCEPT_SELECTION = 0; public static final int CANCEL_SELECTION = 1; public static final int SELECT_PREVIOUS_DAY = 2; public static final int SELECT_NEXT_DAY = 3; public static final int SELECT_DAY_PREVIOUS_WEEK = 4; public static final int SELECT_DAY_NEXT_WEEK = 5; public static final int ADJUST_SELECTION_PREVIOUS_DAY = 6; public static final int ADJUST_SELECTION_NEXT_DAY = 7; public static final int ADJUST_SELECTION_PREVIOUS_WEEK = 8; public static final int ADJUST_SELECTION_NEXT_WEEK = 9; private int action; public KeyboardAction(int action) { this.action = action; } public void actionPerformed(ActionEvent ev) { if (!canSelectByMode()) return; if (!isUsingKeyboard()) { originalDateSpan = getSelection(); } // JW: removed the isUsingKeyboard from the condition // need to fire always. if (action >= ACCEPT_SELECTION && action <= CANCEL_SELECTION) { // refactor the logic ... if (action == CANCEL_SELECTION) { // Restore the original selection. if ((originalDateSpan != null) && !originalDateSpan.isEmpty()) { monthView.setSelectionInterval( originalDateSpan.first(), originalDateSpan .last()); } else { monthView.clearSelection(); } monthView.cancelSelection(); } else { // Accept the keyboard selection. monthView.commitSelection(); } setUsingKeyboard(false); } else if (action >= SELECT_PREVIOUS_DAY && action <= SELECT_DAY_NEXT_WEEK) { setUsingKeyboard(true); monthView.getSelectionModel().setAdjusting(true); pivotDate = null; traverse(action); } else if (monthView.getSelectionMode() == SelectionMode.SINGLE_INTERVAL_SELECTION && action >= ADJUST_SELECTION_PREVIOUS_DAY && action <= ADJUST_SELECTION_NEXT_WEEK) { setUsingKeyboard(true); monthView.getSelectionModel().setAdjusting(true); addToSelection(action); } } private void traverse(int action) { Date oldStart = monthView.isSelectionEmpty() ? monthView.getToday() : monthView.getFirstSelectionDate(); Calendar cal = getCalendar(oldStart); switch (action) { case SELECT_PREVIOUS_DAY: cal.add(Calendar.DAY_OF_MONTH, -1); break; case SELECT_NEXT_DAY: cal.add(Calendar.DAY_OF_MONTH, 1); break; case SELECT_DAY_PREVIOUS_WEEK: cal.add(Calendar.DAY_OF_MONTH, -JXMonthView.DAYS_IN_WEEK); break; case SELECT_DAY_NEXT_WEEK: cal.add(Calendar.DAY_OF_MONTH, JXMonthView.DAYS_IN_WEEK); break; } Date newStartDate = cal.getTime(); if (!newStartDate.equals(oldStart)) { monthView.setSelectionInterval(newStartDate, newStartDate); monthView.ensureDateVisible(newStartDate); } } /** * If we are in a mode that allows for range selection this method * will extend the currently selected range. * * NOTE: This may not be the expected behavior for the keyboard controls * and we ay need to update this code to act in a way that people expect. * * @param action action for adjusting selection */ private void addToSelection(int action) { // PENDING JW: remove use of deprecated // use Date always! Date newStartDate; Date newEndDate; Date selectionStart; Date selectionEnd; if (!monthView.isSelectionEmpty()) { newStartDate = selectionStart = monthView.getFirstSelectionDate(); newEndDate = selectionEnd = monthView.getLastSelectionDate(); } else { newStartDate = selectionStart = monthView.getToday(); newEndDate = selectionEnd = newStartDate; } if (pivotDate == null) { pivotDate = newStartDate; } boolean isForward = true; // want a copy to play with - each branch sets and reads the time // actually don't care about the pre-set time. Calendar cal = getCalendar(); switch (action) { case ADJUST_SELECTION_PREVIOUS_DAY: if (!newEndDate.after(pivotDate)) { cal.setTime(newStartDate); cal.add(Calendar.DAY_OF_MONTH, -1); newStartDate = cal.getTime(); } else { cal.setTime(newEndDate); cal.add(Calendar.DAY_OF_MONTH, -1); newEndDate = cal.getTime(); } isForward = false; break; case ADJUST_SELECTION_NEXT_DAY: if (!newStartDate.before(pivotDate)) { cal.setTime(newEndDate); cal.add(Calendar.DAY_OF_MONTH, 1); newStartDate = pivotDate; newEndDate = cal.getTime(); } else { cal.setTime(newStartDate); cal.add(Calendar.DAY_OF_MONTH, 1); newStartDate = cal.getTime(); } break; case ADJUST_SELECTION_PREVIOUS_WEEK: if (!newEndDate.after(pivotDate)) { cal.setTime(newStartDate); cal.add(Calendar.DAY_OF_MONTH, -JXMonthView.DAYS_IN_WEEK); newStartDate = cal.getTime(); } else { cal.setTime(newEndDate); cal.add(Calendar.DAY_OF_MONTH, -JXMonthView.DAYS_IN_WEEK); Date newTime = cal.getTime(); if (!newTime.after(pivotDate)) { newStartDate = newTime; newEndDate = pivotDate; } else { newEndDate = cal.getTime(); } } isForward = false; break; case ADJUST_SELECTION_NEXT_WEEK: if (!newStartDate.before(pivotDate)) { cal.setTime(newEndDate); cal.add(Calendar.DAY_OF_MONTH, JXMonthView.DAYS_IN_WEEK); newEndDate = cal.getTime(); } else { cal.setTime(newStartDate); cal.add(Calendar.DAY_OF_MONTH, JXMonthView.DAYS_IN_WEEK); Date newTime = cal.getTime(); if (!newTime.before(pivotDate)) { newStartDate = pivotDate; newEndDate = newTime; } else { newStartDate = cal.getTime(); } } break; } if (!newStartDate.equals(selectionStart) || !newEndDate.equals(selectionEnd)) { monthView.setSelectionInterval(newStartDate, newEndDate); monthView.ensureDateVisible(isForward ? newEndDate : newStartDate); } } } // -- deprecated methods, no longer used internally, kept a short while /** * Get the view index for the specified day of the week. This value will range * from 0 to DAYS_IN_WEEK - 1. For example if the first day of the week was set * to Calendar.MONDAY and we requested the view index for Calendar.TUESDAY the result * would be 1. * * @param dayOfWeek day of the week to calculate view index for, acceptable values are * <code>Calendar.MONDAY</code> - <code>Calendar.SUNDAY</code> * @return view index for the specified day of the week * @deprecated with revised location/date mapping no longer needed, * no longer used internally */ @Deprecated @SuppressWarnings("unused") private int getDayOfWeekViewIndex(int dayOfWeek) { int result = dayOfWeek - monthView.getFirstDayOfWeek(); if (result < 0) { result += JXMonthView.DAYS_IN_WEEK; } return result; } /** * Returns an index defining which, if any, of the buttons for * traversing the month was pressed. This method should only be * called when <code>setTraversable</code> is set to true. * * @param x x position of the pointer * @param y y position of the pointer * @return MONTH_UP, MONTH_DOWN or -1 when no button is selected. * * @deprecated use {@link #getTraversableGridPositionAtLocation(int, int)} */ @Deprecated protected int getTraversableButtonAt(int x, int y) { return getTraversableGridPositionAtLocation(x, y); } /** * Get the row and column for the calendar at the specified coordinates * * @param x x location * @param y y location * @return a new <code>Point</code> object containing the row as the x value * and column as the y value * @deprecated use {@link #getMonthGridPositionAtLocation(int, int)} - this method is * no longer used internally. Note that the coordinate mapping in the * returned Point of new method is the other way round * (p.x == column, p.y == row) as in this! */ @Deprecated protected Point getCalRowColAt(int x, int y) { if (isLeftToRight ? (startX > x) : (startX < x) || startY > y) { return NO_SUCH_CALENDAR; } Point result = new Point(); // Determine which row of calendars we're in. result.x = (y - startY) / (calendarHeight + CALENDAR_SPACING); // Determine which column of calendars we're in. result.y = (isLeftToRight ? (x - startX) : (startX - x)) / (calendarWidth + CALENDAR_SPACING); // Make sure the row and column of calendars calculated is being // managed. if (result.x > calendarRowCount - 1 || result.y > calendarColumnCount -1) { result = NO_SUCH_CALENDAR; } return result; } /** * old way of calculating the position of the grid of months. * This is no longer used in current code, only in deprecated. * * @deprecated the result is no longer used except from deprecated methods. */ @Deprecated private void calculateStartPositionUnused() { // Calculate offset in x-axis for centering calendars. int width = monthView.getWidth(); startX = (width - calculateCalendarGridWidth()) / 2; if (!isLeftToRight) { startX = width - startX; } // Calculate offset in y-axis for centering calendars. startY = calculateCalendarGridY(); } /** * {@inheritDoc} * * @deprecated use {@link #getDayAtLocation(int, int)} This method is * no longer used internally */ @Deprecated @Override public long getDayAt(int x, int y) { Date cal = getDayAtLocation(x, y); return cal != null ? cal.getTime() : -1; } /** * @return the start of today. * * @deprecated use {@link #getToday()} */ @Deprecated protected long getTodayInMillis() { return getToday().getTime(); } /** * Returns true if the date passed in is the same as today. * * PENDING JW: really want the exact test? * * @param date long representing the date you want to compare to today. * @return true if the date passed is the same as today. * * @deprecated use {@link #isToday(Date)} */ @Deprecated protected boolean isToday(long date) { return date == getToday().getTime(); } /** * {@inheritDoc} */ @Override public long getLastDisplayedDate() { return lastDisplayedDate.getTime(); } /** * {@inheritDoc} <p> * * This method will be hidden soon: the newer perspective is that the * ui is responsible to keep the value in a reasonable state to query from * the outside. */ @Override public long calculateLastDisplayedDate() { updateLastDisplayedDay(getFirstDisplayedDay()); // NOTE JW: this is the only place (outside the getter/setter) // where the field is accessed directly - no need to cleanup because // this will be removed before final. return lastDisplayedDate.getTime(); } /** * Sets the firstDisplayedDate property to the given value. Must update * dependent state as well. * * Here: updated lastDisplayedDatefirstDisplayedMonth/Year accordingly. * * * @param firstDisplayedDate the firstDisplayedDate to set * * @deprecated use {@link #setFirstDisplayedDay(Date)} */ @Deprecated protected void setFirstDisplayedDate(long firstDisplayedDate) { setFirstDisplayedDay(new Date(firstDisplayedDate)); } /** * @return the firstDisplayedDate * * @deprecated use {@link #getFirstDisplayedDay()} */ @Deprecated protected long getFirstDisplayedDate() { return firstDisplayedDate.getTime(); } /** * Returns the monthViews calendar configured to the given time. * * NOTE: it's safe to change the calendar state without resetting because * it's JXMonthView's responsibility to protect itself. * * @param millis the date to configure the calendar with * @return the monthView's calendar, configured with the given date. * @deprecated use {@link #getCalendar(Date)} */ @Deprecated protected Calendar getCalendar(long millis) { Calendar calendar = monthView.getCalendar(); calendar.setTimeInMillis(millis); return calendar; } }
package net.nemerosa.ontrack.repository; import net.nemerosa.ontrack.common.Document; import net.nemerosa.ontrack.model.Ack; import net.nemerosa.ontrack.model.exceptions.*; import net.nemerosa.ontrack.model.structure.*; import net.nemerosa.ontrack.repository.support.AbstractJdbcRepository; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; @Repository public class StructureJdbcRepository extends AbstractJdbcRepository implements StructureRepository { private final BranchTemplateRepository branchTemplateRepository; @Autowired public StructureJdbcRepository(DataSource dataSource, BranchTemplateRepository branchTemplateRepository) { super(dataSource); this.branchTemplateRepository = branchTemplateRepository; } @Override public Project newProject(Project project) { // Creation try { int id = dbCreate( "INSERT INTO PROJECTS(NAME, DESCRIPTION, DISABLED, CREATION, CREATOR) VALUES (:name, :description, :disabled, :creation, :creator)", params("name", project.getName()) .addValue("description", project.getDescription()) .addValue("disabled", project.isDisabled()) .addValue("creation", dateTimeForDB(project.getSignature().getTime())) .addValue("creator", project.getSignature().getUser().getName()) ); // Returns with ID return project.withId(id(id)); } catch (DuplicateKeyException ex) { throw new ProjectNameAlreadyDefinedException(project.getName()); } } @Override public List<Project> getProjectList() { return getJdbcTemplate().query( "SELECT * FROM PROJECTS ORDER BY NAME", (rs, rowNum) -> toProject(rs) ); } @Override public Project getProject(ID projectId) { try { return getNamedParameterJdbcTemplate().queryForObject( "SELECT * FROM PROJECTS WHERE ID = :id", params("id", projectId.getValue()), (rs, rowNum) -> toProject(rs) ); } catch (EmptyResultDataAccessException ex) { throw new ProjectNotFoundException(projectId); } } @Override public Optional<Project> getProjectByName(String project) { return Optional.ofNullable( getFirstItem( "SELECT * FROM PROJECTS WHERE NAME = :name", params("name", project), (rs, rowNum) -> toProject(rs) ) ); } @Override public void saveProject(Project project) { getNamedParameterJdbcTemplate().update( "UPDATE PROJECTS SET NAME = :name, DESCRIPTION = :description, DISABLED = :disabled WHERE ID = :id", params("name", project.getName()) .addValue("description", project.getDescription()) .addValue("disabled", project.isDisabled()) .addValue("id", project.getId().getValue()) ); } @Override public Ack deleteProject(ID projectId) { return Ack.one( getNamedParameterJdbcTemplate().update( "DELETE FROM PROJECTS WHERE ID = :id", params("id", projectId.getValue()) ) ); } @Override public Branch getBranch(ID branchId) { try { return getNamedParameterJdbcTemplate().queryForObject( "SELECT * FROM BRANCHES WHERE ID = :id", params("id", branchId.getValue()), (rs, rowNum) -> toBranch(rs, this::getProject) ); } catch (EmptyResultDataAccessException ex) { throw new BranchNotFoundException(branchId); } } @Override public Optional<Branch> getBranchByName(String project, String branch) { return getProjectByName(project) .map(p -> getFirstItem( "SELECT * FROM BRANCHES WHERE PROJECTID = :project AND NAME = :name", params("name", branch).addValue("project", p.id()), (rs, rowNum) -> toBranch(rs, id -> p) )); } @Override public List<Branch> getBranchesForProject(ID projectId) { Project project = getProject(projectId); return getNamedParameterJdbcTemplate().query( "SELECT * FROM BRANCHES WHERE PROJECTID = :projectId ORDER BY ID DESC", params("projectId", projectId.getValue()), (rs, rowNum) -> toBranch(rs, id -> project) ); } @Override public Branch newBranch(Branch branch) { // Creation try { int id = dbCreate( "INSERT INTO BRANCHES(PROJECTID, NAME, DESCRIPTION, DISABLED, CREATION, CREATOR) VALUES (:projectId, :name, :description, :disabled, :creation, :creator)", params("name", branch.getName()) .addValue("description", branch.getDescription()) .addValue("disabled", branch.isDisabled()) .addValue("projectId", branch.getProject().id()) .addValue("creation", dateTimeForDB(branch.getSignature().getTime())) .addValue("creator", branch.getSignature().getUser().getName()) ); // Returns with ID return branch.withId(id(id)); } catch (DuplicateKeyException ex) { throw new BranchNameAlreadyDefinedException(branch.getName()); } } @Override public void saveBranch(Branch branch) { // Update try { getNamedParameterJdbcTemplate().update( "UPDATE BRANCHES SET NAME = :name, DESCRIPTION = :description, DISABLED = :disabled WHERE ID = :id", params("name", branch.getName()) .addValue("description", branch.getDescription()) .addValue("disabled", branch.isDisabled()) .addValue("id", branch.id()) ); } catch (DuplicateKeyException ex) { throw new BranchNameAlreadyDefinedException(branch.getName()); } } @Override public Ack deleteBranch(ID branchId) { return Ack.one( getNamedParameterJdbcTemplate().update( "DELETE FROM BRANCHES WHERE ID = :id", params("id", branchId.getValue()) ) ); } @Override public void builds(Branch branch, Predicate<Build> buildPredicate, BuildSortDirection sortDirection) { String order = sortDirection == BuildSortDirection.FROM_NEWEST ? "DESC" : "ASC"; getNamedParameterJdbcTemplate().execute( "SELECT * FROM BUILDS WHERE BRANCHID = :branchId ORDER BY ID " + order, params("branchId", branch.id()), ps -> { ResultSet rs = ps.executeQuery(); boolean goingOn = true; while (rs.next() && goingOn) { // Gets the builds Build build = toBuild( rs, id -> branch ); // Dealing with this build goingOn = buildPredicate.test(build); } return null; } ); } @Override public void builds(Project project, Predicate<Build> buildPredicate) { getNamedParameterJdbcTemplate().execute( "SELECT B.* FROM BUILDS B INNER JOIN BRANCHES R ON R.ID = B.BRANCHID AND R.PROJECTID = :projectId ORDER BY B.ID DESC", params("projectId", project.id()), ps -> { ResultSet rs = ps.executeQuery(); boolean goingOn = true; while (rs.next() && goingOn) { // Gets the builds Build build = toBuild( rs, this::getBranch ); // Dealing with this build goingOn = buildPredicate.test(build); } return null; } ); } @Override public Build getLastBuildForBranch(Branch branch) { return getFirstItem( "SELECT * FROM BUILDS WHERE BRANCHID = :branch ORDER BY ID DESC LIMIT 1", params("branch", branch.id()), (rs, num) -> toBuild(rs, (id) -> branch) ); } @Override public Ack deleteBuild(ID buildId) { return Ack.one( getNamedParameterJdbcTemplate().update( "DELETE FROM BUILDS WHERE ID = :id", params("id", buildId.getValue()) ) ); } @Override public void addBuildLink(ID fromBuildId, ID toBuildId) { deleteBuildLink(fromBuildId, toBuildId); getNamedParameterJdbcTemplate().update( "INSERT INTO BUILD_LINKS(BUILDID, TARGETBUILDID) VALUES (:fromBuildId, :toBuildId)", params("fromBuildId", fromBuildId.get()).addValue("toBuildId", toBuildId.get()) ); } @Override public void deleteBuildLink(ID fromBuildId, ID toBuildId) { getNamedParameterJdbcTemplate().update( "DELETE FROM BUILD_LINKS WHERE BUILDID = :fromBuildId AND TARGETBUILDID = :toBuildId", params("fromBuildId", fromBuildId.get()).addValue("toBuildId", toBuildId.get()) ); } @Override public List<Build> getBuildLinksFrom(ID buildId) { return getNamedParameterJdbcTemplate().query( "SELECT T.* FROM BUILDS T " + "INNER JOIN BUILD_LINKS BL ON BL.TARGETBUILDID = T.ID " + "WHERE BL.BUILDID = :buildId", params("buildId", buildId.get()), (rs, num) -> toBuild(rs, this::getBranch) ); } @Override public List<Build> getBuildsUsing(Build build) { return getNamedParameterJdbcTemplate().query( "SELECT F.* FROM BUILDS F " + "INNER JOIN BUILD_LINKS BL ON BL.BUILDID = F.ID " + "WHERE BL.TARGETBUILDID = :buildId " + "ORDER BY F.ID DESC ", params("buildId", build.id()), (rs, num) -> toBuild(rs, this::getBranch) ); } @Override public List<Build> getBuildLinksTo(ID buildId) { return getNamedParameterJdbcTemplate().query( "SELECT F.* FROM BUILDS F " + "INNER JOIN BUILD_LINKS BL ON BL.BUILDID = F.ID " + "WHERE BL.TARGETBUILDID = :buildId " + "ORDER BY F.ID DESC " + "LIMIT 20", params("buildId", buildId.get()), (rs, num) -> toBuild(rs, this::getBranch) ); } @Override public List<Build> searchBuildsLinkedTo(String projectName, String buildPattern) { return getNamedParameterJdbcTemplate().query( "SELECT F.* FROM BUILDS F " + "INNER JOIN BUILD_LINKS BL ON BL.BUILDID = F.ID " + "INNER JOIN BUILDS T ON BL.TARGETBUILDID = T.ID " + "INNER JOIN BRANCHES BR ON BR.ID = T.BRANCHID " + "INNER JOIN PROJECTS P ON P.ID = BR.PROJECTID " + "WHERE T.NAME LIKE :buildNamePattern AND P.NAME = :projectName " + "ORDER BY F.ID DESC " + "LIMIT 100", params("buildNamePattern", expandBuildPattern(buildPattern)).addValue("projectName", projectName), (rs, num) -> toBuild(rs, this::getBranch) ); } @Override public boolean isLinkedFrom(ID id, String project, String buildPattern) { return getOptional( "SELECT BL.BUILDID FROM BUILD_LINKS BL " + "INNER JOIN BUILDS F ON BL.BUILDID = F.ID " + "INNER JOIN BRANCHES BR ON BR.ID = F.BRANCHID " + "INNER JOIN PROJECTS P ON P.ID = BR.PROJECTID " + "WHERE BL.TARGETBUILDID = :buildId AND F.NAME LIKE :buildNamePattern AND P.NAME = :projectName " + "LIMIT 1", params("buildId", id.get()) .addValue("buildNamePattern", expandBuildPattern(buildPattern)) .addValue("projectName", project), Integer.class ).isPresent(); } private String expandBuildPattern(String buildPattern) { if (StringUtils.isBlank(buildPattern)) { return "%"; } else { return StringUtils.replace(buildPattern, "*", "%"); } } @Override public boolean isLinkedTo(ID id, String project, String buildPattern) { return getOptional( "SELECT BL.TARGETBUILDID FROM BUILD_LINKS BL " + "INNER JOIN BUILDS T ON BL.TARGETBUILDID = T.ID " + "INNER JOIN BRANCHES BR ON BR.ID = T.BRANCHID " + "INNER JOIN PROJECTS P ON P.ID = BR.PROJECTID " + "WHERE BL.BUILDID = :buildId AND T.NAME LIKE :buildNamePattern AND P.NAME = :projectName " + "LIMIT 1", params("buildId", id.get()) .addValue("buildNamePattern", expandBuildPattern(buildPattern)) .addValue("projectName", project), Integer.class ).isPresent(); } protected Build toBuild(ResultSet rs, Function<ID, Branch> branchSupplier) throws SQLException { return Build.of( branchSupplier.apply(id(rs, "branchId")), new NameDescription( rs.getString("name"), rs.getString("description") ), readSignature(rs) ).withId(id(rs)); } @Override public Build newBuild(Build build) { // Creation try { int id = dbCreate( "INSERT INTO BUILDS(BRANCHID, NAME, DESCRIPTION, CREATION, CREATOR) VALUES (:branchId, :name, :description, :creation, :creator)", params("name", build.getName()) .addValue("description", build.getDescription()) .addValue("branchId", build.getBranch().id()) .addValue("creation", dateTimeForDB(build.getSignature().getTime())) .addValue("creator", build.getSignature().getUser().getName()) ); return build.withId(id(id)); } catch (DuplicateKeyException ex) { throw new BuildNameAlreadyDefinedException(build.getName()); } } @Override public Build saveBuild(Build build) { // Update try { getNamedParameterJdbcTemplate().update( "UPDATE BUILDS SET NAME = :name, DESCRIPTION = :description, CREATION = :creation, CREATOR = :creator WHERE ID = :id", params("name", build.getName()) .addValue("description", build.getDescription()) .addValue("creation", dateTimeForDB(build.getSignature().getTime())) .addValue("creator", build.getSignature().getUser().getName()) .addValue("id", build.id()) ); return build; } catch (DuplicateKeyException ex) { throw new BuildNameAlreadyDefinedException(build.getName()); } } @Override public Build getBuild(ID buildId) { try { return getNamedParameterJdbcTemplate().queryForObject( "SELECT * FROM BUILDS WHERE ID = :id", params("id", buildId.getValue()), (rs, rowNum) -> toBuild(rs, this::getBranch) ); } catch (EmptyResultDataAccessException ex) { throw new BuildNotFoundException(buildId); } } @Override public Optional<Build> getBuildByName(String project, String branch, String build) { return getBranchByName(project, branch).map(b -> getFirstItem( "SELECT * FROM BUILDS WHERE NAME = :name AND BRANCHID = :branchId", params("name", build).addValue("branchId", b.id()), (rs, rowNum) -> toBuild(rs, this::getBranch) )); } @Override public Optional<Build> findBuildAfterUsingNumericForm(ID branchId, String buildName) { return Optional.ofNullable( getFirstItem( "SELECT * FROM (SELECT * FROM BUILDS WHERE BRANCHID = :branch AND NAME REGEXP '[0-9]+') " + "WHERE CONVERT(NAME,INT) >= CONVERT(:name,INT) ORDER BY CONVERT(NAME,INT) " + "LIMIT 1", params("branch", branchId.getValue()).addValue("name", buildName), (rs, rowNum) -> toBuild(rs, this::getBranch) ) ); } @Override public int getBuildCount(Branch branch) { return getNamedParameterJdbcTemplate().queryForObject( "SELECT COUNT(ID) FROM BUILDS WHERE BRANCHID = :branchId", params("branchId", branch.id()), Integer.class ); } @Override public Optional<Build> getPreviousBuild(Build build) { return getOptional( "SELECT * FROM BUILDS WHERE BRANCHID = :branch AND ID < :id ORDER BY ID DESC LIMIT 1", params("branch", build.getBranch().id()).addValue("id", build.id()), (rs, rowNum) -> toBuild(rs, this::getBranch) ); } @Override public Optional<Build> getNextBuild(Build build) { return getOptional( "SELECT * FROM BUILDS WHERE BRANCHID = :branch AND ID > :id ORDER BY ID ASC LIMIT 1", params("branch", build.getBranch().id()).addValue("id", build.id()), (rs, rowNum) -> toBuild(rs, this::getBranch) ); } @Override public List<PromotionLevel> getPromotionLevelListForBranch(ID branchId) { Branch branch = getBranch(branchId); return getNamedParameterJdbcTemplate().query( "SELECT * FROM PROMOTION_LEVELS WHERE BRANCHID = :branchId ORDER BY ORDERNB", params("branchId", branchId.getValue()), (rs, rowNum) -> toPromotionLevel(rs, id -> branch) ); } @Override public PromotionLevel newPromotionLevel(PromotionLevel promotionLevel) { // Creation try { // Order nb = max + 1 Integer orderNbValue = getFirstItem( "SELECT MAX(ORDERNB) FROM promotion_levels WHERE BRANCHID = :branchId", params("branchId", promotionLevel.getBranch().id()), Integer.class ); int orderNb = orderNbValue != null ? orderNbValue + 1 : 0; // Insertion int id = dbCreate( "INSERT INTO PROMOTION_LEVELS(BRANCHID, NAME, DESCRIPTION, ORDERNB, CREATION, CREATOR) VALUES (:branchId, :name, :description, :orderNb, :creation, :creator)", params("name", promotionLevel.getName()) .addValue("description", promotionLevel.getDescription()) .addValue("branchId", promotionLevel.getBranch().id()) .addValue("orderNb", orderNb) .addValue("creation", dateTimeForDB(promotionLevel.getSignature().getTime())) .addValue("creator", promotionLevel.getSignature().getUser().getName()) ); return promotionLevel.withId(id(id)); } catch (DuplicateKeyException ex) { throw new PromotionLevelNameAlreadyDefinedException(promotionLevel.getName()); } } @Override public PromotionLevel getPromotionLevel(ID promotionLevelId) { try { return getNamedParameterJdbcTemplate().queryForObject( "SELECT * FROM PROMOTION_LEVELS WHERE ID = :id", params("id", promotionLevelId.getValue()), (rs, rowNum) -> toPromotionLevel(rs, this::getBranch) ); } catch (EmptyResultDataAccessException ex) { throw new PromotionLevelNotFoundException(promotionLevelId); } } @Override public Optional<PromotionLevel> getPromotionLevelByName(String project, String branch, String promotionLevel) { return getBranchByName(project, branch) .flatMap(b -> getPromotionLevelByName(b, promotionLevel)); } @Override public Optional<PromotionLevel> getPromotionLevelByName(Branch branch, String promotionLevel) { return getOptional( "SELECT * FROM PROMOTION_LEVELS WHERE BRANCHID = :branch AND NAME = :name", params("name", promotionLevel).addValue("branch", branch.id()), (rs, rowNum) -> toPromotionLevel(rs, id -> branch) ); } @Override public Document getPromotionLevelImage(ID promotionLevelId) { return getOptional( "SELECT IMAGETYPE, IMAGEBYTES FROM PROMOTION_LEVELS WHERE ID = :id", params("id", promotionLevelId.getValue()), (rs, rowNum) -> toDocument(rs) ).orElse(Document.EMPTY); } @Override public void setPromotionLevelImage(ID promotionLevelId, Document document) { getNamedParameterJdbcTemplate().update( "UPDATE PROMOTION_LEVELS SET IMAGETYPE = :type, IMAGEBYTES = :content WHERE ID = :id", params("id", promotionLevelId.getValue()) .addValue("type", document != null ? document.getType() : null) .addValue("content", document != null ? document.getContent() : null) ); } @Override public void savePromotionLevel(PromotionLevel promotionLevel) { // Update try { getNamedParameterJdbcTemplate().update( "UPDATE PROMOTION_LEVELS SET NAME = :name, DESCRIPTION = :description WHERE ID = :id", params("name", promotionLevel.getName()) .addValue("description", promotionLevel.getDescription()) .addValue("id", promotionLevel.id()) ); } catch (DuplicateKeyException ex) { throw new PromotionLevelNameAlreadyDefinedException(promotionLevel.getName()); } } @Override public Ack deletePromotionLevel(ID promotionLevelId) { return Ack.one( getNamedParameterJdbcTemplate().update( "DELETE FROM PROMOTION_LEVELS WHERE ID = :id", params("id", promotionLevelId.getValue()) ) ); } @Override public void reorderPromotionLevels(ID branchId, Reordering reordering) { int order = 1; for (int id : reordering.getIds()) { getNamedParameterJdbcTemplate().update( "UPDATE PROMOTION_LEVELS SET ORDERNB = :order WHERE ID = :id", params("id", id).addValue("order", order++) ); } } @Override public PromotionRun newPromotionRun(PromotionRun promotionRun) { return promotionRun.withId( id( dbCreate( "INSERT INTO PROMOTION_RUNS(BUILDID, PROMOTIONLEVELID, CREATION, CREATOR, DESCRIPTION) VALUES (:buildId, :promotionLevelId, :creation, :creator, :description)", params("buildId", promotionRun.getBuild().id()) .addValue("promotionLevelId", promotionRun.getPromotionLevel().id()) .addValue("description", promotionRun.getDescription()) .addValue("creation", dateTimeForDB(promotionRun.getSignature().getTime())) .addValue("creator", promotionRun.getSignature().getUser().getName()) ) ) ); } @Override public PromotionRun getPromotionRun(ID promotionRunId) { return getNamedParameterJdbcTemplate().queryForObject( "SELECT * FROM PROMOTION_RUNS WHERE ID = :id", params("id", promotionRunId.getValue()), (rs, rowNum) -> toPromotionRun( rs, this::getBuild, this::getPromotionLevel ) ); } @Override public Ack deletePromotionRun(ID promotionRunId) { return Ack.one( getNamedParameterJdbcTemplate().update( "DELETE FROM PROMOTION_RUNS WHERE ID = :promotionRunId", params("promotionRunId", promotionRunId.getValue()) ) ); } @Override public List<PromotionRun> getPromotionRunsForBuild(Build build) { return getNamedParameterJdbcTemplate().query( "SELECT * FROM PROMOTION_RUNS WHERE BUILDID = :buildId ORDER BY CREATION DESC", params("buildId", build.id()), (rs, rowNum) -> toPromotionRun(rs, (id) -> build, this::getPromotionLevel ) ); } @Override public List<PromotionRun> getLastPromotionRunsForBuild(Build build) { // Branch Branch branch = build.getBranch(); // Promotion levels for the branch List<PromotionLevel> promotionLevels = getPromotionLevelListForBranch(branch.getId()); // Gets the last promotion run for each promotion level return promotionLevels.stream() .map(promotionLevel -> getLastPromotionRun(build, promotionLevel)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } @Override public PromotionRun getLastPromotionRunForPromotionLevel(PromotionLevel promotionLevel) { return getFirstItem( "SELECT PR.* FROM PROMOTION_RUNS PR" + " INNER JOIN BUILDS B ON B.ID = PR.BUILDID" + " WHERE PROMOTIONLEVELID = :promotionLevelId" + " ORDER BY B.ID DESC" + " LIMIT 1", params("promotionLevelId", promotionLevel.id()), (rs, rowNum) -> toPromotionRun(rs, this::getBuild, (promotionLevelId) -> promotionLevel) ); } @Override public Optional<PromotionRun> getLastPromotionRun(Build build, PromotionLevel promotionLevel) { return Optional.ofNullable( getFirstItem( "SELECT * FROM PROMOTION_RUNS " + "WHERE BUILDID = :buildId " + "AND PROMOTIONLEVELID = :promotionLevelId " + "ORDER BY CREATION DESC, ID DESC LIMIT 1", params("buildId", build.id()).addValue("promotionLevelId", promotionLevel.id()), (rs, rowNum) -> toPromotionRun(rs, (id) -> build, (id) -> promotionLevel ) ) ); } @Override public List<PromotionRun> getPromotionRunsForBuildAndPromotionLevel(Build build, PromotionLevel promotionLevel) { return getNamedParameterJdbcTemplate().query( "SELECT * FROM PROMOTION_RUNS " + "WHERE BUILDID = :buildId " + "AND PROMOTIONLEVELID = :promotionLevelId " + "ORDER BY CREATION DESC, ID DESC", params("buildId", build.id()).addValue("promotionLevelId", promotionLevel.id()), (rs, rowNum) -> toPromotionRun(rs, (id) -> build, (id) -> promotionLevel ) ); } @Override public List<PromotionRun> getPromotionRunsForPromotionLevel(PromotionLevel promotionLevel) { return getNamedParameterJdbcTemplate().query( "SELECT * FROM PROMOTION_RUNS WHERE PROMOTIONLEVELID = :promotionLevelId ORDER BY CREATION DESC, ID DESC", params("promotionLevelId", promotionLevel.id()), (rs, rowNum) -> toPromotionRun(rs, this::getBuild, (id) -> promotionLevel ) ); } @Override public Optional<PromotionRun> getEarliestPromotionRunAfterBuild(PromotionLevel promotionLevel, Build build) { return getOptional( "SELECT * FROM PROMOTION_RUNS WHERE PROMOTIONLEVELID = :promotionLevelId AND BUILDID >= :buildId ORDER BY CREATION ASC, ID ASC LIMIT 1", params("promotionLevelId", promotionLevel.id()) .addValue("buildId", build.id()), (rs, num) -> toPromotionRun( rs, this::getBuild, (x) -> promotionLevel ) ); } protected PromotionRun toPromotionRun(ResultSet rs, Function<ID, Build> buildLoader, Function<ID, PromotionLevel> promotionLevelLoader) throws SQLException { return PromotionRun.of( buildLoader.apply(id(rs, "buildId")), promotionLevelLoader.apply(id(rs, "promotionLevelId")), readSignature(rs), rs.getString("description") ).withId(id(rs)); } @Override public List<ValidationStamp> getValidationStampListForBranch(ID branchId) { Branch branch = getBranch(branchId); return getNamedParameterJdbcTemplate().query( "SELECT * FROM VALIDATION_STAMPS WHERE BRANCHID = :branchId ORDER BY ORDERNB", params("branchId", branchId.getValue()), (rs, rowNum) -> toValidationStamp(rs, id -> branch) ); } @Override public ValidationStamp newValidationStamp(ValidationStamp validationStamp) { // Creation try { // Order nb = max + 1 Integer orderNbValue = getFirstItem( "SELECT MAX(ORDERNB) FROM VALIDATION_STAMPS WHERE BRANCHID = :branchId", params("branchId", validationStamp.getBranch().id()), Integer.class ); int orderNb = orderNbValue != null ? orderNbValue + 1 : 0; // Insertion int id = dbCreate( "INSERT INTO VALIDATION_STAMPS(BRANCHID, NAME, DESCRIPTION, ORDERNB, CREATION, CREATOR) VALUES (:branchId, :name, :description, :orderNb, :creation, :creator)", params("name", validationStamp.getName()) .addValue("description", validationStamp.getDescription()) .addValue("branchId", validationStamp.getBranch().id()) .addValue("orderNb", orderNb) .addValue("creation", dateTimeForDB(validationStamp.getSignature().getTime())) .addValue("creator", validationStamp.getSignature().getUser().getName()) ); return validationStamp.withId(id(id)); } catch (DuplicateKeyException ex) { throw new ValidationStampNameAlreadyDefinedException(validationStamp.getName()); } } @Override public ValidationStamp getValidationStamp(ID validationStampId) { try { return getNamedParameterJdbcTemplate().queryForObject( "SELECT * FROM VALIDATION_STAMPS WHERE ID = :id", params("id", validationStampId.getValue()), (rs, rowNum) -> toValidationStamp(rs, this::getBranch) ); } catch (EmptyResultDataAccessException ex) { throw new ValidationStampNotFoundException(validationStampId); } } @Override public Optional<ValidationStamp> getValidationStampByName(String project, String branch, String validationStamp) { return getBranchByName(project, branch) .flatMap(b -> getValidationStampByName(b, validationStamp)); } @Override public Optional<ValidationStamp> getValidationStampByName(Branch branch, String validationStamp) { return getOptional( "SELECT * FROM VALIDATION_STAMPS WHERE NAME = :name AND BRANCHID = :branch", params("name", validationStamp).addValue("branch", branch.id()), (rs, rowNum) -> toValidationStamp(rs, id -> branch) ); } @Override public Document getValidationStampImage(ID validationStampId) { return getOptional( "SELECT IMAGETYPE, IMAGEBYTES FROM VALIDATION_STAMPS WHERE ID = :id", params("id", validationStampId.getValue()), (rs, rowNum) -> toDocument(rs) ).orElse(Document.EMPTY); } @Override public void setValidationStampImage(ID validationStampId, Document document) { getNamedParameterJdbcTemplate().update( "UPDATE VALIDATION_STAMPS SET IMAGETYPE = :type, IMAGEBYTES = :content WHERE ID = :id", params("id", validationStampId.getValue()) .addValue("type", Document.isValid(document) ? document.getType() : null) .addValue("content", Document.isValid(document) ? document.getContent() : null) ); } @Override public void bulkUpdateValidationStamps(ID validationStampId) { // Description & name ValidationStamp validationStamp = getValidationStamp(validationStampId); String description = validationStamp.getDescription(); String name = validationStamp.getName(); // Image Document image = getValidationStampImage(validationStampId); // Bulk update getNamedParameterJdbcTemplate().update( "UPDATE VALIDATION_STAMPS SET IMAGETYPE = :type, IMAGEBYTES = :content, DESCRIPTION = :description " + "WHERE ID <> :id AND NAME = :name", params("id", validationStampId.getValue()) .addValue("name", name) .addValue("description", description) .addValue("type", Document.isValid(image) ? image.getType() : null) .addValue("content", Document.isValid(image) ? image.getContent() : null) ); } @Override public void saveValidationStamp(ValidationStamp validationStamp) { // Update try { getNamedParameterJdbcTemplate().update( "UPDATE VALIDATION_STAMPS SET NAME = :name, DESCRIPTION = :description WHERE ID = :id", params("name", validationStamp.getName()) .addValue("description", validationStamp.getDescription()) .addValue("id", validationStamp.id()) ); } catch (DuplicateKeyException ex) { throw new ValidationStampNameAlreadyDefinedException(validationStamp.getName()); } } @Override public Ack deleteValidationStamp(ID validationStampId) { return Ack.one( getNamedParameterJdbcTemplate().update( "DELETE FROM VALIDATION_STAMPS WHERE ID = :id", params("id", validationStampId.getValue()) ) ); } @Override public void reorderValidationStamps(ID branchId, Reordering reordering) { int order = 1; for (int id : reordering.getIds()) { getNamedParameterJdbcTemplate().update( "UPDATE VALIDATION_STAMPS SET ORDERNB = :order WHERE ID = :id", params("id", id).addValue("order", order++) ); } } @Override public ValidationRun newValidationRun(ValidationRun validationRun, Function<String, ValidationRunStatusID> validationRunStatusService) { // Validation run itself (parent) int id = dbCreate( "INSERT INTO VALIDATION_RUNS(BUILDID, VALIDATIONSTAMPID) VALUES (:buildId, :validationStampId)", params("buildId", validationRun.getBuild().id()) .addValue("validationStampId", validationRun.getValidationStamp().id()) ); // Statuses validationRun.getValidationRunStatuses() .forEach(validationRunStatus -> newValidationRunStatus(id, validationRunStatus)); // Reloads the run return getValidationRun(ID.of(id), validationRunStatusService); } @Override public ValidationRun getValidationRun(ID validationRunId, Function<String, ValidationRunStatusID> validationRunStatusService) { return getNamedParameterJdbcTemplate().queryForObject( "SELECT * FROM VALIDATION_RUNS WHERE ID = :id", params("id", validationRunId.getValue()), (rs, rowNum) -> toValidationRun( rs, this::getBuild, this::getValidationStamp, validationRunStatusService ) ); } @Override public List<ValidationRun> getValidationRunsForBuild(Build build, Function<String, ValidationRunStatusID> validationRunStatusService) { return getNamedParameterJdbcTemplate().query( "SELECT * FROM VALIDATION_RUNS WHERE BUILDID = :buildId", params("buildId", build.id()), (rs, rowNum) -> toValidationRun( rs, id -> build, this::getValidationStamp, validationRunStatusService ) ); } @Override public List<ValidationRun> getValidationRunsForBuild(Build build, int offset, int count, Function<String, ValidationRunStatusID> validationRunStatusService) { return getNamedParameterJdbcTemplate().query( "SELECT * FROM VALIDATION_RUNS WHERE BUILDID = :buildId ORDER BY ID DESC LIMIT :count OFFSET :offset", params("buildId", build.id()) .addValue("offset", offset) .addValue("count", count), (rs, rowNum) -> toValidationRun( rs, id -> build, this::getValidationStamp, validationRunStatusService ) ); } @Override public int getValidationRunsCountForBuild(Build build) { return getNamedParameterJdbcTemplate().queryForObject( "SELECT COUNT(ID) FROM VALIDATION_RUNS WHERE BUILDID = :buildId", params("buildId", build.id()), Integer.class ); } @Override public List<ValidationRun> getValidationRunsForBuildAndValidationStamp(Build build, ValidationStamp validationStamp, Function<String, ValidationRunStatusID> validationRunStatusService) { return getNamedParameterJdbcTemplate().query( "SELECT * FROM VALIDATION_RUNS WHERE BUILDID = :buildId AND VALIDATIONSTAMPID = :validationStampId ORDER BY ID DESC", params("buildId", build.id()).addValue("validationStampId", validationStamp.id()), (rs, rowNum) -> toValidationRun( rs, id -> build, id -> validationStamp, validationRunStatusService ) ); } @Override public List<ValidationRun> getValidationRunsForBuildAndValidationStamp(Build build, ValidationStamp validationStamp, int offset, int count, Function<String, ValidationRunStatusID> validationRunStatusService) { return getNamedParameterJdbcTemplate().query( "SELECT * FROM VALIDATION_RUNS WHERE BUILDID = :buildId AND VALIDATIONSTAMPID = :validationStampId ORDER BY ID DESC LIMIT :limit OFFSET :offset", params("buildId", build.id()).addValue("validationStampId", validationStamp.id()) .addValue("limit", count) .addValue("offset", offset), (rs, rowNum) -> toValidationRun( rs, id -> build, id -> validationStamp, validationRunStatusService ) ); } @Override public int getValidationRunsCountForBuildAndValidationStamp(ID buildId, ID validationStampId) { return getNamedParameterJdbcTemplate().queryForObject( "SELECT COUNT(ID) FROM VALIDATION_RUNS WHERE BUILDID = :buildId AND VALIDATIONSTAMPID = :validationStampId", params("buildId", buildId.getValue()).addValue("validationStampId", validationStampId.getValue()), Integer.class ); } @Override public List<ValidationRun> getValidationRunsForValidationStamp(ValidationStamp validationStamp, int offset, int count, Function<String, ValidationRunStatusID> validationRunStatusService) { return getNamedParameterJdbcTemplate().query( "SELECT * FROM VALIDATION_RUNS WHERE VALIDATIONSTAMPID = :validationStampId ORDER BY BUILDID DESC, ID DESC LIMIT :limit OFFSET :offset", params("validationStampId", validationStamp.id()) .addValue("limit", count) .addValue("offset", offset), (rs, rowNum) -> toValidationRun( rs, this::getBuild, id -> validationStamp, validationRunStatusService ) ); } @Override public int getValidationRunsCountForValidationStamp(ID validationStampId) { return getNamedParameterJdbcTemplate().queryForObject( "SELECT COUNT(ID) FROM VALIDATION_RUNS WHERE VALIDATIONSTAMPID = :validationStampId", params("validationStampId", validationStampId.getValue()), Integer.class ); } @Override public ValidationRun newValidationRunStatus(ValidationRun validationRun, ValidationRunStatus runStatus) { // Saves the new status newValidationRunStatus(validationRun.id(), runStatus); return validationRun.add(runStatus); } protected void newValidationRunStatus(int validationRunId, ValidationRunStatus validationRunStatus) { dbCreate( "INSERT INTO VALIDATION_RUN_STATUSES(VALIDATIONRUNID, VALIDATIONRUNSTATUSID, CREATION, CREATOR, DESCRIPTION) " + "VALUES (:validationRunId, :validationRunStatusId, :creation, :creator, :description)", params("validationRunId", validationRunId) .addValue("validationRunStatusId", validationRunStatus.getStatusID().getId()) .addValue("description", validationRunStatus.getDescription()) .addValue("creation", dateTimeForDB(validationRunStatus.getSignature().getTime())) .addValue("creator", validationRunStatus.getSignature().getUser().getName()) ); } protected ValidationRun toValidationRun(ResultSet rs, Function<ID, Build> buildSupplier, Function<ID, ValidationStamp> validationStampSupplier, Function<String, ValidationRunStatusID> validationRunStatusService) throws SQLException { int id = rs.getInt("id"); // Statuses List<ValidationRunStatus> statuses = getNamedParameterJdbcTemplate().query( "SELECT * FROM VALIDATION_RUN_STATUSES WHERE VALIDATIONRUNID = :validationRunId ORDER BY CREATION DESC", params("validationRunId", id), (rs1, rowNum) -> ValidationRunStatus.of( readSignature(rs1), validationRunStatusService.apply(rs1.getString("validationRunStatusId")), rs1.getString("description") ) ); // Build & validation stamp ID buildId = id(rs, "buildId"); ID validationStampId = id(rs, "validationStampId"); // Run order int runOrder = getNamedParameterJdbcTemplate().queryForObject( "SELECT COUNT(*) FROM VALIDATION_RUNS WHERE BUILDID=:buildId AND VALIDATIONSTAMPID=:validationStampId AND ID <= :id", params("id", id).addValue("buildId", buildId.getValue()).addValue("validationStampId", validationStampId.getValue()), Integer.class ); // Run itself return ValidationRun.of( buildSupplier.apply(buildId), validationStampSupplier.apply(validationStampId), runOrder, statuses ).withId(ID.of(id)); } protected PromotionLevel toPromotionLevel(ResultSet rs, Function<ID, Branch> branchSupplier) throws SQLException { return PromotionLevel.of( branchSupplier.apply(id(rs, "branchId")), new NameDescription( rs.getString("name"), rs.getString("description") ) ).withId(id(rs)) .withSignature(readSignature(rs)) .withImage(StringUtils.isNotBlank(rs.getString("imagetype"))); } protected ValidationStamp toValidationStamp(ResultSet rs, Function<ID, Branch> branchSupplier) throws SQLException { return ValidationStamp.of( branchSupplier.apply(id(rs, "branchId")), new NameDescription( rs.getString("name"), rs.getString("description") ) ).withId(id(rs)) .withSignature(readSignature(rs)) .withImage(StringUtils.isNotBlank(rs.getString("imagetype"))); } protected Branch toBranch(ResultSet rs, Function<ID, Project> projectSupplier) throws SQLException { ID projectId = id(rs, "projectId"); ID branchId = id(rs); return Branch.of( projectSupplier.apply(projectId), new NameDescription( rs.getString("name"), rs.getString("description") ) ) .withId(branchId) .withSignature(readSignature(rs)) .withType(getBranchType(branchId)) .withDisabled(rs.getBoolean("disabled")); } private BranchType getBranchType(ID branchId) { if (branchTemplateRepository.isTemplateDefinition(branchId)) { return BranchType.TEMPLATE_DEFINITION; } else if (branchTemplateRepository.isTemplateInstance(branchId)) { return BranchType.TEMPLATE_INSTANCE; } else { return BranchType.CLASSIC; } } protected Project toProject(ResultSet rs) throws SQLException { return Project.of(new NameDescription( rs.getString("name"), rs.getString("description") )) .withId(id(rs.getInt("id"))) .withSignature(readSignature(rs)) .withDisabled(rs.getBoolean("disabled")); } }
package edu.mit.streamjit.impl.common; import com.google.common.base.Function; import static com.google.common.base.Preconditions.*; import com.google.common.base.Strings; import com.google.common.collect.BoundType; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Maps; import com.google.common.collect.Range; import com.jeffreybosboom.serviceproviderprocessor.ServiceProvider; import edu.mit.streamjit.api.Identity; import edu.mit.streamjit.api.Pipeline; import edu.mit.streamjit.api.Worker; import edu.mit.streamjit.impl.blob.BlobFactory; import edu.mit.streamjit.impl.common.Configuration.PartitionParameter.BlobSpecifier; import edu.mit.streamjit.impl.interp.Interpreter; import edu.mit.streamjit.util.ReflectionUtils; import edu.mit.streamjit.util.json.Jsonifier; import edu.mit.streamjit.util.json.JsonifierFactory; import edu.mit.streamjit.util.json.Jsonifiers; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableSet; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.TreeSet; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonValue; /** * A Configuration contains parameters that can be manipulated by the autotuner * (or other things). * * Instances of this class are immutable. This class uses the builder pattern; * to create a Configuration, get a builder by calling Configuration.builder(), * add parameters or subconfigurations to it, then call the builder's build() * method to build the configuration. * * Unless otherwise specified, passing null or an empty string to this class' * or any parameter class' methods will result in a NullPointerException being * thrown. * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 3/23/2013 */ public final class Configuration { private final ImmutableMap<String, Parameter> parameters; private final ImmutableMap<String, Configuration> subconfigurations; private final ImmutableMap<String, Object> extraData; private Configuration(ImmutableMap<String, Parameter> parameters, ImmutableMap<String, Configuration> subconfigurations, ImmutableMap<String, Object> extraData) { //We're only called by the builder, so assert, not throw IAE. assert parameters != null; assert subconfigurations != null; this.parameters = parameters; this.subconfigurations = subconfigurations; this.extraData = extraData; } /** * Builds Configuration instances. Parameters and subconfigurations can be * added or removed from this builder; calling build() creates a * Configuration from the current builder state. Note that build() may be * called more than once; combined with clone(), this allows creating * "prototype" builders that can be cloned, customized, and built. */ public static final class Builder implements Cloneable { private final Map<String, Parameter> parameters; private final Map<String, Configuration> subconfigurations; private final Map<String, Object> extraData; /** * Constructs a new Builder. Called only by Configuration.build(). */ private Builder() { //Type inference fail. //These maps have their contents copied in the other constructor, so //just use these singleton empty maps. this(ImmutableMap.<String, Parameter>of(), ImmutableMap.<String, Configuration>of(), ImmutableMap.<String, Object>of()); } /** * Constructs a new Builder with the given parameters and * subconfigurations. Called only by Builder.clone() and * Configuration.builder(Configuration). * @param parameters the parameters * @param subconfigurations the subconfigurations */ private Builder(Map<String, Parameter> parameters, Map<String, Configuration> subconfigurations, Map<String, Object> extraData) { //Only called by our own code, so assert. assert parameters != null; assert subconfigurations != null; this.parameters = new HashMap<>(parameters); this.subconfigurations = new HashMap<>(subconfigurations); this.extraData = new HashMap<>(extraData); } public Builder addParameter(Parameter parameter) { checkNotNull(parameter); //The parameter constructor should enforce this, so assert. assert !Strings.isNullOrEmpty(parameter.getName()) : parameter; checkArgument(!parameters.containsKey(parameter.getName()), "conflicting names %s %s", parameters.get(parameter.getName()), parameters); parameters.put(parameter.getName(), parameter); return this; } /** * Removes and returns the parameter with the given name from this * builder, or returns null if this builder doesn't contain a parameter * with that name. * @param name the name of the parameter to remove * @return the removed parameter, or null */ public Parameter removeParameter(String name) { return parameters.remove(checkNotNull(Strings.emptyToNull(name))); } public Builder addSubconfiguration(String name, Configuration subconfiguration) { checkNotNull(Strings.emptyToNull(name)); checkNotNull(subconfiguration); checkArgument(!subconfigurations.containsKey(name), "name %s already in use", name); subconfigurations.put(name, subconfiguration); return this; } /** * Removes and returns the subconfiguration with the given name from * this builder, or returns null if this builder doesn't contain a * subconfiguration with that name. * @param name the name of the subconfiguration to remove * @return the removed subconfiguration, or null */ public Configuration removeSubconfiguration(String name) { return subconfigurations.remove(checkNotNull(Strings.emptyToNull(name))); } /** * Adds extra data to this builder, replacing any data with the same * name. * @param name the name of the extra data to put (cannot be null) * @param data the extra data (cannot be null) * @return this * @throws NullPointerException if name is null or the empty string, or * if data is null */ public Builder putExtraData(String name, Object data) { checkNotNull(Strings.emptyToNull(name)); checkNotNull(data); extraData.put(name, data); return this; } /** * Builds a new Configuration from the parameters and subconfigurations * added to this builder. This builder is still valid and may be used * to build more configurations (perhaps after adding or removing * elements), but the returned configurations remain immutable. * @return a new Configuration containing the parameters and * subconfigurations added to this builder */ public Configuration build() { return new Configuration(ImmutableMap.copyOf(parameters), ImmutableMap.copyOf(subconfigurations), ImmutableMap.copyOf(extraData)); } /** * Returns a copy of this builder. Subsequent changes to this builder * have no effect on the copy, and vice versa. This method is useful * for creating "prototype" builders that can be cloned, customized, * and built. * @return a copy of this builder */ @Override public Builder clone() { //We're final, so we don't need to use super.clone(). return new Builder(parameters, subconfigurations, extraData); } } /** * Creates a new, empty builder. * @return a new, empty builder */ public static Builder builder() { return new Builder(); } /** * Creates a new Builder with the same parameters, subconfigurations and * extra data as the given configuration. * @param config the Configuration to create a builder from * @return a new Builder with the configuration's contents */ public static Builder builder(Configuration config) { return new Builder(config.getParametersMap(), config.getSubconfigurationsMap(), config.getExtraDataMap()); } public static Configuration fromJson(String json) { return Jsonifiers.fromJson(json, Configuration.class); } public String toJson() { return Jsonifiers.toJson(this).toString(); } /** * JSON-ifies Configurations. Note that Configuration handles its maps * specially to simplify parsing on the Python side. * * This class is protected with a public constructor to allow ServiceLoader * to instantiate it. */ @ServiceProvider(JsonifierFactory.class) protected static final class ConfigurationJsonifier implements Jsonifier<Configuration>, JsonifierFactory { public ConfigurationJsonifier() {} @Override public Configuration fromJson(JsonValue value) { JsonObject configObj = Jsonifiers.checkClassEqual(value, Configuration.class); JsonObject parametersObj = checkNotNull(configObj.getJsonObject("params")); JsonObject subconfigurationsObj = checkNotNull(configObj.getJsonObject("subconfigs")); JsonObject extraDataObj = checkNotNull(configObj.getJsonObject("extraData")); Builder builder = builder(); for (Map.Entry<String, JsonValue> param : parametersObj.entrySet()) builder.addParameter(Jsonifiers.fromJson(param.getValue(), Parameter.class)); for (Map.Entry<String, JsonValue> subconfiguration : subconfigurationsObj.entrySet()) builder.addSubconfiguration(subconfiguration.getKey(), Jsonifiers.fromJson(subconfiguration.getValue(), Configuration.class)); for (Map.Entry<String, JsonValue> data : extraDataObj.entrySet()) { JsonArray arr = (JsonArray)data.getValue(); Class<?> c = Jsonifiers.fromJson(arr.get(0), Class.class); builder.putExtraData(data.getKey(), Jsonifiers.fromJson(arr.get(1), c)); } return builder.build(); } @Override public JsonValue toJson(Configuration t) { JsonObjectBuilder paramsBuilder = Json.createObjectBuilder(); for (Map.Entry<String, Parameter> param : t.parameters.entrySet()) paramsBuilder.add(param.getKey(), Jsonifiers.toJson(param.getValue())); JsonObjectBuilder subconfigsBuilder = Json.createObjectBuilder(); for (Map.Entry<String, Configuration> subconfig : t.subconfigurations.entrySet()) subconfigsBuilder.add(subconfig.getKey(), Jsonifiers.toJson(subconfig.getValue())); JsonObjectBuilder extraDataBuilder = Json.createObjectBuilder(); for (Map.Entry<String, Object> data : t.extraData.entrySet()) { JsonArrayBuilder da = Json.createArrayBuilder(); da.add(Jsonifiers.toJson(data.getValue().getClass())); da.add(Jsonifiers.toJson(data.getValue())); extraDataBuilder.add(data.getKey(), da); } return Json.createObjectBuilder() .add("class", Jsonifiers.toJson(Configuration.class)) .add("params", paramsBuilder) .add("subconfigs", subconfigsBuilder) .add("extraData", extraDataBuilder) //Python-side support .add("__module__", "configuration") .add("__class__", Configuration.class.getSimpleName()) .build(); } @Override @SuppressWarnings("unchecked") public <T> Jsonifier<T> getJsonifier(Class<T> klass) { return (Jsonifier<T>)(klass.equals(Configuration.class) ? this : null); } } /** * Returns an immutable mapping of parameter names to the parameters in this * configuration. * @return an immutable mapping of the parameters in this configuration */ public ImmutableMap<String, Parameter> getParametersMap() { return parameters; } /** * Gets the parameter with the given name, or null if this configuration * doesn't contain a parameter with that name. * @param name the name of the parameter * @return the parameter, or null */ public Parameter getParameter(String name) { return parameters.get(checkNotNull(Strings.emptyToNull(name))); } /** * Gets the parameter with the given name cast to the given parameter type, * or null if this configuration doesn't contain a parameter with that name. * If this configuration does have a parameter with that name but of a * different type, a ClassCastException will be thrown. * @param <T> the type of the parameter to get * @param name the name of the parameter * @param parameterType the type of the parameter * @return the parameter, or null * @throws ClassCastException if the parameter with the given name exists * but is of a different type */ public <T extends Parameter> T getParameter(String name, Class<T> parameterType) { return checkNotNull(parameterType).cast(getParameter(name)); } /** * Gets the generic parameter with the given name cast to the given * parameter type (including checking the type parameter type), or null if * this configuration doesn't contain a parameter with that name. If this * configuration does have a parameter with that name but of a different * type or with a different type parameter type, */ public <U, T extends GenericParameter<?>, V extends GenericParameter<U>> V getParameter(String name, Class<T> parameterType, Class<U> typeParameterType) { T parameter = getParameter(name, parameterType); if (parameter == null) return null; //This must be an exact match. if (parameter.getGenericParameter() != typeParameterType) throw new ClassCastException("Type parameter type mismatch: "+parameter.getGenericParameter() +" != "+typeParameterType); //Due to the checks above, this is safe. @SuppressWarnings("unchecked") V retval = (V)parameter; return retval; } /** * Returns an immutable mapping of subconfiguration names to the * subconfigurations of this configuration. * @return an immutable mapping of the subconfigurations of this * configuration */ public ImmutableMap<String, Configuration> getSubconfigurationsMap() { return subconfigurations; } /** * Gets the subconfiguration with the given name, or null if this * configuration doesn't contain a subconfiguration with that name. * @param name the name of the subconfiguration * @return the subconfiguration, or null */ public Configuration getSubconfiguration(String name) { return subconfigurations.get(checkNotNull(Strings.emptyToNull(name))); } /** * Returns an immutable mapping of extra data names to the extra data of * this configuration. * @return an immutable mapping of the extra data of this configuration */ public ImmutableMap<String, Object> getExtraDataMap() { return extraData; } /** * Gets the extra data with the given name, or null if this configuration * doesn't contain extra data with that name * @param name the name of the extra data * @return the extra data, or null */ public Object getExtraData(String name) { return extraData.get(checkNotNull(Strings.emptyToNull(name))); } /** * A Parameter is a configuration object with a name. All implementations * of this interface are immutable. * * Users of Configuration shouldn't implement this interface themselves; * instead, use one of the provided implementations in Configuration. */ public interface Parameter extends java.io.Serializable { public String getName(); } /** * A GenericParameter is a Parameter with a type parameter. (The name * GenericParameter was chosen in preference to ParameterizedParameter.) * * This interface isn't particularly interesting in and of itself; it mostly * exists to make the Configuration.getParameter(String, Class<T>, Class<U>) * overload have the proper (and checked) return type. * @param <T> */ public interface GenericParameter<T> extends Parameter { public Class<?> getGenericParameter(); } /** * An IntParameter has an integer value that lies within some closed range. * The lower and upper bounds are <b>inclusive</b>. */ public static final class IntParameter implements Parameter { private static final long serialVersionUID = 1L; private final String name; /** * The Range of this IntParameter. Note that this range is closed on * both ends. */ private final Range<Integer> range; /** * The value of this IntParameter, which must be contained in the range. */ private final int value; /** * Constructs a new IntParameter. * @param name the parameter's name * @param min the minimum of the range (inclusive) * @param max the maximum of the range (inclusive) * @param value the parameter's value */ public IntParameter(String name, int min, int max, int value) { this(name, Range.closed(min, max), value); } /** * Constructs a new IntParameter. * @param name the parameter's name * @param range the parameter's range, which must be nonempty and closed * at both ends * @param value the parameter's value */ public IntParameter(String name, Range<Integer> range, int value) { this.name = checkNotNull(Strings.emptyToNull(name)); checkNotNull(range); checkArgument(range.hasLowerBound() && range.lowerBoundType() == BoundType.CLOSED && range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED && !range.isEmpty()); this.range = range; checkArgument(range.contains(value), "value %s out of range %s", value, range); this.value = value; } @ServiceProvider(JsonifierFactory.class) protected static final class IntParameterJsonifier implements Jsonifier<IntParameter>, JsonifierFactory { public IntParameterJsonifier() {} @Override public IntParameter fromJson(JsonValue jsonvalue) { JsonObject obj = Jsonifiers.checkClassEqual(jsonvalue, IntParameter.class); String name = obj.getString("name"); int min = obj.getInt("min"); int max = obj.getInt("max"); int value = obj.getInt("value"); return new IntParameter(name, min, max, value); } @Override public JsonValue toJson(IntParameter t) { return Json.createObjectBuilder() .add("class", Jsonifiers.toJson(IntParameter.class)) .add("name", t.getName()) .add("min", t.getMin()) .add("max", t.getMax()) .add("value", t.getValue()) //Python-side support .add("__module__", "parameters") .add("__class__", IntParameter.class.getSimpleName()) .build(); } @Override @SuppressWarnings("unchecked") public <T> Jsonifier<T> getJsonifier(Class<T> klass) { return (Jsonifier<T>)(klass.equals(IntParameter.class) ? this : null); } } @Override public String getName() { return name; } public int getMin() { return range.lowerEndpoint(); } public int getMax() { return range.upperEndpoint(); } public Range<Integer> getRange() { return range; } public int getValue() { return value; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final IntParameter other = (IntParameter)obj; if (!Objects.equals(this.name, other.name)) return false; if (!Objects.equals(this.range, other.range)) return false; if (this.value != other.value) return false; return true; } @Override public int hashCode() { int hash = 3; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.range); hash = 97 * hash + this.value; return hash; } @Override public String toString() { return String.format("[%s: %d in %s]", name, value, range); } } public static final class FloatParameter implements Parameter { private static final long serialVersionUID = 1L; private final String name; private final Range<Float> range; private final float value; public FloatParameter(String name, float min, float max, float value) { this(name, Range.closed(min, max), value); } public FloatParameter(String name, Range<Float> range, float value) { this.name = checkNotNull(Strings.emptyToNull(name)); checkNotNull(range); checkArgument(range.hasLowerBound() && range.lowerBoundType() == BoundType.CLOSED && range.hasUpperBound() && range.upperBoundType() == BoundType.CLOSED && !range.isEmpty()); this.range = range; checkArgument(range.contains(value), "value %s out of range %s", value, range); this.value = value; } @ServiceProvider(JsonifierFactory.class) protected static final class FloatParameterJsonifier implements Jsonifier<FloatParameter>, JsonifierFactory { public FloatParameterJsonifier() {} @Override public FloatParameter fromJson(JsonValue jsonvalue) { JsonObject obj = Jsonifiers.checkClassEqual(jsonvalue, IntParameter.class); String name = obj.getString("name"); float min = obj.getJsonNumber("min").bigDecimalValue().floatValue(); float max = obj.getJsonNumber("max").bigDecimalValue().floatValue(); float value = obj.getJsonNumber("value").bigDecimalValue().floatValue(); return new FloatParameter(name, min, max, value); } @Override public JsonValue toJson(FloatParameter t) { return Json.createObjectBuilder() .add("class", Jsonifiers.toJson(FloatParameter.class)) .add("name", t.getName()) .add("min", t.getMin()) .add("max", t.getMax()) .add("value", t.getValue()) //Python-side support .add("__module__", "sjparameters") .add("__class__", "sjFloatParameter") .build(); } @Override @SuppressWarnings("unchecked") public <T> Jsonifier<T> getJsonifier(Class<T> klass) { return (Jsonifier<T>)(klass.equals(FloatParameter.class) ? this : null); } } @Override public String getName() { return name; } public float getMin() { return range.lowerEndpoint(); } public float getMax() { return range.upperEndpoint(); } public Range<Float> getRange() { return range; } public float getValue() { return value; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final FloatParameter other = (FloatParameter)obj; if (!Objects.equals(this.name, other.name)) return false; if (!Objects.equals(this.range, other.range)) return false; if (this.value != other.value) return false; return true; } @Override public int hashCode() { int hash = 3; hash = 97 * hash + Objects.hashCode(this.name); hash = 97 * hash + Objects.hashCode(this.range); hash = 97 * hash + Float.floatToIntBits(this.value); return hash; } @Override public String toString() { return String.format("[%s: %d in %s]", name, value, range); } } /** * A SwitchParameter represents a choice of one of some universe of objects. * For example, a SwitchParameter<Boolean> is a simple on-off flag, while a * SwitchParameter<ChannelFactory> represents a choice of factories. * * The autotuner assumes there's no numeric relationship between the objects * in the universe, in contrast to IntParameter, for which it will try to * fit a model. * * The order of a SwitchParameter's universe is relevant for equals() and * hashCode() and correct operation of the autotuner. (To the autotuner, a * SwitchParameter is just an integer between 0 and the universe size; if * the order of the universe changes, the meaning of that integer changes * and the autotuner will get confused.) * * Objects put into SwitchParameters must implements equals() and hashCode() * for SwitchParameter's equals() and hashCode() methods to work correctly. * Objects put into SwitchParameters must be immutable. * * To the extent possible, the type T should not itself contain type * parameters. Consider defining a new class or interface that fixes the * type parameters. * * TODO: restrictions required for JSON representation: toString() and * fromString/valueOf/String ctor, fallback to base64 encoded Serializable, * etc; List/Set etc. not good unless contains only one type (e.g., * List<String> can be handled okay) * @param <T> */ public static final class SwitchParameter<T> implements GenericParameter<T> { private static final long serialVersionUID = 1L; private final String name; /** * The type of elements in this SwitchParameter. */ private final Class<T> type; /** * The universe of this SwitchParameter -- must not contain any * duplicate elements. */ private final ImmutableList<T> universe; /** * The index of the value in the universe. Note that most of the * interface prefers to work with Ts rather than values. */ private final int value; /** * Create a new SwitchParameter with the given type, value, and * universe. The universe must contain at least one element, contain no * duplicate elements, and contain the value. * * The type must be provided explicitly, rather than being inferred as * value.getClass(), as value might be of a more-derived type than the * elements in the universe. * @param name the name of this parameter * @param type the type of the universe * @param value the value of this parameter * @param universe the universe of possible values of this parameter */ public SwitchParameter(String name, Class<T> type, T value, Iterable<? extends T> universe) { this.name = checkNotNull(Strings.emptyToNull(name)); this.type = checkNotNull(type); int size = 0; ImmutableSet.Builder<T> builder = ImmutableSet.builder(); for (T t : universe) { checkArgument(!ReflectionUtils.usesObjectEquality(t.getClass()), "all objects in universe must have proper equals()/hashCode()"); builder.add(t); ++size; } ImmutableSet<T> set = builder.build(); checkArgument(set.size() == size, "universe contains duplicate elements"); //A single element universe is permitted, through not particularly //useful. checkArgument(set.size() > 0, "empty universe"); this.universe = set.asList(); this.value = checkElementIndex(this.universe.indexOf(value), this.universe.size(), "value not in universe"); } /** * Creates a new SwitchParameter<Boolean> with the given name and value. * The universe is [false, true]. * @param name the name of this parameter * @param value the value of this parameter (true or false) * @return a new SwitchParameter<Boolean> with the given name and value */ public static SwitchParameter<Boolean> create(String name, boolean value) { return new SwitchParameter<>(name, Boolean.class, value, Arrays.asList(false, true)); } @ServiceProvider(JsonifierFactory.class) protected static final class SwitchParameterJsonifier implements Jsonifier<SwitchParameter<?>>, JsonifierFactory { public SwitchParameterJsonifier() {} @Override @SuppressWarnings({"unchecked", "rawtypes"}) public SwitchParameter<?> fromJson(JsonValue jsonvalue) { JsonObject obj = Jsonifiers.checkClassEqual(jsonvalue, SwitchParameter.class); String name = obj.getString("name"); Class<?> universeType = Jsonifiers.fromJson(obj.get("universeType"), Class.class); ImmutableList<?> universe = ImmutableList.copyOf(Jsonifiers.fromJson(obj.get("universe"), ReflectionUtils.getArrayType(universeType))); //We should have caught this in fromJson(v, universeType). assert Jsonifiers.notHeapPolluted(universe, universeType); int value = obj.getInt("value"); return new SwitchParameter(name, universeType, universe.get(value), universe); } @Override public JsonValue toJson(SwitchParameter<?> t) { return Json.createObjectBuilder() .add("class", Jsonifiers.toJson(SwitchParameter.class)) .add("name", t.getName()) .add("universeType", Jsonifiers.toJson(t.type)) .add("universe", Jsonifiers.toJson(t.universe.toArray())) .add("value", t.value) //Python-side support .add("__module__", "parameters") .add("__class__", SwitchParameter.class.getSimpleName()) .build(); } @Override @SuppressWarnings("unchecked") public <T> Jsonifier<T> getJsonifier(Class<T> klass) { return (Jsonifier<T>)(klass.equals(SwitchParameter.class) ? this : null); } } @Override public String getName() { return name; } @Override public Class<T> getGenericParameter() { return type; } /** * Gets this parameter's value. * @return this parameter's value */ public T getValue() { return universe.get(value); } /** * Gets the universe of possible values for this parameter. * @return the universe of possible values for this parameter */ public ImmutableList<T> getUniverse() { return universe; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final SwitchParameter<?> other = (SwitchParameter<?>)obj; if (!Objects.equals(this.type, other.type)) return false; if (!Objects.equals(this.universe, other.universe)) return false; if (this.value != other.value) return false; return true; } @Override public int hashCode() { int hash = 7; hash = 47 * hash + Objects.hashCode(this.type); hash = 47 * hash + Objects.hashCode(this.universe); hash = 47 * hash + this.value; return hash; } @Override public String toString() { return String.format("[%s: %s (index %d) of %s]", name, getValue(), value, universe); } } /** * A PartitionParameter represents a partitioning of a stream graph * (workers) into Blobs, the kind of those Blobs, and the mapping of Blobs * to cores on machines. * <p/> * For the purposes of this class, machines are considered distinct, but * cores on the same machine are not. */ public static final class PartitionParameter implements Parameter { private static final long serialVersionUID = 1L; private final String name; /** * Map of MachineID and the number of cores on corresponding machine. Always contains at least one * element and all elements are always >= 1. */ private final ImmutableMap<Integer, Integer> machineCoreMap; /** * A map of machineID and list of blobs on that machine. The inner * lists are sorted. */ private final ImmutableMap<Integer, ImmutableList<BlobSpecifier>> machineBlobMap; /** * The BlobFactories that can be used to create blobs. This list * contains no duplicate elements. */ private final ImmutableList<BlobFactory> blobFactoryUniverse; /** * The maximum identifier of a worker in the stream graph, used during * deserialization to check that all workers have been assigned to a * blob. */ private final int maxWorkerIdentifier; /** * Only called by the builder. */ private PartitionParameter(String name, ImmutableMap<Integer, Integer> machineCoreMap, ImmutableMap<Integer, ImmutableList<BlobSpecifier>> blobs, ImmutableList<BlobFactory> blobFactoryUniverse, int maxWorkerIdentifier) { this.name = name; this.machineBlobMap = blobs; this.blobFactoryUniverse = blobFactoryUniverse; this.maxWorkerIdentifier = maxWorkerIdentifier; this.machineCoreMap = machineCoreMap; } public static final class Builder { private final String name; private final ImmutableMap<Integer, Integer> machineCoreMap; private final Map<Integer, Integer> coresAvailable; private final List<BlobFactory> blobFactoryUniverse = new ArrayList<>(); private final Map<Integer, List<BlobSpecifier>> machineBlobMap = new HashMap<>(); private final NavigableSet<Integer> workersInBlobs = new TreeSet<>(); private Builder(String name, ImmutableMap<Integer, Integer> machineCoreMap) { this.name = name; this.machineCoreMap = machineCoreMap; this.coresAvailable = new HashMap<>(machineCoreMap); //You might think we can use Collections.nCopies() here, but //that would mean all cores would share the same list! for (int i : machineCoreMap.keySet()) machineBlobMap.put(i, new ArrayList<BlobSpecifier>()); } public Builder addBlobFactory(BlobFactory factory) { checkArgument(!ReflectionUtils.usesObjectEquality(factory.getClass()), "blob factories must have a proper equals() and hashCode()"); checkArgument(!blobFactoryUniverse.contains(checkNotNull(factory)), "blob factory already added"); blobFactoryUniverse.add(factory); return this; } public Builder addBlob(int machine, int cores, BlobFactory blobFactory, Set<Worker<?, ?>> workers) { checkArgument(machineCoreMap.containsKey(machine), "No machine with the machineID %d", machine); checkArgument(cores <= machineCoreMap.get(machine), "allocating %s cores but only %s available on machine %s", cores, machineCoreMap.get(machine), machine); checkArgument(blobFactoryUniverse.contains(blobFactory), "blob factory %s not in universe %s", blobFactory, blobFactoryUniverse); ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder(); for (Worker<?, ?> worker : workers) { int identifier = Workers.getIdentifier(worker); checkArgument(identifier >= 0, "uninitialized worker identifier: %s", worker); checkArgument(!workersInBlobs.contains(identifier), "worker %s already assigned to blob", worker); builder.add(identifier); } ImmutableSortedSet<Integer> workerIdentifiers = builder.build(); //Okay, we've checked everything. Commit. machineBlobMap.get(machine).add(new BlobSpecifier(workerIdentifiers, machine, cores, blobFactory)); workersInBlobs.addAll(workerIdentifiers); int remainingCores = coresAvailable.get(machine) - cores; coresAvailable.put(machine, remainingCores); return this; } public PartitionParameter build() { ImmutableMap.Builder<Integer, ImmutableList<BlobSpecifier>> blobBuilder = ImmutableMap.builder(); for (Entry<Integer, List<BlobSpecifier>> blobMapEntry : machineBlobMap.entrySet()) { Collections.sort(blobMapEntry.getValue()); blobBuilder.put(blobMapEntry.getKey(), ImmutableList.copyOf(blobMapEntry.getValue())); } return new PartitionParameter(name, machineCoreMap, blobBuilder.build(), ImmutableList.copyOf(blobFactoryUniverse), workersInBlobs.last()); } } public static Builder builder(String name, Map<Integer, Integer> machineCoreMap) { checkArgument(!machineCoreMap.isEmpty()); for (Integer i : machineCoreMap.values()) checkArgument(checkNotNull(i) >= 1); return new Builder(checkNotNull(Strings.emptyToNull(name)), ImmutableMap.copyOf(machineCoreMap)); } /** * A blob's properties. */ public static final class BlobSpecifier implements Comparable<BlobSpecifier> { /** * The identifiers of the workers in this blob. */ private final ImmutableSortedSet<Integer> workerIdentifiers; /** * The index of the machine this blob is on. */ private final int machine; /** * The number of cores allocated to this blob. */ private final int cores; /** * The BlobFactory to be used to create this blob. */ private final BlobFactory blobFactory; private BlobSpecifier(ImmutableSortedSet<Integer> workerIdentifiers, int machine, int cores, BlobFactory blobFactory) { this.workerIdentifiers = workerIdentifiers; checkArgument(machine >= 0); this.machine = machine; checkArgument(cores >= 1, "all blobs must be assigned at least one core"); this.cores = cores; this.blobFactory = blobFactory; } @ServiceProvider(JsonifierFactory.class) protected static final class BlobSpecifierJsonifier implements Jsonifier<BlobSpecifier>, JsonifierFactory { public BlobSpecifierJsonifier() {} @Override public BlobSpecifier fromJson(JsonValue value) { //TODO: array serialization, error checking JsonObject obj = Jsonifiers.checkClassEqual(value, BlobSpecifier.class); int machine = obj.getInt("machine"); int cores = obj.getInt("cores"); BlobFactory blobFactory = Jsonifiers.fromJson(obj.get("blobFactory"), BlobFactory.class); ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder(); for (JsonValue i : obj.getJsonArray("workerIds")) builder.add(Jsonifiers.fromJson(i, Integer.class)); return new BlobSpecifier(builder.build(), machine, cores, blobFactory); } @Override public JsonValue toJson(BlobSpecifier t) { JsonArrayBuilder workerIds = Json.createArrayBuilder(); for (int i : t.workerIdentifiers) workerIds.add(i); return Json.createObjectBuilder() .add("class", Jsonifiers.toJson(BlobSpecifier.class)) .add("machine", t.machine) .add("cores", t.cores) .add("blobFactory", Jsonifiers.toJson(t.blobFactory)) .add("workerIds", workerIds) //Python-side support .add("__module__", "configuration") .add("__class__", BlobSpecifier.class.getSimpleName()) .build(); } @Override @SuppressWarnings("unchecked") public <T> Jsonifier<T> getJsonifier(Class<T> klass) { return (Jsonifier<T>)(klass.equals(BlobSpecifier.class) ? this : null); } } public ImmutableSortedSet<Integer> getWorkerIdentifiers() { return workerIdentifiers; } public ImmutableSet<Worker<?, ?>> getWorkers(Worker<?, ?> streamGraph) { ImmutableSet<Worker<?, ?>> allWorkers = Workers.getAllWorkersInGraph(streamGraph); ImmutableMap<Integer, Worker<?, ?>> workersByIdentifier = Maps.uniqueIndex(allWorkers, new Function<Worker<?, ?>, Integer>() { @Override public Integer apply(Worker<?, ?> input) { return Workers.getIdentifier(input); } }); ImmutableSet.Builder<Worker<?, ?>> workersInBlob = ImmutableSet.builder(); for (Integer i : workerIdentifiers) { Worker<?, ?> w = workersByIdentifier.get(i); if (w == null) throw new IllegalArgumentException("Identifier " + i + " not in given stream graph"); workersInBlob.add(w); } return workersInBlob.build(); } public int getMachine() { return machine; } public int getCores() { return cores; } public BlobFactory getBlobFactory() { return blobFactory; } @Override public int hashCode() { int hash = 3; hash = 37 * hash + Objects.hashCode(this.workerIdentifiers); hash = 37 * hash + this.machine; hash = 37 * hash + this.cores; hash = 37 * hash + Objects.hashCode(this.blobFactory); return hash; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final BlobSpecifier other = (BlobSpecifier)obj; if (!Objects.equals(this.workerIdentifiers, other.workerIdentifiers)) return false; if (this.machine != other.machine) return false; if (this.cores != other.cores) return false; if (!Objects.equals(this.blobFactory, other.blobFactory)) return false; return true; } @Override public int compareTo(BlobSpecifier o) { //Worker identifiers are unique within the stream graph, so //we can base our comparison on them. return workerIdentifiers.first().compareTo(o.workerIdentifiers.first()); } } @ServiceProvider(JsonifierFactory.class) protected static final class PartitionParameterJsonifier implements Jsonifier<PartitionParameter>, JsonifierFactory { public PartitionParameterJsonifier() {} @Override public PartitionParameter fromJson(JsonValue value) { //TODO: array serialization, error checking JsonObject obj = Jsonifiers.checkClassEqual(value, PartitionParameter.class); String name = obj.getString("name"); int maxWorkerIdentifier = obj.getInt("maxWorkerIdentifier"); Map<Integer, Integer> machineCoreMap = new HashMap<>(); JsonObject mapObj = checkNotNull(obj.getJsonObject("machineCoreMap")); for (Map.Entry<String, JsonValue> data : mapObj.entrySet()) { machineCoreMap.put(Integer.parseInt(data.getKey()), Jsonifiers.fromJson(data.getValue(), Integer.class)); } ImmutableList.Builder<BlobFactory> blobFactoryUniverse = ImmutableList.builder(); for (JsonValue v : obj.getJsonArray("blobFactoryUniverse")) blobFactoryUniverse.add(Jsonifiers.fromJson(v, BlobFactory.class)); Map<Integer, List<BlobSpecifier>> blobMachineMap = new HashMap<>(); JsonObject blobsObj = checkNotNull(obj.getJsonObject("machineBlobMap")); for (Map.Entry<String, JsonValue> data : blobsObj.entrySet()) { List<BlobSpecifier> bsList = new ArrayList<BlobSpecifier>(); JsonArray arr = (JsonArray)data.getValue(); for(int i = 0; i < arr.size(); i++) { BlobSpecifier bs = Jsonifiers.fromJson(arr.get(i), BlobSpecifier.class); if(bs.getMachine() != Integer.parseInt(data.getKey())) throw new IllegalArgumentException("fromJson error : Blobs and corresponding assigned machines mismatch"); bsList.add(bs); } if(blobMachineMap.containsKey(Integer.parseInt(data.getKey()))) throw new IllegalArgumentException("Multiple BlobSpecifier list exists for same machine"); blobMachineMap.put(Integer.parseInt(data.getKey()), bsList); } ImmutableMap.Builder<Integer, ImmutableList<BlobSpecifier>> blobBuilder = ImmutableMap.builder(); for (Entry<Integer, List<BlobSpecifier>> blobMapEntry : blobMachineMap.entrySet()) { Collections.sort(blobMapEntry.getValue()); blobBuilder.put(blobMapEntry.getKey(), ImmutableList.copyOf(blobMapEntry.getValue())); } return new PartitionParameter(name, ImmutableMap.copyOf(machineCoreMap), blobBuilder.build(), blobFactoryUniverse.build(), maxWorkerIdentifier); } @Override public JsonValue toJson(PartitionParameter t) { JsonObjectBuilder machineCoreMapBuilder = Json.createObjectBuilder(); for (Map.Entry<Integer, Integer> data : t.machineCoreMap.entrySet()) { machineCoreMapBuilder.add(data.getKey().toString(), Jsonifiers.toJson(data.getValue())); } JsonArrayBuilder blobFactoryUniverse = Json.createArrayBuilder(); for (BlobFactory factory : t.blobFactoryUniverse) blobFactoryUniverse.add(Jsonifiers.toJson(factory)); JsonObjectBuilder blobsBuilder = Json.createObjectBuilder(); for (Map.Entry<Integer,ImmutableList<BlobSpecifier>> machine : t.machineBlobMap.entrySet()) { JsonArrayBuilder bsArraybuilder = Json.createArrayBuilder(); for(BlobSpecifier bs : machine.getValue()) bsArraybuilder.add(Jsonifiers.toJson(bs)); blobsBuilder.add(machine.getKey().toString(), bsArraybuilder); } return Json.createObjectBuilder() .add("class", Jsonifiers.toJson(PartitionParameter.class)) .add("name", t.getName()) .add("maxWorkerIdentifier", t.maxWorkerIdentifier) .add("machineCoreMap", machineCoreMapBuilder) .add("blobFactoryUniverse", blobFactoryUniverse) .add("machineBlobMap", blobsBuilder) //Python-side support .add("__module__", "parameters") .add("__class__", PartitionParameter.class.getSimpleName()) .build(); } @Override @SuppressWarnings("unchecked") public <T> Jsonifier<T> getJsonifier(Class<T> klass) { return (Jsonifier<T>)(klass.equals(PartitionParameter.class) ? this : null); } } @Override public String getName() { return name; } public int getMachineCount() { return machineCoreMap.size(); } public int getCoresOnMachine(int machine) { return machineCoreMap.get(machine); } public ImmutableList<BlobSpecifier> getBlobsOnMachine(int machine) { return machineBlobMap.get(machine); } public ImmutableList<BlobFactory> getBlobFactories() { return blobFactoryUniverse; } /** * @param worker * @return the machineID where on which the passed worker is assigned. */ public int getAssignedMachine(Worker<?, ?> worker) { int id = Workers.getIdentifier(worker); for(int machineID : machineBlobMap.keySet() ) { for (BlobSpecifier bs : machineBlobMap.get(machineID)) { if (bs.getWorkerIdentifiers().contains(id)) return machineID; } } throw new IllegalArgumentException(String.format("%s is not assigned to anyof the machines", worker)); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final PartitionParameter other = (PartitionParameter)obj; if (!Objects.equals(this.name, other.name)) return false; if (!Objects.equals(this.machineCoreMap, other.machineCoreMap)) return false; if (!Objects.equals(this.machineBlobMap, other.machineBlobMap)) return false; if (!Objects.equals(this.blobFactoryUniverse, other.blobFactoryUniverse)) return false; if (this.maxWorkerIdentifier != other.maxWorkerIdentifier) return false; return true; } @Override public int hashCode() { int hash = 3; hash = 61 * hash + Objects.hashCode(this.name); hash = 61 * hash + Objects.hashCode(this.machineCoreMap); hash = 61 * hash + Objects.hashCode(this.machineBlobMap); hash = 61 * hash + Objects.hashCode(this.blobFactoryUniverse); hash = 61 * hash + this.maxWorkerIdentifier; return hash; } } public static Configuration randomize(Configuration cfg, Random rng) { Configuration.Builder builder = Configuration.builder(); for (Parameter p : cfg.getParametersMap().values()) { if (p instanceof IntParameter) { int min = ((IntParameter)p).getMin(), max = ((IntParameter)p).getMax(); int newValue = rng.nextInt(max-min+1) + min; builder.addParameter(new IntParameter(p.getName(), min, max, newValue)); } else if (p instanceof SwitchParameter) { SwitchParameter<?> sp = (SwitchParameter)p; builder.addParameter(new SwitchParameter(sp.getName(), sp.getGenericParameter(), sp.getUniverse().get(rng.nextInt(sp.getUniverse().size())), sp.getUniverse())); } else throw new UnsupportedOperationException("don't know how to randomize a "+p.getClass()+" named "+p.getName()); } for (Map.Entry<String, Object> e : cfg.getExtraDataMap().entrySet()) builder.putExtraData(e.getKey(), e.getValue()); return builder.build(); } public static void main(String[] args) { Configuration.Builder builder = Configuration.builder(); builder.addParameter(new IntParameter("foo", 0, 10, 8)); builder.addParameter(SwitchParameter.create("bar", true)); builder.addParameter(new SwitchParameter<>("baz", Integer.class, 3, Arrays.asList(1, 2, 3, 4))); Identity<Integer> first = new Identity<>(), second = new Identity<>(); Pipeline<Integer, Integer> pipeline = new Pipeline<>(first, second); ConnectWorkersVisitor cwv = new ConnectWorkersVisitor(); pipeline.visit(cwv); Map<Integer, Integer> mapEx = new HashMap<>(); mapEx.put(2, 8); mapEx.put(5, 16); mapEx.put(11, 24); mapEx.put(8, 12); mapEx.put(3, 32); mapEx.put(17, 64); List<Integer> crsPerMachine = new ArrayList<>(); crsPerMachine.add(8); crsPerMachine.add(16); PartitionParameter.Builder partParam = PartitionParameter.builder("part", mapEx); BlobFactory factory = new Interpreter.InterpreterBlobFactory(); partParam.addBlobFactory(factory); partParam.addBlob(17, 4, factory, Collections.<Worker<?, ?>>singleton(first)); partParam.addBlob(17, 1, factory, Collections.<Worker<?, ?>>singleton(second)); builder.addParameter(partParam.build()); builder.putExtraData("one", 1); builder.putExtraData("two", 2); builder.putExtraData("topLevelClassName", first.getClass().getName()); Configuration cfg1 = builder.build(); SwitchParameter<Integer> parameter = cfg1.getParameter("baz", SwitchParameter.class, Integer.class); String json = Jsonifiers.toJson(cfg1).toString(); //System.out.println(json); Configuration cfg2 = Jsonifiers.fromJson(json, Configuration.class); //System.out.println(cfg2); //String json2 = Jsonifiers.toJson(cfg2).toString(); //System.out.println(json2); PartitionParameter partp = (PartitionParameter) cfg2.getParameter("part"); System.out.println(partp.getCoresOnMachine(3)); List<BlobSpecifier> blobList = partp.getBlobsOnMachine(17); for (BlobSpecifier bs : blobList) System.out.println(bs.getWorkerIdentifiers()); //System.out.println(partp.getCoresOnMachineEx(17)); /*Configuration.Builder builder = Configuration.builder(); builder.addParameter(new IntParameter("foo", 0, 10, 8)); Configuration cfg1 = builder.build(); String json = Jsonifiers.toJson(cfg1).toString(); System.out.println(json);*/ } }
package eu.socialsensor.main; import eu.socialsensor.benchmarks.FindNeighboursOfAllNodesBenchmark; import eu.socialsensor.benchmarks.MassiveInsertionBenchmark; import eu.socialsensor.benchmarks.SingleInsertionBenchmark; public class GraphDatabaseBenchmark { private final static String enronDataset = "data/enronEdges.txt"; private final static String flickrDataset = "data/flickrEdges.txt"; private final static String amazonDataset = "data/amazonEdges.txt"; private final static String youtubeDataset = "data/youtubeEdges.txt"; private final static String livejournalDataset = "data/livejournalEdges.txt"; /** * This is the main function. Before you run the project un-comment * lines that correspond to the benchmark you want to run. */ public static void main(String[] args) { // MassiveInsertionBenchmark massiveInsertionBenchmark = new MassiveInsertionBenchmark(flickrDataset); // massiveInsertionBenchmark.startMassiveBenchmark(); SingleInsertionBenchmark singleInsertionBenchmark = new SingleInsertionBenchmark("data/test.txt"); singleInsertionBenchmark.startBenchmark(); // FindNeighboursOfAllNodesBenchmark findNeighboursOfAllNodesBenchmark = new FindNeighboursOfAllNodesBenchmark(); // findNeighboursOfAllNodesBenchmark.startBenchmark(); // FindNodesOfAllEdgesBenchmark findNodesOfAllEdgesBenchmark = new FindNodesOfAllEdgesBenchmark(); // findNodesOfAllEdgesBenchmark.startBenchmark(); // FindShortestPathBenchmark findShortestPathBenchmark = new FindShortestPathBenchmark(); // findShortestPathBenchmark.startBenchmark(); } }
package nars.predict; import automenta.vivisect.TreeMLData; import automenta.vivisect.swing.NWindow; import automenta.vivisect.swing.PCanvas; import automenta.vivisect.timeline.LineChart; import automenta.vivisect.timeline.TimelineVis; import java.awt.Color; import nars.core.Events.TaskImmediateProcess; import nars.core.NAR; import nars.core.Parameters; import nars.core.build.Default; import nars.core.control.NAL; import nars.entity.Concept; import nars.entity.Task; import nars.gui.NARSwing; import nars.gui.output.ConceptsPanel; import nars.io.ChangedTextInput; import nars.io.TextOutput; import nars.io.narsese.Narsese; import nars.language.Tense; import nars.language.Term; public class Predict_NARS_Core { static float signal = 0; static TreeMLData[] predictions; protected boolean allowTask(NAR n,Task t) { if (t.sentence.isEternal()) { return false; } if ((t.sentence.getOccurenceTime() > n.time())) { Term term = t.getTerm(); int time = (int) t.sentence.getOccurenceTime(); int value = -1; float conf = t.sentence.truth.getConfidence(); float expect = 2f * (t.sentence.truth.getFrequency() - 0.5f) * conf; String ts = term.toString(); if (ts.startsWith("<x_t0 char cc = ts.charAt("<x_t0 --> y".length()); value = cc - '0'; predictions[0].add((int)n.time(), value ); } /* if (value != -1) { //predictions[(int)value].addPlus(time, expect); for (int tt = time - duration / 2; tt <= time + duration / 2; tt++) { double smooth = 1; expect *= getPredictionEnvelope(time-tt, smooth * duration*2f); // //if (future) // predictions[value].addPlus(tt, expect); // else // reflections[value].addPlus(tt, expect); /// } }*/ return true; } return false; } public static void main(String[] args) throws Narsese.InvalidInputException, InterruptedException { Parameters.DEBUG = true; int duration = 8; float freq = 1.0f / duration * 0.075f; double missingDataRate = 0.1; double noiseRate = 0.02; boolean onlyNoticeChange = false; int thinkInterval = 50; int discretization = 3; NAR n = new NAR(new Default().setInternalExperience(null)); n.param.duration.set(duration); //n.param.duration.setLinear(0.5); n.param.conceptBeliefsMax.set(64); //n.param.conceptForgetDurations.set(16); n.on(TaskImmediateProcess.class, new TaskImmediateProcess() { int curmax=0; @Override public void onProcessed(Task t, NAL n) { if (t.sentence.getOccurenceTime() >= n.memory.time()) { //no need to restrict to future value //if(t.sentence.getOccurenceTime() - n.memory.time() > duration*10) { // return; //dont let it predict too far apart because the plot does not support <THIS1> Term term = t.getTerm(); int time = (int) t.sentence.getOccurenceTime(); int value = -1; float conf = t.sentence.truth.getConfidence(); float expect = 2f * (t.sentence.truth.getFrequency() - 0.5f) * conf; String ts = term.toString(); if (ts.startsWith("<{x} char cc = ts.charAt("<{x} --> y".length()); value = cc - '0'; //predictions[0].addPlus((int) n.memory.time(), Math.random()*100); //if((int) t.sentence.getOccurenceTime()>=curmax) // <THIS1> - plot does not support updating old values.. predictions[0].add((int) t.sentence.getOccurenceTime(), (value)/10.0 ); curmax=(int) Math.max(t.sentence.getOccurenceTime(), curmax); } } } }); Discretize discretize = new Discretize(n, discretization); TreeMLData observed = new TreeMLData("value", Color.WHITE).setRange(0, 1f); predictions = new TreeMLData[discretization]; TreeMLData[] reflections = new TreeMLData[discretization]; for (int i = 0; i < predictions.length; i++) { predictions[i] = new TreeMLData("Pred" + i, Color.getHSBColor(0.25f + i / 4f, 0.85f, 0.85f)); reflections[i] = new TreeMLData("Refl" + i, Color.getHSBColor(0.25f + i / 4f, 0.85f, 0.85f)); reflections[i].setDefaultValue(0.0); } TimelineVis tc = new TimelineVis( new LineChart(observed).thickness(16f).height(128), new LineChart(predictions).thickness(16f).height(128), new LineChart(reflections).thickness(16f).height(128) /*new LineChart(predictions[1]).thickness(16f).height(128), new LineChart(predictions[2]).thickness(16f).height(128),*/ ); new NWindow("_", new PCanvas(tc)).show(800, 800, true); for (Term t : discretize.getValueTerms("x")) n.believe(t.toString(), Tense.Present, 0.5f, 0.5f); //n.run(discretization*4); n.run(discretization*4); Concept[] valueBeliefConcepts = discretize.getValueConcepts("x"); NARSwing.themeInvert(); new NWindow("x", new ConceptsPanel(n, valueBeliefConcepts)).show(900, 600, true); // new NARSwing(n); ChangedTextInput chg=new ChangedTextInput(n); ChangedTextInput chg2=new ChangedTextInput(n); int prevY = -1, curY = -1; int cnt=0; while (true) { cnt++; n.run(thinkInterval); Thread.sleep(3); //signal = (float)Math.max(0, Math.min(1.0, Math.tan(freq * n.time()) * 0.5f + 0.5f)); signal = (float)Math.sin(freq * n.time()) * 0.5f + 0.5f; //signal = ((float) Math.sin(freq * n.time()) > 0 ? 1f : -1f) * 0.5f + 0.5f; //signal *= 1.0 + (Math.random()-0.5f)* 2f * noiseRate; if (Math.random() > missingDataRate) observed.add((int) n.time(), signal); prevY = curY; curY = discretize.f(signal); if ((curY == prevY) && (onlyNoticeChange)) { continue; } //discretize.believe("x", signal, 0); //if(cnt<1000) { //switch to see what NARS does when observations end :) double prec=4.0; int val=(int)(((int)((signal*prec))*(10.0/prec))); chg.set("<{x} --> y"+val+">. :|:"); chg2.set("<{x} --> y"+val+">!"); //System.out.println(val); /*} else if (cnt==1000){ System.out.println("observation phase end, residual predictions follow"); }*/ } } }
package edu.umd.cs.findbugs.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.WillClose; import javax.annotation.WillCloseWhenClosed; import javax.annotation.WillNotClose; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.jsr305.TypeQualifierValue; /** * @author William Pugh */ public class Util { public static final boolean LOGGING = SystemProperties.getBoolean("findbugs.shutdownLogging"); public static Iterable<Integer> setBitIteratable(final BitSet b) { return new Iterable<Integer>(){ public Iterator<Integer> iterator() { return setBitIterator(b); }}; } public static Iterator<Integer> setBitIterator(final BitSet b) { return new Iterator<Integer>() { int nextBit = b.nextSetBit(0); public boolean hasNext() { return nextBit >= 0; } public Integer next() { int result = nextBit; nextBit = b.nextSetBit(nextBit+1); return result; } public void remove() { throw new UnsupportedOperationException(); }}; } public static String repeat(String s, int number) { StringBuilder b = new StringBuilder(s.length() * number); for(int i = 0; i < number; i++) b.append(s); return b.toString(); } static Collection<Runnable> runAtShutdown; public static synchronized void runLogAtShutdown(Runnable r) { if (LOGGING) { if (runAtShutdown == null) { runAtShutdown = new LinkedList<Runnable>(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for(Runnable r : runAtShutdown) { try { r.run(); } catch (RuntimeException e) { e.printStackTrace(); } } } }); } runAtShutdown.add(r); } } public static <T> Set<T> emptyOrNonnullSingleton(T t) { if (t == null) return Collections.<T>emptySet(); return Collections.<T>singleton(t); } public static <K,V> Map<K,V> immutableMap(Map<K,V> map) { if (map.size() == 0) return Collections.<K,V>emptyMap(); return Collections.<K,V>unmodifiableMap(map); } public static int nullSafeHashcode(@CheckForNull Object o) { if (o == null) return 0; return o.hashCode(); } public static <T> boolean nullSafeEquals(@CheckForNull T o1, @CheckForNull T o2) { if (o1 == o2) return true; if (o1 == null || o2 == null) return false; return o1.equals(o2); } public static Reader getReader(@WillCloseWhenClosed InputStream in) throws UnsupportedEncodingException { return new InputStreamReader(in, "UTF-8"); } public static Reader getFileReader(String filename) throws UnsupportedEncodingException, FileNotFoundException { return getReader(new FileInputStream(filename)); } public static Reader getFileReader(File filename) throws UnsupportedEncodingException, FileNotFoundException { return getReader(new FileInputStream(filename)); } public static Writer getWriter(@WillCloseWhenClosed OutputStream out) throws UnsupportedEncodingException, FileNotFoundException { return new OutputStreamWriter(out, "UTF-8"); } public static Writer getFileWriter(String filename) throws UnsupportedEncodingException, FileNotFoundException { return getWriter(new FileOutputStream(filename)); } public static void closeSilently(@WillClose InputStream in) { try { if (in != null) in.close(); } catch (IOException e) { assert true; } } public static void closeSilently(@WillClose Reader in) { try { if (in != null) in.close(); } catch (IOException e) { assert true; } } public static void closeSilently(@WillClose OutputStream out) { try { if (out != null) out.close(); } catch (IOException e) { assert true; } } static final Pattern tag = Pattern.compile("^\\s*<(\\w+)"); public static String getXMLType(@WillNotClose InputStream in) throws IOException { if (!in.markSupported()) throw new IllegalArgumentException("Input stream does not support mark"); in.mark(5000); BufferedReader r = null; try { r = new BufferedReader(Util.getReader(in), 2000); String s; int count = 0; while (count < 4) { s = r.readLine(); if (s == null) break; Matcher m = tag.matcher(s); if (m.find()) return m.group(1); } throw new IOException("Didn't find xml tag"); } finally { in.reset(); } } public static IOException makeIOException(String msg, Throwable cause) { IOException e = new IOException(msg); e.initCause(cause); return e; } public static String getFileExtension(File f) { String name = f.getName(); int lastDot = name.lastIndexOf('.'); if (lastDot == -1) return ""; return name.substring(lastDot+1).toLowerCase(); } public static void throwIOException(String msg, Throwable cause) throws IOException { IOException e = new IOException(msg); e.initCause(cause); throw e; } /** * @param i the Iterable whose first element is to be retrieved * @return first element of iterable */ public static <E> E first(Iterable<E> i) { Iterator<E> iterator = i.iterator(); if (!iterator.hasNext()) throw new IllegalArgumentException("iterator has no elements"); return iterator.next(); } }
package aeronicamc.mods.mxtune.items; import aeronicamc.mods.mxtune.inventory.InstrumentContainer; import aeronicamc.mods.mxtune.managers.PlayIdSupplier; import aeronicamc.mods.mxtune.managers.PlayManager; import aeronicamc.mods.mxtune.util.IInstrument; import aeronicamc.mods.mxtune.util.SheetMusicHelper; import aeronicamc.mods.mxtune.util.SoundFontProxyManager; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.INamedContainerProvider; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemUseContext; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ActionResult; import net.minecraft.util.ActionResultType; import net.minecraft.util.Hand; import net.minecraft.util.NonNullList; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraftforge.common.util.Constants; import net.minecraftforge.fml.network.NetworkHooks; import javax.annotation.Nullable; import java.util.List; public class ItemMultiInst extends Item implements IInstrument, INamedContainerProvider { private final static String KEY_PLAY_ID = "MXTunePlayId"; private final static ITextComponent SHIFT_HELP = new TranslationTextComponent("item.mxtune.multi_inst.shift"); private final static ITextComponent HELP_01 = new TranslationTextComponent("item.mxtune.multi_inst.shift.help01"); private final static ITextComponent HELP_02 = new TranslationTextComponent("item.mxtune.multi_inst.shift.help02"); public ItemMultiInst(Properties pProperties) { super(pProperties); } @Override public ActionResult<ItemStack> use(World pLevel, PlayerEntity pPlayer, Hand pHand) { if (!pLevel.isClientSide()) { ItemStack itemStackIn = pPlayer.getItemInHand(pHand); int playId = getPlayId(itemStackIn); if (pPlayer.isCrouching() && pHand.equals(Hand.MAIN_HAND)) { NetworkHooks.openGui((ServerPlayerEntity) pPlayer, this, pPlayer.blockPosition()); } else if (!pPlayer.isCrouching() && pHand.equals(Hand.MAIN_HAND)) { if ((playId <= 0) || !PlayManager.isActivePlayId(playId)) { setPlayId(itemStackIn, PlayManager.playMusic(pPlayer)); } } } return ActionResult.pass(pPlayer.getItemInHand(pHand)); } /** * Get this stack's playId, or INVALID (-1) if no playId is defined. */ private int getPlayId(ItemStack pStack) { return pStack.hasTag() && pStack.getTag() != null && pStack.getTag().contains(KEY_PLAY_ID, Constants.NBT.TAG_INT) ? pStack.getTag().getInt(KEY_PLAY_ID) : PlayIdSupplier.INVALID; } /** * Set this stack's playId. */ private void setPlayId(ItemStack pStack, int pCost) { pStack.getOrCreateTag().putInt(KEY_PLAY_ID, pCost); } /** * Get this stack's patch, or 0 if no patch is defined. */ @Override public int getPatch(ItemStack pStack) { return pStack.getMaxDamage(); } // Stop playing if active and the item is no longer selected. @Override public void inventoryTick(ItemStack pStack, World pLevel, Entity pEntity, int pItemSlot, boolean pIsSelected) { if (!pLevel.isClientSide()) { int playId = getPlayId(pStack); if (!pIsSelected && PlayManager.isActivePlayId(playId)) { PlayManager.stopPlayId(playId); setPlayId(pStack, PlayIdSupplier.INVALID); } } } // Stop playing if dropped @Override public boolean onDroppedByPlayer(ItemStack pStack, PlayerEntity pPlayer) { if (!pPlayer.level.isClientSide()) { int playId = getPlayId(pStack); if (PlayManager.isActivePlayId(playId)) { PlayManager.stopPlayId(playId); setPlayId(pStack, PlayIdSupplier.INVALID); } } return true; } // Stop playing when moved from inventory into the world @Override public int getEntityLifespan(ItemStack pStack, World pLevel) { if (!pLevel.isClientSide()) { int playId = getPlayId(pStack); if (PlayManager.isActivePlayId(playId)) { PlayManager.stopPlayId(playId); setPlayId(pStack, PlayIdSupplier.INVALID); } } return super.getEntityLifespan(pStack, pLevel); } @Override public void onCraftedBy(ItemStack pStack, World pLevel, PlayerEntity pPlayer) { setPlayId(pStack, PlayIdSupplier.INVALID); } @Override public void fillItemCategory(ItemGroup pGroup, NonNullList<ItemStack> pItems) // getSubItems { super.fillItemCategory(pGroup, pItems); } @Override public String getDescriptionId(ItemStack pStack) { return SoundFontProxyManager.getLangKeyName(pStack.getMaxDamage()); } @Override public int getUseDuration(ItemStack pStack) { return 72000; } @Override public ActionResultType interactLivingEntity(ItemStack pStack, PlayerEntity pPlayer, LivingEntity pTarget, Hand pHand) { return ActionResultType.PASS; } // Prevent the item from activating [this.use(...)] when clicking a block with a TileEntity @Override public ActionResultType useOn(ItemUseContext pContext) { TileEntity tileEntity = pContext.getLevel().getBlockEntity(pContext.getClickedPos()); if (tileEntity != null && tileEntity.getBlockState().hasTileEntity()) return ActionResultType.SUCCESS; return super.useOn(pContext); } /** * Gets the title name of the book * * @param pStack */ @Override public ITextComponent getName(ItemStack pStack) { return new TranslationTextComponent(SoundFontProxyManager.getLangKeyName(pStack.getMaxDamage())); } /** * Allow the item one last chance to modify its name used for the tool highlight * useful for adding something extra that can't be removed by a user in the * displayed name, such as a mode of operation. * * @param item the ItemStack for the item. * @param displayName the name that will be displayed unless it is changed in */ @Override public ITextComponent getHighlightTip(ItemStack item, ITextComponent displayName) { return new TranslationTextComponent(SoundFontProxyManager.getLangKeyName(item.getMaxDamage())); } @Override public ITextComponent getDisplayName() { return new StringTextComponent("What's dis?"); } @Override public void appendHoverText(ItemStack pStack, @Nullable World pLevel, List<ITextComponent> pTooltip, ITooltipFlag pFlag) { ItemStack iMusic = SheetMusicHelper.getIMusicFromIInstrument(pStack); pTooltip.add(SheetMusicHelper.getFormattedMusicTitle(iMusic)); if (SheetMusicHelper.hasMusicText(SheetMusicHelper.getIMusicFromIInstrument(pStack))) { pTooltip.add(SheetMusicHelper.getFormattedMusicDuration(iMusic)); pTooltip.add(SheetMusicHelper.getFormattedSheetMusicDaysLeft(iMusic)); } if (Screen.hasShiftDown()) { pTooltip.add(HELP_01); pTooltip.add(HELP_02); } else { pTooltip.add(SHIFT_HELP); } } @Nullable @Override public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) { if (playerEntity.level == null) return null; return new InstrumentContainer(i, playerEntity.level, playerEntity.blockPosition(), playerInventory, playerEntity); } }
package com.rethinkdb.ast; import com.rethinkdb.gen.exc.ReqlDriverError; import com.rethinkdb.gen.proto.TermType; import com.rethinkdb.model.Arguments; import com.rethinkdb.model.OptArgs; import com.rethinkdb.net.Connection; import com.rethinkdb.net.ConnectionInstance; import org.json.simple.JSONArray; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** Base class for all reql queries. */ public class ReqlAst { protected final TermType termType; protected final Arguments args; protected final OptArgs optargs; protected ReqlAst(TermType termType, Arguments args, OptArgs optargs) { if(termType == null){ throw new ReqlDriverError("termType can't be null!"); } this.termType = termType; this.args = args != null ? args : new Arguments(); this.optargs = optargs != null ? optargs : new OptArgs(); } protected Object build() { // Create a JSON object from the Ast JSONArray list = new JSONArray(); list.add(termType.value); if (args.size() > 0) { list.add(args.stream() .map(ReqlAst::build) .collect(Collectors.toCollection(JSONArray::new))); }else { list.add(new JSONArray()); } if (optargs.size() > 0) { list.add(buildOptarg(optargs)); } return list; } public static Map<String, Object> buildOptarg(OptArgs opts){ Map<String, Object> result = new HashMap<>( opts.size() ); opts.forEach( (name, arg) -> result.put( name, arg.build() ) ); return result; } /** * Runs this query via connection {@code conn} with default options and returns an atom result * or a sequence result as a cursor. The atom result either has a primitive type (e.g., {@code Integer}) * or represents a JSON object as a {@code Map<String, Object>}. The cursor is a {@code com.rethinkdb.net.Cursor} * which may be iterated to get a sequence of atom results * @param conn The connection to run this query * @param <T> The type of result * @return The result of this query */ public <T> T run(Connection<? extends ConnectionInstance> conn) { return conn.run(this, new OptArgs(), Optional.empty()); } /** * Runs this query via connection {@code conn} with options {@code runOpts} and returns an atom result * or a sequence result as a cursor. The atom result either has a primitive type (e.g., {@code Integer}) * or represents a JSON object as a {@code Map<String, Object>}. The cursor is a {@code com.rethinkdb.net.Cursor} * which may be iterated to get a sequence of atom results * @param conn The connection to run this query * @param runOpts The options to run this query with * @param <T> The type of result * @return The result of this query */ public <T> T run(Connection<? extends ConnectionInstance> conn, OptArgs runOpts) { return conn.run(this, runOpts, Optional.empty()); } /** * Runs this query via connection {@code conn} with default options and returns an atom result * or a sequence result as a cursor. The atom result representing a JSON object is converted * to an object of type {@code Class<P>} specified with {@code pojoClass}. The cursor * is a {@code com.rethinkdb.net.Cursor} which may be iterated to get a sequence of atom results * of type {@code Class<P>} * @param conn The connection to run this query * @param pojoClass The class of POJO to convert to * @param <T> The type of result * @param <P> The type of POJO to convert to * @return The result of this query (either a {@code P or a Cursor<P>} */ public <T, P> T run(Connection<? extends ConnectionInstance> conn, Class<P> pojoClass) { return conn.run(this, new OptArgs(), Optional.of(pojoClass)); } /** * Runs this query via connection {@code conn} with options {@code runOpts} and returns an atom result * or a sequence result as a cursor. The atom result representing a JSON object is converted * to an object of type {@code Class<P>} specified with {@code pojoClass}. The cursor * is a {@code com.rethinkdb.net.Cursor} which may be iterated to get a sequence of atom results * of type {@code Class<P>} * @param conn The connection to run this query * @param runOpts The options to run this query with * @param pojoClass The class of POJO to convert to * @param <T> The type of result * @param <P> The type of POJO to convert to * @return The result of this query (either a {@code P or a Cursor<P>} */ public <T, P> T run(Connection<? extends ConnectionInstance> conn, OptArgs runOpts, Class<P> pojoClass) { return conn.run(this, runOpts, Optional.of(pojoClass)); } public void runNoReply(Connection conn){ conn.runNoReply(this, new OptArgs()); } public void runNoReply(Connection conn, OptArgs globalOpts){ conn.runNoReply(this, globalOpts); } @Override public String toString() { return "ReqlAst{" + "termType=" + termType + ", args=" + args + ", optargs=" + optargs + '}'; } }
package alokawi.poc.spark.core; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.spark.SparkConf; import org.apache.spark.SparkContext; import org.apache.spark.sql.Column; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SQLContext; import org.apache.spark.sql.SparkSession; /** * @author alokkumar * */ public class SparkCassandraUtils { /** * @param args */ public static void main(String[] args) { SparkCassandraUtils cassandraUtils = new SparkCassandraUtils(); cassandraUtils.execute(); } @SuppressWarnings("deprecation") private void execute() { SparkConf conf = new SparkConf(); conf.setAppName("cassandra-spark-poc"); conf.setMaster("local[*]"); SparkContext sparkContext = new SparkContext(conf); System.out.println(sparkContext); SparkSession sparkSession = SparkSession.builder().appName("cassandra-spark-poc").master("local[*]") .getOrCreate(); SQLContext sqlContext = new SQLContext(sparkSession); Map<String, String> options = new HashMap<String, String>(); options.put("keyspace", "wootag"); options.put("table", "video_view"); Dataset<Row> dataset = sqlContext.read().format("org.apache.spark.sql.cassandra").options(options).load() .cache(); dataset.registerTempTable("temptable"); String query = "select video_id, view_duration_in_second, count(*) from temptable group by 1, 2"; List<Row> collectAsList = sqlContext.sql(query).collectAsList(); for (Row row : collectAsList) { System.out.println(row.get(0) + "," + row.get(1) + "," + row.get(2)); } // sqlContext.sql(query).show(1000); long startTime = 1485907200000L; long endTime = 1487226374000L; for (long i = startTime; i <= endTime; i = i + TimeUnit.DAYS.toMillis(1)) { dataset.filter(new Column("event_start_timestamp").geq(i)) .filter(new Column("event_start_timestamp").leq(i + TimeUnit.DAYS.toMillis(1))) .groupBy(new Column("view_duration_in_second"), new Column("video_id")).count() .orderBy("view_duration_in_second").show(1000); sleepDelay(); } } private void sleepDelay() { try { Thread.sleep(3000L); } catch (InterruptedException e) { e.printStackTrace(); } } }
package org.strategoxt.imp.runtime.services.outline; import java.util.LinkedList; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.imp.parser.IModelListener; import org.eclipse.imp.parser.IParseController; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.views.contentoutline.ContentOutlinePage; import org.spoofax.interpreter.terms.IStrategoInt; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr.client.imploder.ImploderAttachment; import org.spoofax.jsglr.client.imploder.ImploderOriginTermFactory; import org.spoofax.terms.TermFactory; import org.spoofax.terms.attachments.OriginAttachment; import org.strategoxt.imp.runtime.EditorState; import org.strategoxt.imp.runtime.dynamicloading.BadDescriptorException; import org.strategoxt.imp.runtime.services.StrategoObserver; import org.strategoxt.imp.runtime.stratego.StrategoTermPath; import org.strategoxt.lang.Context; /** * @author Oskar van Rest */ public class SpoofaxOutlinePage extends ContentOutlinePage implements IModelListener { public final static String OUTLINE_STRATEGY = "outline-strategy"; public final static String OUTLINE_EXPAND_TO_LEVEL = "outline-expand-to-level"; private int outline_expand_to_level = 2; private EditorState editorState; private ImploderOriginTermFactory factory = new ImploderOriginTermFactory(new TermFactory()); private StrategoObserver observer; private boolean debounceSelectionChanged; private IStrategoTerm outline; public SpoofaxOutlinePage(EditorState editorState) { this.editorState = editorState; try { observer = editorState.getDescriptor().createService(StrategoObserver.class, editorState.getParseController()); } catch (BadDescriptorException e) { e.printStackTrace(); } editorState.getEditor().addModelListener(this); editorState.getEditor().getSelectionProvider().addSelectionChangedListener(this); } @Override public void dispose() { editorState.getEditor().removeModelListener(this); } @Override public void createControl(Composite parent) { super.createControl(parent); getTreeViewer().setContentProvider(new SpoofaxOutlineContentProvider()); String pluginPath = editorState.getDescriptor().getBasePath().toPortableString(); getTreeViewer().setLabelProvider(new SpoofaxOutlineLabelProvider(pluginPath)); observer.getLock().lock(); try { IStrategoTerm outline_expand_to_level = observer.invokeSilent(OUTLINE_EXPAND_TO_LEVEL, editorState.getCurrentAst(), editorState.getResource().getFullPath().toFile()); if (outline_expand_to_level != null) { this.outline_expand_to_level = ((IStrategoInt) outline_expand_to_level).intValue(); } } finally { observer.getLock().unlock(); } update(); } public AnalysisRequired getAnalysisRequired() { return AnalysisRequired.NONE; } public void update(IParseController controller, IProgressMonitor monitor) { update(); } public void update() { observer.getLock().lock(); try { outline = observer.invokeSilent(OUTLINE_STRATEGY, editorState.getCurrentAst(), editorState.getResource().getFullPath().toFile()); if (outline == null) { outline = factory.makeAppl(factory.makeConstructor("Node", 2), factory.makeString(OUTLINE_STRATEGY + " failed"), factory.makeList()); } // ensures propagation of origin information factory.makeLink(outline, editorState.getCurrentAst()); Display.getDefault().asyncExec(new Runnable() { public void run() { getTreeViewer().setInput(outline); getTreeViewer().expandToLevel(outline_expand_to_level); } }); } finally { observer.getLock().unlock(); } } @Override public void selectionChanged(SelectionChangedEvent event) { if (event.getSource() == getTreeViewer()) { super.selectionChanged(event); } if (debounceSelectionChanged) { return; } debounceSelectionChanged = true; if (event.getSource() == getTreeViewer()) { outlineSelectionToTextSelection(); } else { textSelectionToOutlineSelection(); } debounceSelectionChanged = false; } public void outlineSelectionToTextSelection() { TreeSelection treeSelection = (TreeSelection) getSelection(); if (treeSelection.isEmpty()) { return; } IStrategoTerm firstElem = (IStrategoTerm) treeSelection.getFirstElement(); IStrategoTerm origin = OriginAttachment.getOrigin(firstElem.getSubterm(0)); // use origin of label if (origin == null) { origin = OriginAttachment.getOrigin(firstElem); // use origin of node } if (origin == null) { origin = firstElem.getSubterm(0); // assume label is origin } if (ImploderAttachment.hasImploderOrigin(origin)) { int startOffset = (ImploderAttachment.getLeftToken(origin).getStartOffset()); int endOffset = (ImploderAttachment.getRightToken(origin).getEndOffset()) + 1; TextSelection newSelection = new TextSelection(startOffset, endOffset - startOffset); editorState.getEditor().getSelectionProvider().setSelection(newSelection); } } public void textSelectionToOutlineSelection() { IStrategoTerm textSelection = null; try { textSelection = editorState.getSelectionAst(true); } catch (IndexOutOfBoundsException e) { // hack: happens when user selects text, deletes it and then chooses 'undo' // TODO: fix EditorState.getSelectionAst() } if (textSelection == null) { return; } Context context = observer.getRuntime().getCompiledContext(); IStrategoList path = StrategoTermPath.getTermPathWithOrigin(context, outline, textSelection); if (path == null) { return; } TreePath[] treePaths = termPathToTreePaths(path); TreeSelection selection = new TreeSelection(treePaths); setSelection(selection); } private TreePath[] termPathToTreePaths(IStrategoList path) { return termPathToTreePaths(path, outline, new LinkedList<IStrategoTerm>()); } private TreePath[] termPathToTreePaths(IStrategoList path, IStrategoTerm current, LinkedList<IStrategoTerm> segments) { if (current.getTermType()==IStrategoTerm.APPL) { segments.add(current); } if (path.isEmpty()) { if (current.getTermType()==IStrategoTerm.APPL || current.getTermType()==IStrategoTerm.STRING) { TreePath[] result = new TreePath[1]; result[0] = new TreePath(segments.toArray()); return result; } else { IStrategoTerm[] leaves = current.getAllSubterms(); TreePath[] result = new TreePath[leaves.length]; for (int i=0; i<leaves.length; i++) { segments.add(leaves[i]); result[i] = new TreePath(segments.toArray()); segments.removeLast(); } return result; } } current = current.getSubterm(((IStrategoInt) path.head()).intValue()); path = path.tail(); return termPathToTreePaths(path, current, segments); } @Override public void setFocus() { super.setFocus(); outlineSelectionToTextSelection(); } }
package one.noa.onusbutton; import android.content.Context; import android.content.res.TypedArray; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.v7.content.res.AppCompatResources; import android.util.AttributeSet; import android.view.Gravity; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.TextView; import one.noa.library.R; import one.noa.onusbutton.dispatcher.BasicLoadingDispatcher; import one.noa.onusbutton.dispatcher.StateDispatcher; public class OnusButton extends FrameLayout { private static final int INVALID_VALUE = -1; private TextView labelPlaceholder; private ProgressBar progressBar; private boolean isLoading; private StateDispatcher loadingDispatcher = new BasicLoadingDispatcher(); public OnusButton(Context context) { this(context, null); } public OnusButton(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.buttonStyle); } public OnusButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initializeViews(context, attrs, defStyleAttr); initAttrs(context, attrs); } private void initializeViews(Context context, AttributeSet attrs, int defStyleAttr) { // Avoid padding on container, it happens on label setClipToPadding(false); setPadding(0, 0, 0, 0); initializePlaceholderButton(context, attrs, defStyleAttr); initializeProgressBar(context, attrs, defStyleAttr); } private void initializeProgressBar(Context context, AttributeSet attrs, int defStyleAttr) { LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams .WRAP_CONTENT); layoutParams.gravity = Gravity.CENTER; int defaultStyleAttr = defStyleAttr == INVALID_VALUE ? android.R.attr.progressBarStyleSmall : defStyleAttr; TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.OnusButton, defaultStyleAttr, 0); Drawable progressBarDrawable = typedArray.getDrawable(R.styleable.OnusButton_loadingDrawable); int defaultProgressBarColor = labelPlaceholder.getCurrentTextColor(); int progressBarColor = typedArray.getColor(R.styleable.OnusButton_loadingDrawableColor, defaultProgressBarColor); progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleSmallInverse); if (progressBarDrawable != null) { progressBarDrawable.setColorFilter(progressBarColor, PorterDuff.Mode.SRC_IN); progressBar.setIndeterminateDrawable(progressBarDrawable); } else { int defaultColor = getResources().getColor(android.R.color.white); int color = progressBarColor != INVALID_VALUE ? progressBarColor : defaultColor; progressBar.getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN); } progressBar.setIndeterminate(true); addView(progressBar, layoutParams); typedArray.recycle(); } private void adjustProgressBarOnSizeChanged(int w, int h, int oldw, int oldh) { int progressBarWidth = progressBar.getMeasuredWidth(); int derivedMargin = (h - progressBar.getMeasuredWidth()) / 2; int defaultMargin = Math.max(progressBarWidth, Math.min(progressBarWidth * 2, derivedMargin)); LayoutParams layoutParams = (LayoutParams) progressBar.getLayoutParams(); layoutParams.leftMargin = layoutParams.rightMargin = defaultMargin; progressBar.setLayoutParams(layoutParams); } private void initializePlaceholderButton(Context context, AttributeSet attrs, int defStyleAttr) { labelPlaceholder = new TextView(context, attrs, defStyleAttr); // Ignore global properties (boundaries, background) labelPlaceholder.setBackground(null); labelPlaceholder.setClickable(false); // Null margins on placeholder to avoid inheriting from parent. Margins are applied to container LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layoutParams.setMargins(0, 0, 0, 0); addView(labelPlaceholder, layoutParams); } void initAttrs(Context context, AttributeSet attrs) { if (attrs != null) { TypedArray attributeArray = context.obtainStyledAttributes(attrs, R.styleable.OnusButton); Drawable drawableLeft = null; Drawable drawableRight = null; Drawable drawableBottom = null; Drawable drawableTop = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { drawableLeft = attributeArray.getDrawable(R.styleable.OnusButton_drawableLeftCompat); drawableRight = attributeArray.getDrawable(R.styleable.OnusButton_drawableRightCompat); drawableBottom = attributeArray.getDrawable(R.styleable.OnusButton_drawableBottomCompat); drawableTop = attributeArray.getDrawable(R.styleable.OnusButton_drawableTopCompat); } else { final int drawableLeftId = attributeArray.getResourceId(R.styleable.OnusButton_drawableLeftCompat, -1); final int drawableRightId = attributeArray.getResourceId(R.styleable.OnusButton_drawableRightCompat, -1); final int drawableBottomId = attributeArray.getResourceId(R.styleable.OnusButton_drawableBottomCompat, -1); final int drawableTopId = attributeArray.getResourceId(R.styleable.OnusButton_drawableTopCompat, -1); if (drawableLeftId != -1) drawableLeft = AppCompatResources.getDrawable(context, drawableLeftId); if (drawableRightId != -1) drawableRight = AppCompatResources.getDrawable(context, drawableRightId); if (drawableBottomId != -1) drawableBottom = AppCompatResources.getDrawable(context, drawableBottomId); if (drawableTopId != -1) drawableTop = AppCompatResources.getDrawable(context, drawableTopId); } setCompoundDrawablesWithIntrinsicBounds(drawableLeft, drawableTop, drawableRight, drawableBottom); attributeArray.recycle(); } } public void setLoadingDispatcher(StateDispatcher loadingDispatcher) { this.loadingDispatcher = loadingDispatcher; } public void setLoading(boolean loading) { isLoading = loading; setClickable(!isLoading); if (loading) { startAnimation(); } else { stopAnimation(); } } public boolean isLoading() { return isLoading; } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); if (visibility == VISIBLE) { if (isLoading) { startAnimation(); } else { stopAnimation(); } } } private void startAnimation() { if (getVisibility() != VISIBLE) { return; } loadingDispatcher.dispatchLoadingStart(this, labelPlaceholder, progressBar); } private void stopAnimation() { if (getVisibility() != VISIBLE) { return; } loadingDispatcher.dispatchLoadingStop(this, labelPlaceholder, progressBar); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); adjustProgressBarOnSizeChanged(w, h, oldw, oldh); loadingDispatcher.onSizeChanged(this, labelPlaceholder, progressBar); } // TextView Inherited Methods public TextView getTextLabel() { return labelPlaceholder; } public void setText(CharSequence text) { labelPlaceholder.setText(text); } public CharSequence getText() { return labelPlaceholder.getText(); } public int length() { return labelPlaceholder.length(); } public void setTypeface(Typeface tf, int style) { labelPlaceholder.setTypeface(tf, style); } public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) { labelPlaceholder.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, Drawable right, Drawable bottom) { labelPlaceholder.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom); } // ProgressBar Inherited Methods public ProgressBar getProgressBar() { return progressBar; } }
package org.devgateway.toolkit.persistence.mongo.reader; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.poi.ss.usermodel.DateUtil; import org.devgateway.toolkit.persistence.mongo.spring.VNImportService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.mongodb.repository.MongoRepository; public abstract class RowImporter<T, R extends MongoRepository<T, String>> { private final Logger logger = LoggerFactory.getLogger(VNImportService.class); protected R repository; protected VNImportService importService; protected int skipRows; protected int cursorRowNo = 0; protected int importedRows = 0; protected List<T> documents; public RowImporter(R repository, VNImportService importService, int skipRows) { this.repository = repository; this.importService=importService; documents = new ArrayList<>(); this.skipRows = skipRows; } /** * Returns a double number, checking the {@link NumberFormatException} and * wrapping the error into a {@link RuntimeException} that can be thrown * later * * @param string * @return */ public Double getDouble(String string) { try { return Double.parseDouble(string); } catch (NumberFormatException e) { throw new RuntimeException("Cell value " + string + " is not a valid number."); } } public BigDecimal getDecimal(String string) { try { return new BigDecimal(string); } catch (NumberFormatException e) { throw new RuntimeException("Cell value " + string + " is not a valid decimal."); } } public Integer getInteger(String string) { try { return Integer.parseInt(string); } catch (NumberFormatException e) { throw new RuntimeException("Cell value " + string + " is not a valid integer."); } } public Date getDateFromString(SimpleDateFormat sdf,String string) { try { return sdf.parse(string); } catch (ParseException e) { throw new RuntimeException( "Cell value " + string + " is not a valid date. Use format " + sdf.getNumberFormat().toString()); } } public Date getExcelDate(String string) { try { return DateUtil.getJavaCalendar(Double.parseDouble(string)).getTime(); } catch (NumberFormatException e) { throw new RuntimeException("Cell value " + string + " is not a valid Excel date."); } } private boolean isRowEmpty(String[] row ) { for(int i=0;i<row.length;i++) if(!row[i].trim().isEmpty()) return false; return true; } public boolean importRows(List<String[]> rows) throws ParseException { documents.clear(); for (String[] row : rows) { if (cursorRowNo++ < skipRows || isRowEmpty(row)) continue; try { importRow(row); importedRows++; } catch (Exception e) { importService.logMessage(" <font style='color:red'>Error importing row " + cursorRowNo + ". "+ e+"</font>"); // throw e; we do not stop } } repository.save(documents); logger.debug("Finished importing " + importedRows+" rows."); return true; } public abstract boolean importRow(String[] row) throws ParseException; }
package com.amediamanager.service; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.rds.AmazonRDSClient; import com.amediamanager.config.ConfigurationSettings; @Service public class AwsClientService { @Autowired ConfigurationSettings config; private AmazonDynamoDBClient dynamoDbClient; private AmazonS3Client s3Client; private AmazonRDSClient amazonRdsClient; private AmazonCloudWatchClient cloudWatchClient; private Region region; @PostConstruct public void init() { region = Region.getRegion((Regions.fromName(config.getProperty(ConfigurationSettings.ConfigProps.AWS_REGION)))); // DynamoDB dynamoDbClient = new AmazonDynamoDBClient(); dynamoDbClient.setRegion(region); s3Client = new AmazonS3Client(); s3Client.setRegion(region); // RDS amazonRdsClient = new AmazonRDSClient(); amazonRdsClient.setRegion(region); // CloudWatch cloudWatchClient = new AmazonCloudWatchClient(); cloudWatchClient.setRegion(region); } public AmazonDynamoDBClient getDynamoDbClient() { return dynamoDbClient; } public void setDynamoDbClient(AmazonDynamoDBClient dynamoDbClient) { this.dynamoDbClient = dynamoDbClient; } public AmazonS3Client getS3Client() { return s3Client; } public void setS3Client(AmazonS3Client s3Client) { this.s3Client = s3Client; } public AmazonRDSClient getAmazonRdsClient() { return amazonRdsClient; } public void setAmazonRdsClient(AmazonRDSClient amazonRdsClient) { this.amazonRdsClient = amazonRdsClient; } public AmazonCloudWatchClient getCloudWatchClient() { return cloudWatchClient; } public void setCloudWatchClient(AmazonCloudWatchClient client) { this.cloudWatchClient = client; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } }
package com.yahoo.vespa.flags; import com.yahoo.component.Vtag; import com.yahoo.vespa.defaults.Defaults; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import java.util.TreeMap; import static com.yahoo.vespa.flags.FetchVector.Dimension.APPLICATION_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.CLUSTER_TYPE; import static com.yahoo.vespa.flags.FetchVector.Dimension.HOSTNAME; import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID; import static com.yahoo.vespa.flags.FetchVector.Dimension.VESPA_VERSION; import static com.yahoo.vespa.flags.FetchVector.Dimension.ZONE_ID; /** * Definitions of feature flags. * * <p>To use feature flags, define the flag in this class as an "unbound" flag, e.g. {@link UnboundBooleanFlag} * or {@link UnboundStringFlag}. At the location you want to get the value of the flag, you need the following:</p> * * <ol> * <li>The unbound flag</li> * <li>A {@link FlagSource}. The flag source is typically available as an injectable component. Binding * an unbound flag to a flag source produces a (bound) flag, e.g. {@link BooleanFlag} and {@link StringFlag}.</li> * <li>If you would like your flag value to be dependent on e.g. the application ID, then 1. you should * declare this in the unbound flag definition in this file (referring to * {@link FetchVector.Dimension#APPLICATION_ID}), and 2. specify the application ID when retrieving the value, e.g. * {@link BooleanFlag#with(FetchVector.Dimension, String)}. See {@link FetchVector} for more info.</li> * </ol> * * <p>Once the code is in place, you can override the flag value. This depends on the flag source, but typically * there is a REST API for updating the flags in the config server, which is the root of all flag sources in the zone.</p> * * @author hakonhall */ public class Flags { private static volatile TreeMap<FlagId, FlagDefinition> flags = new TreeMap<>(); public static final UnboundDoubleFlag DEFAULT_TERM_WISE_LIMIT = defineDoubleFlag( "default-term-wise-limit", 1.0, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Default limit for when to apply termwise query evaluation", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag FEED_SEQUENCER_TYPE = defineStringFlag( "feed-sequencer-type", "LATENCY", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for feeding, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundStringFlag RESPONSE_SEQUENCER_TYPE = defineStringFlag( "response-sequencer-type", "ADAPTIVE", List.of("baldersheim"), "2020-12-02", "2022-01-01", "Selects type of sequenced executor used for mbus responses, valid values are LATENCY, ADAPTIVE, THROUGHPUT", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag RESPONSE_NUM_THREADS = defineIntFlag( "response-num-threads", 2, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Number of threads used for mbus responses, default is 2, negative number = numcores/4", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_COMMUNICATIONMANAGER_THREAD = defineFeatureFlag( "skip-communicatiomanager-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the communicationmanager thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REQUEST_THREAD = defineFeatureFlag( "skip-mbus-request-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus request thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag SKIP_MBUS_REPLY_THREAD = defineFeatureFlag( "skip-mbus-reply-thread", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Should we skip the mbus reply thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_THREE_PHASE_UPDATES = defineFeatureFlag( "use-three-phase-updates", false, List.of("vekterli"), "2020-12-02", "2021-08-01", "Whether to enable the use of three-phase updates when bucket replicas are out of sync.", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); // TODO: Remove when models referring to this are gone in all systems public static final UnboundBooleanFlag TENANT_IAM_ROLE = defineFeatureFlag( "application-iam-roles", false, List.of("tokle"), "2020-12-02", "2021-08-01", "Allow separate iam roles when provisioning/assigning hosts", "Takes effect immediately on new hosts, on next redeploy for applications", TENANT_ID); public static final UnboundBooleanFlag HIDE_SHARED_ROUTING_ENDPOINT = defineFeatureFlag( "hide-shared-routing-endpoint", false, List.of("tokle", "bjormel"), "2020-12-02", "2021-09-01", "Whether the controller should hide shared routing layer endpoint", "Takes effect immediately", APPLICATION_ID ); public static final UnboundBooleanFlag USE_ASYNC_MESSAGE_HANDLING_ON_SCHEDULE = defineFeatureFlag( "async-message-handling-on-schedule", false, List.of("baldersheim"), "2020-12-02", "2022-01-01", "Optionally deliver async messages in own thread", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundDoubleFlag FEED_CONCURRENCY = defineDoubleFlag( "feed-concurrency", 0.5, List.of("baldersheim"), "2020-12-02", "2022-01-01", "How much concurrency should be allowed for feed", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag GROUP_SUSPENSION = defineFeatureFlag( "group-suspension", true, List.of("hakon"), "2021-01-22", "2021-08-22", "Allow all content nodes in a hierarchical group to suspend at the same time", "Takes effect on the next suspension request to the Orchestrator.", APPLICATION_ID); public static final UnboundBooleanFlag ENCRYPT_DISK = defineFeatureFlag( "encrypt-disk", false, List.of("hakonhall"), "2021-05-05", "2021-08-05", "Allow migrating an unencrypted data partition to being encrypted.", "Takes effect on next host-admin tick."); public static final UnboundBooleanFlag ENCRYPT_DIRTY_DISK = defineFeatureFlag( "encrypt-dirty-disk", false, List.of("hakonhall"), "2021-05-14", "2021-08-05", "Allow migrating an unencrypted data partition to being encrypted when (de)provisioned.", "Takes effect on next host-admin tick."); public static final UnboundBooleanFlag ENABLE_FEED_BLOCK_IN_DISTRIBUTOR = defineFeatureFlag( "enable-feed-block-in-distributor", true, List.of("geirst"), "2021-01-27", "2021-07-01", "Enables blocking of feed in the distributor if resource usage is above limit on at least one content node", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag METRICS_PROXY_MAX_HEAP_SIZE_IN_MB = defineIntFlag( "metrics-proxy-max-heap-size-in-mb", 256, List.of("hmusum"), "2021-03-01", "2021-07-01", "JVM max heap size for metrics proxy in Mb", "Takes effect when restarting metrics proxy", CLUSTER_TYPE); public static final UnboundStringFlag DEDICATED_CLUSTER_CONTROLLER_FLAVOR = defineStringFlag( "dedicated-cluster-controller-flavor", "", List.of("jonmv"), "2021-02-25", "2021-08-25", "Flavor as <vpu>-<memgb>-<diskgb> to use for dedicated cluster controller nodes", "Takes effect immediately, for subsequent provisioning", APPLICATION_ID); public static final UnboundListFlag<String> ALLOWED_ATHENZ_PROXY_IDENTITIES = defineListFlag( "allowed-athenz-proxy-identities", List.of(), String.class, List.of("bjorncs", "tokle"), "2021-02-10", "2021-08-01", "Allowed Athenz proxy identities", "takes effect at redeployment"); public static final UnboundBooleanFlag GENERATE_NON_MTLS_ENDPOINT = defineFeatureFlag( "generate-non-mtls-endpoint", true, List.of("tokle"), "2021-02-18", "2021-10-01", "Whether to generate the non-mtls endpoint", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag MAX_ACTIVATION_INHIBITED_OUT_OF_SYNC_GROUPS = defineIntFlag( "max-activation-inhibited-out-of-sync-groups", 0, List.of("vekterli"), "2021-02-19", "2021-07-01", "Allows replicas in up to N content groups to not be activated " + "for query visibility if they are out of sync with a majority of other replicas", "Takes effect at redeployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_CUSTOM_ACL_MAPPING = defineFeatureFlag( "enable-custom-acl-mapping", false, List.of("mortent","bjorncs"), "2021-04-13", "2021-08-01", "Whether access control filters should read acl request mapping from handler or use default", "Takes effect at redeployment", APPLICATION_ID); public static final UnboundIntFlag NUM_DISTRIBUTOR_STRIPES = defineIntFlag( "num-distributor-stripes", 0, List.of("geirst", "vekterli"), "2021-04-20", "2021-07-01", "Specifies the number of stripes used by the distributor. When 0, legacy single stripe behavior is used.", "Takes effect after distributor restart", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_CONCURRENT_MERGES_PER_NODE = defineIntFlag( "max-concurrent-merges-per-node", 16, List.of("balder", "vekterli"), "2021-06-06", "2021-08-01", "Specifies max concurrent merges per content node.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundIntFlag MAX_MERGE_QUEUE_SIZE = defineIntFlag( "max-merge-queue-size", 1024, List.of("balder", "vekterli"), "2021-06-06", "2021-08-01", "Specifies max size of merge queue.", "Takes effect at redeploy", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag USE_EXTERNAL_RANK_EXPRESSION = defineFeatureFlag( "use-external-rank-expression", false, List.of("baldersheim"), "2021-05-24", "2021-07-01", "Whether to use distributed external rank expression or inline in rankproperties", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag DISTRIBUTE_EXTERNAL_RANK_EXPRESSION = defineFeatureFlag( "distribute-external-rank-expression", false, List.of("baldersheim"), "2021-05-27", "2021-07-01", "Whether to use distributed external rank expression files by filedistribution", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundIntFlag LARGE_RANK_EXPRESSION_LIMIT = defineIntFlag( "large-rank-expression-limit", 0x10000, List.of("baldersheim"), "2021-06-09", "2021-07-01", "Limit for size of rank expressions distributed by filedistribution", "Takes effect on next internal redeployment", APPLICATION_ID); public static final UnboundBooleanFlag ENABLE_ROUTING_CORE_DUMP = defineFeatureFlag( "enable-routing-core-dumps", false, List.of("tokle"), "2021-04-16", "2021-08-01", "Whether to enable core dumps for routing layer", "Takes effect on next host-admin tick", HOSTNAME); public static final UnboundBooleanFlag CFG_DEPLOY_MULTIPART = defineFeatureFlag( "cfg-deploy-multipart", false, List.of("tokle"), "2021-05-19", "2021-08-01", "Whether to deploy applications using multipart form data (instead of url params)", "Takes effect immediately", APPLICATION_ID); public static final UnboundIntFlag MAX_ENCRYPTING_HOSTS = defineIntFlag( "max-encrypting-hosts", 0, List.of("mpolden", "hakonhall"), "2021-05-27", "2021-10-01", "The maximum number of hosts allowed to encrypt their disk concurrently", "Takes effect on next run of HostEncrypter, but any currently encrypting hosts will not be cancelled when reducing the limit"); public static final UnboundBooleanFlag REQUIRE_CONNECTIVITY_CHECK = defineFeatureFlag( "require-connectivity-check", false, List.of("arnej"), "2021-06-03", "2021-09-01", "Require that config-sentinel connectivity check passes with good quality before starting services", "Takes effect on next restart", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag THROW_EXCEPTION_IF_RESOURCE_LIMITS_SPECIFIED = defineFeatureFlag( "throw-exception-if-resource-limits-specified", false, List.of("hmusum"), "2021-06-07", "2021-08-07", "Whether to throw an exception in hosted Vespa if the application specifies resource limits in services.xml", "Takes effect on next deployment through controller", APPLICATION_ID); public static final UnboundBooleanFlag MOVE_SEARCH_DEFINITIONS_TO_SCHEMAS_DIR = defineFeatureFlag( "move-search-definitions-to-schemas-dir", false, List.of("hmusum"), "2021-06-09", "2021-08-09", "Whether to move files in searchdefinitions/ to schemas/ when deploying an application", "Takes effect on next deployment", ZONE_ID, APPLICATION_ID); public static final UnboundBooleanFlag LOAD_LOCAL_SESSIONS_WHEN_BOOTSTRAPPING = defineFeatureFlag( "load-local-sessions-when-bootstrapping", true, List.of("hmusum"), "2021-06-15", "2021-07-15", "Whether to load local sessions when bootstrapping config server", "Takes effect on restart of config server"); /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundBooleanFlag defineFeatureFlag(String flagId, boolean defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundBooleanFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundStringFlag defineStringFlag(String flagId, String defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundStringFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundIntFlag defineIntFlag(String flagId, int defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundIntFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundLongFlag defineLongFlag(String flagId, long defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundLongFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static UnboundDoubleFlag defineDoubleFlag(String flagId, double defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define(UnboundDoubleFlag::new, flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundJacksonFlag<T> defineJacksonFlag(String flagId, T defaultValue, Class<T> jacksonClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((id2, defaultValue2, vector2) -> new UnboundJacksonFlag<>(id2, defaultValue2, vector2, jacksonClass), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } /** WARNING: public for testing: All flags should be defined in {@link Flags}. */ public static <T> UnboundListFlag<T> defineListFlag(String flagId, List<T> defaultValue, Class<T> elementClass, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension... dimensions) { return define((fid, dval, fvec) -> new UnboundListFlag<>(fid, dval, elementClass, fvec), flagId, defaultValue, owners, createdAt, expiresAt, description, modificationEffect, dimensions); } @FunctionalInterface private interface TypedUnboundFlagFactory<T, U extends UnboundFlag<?, ?, ?>> { U create(FlagId id, T defaultVale, FetchVector defaultFetchVector); } /** * Defines a Flag. * * @param factory Factory for creating unbound flag of type U * @param flagId The globally unique FlagId. * @param defaultValue The default value if none is present after resolution. * @param description Description of how the flag is used. * @param modificationEffect What is required for the flag to take effect? A restart of process? immediately? etc. * @param dimensions What dimensions will be set in the {@link FetchVector} when fetching * the flag value in * {@link FlagSource#fetch(FlagId, FetchVector) FlagSource::fetch}. * For instance, if APPLICATION is one of the dimensions here, you should make sure * APPLICATION is set to the ApplicationId in the fetch vector when fetching the RawFlag * from the FlagSource. * @param <T> The boxed type of the flag value, e.g. Boolean for flags guarding features. * @param <U> The type of the unbound flag, e.g. UnboundBooleanFlag. * @return An unbound flag with {@link FetchVector.Dimension#HOSTNAME HOSTNAME} and * {@link FetchVector.Dimension#VESPA_VERSION VESPA_VERSION} already set. The ZONE environment * is typically implicit. */ private static <T, U extends UnboundFlag<?, ?, ?>> U define(TypedUnboundFlagFactory<T, U> factory, String flagId, T defaultValue, List<String> owners, String createdAt, String expiresAt, String description, String modificationEffect, FetchVector.Dimension[] dimensions) { FlagId id = new FlagId(flagId); FetchVector vector = new FetchVector() .with(HOSTNAME, Defaults.getDefaults().vespaHostname()) // Warning: In unit tests and outside official Vespa releases, the currentVersion is e.g. 7.0.0 // (determined by the current major version). Consider not setting VESPA_VERSION if minor = micro = 0. .with(VESPA_VERSION, Vtag.currentVersion.toFullString()); U unboundFlag = factory.create(id, defaultValue, vector); FlagDefinition definition = new FlagDefinition( unboundFlag, owners, parseDate(createdAt), parseDate(expiresAt), description, modificationEffect, dimensions); flags.put(id, definition); return unboundFlag; } private static Instant parseDate(String rawDate) { return DateTimeFormatter.ISO_DATE.parse(rawDate, LocalDate::from).atStartOfDay().toInstant(ZoneOffset.UTC); } public static List<FlagDefinition> getAllFlags() { return List.copyOf(flags.values()); } public static Optional<FlagDefinition> getFlag(FlagId flagId) { return Optional.ofNullable(flags.get(flagId)); } /** * Allows the statically defined flags to be controlled in a test. * * <p>Returns a Replacer instance to be used with e.g. a try-with-resources block. Within the block, * the flags starts out as cleared. Flags can be defined, etc. When leaving the block, the flags from * before the block is reinserted. * * <p>NOT thread-safe. Tests using this cannot run in parallel. */ public static Replacer clearFlagsForTesting() { return new Replacer(); } public static class Replacer implements AutoCloseable { private static volatile boolean flagsCleared = false; private final TreeMap<FlagId, FlagDefinition> savedFlags; private Replacer() { verifyAndSetFlagsCleared(true); this.savedFlags = Flags.flags; Flags.flags = new TreeMap<>(); } @Override public void close() { verifyAndSetFlagsCleared(false); Flags.flags = savedFlags; } /** * Used to implement a simple verification that Replacer is not used by multiple threads. * For instance two different tests running in parallel cannot both use Replacer. */ private static void verifyAndSetFlagsCleared(boolean newValue) { if (flagsCleared == newValue) { throw new IllegalStateException("clearFlagsForTesting called while already cleared - running tests in parallell!?"); } flagsCleared = newValue; } } }
package com.malhartech.stram; import com.malhartech.api.Operator.InputPort; import com.malhartech.api.Operator.OutputPort; import com.malhartech.api.Operator.Unifier; import com.malhartech.api.*; import com.malhartech.bufferserver.server.Server; import com.malhartech.bufferserver.storage.DiskStorage; import com.malhartech.bufferserver.util.Codec; import com.malhartech.engine.Operators.PortMappingDescriptor; import com.malhartech.engine.*; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat.DNodeState; import com.malhartech.stream.*; import com.malhartech.util.AttributeMap; import com.malhartech.util.ScheduledThreadPoolExecutor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.PrivilegedExceptionAction; import java.util.Map.Entry; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import malhar.netlet.DefaultEventLoop; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.log4j.LogManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * The main() for streaming container processes launched by {@link com.malhartech.stram.StramAppMaster}.<p> * <br> * */ public class StramChild { private static final Logger logger = LoggerFactory.getLogger(StramChild.class); private static final String NODE_PORT_SPLIT_SEPARATOR = "\\."; public static final String NODE_PORT_CONCAT_SEPARATOR = "."; private static final int SPIN_MILLIS = 20; private final String containerId; private final Configuration conf; private final StreamingContainerUmbilicalProtocol umbilical; protected final Map<Integer, Node<?>> nodes = new ConcurrentHashMap<Integer, Node<?>>(); private final Map<String, ComponentContextPair<Stream<Object>, StreamContext>> streams = new ConcurrentHashMap<String, ComponentContextPair<Stream<Object>, StreamContext>>(); protected final Map<Integer, WindowGenerator> generators = new ConcurrentHashMap<Integer, WindowGenerator>(); protected final Map<Integer, OperatorContext> activeNodes = new ConcurrentHashMap<Integer, OperatorContext>(); private final Map<Stream<?>, StreamContext> activeStreams = new ConcurrentHashMap<Stream<?>, StreamContext>(); private final Map<WindowGenerator, Object> activeGenerators = new ConcurrentHashMap<WindowGenerator, Object>(); private int heartbeatIntervalMillis = 1000; private volatile boolean exitHeartbeatLoop = false; private final Object heartbeatTrigger = new Object(); private String checkpointFsPath; private String appPath; public static final DefaultEventLoop eventloop; static { try { eventloop = new DefaultEventLoop("alone"); } catch (IOException io) { throw new RuntimeException(io); } } /** * Map of last backup window id that is used to communicate checkpoint state back to Stram. TODO: Consider adding this to the node context instead. */ private final Map<Integer, Long> backupInfo = new ConcurrentHashMap<Integer, Long>(); private long firstWindowMillis; private int windowWidthMillis; private InetSocketAddress bufferServerAddress; private com.malhartech.bufferserver.server.Server bufferServer; private AttributeMap<DAGContext> applicationAttributes; protected HashMap<Integer, TupleRecorder> tupleRecorders = new HashMap<Integer, TupleRecorder>(); private int tupleRecordingPartFileSize; protected StramChild(String containerId, Configuration conf, StreamingContainerUmbilicalProtocol umbilical) { logger.debug("instantiated StramChild {}", containerId); this.umbilical = umbilical; this.containerId = containerId; this.conf = conf; } public void setup(StreamingContainerContext ctx) { this.applicationAttributes = ctx.applicationAttributes; heartbeatIntervalMillis = ctx.applicationAttributes.attrValue(DAG.STRAM_HEARTBEAT_INTERVAL_MILLIS, 1000); firstWindowMillis = ctx.startWindowMillis; windowWidthMillis = ctx.applicationAttributes.attrValue(DAG.STRAM_WINDOW_SIZE_MILLIS, 500); this.checkpointFsPath = ctx.applicationAttributes.attrValue(DAG.STRAM_CHECKPOINT_DIR, "checkpoint-dfs-path-not-configured"); this.appPath = ctx.applicationAttributes.attrValue(DAG.STRAM_APP_PATH, "app-dfs-path-not-configured"); this.tupleRecordingPartFileSize = ctx.applicationAttributes.attrValue(DAG.STRAM_TUPLE_RECORDING_PART_FILE_SIZE, 100 * 1024); try { if (ctx.deployBufferServer) { // start buffer server, if it was not set externally bufferServer = new Server(0, 64 * 1024 * 1024, 8); bufferServer.setSpoolStorage(new DiskStorage()); SocketAddress bindAddr = bufferServer.run(); logger.info("Buffer server started: {}", bindAddr); this.bufferServerAddress = NetUtils.getConnectAddress(((InetSocketAddress)bindAddr)); } } catch (Exception ex) { logger.warn("deploy request failed due to {}", ex); throw new IllegalStateException("Failed to deploy buffer server", ex); } } public String getContainerId() { return this.containerId; } public TupleRecorder getTupleRecorder(int operId) { return tupleRecorders.get(operId); } /** * Initialize container. Establishes heartbeat connection to the master * process through the callback address provided on the command line. Deploys * initial modules, then enters the heartbeat loop, which will only terminate * once container receives shutdown request from the master. On shutdown, * after exiting heartbeat loop, deactivate all modules and terminate * processing threads. * * @param args * @throws Throwable */ public static void main(String[] args) throws Throwable { logger.info("Child starting with classpath: {}", System.getProperty("java.class.path")); final Configuration defaultConf = new Configuration(); //defaultConf.addResource(MRJobConfig.JOB_CONF_FILE); UserGroupInformation.setConfiguration(defaultConf); String host = args[0]; int port = Integer.parseInt(args[1]); final InetSocketAddress address = NetUtils.createSocketAddrForHost(host, port); final String childId = System.getProperty("stram.cid"); //Token<JobTokenIdentifier> jt = loadCredentials(defaultConf, address); // Communicate with parent as actual task owner. UserGroupInformation taskOwner = UserGroupInformation.createRemoteUser(StramChild.class.getName()); //taskOwner.addToken(jt); final StreamingContainerUmbilicalProtocol umbilical = taskOwner.doAs(new PrivilegedExceptionAction<StreamingContainerUmbilicalProtocol>() { @Override public StreamingContainerUmbilicalProtocol run() throws Exception { return RPC.getProxy(StreamingContainerUmbilicalProtocol.class, StreamingContainerUmbilicalProtocol.versionID, address, defaultConf); } }); logger.debug("PID: " + System.getenv().get("JVM_PID")); UserGroupInformation childUGI; int exitStatus = 1; try { childUGI = UserGroupInformation.createRemoteUser(System.getenv(ApplicationConstants.Environment.USER.toString())); // Add tokens to new user so that it may execute its task correctly. for (Token<?> token : UserGroupInformation.getCurrentUser().getTokens()) { childUGI.addToken(token); } childUGI.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { StreamingContainerContext ctx = umbilical.getInitContext(childId); StramChild stramChild = new StramChild(childId, defaultConf, umbilical); logger.debug("Got context: " + ctx); stramChild.setup(ctx); try { // main thread enters heartbeat loop stramChild.monitorHeartbeat(); } finally { // teardown stramChild.teardown(); } return null; } }); exitStatus = 0; } catch (Exception exception) { logger.warn("Exception running child : " + StringUtils.stringifyException(exception)); // Report back any failures, for diagnostic purposes ByteArrayOutputStream baos = new ByteArrayOutputStream(); exception.printStackTrace(new PrintStream(baos)); umbilical.log(childId, "FATAL: " + baos.toString()); } catch (Throwable throwable) { logger.error("Error running child : " + StringUtils.stringifyException(throwable)); Throwable tCause = throwable.getCause(); String cause = tCause == null ? throwable.getMessage() : StringUtils.stringifyException(tCause); umbilical.log(childId, cause); } finally { RPC.stopProxy(umbilical); DefaultMetricsSystem.shutdown(); // Shutting down log4j of the child-vm... // This assumes that on return from Task.activate() // there is no more logging done. LogManager.shutdown(); } if (exitStatus != 0) { System.exit(exitStatus); } } public synchronized void deactivate() { ArrayList<Thread> activeThreads = new ArrayList<Thread>(); ArrayList<Integer> activeOperators = new ArrayList<Integer>(); for (Entry<Integer, Node<?>> e : nodes.entrySet()) { OperatorContext oc = activeNodes.get(e.getKey()); if (oc == null) { disconnectNode(e.getKey()); } else { activeThreads.add(oc.getThread()); activeOperators.add(e.getKey()); e.getValue().deactivate(); } } try { Iterator<Integer> iterator = activeOperators.iterator(); for (Thread t : activeThreads) { t.join(); disconnectNode(iterator.next()); } assert (activeNodes.isEmpty()); } catch (InterruptedException ex) { logger.info("Aborting wait for for operators to get deactivated as got interrupted with {}", ex); } for (WindowGenerator wg : activeGenerators.keySet()) { wg.deactivate(); } activeGenerators.clear(); for (Stream<?> stream : activeStreams.keySet()) { stream.deactivate(); } activeStreams.clear(); } private void disconnectNode(int nodeid) { Node<?> node = nodes.get(nodeid); disconnectWindowGenerator(nodeid, node); Set<String> removableStreams = new HashSet<String>(); // temporary fix - find out why List does not work. // with the logic i have in here, the list should not contain repeated streams. but it does and that causes problem. for (Entry<String, ComponentContextPair<Stream<Object>, StreamContext>> entry : streams.entrySet()) { String indexingKey = entry.getKey(); Stream<?> stream = entry.getValue().component; StreamContext context = entry.getValue().context; String sourceIdentifier = context.getSourceId(); String sinkIdentifier = context.getSinkId(); logger.debug("considering stream {} against id {}", stream, indexingKey); if (nodeid == Integer.parseInt(sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR)[0])) { /* * the stream originates at the output port of one of the operators that are going to vanish. */ if (activeStreams.containsKey(stream)) { logger.debug("deactivating {}", stream); stream.deactivate(); activeStreams.remove(stream); } removableStreams.add(sourceIdentifier); String[] sinkIds = sinkIdentifier.split(", "); for (String sinkId : sinkIds) { if (!sinkId.startsWith("tcp: String[] nodeport = sinkId.split(NODE_PORT_SPLIT_SEPARATOR); Node<?> n = nodes.get(Integer.parseInt(nodeport[0])); if (n instanceof UnifierNode) { n.connectInputPort(nodeport[1] + "(" + sourceIdentifier + ")", null, null); } else if (n != null) { // check why null pointer exception gets thrown here during shutdown! - chetan n.connectInputPort(nodeport[1], null, null); } } else if (stream.isMultiSinkCapable()) { ComponentContextPair<Stream<Object>, StreamContext> spair = streams.get(sinkId); logger.debug("found stream {} against {}", spair == null ? null : spair.component, sinkId); if (spair == null) { assert (!sinkId.startsWith("tcp: } else { assert (sinkId.startsWith("tcp: if (activeStreams.containsKey(spair.component)) { logger.debug("deactivating {} for sink {}", spair.component, sinkId); spair.component.deactivate(); activeStreams.remove(spair.component); } removableStreams.add(sinkId); } } } } else { /** * the stream may or may not feed into one of the operators which are being undeployed. */ String[] sinkIds = sinkIdentifier.split(", "); for (int i = sinkIds.length; i String[] nodeport = sinkIds[i].split(NODE_PORT_SPLIT_SEPARATOR); if (Integer.toString(nodeid).equals(nodeport[0])) { stream.setSink(sinkIds[i], null); if (node instanceof UnifierNode) { node.connectInputPort(nodeport[1] + "(" + sourceIdentifier + ")", null, null); } else { node.connectInputPort(nodeport[1], null, null); } sinkIds[i] = null; } } String sinkId = null; for (int i = sinkIds.length; i if (sinkIds[i] != null) { if (sinkId == null) { sinkId = sinkIds[i]; } else { sinkId = sinkId.concat(", ").concat(sinkIds[i]); } } } if (sinkId == null) { if (activeStreams.containsKey(stream)) { logger.debug("deactivating {}", stream); stream.deactivate(); activeStreams.remove(stream); } removableStreams.add(indexingKey); } else { // may be we should also check if the count has changed from something to 1 // and replace mux with 1:1 sink. it's not necessary though. context.setSinkId(sinkId); } } } for (String streamId : removableStreams) { logger.debug("removing stream {}", streamId); // need to check why control comes here twice to remove the stream which was deleted before. // is it because of multiSinkCapableStream ? ComponentContextPair<Stream<Object>, StreamContext> pair = streams.remove(streamId); pair.component.teardown(); } } private void disconnectWindowGenerator(int nodeid, Node<?> node) { WindowGenerator chosen1 = generators.remove(nodeid); if (chosen1 != null) { chosen1.setSink(Integer.toString(nodeid).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT), null); node.connectInputPort(Node.INPUT, null, null); int count = 0; for (WindowGenerator wg : generators.values()) { if (chosen1 == wg) { count++; } } if (count == 0) { activeGenerators.remove(chosen1); chosen1.deactivate(); chosen1.teardown(); } } } private synchronized void undeploy(List<OperatorDeployInfo> nodeList) { logger.info("got undeploy request {}", nodeList); /** * make sure that all the operators which we are asked to undeploy are in this container. */ HashMap<Integer, Node<?>> toUndeploy = new HashMap<Integer, Node<?>>(); for (OperatorDeployInfo ndi : nodeList) { Node<?> node = nodes.get(ndi.id); if (node == null) { throw new IllegalArgumentException("Node " + ndi.id + " is not hosted in this container!"); } else if (toUndeploy.containsKey(ndi.id)) { throw new IllegalArgumentException("Node " + ndi.id + " is requested to be undeployed more than once"); } else { toUndeploy.put(ndi.id, node); } } // track all the ids to undeploy // track the ones which are active ArrayList<Thread> joinList = new ArrayList<Thread>(); ArrayList<Integer> discoList = new ArrayList<Integer>(); for (OperatorDeployInfo ndi : nodeList) { OperatorContext oc = activeNodes.get(ndi.id); if (oc == null) { disconnectNode(ndi.id); } else { joinList.add(oc.getThread()); discoList.add(ndi.id); nodes.get(ndi.id).deactivate(); } } try { Iterator<Integer> iterator = discoList.iterator(); for (Thread t : joinList) { t.join(); disconnectNode(iterator.next()); } logger.info("undeploy complete"); } catch (InterruptedException ex) { logger.warn("Aborted waiting for the deactivate to finish!"); } for (OperatorDeployInfo ndi : nodeList) { nodes.remove(ndi.id); } } public void teardown() { deactivate(); assert (streams.isEmpty()); nodes.clear(); HashSet<WindowGenerator> gens = new HashSet<WindowGenerator>(); gens.addAll(generators.values()); generators.clear(); for (WindowGenerator wg : gens) { wg.teardown(); } if (bufferServer != null) { bufferServer.shutdown(); } gens.clear(); } protected void triggerHeartbeat() { synchronized (heartbeatTrigger) { heartbeatTrigger.notifyAll(); } } protected void monitorHeartbeat() throws IOException { umbilical.log(containerId, "[" + containerId + "] Entering heartbeat loop.."); logger.debug("Entering heartbeat loop (interval is {} ms)", this.heartbeatIntervalMillis); while (!exitHeartbeatLoop) { synchronized (this.heartbeatTrigger) { try { this.heartbeatTrigger.wait(heartbeatIntervalMillis); } catch (InterruptedException e1) { logger.warn("Interrupted in heartbeat loop, exiting.."); break; } } long currentTime = System.currentTimeMillis(); ContainerHeartbeat msg = new ContainerHeartbeat(); msg.setContainerId(this.containerId); if (this.bufferServerAddress != null) { msg.bufferServerHost = this.bufferServerAddress.getHostName(); msg.bufferServerPort = this.bufferServerAddress.getPort(); } List<StreamingNodeHeartbeat> heartbeats = new ArrayList<StreamingNodeHeartbeat>(nodes.size()); // gather heartbeat info for all operators for (Map.Entry<Integer, Node<?>> e : nodes.entrySet()) { StreamingNodeHeartbeat hb = new StreamingNodeHeartbeat(); hb.setNodeId(e.getKey()); hb.setGeneratedTms(currentTime); hb.setIntervalMs(heartbeatIntervalMillis); if (activeNodes.containsKey(e.getKey())) { activeNodes.get(e.getKey()).drainHeartbeatCounters(hb.getWindowStats()); hb.setState(DNodeState.ACTIVE.toString()); } else { hb.setState(e.getValue().isAlive() ? DNodeState.FAILED.toString() : DNodeState.IDLE.toString()); } // propagate the backup window, if any Long backupWindowId = backupInfo.get(e.getKey()); if (backupWindowId != null) { hb.setLastBackupWindowId(backupWindowId); } TupleRecorder tupleRecorder = tupleRecorders.get(e.getKey()); if (tupleRecorder == null) { hb.setRecordingName(null); } else { hb.setRecordingName(tupleRecorder.getRecordingName()); } heartbeats.add(hb); } msg.setDnodeEntries(heartbeats); // heartbeat call and follow-up processing //logger.debug("Sending heartbeat for {} operators.", msg.getDnodeEntries().size()); try { ContainerHeartbeatResponse rsp = umbilical.processHeartbeat(msg); if (rsp != null) { processHeartbeatResponse(rsp); // keep polling at smaller interval if work is pending while (rsp != null && rsp.hasPendingRequests) { logger.info("Waiting for pending request."); synchronized (this.heartbeatTrigger) { try { this.heartbeatTrigger.wait(500); } catch (InterruptedException e1) { logger.warn("Interrupted in heartbeat loop, exiting.."); break; } } rsp = umbilical.pollRequest(this.containerId); if (rsp != null) { processHeartbeatResponse(rsp); } } } } catch (Exception e) { logger.warn("Exception received (may be during shutdown?)", e); } } logger.debug("Exiting hearbeat loop"); umbilical.log(containerId, "[" + containerId + "] Exiting heartbeat loop.."); } protected void processHeartbeatResponse(ContainerHeartbeatResponse rsp) { if (rsp.shutdown) { logger.info("Received shutdown request"); this.exitHeartbeatLoop = true; return; } if (rsp.undeployRequest != null) { logger.info("Undeploy request: {}", rsp.undeployRequest); undeploy(rsp.undeployRequest); } if (rsp.deployRequest != null) { logger.info("Deploy request: {}", rsp.deployRequest); try { deploy(rsp.deployRequest); } catch (Exception e) { logger.error("deploy request failed due to {}", e); // TODO: report it to stram? try { umbilical.log(this.containerId, "deploy request failed: " + rsp.deployRequest + " " + ExceptionUtils.getStackTrace(e)); } catch (IOException ioe) { // ignore } this.exitHeartbeatLoop = true; throw new IllegalStateException("Deploy request failed: " + rsp.deployRequest, e); } } if (rsp.nodeRequests != null) { // processing of per operator requests for (StramToNodeRequest req : rsp.nodeRequests) { OperatorContext nc = activeNodes.get(req.getNodeId()); if (nc == null) { logger.warn("Received request with invalid node id {} ({})", req.getNodeId(), req); } else { logger.debug("Stram request: {}", req); processStramRequest(nc, req); } } } } /** * Process request from stram for further communication through the protocol. Extended reporting is on a per node basis (won't occur under regular operation) * * @param n * @param snr */ private void processStramRequest(OperatorContext context, final StramToNodeRequest snr) { int operatorId = snr.getNodeId(); final Node<?> node = nodes.get(operatorId); final String name = snr.getName(); switch (snr.getRequestType()) { case REPORT_PARTION_STATS: logger.warn("Ignoring stram request {}", snr); break; case CHECKPOINT: context.request(new OperatorContext.NodeRequest() { @Override public void execute(Operator operator, int id, long windowId) throws IOException { new HdfsBackupAgent(StramChild.this.conf, StramChild.this.checkpointFsPath).backup(id, windowId, operator, StramUtils.getNodeSerDe(null)); // record last backup window id for heartbeat StramChild.this.backupInfo.put(id, windowId); node.emitCheckpoint(windowId); if (operator instanceof CheckpointListener) { ((CheckpointListener)operator).checkpointed(windowId); ((CheckpointListener)operator).committed(snr.getRecoveryCheckpoint()); } } }); break; case START_RECORDING: logger.debug("Received start recording request for " + operatorId + " with name " + name); if (!tupleRecorders.containsKey(operatorId)) { context.request(new OperatorContext.NodeRequest() { @Override public void execute(Operator operator, int operatorId, long windowId) throws IOException { logger.debug("Executing start recording request for " + operatorId); TupleRecorder tupleRecorder = tupleRecorders.get(operatorId); if (tupleRecorder == null) { tupleRecorder = new TupleRecorder(); String basePath = StramChild.this.appPath + "/recordings/" + operatorId + "/" + tupleRecorder.getStartTime(); if (name != null && !name.isEmpty()) { tupleRecorder.setRecordingName(name); } else { String defaultName = StramChild.this.containerId + "_" + operatorId + "_" + tupleRecorder.getStartTime(); tupleRecorder.setRecordingName(defaultName); } tupleRecorder.setBasePath(basePath); tupleRecorder.setBytesPerPartFile(StramChild.this.tupleRecordingPartFileSize); HashMap<String, Sink<Object>> sinkMap = new HashMap<String, Sink<Object>>(); PortMappingDescriptor descriptor = node.getPortMappingDescriptor(); for (Map.Entry<String, InputPort<?>> entry : descriptor.inputPorts.entrySet()) { String streamId = getDeclaredStreamId(operatorId, entry.getKey()); if (streamId != null) { logger.info("Adding recorder sink to input port {}, stream {}", entry.getKey(), streamId); tupleRecorder.addInputPortInfo(entry.getKey(), streamId); sinkMap.put(entry.getKey(), tupleRecorder.newSink(entry.getKey())); } } for (Map.Entry<String, OutputPort<?>> entry : descriptor.outputPorts.entrySet()) { String streamId = getDeclaredStreamId(operatorId, entry.getKey()); if (streamId != null) { logger.info("Adding recorder sink to output port {}, stream {}", entry.getKey(), streamId); tupleRecorder.addOutputPortInfo(entry.getKey(), streamId); sinkMap.put(entry.getKey(), tupleRecorder.newSink(entry.getKey())); } } logger.debug("Started recording to base path " + basePath); node.addSinks(sinkMap); tupleRecorder.setup(null); tupleRecorders.put(operatorId, tupleRecorder); } } }); } else { logger.error("(START_RECORDING) Operator id " + operatorId + " is already being recorded."); } break; case STOP_RECORDING: logger.debug("Received stop recording request for " + operatorId); if (tupleRecorders.containsKey(operatorId)) { context.request(new OperatorContext.NodeRequest() { @Override public void execute(Operator operator, int operatorId, long windowId) throws IOException { logger.debug("Executing stop recording request for " + operatorId); TupleRecorder tupleRecorder = tupleRecorders.get(operatorId); if (tupleRecorder != null) { node.removeSinks(tupleRecorder.getSinkMap()); tupleRecorder.teardown(); logger.debug("Stopped recording for operator id " + operatorId); tupleRecorders.remove(operatorId); } } }); } else { logger.error("(STOP_RECORDING) Operator id " + operatorId + " is not being recorded."); } break; default: logger.error("Unknown request from stram {}", snr); } } private synchronized void deploy(List<OperatorDeployInfo> nodeList) throws Exception { /* * A little bit of up front sanity check would reduce the percentage of deploy failures later. */ for (OperatorDeployInfo ndi : nodeList) { if (nodes.containsKey(ndi.id)) { throw new IllegalStateException("Node with id: " + ndi.id + " already present in the container"); } } deployNodes(nodeList); HashMap<String, ArrayList<String>> groupedInputStreams = new HashMap<String, ArrayList<String>>(); for (OperatorDeployInfo ndi : nodeList) { groupInputStreams(groupedInputStreams, ndi); } deployOutputStreams(nodeList, groupedInputStreams); deployInputStreams(nodeList); activate(nodeList); } private void massageUnifierDeployInfo(OperatorDeployInfo odi) { for (OperatorDeployInfo.InputDeployInfo idi : odi.inputs) { idi.portName += "(" + idi.sourceNodeId + NODE_PORT_CONCAT_SEPARATOR + idi.sourcePortName + ")"; } } @SuppressWarnings("unchecked") private void deployNodes(List<OperatorDeployInfo> nodeList) throws Exception { OperatorCodec operatorSerDe = StramUtils.getNodeSerDe(null); BackupAgent backupAgent = new HdfsBackupAgent(this.conf, this.checkpointFsPath); for (OperatorDeployInfo ndi : nodeList) { try { final Object foreignObject; if (ndi.checkpointWindowId > 0) { logger.debug("Restoring node {} to checkpoint {}", ndi.id, Codec.getStringWindowId(ndi.checkpointWindowId)); foreignObject = backupAgent.restore(ndi.id, ndi.checkpointWindowId, operatorSerDe); } else { foreignObject = operatorSerDe.read(new ByteArrayInputStream(ndi.serializedNode)); } String nodeid = Integer.toString(ndi.id).concat("/").concat(ndi.declaredId).concat(":").concat(foreignObject.getClass().getSimpleName()); if (foreignObject instanceof InputOperator && ndi.type == OperatorDeployInfo.OperatorType.INPUT) { nodes.put(ndi.id, new InputNode(nodeid, (InputOperator)foreignObject)); } else if (foreignObject instanceof Unifier && ndi.type == OperatorDeployInfo.OperatorType.UNIFIER) { nodes.put(ndi.id, new UnifierNode(nodeid, (Unifier<Object>)foreignObject)); massageUnifierDeployInfo(ndi); } else { nodes.put(ndi.id, new GenericNode(nodeid, (Operator)foreignObject)); } } catch (Exception e) { logger.error(e.getLocalizedMessage()); throw e; } } } private void deployOutputStreams(List<OperatorDeployInfo> nodeList, HashMap<String, ArrayList<String>> groupedInputStreams) throws Exception { /* * We proceed to deploy all the output streams. At the end of this block, our streams collection * will contain all the streams which originate at the output port of the operators. The streams * are generally mapped against the "nodename.portname" string. But the BufferOutputStreams which * share the output port with other inline streams are mapped against the Buffer Server port to * avoid collision and at the same time keep track of these buffer streams. */ for (OperatorDeployInfo ndi : nodeList) { Node<?> node = nodes.get(ndi.id); for (OperatorDeployInfo.OutputDeployInfo nodi : ndi.outputs) { String sourceIdentifier = Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nodi.portName); String sinkIdentifier; StreamContext context = new StreamContext(nodi.declaredStreamId); Stream<Object> stream; ArrayList<String> collection = groupedInputStreams.get(sourceIdentifier); if (collection == null) { /* * Let's create a stream to carry the data to the Buffer Server. * Nobody in this container is interested in the output placed on this stream, but * this stream exists. That means someone outside of this container must be interested. */ assert (nodi.isInline() == false); context.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort)); if (NetUtils.isLocalAddress(context.getBufferServerAddress().getAddress())) { context.setBufferServerAddress(new InetSocketAddress(InetAddress.getByName(null), nodi.bufferServerPort)); } stream = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName)); stream.setup(context); logger.debug("deployed a buffer stream {}", stream); sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier); } else if (collection.size() == 1) { if (nodi.isInline()) { /** * Let's create an inline stream to carry data from output port to input port of some other node. * There is only one node interested in output placed on this stream, and that node is in this container. */ stream = new InlineStream(); stream.setup(context); sinkIdentifier = null; } else { /** * Let's create 2 streams: 1 inline and 1 going to the Buffer Server. * Although there is a node in this container interested in output placed on this stream, there * seems to at least one more party interested but placed in a container other than this one. */ sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier); StreamContext bssc = new StreamContext(nodi.declaredStreamId); bssc.setSourceId(sourceIdentifier); bssc.setSinkId(sinkIdentifier); bssc.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort)); BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName)); bsos.setup(bssc); logger.debug("deployed a buffer stream {}", bsos); streams.put(sinkIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(bsos, bssc)); // should we create inline stream here or wait for the input deployments to create the inline streams? stream = new MuxStream(); stream.setup(context); stream.setSink(sinkIdentifier, bsos); logger.debug("stored stream {} against key {}", bsos, sinkIdentifier); } } else { /** * Since there are multiple parties interested in this node itself, we are going to come * to this block multiple times. The actions we take subsequent times are going to be different * than the first time. We create the MuxStream only the first time. */ ComponentContextPair<Stream<Object>, StreamContext> pair = streams.get(sourceIdentifier); if (pair == null) { /** * Let's multiplex the output placed on this stream. * This container itself contains more than one parties interested. */ stream = new MuxStream(); stream.setup(context); } else { stream = pair.component; } if (nodi.isInline()) { sinkIdentifier = null; } else { sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier); StreamContext bssc = new StreamContext(nodi.declaredStreamId); bssc.setSourceId(sourceIdentifier); bssc.setSinkId(sinkIdentifier); bssc.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint bssc.setBufferServerAddress(InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort)); BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName)); bsos.setup(bssc); logger.debug("deployed a buffer stream {}", bsos); streams.put(sinkIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(bsos, bssc)); logger.debug("stored stream {} against key {}", bsos, sinkIdentifier); stream.setup(context); stream.setSink(sinkIdentifier, bsos); } } if (!streams.containsKey(sourceIdentifier)) { node.connectOutputPort(nodi.portName, nodi.contextAttributes, stream); context.setSourceId(sourceIdentifier); context.setSinkId(sinkIdentifier); context.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint streams.put(sourceIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(stream, context)); logger.debug("stored stream {} against key {}", stream, sourceIdentifier); } } } } /** * If the port is connected, find return the declared stream Id. * * @param operatorId id of the operator to which the port belongs. * @param portname name of port to which the stream is connected. * @return Stream Id if connected, null otherwise. */ public final String getDeclaredStreamId(int operatorId, String portname) { String identifier = String.valueOf(operatorId).concat(NODE_PORT_CONCAT_SEPARATOR).concat(portname); ComponentContextPair<Stream<Object>, StreamContext> spair = streams.get(identifier); if (spair == null) { return null; } return spair.context.getId(); } private void deployInputStreams(List<OperatorDeployInfo> nodeList) throws Exception { // collect any input operators along with their smallest window id, // those are subsequently used to setup the window generator ArrayList<OperatorDeployInfo> inputNodes = new ArrayList<OperatorDeployInfo>(); long smallestCheckpointedWindowId = Long.MAX_VALUE; /* * Hook up all the downstream ports. There are 2 places where we deal with more than 1 * downstream ports. The first one follows immediately for WindowGenerator. The second * case is when source for the input port of some node in this container is in another * container. So we need to create the stream. We need to track this stream along with * other streams,and many such streams may exist, we hash them against buffer server * info as we did for outputs but throw in the sinkid in the mix as well. */ for (OperatorDeployInfo ndi : nodeList) { if (ndi.inputs == null || ndi.inputs.isEmpty()) { /** * This has to be InputNode, so let's hook the WindowGenerator to it. * A node which does not take any input cannot exist in the DAG since it would be completely * unaware of the windows. So for that reason, AbstractInputNode allows Component.INPUT port. */ inputNodes.add(ndi); /* * When we activate the window Generator, we plan to activate it only from required windowId. */ if (ndi.checkpointWindowId < smallestCheckpointedWindowId) { smallestCheckpointedWindowId = ndi.checkpointWindowId; } } else { Node<?> node = nodes.get(ndi.id); for (OperatorDeployInfo.InputDeployInfo nidi : ndi.inputs) { String sourceIdentifier = Integer.toString(nidi.sourceNodeId).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName); String sinkIdentifier = Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName); ComponentContextPair<Stream<Object>, StreamContext> pair = streams.get(sourceIdentifier); if (pair == null) { /* * We connect to the buffer server for the input on this port. * We have already placed all the output streams for all the operators in this container. * Yet, there is no stream which can source this port so it has to come from the buffer * server, so let's make a connection to it. */ assert (nidi.isInline() == false); StreamContext context = new StreamContext(nidi.declaredStreamId); context.setPartitions(nidi.partitionMask, nidi.partitionKeys); context.setSourceId(sourceIdentifier); context.setSinkId(sinkIdentifier); context.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint context.setBufferServerAddress(InetSocketAddress.createUnresolved(nidi.bufferServerHost, nidi.bufferServerPort)); @SuppressWarnings("unchecked") Stream<Object> stream = (Stream)new BufferServerInputStream(StramUtils.getSerdeInstance(nidi.serDeClassName)); stream.setup(context); logger.debug("deployed buffer input stream {}", stream); Sink<Object> s = node.connectInputPort(nidi.portName, nidi.contextAttributes, stream); stream.setSink(sinkIdentifier, ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(stream, sinkIdentifier, s, ndi.checkpointWindowId) : s); streams.put(sinkIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(stream, context)); logger.debug("put input stream {} against key {}", stream, sinkIdentifier); } else { String streamSinkId = pair.context.getSinkId(); Sink<Object> s; if (streamSinkId == null) { s = node.connectInputPort(nidi.portName, nidi.contextAttributes, pair.component); pair.context.setSinkId(sinkIdentifier); } else if (pair.component.isMultiSinkCapable()) { s = node.connectInputPort(nidi.portName, nidi.contextAttributes, pair.component); pair.context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier)); } else { /** * we are trying to tap into existing InlineStream or BufferServerOutputStream. * Since none of those streams are MultiSinkCapable, we need to replace them with Mux. */ StreamContext context = new StreamContext(nidi.declaredStreamId); context.setSourceId(sourceIdentifier); context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier)); context.setStartingWindowId(ndi.checkpointWindowId > 0 ? ndi.checkpointWindowId + 1 : 0); // TODO: next window after checkpoint Stream<Object> stream = new MuxStream(); stream.setup(context); logger.debug("deployed input mux stream {}", stream); s = node.connectInputPort(nidi.portName, nidi.contextAttributes, stream); streams.put(sourceIdentifier, new ComponentContextPair<Stream<Object>, StreamContext>(stream, context)); logger.debug("stored input stream {} against key {}", stream, sourceIdentifier); /** * Lets wire the MuxStream to upstream node. */ String[] nodeport = sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR); Node<?> upstreamNode = nodes.get(Integer.parseInt(nodeport[0])); upstreamNode.connectOutputPort(nodeport[1], nidi.contextAttributes, stream); Sink<Object> existingSink; if (pair.component instanceof InlineStream) { String[] np = streamSinkId.split(NODE_PORT_SPLIT_SEPARATOR); Node<?> anotherNode = nodes.get(Integer.parseInt(np[0])); existingSink = anotherNode.connectInputPort(np[1], nidi.contextAttributes, stream); // the context object here is probably wrong /* * we do not need to do this but looks bad if leave it in limbo. */ pair.component.deactivate(); pair.component.teardown(); } else { existingSink = pair.component; /* * we got this stream since it was mapped against sourceId, but since * we took that place for MuxStream, we give this a new place of its own. */ streams.put(pair.context.getSinkId(), pair); logger.debug("relocated stream {} against key {}", pair.context.getSinkId()); } stream.setSink(streamSinkId, existingSink); } if (nidi.partitionKeys == null || nidi.partitionKeys.isEmpty()) { logger.debug("got simple inline stream from {} to {} - {}", new Object[] {sourceIdentifier, sinkIdentifier, nidi}); pair.component.setSink(sinkIdentifier, ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(pair.component, sinkIdentifier, s, ndi.checkpointWindowId) : s); } else { /* * generally speaking we do not have partitions on the inline streams so the control should not * come here but if it comes, then we are ready to handle it using the partition aware streams. */ logger.debug("got partitions on the inline stream from {} to {} - {}", new Object[] {sourceIdentifier, sinkIdentifier, nidi}); PartitionAwareSink<Object> pas = new PartitionAwareSink<Object>(StramUtils.getSerdeInstance(nidi.serDeClassName), nidi.partitionKeys, nidi.partitionMask, s); pair.component.setSink(sinkIdentifier, ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(pair.component, sinkIdentifier, pas, ndi.checkpointWindowId) : pas); } } } } } if (!inputNodes.isEmpty()) { WindowGenerator windowGenerator = setupWindowGenerator(smallestCheckpointedWindowId); for (OperatorDeployInfo ndi : inputNodes) { generators.put(ndi.id, windowGenerator); Node<?> node = nodes.get(ndi.id); Sink<Object> s = node.connectInputPort(Node.INPUT, null, windowGenerator); windowGenerator.setSink(Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT), ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink<Object>(windowGenerator, Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(Node.INPUT), s, ndi.checkpointWindowId) : s); } } } /** * Create the window generator for the given start window id. * This is a hook for tests to control the window generation. * * @param smallestWindowId * @return WindowGenerator */ protected WindowGenerator setupWindowGenerator(long smallestWindowId) { WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1, "WindowGenerator")); /** * let's make sure that we send the same window Ids with the same reset windows. */ windowGenerator.setResetWindow(firstWindowMillis); long millisAtFirstWindow = (smallestWindowId >> 32) * 1000 + windowWidthMillis * (smallestWindowId & WindowGenerator.MAX_WINDOW_ID); windowGenerator.setFirstWindow(millisAtFirstWindow > firstWindowMillis ? millisAtFirstWindow : firstWindowMillis); windowGenerator.setWindowWidth(windowWidthMillis); return windowGenerator; } @SuppressWarnings({"SleepWhileInLoop", "SleepWhileHoldingLock"}) public synchronized void activate(List<OperatorDeployInfo> nodeList) { for (ComponentContextPair<Stream<Object>, StreamContext> pair : streams.values()) { if (!(pair.component instanceof SocketInputStream || activeStreams.containsKey(pair.component))) { activeStreams.put(pair.component, pair.context); pair.component.activate(pair.context); } } final AtomicInteger activatedNodeCount = new AtomicInteger(activeNodes.size()); for (final OperatorDeployInfo ndi : nodeList) { final Node<?> node = nodes.get(ndi.id); assert (!activeNodes.containsKey(ndi.id)); new Thread(node.id) { @Override public void run() { try { OperatorContext context = new OperatorContext(new Integer(ndi.id), this, ndi.contextAttributes, applicationAttributes); node.getOperator().setup(context); activeNodes.put(ndi.id, context); activatedNodeCount.incrementAndGet(); logger.info("activating {} in container {}", node, containerId); node.activate(context); } catch (Throwable ex) { logger.error("Node stopped abnormally because of exception", ex); } finally { activeNodes.remove(ndi.id); node.getOperator().teardown(); logger.info("deactivated {}", node.id); } } }.start(); } /** * we need to make sure that before any of the operators gets the first message, it's activate. */ try { do { Thread.sleep(SPIN_MILLIS); } while (activatedNodeCount.get() < nodes.size()); } catch (InterruptedException ex) { logger.debug(ex.getLocalizedMessage()); } for (ComponentContextPair<Stream<Object>, StreamContext> pair : streams.values()) { if (pair.component instanceof SocketInputStream && !activeStreams.containsKey(pair.component)) { activeStreams.put(pair.component, pair.context); pair.component.activate(pair.context); } } for (WindowGenerator wg : generators.values()) { if (!activeGenerators.containsKey(wg)) { activeGenerators.put(wg, generators); wg.activate(null); } } } private void groupInputStreams(HashMap<String, ArrayList<String>> groupedInputStreams, OperatorDeployInfo ndi) { for (OperatorDeployInfo.InputDeployInfo nidi : ndi.inputs) { String source = Integer.toString(nidi.sourceNodeId).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName); /* * if we do not want to combine multiple streams with different partitions from the * same upstream node, we could also use the partition to group the streams together. * This logic comes with the danger that the performance of the group which shares * the same stream is bounded on the higher side by the performance of the lowest * performer upstream port. May be combining the streams is not such a good thing * but let's see if we allow this as an option to the user, what they end up choosing * the most. */ ArrayList<String> collection = groupedInputStreams.get(source); if (collection == null) { collection = new ArrayList<String>(); groupedInputStreams.put(source, collection); } collection.add(Integer.toString(ndi.id).concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName)); } } }
package com.bitsofproof.supernode.api; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class ScriptFormat { public static final int SIGHASH_ALL = 1; public static final int SIGHASH_NONE = 2; public static final int SIGHASH_SINGLE = 3; public static final int SIGHASH_ANYONECANPAY = 0x80; public static enum Opcode { OP_FALSE (0), OP_PUSH1 (1), OP_PUSH2 (2), OP_PUSH3 (3), OP_PUSH4 (4), OP_PUSH5 (5), OP_PUSH6 (6), OP_PUSH7 (7), OP_PUSH8 (8), OP_PUSH9 (9), OP_PUSH10 ( 10), OP_PUSH11 (11), OP_PUSH12 (12), OP_PUSH13 (13), OP_PUSH14 (14), OP_PUSH15 (15), OP_PUSH16 (16), OP_PUSH17 (17), OP_PUSH18 (18), OP_PUSH19 ( 19), OP_PUSH20 (20), OP_PUSH21 (21), OP_PUSH22 (22), OP_PUSH23 (23), OP_PUSH24 (24), OP_PUSH25 (25), OP_PUSH26 (26), OP_PUSH27 (27), OP_PUSH28 ( 28), OP_PUSH29 (29), OP_PUSH30 (30), OP_PUSH31 (31), OP_PUSH32 (32), OP_PUSH33 (33), OP_PUSH34 (34), OP_PUSH35 (35), OP_PUSH36 (36), OP_PUSH37 ( 37), OP_PUSH38 (38), OP_PUSH39 (39), OP_PUSH40 (40), OP_PUSH41 (41), OP_PUSH42 (42), OP_PUSH43 (43), OP_PUSH44 (44), OP_PUSH45 (45), OP_PUSH46 ( 46), OP_PUSH47 (47), OP_PUSH48 (48), OP_PUSH49 (49), OP_PUSH50 (50), OP_PUSH51 (51), OP_PUSH52 (52), OP_PUSH53 (53), OP_PUSH54 (54), OP_PUSH55 ( 55), OP_PUSH56 (56), OP_PUSH57 (57), OP_PUSH58 (58), OP_PUSH59 (59), OP_PUSH60 (60), OP_PUSH61 (61), OP_PUSH62 (62), OP_PUSH63 (63), OP_PUSH64 ( 64), OP_PUSH65 (65), OP_PUSH66 (66), OP_PUSH67 (67), OP_PUSH68 (68), OP_PUSH69 (69), OP_PUSH70 (70), OP_PUSH71 (71), OP_PUSH72 (72), OP_PUSH73 ( 73), OP_PUSH74 (74), OP_PUSH75 (75), OP_PUSHDATA1 (76), OP_PUSHDATA2 (77), OP_PUSHDATA4 (78), OP_1NEGATE (79), OP_RESERVED (80), OP_1 (81), OP_2 (82), OP_3 (83), OP_4 (84), OP_5 (85), OP_6 (86), OP_7 (87), OP_8 (88), OP_9 (89), OP_10 (90), OP_11 (91), OP_12 (92), OP_13 (93), OP_14 (94), OP_15 (95), OP_16 (96), OP_NOP (97), OP_VER (98), OP_IF (99), OP_NOTIF (100), OP_VERIF (101), OP_VERNOTIF (102), OP_ELSE (103), OP_ENDIF (104), OP_VERIFY (105), OP_RETURN (106), OP_TOALTSTACK (107), OP_FROMALTSTACK (108), OP_2DROP (109), OP_2DUP (110), OP_3DUP (111), OP_2OVER (112), OP_2ROT (113), OP_2SWAP (114), OP_IFDUP (115), OP_DEPTH (116), OP_DROP (117), OP_DUP (118), OP_NIP (119), OP_OVER (120), OP_PICK (121), OP_ROLL (122), OP_ROT (123), OP_SWAP (124), OP_TUCK (125), OP_CAT (126), OP_SUBSTR (127), OP_LEFT (128), OP_RIGHT (129), OP_SIZE (130), OP_INVERT (131), OP_AND (132), OP_OR (133), OP_XOR (134), OP_EQUAL (135), OP_EQUALVERIFY (136), OP_RESERVED1 (137), OP_RESERVED2 (138), OP_1ADD (139), // 0x8b in out 1 is added to the input. OP_1SUB (140), // 0x8c in out 1 is subtracted from the input. OP_2MUL (141), // 0x8d in out The input is multiplied by 2. Currently // disabled. OP_2DIV (142), // 0x8e in out The input is divided by 2. Currently // disabled. OP_NEGATE (143), // 0x8f in out The sign of the input is flipped. OP_ABS (144), // 0x90 in out The input is made positive. OP_NOT (145), // 0x91 in out If the input is 0 or 1, it is flipped. // Otherwise the output will be 0. OP_0NOTEQUAL (146), // 0x92 in out Returns 0 if the input is 0. 1 // otherwise. OP_ADD (147), // 0x93 a b out a is added to b. OP_SUB (148), // 0x94 a b out b is subtracted from a. OP_MUL (149), // 0x95 a b out a is multiplied by b. Currently disabled. OP_DIV (150), // 0x96 a b out a is divided by b. Currently disabled. OP_MOD (151), // 0x97 a b out Returns the remainder after dividing a by // b. Currently disabled. OP_LSHIFT (152), // 0x98 a b out Shifts a left b bits, preserving sign. // Currently disabled. OP_RSHIFT (153), // 0x99 a b out Shifts a right b bits, preserving sign. // Currently disabled. OP_BOOLAND (154), // 0x9a a b out If both a and b are not 0, the output // is 1. Otherwise 0. OP_BOOLOR (155), // 0x9b a b out If a or b is not 0, the output is 1. // Otherwise 0. OP_NUMEQUAL (156), // 0x9c a b out Returns 1 if the numbers are equal, 0 // otherwise. OP_NUMEQUALVERIFY (157), // 0x9d a b out Same as OP_NUMEQUAL, but runs // OP_VERIFY afterward. OP_NUMNOTEQUAL (158), // 0x9e a b out Returns 1 if the numbers are not // equal, 0 otherwise. OP_LESSTHAN (159), // 0x9f a b out Returns 1 if a is less than b, 0 // otherwise. OP_GREATERTHAN (160), // 0xa0 a b out Returns 1 if a is greater than b, // otherwise. OP_LESSTHANOREQUAL (161), // 0xa1 a b out Returns 1 if a is less than or // equal to b, 0 otherwise. OP_GREATERTHANOREQUAL (162), // 0xa2 a b out Returns 1 if a is greater // than or equal to b, 0 otherwise. OP_MIN (163), // 0xa3 a b out Returns the smaller of a and b. OP_MAX (164), // 0xa4 a b out Returns the larger of a and b. OP_WITHIN (165), // 0xa5 x min max out Returns 1 if x is within the // specified range (left-inclusive), 0 otherwise. OP_RIPEMD160 (166), // 0xa6 in hash The input is hashed using // RIPEMD-160. OP_SHA1 (167), // 0xa7 in hash The input is hashed using SHA-1. OP_SHA256 (168), // 0xa8 in hash The input is hashed using SHA-256. OP_HASH160 (169), // 0xa9 in hash The input is hashed twice: first with // SHA-256 and then with RIPEMD-160. OP_HASH256 (170), // 0xaa in hash The input is hashed two times with // SHA-256. OP_CODESEPARATOR (171), // 0xab Nothing Nothing All of the signature // checking words will only match signatures to // the data after the most recently-executed // OP_CODESEPARATOR. OP_CHECKSIG (172), // 0xac sig pubkey True / false The entire // transaction's outputs, inputs, and script (from // the most recently-executed OP_CODESEPARATOR to // the end) are hashed. The signature used by // OP_CHECKSIG must be a valid signature for this // hash and public key. If it is, 1 is returned, 0 // otherwise. OP_CHECKSIGVERIFY (173), // 0xad sig pubkey True / false Same as // OP_CHECKSIG, but OP_VERIFY is executed // afterward. OP_CHECKMULTISIG (174), // 0xae x sig1 sig2 ... <number of signatures> // pub1 pub2 <number of public keys> True / // False For each signature and public key pair, // OP_CHECKSIG is executed. If more public keys // than signatures are listed, some key/sig // pairs can fail. All signatures need to match // a public key. If all signatures are valid, 1 // is returned, 0 otherwise. Due to a bug, one // extra unused value is removed from the stack. OP_CHECKMULTISIGVERIFY (175), // 0xaf x sig1 sig2 ... <number of // signatures> pub1 pub2 ... <number of // public keys> True / False Same as // OP_CHECKMULTISIG, but OP_VERIFY is // executed afterward. OP_NOP1 (176), OP_NOP2 (177), OP_NOP3 (178), OP_NOP4 (179), OP_NOP5 (180), OP_NOP6 (181), OP_NOP7 (182), OP_NOP8 (183), OP_NOP9 (184), OP_NOP10 (185); final int o; Opcode (int n) { this.o = n; } } public static class Token { public Opcode op; public byte[] data; public Token () { } public Token (Opcode op) { this.op = op; data = null; } } public static class Reader { private final byte[] bytes; int cursor; public Reader (byte[] script) { this.bytes = script; this.cursor = 0; } public boolean eof () { return cursor == bytes.length; } public byte[] readBytes (int n) { byte[] b = new byte[n]; System.arraycopy (bytes, cursor, b, 0, n); cursor += n; return b; } public void skipBytes (int n) { cursor += n; } public int readByte () { return bytes[cursor++] & 0xff; } public long readInt16 () { long value = ((bytes[cursor] & 0xFFL) << 0) | ((bytes[cursor + 1] & 0xFFL) << 8); cursor += 2; return value; } public long readInt32 () { long value = ((bytes[cursor] & 0xFFL) << 0) | ((bytes[cursor + 1] & 0xFFL) << 8) | ((bytes[cursor + 2] & 0xFFL) << 16) | ((bytes[cursor + 3] & 0xFFL) << 24); cursor += 4; return value; } } public static class Writer { private final ByteArrayOutputStream s; public Writer () { s = new ByteArrayOutputStream (); } public Writer (ByteArrayOutputStream s) { this.s = s; } public void writeByte (int n) { s.write (n); } public void writeBytes (byte[] b) { try { s.write (b); } catch ( IOException e ) { } } public void writeData (byte[] data) { if ( data.length <= 75 ) { writeByte (data.length); writeBytes (data); } else if ( data.length <= 0xff ) { writeByte (Opcode.OP_PUSHDATA1.o); writeByte (data.length); writeBytes (data); } else if ( data.length <= 0xffff ) { writeByte (Opcode.OP_PUSHDATA2.o); writeInt16 (data.length); writeBytes (data); } else if ( data.length <= 0x7fffffff ) { writeByte (Opcode.OP_PUSHDATA4.o); writeInt16 (data.length); writeBytes (data); } } public void writeToken (Token token) { s.write (token.op.o); if ( token.data != null ) { try { s.write (token.data); } catch ( IOException e ) { } } } public void writeInt16 (long n) { s.write ((int) (0xFFL & n)); s.write ((int) (0xFFL & (n >> 8))); } public void writeInt32 (long n) { s.write ((int) (0xFF & n)); s.write ((int) (0xFF & (n >> 8))); s.write ((int) (0xFF & (n >> 16))); s.write ((int) (0xFF & (n >> 24))); } public byte[] toByteArray () { return s.toByteArray (); } } public static class Tokenizer { private final Reader reader; public Tokenizer (byte[] script) { reader = new Reader (script); } public boolean hashMoreElements () { return !reader.eof (); } public int getCursor () { return reader.cursor; } @SuppressWarnings ("incomplete-switch") public Token nextToken () throws ValidationException { Token token = new Token (); int ix = reader.readByte (); if ( ix > 185 ) { throw new ValidationException ("Invalid script" + ix + " opcode at " + reader.cursor); } Opcode op = Opcode.values ()[ix]; token.op = op; if ( op.o <= 75 ) { token.data = reader.readBytes (op.o); return token; } switch ( op ) { case OP_PUSHDATA1: { token.data = reader.readBytes (reader.readByte ()); break; } case OP_PUSHDATA2: { token.data = reader.readBytes ((int) reader.readInt16 ()); break; } case OP_PUSHDATA4: { token.data = reader.readBytes ((int) reader.readInt32 ()); break; } } return token; } } public static class Number { byte[] w; public Number (byte[] b) { w = new byte[b.length]; System.arraycopy (b, 0, w, 0, b.length); } public Number (long n) throws ValidationException { if ( n == 0 ) { w = new byte[0]; return; } boolean negative = false; if ( n < 0 ) { negative = true; n = -n; } if ( n <= 0x7f ) { w = new byte[] { (byte) (n & 0xff) }; w[0] |= negative ? 0x80 : 0; return; } if ( n <= 0x7fff ) { w = new byte[] { (byte) (n & 0xff), (byte) ((n >> 8) & 0xff) }; w[1] |= negative ? 0x80 : 0; return; } if ( n <= 0x7fffff ) { w = new byte[] { (byte) (n & 0xff), (byte) ((n >> 8) & 0xff), (byte) ((n >> 16) & 0xff) }; w[2] |= negative ? 0x80 : 0; return; } w = new byte[] { (byte) (n & 0xff), (byte) ((n >> 8) & 0xff), (byte) ((n >> 16) & 0xff), (byte) ((n >> 24) & 0xff) }; if ( ((n >> 24) & 0x80) != 0 ) { byte[] tmp = new byte[5]; System.arraycopy (w, 0, tmp, 0, 4); w = tmp; } w[w.length - 1] |= negative ? 0x80 : 0; } public byte[] toByteArray () { byte[] tmp = new byte[w.length]; System.arraycopy (w, 0, tmp, 0, w.length); return tmp; } public long intValue () throws ValidationException { if ( w.length == 0 ) { return 0; } boolean negative = false; if ( (w[w.length - 1] & 0x80) != 0 ) { negative = true; w[w.length - 1] &= 0x7f; } int n = 0; if ( w.length > 0 ) { n += w[0] & 0xff; } if ( w.length > 1 ) { n += (w[1] & 0xff) << 8; } if ( w.length > 2 ) { n += (w[2] & 0xff) << 16; } if ( w.length > 3 ) { n += (w[3] & 0xff) << 24; } if ( negative ) { n = -n; } return n; } } public static int intValue (byte[] n) throws ValidationException { return (int) new ScriptFormat.Number (n).intValue (); } public static List<ScriptFormat.Token> parse (byte[] script) throws ValidationException { List<ScriptFormat.Token> p = new ArrayList<ScriptFormat.Token> (); ScriptFormat.Tokenizer tokenizer = new ScriptFormat.Tokenizer (script); while ( tokenizer.hashMoreElements () ) { p.add (tokenizer.nextToken ()); } return p; } public static boolean isPushOnly (byte[] script) throws ValidationException { for ( ScriptFormat.Token t : parse (script) ) { if ( t.op.o > 78 ) { return false; } } return true; } @SuppressWarnings ("incomplete-switch") public static int sigOpCount (byte[] script) throws ValidationException { int nsig = 0; ScriptFormat.Opcode last = ScriptFormat.Opcode.OP_FALSE; ScriptFormat.Tokenizer tokenizer = new ScriptFormat.Tokenizer (script); while ( tokenizer.hashMoreElements () ) { ScriptFormat.Token token = tokenizer.nextToken (); if ( token.data == null ) { switch ( token.op ) { case OP_CHECKSIG: case OP_CHECKSIGVERIFY: ++nsig; break; case OP_CHECKMULTISIG: case OP_CHECKMULTISIGVERIFY: if ( last.o >= 0 && last.o <= 16 ) { nsig += last.o; } else { nsig += 20; } break; } last = token.op; } } return nsig; } public static byte[] fromReadable (String s) { ScriptFormat.Writer writer = new ScriptFormat.Writer (); StringTokenizer tokenizer = new StringTokenizer (s, " "); while ( tokenizer.hasMoreElements () ) { String token = tokenizer.nextToken (); ScriptFormat.Opcode op = ScriptFormat.Opcode.OP_FALSE; if ( token.startsWith ("0x") ) { byte[] data = ByteUtils.fromHex (token.substring (2)); writer.writeBytes (data); } else if ( token.startsWith ("'") ) { String str = token.substring (1, token.length () - 1); try { writer.writeData (str.getBytes ("US-ASCII")); } catch ( UnsupportedEncodingException e ) { } } else if ( (token.startsWith ("-") || token.startsWith ("0") || token.startsWith ("1") || token.startsWith ("2") || token.startsWith ("3") || token.startsWith ("4") || token.startsWith ("5") || token.startsWith ("6") || token.startsWith ("7") || token.startsWith ("8") || token .startsWith ("9")) && !token.equals ("0NOTEQUAL") && !token.equals ("1NEGATE") && !token.equals ("2DROP") && !token.equals ("2DUP") && !token.equals ("3DUP") && !token.equals ("2OVER") && !token.equals ("2ROT") && !token.equals ("2SWAP") && !token.equals ("1ADD") && !token.equals ("1SUB") && !token.equals ("2MUL") && !token.equals ("2DIV") && !token.equals ("2SWAP") ) { try { long n = Long.valueOf (token).longValue (); if ( n >= 1 && n <= 16 ) { writer.writeByte (Opcode.OP_1.o + (int) n - 1); } else { writer.writeData (new Number (n).toByteArray ()); } } catch ( NumberFormatException e ) { } catch ( ValidationException e ) { } } else { if ( token.startsWith ("OP_") ) { op = ScriptFormat.Opcode.valueOf (token); } else { op = ScriptFormat.Opcode.valueOf ("OP_" + token); } writer.writeByte (op.o); } } return writer.toByteArray (); } public static String toReadable (byte[] script) throws ValidationException { List<ScriptFormat.Token> tokens = parse (script); StringBuffer b = new StringBuffer (); boolean first = true; for ( ScriptFormat.Token token : tokens ) { if ( !first ) { b.append (" "); } first = false; if ( token.data != null ) { if ( token.data.length > 0 ) { b.append ("0x" + ByteUtils.toHex (token.data)); } else { b.append ("0x0"); } } else { b.append (token.op.toString ().substring (2)); } } return b.toString (); } public static boolean isPayToScriptHash (byte[] script) { try { List<ScriptFormat.Token> parsed = parse (script); return parsed.size () == 3 && parsed.get (0).op == ScriptFormat.Opcode.OP_HASH160 && (parsed.get (1).data != null && parsed.get (1).op.o <= 75) && parsed.get (1).data.length == 20 && parsed.get (2).op == ScriptFormat.Opcode.OP_EQUAL; } catch ( ValidationException e ) { return false; } } public static boolean isPayToKey (byte[] script) { try { List<ScriptFormat.Token> parsed = parse (script); return parsed.size () == 2 && parsed.get (0).data != null && parsed.get (1).op == ScriptFormat.Opcode.OP_CHECKSIG; } catch ( ValidationException e ) { return false; } } public static boolean isPayToAddress (byte[] script) { try { List<ScriptFormat.Token> parsed = parse (script); return parsed.size () == 5 && parsed.get (0).op == ScriptFormat.Opcode.OP_DUP && parsed.get (1).op == ScriptFormat.Opcode.OP_HASH160 && parsed.get (2).data != null && parsed.get (3).op == ScriptFormat.Opcode.OP_EQUALVERIFY && parsed.get (4).op == ScriptFormat.Opcode.OP_CHECKSIG; } catch ( ValidationException e ) { return false; } } public static boolean isMultiSig (byte[] script) { try { List<ScriptFormat.Token> parsed = parse (script); int nkeys = -1; int nvotes = -1; for ( int i = 0; i < parsed.size (); ++i ) { if ( parsed.get (i).op == ScriptFormat.Opcode.OP_CHECKMULTISIG || parsed.get (i).op == ScriptFormat.Opcode.OP_CHECKMULTISIGVERIFY ) { nkeys = parsed.get (i - 1).op.ordinal () - ScriptFormat.Opcode.OP_1.ordinal () + 1; nvotes = parsed.get (i - nkeys - 2).op.ordinal () - ScriptFormat.Opcode.OP_1.ordinal () + 1; break; } } if ( nkeys <= 0 || nkeys > 3 ) { return false; } if ( parsed.size () != nkeys + 3 ) { return false; } if ( nvotes < 0 || nvotes > nkeys ) { return false; } } catch ( ValidationException e ) { return false; } return true; } public static boolean isStandard (byte[] script) { return isPayToAddress (script) || isPayToKey (script) || isPayToScriptHash (script) || isMultiSig (script); } public static byte[] getPayToAddressScript (byte[] keyHash) { ScriptFormat.Writer writer = new ScriptFormat.Writer (); writer.writeToken (new ScriptFormat.Token (ScriptFormat.Opcode.OP_DUP)); writer.writeToken (new ScriptFormat.Token (ScriptFormat.Opcode.OP_HASH160)); writer.writeData (keyHash); writer.writeToken (new ScriptFormat.Token (ScriptFormat.Opcode.OP_EQUALVERIFY)); writer.writeToken (new ScriptFormat.Token (ScriptFormat.Opcode.OP_CHECKSIG)); return writer.toByteArray (); } public static byte[] deleteSignatureFromScript (byte[] script, byte[] sig) throws ValidationException { ScriptFormat.Tokenizer tokenizer = new ScriptFormat.Tokenizer (script); ScriptFormat.Writer writer = new ScriptFormat.Writer (); while ( tokenizer.hashMoreElements () ) { ScriptFormat.Token token = tokenizer.nextToken (); if ( token.data != null && token.data.length == sig.length ) { boolean found = true; for ( int i = 0; i < sig.length; ++i ) { if ( sig[i] != token.data[i] ) { found = false; break; } } if ( !found ) { writer.writeToken (token); } } else { writer.writeToken (token); } } return writer.toByteArray (); } }
package com.malhartech.stram; import com.malhartech.dag.BackupAgent; import com.malhartech.dag.Component; import com.malhartech.dag.ComponentContextPair; import com.malhartech.dag.Node; import com.malhartech.dag.NodeConfiguration; import com.malhartech.dag.NodeContext; import com.malhartech.dag.NodeSerDe; import com.malhartech.dag.Sink; import com.malhartech.dag.Stream; import com.malhartech.dag.StreamConfiguration; import com.malhartech.dag.StreamContext; import com.malhartech.dag.WindowIdActivatedSink; import com.malhartech.stram.StreamingNodeUmbilicalProtocol.ContainerHeartbeat; import com.malhartech.stram.StreamingNodeUmbilicalProtocol.ContainerHeartbeatResponse; import com.malhartech.stram.StreamingNodeUmbilicalProtocol.StramToNodeRequest; import com.malhartech.stram.StreamingNodeUmbilicalProtocol.StreamingContainerContext; import com.malhartech.stram.StreamingNodeUmbilicalProtocol.StreamingNodeHeartbeat; import com.malhartech.stram.StreamingNodeUmbilicalProtocol.StreamingNodeHeartbeat.DNodeState; import com.malhartech.stream.BufferServerInputStream; import com.malhartech.stream.BufferServerOutputStream; import com.malhartech.stream.InlineStream; import com.malhartech.stream.MuxStream; import com.malhartech.stream.PartitionAwareSink; import com.malhartech.stream.SocketInputStream; import com.malhartech.util.ScheduledThreadPoolExecutor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.InetSocketAddress; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FSError; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.log4j.LogManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // make sure that setup and teardown is called through the same thread which calls process /** * * The main() for streaming node processes launched by {@link com.malhartech.stram.StramAppMaster}.<p> * <br> * */ public class StramChild { private static final Logger logger = LoggerFactory.getLogger(StramChild.class); private static final String NODE_PORT_SPLIT_SEPARATOR = "\\."; private static final String NODE_PORT_CONCAT_SEPARATOR = "."; //private static final String SOURCE_SINK_SEPARATOR = "\u279C"; private final String containerId; private final Configuration conf; private final StreamingNodeUmbilicalProtocol umbilical; protected final Map<String, ComponentContextPair<Node, NodeContext>> nodes = new ConcurrentHashMap<String, ComponentContextPair<Node, NodeContext>>(); private final Map<String, ComponentContextPair<Stream, StreamContext>> streams = new ConcurrentHashMap<String, ComponentContextPair<Stream, StreamContext>>(); protected final Map<String, WindowGenerator> generators = new ConcurrentHashMap<String, WindowGenerator>(); /** * for the following 3 fields, my preferred type is HashSet but synchronizing access to HashSet object was resulting in very verbose code. */ private final Map<Node, NodeContext> activeNodes = new ConcurrentHashMap<Node, NodeContext>(); private final Map<Stream, StreamContext> activeStreams = new ConcurrentHashMap<Stream, StreamContext>(); private final Map<WindowGenerator, Object> activeGenerators = new ConcurrentHashMap<WindowGenerator, Object>(); private long heartbeatIntervalMillis = 1000; private volatile boolean exitHeartbeatLoop = false; private final Object heartbeatTrigger = new Object(); private String checkpointDfsPath; /** * Map of last backup window id that is used to communicate checkpoint state back to Stram. TODO: Consider adding this to the node context instead. */ private final Map<String, Long> backupInfo = new ConcurrentHashMap<String, Long>(); private long firstWindowMillis; private int windowWidthMillis; protected StramChild(String containerId, Configuration conf, StreamingNodeUmbilicalProtocol umbilical) { logger.debug("instantiated StramChild {}", containerId); this.umbilical = umbilical; this.containerId = containerId; this.conf = conf; } public void setup(StreamingContainerContext ctx) { heartbeatIntervalMillis = ctx.getHeartbeatIntervalMillis(); if (heartbeatIntervalMillis == 0) { heartbeatIntervalMillis = 1000; } firstWindowMillis = ctx.getStartWindowMillis(); windowWidthMillis = ctx.getWindowSizeMillis(); if (windowWidthMillis == 0) { windowWidthMillis = 500; } if ((this.checkpointDfsPath = ctx.getCheckpointDfsPath()) == null) { this.checkpointDfsPath = "checkpoint-dfs-path-not-configured"; } try { deploy(ctx.nodeList); } catch (Exception ex) { logger.debug("deploy request failed due to {}", ex); } } public String getContainerId() { return this.containerId; } protected Map<String, ComponentContextPair<Node, NodeContext>> getNodes() { return this.nodes; } /** * Initialize container with nodes and streams in the context. * Existing nodes are not affected by this operation. * * @param ctx * @throws IOException */ public static void main(String[] args) throws Throwable { logger.debug("Child starting with classpath: {}", System.getProperty("java.class.path")); final Configuration defaultConf = new Configuration(); //defaultConf.addResource(MRJobConfig.JOB_CONF_FILE); UserGroupInformation.setConfiguration(defaultConf); String host = args[0]; int port = Integer.parseInt(args[1]); final InetSocketAddress address = NetUtils.createSocketAddrForHost(host, port); final String childId = args[2]; //Token<JobTokenIdentifier> jt = loadCredentials(defaultConf, address); // Communicate with parent as actual task owner. UserGroupInformation taskOwner = UserGroupInformation.createRemoteUser(StramChild.class.getName()); //taskOwner.addToken(jt); final StreamingNodeUmbilicalProtocol umbilical = taskOwner.doAs(new PrivilegedExceptionAction<StreamingNodeUmbilicalProtocol>() { @Override public StreamingNodeUmbilicalProtocol run() throws Exception { return RPC.getProxy(StreamingNodeUmbilicalProtocol.class, StreamingNodeUmbilicalProtocol.versionID, address, defaultConf); } }); logger.debug("PID: " + System.getenv().get("JVM_PID")); UserGroupInformation childUGI; try { childUGI = UserGroupInformation.createRemoteUser(System.getenv(ApplicationConstants.Environment.USER.toString())); // Add tokens to new user so that it may execute its task correctly. for (Token<?> token: UserGroupInformation.getCurrentUser().getTokens()) { childUGI.addToken(token); } childUGI.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { StramChild stramChild = new StramChild(childId, defaultConf, umbilical); StreamingContainerContext ctx = umbilical.getInitContext(childId); logger.debug("Got context: " + ctx); stramChild.setup(ctx); // main thread enters heartbeat loop stramChild.monitorHeartbeat(); // teardown stramChild.deactivate(); stramChild.teardown(); return null; } }); } catch (FSError e) { logger.error("FSError from child", e); umbilical.log(childId, e.getMessage()); } catch (Exception exception) { logger.warn("Exception running child : " + StringUtils.stringifyException(exception)); // Report back any failures, for diagnostic purposes ByteArrayOutputStream baos = new ByteArrayOutputStream(); exception.printStackTrace(new PrintStream(baos)); umbilical.log(childId, "FATAL: " + baos.toString()); } catch (Throwable throwable) { logger.error("Error running child : " + StringUtils.stringifyException(throwable)); Throwable tCause = throwable.getCause(); String cause = tCause == null ? throwable.getMessage() : StringUtils.stringifyException(tCause); umbilical.log(childId, cause); } finally { RPC.stopProxy(umbilical); DefaultMetricsSystem.shutdown(); // Shutting down log4j of the child-vm... // This assumes that on return from Task.activate() // there is no more logging done. LogManager.shutdown(); } } public synchronized void deactivate() { for (WindowGenerator wg: activeGenerators.keySet()) { wg.deactivate(); } activeGenerators.clear(); for (Node node: activeNodes.keySet()) { node.deactivate(); } for (Stream stream: activeStreams.keySet()) { stream.deactivate(); } activeStreams.clear(); } private synchronized void disconnectNode(String nodeid) { Node node = nodes.get(nodeid).component; disconnectWindowGenerator(nodeid, node); Set<String> removableSocketOutputStreams = new HashSet<String>(); // temporary fix - find out why List does not work. // with the logic i have in here, the list should not contain repeated streams. but it does and that causes problem. for (Entry<String, ComponentContextPair<Stream, StreamContext>> entry: streams.entrySet()) { String indexingKey = entry.getKey(); Stream stream = entry.getValue().component; StreamContext context = entry.getValue().context; String sourceIdentifier = context.getSourceId(); String sinkIdentifier = context.getSinkId(); logger.debug("considering stream {} against id {}", stream, indexingKey); if (nodeid.equals(sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR)[0])) { /** * the stream originates at the output port of one of the nodes that are going to vanish. */ if (activeStreams.containsKey(stream)) { logger.debug("deactivating {}", stream); stream.deactivate(); activeStreams.remove(stream); } removableSocketOutputStreams.add(sourceIdentifier); String[] sinkIds = sinkIdentifier.split(", "); for (String sinkId: sinkIds) { if (!sinkId.startsWith("tcp: String[] nodeport = sinkId.split(NODE_PORT_SPLIT_SEPARATOR); ComponentContextPair<Node, NodeContext> npair = nodes.get(nodeport[0]); npair.component.connect(nodeport[1], null); } else if (stream.isMultiSinkCapable()) { ComponentContextPair<Stream, StreamContext> spair = streams.get(sinkId); logger.debug("found stream {} against {}", spair == null ? null : spair.component, sinkId); if (spair == null) { assert (!sinkId.startsWith("tcp: } else { assert (sinkId.startsWith("tcp: if (activeStreams.containsKey(spair.component)) { logger.debug("deactivating {} for sink {}", spair.component, sinkId); spair.component.deactivate(); activeStreams.remove(spair.component); } spair.component.connect(Component.INPUT, null); removableSocketOutputStreams.add(sinkId); } } } stream.connect(Component.INPUT, null); } else { /** * the stream may or may not feed into one of the nodes which are being undeployed. */ String[] sinkIds = sinkIdentifier.split(", "); for (int i = sinkIds.length; i String[] nodeport = sinkIds[i].split(NODE_PORT_SPLIT_SEPARATOR); if (nodeid.equals(nodeport[0])) { stream.connect(sinkIds[i], null); node.connect(nodeport[1], null); sinkIds[i] = null; } } String sinkId = null; for (int i = sinkIds.length; i if (sinkIds[i] != null) { if (sinkId == null) { sinkId = sinkIds[i]; } else { sinkId = sinkId.concat(", ").concat(sinkIds[i]); } } } if (sinkId == null) { if (activeStreams.containsKey(stream)) { logger.debug("deactivating {}", stream); stream.deactivate(); activeStreams.remove(stream); } removableSocketOutputStreams.add(indexingKey); } else { // may be we should also check if the count has changed from something to 1 // and replace mux with 1:1 sink. it's not necessary though. context.setSinkId(sinkId); } } } for (String streamId: removableSocketOutputStreams) { logger.debug("removing stream {}", streamId); // need to check why control comes here twice to remove the stream which was deleted before. // is it because of multiSinkCapableStream ? ComponentContextPair<Stream, StreamContext> pair = streams.remove(streamId); pair.component.teardown(); } } private void disconnectWindowGenerator(String nodeid, Node node) { WindowGenerator chosen1 = generators.remove(nodeid); if (chosen1 != null) { chosen1.connect(nodeid.concat(NODE_PORT_CONCAT_SEPARATOR).concat(Component.INPUT), null); node.connect(Component.INPUT, null); int count = 0; for (WindowGenerator wg: generators.values()) { if (chosen1 == wg) { count++; } } if (count == 0) { activeGenerators.remove(chosen1); chosen1.deactivate(); chosen1.teardown(); } } } private synchronized void undeploy(List<NodeDeployInfo> nodeList) { /** * make sure that all the nodes which we are asked to undeploy are in this container. */ HashMap<String, Node> toUndeploy = new HashMap<String, Node>(); for (NodeDeployInfo ndi: nodeList) { ComponentContextPair<Node, NodeContext> pair = nodes.get(ndi.id); if (pair == null) { throw new IllegalArgumentException("Node " + ndi.id + " is not hosted in this container!"); } else if (toUndeploy.containsKey(ndi.id)) { throw new IllegalArgumentException("Node " + ndi.id + " is requested to be undeployed more than once"); } else { toUndeploy.put(ndi.id, pair.component); } } for (NodeDeployInfo ndi: nodeList) { ComponentContextPair<Node, NodeContext> pair = nodes.get(ndi.id); if (activeNodes.containsKey(pair.component)) { pair.component.deactivate(); } } } public void teardown() { HashSet<WindowGenerator> gens = new HashSet<WindowGenerator>(); gens.addAll(generators.values()); generators.clear(); for (WindowGenerator wg: gens) { wg.teardown(); } gens.clear(); for (ComponentContextPair<Node, NodeContext> nc: this.nodes.values()) { nc.component.teardown(); } for (Stream stream: activeStreams.keySet()) { stream.teardown(); } activeStreams.clear(); } protected void triggerHeartbeat() { synchronized (heartbeatTrigger) { heartbeatTrigger.notifyAll(); } } protected void monitorHeartbeat() throws IOException { umbilical.log(containerId, "[" + containerId + "] Entering heartbeat loop.."); logger.debug("Entering hearbeat loop (interval is {} ms)", this.heartbeatIntervalMillis); while (!exitHeartbeatLoop) { synchronized (this.heartbeatTrigger) { try { this.heartbeatTrigger.wait(heartbeatIntervalMillis); } catch (InterruptedException e1) { logger.warn("Interrupted in heartbeat loop, exiting.."); break; } } long currentTime = System.currentTimeMillis(); ContainerHeartbeat msg = new ContainerHeartbeat(); msg.setContainerId(this.containerId); List<StreamingNodeHeartbeat> heartbeats = new ArrayList<StreamingNodeHeartbeat>(nodes.size()); // gather heartbeat info for all nodes for (Map.Entry<String, ComponentContextPair<Node, NodeContext>> e: nodes.entrySet()) { StreamingNodeHeartbeat hb = new StreamingNodeHeartbeat(); hb.setNodeId(e.getKey()); hb.setGeneratedTms(currentTime); hb.setIntervalMs(heartbeatIntervalMillis); e.getValue().context.drainHeartbeatCounters(hb.getHeartbeatsContainer()); hb.setState((activeNodes.containsKey(e.getValue().component) ? DNodeState.PROCESSING : DNodeState.IDLE).toString()); // propagate the backup window, if any Long backupWindowId = backupInfo.get(e.getKey()); if (backupWindowId != null) { hb.setLastBackupWindowId(backupWindowId); } heartbeats.add(hb); } msg.setDnodeEntries(heartbeats); // heartbeat call and follow-up processing //logger.debug("Sending heartbeat for {} nodes.", msg.getDnodeEntries().size()); try { ContainerHeartbeatResponse rsp = umbilical.processHeartbeat(msg); if (rsp != null) { processHeartbeatResponse(rsp); // keep polling at smaller interval if work is pending while (rsp != null && rsp.hasPendingRequests) { logger.info("Waiting for pending request."); synchronized (this.heartbeatTrigger) { try { this.heartbeatTrigger.wait(500); } catch (InterruptedException e1) { logger.warn("Interrupted in heartbeat loop, exiting.."); break; } } rsp = umbilical.pollRequest(this.containerId); if (rsp != null) { processHeartbeatResponse(rsp); } } } } catch (Exception e) { logger.warn("Exception received (may be during shutdown?) {}", e.getLocalizedMessage(), e); } } logger.debug("Exiting hearbeat loop"); umbilical.log(containerId, "[" + containerId + "] Exiting heartbeat loop.."); } protected void processHeartbeatResponse(ContainerHeartbeatResponse rsp) { if (rsp.shutdown) { logger.info("Received shutdown request"); this.exitHeartbeatLoop = true; return; } if (rsp.undeployRequest != null) { logger.info("Undeploy request: {}", rsp.undeployRequest); undeploy(rsp.undeployRequest); } if (rsp.deployRequest != null) { logger.info("Deploy request: {}", rsp.deployRequest); try { deploy(rsp.deployRequest); } catch (Exception e) { logger.error("deploy request failed due to {}", e); // report it to stram } } if (rsp.nodeRequests != null) { // extended processing per node for (StramToNodeRequest req: rsp.nodeRequests) { ComponentContextPair<Node, NodeContext> pair = nodes.get(req.getNodeId()); if (pair == null) { logger.warn("Received request with invalid node id {} ({})", req.getNodeId(), req); } else { logger.debug("Stram request: {}", req); processStramRequest(pair, req); } } } } /** * Process request from stram for further communication through the protocol. Extended reporting is on a per node basis (won't occur under regular operation) * * @param n * @param snr */ private void processStramRequest(ComponentContextPair<Node, NodeContext> pair, StramToNodeRequest snr) { switch (snr.getRequestType()) { case REPORT_PARTION_STATS: logger.warn("Ignoring stram request {}", snr); break; case CHECKPOINT: pair.context.requestBackup(new HdfsBackupAgent(StramUtils.getNodeSerDe(null))); break; default: logger.error("Unknown request from stram {}", snr); } } private synchronized void deploy(List<NodeDeployInfo> nodeList) throws Exception { /** * A little bit of up front sanity check would reduce the percentage of deploy failures later. */ HashMap<String, ArrayList<String>> groupedInputStreams = new HashMap<String, ArrayList<String>>(); for (NodeDeployInfo ndi: nodeList) { if (nodes.containsKey(ndi.id)) { throw new IllegalStateException("Node with id: " + ndi.id + " already present in the container"); } groupInputStreams(groupedInputStreams, ndi); } deployNodes(nodeList); deployOutputStreams(nodeList, groupedInputStreams); deployInputStreams(nodeList); activate(nodeList); } private void deployNodes(List<NodeDeployInfo> nodeList) throws Exception { NodeSerDe nodeSerDe = StramUtils.getNodeSerDe(null); HdfsBackupAgent backupAgent = new HdfsBackupAgent(nodeSerDe); for (NodeDeployInfo ndi: nodeList) { NodeContext nc = new NodeContext(ndi.id); try { final Object foreignObject; if (ndi.checkpointWindowId > 0) { logger.debug("Restoring node {} to checkpoint {}", ndi.id, ndi.checkpointWindowId); foreignObject = backupAgent.restore(ndi.id, ndi.checkpointWindowId); } else { foreignObject = nodeSerDe.read(new ByteArrayInputStream(ndi.serializedNode)); } Node node = (Node)foreignObject; StramUtils.internalSetupNode(node, ndi.id.concat(":").concat(ndi.declaredId)); node.setup(new NodeConfiguration(ndi.id, ndi.properties)); nodes.put(ndi.id, new ComponentContextPair<Node, NodeContext>(node, nc)); } catch (Exception e) { logger.error(e.getLocalizedMessage()); throw e; } } } private void deployOutputStreams(List<NodeDeployInfo> nodeList, HashMap<String, ArrayList<String>> groupedInputStreams) throws Exception { /** * We proceed to deploy all the output streams. * At the end of this block, our streams collection will contain all the streams which originate at the * output port of the nodes. The streams are generally mapped against the "nodename.portname" string. * But the BufferOutputStreams which share the output port with other inline streams are mapped against * the Buffer Server port to avoid collision and at the same time keep track of these buffer streams. */ for (NodeDeployInfo ndi: nodeList) { Node node = nodes.get(ndi.id).component; for (NodeDeployInfo.NodeOutputDeployInfo nodi: ndi.outputs) { String sourceIdentifier = ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nodi.portName); String sinkIdentifier; Stream stream; ArrayList<String> collection = groupedInputStreams.get(sourceIdentifier); if (collection == null) { /** * Let's create a stream to carry the data to the Buffer Server. * Nobody in this container is interested in the output placed on this stream, but * this stream exists. That means someone outside of this container must be interested. */ assert (nodi.isInline() == false); StreamConfiguration config = new StreamConfiguration(); config.setSocketAddr(StreamConfiguration.SERVER_ADDRESS, InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort)); stream = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName)); stream.setup(config); logger.debug("deployed a buffer stream {}", stream); sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier); } else if (collection.size() == 1) { if (nodi.isInline()) { /** * Let's create an inline stream to carry data from output port to input port of some other node. * There is only one node interested in output placed on this stream, and that node is in this container. */ stream = new InlineStream(); stream.setup(new StreamConfiguration()); sinkIdentifier = null; } else { /** * Let's create 2 streams: 1 inline and 1 going to the Buffer Server. * Although there is a node in this container interested in output placed on this stream, there * seems to at least one more party interested but placed in a container other than this one. */ StreamConfiguration config = new StreamConfiguration(); config.setSocketAddr(StreamConfiguration.SERVER_ADDRESS, InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort)); BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName)); bsos.setup(config); logger.debug("deployed a buffer stream {}", bsos); // the following sinkIdentifier may not gel well with the rest of the logic sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier); StreamContext bssc = new StreamContext(nodi.declaredStreamId); bssc.setSourceId(sourceIdentifier); bssc.setSinkId(sinkIdentifier); streams.put(sinkIdentifier, new ComponentContextPair<Stream, StreamContext>(bsos, bssc)); // should we create inline stream here or wait for the input deployments to create the inline streams? stream = new MuxStream(); stream.setup(new StreamConfiguration()); Sink s = bsos.connect(Component.INPUT, stream); stream.connect(sinkIdentifier, s); logger.debug("stored stream {} against key {}", bsos, sinkIdentifier); } } else { /** * Since there are multiple parties interested in this node itself, we are going to come * to this block multiple times. The actions we take subsequent times are going to be different * than the first time. We create the MuxStream only the first time. */ ComponentContextPair<Stream, StreamContext> pair = streams.get(sourceIdentifier); if (pair == null) { /** * Let's multiplex the output placed on this stream. * This container itself contains more than one parties interested. */ stream = new MuxStream(); stream.setup(new StreamConfiguration()); } else { stream = pair.component; } if (nodi.isInline()) { sinkIdentifier = null; } else { StreamConfiguration config = new StreamConfiguration(); config.setSocketAddr(StreamConfiguration.SERVER_ADDRESS, InetSocketAddress.createUnresolved(nodi.bufferServerHost, nodi.bufferServerPort)); BufferServerOutputStream bsos = new BufferServerOutputStream(StramUtils.getSerdeInstance(nodi.serDeClassName)); bsos.setup(config); logger.debug("deployed a buffer stream {}", bsos); sinkIdentifier = "tcp://".concat(nodi.bufferServerHost).concat(":").concat(String.valueOf(nodi.bufferServerPort)).concat("/").concat(sourceIdentifier); StreamContext bssc = new StreamContext(nodi.declaredStreamId); bssc.setSourceId(sourceIdentifier); bssc.setSinkId(sinkIdentifier); Sink s = bsos.connect(Component.INPUT, stream); stream.connect(sinkIdentifier, s); streams.put(sinkIdentifier, new ComponentContextPair<Stream, StreamContext>(bsos, bssc)); logger.debug("stored stream {} against key {}", bsos, sinkIdentifier); } } if (!streams.containsKey(sourceIdentifier)) { Sink s = stream.connect(Component.INPUT, node); node.connect(nodi.portName, s); StreamContext context = new StreamContext(nodi.declaredStreamId); context.setSourceId(sourceIdentifier); context.setSinkId(sinkIdentifier); streams.put(sourceIdentifier, new ComponentContextPair<Stream, StreamContext>(stream, context)); logger.debug("stored stream {} against key {}", stream, sourceIdentifier); } } } } private void deployInputStreams(List<NodeDeployInfo> nodeList) throws Exception { // collect any input nodes along with their smallest window id, // those are subsequently used to setup the window generator ArrayList<NodeDeployInfo> inputNodes = new ArrayList<NodeDeployInfo>(); long smallestWindowId = Long.MAX_VALUE; /** * Hook up all the downstream sinks. * There are 2 places where we deal with more than sinks. The first one follows immediately for WindowGenerator. * The second case is when source for the input of some node in this container is another container. So we need * to create the stream. We need to track this stream along with other streams, and many such streams may exist, * we hash them against buffer server info as we did for outputs but throw in the sinkid in the mix as well. */ for (NodeDeployInfo ndi: nodeList) { if (ndi.inputs == null || ndi.inputs.isEmpty()) { /** * This has to be AbstractInputNode, so let's hook the WindowGenerator to it. * A node which does not take any input cannot exist in the DAG since it would be completely * unaware of the windows. So for that reason, AbstractInputNode allows Component.INPUT port. */ inputNodes.add(ndi); /** * When we activate the window Generator, we plan to activate it only from required windowId. */ if (ndi.checkpointWindowId < smallestWindowId) { smallestWindowId = ndi.checkpointWindowId; } } else { Node node = nodes.get(ndi.id).component; for (NodeDeployInfo.NodeInputDeployInfo nidi: ndi.inputs) { String sourceIdentifier = nidi.sourceNodeId.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName); String sinkIdentifier = ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName); ComponentContextPair<Stream, StreamContext> pair = streams.get(sourceIdentifier); if (pair == null) { /** * We connect to the buffer server for the input on this port. * We have already placed all the output streams for all the nodes in this container yet, there is no stream * which can source this port so it has to come from the buffer server, so let's make a connection to it. */ assert (nidi.isInline() == false); StreamConfiguration config = new StreamConfiguration(); config.setSocketAddr(StreamConfiguration.SERVER_ADDRESS, InetSocketAddress.createUnresolved(nidi.bufferServerHost, nidi.bufferServerPort)); Stream stream = new BufferServerInputStream(StramUtils.getSerdeInstance(nidi.serDeClassName)); stream.setup(config); logger.debug("deployed buffer input stream {}", stream); StreamContext context = new StreamContext(nidi.declaredStreamId); context.setPartitions(nidi.partitionKeys); context.setSourceId(sourceIdentifier); context.setSinkId(sinkIdentifier); Sink s = node.connect(nidi.portName, stream); stream.connect(sinkIdentifier, ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink(stream, sinkIdentifier, s, ndi.checkpointWindowId) : s); streams.put(sinkIdentifier, new ComponentContextPair<Stream, StreamContext>(stream, context)); logger.debug("put input stream {} against key {}", stream, sinkIdentifier); } else { String streamSinkId = pair.context.getSinkId(); Sink s; if (streamSinkId == null) { s = node.connect(nidi.portName, pair.component); pair.context.setSinkId(sinkIdentifier); } else if (pair.component.isMultiSinkCapable()) { s = node.connect(nidi.portName, pair.component); pair.context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier)); } else { /** * we are trying to tap into existing InlineStream or BufferServerOutputStream. * Since none of those streams are MultiSinkCapable, we need to replace them with Mux. */ StreamContext context = new StreamContext(nidi.declaredStreamId); context.setSourceId(sourceIdentifier); context.setSinkId(streamSinkId.concat(", ").concat(sinkIdentifier)); Stream stream = new MuxStream(); stream.setup(new StreamConfiguration()); logger.debug("deployed input mux stream {}", stream); s = node.connect(nidi.portName, stream); streams.put(sourceIdentifier, new ComponentContextPair<Stream, StreamContext>(stream, context)); logger.debug("stored input stream {} against key {}", stream, sourceIdentifier); /** * Lets wire the MuxStream to upstream node. */ String[] nodeport = sourceIdentifier.split(NODE_PORT_SPLIT_SEPARATOR); Node upstreamNode = nodes.get(nodeport[0]).component; Sink muxSink = stream.connect(Component.INPUT, upstreamNode); upstreamNode.connect(nodeport[1], muxSink); Sink existingSink; if (pair.component instanceof InlineStream) { String[] np = streamSinkId.split(NODE_PORT_SPLIT_SEPARATOR); Node anotherNode = nodes.get(np[0]).component; existingSink = anotherNode.connect(np[1], stream); /* * we do not need to do this but looks bad if leave it in limbo. */ pair.component.deactivate(); pair.component.teardown(); } else { existingSink = pair.component.connect(Component.INPUT, stream); /* * we got this stream since it was mapped against sourceId, but since * we took that place for MuxStream, we give this a new place of its own. */ streams.put(pair.context.getSinkId(), pair); logger.debug("relocated stream {} against key {}", pair.context.getSinkId()); } stream.connect(streamSinkId, existingSink); } if (nidi.partitionKeys == null || nidi.partitionKeys.isEmpty()) { pair.component.connect(sinkIdentifier, ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink(pair.component, sinkIdentifier, s, ndi.checkpointWindowId) : s); } else { /* * generally speaking we do not have partitions on the inline streams so the control should not * come here but if it comes, then we are ready to handle it using the partition aware streams. */ PartitionAwareSink pas = new PartitionAwareSink(StramUtils.getSerdeInstance(nidi.serDeClassName), nidi.partitionKeys, s); pair.component.connect(sinkIdentifier, ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink(pair.component, sinkIdentifier, pas, ndi.checkpointWindowId) : pas); } } } } } if (!inputNodes.isEmpty()) { WindowGenerator windowGenerator = setupWindowGenerator(smallestWindowId); for (NodeDeployInfo ndi: inputNodes) { generators.put(ndi.id, windowGenerator); Node node = nodes.get(ndi.id).component; Sink s = node.connect(Component.INPUT, windowGenerator); windowGenerator.connect(ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(Component.INPUT), ndi.checkpointWindowId > 0 ? new WindowIdActivatedSink(windowGenerator, ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(Component.INPUT), s, ndi.checkpointWindowId) : s); } } } /** * Create the window generator for the given start window id. * This is a hook for tests to control the window generation. * * @param smallestWindowId * @return */ protected WindowGenerator setupWindowGenerator(long smallestWindowId) { WindowGenerator windowGenerator = new WindowGenerator(new ScheduledThreadPoolExecutor(1)); /** * let's make sure that we send the same window Ids with the same reset windows. */ // let's see if we want to send the exact same window id even the second time. NodeConfiguration config = new NodeConfiguration("doesn't matter", null); config.setLong(WindowGenerator.RESET_WINDOW_MILLIS, firstWindowMillis); if (smallestWindowId > firstWindowMillis) { config.setLong(WindowGenerator.FIRST_WINDOW_MILLIS, (smallestWindowId >> 32) * 1000 + windowWidthMillis * (smallestWindowId & WindowGenerator.MAX_WINDOW_ID)); } else { config.setLong(WindowGenerator.FIRST_WINDOW_MILLIS, firstWindowMillis); } config.setInt(WindowGenerator.WINDOW_WIDTH_MILLIS, windowWidthMillis); windowGenerator.setup(config); return windowGenerator; } @SuppressWarnings({"SleepWhileInLoop", "SleepWhileHoldingLock"}) public synchronized void activate(List<NodeDeployInfo> nodeList) { for (ComponentContextPair<Stream, StreamContext> pair: streams.values()) { if (!(pair.component instanceof SocketInputStream || activeStreams.containsKey(pair.component))) { activeStreams.put(pair.component, pair.context); pair.component.activate(pair.context); } } final AtomicInteger activatedNodeCount = new AtomicInteger(activeNodes.size()); for (final NodeDeployInfo ndi: nodeList) { final ComponentContextPair<Node, NodeContext> pair = nodes.get(ndi.id); assert (!activeNodes.containsKey(pair.component)); logger.debug("activating node {} in container {}", pair.component.toString(), containerId); new Thread(pair.component.toString()) { @Override public void run() { activatedNodeCount.incrementAndGet(); activeNodes.put(pair.component, pair.context); pair.component.activate(pair.context); activeNodes.remove(pair.component); disconnectNode(ndi.id); } }.start(); } /** * we need to make sure that before any of the nodes gets the first message, it's activated. */ try { do { Thread.sleep(20); } while (activatedNodeCount.get() < nodes.size()); } catch (InterruptedException ex) { logger.debug(ex.getLocalizedMessage()); } for (ComponentContextPair<Stream, StreamContext> pair: streams.values()) { if (pair.component instanceof SocketInputStream && !activeStreams.containsKey(pair.component)) { activeStreams.put(pair.component, pair.context); pair.component.activate(pair.context); } } for (WindowGenerator wg: generators.values()) { if (!activeGenerators.containsKey(wg)) { activeGenerators.put(wg, generators); wg.activate(null); } } } private void groupInputStreams(HashMap<String, ArrayList<String>> groupedInputStreams, NodeDeployInfo ndi) { for (NodeDeployInfo.NodeInputDeployInfo nidi: ndi.inputs) { String source = nidi.sourceNodeId.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.sourcePortName); /** * if we do not want to combine multiple streams with different partitions from the * same upstream node, we could also use the partition to group the streams together. * This logic comes with the danger that the performance of the group which shares the same * stream is bounded on the higher side by the performance of the lowest performer. May be * combining the streams is not such a good thing but let's see if we allow this as an option * to the user, what they end up choosing the most. */ ArrayList<String> collection = groupedInputStreams.get(source); if (collection == null) { collection = new ArrayList<String>(); groupedInputStreams.put(source, collection); } collection.add(ndi.id.concat(NODE_PORT_CONCAT_SEPARATOR).concat(nidi.portName)); } } private class HdfsBackupAgent implements BackupAgent { private final NodeSerDe serDe; private HdfsBackupAgent(NodeSerDe serde) { serDe = serde; } @Override public void backup(String nodeId, long windowId, Object o) throws IOException { FileSystem fs = FileSystem.get(conf); Path path = new Path(StramChild.this.checkpointDfsPath + "/" + nodeId + "/" + windowId); logger.debug("Backup path: {}", path); FSDataOutputStream output = fs.create(path); try { serDe.write(o, output); // record last backup window id for heartbeat StramChild.this.backupInfo.put(nodeId, windowId); } finally { output.close(); } } @Override public Object restore(String id, long windowId) throws IOException { FileSystem fs = FileSystem.get(conf); FSDataInputStream input = fs.open(new Path(StramChild.this.checkpointDfsPath + "/" + id + "/" + windowId)); try { return serDe.read(input); } finally { input.close(); } } } }
package com.blamejared.mcbot.commands; import java.awt.Color; import java.io.IOException; import java.net.SocketTimeoutException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.time.LocalDateTime; import java.util.Comparator; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang3.StringUtils; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.blamejared.mcbot.commands.api.Argument; import com.blamejared.mcbot.commands.api.Command; import com.blamejared.mcbot.commands.api.CommandBase; import com.blamejared.mcbot.commands.api.CommandContext; import com.blamejared.mcbot.commands.api.CommandException; import com.blamejared.mcbot.commands.api.Flag; import com.blamejared.mcbot.util.BakedMessage; import com.blamejared.mcbot.util.DefaultNonNull; import com.blamejared.mcbot.util.NonNull; import com.blamejared.mcbot.util.Nullable; import com.blamejared.mcbot.util.PaginatedMessageFactory; import com.blamejared.mcbot.util.Threads; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import lombok.Value; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.util.EmbedBuilder; @Command public class CommandCurse extends CommandBase { @Value @DefaultNonNull private static final class ModInfo implements Comparable<ModInfo> { String name; String URL; String[] tags; long mdownloads, downloads; @Nullable Document modpage; SortStrategy sort; @Override public int compareTo(@SuppressWarnings("null") ModInfo o) { return sort.compare(this, o); } } private enum SortStrategy implements Comparator<ModInfo> { ALPHABETICAL { @Override public int compare(ModInfo o1, ModInfo o2) { return o1.getName().compareTo(o2.getName()); } }, DOWNLOADS { @Override public int compare(ModInfo o1, ModInfo o2) { return Long.compare(o2.getDownloads(), o1.getDownloads()); } } } private static final Argument<String> ARG_USERNAME = new WordArgument("username", "The curse username of the mod author.", true); private static final Flag FLAG_MINI = new SimpleFlag("m", "Only produces the first page, for fast (but cursory) results.", false) { public String longFormName() { return "mini"; } }; private static final Flag FLAG_SORT = new SimpleFlag("s", "Controls the sorting of mods. Possible values: a[lphabetical], d[ownloads]", true) { public String longFormName() { return "sort"; } }; public CommandCurse() { super("curse", false, Lists.newArrayList(FLAG_MINI, FLAG_SORT), Lists.newArrayList(ARG_USERNAME)); } private final Random rand = new Random(); @Override public void process(CommandContext ctx) throws CommandException { long time = System.currentTimeMillis(); String user = ctx.getArg(ARG_USERNAME); rand.setSeed(user.hashCode()); int color = Color.HSBtoRGB(rand.nextFloat(), 1, 1); String authorName = ctx.getMessage().getAuthor().getDisplayName(ctx.getGuild()) + " requested"; String authorIcon = ctx.getMessage().getAuthor().getAvatarURL(); IMessage waitMsg = ctx.hasFlag(FLAG_MINI) ? null : ctx.reply("Please wait, this may take a while..."); ctx.getChannel().setTypingStatus(true); PaginatedMessageFactory.Builder msgbuilder = PaginatedMessageFactory.INSTANCE.builder(ctx.getChannel()); try { Document doc; try { doc = getDocumentSafely(String.format("https://mods.curse.com/members/%s/projects", user)); } catch (HttpStatusException e) { if (e.getStatusCode() / 100 == 4) { throw new CommandException("User " + user + " does not exist."); } throw e; } String username = doc.getElementsByClass("username").first().text(); String avatar = doc.getElementsByClass("avatar").first().child(0).child(0).attr("src"); String title = "Information on: " + username; SortStrategy sort = Optional.ofNullable(ctx.getFlag(FLAG_SORT)).map(s -> { for (SortStrategy strat : SortStrategy.values()) { if ((s.length() == 1 && Character.toUpperCase(s.charAt(0)) == strat.name().charAt(0)) || strat.name().equalsIgnoreCase(s)) { return strat; } } return null; }).orElse(SortStrategy.ALPHABETICAL); Set<ModInfo> mods = new TreeSet<>(); Element nextPageButton = null; // Always run first page do { // After first page if (nextPageButton != null) { doc = getDocumentSafely("https://mods.curse.com" + nextPageButton.child(0).attr("href")); } // Get all detail titles, map to their only child (<a> tag) doc.getElementsByTag("dt").stream().map(ele -> ele.child(0)).forEach(ele -> { ctx.getChannel().setTypingStatus(true); // make sure this stays active // Mod name is the text, mod URL is the link target @SuppressWarnings("null") @NonNull String mod = ele.text(); @SuppressWarnings("null") @NonNull String url = ele.attr("href"); // Navigate up to <dl> and grab second child, which is the <dd> with tags, get all <a> tags from them @SuppressWarnings("null") @NonNull String[] tags = ele.parent().parent().child(1).getElementsByTag("a").stream().map(e -> e.text()).toArray(String[]::new); if (ctx.hasFlag(FLAG_MINI)) { mods.add(new ModInfo(mod, url, tags, 0, 0, null, sort)); } else { try { Document modpage = getDocumentSafely("https://mods.curse.com" + url); long mdownloads = Long.parseLong(modpage.getElementsByClass("average-downloads").first().text().replaceAll("(Monthly Downloads|,)", "").trim()); long downloads = Long.parseLong(modpage.getElementsByClass("downloads").first().text().replaceAll("(Total Downloads|,)", "").trim()); url = "http://mods.curse.com" + url.replaceAll(" ", "-"); mods.add(new ModInfo(mod, url, tags, mdownloads, downloads, modpage, sort)); } catch (IOException e) { e.printStackTrace(); mods.add(new ModInfo(mod, url, tags, 0, 0, null, sort)); } } }); // Try to find the next page button nextPageButton = doc.select(".b-pagination-item.next-page").first(); // If it's present, process it } while (nextPageButton != null); if (mods.isEmpty()) { throw new CommandException("User does not have any visible projects."); } // Load main curseforge page and get the total mod download count long globalDownloads = 0; if (!ctx.hasFlag(FLAG_MINI)) { globalDownloads = getDocumentSafely("https://minecraft.curseforge.com/projects").getElementsByClass("category-info").stream() .filter(e -> e.child(0).child(0).text().equals("Mods")) .findFirst() .map(e -> e.getElementsByTag("p").first().text()) .map(s -> s.substring(s.lastIndexOf("more than"), s.lastIndexOf("downloads"))) // trim out the relevant part of the string .map(s -> s.replaceAll("(more than|,)", "").trim()) // delete excess characters .map(Long::parseLong) .orElseThrow(() -> new CommandException("Could not load global downloads")); } long totalDownloads = mods.stream().mapToLong(ModInfo::getDownloads).sum(); EmbedBuilder mainpg = new EmbedBuilder() .withTitle(title) .withColor(color) .withAuthorName(authorName) .withAuthorIcon(authorIcon) .withUrl("https://mods.curse.com/members/" + user) .withThumbnail(avatar) .withTimestamp(LocalDateTime.now()) .withFooterText("Info provided by Curse/CurseForge"); if (!ctx.hasFlag(FLAG_MINI)) { mainpg.appendField("Total downloads", NumberFormat.getIntegerInstance().format(totalDownloads) + " (" + formatPercent(((double) totalDownloads / globalDownloads)) + ")", false) .withDesc("Main page"); } mainpg.appendField("Project count", Integer.toString(mods.size()), false); if (ctx.hasFlag(FLAG_MINI)) { StringBuilder top3 = new StringBuilder(); mods.stream().limit(3).forEach(mod -> top3.append("[").append(mod.getName()).append("](").append(mod.getURL()).append(")").append('\n')); mainpg.appendField("First 3", top3.toString(), false); ctx.reply(mainpg.build()); } else { StringBuilder top3 = new StringBuilder(); mods.stream().sorted((m1, m2) -> Long.compare(m2.getDownloads(), m1.getDownloads())).limit(3) .forEach(mod -> top3.append("[").append(mod.getName()).append("](").append(mod.getURL()).append(")").append(": ") .append(NumberFormat.getIntegerInstance().format(mod.getDownloads())).append('\n')); mainpg.appendField("Top 3", top3.toString(), false); msgbuilder.addPage(new BakedMessage().withEmbed(mainpg.build())); final int modsPerPage = 5; final int pages = (mods.size() / modsPerPage) + 1; for (int i = 0; i < pages; i++) { final EmbedBuilder page = new EmbedBuilder() .withTitle(title) .withDesc("Mods page " + (i + 1) + "/" + pages) .withColor(color) .withAuthorName(authorName) .withAuthorIcon(authorIcon) .withUrl("https://mods.curse.com/members/" + user) .withTimestamp(LocalDateTime.now()) .withThumbnail(avatar); mods.stream().skip(modsPerPage * i).limit(modsPerPage).forEach(mod -> { StringBuilder desc = new StringBuilder(); desc.append("[Link](" + mod.getURL() + ")\n"); desc.append("Tags: ").append(Joiner.on(" | ").join(mod.getTags())).append("\n"); desc.append("Downloads: ") .append(DecimalFormat.getIntegerInstance().format(mod.getDownloads())) .append(" (").append(formatPercent((double) mod.getDownloads() / totalDownloads)).append(" of total) | ") .append(shortNum(mod.getMdownloads())).append("/month\n"); String role = mod.getModpage() == null ? "Error!" : mod.getModpage().getElementsByClass("authors").first().children().stream() .filter(el -> StringUtils.containsIgnoreCase(el.children().text(), username)) .findFirst() .map(Element::ownText) .map(s -> s.trim().substring(0, s.indexOf(':'))) .orElse("Unknown"); page.appendField(mod.getName() + " | " + role + "", desc.toString(), false); }); msgbuilder.addPage(new BakedMessage().withEmbed(page.build())); } waitMsg.delete(); msgbuilder.setParent(ctx.getMessage()).setProtected(false).build().send(); } } catch (IOException e) { throw new CommandException(e); } finally { if (waitMsg != null) waitMsg.delete(); ctx.getChannel().setTypingStatus(false); } System.out.println("Took: " + (System.currentTimeMillis()-time)); } private String shortNum(long num) { NumberFormat fmt = DecimalFormat.getIntegerInstance(); if (num < 1_000) { return fmt.format(num); } else if (num < 1_000_000) { return fmt.format(num / 1_000) + "k"; } else if (num < 1_000_000_000) { return fmt.format(num / 1_000_000) + "M"; } return fmt.format(num / 1_000_000_000) + "B"; } private Document getDocumentSafely(String url) throws IOException { Document ret = null; while (ret == null) { try { ret = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1").get(); } catch (SocketTimeoutException e) { System.out.println("Caught timeout loading URL: " + url); System.out.println("Retrying in 5 seconds..."); Threads.sleep(5000); } catch (IOException e) { throw e; } } return ret; } private final String formatPercent(double pct) { NumberFormat pctFmt = DecimalFormat.getPercentInstance(); pctFmt.setMaximumFractionDigits(pct >= 0.1 ? 0 : pct >= 0.01 ? 1 : 4); return pctFmt.format(pct); } public String getDescription() { return "Displays download counts for all of a modder's curse projects."; } }
package com.borderfree.kata.numerals; import java.util.EnumSet; public class RomanNumerals { private static class AccNumeral { final String str; final int remaining; public AccNumeral(String str, int remaining) { this.str = str; this.remaining = remaining; } } private enum RomanNumeral { OneThousand(1000, "M"), NineHundred(900, "CM"), FiveHundred(500, "D"), FourHundred(400, "CD"), OneHundred(100, "C"), Ninety(90, "XC"), Fifty(50, "L"), Forty(40, "XL"), Ten(10, "X"), Nine(9, "IX"), Five(5, "V"), Four(4, "IV"), One(1, "I"); final int arabic; final String roman; RomanNumeral(int arabic, String roman) { this.arabic = arabic; this.roman = roman; } } final static EnumSet<RomanNumeral> romanNumerals = EnumSet.allOf(RomanNumeral.class); public static String arabicToRoman(final int arabic) { final AccNumeral result = romanNumerals.stream().reduce(new AccNumeral("", arabic), RomanNumerals::appendRomanNumeral, (accNumeral, accNumeral2) -> new AccNumeral(accNumeral.str + accNumeral2.str, accNumeral.remaining - accNumeral2.remaining)); return result.str; } private static AccNumeral appendRomanNumeral(final AccNumeral acc, final RomanNumeral romanNumeral) { if (acc.remaining >= romanNumeral.arabic) { return appendRomanNumeral(new AccNumeral(acc.str + romanNumeral.roman, acc.remaining - romanNumeral.arabic), romanNumeral); } else { return acc; } } }
package cpw.mods.fml.client; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.multiplayer.GuiConnecting; import net.minecraft.client.multiplayer.NetClientHandler; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.renderer.entity.Render; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.resources.FileResourcePack; import net.minecraft.client.resources.FolderResourcePack; import net.minecraft.client.resources.ReloadableResourceManager; import net.minecraft.client.resources.ResourcePack; import net.minecraft.client.resources.SimpleReloadableResourceManager; import net.minecraft.crash.CrashReport; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.INetworkManager; import net.minecraft.network.packet.NetHandler; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.Packet131MapData; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.MapDifference; import com.google.common.collect.MapDifference.ValueDifference; import com.google.common.collect.Maps; import cpw.mods.fml.client.modloader.ModLoaderClientHelper; import cpw.mods.fml.client.registry.KeyBindingRegistry; import cpw.mods.fml.client.registry.RenderingRegistry; import cpw.mods.fml.common.DummyModContainer; import cpw.mods.fml.common.DuplicateModsFoundException; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.IFMLSidedHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.LoaderException; import cpw.mods.fml.common.MetadataCollection; import cpw.mods.fml.common.MissingModsException; import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.common.ObfuscationReflectionHelper; import cpw.mods.fml.common.WrongMinecraftVersionException; import cpw.mods.fml.common.network.EntitySpawnAdjustmentPacket; import cpw.mods.fml.common.network.EntitySpawnPacket; import cpw.mods.fml.common.network.ModMissingPacket; import cpw.mods.fml.common.registry.EntityRegistry.EntityRegistration; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.IEntityAdditionalSpawnData; import cpw.mods.fml.common.registry.IThrowableEntity; import cpw.mods.fml.common.registry.ItemData; import cpw.mods.fml.common.registry.LanguageRegistry; import cpw.mods.fml.common.toposort.ModSortingException; import cpw.mods.fml.relauncher.Side; /** * Handles primary communication from hooked code into the system * * The FML entry point is {@link #beginMinecraftLoading(Minecraft, List)} called from * {@link Minecraft} * * Obfuscated code should focus on this class and other members of the "server" * (or "client") code * * The actual mod loading is handled at arms length by {@link Loader} * * It is expected that a similar class will exist for each target environment: * Bukkit and Client side. * * It should not be directly modified. * * @author cpw * */ public class FMLClientHandler implements IFMLSidedHandler { /** * The singleton */ private static final FMLClientHandler INSTANCE = new FMLClientHandler(); /** * A reference to the server itself */ private Minecraft client; private DummyModContainer optifineContainer; private boolean guiLoaded; private boolean serverIsRunning; private MissingModsException modsMissing; private ModSortingException modSorting; private boolean loading = true; private WrongMinecraftVersionException wrongMC; private CustomModLoadingErrorDisplayException customError; private DuplicateModsFoundException dupesFound; private boolean serverShouldBeKilledQuietly; private List<ResourcePack> resourcePackList; private ReloadableResourceManager resourceManager; private Map<String, ResourcePack> resourcePackMap; /** * Called to start the whole game off * * @param minecraft The minecraft instance being launched * @param resourcePackList The resource pack list we will populate with mods * @param resourceManager The resource manager */ public void beginMinecraftLoading(Minecraft minecraft, List resourcePackList, ReloadableResourceManager resourceManager) { client = minecraft; this.resourcePackList = resourcePackList; this.resourceManager = resourceManager; this.resourcePackMap = Maps.newHashMap(); if (minecraft.func_71355_q()) { FMLLog.severe("DEMO MODE DETECTED, FML will not work. Finishing now."); haltGame("FML will not run in demo mode", new RuntimeException()); return; } // TextureFXManager.instance().setClient(client); FMLCommonHandler.instance().beginLoading(this); new ModLoaderClientHelper(client); try { Class<?> optifineConfig = Class.forName("Config", false, Loader.instance().getModClassLoader()); String optifineVersion = (String) optifineConfig.getField("VERSION").get(null); Map<String,Object> dummyOptifineMeta = ImmutableMap.<String,Object>builder().put("name", "Optifine").put("version", optifineVersion).build(); ModMetadata optifineMetadata = MetadataCollection.from(getClass().getResourceAsStream("optifinemod.info"),"optifine").getMetadataForId("optifine", dummyOptifineMeta); optifineContainer = new DummyModContainer(optifineMetadata); FMLLog.info("Forge Mod Loader has detected optifine %s, enabling compatibility features",optifineContainer.getVersion()); } catch (Exception e) { optifineContainer = null; } try { Loader.instance().loadMods(); } catch (WrongMinecraftVersionException wrong) { wrongMC = wrong; } catch (DuplicateModsFoundException dupes) { dupesFound = dupes; } catch (MissingModsException missing) { modsMissing = missing; } catch (ModSortingException sorting) { modSorting = sorting; } catch (CustomModLoadingErrorDisplayException custom) { FMLLog.log(Level.SEVERE, custom, "A custom exception was thrown by a mod, the game will now halt"); customError = custom; } catch (LoaderException le) { haltGame("There was a severe problem during mod loading that has caused the game to fail", le); return; } } @Override public void haltGame(String message, Throwable t) { client.func_71377_b(new CrashReport(message, t)); throw Throwables.propagate(t); } /** * Called a bit later on during initialization to finish loading mods * Also initializes key bindings * */ @SuppressWarnings("deprecation") public void finishMinecraftLoading() { if (modsMissing != null || wrongMC != null || customError!=null || dupesFound!=null || modSorting!=null) { return; } try { Loader.instance().initializeMods(); } catch (CustomModLoadingErrorDisplayException custom) { FMLLog.log(Level.SEVERE, custom, "A custom exception was thrown by a mod, the game will now halt"); customError = custom; return; } catch (LoaderException le) { haltGame("There was a severe problem during mod loading that has caused the game to fail", le); return; } // Reload resources client.func_110436_a(); RenderingRegistry.instance().loadEntityRenderers((Map<Class<? extends Entity>, Render>)RenderManager.field_78727_a.field_78729_o); loading = false; KeyBindingRegistry.instance().uploadKeyBindingsToGame(client.field_71474_y); } public void onInitializationComplete() { if (wrongMC != null) { client.func_71373_a(new GuiWrongMinecraft(wrongMC)); } else if (modsMissing != null) { client.func_71373_a(new GuiModsMissing(modsMissing)); } else if (dupesFound != null) { client.func_71373_a(new GuiDupesFound(dupesFound)); } else if (modSorting != null) { client.func_71373_a(new GuiSortingProblem(modSorting)); } else if (customError != null) { client.func_71373_a(new GuiCustomModLoadingErrorScreen(customError)); } else { // Force renderengine to reload and re-initialize all textures // client.field_71446_o.func_78352_b(); // TextureFXManager.instance().loadTextures(client.field_71418_C.func_77292_e()); } } /** * Get the server instance */ public Minecraft getClient() { return client; } /** * Get a handle to the client's logger instance * The client actually doesn't have one- so we return null */ public Logger getMinecraftLogger() { return null; } /** * @return the instance */ public static FMLClientHandler instance() { return INSTANCE; } /** * @param player * @param gui */ public void displayGuiScreen(EntityPlayer player, GuiScreen gui) { if (client.field_71439_g==player && gui != null) { client.func_71373_a(gui); } } /** * @param mods */ public void addSpecialModEntries(ArrayList<ModContainer> mods) { if (optifineContainer!=null) { mods.add(optifineContainer); } } @Override public List<String> getAdditionalBrandingInformation() { if (optifineContainer!=null) { return Arrays.asList(String.format("Optifine %s",optifineContainer.getVersion())); } else { return ImmutableList.<String>of(); } } @Override public Side getSide() { return Side.CLIENT; } public boolean hasOptifine() { return optifineContainer!=null; } @Override public void showGuiScreen(Object clientGuiElement) { GuiScreen gui = (GuiScreen) clientGuiElement; client.func_71373_a(gui); } @Override public Entity spawnEntityIntoClientWorld(EntityRegistration er, EntitySpawnPacket packet) { WorldClient wc = client.field_71441_e; Class<? extends Entity> cls = er.getEntityClass(); try { Entity entity; if (er.hasCustomSpawning()) { entity = er.doCustomSpawning(packet); } else { entity = (Entity)(cls.getConstructor(World.class).newInstance(wc)); int offset = packet.entityId - entity.field_70157_k; entity.field_70157_k = packet.entityId; entity.func_70012_b(packet.scaledX, packet.scaledY, packet.scaledZ, packet.scaledYaw, packet.scaledPitch); if (entity instanceof EntityLiving) { ((EntityLiving)entity).field_70759_as = packet.scaledHeadYaw; } Entity parts[] = entity.func_70021_al(); if (parts != null) { for (int j = 0; j < parts.length; j++) { parts[j].field_70157_k += offset; } } } entity.field_70118_ct = packet.rawX; entity.field_70117_cu = packet.rawY; entity.field_70116_cv = packet.rawZ; if (entity instanceof IThrowableEntity) { Entity thrower = client.field_71439_g.field_70157_k == packet.throwerId ? client.field_71439_g : wc.func_73045_a(packet.throwerId); ((IThrowableEntity)entity).setThrower(thrower); } if (packet.metadata != null) { entity.func_70096_w().func_75687_a((List)packet.metadata); } if (packet.throwerId > 0) { entity.func_70016_h(packet.speedScaledX, packet.speedScaledY, packet.speedScaledZ); } if (entity instanceof IEntityAdditionalSpawnData) { ((IEntityAdditionalSpawnData)entity).readSpawnData(packet.dataStream); } wc.func_73027_a(packet.entityId, entity); return entity; } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "A severe problem occurred during the spawning of an entity"); throw Throwables.propagate(e); } } @Override public void adjustEntityLocationOnClient(EntitySpawnAdjustmentPacket packet) { Entity ent = client.field_71441_e.func_73045_a(packet.entityId); if (ent != null) { ent.field_70118_ct = packet.serverX; ent.field_70117_cu = packet.serverY; ent.field_70116_cv = packet.serverZ; } else { FMLLog.fine("Attempted to adjust the position of entity %d which is not present on the client", packet.entityId); } } @Override public void beginServerLoading(MinecraftServer server) { serverShouldBeKilledQuietly = false; // NOOP } @Override public void finishServerLoading() { // NOOP } @Override public MinecraftServer getServer() { return client.func_71401_C(); } @Override public void sendPacket(Packet packet) { if(client.field_71439_g != null) { client.field_71439_g.field_71174_a.func_72552_c(packet); } } @Override public void displayMissingMods(ModMissingPacket modMissingPacket) { client.func_71373_a(new GuiModsMissingForServer(modMissingPacket)); } /** * If the client is in the midst of loading, we disable saving so that custom settings aren't wiped out */ public boolean isLoading() { return loading; } @Override public void handleTinyPacket(NetHandler handler, Packet131MapData mapData) { ((NetClientHandler)handler).fmlPacket131Callback(mapData); } @Override public void setClientCompatibilityLevel(byte compatibilityLevel) { NetClientHandler.setConnectionCompatibilityLevel(compatibilityLevel); } @Override public byte getClientCompatibilityLevel() { return NetClientHandler.getConnectionCompatibilityLevel(); } public void warnIDMismatch(MapDifference<Integer, ItemData> idDifferences, boolean mayContinue) { GuiIdMismatchScreen mismatch = new GuiIdMismatchScreen(idDifferences, mayContinue); client.func_71373_a(mismatch); } public void callbackIdDifferenceResponse(boolean response) { if (response) { serverShouldBeKilledQuietly = false; GameData.releaseGate(true); client.continueWorldLoading(); } else { serverShouldBeKilledQuietly = true; GameData.releaseGate(false); // Reset and clear the client state client.func_71403_a((WorldClient)null); client.func_71373_a(null); } } @Override public boolean shouldServerShouldBeKilledQuietly() { return serverShouldBeKilledQuietly; } @Override public void disconnectIDMismatch(MapDifference<Integer, ItemData> s, NetHandler toKill, INetworkManager mgr) { boolean criticalMismatch = !s.entriesOnlyOnLeft().isEmpty(); for (Entry<Integer, ValueDifference<ItemData>> mismatch : s.entriesDiffering().entrySet()) { ValueDifference<ItemData> vd = mismatch.getValue(); if (!vd.leftValue().mayDifferByOrdinal(vd.rightValue())) { criticalMismatch = true; } } if (!criticalMismatch) { // We'll carry on with this connection, and just log a message instead return; } // Nuke the connection ((NetClientHandler)toKill).func_72553_e(); // Stop GuiConnecting GuiConnecting.forceTermination((GuiConnecting)client.field_71462_r); // pulse the network manager queue to clear cruft mgr.func_74428_b(); // Nuke the world client client.func_71403_a((WorldClient)null); // Show error screen warnIDMismatch(s, false); } /** * Is this GUI type open? * * @param gui The type of GUI to test for * @return if a GUI of this type is open */ public boolean isGUIOpen(Class<? extends GuiScreen> gui) { return client.field_71462_r != null && client.field_71462_r.getClass().equals(gui); } @Override public void addModAsResource(ModContainer container) { Class<?> resourcePackType = container.getCustomResourcePackClass(); if (resourcePackType != null) { try { ResourcePack pack = (ResourcePack) resourcePackType.getConstructor(ModContainer.class).newInstance(container); resourcePackList.add(pack); resourcePackMap.put(container.getModId(), pack); } catch (NoSuchMethodException e) { FMLLog.log(Level.SEVERE, "The container %s (type %s) returned an invalid class for it's resource pack.", container.getName(), container.getClass().getName()); return; } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "An unexpected exception occurred constructing the custom resource pack for %s", container.getName()); throw Throwables.propagate(e); } } } @Override public void updateResourcePackList() { client.func_110436_a(); } public ResourcePack getResourcePackFor(String modId) { return resourcePackMap.get(modId); } @Override public String getCurrentLanguage() { return client.func_135016_M().func_135041_c().func_135034_a(); } @Override public void serverStopped() { // If the server crashes during startup, it might hang the client- reset the client so it can abend properly. MinecraftServer server = getServer(); if (server != null && !server.func_71200_ad()) { ObfuscationReflectionHelper.setPrivateValue(MinecraftServer.class, server, true, "field_71296"+"_Q","serverIs"+"Running"); } } }
package com.btk5h.skriptmirror.skript; import com.btk5h.skriptmirror.Descriptor; import com.btk5h.skriptmirror.JavaType; import com.btk5h.skriptmirror.LRUCache; import com.btk5h.skriptmirror.Util; import org.bukkit.event.Event; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import ch.njol.skript.Skript; import ch.njol.skript.SkriptAPIException; import ch.njol.skript.classes.Changer; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.ExpressionType; import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.UnparsedLiteral; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.skript.registrations.Converters; import ch.njol.skript.util.Utils; import ch.njol.util.Checker; import ch.njol.util.Kleenean; import ch.njol.util.coll.iterator.ArrayIterator; public class ExprJavaCall<T> implements Expression<T> { private static final MethodHandles.Lookup LOOKUP = MethodHandles.publicLookup(); private static final Object[] EMPTY = new Object[0]; private static final Descriptor CONSTRUCTOR_DESCRIPTOR = Descriptor.create("<init>"); private static final Map<Class<?>, Class<?>> WRAPPER_CLASSES = new HashMap<>(); private static final Set<Class<?>> NUMERIC_CLASSES = new HashSet<>(); static { WRAPPER_CLASSES.put(boolean.class, Boolean.class); WRAPPER_CLASSES.put(byte.class, Byte.class); WRAPPER_CLASSES.put(char.class, Character.class); WRAPPER_CLASSES.put(double.class, Double.class); WRAPPER_CLASSES.put(float.class, Float.class); WRAPPER_CLASSES.put(int.class, Integer.class); WRAPPER_CLASSES.put(long.class, Long.class); WRAPPER_CLASSES.put(short.class, Short.class); NUMERIC_CLASSES.add(byte.class); NUMERIC_CLASSES.add(double.class); NUMERIC_CLASSES.add(float.class); NUMERIC_CLASSES.add(int.class); NUMERIC_CLASSES.add(long.class); NUMERIC_CLASSES.add(short.class); } static { //noinspection unchecked Skript.registerExpression(ExprJavaCall.class, Object.class, ExpressionType.PATTERN_MATCHES_EVERYTHING, "%object%..%string%(0¦!|1¦\\([%-objects%]\\))", "%object%.<[\\w$.\\[\\]]+>(0¦!|1¦\\([%-objects%]\\))", "new %javatype%\\([%-objects%]\\)"); } private enum Type { FIELD, METHOD, CONSTRUCTOR; @Override public String toString() { return name().toLowerCase(); } } private LRUCache<Descriptor, Collection<MethodHandle>> callSiteCache = new LRUCache<>(8); private Expression<Object> targetArg; private Expression<Object> args; private Type type; private boolean isDynamic; private boolean suppressErrors = false; private Descriptor staticDescriptor; private Expression<String> dynamicDescriptor; private final ExprJavaCall<?> source; private final Class<? extends T>[] types; private final Class<T> superType; @SuppressWarnings("unchecked") public ExprJavaCall() { this(null, (Class<? extends T>) Object.class); } @SuppressWarnings("unchecked") @SafeVarargs private ExprJavaCall(ExprJavaCall<?> source, Class<? extends T>... types) { this.source = source; if (source != null) { this.targetArg = source.targetArg; this.args = source.args; this.type = source.type; this.suppressErrors = source.suppressErrors; this.staticDescriptor = source.staticDescriptor; this.dynamicDescriptor = source.dynamicDescriptor; } this.types = types; this.superType = (Class<T>) Utils.getSuperType(types); } private Collection<MethodHandle> getCallSite(Descriptor e) { return callSiteCache.computeIfAbsent(e, this::createCallSite); } private Collection<MethodHandle> createCallSite(Descriptor e) { Class<?> javaClass = e.getJavaClass(); switch (type) { case FIELD: return Util.fields(javaClass) .filter(f -> f.getName().equals(e.getIdentifier())) .peek(f -> f.setAccessible(true)) .flatMap(Util.propagateErrors(f -> Stream.of( LOOKUP.unreflectGetter(f), LOOKUP.unreflectSetter(f) ))) .limit(2) .collect(Collectors.toList()); case METHOD: return Util.methods(javaClass) .filter(m -> m.getName().equals(e.getIdentifier())) .peek(m -> m.setAccessible(true)) .map(Util.propagateErrors(LOOKUP::unreflect)) //.map(ExprJavaCall::asSpreader) .collect(Collectors.toList()); case CONSTRUCTOR: return Util.constructor(javaClass) .peek(c -> c.setAccessible(true)) .map(Util.propagateErrors(LOOKUP::unreflectConstructor)) //.map(ExprJavaCall::asSpreader) .collect(Collectors.toList()); default: throw new IllegalStateException(); } } private static MethodHandle asSpreader(MethodHandle mh) { int paramCount = mh.type().parameterCount(); if (mh.isVarargsCollector()) { if (paramCount == 1) { return mh; } return mh.asSpreader(Object[].class, paramCount - 1); } return mh.asSpreader(Object[].class, paramCount); } @SuppressWarnings("unchecked") private T[] invoke(Object target, Object[] arguments, Descriptor baseDescriptor) { T returnedValue = null; Class<?> targetClass = Util.toClass(target); Descriptor descriptor = specifyDescriptor(baseDescriptor, targetClass); Class<?>[] argTypes = null; if (descriptor.getJavaClass().isAssignableFrom(targetClass)) { Object[] arr; if (target instanceof JavaType) { arr = new Object[arguments.length]; System.arraycopy(arguments, 0, arr, 0, arguments.length); } else { arr = new Object[arguments.length + 1]; arr[0] = target; System.arraycopy(arguments, 0, arr, 1, arguments.length); } argTypes = Arrays.stream(arr) .map(Object::getClass) .toArray(Class<?>[]::new); Optional<MethodHandle> method = selectMethod(descriptor, argTypes); if (method.isPresent()) { MethodHandle mh = method.get(); convertTypes(mh.type(), arr); try { returnedValue = (T) mh.invokeWithArguments(arr); } catch (Throwable throwable) { if (!suppressErrors) { Skript.warning( String.format("%s (%s) -> %s called with %s (%s) threw a %s: %s%n" + "Run Skript with the verbosity 'very high' for the stack trace.", target, targetClass, toString(descriptor), Arrays.toString(arguments), Arrays.toString(argTypes), throwable.getClass(), throwable.getMessage())); if (Skript.logVeryHigh()) { StringWriter errors = new StringWriter(); throwable.printStackTrace(new PrintWriter(errors)); Skript.warning(errors.toString()); } } } } else { if (!suppressErrors) { Skript.warning( String.format("%s (%s) -> %s could not be resolved with the arguments %s (%s)", target, targetClass, toString(descriptor), Arrays.toString(arguments), Arrays.toString(argTypes))); } } } else { if (!suppressErrors) { Skript.warning(String.format("%s (%s) is not a %s", target, targetClass, descriptor.getJavaClass())); } } if (returnedValue == null) { return (T[]) EMPTY; } returnedValue = Converters.convert(returnedValue, types); if (returnedValue == null) { if (!suppressErrors) { Skript.warning( String.format("%s (%s) -> %s called with %s (%s) could not be converted to %s", target, targetClass, toString(descriptor), Arrays.toString(arguments), Arrays.toString(argTypes), Arrays.toString(types))); } return (T[]) EMPTY; } T[] returnArray = (T[]) Array.newInstance(superType, 1); returnArray[0] = returnedValue; return returnArray; } @SuppressWarnings("ThrowableNotThrown") private Descriptor getDescriptor(Event e) { if (isDynamic) { String desc = dynamicDescriptor.getSingle(e); if (desc == null) { return null; } try { return Descriptor.parse(desc); } catch (ClassNotFoundException ex) { if (!suppressErrors) { Skript.exception(ex); } return Descriptor.create(null); } } return staticDescriptor; } private static Descriptor specifyDescriptor(Descriptor descriptor, Class<?> cls) { if (descriptor.getJavaClass() != null) { return descriptor; } return Descriptor.create(cls, descriptor.getIdentifier()); } private Optional<MethodHandle> selectMethod(Descriptor descriptor, Class<?>[] argTypes) { return getCallSite(descriptor).stream() .filter(mh -> matchesArgs(argTypes, mh)) .findFirst(); } private static boolean matchesArgs(Class<?>[] args, MethodHandle mh) { MethodType mt = mh.type(); if (mt.parameterCount() != args.length && !mh.isVarargsCollector()) { return false; } Class<?>[] params = mt.parameterArray(); for (int i = 0; i < params.length; i++) { if (i == params.length - 1 && mh.isVarargsCollector()) { break; } Class<?> param = params[i]; Class<?> arg = args[i]; if (!param.isAssignableFrom(arg)) { if (Number.class.isAssignableFrom(arg) && NUMERIC_CLASSES.contains(param)) { continue; } if (param.isPrimitive() && arg == WRAPPER_CLASSES.get(param)) { continue; } return false; } } return true; } private static void convertTypes(MethodType mt, Object[] args) { if (!mt.hasPrimitives()) { return; } Class<?>[] params = mt.parameterArray(); for (int i = 0; i < params.length; i++) { Class<?> param = params[i]; if (param.isPrimitive()) { if (param == byte.class) { args[i] = ((Number) args[i]).byteValue(); } else if (param == double.class) { args[i] = ((Number) args[i]).doubleValue(); } else if (param == float.class) { args[i] = ((Number) args[i]).floatValue(); } else if (param == int.class) { args[i] = ((Number) args[i]).intValue(); } else if (param == long.class) { args[i] = ((Number) args[i]).longValue(); } else if (param == short.class) { args[i] = ((Number) args[i]).shortValue(); } } } } void setSuppressErrors(boolean suppressErrors) { this.suppressErrors = suppressErrors; if (targetArg instanceof ExprJavaCall) { ((ExprJavaCall) targetArg).setSuppressErrors(suppressErrors); } } @Override public T getSingle(Event e) { T[] all = getArray(e); if (all.length == 0) { return null; } return all[0]; } @Override public T[] getArray(Event e) { return getAll(e); } @SuppressWarnings("unchecked") @Override public T[] getAll(Event e) { Object target = targetArg.getSingle(e); Object[] arguments; if (target == null) { return null; } if (args != null) { try { arguments = args.getArray(e); } catch (SkriptAPIException ex) { Skript.error("The arguments passed to " + getDescriptor(e) + " could not be parsed. Try " + "setting a list variable to the arguments and pass that variable to the reflection " + "call instead!"); return null; } } else { arguments = EMPTY; } return invoke(target, arguments, getDescriptor(e)); } @Override public boolean isSingle() { return true; } @Override public boolean check(Event e, Checker<? super T> c, boolean negated) { return SimpleExpression.check(getAll(e), c, negated, getAnd()); } @Override public boolean check(Event e, Checker<? super T> c) { return SimpleExpression.check(getAll(e), c, false, getAnd()); } @Override public <R> Expression<? extends R> getConvertedExpression(Class<R>[] to) { return new ExprJavaCall<>(this, to); } @Override public Class<T> getReturnType() { return superType; } @Override public boolean getAnd() { return true; } @Override public boolean setTime(int time) { return false; } @Override public int getTime() { return 0; } @Override public boolean isDefault() { return false; } @Override public Iterator<? extends T> iterator(Event e) { return new ArrayIterator<>(getAll(e)); } @Override public boolean isLoopOf(String s) { return false; } @Override public Expression<?> getSource() { return source == null ? this : source; } @Override public Expression<? extends T> simplify() { return this; } @Override public String toString(Event e, boolean debug) { return toString(getDescriptor(e)); } private String toString(Descriptor descriptor) { return type + " " + descriptor; } @Override public Class<?>[] acceptChange(Changer.ChangeMode mode) { if (type == Type.FIELD && (mode == Changer.ChangeMode.SET || mode == Changer.ChangeMode.DELETE)) { return new Class<?>[]{Object.class}; } return null; } @Override public void change(Event e, Object[] delta, Changer.ChangeMode mode) { Object target = targetArg.getSingle(e); if (target == null) { return; } Object[] args = new Object[1]; switch (mode) { case SET: args[0] = delta[0]; break; case DELETE: args[0] = null; break; } invoke(target, args, getDescriptor(e)); } @SuppressWarnings("unchecked") @Override public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parseResult) { targetArg = (Expression<Object>) exprs[0]; args = (Expression<Object>) exprs[matchedPattern == 0 ? 2 : 1]; if (targetArg instanceof UnparsedLiteral || args instanceof UnparsedLiteral) { return false; } switch (matchedPattern) { case 0: isDynamic = true; type = parseResult.mark == 0 ? Type.FIELD : Type.METHOD; dynamicDescriptor = (Expression<String>) exprs[1]; break; case 1: isDynamic = false; type = parseResult.mark == 0 ? Type.FIELD : Type.METHOD; String desc = parseResult.regexes.get(0).group(); try { staticDescriptor = Descriptor.parse(desc); if (staticDescriptor == null) { Skript.error(desc + " is not a valid descriptor."); return false; } if (staticDescriptor.getJavaClass() != null && getCallSite(staticDescriptor).size() == 0) { Skript.error(desc + " refers to a non-existent method/field."); return false; } } catch (ClassNotFoundException e) { Skript.error(desc + " refers to a non-existent class."); return false; } break; case 2: type = Type.CONSTRUCTOR; staticDescriptor = CONSTRUCTOR_DESCRIPTOR; break; } return true; } }
package com.canoo.webtest.steps.request; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.xml.sax.SAXException; import com.canoo.webtest.util.FileUtil; import com.canoo.webtest.util.MapUtil; import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebRequest; /** * Performs an initial request to an url and makes the received response * available for subsequent steps. * <p> * The url may be specified as an absolute url (with protocol) that will be used * directly or as the end part of an url. In this case the protocol, host, port and basepath * properties of the &lt;config&gt; step will be used to build a complete url. * </p> * <p> * This step accepts optional &lt;httpHeader&gt; nested elements * to define the custom request headers. * </p> * @author unknown * @author Marc Guillemot * @author Paul King * @author Luke Campbell * @author Dave Parillo * @webtest.step * category="Core" * name="invoke" * description="This step executes a request to a particular URL." */ public class InvokePage extends AbstractTargetAction { private static final Logger LOG = Logger.getLogger(InvokePage.class); /** A list of the nested HttpHeader elements */ private final List<HttpHeader> headers = new ArrayList<HttpHeader>(); private String fUrl; private String fCompleteUrl; private String fMethod = "GET"; private File fContentFile; private String fContent; private String fContentType; public String getMethod() { return fMethod; } public String getUrl() { return fUrl; } public String getContentType() { return fContentType; } public String getCompleteUrl() { return fCompleteUrl; } /** * Sets the url. * * @param newUrl the relative or absolute url * @webtest.parameter required="yes" * description="A complete URL or the 'relative' part of an URL which will be appended to the 'static' parts created from the configuration information defined with the <config> step." */ public void setUrl(final String newUrl) { fUrl = newUrl; } public void setCompleteUrl(String completeUrl) { fCompleteUrl = completeUrl; } /** * Sets the Content Type * @param contentType * @webtest.parameter * required="no" * description="Sets the content-type HTTP header for POST, PATCH, and PUT requests" * default="application/x-www-form-urlencoded" */ public void setContentType(final String contentType) { fContentType = contentType; } public void setMethod(final String method) { fMethod = method; } public File getContentFile() { return fContentFile; } /** * Sets the filename of the request contents. * * @param contentFile * @webtest.parameter * required="no" * description="Filename to extract request contents from. * Ignored for GET requests. * Only one of <em>content</em> and <em>contentFile</em> should be set." */ public void setContentFile(final File contentFile) { fContentFile = contentFile; } public String getContent() { return fContent; } /** * Sets the request content. * * @param content * @webtest.parameter * required="no" * description="Form data in 'application/x-www-form-urlencoded' format, which will be sent in the body of a POST request. Ignored for GET requests. Only one of <em>content</em> and <em>contentFile</em> should be set." */ public void setContent(final String content) { fContent = content; } private boolean isContentNull() { return getContent() == null && getContentFile() == null; } /** * Adds each nested HttpHeader element to our list of headers. * @param header The HTTP header * @webtest.nested.parameter * required="no" * description="Add additional HTTP Headers to the current invoke." */ public void addHttpHeader(HttpHeader header) { headers.add(header); } public List<HttpHeader> getHeaders() { return headers; } @Override protected void verifyParameters() { super.verifyParameters(); nullParamCheck(getUrl(), "url"); paramCheck(getContent() != null && getContentFile() != null, "Only one of 'content' and 'contentFile' must be set."); if ("POST".equals(fMethod)) { paramCheck(isContentNull(), "One of 'content' or 'contentFile' must be set for POST."); } paramCheck("PUT".equals(fMethod) && isContentNull(), "One of 'content' or 'contentFile' must be set for PUT."); paramCheck("PATCH".equals(fMethod) && isContentNull(), "One of 'content' or 'contentFile' must be set for PATCH."); } /** * Returns the resulting page from the request. This method also updates * the request headers with each of the nested HttpHeader elements. */ protected Page findTarget() throws IOException, SAXException { String method = getMethod(); if ("POST".equals(method) || "PUT".equals(method) || "PATCH".equals(method)) { return findTargetByPost(); } String completeUrl = getContext().getConfig().getUrlForPage(getUrl()); setCompleteUrl(completeUrl); final WebRequest settings = new WebRequest(new URL(completeUrl)); final Map<String, String> httpHeaders = new HashMap<String, String>(); for (HttpHeader header : headers) { httpHeaders.put(header.getName(), header.getValue()); } settings.setAdditionalHeaders(httpHeaders); settings.setHttpMethod(HttpMethod.valueOf(getMethod().toUpperCase())); return getResponse(settings); } /** * Returns the resulting page from the POST/PUT/PATCH request. This method * also updates the request headers with each of the nested HttpHeader * elements. */ protected Page findTargetByPost() throws IOException, SAXException { String url = getContext().getConfig().getUrlForPage(getUrl()); final String contentType = getContentType(); final String content; final WebRequest settings = new WebRequest(new URL(url), HttpMethod.valueOf(getMethod())); // Store each extra header final Map<String, String> requestHeaders = new HashMap<String, String>(); if (!StringUtils.isEmpty(contentType)) { requestHeaders.put("Content-Type", contentType); } else { // default content-type is an HTML Form requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); } // Update the request headers with each of our nested HttpHeader // elements. for (HttpHeader header : headers) { requestHeaders.put(header.getName(), header.getValue()); } settings.setAdditionalHeaders(requestHeaders); if (getContent() != null) { content = getContent(); } else { content = FileUtil.readFileToString(getContentFile(), this); } settings.setRequestBody(content); return getResponse(settings); } protected String getLogMessageForTarget() { return "by URL: " + getUrl(); } /** * Adds the computed url if only a part was specified (nice to have in reports) */ @Override protected void addComputedParameters(final Map map) { super.addComputedParameters(map); if (!StringUtils.equals(fUrl, fCompleteUrl)) { MapUtil.putIfNotNull(map, "-> complete url", fCompleteUrl); } } /** * Container for HTTP Headers. * @author Luke Campbell * @webtest.nested * required="no" * name="httpHeader" * description="Container for HTTP Headers. * Can be used like * <invoke ...> * <httpHeader name="X-Extra-Header" value="value" /> * </invoke> * " */ public static class HttpHeader { private String name; private String value; public String getName() { return name; } public String getValue() { return value; } /** * Sets the name component of the HTTP Header * * @param name * @webtest.parameter * required="yes" * description="Sets the name component of the HTTP Header" */ public void setName(String name) { this.name = name; } /** * Sets the name component of the HTTP Header * * @param value * @webtest.parameter * required="yes" * description="Sets the value of the HTTP Header" */ public void setValue(String value) { this.value = value; } } }
package com.codebrig.jvmmechanic.agent; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.Maps; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @author Brandon Fergerson <brandon.fergerson@codebrig.com> */ public class CacheString { public static CacheString readFromBuffer(ConfigProperties configProperties, ByteBuffer buffer) { if (buffer.get() == 1) { //cached int cacheIndex = buffer.getInt(); String cacheString = cachedStrings.computeIfAbsent(cacheIndex, i -> (String) configProperties.get("cache_string_" + i)); return new CacheString(configProperties, cacheString); } else { //raw string if (buffer.get() == 1) { int strLength = buffer.getInt(); byte[] strBytes = new byte[strLength]; buffer.get(strBytes); return new CacheString(configProperties, new String(strBytes)); } else { return new CacheString(configProperties, null); } } } private static final AtomicInteger cacheIndexKey = new AtomicInteger(); private static final Map<Integer, String> cachedStrings = Maps.newConcurrentMap(); private static final Cache<String, Integer> cacheCandiates = CacheBuilder.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .build(); private final ConfigProperties configProperties; private final String string; private int cacheIndex = -1; public CacheString(ConfigProperties configProperties, String string) { this.configProperties = configProperties; this.string = string; tryToCache(); } public void writeToBuffer(ByteBuffer buffer) { boolean cache = isCachable(); buffer.put((byte)(cache ? 1 : 0)); if (cache) { buffer.putInt(cacheIndex); } else { buffer.put((byte)(getString() != null ? 1 : 0)); if (getString() != null) { byte[] strBytes = getString().getBytes(); buffer.putInt(strBytes.length); buffer.put(strBytes); } } } public String getString() { return string; } public boolean isCachable() { return getCacheIndex() != -1; } public int getCacheIndex() { return cacheIndex; } public void setCacheIndex(int cacheIndex) { this.cacheIndex = cacheIndex; } private void tryToCache() { if (getString() == null || configProperties == null) { return; } Integer possibleCacheIndex = cacheCandiates.getIfPresent(getString()); if (possibleCacheIndex != null) { configProperties.put("cache_string_" + possibleCacheIndex, getString()); configProperties.sync(); cachedStrings.put(possibleCacheIndex, getString()); setCacheIndex(possibleCacheIndex); } else { cacheCandiates.put(getString(), cacheIndexKey.getAndIncrement()); } } @Override public String toString() { return getString(); } }
package com.demigodsrpg.chitchat.format; import com.demigodsrpg.chitchat.Chitchat; import com.demigodsrpg.chitchat.tag.PlayerTag; import com.google.common.collect.ImmutableList; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import java.util.*; /** * A class representing the format of chat. */ public class ChatFormat { // -- IMPORTANT DATA -- // private final List<PlayerTag> playerTags = new LinkedList<PlayerTag>(); private final String format; // -- CONSTRUCTORS -- // /** * Create a default chat format. */ public ChatFormat() { this(Chitchat.getInst().getConfig().getString("format", "+tags&7+displayname&7: &f+message")); } /** * Create a chat format from a string representing the format. * * @param format The string representing the format. */ public ChatFormat(String format) { this.format = format; } // -- MUTATORS -- // /** * Add a player tag to the chat format. * * @param playerTag A player tag. * @return This chat format. */ public ChatFormat add(PlayerTag playerTag) { // Negative priorities don't exist if(playerTag.getPriority() < 0) { playerTags.add(0, playerTag); } // Make sure the priority fits into the linked list else if(playerTag.getPriority() + 1 > playerTags.size()) { playerTags.add(playerTag); } // Add to the correct spot else { playerTags.add(playerTag.getPriority(), playerTag); } return this; } /** * Add a collection of player tags to the chat format. * * @param playerTags A collection of player tags. * @return This chat format. */ public ChatFormat addAll(Collection<PlayerTag> playerTags) { for(PlayerTag tag : playerTags) { add(tag); } return this; } /** * Add an array of player tags to the chat format. * * @param playerTags An array of player tags. * @return This chat format. */ public ChatFormat addAll(PlayerTag[] playerTags) { for(PlayerTag tag : playerTags) { add(tag); } return this; } // -- GETTERS -- // /** * Get an immutable copy of the player tags. * * @return An immutable copy of the player tags. */ public ImmutableList<PlayerTag> getPlayerTags() { return ImmutableList.copyOf(playerTags); } /** * Get the string representation of all of the player tags. * * @param player The player for whom the tags will be applied. * @return The string of the final tag results. */ public String getTagsString(Player player) { String formatted = ""; for (PlayerTag tag : playerTags) { formatted += tag.getFor(player); } return formatted; } /** * Get the format base string. * * @return The format base string. */ public String getFormatString() { return format; } /** * Get the final formatted message for this chat format. * * @param player The player chatting. * @param message The message being sent. * @return The final formatted message. */ public String getFormattedMessage(Player player, String message) { return ChatColor.translateAlternateColorCodes('&', format. replace("+tags", getTagsString(player)). replace("+message", message). replaceAll("%", "%%"). replace("+displayname", player.getDisplayName())); } }
package com.dumptruckman.lockandkey; import org.jetbrains.annotations.NotNull; import pluginbase.config.annotation.Comment; import pluginbase.config.annotation.NoTypeKey; import pluginbase.plugin.PluginBase; import pluginbase.plugin.Settings; import java.util.ArrayList; import java.util.List; @NoTypeKey public final class PluginSettings extends Settings { private LockSettings locks = new LockSettings(); public PluginSettings(@NotNull PluginBase plugin) { super(plugin); } private PluginSettings() { } public LockSettings getLocks() { return locks; } @NoTypeKey public final static class LockSettings { @Comment({"How often to save lock data (in ticks).", "1200 ticks is approximately 1 minute"}) private long saveTicks = 1200L; @Comment({"The name of the lock creation ingredient (Redstone)"}) private String dustName = "Sealing Dust"; @Comment({"The name of the lock creation ingredient block (Redstone Block)"}) private String dustBlockName = "Concentrated Sealing Dust"; @Comment({"This section is where you can change the description on the different items from this plugin."}) private Descriptions descriptions = new Descriptions(); @Comment({"Whether or not to show the lock code as the last line of the item lore of items"}) private boolean lockCodeVisible = true; @Comment({"This is a string of all the valid characters than can be used for a lock code.", "A random selection of these will be created for every new key-lock combination."}) private String lockCodeCharacters = "ABCDEF1234567890"; @Comment({"This is the number of characters to use in a lock code.", "Having a small length and few characters raises the chance to produce keys that work on locks they were not created for."}) private int lockCodeLength = 4; public long getSaveTicks() { return saveTicks; } public String getDustName() { return dustName; } public String getDustBlockName() { return dustBlockName; } public String getLockCodeCharacters() { return lockCodeCharacters; } public int getLockCodeLength() { return lockCodeLength; } public boolean isLockCodeVisible() { return lockCodeVisible; } public Descriptions getDescriptions() { return descriptions; } @NoTypeKey public final static class Descriptions { @Comment({"This is the item description of locked items (doors, buttons, etc)"}) private List<String> lockLore; { lockLore = new ArrayList<>(); lockLore.add("This item is locked when placed."); lockLore.add("It can only be opened by the owner"); lockLore.add("or anyone with a key."); } @Comment({"This is the item description of the Sealing Dust"}) private List<String> dustLore; { dustLore = new ArrayList<>(); dustLore.add("This dust contains the"); dustLore.add("magic required to lock"); dustLore.add("objects so that only"); dustLore.add("their owner may use them."); } @Comment({"This is the item description of the Concentrated Sealing Dust"}) private List<String> dustBlockLore; { dustBlockLore = new ArrayList<>(); dustBlockLore.add("A concentrated form of"); dustBlockLore.add("Sealing Dust"); } @Comment({"This is the item description of an Uncut Key"}) private List<String> uncutKeyLore; { uncutKeyLore = new ArrayList<>(); uncutKeyLore.add("This key can be cut to fit any lock."); uncutKeyLore.add("Sneak right click the locked block"); uncutKeyLore.add("to configure this key for that block."); } @Comment({"This is the item description of an (cut) Key"}) private List<String> keyLore; { keyLore = new ArrayList<>(); keyLore.add("This key unlocks something somewhere..."); } public List<String> getLockLore() { return lockLore; } public List<String> getDustLore() { return dustLore; } public List<String> getDustBlockLore() { return dustBlockLore; } public List<String> getUncutKeyLore() { return uncutKeyLore; } public List<String> getKeyLore() { return keyLore; } } } }
package com.educode.minecraft.gui; import com.educode.helper.ArrayHelper; import com.educode.minecraft.CompilerMod; import com.educode.minecraft.networking.MessageSaveFile; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Tuple; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.apache.commons.lang3.StringUtils; import org.lwjgl.input.Keyboard; import java.io.IOException; import java.util.HashMap; import java.util.Set; import static org.lwjgl.input.Keyboard.*; @SideOnly(Side.CLIENT) public class GuiProgramEditor extends GuiScreen { private static final ResourceLocation BOOK_GUI_TEXTURES = new ResourceLocation("textures/gui/book.png"); private static String _text = ""; private static String _formattedText = ""; private static String _fileName; private static String[] _lines; private static int _position = 0; private static int _lineNumber = 0; private static int _visibleTopLine = 1; private static int _visibleBottomLine = 25; private static final String _cursorSymbol = "\uFEFF"; private static final String _cursorSymbolVisible = "|"; private static int _positionInLine = 0; public GuiProgramEditor() { super(); } public static void setFileName(String name) { _fileName = name; } private static String testWords(String[] words, HashMap<String[], TextFormatting> keyWordMap, String[] partialKeywords) { boolean buildingString = false; Tuple<Integer, String[]> keywords; String partial = ""; StringBuilder formattedLine = new StringBuilder(); for (String word : words) { if (word.replace(_cursorSymbol, "").contains("Collection<")) { String[] collectionCollection = word.split("(<)"); if(ArrayHelper.characterCountInArray(">", collectionCollection) == collectionCollection.length - 1) { StringBuilder finalCollection = new StringBuilder(TextFormatting.AQUA.toString()); for (int i = 0; i < collectionCollection.length-1; i++) { finalCollection.append(collectionCollection[i]).append("<"); } String type; if (collectionCollection[collectionCollection.length - 1].contains(">" + _cursorSymbol)) { type = collectionCollection[collectionCollection.length-1].replace(">", "").replace(_cursorSymbol, ""); } else { type = collectionCollection[collectionCollection.length-1].replace(">", ""); } keywords = testWord(type.replace(_cursorSymbol, ""), keyWordMap.keySet(), partialKeywords); switch(keywords.getFirst()) { case 0: finalCollection.append(TextFormatting.WHITE).append(type).append(TextFormatting.AQUA); break; case 1: finalCollection.append(type); break; case 2: finalCollection.append(TextFormatting.WHITE).append(type).append(TextFormatting.AQUA); break; } String debug = collectionCollection[collectionCollection.length-1].replace(type, ""); finalCollection.append(debug); formattedLine.append(finalCollection).append(TextFormatting.WHITE.toString()); continue; } } if (buildingString) { if (word.contains("\"")) { buildingString = false; StringBuilder stringEnd = new StringBuilder(word); stringEnd.insert(word.indexOf("\"") + 1, TextFormatting.WHITE); formattedLine.append(stringEnd).append(" "); continue; } formattedLine.append(word).append(" "); continue; } if(word.contains("\"")) { buildingString = true; StringBuilder stringStart = new StringBuilder(word); stringStart.insert(word.indexOf("\""), TextFormatting.RED); if (word.lastIndexOf("\"") != word.indexOf("\"")) { buildingString = false; // + 3 because color code is 2 characters and we insert colorcode after the string: 2+1=3 stringStart.insert(ArrayHelper.indexOfNth('\"', word.toCharArray(), 2) + 3, TextFormatting.WHITE); } formattedLine.append(stringStart).append(" "); continue; } if(word.replace(_cursorSymbol, "").contains(" { StringBuilder commentWord = new StringBuilder(word); if (words.length == ArrayHelper.indexOfNth(word, words, 1) + 1) { commentWord.insert(word.replace(_cursorSymbol,"").indexOf("//"), TextFormatting.GRAY); commentWord.append(TextFormatting.WHITE).append(" "); formattedLine.append(commentWord); continue; } StringBuilder lastWord = new StringBuilder(words[words.length - 1]); commentWord.insert(word.replace(_cursorSymbol,"").indexOf("//"), TextFormatting.GRAY); lastWord.insert(lastWord.length(), TextFormatting.WHITE + " "); formattedLine.append(commentWord).append(" "); for (int j = ArrayHelper.indexOfNth(word, words, 1) + 1; j < words.length - 1; j++) { formattedLine.append(words[j]).append(" "); } formattedLine.append(lastWord); return formattedLine.toString(); } if (partial.equals("")) { keywords = testWord(word.replace(_cursorSymbol, ""), keyWordMap.keySet(),partialKeywords); switch(keywords.getFirst()) { case 0: formattedLine.append(word).append(" "); break; case 1: TextFormatting col = keyWordMap.get(keywords.getSecond()); formattedLine.append(col).append(word).append(" ").append(TextFormatting.WHITE); break; case 2: partial = word; formattedLine.append(partial).append(" "); break; } } else { keywords = testWord((partial + " " + word).replace(_cursorSymbol, ""), keyWordMap.keySet(), partialKeywords); switch(keywords.getFirst()) { case 0: formattedLine.append(word).append(" "); break; case 1: TextFormatting col = keyWordMap.get(keywords.getSecond()); formattedLine.insert(formattedLine.length() - (partial.length() + 1), col); formattedLine.append(word).append(TextFormatting.WHITE).append(" "); partial = ""; break; case 2: partial = partial + " " + word; formattedLine.append(partial).append(" "); break; } } } return formattedLine.toString(); } private static Tuple<Integer, String[]> testWord(String word, Set<String[]> keySet, String[] partialKeywords) { for(String[] keywords : keySet) { for (String keyword : keywords) { if(word.equals(keyword)) { return new Tuple<>(1, keywords); } else { for (String partialKeyword : partialKeywords) { if (word.equals(partialKeyword)) { return new Tuple<>(2, null); } } } } } return new Tuple<>(0, null); } public static void setText(String text) { //Highlight keywords final String[] partialKeywords = new String[] {"end", "repeat", "less", "greater", "on"}; final String[] blockKeywords = new String[] {"program", "end program", "method", "end method", "if", "then", "else", "end if", "repeat while", "end repeat", "return", "returns", "foreach", "in", "end foreach"}; final String[] booleanKeywords = new String[] {"not", "equals", "less than", "greater than", "or", "and"}; final String[] typeKeywords = new String[] {"number", "Coordinates", "string", "bool", "Item", "Entity"}; final String[] tfKeywords = new String[] {"true", "false"}; final String[] eventKeywords = new String[] {"on event", "call"}; final String[] events = new String[] {"robotDeath", "robotAttacked", "messageReceived", "entityDeath"}; //Assign colors for above keywords HashMap<String[], TextFormatting> keyWordMap = new HashMap<>(); keyWordMap.put(blockKeywords, TextFormatting.LIGHT_PURPLE); keyWordMap.put(booleanKeywords, TextFormatting.GOLD); keyWordMap.put(typeKeywords, TextFormatting.AQUA); keyWordMap.put(tfKeywords, TextFormatting.GREEN); keyWordMap.put(eventKeywords, TextFormatting.BLUE); keyWordMap.put(events, TextFormatting.DARK_AQUA); //Remove \r from _text as they are unnecessary _text = text.replace("\r", ""); //Insert the cursor String textWithCursor = new StringBuffer(_text).insert(_position, _cursorSymbol).toString(); //Split the text into lines in an array _lines = textWithCursor.split("(\n)"); // setting line number for (int i = 0; i <= _lines.length - 1; i++) { if (_lines[i].contains(_cursorSymbol)) { _lineNumber = i + 1; break; } } // calc position in line // TODO: There's no reason why cursor symbol should a char, change indexOfNth to support strings _positionInLine = _lines[_lineNumber - 1].indexOf(_cursorSymbol) + 1; //set visible part of editor for scrolling if (_lineNumber < _visibleTopLine) { _visibleTopLine _visibleBottomLine } else if (_lineNumber > _visibleBottomLine) { _visibleTopLine++; _visibleBottomLine++; } StringBuilder newFormattedText = new StringBuilder(); //Format the text from _text by going through each line and then append it to newFormattedText for (String line : ArrayHelper.getSubArray(_visibleTopLine - 1, _visibleBottomLine - 1, _lines)) { newFormattedText.append(testWords(line.split("( )"), keyWordMap, partialKeywords)).append("\n"); } //Add the new formatted text to the text shown on screen _formattedText = TextFormatting.WHITE + newFormattedText.toString().replace(_cursorSymbol, _cursorSymbolVisible); } private static void insert(String content) { int oldPosition = _position; _position += content.length(); setText(new StringBuffer(_text).insert(oldPosition, content).toString()); } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); // Draw position string this.fontRendererObj.drawString(TextFormatting.WHITE + "Position: " + _positionInLine, this.width - 100, 10, 0); // Draw line number this.fontRendererObj.drawString(TextFormatting.WHITE + "Line Num: " + _lineNumber, this.width - 100, 25, 0); //this.fontRendererObj.drawString(TextFormatting.WHITE + "Doc Position: " + _position, this.width - 100, 40, 0); // Draw code this.fontRendererObj.drawSplitString( _formattedText, 10, 10, this.width - 10, 0); super.drawScreen(mouseX, mouseY, partialTicks); } @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { updateScreen(); Keyboard.enableRepeatEvents(true); } @Override protected void actionPerformed(GuiButton button) throws IOException { } public void onGuiClosed() { Keyboard.enableRepeatEvents(false); } private void setPositionSafe(int newPosition) { if (newPosition < 0) newPosition = 0; else if (newPosition > _text.length() - 1) newPosition = _text.length() - 1; _position = newPosition; } protected void keyTyped(char typedChar, int keyCode) throws IOException { if (keyCode == KEY_ESCAPE) // Close the GUI this.mc.displayGuiScreen(null); // Displaying null hides the GUI screen else if (isKeyDown(KEY_LCONTROL)) { if (keyCode == KEY_S) // Save file CompilerMod.NETWORK_INSTANCE.sendToServer(new MessageSaveFile(_fileName, _text)); } else if (keyCode == KEY_RETURN) // Newline { int indexOfFirstChar = StringUtils.indexOfAnyBut(_lines[_lineNumber - 1], ' '); StringBuffer newLine = new StringBuffer("\n"); for (int i = 0; i < indexOfFirstChar; i++) { newLine.append(" "); } insert(newLine.toString()); } else if (keyCode == KEY_TAB) // Tab (creates two spaces) insert(" "); else if (keyCode == KEY_LEFT && _position > 0) // Change position to left { _position setText(_text); } else if (keyCode == KEY_RIGHT && _position < _text.length()) { _position++; setText(_text); } else if (keyCode == KEY_DELETE && !_text.isEmpty() && _position < _text.length() - 1) setText(new StringBuffer(_text).deleteCharAt(_position).toString()); else if (keyCode == KEY_BACK && !_text.isEmpty() && _position > 0) { _position setText(new StringBuffer(_text).deleteCharAt(_position).toString()); } else if (keyCode == KEY_DOWN) { if (_lineNumber != _lines.length) { if (_lines[_lineNumber].length() <= _positionInLine - 1) { setPositionSafe(_position + (_lines[_lineNumber - 1].length() - _positionInLine) + _lines[_lineNumber].length() + 1); } else { setPositionSafe(_position + _lines[_lineNumber - 1].length()); } setText(_text); } } else if (keyCode == KEY_UP) { if (_lineNumber != 1) { if (_lines[_lineNumber - 2].length() <= _positionInLine - 1) { setPositionSafe(_position - _positionInLine); } else { setPositionSafe(_position - _lines[_lineNumber - 2].length() - 1); } setText(_text); } } else if (ChatAllowedCharacters.isAllowedCharacter(typedChar)) insert(String.valueOf(typedChar)); else System.out.println("Key code:" + keyCode); } public static void resetPosition() { _position = 0; _lineNumber = 1; _positionInLine = 1; _visibleTopLine = 1; _visibleBottomLine = 25; } }
package com.frostwire.jlibtorrent; import com.frostwire.jlibtorrent.swig.*; import java.util.ArrayList; import java.util.List; /** * The {@link AddTorrentParams} is a parameter pack for adding torrents to a * session. The key fields when adding a torrent are: * <ul> * <li>ti - when you have a .torrent file</li> * <li>url - when you have a magnet link or http URL to the .torrent file</li> * <li>info_hash - when all you have is an info-hash (this is similar to a magnet link)</li> * </ul> * One of those fields need to be set. Another mandatory field is * {@link #savePath()}. The {@link AddTorrentParams} object is passed into one of the * {@link SessionHandle#addTorrent(AddTorrentParams, ErrorCode)} overloads or * {@link SessionHandle#asyncAddTorrent(AddTorrentParams)}. * <p/> * If you only specify the info-hash, the torrent file will be downloaded * from peers, which requires them to support the metadata extension. It also * takes an optional {@link #name()} argument. This may be left empty in case no * name should be assigned to the torrent. In case it's not, the name is * used for the torrent as long as it doesn't have metadata. * * @author gubatron * @author aldenml */ public final class AddTorrentParams { private final add_torrent_params p; public AddTorrentParams(add_torrent_params p) { this.p = p; } public AddTorrentParams() { this(add_torrent_params.create_instance()); } public add_torrent_params swig() { return p; } /** * Filled in by the constructor. It is used for forward binary compatibility. * * @return */ public int version() { return p.getVersion(); } /** * If the torrent doesn't have a tracker, but relies on the DHT to find * peers, the ``trackers`` can specify tracker URLs for the torrent. * * @return */ public ArrayList<String> trackers() { string_vector v = p.getTrackers(); int size = (int) v.size(); ArrayList<String> l = new ArrayList<>(); for (int i = 0; i < size; i++) { l.add(v.get(i)); } return l; } /** * If the torrent doesn't have a tracker, but relies on the DHT to find * peers, the ``trackers`` can specify tracker URLs for the torrent. * * @param value */ public void trackers(List<String> value) { string_vector v = new string_vector(); for (String s : value) { v.push_back(s); } p.setTrackers(v); } /** * Url seeds to be added to the torrent (`BEP 17`_). * * @return */ public ArrayList<String> urlSeeds() { string_vector v = p.getUrl_seeds(); int size = (int) v.size(); ArrayList<String> l = new ArrayList<>(); for (int i = 0; i < size; i++) { l.add(v.get(i)); } return l; } /** * Url seeds to be added to the torrent (`BEP 17`_). * * @param value */ public void urlSeeds(List<String> value) { string_vector v = new string_vector(); for (String s : value) { v.push_back(s); } p.setUrl_seeds(v); } /** * A list of hostname and port pairs, representing DHT nodes to be added * to the session (if DHT is enabled). The hostname may be an IP address. * * @return */ public ArrayList<Pair<String, Integer>> dhtNodes() { string_int_pair_vector v = p.getDht_nodes(); int size = (int) v.size(); ArrayList<Pair<String, Integer>> l = new ArrayList<>(); for (int i = 0; i < size; i++) { string_int_pair n = v.get(i); l.add(new Pair<>(n.getFirst(), n.getSecond())); } return l; } /** * A list of hostname and port pairs, representing DHT nodes to be added * to the session (if DHT is enabled). The hostname may be an IP address. * * @param value */ public void dhtNodes(List<Pair<String, Integer>> value) { string_int_pair_vector v = new string_int_pair_vector(); for (Pair<String, Integer> p : value) { v.push_back(p.to_string_int_pair()); } p.setDht_nodes(v); } public String name() { return p.getName(); } public void name(String value) { p.setName(value); } /** * The path where the torrent is or will be stored. Note that this may * also be stored in resume data. If you want the save path saved in * the resume data to be used, you need to set the * flag_use_resume_save_path flag. * <p/> * .. note:: * On windows this path (and other paths) are interpreted as UNC * paths. This means they must use backslashes as directory separators * * @return */ public String savePath() { return p.getSave_path(); } /** * The path where the torrent is or will be stored. Note that this may * also be stored in resume data. If you want the save path saved in * the resume data to be used, you need to set the * flag_use_resume_save_path flag. * <p/> * .. note:: * On windows this path (and other paths) are interpreted as UNC * paths. This means they must use backslashes as directory separators * * @param value */ public void savePath(String value) { p.setSave_path(value); } /* public void setResume_data(char_vector value) { libtorrent_jni.add_torrent_params_resume_data_set(swigCPtr, this, char_vector.getCPtr(value), value); } public char_vector getResume_data() { long cPtr = libtorrent_jni.add_torrent_params_resume_data_get(swigCPtr, this); return (cPtr == 0) ? null : new char_vector(cPtr, false); } */ /** * @return * @see StorageMode */ public StorageMode storageMode() { return StorageMode.fromSwig(p.getStorage_mode().swigValue()); } /** * @param value * @see StorageMode */ public void storageMode(StorageMode value) { p.setStorage_mode(storage_mode_t.swigToEnum(value.swig())); } /* public void setFile_priorities(unsigned_char_vector value) { libtorrent_jni.add_torrent_params_file_priorities_set(swigCPtr, this, unsigned_char_vector.getCPtr(value), value); } public unsigned_char_vector getFile_priorities() { long cPtr = libtorrent_jni.add_torrent_params_file_priorities_get(swigCPtr, this); return (cPtr == 0) ? null : new unsigned_char_vector(cPtr, false); } */ /** * The default tracker id to be used when announcing to trackers. By * default this is empty, and no tracker ID is used, since this is an * optional argument. If a tracker returns a tracker ID, that ID is used * instead of this. * * @return */ public String trackerId() { return p.getTrackerid(); } /** * The default tracker id to be used when announcing to trackers. By * default this is empty, and no tracker ID is used, since this is an * optional argument. If a tracker returns a tracker ID, that ID is used * instead of this. * * @param value */ public void trackerId(String value) { p.setTrackerid(value); } /** * If you specify a ``url``, the torrent will be set in * ``downloading_metadata`` state until the .torrent file has been * downloaded. If there's any error while downloading, the torrent will * be stopped and the torrent error state (``torrent_status::error``) * will indicate what went wrong. The ``url`` may refer to a magnet link * or a regular http URL. * <p/> * If it refers to an HTTP URL, the info-hash for the added torrent will * not be the true info-hash of the .torrent. Instead a placeholder, * unique, info-hash is used which is later updated once the .torrent * file has been downloaded. * <p/> * Once the info-hash change happens, a {@link com.frostwire.jlibtorrent.alerts.TorrentUpdateAlert} is posted. * * @return */ public String url() { return p.getUrl(); } /** * If you specify a ``url``, the torrent will be set in * ``downloading_metadata`` state until the .torrent file has been * downloaded. If there's any error while downloading, the torrent will * be stopped and the torrent error state (``torrent_status::error``) * will indicate what went wrong. The ``url`` may refer to a magnet link * or a regular http URL. * <p/> * If it refers to an HTTP URL, the info-hash for the added torrent will * not be the true info-hash of the .torrent. Instead a placeholder, * unique, info-hash is used which is later updated once the .torrent * file has been downloaded. * <p/> * Once the info-hash change happens, a {@link com.frostwire.jlibtorrent.alerts.TorrentUpdateAlert} is posted. * * @param value */ public void url(String value) { p.setUrl(value); } /** * If ``uuid`` is specified, it is used to find duplicates. If another * torrent is already running with the same UUID as the one being added, * it will be considered a duplicate. This is mainly useful for RSS feed * items which has UUIDs specified. * * @return */ public String uuid() { return p.getUuid(); } /** * If ``uuid`` is specified, it is used to find duplicates. If another * torrent is already running with the same UUID as the one being added, * it will be considered a duplicate. This is mainly useful for RSS feed * items which has UUIDs specified. * * @param value */ public void uuid(String value) { p.setUuid(value); } /** * Should point to the URL of the RSS feed this torrent comes from, if it * comes from an RSS feed. * * @return */ public String sourceFeedUrl() { return p.getSource_feed_url(); } /** * Should point to the URL of the RSS feed this torrent comes from, if it * comes from an RSS feed. * * @param value */ public void sourceFeedUrl(String value) { p.setSource_feed_url(value); } /** * Set this to the info hash of the torrent to add in case the info-hash * is the only known property of the torrent. i.e. you don't have a * .torrent file nor a magnet link. * * @return */ public Sha1Hash infoHash() { return new Sha1Hash(p.getInfo_hash()); } /** * Set this to the info hash of the torrent to add in case the info-hash * is the only known property of the torrent. i.e. you don't have a * .torrent file nor a magnet link. * * @param value */ public void infoHash(Sha1Hash value) { p.setInfo_hash(value.swig()); } /* public void setMax_uploads(int value) { libtorrent_jni.add_torrent_params_max_uploads_set(swigCPtr, this, value); } public int getMax_uploads() { return libtorrent_jni.add_torrent_params_max_uploads_get(swigCPtr, this); } public void setMax_connections(int value) { libtorrent_jni.add_torrent_params_max_connections_set(swigCPtr, this, value); } public int getMax_connections() { return libtorrent_jni.add_torrent_params_max_connections_get(swigCPtr, this); } public void setUpload_limit(int value) { libtorrent_jni.add_torrent_params_upload_limit_set(swigCPtr, this, value); } public int getUpload_limit() { return libtorrent_jni.add_torrent_params_upload_limit_get(swigCPtr, this); } public void setDownload_limit(int value) { libtorrent_jni.add_torrent_params_download_limit_set(swigCPtr, this, value); } public int getDownload_limit() { return libtorrent_jni.add_torrent_params_download_limit_get(swigCPtr, this); } */ /** * Flags controlling aspects of this torrent and how it's added. See * {@link com.frostwire.jlibtorrent.swig.add_torrent_params.flags_t} for details. * * @return */ public long flags() { return p.get_flags(); } /** * Flags controlling aspects of this torrent and how it's added. See * {@link com.frostwire.jlibtorrent.swig.add_torrent_params.flags_t} for details. * * @param flags */ public void flags(long flags) { p.set_flags(flags); } /** * {@link TorrentInfo} object with the torrent to add. Unless the url or * {@link #infoHash()} is set, this is required to be initialized. * * @param ti */ public void torrentInfo(TorrentInfo ti) { p.set_ti(ti.swig()); } /** * This optional parameter can be given if up to date * fast-resume data is available. The fast-resume data can be acquired * from a running torrent by calling {@link TorrentHandle#saveResumeData()} * * @param data */ public void resumeData(byte[] data) { p.set_resume_data(Vectors.bytes2byte_vector(data)); } /** * Can be set to control the initial file priorities when adding a * torrent. The semantics are the same as for * {@link TorrentHandle#prioritizeFiles(Priority[])}. * * @param priorities */ public void filePriorities(Priority[] priorities) { p.set_file_priorities(Priority.array2byte_vector(priorities)); } public static AddTorrentParams createInstance() { return new AddTorrentParams(add_torrent_params.create_instance()); } public static AddTorrentParams createInstanceDisabledStorage() { return new AddTorrentParams(add_torrent_params.create_instance_disabled_storage()); } public static AddTorrentParams createInstanceZeroStorage() { return new AddTorrentParams(add_torrent_params.create_instance_zero_storage()); } }
package com.github.cstroe.spendhawk.entity; import com.github.cstroe.spendhawk.util.HibernateUtil; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import javax.annotation.Nonnull; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set; /** * <p> * An account represents a pool of money, against which Transactions are * recorded. Implemented as a JavaBean. * </p> * * An account has: * <ul> * <li>a name</li> * <li>a list of transactions recorded against the account</li> * <li>a balance, which represents the value of the money in the account as * of some date. * <ul> * <li>The balance is the sum of the amounts of the transactions * recorded against the account up and including the given date plus * the balance of its sub-accounts. If the * account has no transactions or sub-accounts, the balance will be $0. * </li> * <li>The balance of the sub-accounts are added to the account's * balance.</li> * </ul> * </li> * <li>a parent account</li> * <li>a list of sub accounts (accounts whose parent is this account)</li> * </ul> */ public class Account implements Comparable<Account> { private static final Double ZERO = 0d; private Long id; private User user; private String name; private Collection<Transaction> transactions; private Account parent; private Set<Account> subAccounts; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<Transaction> getTransactions() { return transactions; } public void setTransactions(Collection<Transaction> transactions) { this.transactions = transactions; } public Account getParent() { return parent; } public void setParent(Account parent) { this.parent = parent; } public Set<Account> getSubAccounts() { return subAccounts; } public void setSubAccounts(Set<Account> subAccounts) { this.subAccounts = subAccounts; } @Override public String toString() { return "Account " + name; } /** * @return The balance of the account as of the current date and time. */ public Double getBalance() { final Date now = new Date(); if(transactions == null || transactions.isEmpty()) { return ZERO; } return transactions.stream() .filter(t -> !t.getEffectiveDate().after(now)) .mapToDouble(Transaction::getAmount) .sum(); } @SuppressWarnings("unchecked") public static List<Account> findAll(User currentUser) { return (List<Account>) HibernateUtil.getSessionFactory().getCurrentSession() .createCriteria(Account.class) .add(Restrictions.eq("user", currentUser)) .list(); } public static Optional<Account> findById(Long id) { return Optional.ofNullable((Account) HibernateUtil.getSessionFactory().getCurrentSession() .createCriteria(Account.class) .add(Restrictions.eq("id", id)) .uniqueResult()); } public static Optional<Account> findById(User currentUser, Long id) { return Optional.ofNullable((Account) HibernateUtil.getSessionFactory().getCurrentSession() .createCriteria(Account.class) .add(Restrictions.eq("id", id)) .add(Restrictions.eq("user", currentUser)) .uniqueResult()); } @Override public int compareTo(@Nonnull Account o) { return this.getName().compareTo(o.getName()); } /** * Find transactions whose description match the search string. * @param query SQL LIKE parameter */ @SuppressWarnings("unchecked") public List<Transaction> findTransactions(String query) { query = "%" + query + "%"; return (List<Transaction>) HibernateUtil.getSessionFactory().getCurrentSession() .createCriteria(Transaction.class) .add(Restrictions.eq("account", this)) .add(Restrictions.ilike("description", query)) .addOrder(Order.desc("effectiveDate")) .list(); } public void delete() { HibernateUtil.getSessionFactory().getCurrentSession().delete(this); } }
package com.github.maven_nar; import java.util.ArrayList; import java.util.List; public class ProcessLibraryCommand { /** * The executable to run * * @parameter default-value="" */ private String executable; /** * The library type that this command is valid for * * @parameter default-value="" */ private String libraryType; /** * Any additional arguments to pass into the executable * * @parameter default-value="" */ private List<String> arguments; public List<String> getCommandList() { List<String> command = new ArrayList<String>(); command.add(executable); if (arguments != null) { command.addAll(arguments); } return command; } public String getExecutable() { return executable; } public void setExecutable(String executable) { this.executable = executable; } public List<String> getArguments() { return arguments; } public void setArguments(List<String> arguments) { this.arguments = arguments; } public String getType() { return libraryType; } }
package com.github.pagehelper.page; import com.github.pagehelper.Dialect; import com.github.pagehelper.PageException; import com.github.pagehelper.dialect.AbstractHelperDialect; import com.github.pagehelper.dialect.helper.*; import com.github.pagehelper.util.StringUtil; import org.apache.ibatis.mapping.MappedStatement; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; /** * * * @author liuzh */ public class PageAutoDialect { private static Map<String, Class<? extends Dialect>> dialectAliasMap = new HashMap<String, Class<? extends Dialect>>(); public static void registerDialectAlias(String alias, Class<? extends Dialect> dialectClass) { dialectAliasMap.put(alias, dialectClass); } static { registerDialectAlias("hsqldb", HsqldbDialect.class); registerDialectAlias("h2", HsqldbDialect.class); registerDialectAlias("postgresql", HsqldbDialect.class); registerDialectAlias("phoenix", HsqldbDialect.class); registerDialectAlias("mysql", MySqlDialect.class); registerDialectAlias("mariadb", MySqlDialect.class); registerDialectAlias("sqlite", MySqlDialect.class); registerDialectAlias("herddb", HerdDBDialect.class); registerDialectAlias("oracle", OracleDialect.class); registerDialectAlias("oracle9i", Oracle9iDialect.class); registerDialectAlias("db2", Db2Dialect.class); registerDialectAlias("informix", InformixDialect.class); // informix-sqli #129 registerDialectAlias("informix-sqli", InformixDialect.class); registerDialectAlias("sqlserver", SqlServerDialect.class); registerDialectAlias("sqlserver2012", SqlServer2012Dialect.class); registerDialectAlias("derby", SqlServer2012Dialect.class); registerDialectAlias("dm", OracleDialect.class); registerDialectAlias("edb", OracleDialect.class); registerDialectAlias("oscar", MySqlDialect.class); registerDialectAlias("clickhouse", MySqlDialect.class); registerDialectAlias("highgo", HsqldbDialect.class); registerDialectAlias("xugu", HsqldbDialect.class); } //dialect,setPropertiessetSqlUtilConfig private boolean autoDialect = true; //jdbcurl private boolean closeConn = true; private Properties properties; private Map<String, AbstractHelperDialect> urlDialectMap = new ConcurrentHashMap<String, AbstractHelperDialect>(); private ReentrantLock lock = new ReentrantLock(); private AbstractHelperDialect delegate; private ThreadLocal<AbstractHelperDialect> dialectThreadLocal = new ThreadLocal<AbstractHelperDialect>(); public void initDelegateDialect(MappedStatement ms) { if (delegate == null) { if (autoDialect) { this.delegate = getDialect(ms); } else { dialectThreadLocal.set(getDialect(ms)); } } } public AbstractHelperDialect getDelegate() { if (delegate != null) { return delegate; } return dialectThreadLocal.get(); } public void clearDelegate() { dialectThreadLocal.remove(); } private String fromJdbcUrl(String jdbcUrl) { final String url = jdbcUrl.toLowerCase(); for (String dialect : dialectAliasMap.keySet()) { if (url.contains(":" + dialect.toLowerCase() + ":")) { return dialect; } } return null; } /** * * * @param className * @return * @throws Exception */ private Class resloveDialectClass(String className) throws Exception { if (dialectAliasMap.containsKey(className.toLowerCase())) { return dialectAliasMap.get(className.toLowerCase()); } else { return Class.forName(className); } } /** * helper * * @param dialectClass * @param properties */ private AbstractHelperDialect initDialect(String dialectClass, Properties properties) { AbstractHelperDialect dialect; if (StringUtil.isEmpty(dialectClass)) { throw new PageException(" PageHelper helper "); } try { Class sqlDialectClass = resloveDialectClass(dialectClass); if (AbstractHelperDialect.class.isAssignableFrom(sqlDialectClass)) { dialect = (AbstractHelperDialect) sqlDialectClass.newInstance(); } else { throw new PageException(" PageHelper " + AbstractHelperDialect.class.getCanonicalName() + " !"); } } catch (Exception e) { throw new PageException(" helper [" + dialectClass + "]:" + e.getMessage(), e); } dialect.setProperties(properties); return dialect; } /** * url * * @param dataSource * @return */ private String getUrl(DataSource dataSource) { Connection conn = null; try { conn = dataSource.getConnection(); return conn.getMetaData().getURL(); } catch (SQLException e) { throw new PageException(e); } finally { if (conn != null) { try { if (closeConn) { conn.close(); } } catch (SQLException e) { //ignore } } } } /** * jdbcUrl * * @param ms * @return */ private AbstractHelperDialect getDialect(MappedStatement ms) { //dataSource DataSource dataSource = ms.getConfiguration().getEnvironment().getDataSource(); String url = getUrl(dataSource); if (urlDialectMap.containsKey(url)) { return urlDialectMap.get(url); } try { lock.lock(); if (urlDialectMap.containsKey(url)) { return urlDialectMap.get(url); } if (StringUtil.isEmpty(url)) { throw new PageException("jdbcUrldialect!"); } String dialectStr = fromJdbcUrl(url); if (dialectStr == null) { throw new PageException(" helperDialect !"); } AbstractHelperDialect dialect = initDialect(dialectStr, properties); urlDialectMap.put(url, dialect); return dialect; } finally { lock.unlock(); } } public void setProperties(Properties properties) { // jdbcurl String closeConn = properties.getProperty("closeConn"); if (StringUtil.isNotEmpty(closeConn)) { this.closeConn = Boolean.parseBoolean(closeConn); } // sqlserver2012 String useSqlserver2012 = properties.getProperty("useSqlserver2012"); if (StringUtil.isNotEmpty(useSqlserver2012) && Boolean.parseBoolean(useSqlserver2012)) { registerDialectAlias("sqlserver", SqlServer2012Dialect.class); registerDialectAlias("sqlserver2008", SqlServerDialect.class); } String dialectAlias = properties.getProperty("dialectAlias"); if (StringUtil.isNotEmpty(dialectAlias)) { String[] alias = dialectAlias.split(";"); for (int i = 0; i < alias.length; i++) { String[] kv = alias[i].split("="); if (kv.length != 2) { throw new IllegalArgumentException("dialectAlias " + " alias1=xx.dialectClass;alias2=dialectClass2 !"); } for (int j = 0; j < kv.length; j++) { try { Class<? extends Dialect> diallectClass = (Class<? extends Dialect>) Class.forName(kv[1]); registerDialectAlias(kv[0], diallectClass); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(" dialectAlias Dialect !", e); } } } } // Helper String dialect = properties.getProperty("helperDialect"); String runtimeDialect = properties.getProperty("autoRuntimeDialect"); if (StringUtil.isNotEmpty(runtimeDialect) && "TRUE".equalsIgnoreCase(runtimeDialect)) { this.autoDialect = false; this.properties = properties; } else if (StringUtil.isEmpty(dialect)) { autoDialect = true; this.properties = properties; } else { autoDialect = false; this.delegate = initDialect(dialect, properties); } } }
package com.github.phantomthief.util; import static com.google.common.base.Preconditions.checkNotNull; import java.io.Serializable; import java.util.function.Supplier; /** * @author w.vela */ public class MoreSuppliers { public static <T> CloseableSupplier<T> lazy(Supplier<T> delegate) { if (delegate instanceof CloseableSupplier) { return (CloseableSupplier<T>) delegate; } else { return new CloseableSupplier<T>(checkNotNull(delegate)); } } public static class CloseableSupplier<T> implements Supplier<T>, Serializable { private final Supplier<T> delegate; private volatile transient boolean initialized; private transient T value; private static final long serialVersionUID = 0L; private CloseableSupplier(Supplier<T> delegate) { this.delegate = delegate; } public T get() { if (!(this.initialized)) { synchronized (this) { if (!(this.initialized)) { T t = this.delegate.get(); this.value = t; this.initialized = true; return t; } } } return this.value; } public boolean isInitialized() { return initialized; } public <X extends Throwable> void ifPresent(ThrowableConsumer<T, X> consumer) throws X { synchronized (this) { if (initialized && this.value != null) { consumer.accept(this.value); } } } public <X extends Throwable> void tryClose(ThrowableConsumer<T, X> close) throws X { synchronized (this) { if (initialized && this.value != null) { close.accept(value); this.value = null; initialized = false; } } } public String toString() { return "MoreSuppliers.lazy(" + this.delegate + ")"; } } }
package com.github.tonivade.resp; import static com.github.tonivade.purefun.Precondition.checkNonEmpty; import static com.github.tonivade.purefun.Precondition.checkNonNull; import static com.github.tonivade.purefun.Precondition.checkRange; import static com.github.tonivade.resp.SessionListener.nullListener; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.tonivade.purefun.Function1; import com.github.tonivade.purefun.type.Option; import com.github.tonivade.resp.command.CommandSuite; import com.github.tonivade.resp.command.Request; import com.github.tonivade.resp.command.RespCommand; import com.github.tonivade.resp.command.ServerContext; import com.github.tonivade.resp.command.Session; import com.github.tonivade.resp.protocol.RedisToken; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.Scheduler; import io.reactivex.rxjava3.schedulers.Schedulers; public class RespServerContext implements ServerContext { private static final Logger LOGGER = LoggerFactory.getLogger(RespServerContext.class); private final StateHolder state = new StateHolder(); private final ConcurrentHashMap<String, Session> clients = new ConcurrentHashMap<>(); private final Scheduler scheduler = Schedulers.from(Executors.newSingleThreadExecutor()); private final String host; private final int port; private final CommandSuite commands; private SessionListener sessionListener; public RespServerContext(String host, int port, CommandSuite commands) { this(host, port, commands, nullListener()); } public RespServerContext(String host, int port, CommandSuite commands, SessionListener sessionListener) { this.host = checkNonEmpty(host); this.port = checkRange(port, 1024, 65535); this.commands = checkNonNull(commands); this.sessionListener = sessionListener; } public void start() { } public void stop() { clear(); scheduler.shutdown(); } @Override public int getClients() { return clients.size(); } @Override public RespCommand getCommand(String name) { return commands.getCommand(name); } @Override public <T> Option<T> getValue(String key) { return state.getValue(key); } @Override public <T> Option<T> removeValue(String key) { return state.removeValue(key); } @Override public void putValue(String key, Object value) { state.putValue(key, value); } @Override public String getHost() { return host; } @Override public int getPort() { return port; } Session getSession(String sourceKey, Function1<String, Session> factory) { return clients.computeIfAbsent(sourceKey, key -> { Session session = factory.apply(key); sessionListener.sessionCreated(session); return session; }); } void processCommand(Request request) { LOGGER.debug("received command: {}", request); RespCommand command = getCommand(request.getCommand()); try { executeOn(execute(command, request)) .subscribe(response -> processResponse(request, response), ex -> LOGGER.error("error executing command: " + request, ex)); } catch (RuntimeException ex) { LOGGER.error("error executing command: " + request, ex); } } protected CommandSuite getCommands() { return commands; } protected void removeSession(String sourceKey) { Session session = clients.remove(sourceKey); if (session != null) { sessionListener.sessionDeleted(session); } } protected Session getSession(String key) { return clients.get(key); } protected RedisToken executeCommand(RespCommand command, Request request) { return command.execute(request); } protected <T> Observable<T> executeOn(Observable<T> observable) { return observable.observeOn(scheduler); } private void processResponse(Request request, RedisToken token) { request.getSession().publish(token); if (request.isExit()) { request.getSession().close(); } } private Observable<RedisToken> execute(RespCommand command, Request request) { return Observable.create(observer -> { observer.onNext(executeCommand(command, request)); observer.onComplete(); }); } private void clear() { clients.clear(); state.clear(); } }
package com.imnotjames.tribbleengine.engine; import com.imnotjames.tribbleengine.Family; import com.imnotjames.tribbleengine.entity.Entity; import java.util.ArrayList; import java.util.List; public class Engine { private List<Entity> entities; private List<EngineSystem> engineSystems; private List<EngineEventListener> listeners; public Engine() { this.entities = new ArrayList<Entity>(); this.engineSystems = new ArrayList<EngineSystem>(); this.listeners = new ArrayList<EngineEventListener>(); } public void update(long delta) { for (EngineSystem s : engineSystems) { s.update(delta); } } public void addEntity(Entity entity) { this.entities.add(entity); EngineEntityEvent event = new EngineEntityEvent(this, entity); for (EngineEventListener listener : this.listeners) { listener.entityAdded(event); } } public void removeEntity(Entity entity) { // If we don't remove the entity don't fire events if (! this.entities.remove(entity)) { return; } EngineEntityEvent event = new EngineEntityEvent(this, entity); for (EngineEventListener listener : this.listeners) { listener.entityRemoved(event); } } public void removeAllEntities() { while (this.entities.size() > 0) { this.removeEntity(this.entities.get(0)); } } public List<Entity> getEntities() { return this.entities; } public List<Entity> getEntities(Family family) { if (family == null) { return this.entities; } List<Entity> filteredEntities = new ArrayList<Entity>(); for (Entity entity : this.entities) { if (family.matches(entity)) { filteredEntities.add(entity); } } return filteredEntities; } public void addSystem(EngineSystem engineSystem) { this.engineSystems.add(engineSystem); engineSystem.setUp(this); // this.engineSystems.sort(); } public void removeSystem(EngineSystem engineSystem) { if (this.engineSystems.remove(engineSystem)) { engineSystem.tearDown(this); } } public void addEventListener(EngineEventListener listener) { this.listeners.add(listener); } public void removeEventListener(EngineEventListener listener) { this.listeners.remove(listener); } }
package com.jtj.web.service.impl; import com.jtj.web.common.ResultDto; import com.jtj.web.dao.UserDao; import com.jtj.web.entity.User; import com.jtj.web.service.SystemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @Service public class SystemServiceImpl implements SystemService { @Autowired private UserDao userDao; @Override public String init(HttpServletRequest request, HttpServletResponse response) { List<User> users = userDao.getUserById(1L); if (users.size() == 0){ return "init"; } return "redirect:/login"; } }
package com.kodcu.controller; import com.esotericsoftware.yamlbeans.YamlReader; import com.kodcu.bean.Config; import com.kodcu.bean.RecentFiles; import com.kodcu.bean.ShortCuts; import com.kodcu.component.MenuBuilt; import com.kodcu.component.MenuItemBuilt; import com.kodcu.other.Current; import com.kodcu.other.IOHelper; import com.kodcu.other.Item; import com.kodcu.service.*; import com.kodcu.service.config.YamlService; import com.kodcu.service.convert.*; import com.kodcu.service.extension.MathJaxService; import com.kodcu.service.extension.PlantUmlService; import com.kodcu.service.extension.TreeService; import com.kodcu.service.ui.*; import com.sun.javafx.application.HostServicesDelegate; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Worker; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.TextFieldTreeCell; import javafx.scene.input.*; import javafx.scene.layout.AnchorPane; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.util.Duration; import netscape.javascript.JSObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.CodeSource; import java.util.*; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; import static java.nio.file.StandardOpenOption.WRITE; @Controller public class ApplicationController extends TextWebSocketHandler implements Initializable { private Logger logger = LoggerFactory.getLogger(ApplicationController.class); private Path userHome = Paths.get(System.getProperty("user.home")); public TabPane tabPane; public WebView previewView; public SplitPane splitPane; public SplitPane splitPaneVertical; public TreeView<Item> treeView; public Label splitHideButton; public Label workingDirButton; public Label goUpLabel; public Label goHomeLabel; public Label refreshLabel; public AnchorPane rootAnchor; public MenuBar recentFilesBar; public ProgressBar indikator; public ListView<String> recentListView; public MenuItem openFileTreeItem; public MenuItem openFolderTreeItem; public MenuItem openFileListItem; public MenuItem openFolderListItem; public MenuItem copyPathTreeItem; public MenuItem copyPathListItem; public MenuItem copyTreeItem; public MenuItem copyListItem; public MenuItem selectAsWorkdir; public MenuButton leftButton; private WebView mathjaxView; public Label htmlPro; public Label pdfPro; public Label ebookPro; public Label docbookPro; public Label browserPro; @Autowired private TablePopupService tablePopupController; @Autowired private PathOrderService pathOrder; @Autowired private TreeService treeService; @Autowired private TooltipTimeFixService tooltipTimeFixService; @Autowired private TabService tabService; @Autowired private PathResolverService pathResolver; @Autowired private PlantUmlService plantUmlService; @Autowired private EditorService editorService; @Autowired private MathJaxService mathJaxService; @Autowired private YamlService yamlService; @Autowired private WebviewService webviewService; @Autowired private RenderService renderService; @Autowired private DocBookService docBookService; @Autowired private Html5BookService htmlBookService; @Autowired private Html5ArticleService htmlArticleService; @Autowired private FopPdfService fopServiceRunner; @Autowired private Epub3Service epub3Service; @Autowired private Current current; @Autowired private FileBrowseService fileBrowser; @Autowired private IndikatorService indikatorService; @Autowired private KindleMobiService kindleMobiService; @Autowired private SampleBookService sampleBookService; @Autowired private EmbeddedWebApplicationContext server; @Autowired private ParserService parserService; @Autowired private AwesomeService awesomeService; @Autowired private DirectoryService directoryService; @Autowired private ThreadService threadService; @Autowired private ScrollService scrollService; @Autowired private DocumentService documentService; @Autowired private EpubController epubController; private Stage stage; private WebEngine previewEngine; private StringProperty lastRendered = new SimpleStringProperty(); private List<WebSocketSession> sessionList = new ArrayList<>(); private Scene scene; private AnchorPane tableAnchor; private Stage tableStage; private Clipboard clipboard = Clipboard.getSystemClipboard(); private ObservableList<String> recentFiles = FXCollections.synchronizedObservableList(FXCollections.observableArrayList()); private AnchorPane configAnchor; private Stage configStage; private int port = 8080; private HostServicesDelegate hostServices; private Path configPath; private Config config; private List<String> bookNames = Arrays.asList("book.asc", "book.txt", "book.asciidoc", "book.adoc", "book.ad"); private Map<String, String> shortCuts; private ChangeListener<String> lastRenderedChangeListener = (observableValue, old, nev) -> { if (Objects.isNull(nev)) return; threadService.runActionLater(() -> { previewEngine.executeScript(String.format("refreshUI('%s')", IOHelper.normalize(nev))); }); sessionList.stream().filter(e -> e.isOpen()).forEach(e -> { try { e.sendMessage(new TextMessage(nev)); } catch (Exception ex) { logger.info(ex.getMessage(), ex); } }); }; @FXML public void createTable(Event event) { threadService.runTaskLater(() -> { threadService.runActionLater(() -> { tableStage.show(); }); }); } @FXML private void openConfig(ActionEvent event) { configStage.show(); } @FXML private void fullScreen(ActionEvent event) { getStage().setFullScreen(!getStage().isFullScreen()); } @FXML private void directoryView(ActionEvent event) { splitPane.setDividerPositions(0.1610294117647059, 0.5823529411764706); } private void generatePdf() { this.generatePdf(false); } private void generatePdf(boolean askPath) { if (!current.currentPath().isPresent()) saveDoc(); threadService.runTaskLater(() -> { if (current.currentIsBook()) { fopServiceRunner.generateBook(askPath); } else { fopServiceRunner.generateArticle(askPath); } }); } @FXML private void generateSampleBook(ActionEvent event) { DirectoryChooser directoryChooser = directoryService.newDirectoryChooser("Select a New Directory for sample book"); File file = directoryChooser.showDialog(null); threadService.runTaskLater(() -> { sampleBookService.produceSampleBook(configPath, file.toPath()); directoryService.setWorkingDirectory(Optional.of(file.toPath())); fileBrowser.browse(treeView, file.toPath()); Platform.runLater(() -> { directoryView(null); tabService.addTab(file.toPath().resolve("book.asc")); }); }); } public void convertDocbook() { convertDocbook(false); } public void convertDocbook(boolean askPath) { threadService.runTaskLater(() -> { if (!current.currentPath().isPresent()) saveDoc(); threadService.runActionLater(() -> { Path currentTabPath = current.currentPath().get(); Path currentTabPathDir = currentTabPath.getParent(); String tabText = current.getCurrentTabText().replace("*", "").trim(); Path docbookPath; if (askPath) { FileChooser fileChooser = directoryService.newFileChooser("Save Docbook file"); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Docbook", "*.xml")); docbookPath = fileChooser.showSaveDialog(null).toPath(); } else docbookPath = currentTabPathDir.resolve(tabText + ".xml"); String docbook = ""; if (current.currentIsBook()) { docbook = docBookService.generateDocbook(); } else { docbook = docBookService.generateDocbookArticle(); } final String finalDocbook = docbook; threadService.runTaskLater(()->{ IOHelper.writeToFile(docbookPath, finalDocbook, CREATE, TRUNCATE_EXISTING, WRITE); }); getRecentFiles().remove(docbookPath.toString()); getRecentFiles().add(0, docbookPath.toString()); }); }); } private void convertEpub() { convertEpub(false); } private void convertEpub(boolean askPath) { epub3Service.produceEpub3(askPath); } public String appendFormula(String fileName, String formula) { return mathJaxService.appendFormula(fileName, formula); } public void svgToPng(String fileName, String svg, String formula, float width, float height) { threadService.runTaskLater(() -> { mathJaxService.svgToPng(fileName, svg, formula, width, height); }); } private void convertMobi() { convertMobi(false); } private void convertMobi(boolean askPath) { if (Objects.nonNull(config.getKindlegenDir())) { if (!Files.exists(Paths.get(config.getKindlegenDir()))) { config.setKindlegenDir(null); } } if (Objects.isNull(config.getKindlegenDir())) { FileChooser fileChooser = directoryService.newFileChooser("Select 'kindlegen' executable"); File kindlegenFile = fileChooser.showOpenDialog(null); if (Objects.isNull(kindlegenFile)) return; config.setKindlegenDir(kindlegenFile.toPath().getParent().toString()); } threadService.runTaskLater(() -> { kindleMobiService.produceMobi(askPath); }); } private void generateHtml() { this.generateHtml(false); } private void generateHtml(boolean askPath) { if (!current.currentPath().isPresent()) this.saveDoc(); threadService.runTaskLater(() -> { if (current.currentIsBook()) htmlBookService.convertHtmlBook(askPath); else htmlArticleService.convertHtmlArticle(askPath); }); } public void createFileTree(String tree, String type, String fileName, String width, String height) { threadService.runTaskLater(() -> { treeService.createFileTree(tree, type, fileName, width, height); }); } @FXML public void goUp() { directoryService.goUp(); } @FXML public void refreshWorkingDir() { directoryService.refreshWorkingDir(); } @FXML public void goHome() { directoryService.changeWorkigDir(userHome); } @Override public void initialize(URL url, ResourceBundle rb) { tooltipTimeFixService.fix(); // Convert menu label icons AwesomeDude.setIcon(htmlPro, AwesomeIcon.HTML5); AwesomeDude.setIcon(pdfPro, AwesomeIcon.FILE_PDF_ALT); AwesomeDude.setIcon(ebookPro, AwesomeIcon.BOOK); AwesomeDude.setIcon(docbookPro, AwesomeIcon.CODE); AwesomeDude.setIcon(browserPro, AwesomeIcon.FLASH); // Left menu label icons AwesomeDude.setIcon(workingDirButton, AwesomeIcon.FOLDER_ALT, "14.0"); AwesomeDude.setIcon(splitHideButton, AwesomeIcon.CHEVRON_LEFT, "14.0"); AwesomeDude.setIcon(refreshLabel, AwesomeIcon.REFRESH, "14.0"); AwesomeDude.setIcon(goUpLabel, AwesomeIcon.LEVEL_UP, "14.0"); AwesomeDude.setIcon(goHomeLabel, AwesomeIcon.HOME, "14.0"); leftButton.setGraphic(AwesomeDude.createIconLabel(AwesomeIcon.COG, "14.0")); ContextMenu htmlProMenu = new ContextMenu(); htmlPro.setContextMenu(htmlProMenu); htmlPro.setOnMouseClicked(event -> { htmlProMenu.show(htmlPro, event.getScreenX(), 50); }); htmlProMenu.getItems().add(MenuItemBuilt.item("Save").onclick(event -> { this.generateHtml(); })); htmlProMenu.getItems().add(MenuItemBuilt.item("Save as").onclick(event -> { this.generateHtml(true); })); htmlProMenu.getItems().add(MenuItemBuilt.item("Copy source").onclick(event -> { this.cutCopy(lastRendered.getValue()); })); ContextMenu pdfProMenu = new ContextMenu(); pdfProMenu.getItems().add(MenuItemBuilt.item("Save").onclick(event -> { this.generatePdf(); })); pdfProMenu.getItems().add(MenuItemBuilt.item("Save as").onclick(event -> { this.generatePdf(true); })); pdfPro.setContextMenu(pdfProMenu); pdfPro.setOnMouseClicked(event -> { pdfProMenu.show(pdfPro, event.getScreenX(), 50); }); ContextMenu docbookProMenu = new ContextMenu(); docbookProMenu.getItems().add(MenuItemBuilt.item("Save").onclick(event -> { this.convertDocbook(); })); docbookProMenu.getItems().add(MenuItemBuilt.item("Save as").onclick(event -> { this.convertDocbook(true); })); docbookPro.setContextMenu(docbookProMenu); docbookPro.setOnMouseClicked(event -> { docbookProMenu.show(docbookPro, event.getScreenX(), 50); }); ContextMenu ebookProMenu = new ContextMenu(); ebookProMenu.getItems().add(MenuBuilt.name("Mobi") .add(MenuItemBuilt.item("Save").onclick(event -> { this.convertMobi(); })) .add(MenuItemBuilt.item("Save as").onclick(event -> { this.convertMobi(true); })).build()); ebookProMenu.getItems().add(MenuBuilt.name("Epub") .add(MenuItemBuilt.item("Save").onclick(event -> { this.convertEpub(); })) .add(MenuItemBuilt.item("Save as").onclick(event -> { this.convertEpub(true); })).build()); ebookPro.setOnMouseClicked(event -> { ebookProMenu.show(ebookPro, event.getScreenX(), 50); }); ebookPro.setContextMenu(ebookProMenu); // sourcePro.setOnAction(event -> { //// this.cutCopy(lastRendered.getValue()); browserPro.setOnMouseClicked(event -> { if (event.getButton() == MouseButton.PRIMARY) this.externalBrowse(); }); port = server.getEmbeddedServletContainer().getPort(); loadConfigurations(); loadRecentFileList(); loadShortCuts(); recentListView.setItems(recentFiles); recentFiles.addListener((ListChangeListener<String>) c -> { recentListView.visibleProperty().setValue(c.getList().size() > 0); recentListView.getSelectionModel().selectFirst(); }); recentListView.setOnMouseClicked(event -> { if (event.getClickCount() > 1) { openRecentListFile(event); } }); treeView.setCellFactory(param -> { TreeCell<Item> cell = new TextFieldTreeCell<Item>(); cell.setOnDragDetected(event -> { Dragboard db = cell.startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putFiles(Arrays.asList(cell.getTreeItem().getValue().getPath().toFile())); db.setContent(content); }); return cell; }); lastRendered.addListener(lastRenderedChangeListener); // MathJax mathjaxView = new WebView(); mathjaxView.setVisible(false); rootAnchor.getChildren().add(mathjaxView); WebEngine mathjaxEngine = mathjaxView.getEngine(); mathjaxEngine.getLoadWorker().stateProperty().addListener((observableValue1, state, state2) -> { JSObject window = (JSObject) mathjaxEngine.executeScript("window"); if (window.getMember("app").equals("undefined")) window.setMember("app", this); }); mathjaxEngine.load(String.format("http://localhost:%d/mathjax.html", port)); previewEngine = previewView.getEngine(); previewEngine.load(String.format("http://localhost:%d/preview.html", port)); previewEngine.getLoadWorker().stateProperty().addListener((observableValue1, state, state2) -> { if (state2 == Worker.State.SUCCEEDED) { JSObject window = (JSObject) previewEngine.executeScript("window"); if (window.getMember("app").equals("undefined")) { window.setMember("app", this); } } }); previewEngine.getLoadWorker().exceptionProperty().addListener((ov, t, t1) -> { logger.info(t1.getMessage(), t1); }); /// Treeview if (Objects.nonNull(config.getWorkingDirectory())) { Optional<Path> optional = Optional.ofNullable(Paths.get(config.getWorkingDirectory())); directoryService.setWorkingDirectory(optional); } Path workDir = directoryService.getWorkingDirectory().orElse(userHome); fileBrowser.browse(treeView, workDir); tabPane.getTabs().addListener((ListChangeListener<Tab>) c -> { if (tabPane.getTabs().isEmpty()) threadService.runActionLater(this::newDoc); }); openFileTreeItem.setOnAction(event -> { Path path = tabService.getSelectedTabPath(); directoryService.getOpenFileConsumer().accept(path); }); openFolderTreeItem.setOnAction(event -> { Path path = tabService.getSelectedTabPath(); path = Files.isDirectory(path) ? path : path.getParent(); if (Objects.nonNull(path)) getHostServices().showDocument(path.toUri().toASCIIString()); }); selectAsWorkdir.setOnAction(event -> { Path path = tabService.getSelectedTabPath(); path = Files.isDirectory(path) ? path : path.getParent(); if (Objects.nonNull(path)) directoryService.changeWorkigDir(path); }); openFolderListItem.setOnAction(event -> { Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem()); path = Files.isDirectory(path) ? path : path.getParent(); if (Objects.nonNull(path)) getHostServices().showDocument(path.toUri().toASCIIString()); }); openFileListItem.setOnAction(this::openRecentListFile); copyPathTreeItem.setOnAction(event -> { Path path = tabService.getSelectedTabPath(); this.cutCopy(path.toString()); }); copyPathListItem.setOnAction(event -> { this.cutCopy(recentListView.getSelectionModel().getSelectedItem()); }); copyTreeItem.setOnAction(event -> { Path path = tabService.getSelectedTabPath(); this.copyFile(path); }); copyListItem.setOnAction(event -> { Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem()); this.copyFile(path); }); treeView.setOnMouseClicked(event -> { TreeItem<Item> selectedItem = treeView.getSelectionModel().getSelectedItem(); if (Objects.isNull(selectedItem)) return; Path selectedPath = selectedItem.getValue().getPath(); if (event.getButton() == MouseButton.PRIMARY) if (Files.isDirectory(selectedPath)) { directoryService.changeWorkigDir(selectedPath); } else if (event.getClickCount() == 2) { directoryService.getOpenFileConsumer().accept(selectedPath); } }); threadService.runActionLater(e -> { if (tabPane.getTabs().isEmpty()) { newDoc(e); } }); } private void loadShortCuts() { try { YamlReader yamlReader = new YamlReader(new FileReader(configPath.resolve("shortcuts.yml").toFile())); yamlReader.getConfig().setClassTag("ShortCuts", ShortCuts.class); shortCuts = yamlReader.read(ShortCuts.class).getKeys(); } catch (Exception e) { logger.error(e.getMessage(), e); } } private void openRecentListFile(Event event) { Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem()); directoryService.getOpenFileConsumer().accept(path); } private void loadConfigurations() { try { CodeSource codeSource = ApplicationController.class.getProtectionDomain().getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); configPath = jarFile.toPath().getParent().getParent().resolve("conf"); YamlReader yamlReader = new YamlReader(new FileReader(configPath.resolve("config.yml").toFile())); yamlReader.getConfig().setClassTag("Config", Config.class); config = yamlReader.read(Config.class); } catch (Exception e) { logger.error(e.getMessage(), e); } if (!config.getDirectoryPanel()) Platform.runLater(() -> { splitPane.setDividerPositions(0, 0.51); }); } private void loadRecentFileList() { try { YamlReader yamlReader = new YamlReader(new FileReader(configPath.resolve("recentFiles.yml").toFile())); yamlReader.getConfig().setClassTag("RecentFiles", RecentFiles.class); RecentFiles readed = yamlReader.read(RecentFiles.class); recentFiles.addAll(readed.getFiles()); } catch (Exception e) { logger.error(e.getMessage(), e); } } public void externalBrowse() { hostServices.showDocument(String.format("http://localhost:%d/index.html", port)); } @FXML public void changeWorkingDir(Event actionEvent) { directoryService.changeWorkigDir(); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessionList.add(session); String value = lastRendered.getValue(); if (Objects.nonNull(value)) session.sendMessage(new TextMessage(value)); } @FXML public void closeApp(ActionEvent event) throws IOException { yamlService.persist(); } @FXML public void openDoc(Event event) { documentService.openDoc(); } @FXML public void newDoc(Event event) { documentService.newDoc(); } @FXML public void hideLeftSplit(Event event) { splitPane.setDividerPositions(0, 0.51); } public void applySohrtCuts() { Set<String> keySet = shortCuts.keySet(); for (String key : keySet) { current.currentEngine().executeScript(String.format("addNewCommand('%s','%s')", key, shortCuts.get(key))); } } public void onscroll(Object pos, Object max) { scrollService.onscroll(pos, max); } public void scrollToCurrentLine(String text) { scrollService.scrollToCurrentLine(text); } public void plantUml(String uml, String type, String fileName) throws IOException { threadService.runTaskLater(() -> { plantUmlService.plantUml(uml, type, fileName); }); } public void appendWildcard() { Label label = current.currentTabLabel(); if (!label.getText().contains(" *")) label.setText(label.getText() + " *"); } public void textListener(String text) { threadService.runTaskLater(() -> { String rendered = renderService.convertBasicHtml(text); if (Objects.nonNull(rendered)) lastRendered.setValue(rendered); }); } public void cutCopy(String data) { ClipboardContent clipboardContent = new ClipboardContent(); clipboardContent.putString(data); clipboard.setContent(clipboardContent); } public void copyFile(Path path) { ClipboardContent clipboardContent = new ClipboardContent(); clipboardContent.putFiles(Arrays.asList(path.toFile())); clipboard.setContent(clipboardContent); } public String paste() { if (clipboard.hasFiles()) { Optional<String> block = parserService.toImageBlock(clipboard.getFiles()); if (block.isPresent()) return block.get(); } if (clipboard.hasImage() && clipboard.hasHtml()) { Optional<String> block = parserService.toWebImageBlock(clipboard.getHtml()); if (block.isPresent()) return block.get(); } return clipboard.getString(); } public void saveDoc() { documentService.saveDoc(); } @FXML public void saveDoc(Event actionEvent) { documentService.saveDoc(); } public void fitToParent(Node node) { AnchorPane.setTopAnchor(node, 0.0); AnchorPane.setBottomAnchor(node, 0.0); AnchorPane.setLeftAnchor(node, 0.0); AnchorPane.setRightAnchor(node, 0.0); } public void saveAndCloseCurrentTab() { this.saveDoc(); tabPane.getTabs().remove(current.currentTab()); } public ProgressIndicator getIndikator() { return indikator; } public void setStage(Stage stage) { this.stage = stage; } public Stage getStage() { return stage; } public void setScene(Scene scene) { this.scene = scene; } public Scene getScene() { return scene; } public void setTableAnchor(AnchorPane tableAnchor) { this.tableAnchor = tableAnchor; } public AnchorPane getTableAnchor() { return tableAnchor; } public void setTableStage(Stage tableStage) { this.tableStage = tableStage; } public Stage getTableStage() { return tableStage; } public void setConfigAnchor(AnchorPane configAnchor) { this.configAnchor = configAnchor; } public AnchorPane getConfigAnchor() { return configAnchor; } public void setConfigStage(Stage configStage) { this.configStage = configStage; } public Stage getConfigStage() { return configStage; } public SplitPane getSplitPane() { return splitPane; } public TreeView<Item> getTreeView() { return treeView; } public void setHostServices(HostServicesDelegate hostServices) { this.hostServices = hostServices; } public HostServicesDelegate getHostServices() { return hostServices; } public Config getConfig() { return config; } public TablePopupService getTablePopupController() { return tablePopupController; } public StringProperty getLastRendered() { return lastRendered; } public ObservableList<String> getRecentFiles() { return recentFiles; } public TabPane getTabPane() { return tabPane; } public WebView getMathjaxView() { return mathjaxView; } public ChangeListener<String> getLastRenderedChangeListener() { return lastRenderedChangeListener; } public AnchorPane getRootAnchor() { return rootAnchor; } public WebView getPreviewView() { return previewView; } public int getPort() { return port; } public Path getConfigPath() { return configPath; } public Current getCurrent() { return current; } }
package com.maddyhome.idea.vim.group; import com.intellij.codeInsight.editorActions.CopyPastePostProcessor; import com.intellij.codeInsight.editorActions.CopyPastePreProcessor; import com.intellij.codeInsight.editorActions.TextBlockTransferable; import com.intellij.codeInsight.editorActions.TextBlockTransferableData; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.RoamingType; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.CaretStateTransferableData; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.richcopy.view.HtmlTransferableData; import com.intellij.openapi.editor.richcopy.view.RtfTransferableData; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.action.motion.mark.MotionGotoFileMarkAction; import com.maddyhome.idea.vim.action.motion.search.SearchAgainNextAction; import com.maddyhome.idea.vim.action.motion.search.SearchAgainPreviousAction; import com.maddyhome.idea.vim.action.motion.search.SearchEntryFwdAction; import com.maddyhome.idea.vim.action.motion.search.SearchEntryRevAction; import com.maddyhome.idea.vim.action.motion.text.MotionParagraphNextAction; import com.maddyhome.idea.vim.action.motion.text.MotionParagraphPreviousAction; import com.maddyhome.idea.vim.action.motion.text.MotionSentenceNextStartAction; import com.maddyhome.idea.vim.action.motion.text.MotionSentencePreviousStartAction; import com.maddyhome.idea.vim.action.motion.updown.MotionPercentOrMatchAction; import com.maddyhome.idea.vim.command.Argument; import com.maddyhome.idea.vim.command.Command; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.command.SelectionType; import com.maddyhome.idea.vim.common.Register; import com.maddyhome.idea.vim.common.TextRange; import com.maddyhome.idea.vim.handler.EditorActionHandlerBase; import com.maddyhome.idea.vim.helper.EditorHelper; import com.maddyhome.idea.vim.helper.StringHelper; import com.maddyhome.idea.vim.ui.ClipboardHandler; import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType; import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString; import com.maddyhome.idea.vim.vimscript.model.options.OptionChangeListener; import com.maddyhome.idea.vim.vimscript.services.OptionService; import kotlin.Pair; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; /** * This group works with command associated with copying and pasting text */ @State(name = "VimRegisterSettings", storages = { @Storage(value = "$APP_CONFIG$/vim_settings_local.xml", roamingType = RoamingType.DISABLED) }) public class RegisterGroup implements PersistentStateComponent<Element> { public static final char UNNAMED_REGISTER = '"'; public static final char LAST_SEARCH_REGISTER = '/'; // IdeaVim does not supporting writing to this register public static final char LAST_COMMAND_REGISTER = ':'; public static final char LAST_INSERTED_TEXT_REGISTER = '.'; public static final char SMALL_DELETION_REGISTER = '-'; public static final char BLACK_HOLE_REGISTER = '_'; public static final char ALTERNATE_BUFFER_REGISTER = '#'; // Not supported public static final char EXPRESSION_BUFFER_REGISTER = '='; public static final char CURRENT_FILENAME_REGISTER = '%'; // Not supported public static final @NonNls String CLIPBOARD_REGISTERS = "*+"; private static final @NonNls String NUMBERED_REGISTERS = "0123456789"; private static final @NonNls String NAMED_REGISTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final @NonNls String WRITABLE_REGISTERS = NUMBERED_REGISTERS + NAMED_REGISTERS + CLIPBOARD_REGISTERS + SMALL_DELETION_REGISTER + BLACK_HOLE_REGISTER + UNNAMED_REGISTER + LAST_SEARCH_REGISTER; private static final String READONLY_REGISTERS = "" + CURRENT_FILENAME_REGISTER + LAST_COMMAND_REGISTER + LAST_INSERTED_TEXT_REGISTER + ALTERNATE_BUFFER_REGISTER + EXPRESSION_BUFFER_REGISTER; // Expression buffer is not actually readonly private static final @NonNls String RECORDABLE_REGISTERS = NUMBERED_REGISTERS + NAMED_REGISTERS + UNNAMED_REGISTER; private static final String PLAYBACK_REGISTERS = RECORDABLE_REGISTERS + UNNAMED_REGISTER + CLIPBOARD_REGISTERS + LAST_INSERTED_TEXT_REGISTER; public static final String VALID_REGISTERS = WRITABLE_REGISTERS + READONLY_REGISTERS; private static final Logger logger = Logger.getInstance(RegisterGroup.class); private final @NotNull HashMap<Character, Register> registers = new HashMap<>(); private char defaultRegister = UNNAMED_REGISTER; private char lastRegister = defaultRegister; private char recordRegister = 0; private @Nullable List<KeyStroke> recordList = null; public RegisterGroup() { VimPlugin.getOptionService().addListener( "clipboard", new OptionChangeListener<VimDataType>() { @Override public void processGlobalValueChange(@Nullable VimDataType oldValue) { String clipboardOptionValue = ((VimString) VimPlugin.getOptionService() .getOptionValue(OptionService.Scope.GLOBAL.INSTANCE, "clipboard", "clipboard")).getValue(); if (clipboardOptionValue.contains("unnamed")) { defaultRegister = '*'; } else if (clipboardOptionValue.contains("unnamedplus")) { defaultRegister = '+'; } else { defaultRegister = UNNAMED_REGISTER; } lastRegister = defaultRegister; } }, true ); } /** * Check to see if the last selected register can be written to. */ private boolean isRegisterWritable() { return READONLY_REGISTERS.indexOf(lastRegister) < 0; } public boolean isValid(char reg) { return VALID_REGISTERS.indexOf(reg) != -1; } /** * Store which register the user wishes to work with. * * @param reg The register name * @return true if a valid register name, false if not */ public boolean selectRegister(char reg) { if (isValid(reg)) { lastRegister = reg; if (logger.isDebugEnabled()) logger.debug("register selected: " + lastRegister); return true; } else { return false; } } /** * Reset the selected register back to the default register. */ public void resetRegister() { lastRegister = defaultRegister; logger.debug("Last register reset to default register"); } public void resetRegisters() { defaultRegister = UNNAMED_REGISTER; lastRegister = defaultRegister; registers.clear(); } /** * Store text into the last register. * * @param editor The editor to get the text from * @param range The range of the text to store * @param type The type of copy * @param isDelete is from a delete * @return true if able to store the text into the register, false if not */ public boolean storeText(@NotNull Editor editor, @NotNull TextRange range, @NotNull SelectionType type, boolean isDelete) { if (isRegisterWritable()) { String text = EditorHelper.getText(editor, range); if (type == SelectionType.LINE_WISE && (text.length() == 0 || text.charAt(text.length() - 1) != '\n')) { // Linewise selection always has a new line at the end text += '\n'; } return storeTextInternal(editor, range, text, type, lastRegister, isDelete); } return false; } /** * Stores text, character wise, in the given special register * * <p>This method is intended to support writing to registers when the text cannot be yanked from an editor. This is * expected to only be used to update the search and command registers. It will not update named registers.</p> * * <p>While this method allows setting the unnamed register, this should only be done from tests, and only when it's * not possible to yank or cut from the fixture editor. This method will skip additional text processing, and won't * update other registers such as the small delete register or reorder the numbered registers. It is much more * preferable to yank from the fixture editor.</p> * * @param register The register to use for storing the text. Cannot be a normal text register * @param text The text to store, without further processing * @return True if the text is stored, false if the passed register is not supported */ public boolean storeTextSpecial(char register, @NotNull String text) { if (READONLY_REGISTERS.indexOf(register) == -1 && register != LAST_SEARCH_REGISTER && register != UNNAMED_REGISTER) { return false; } registers.put(register, new Register(register, SelectionType.CHARACTER_WISE, text, new ArrayList<>())); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + text + "\""); return true; } private boolean storeTextInternal(@NotNull Editor editor, @NotNull TextRange range, @NotNull String text, @NotNull SelectionType type, char register, boolean isDelete) { // Null register doesn't get saved, but acts like it was if (lastRegister == BLACK_HOLE_REGISTER) return true; int start = range.getStartOffset(); int end = range.getEndOffset(); if (isDelete && start == end) { return true; } // Normalize the start and end if (start > end) { int t = start; start = end; end = t; } // If this is an uppercase register, we need to append the text to the corresponding lowercase register final List<TextBlockTransferableData> transferableData = start != -1 ? getTransferableData(editor, range, text) : new ArrayList<>(); final String processedText = start != -1 ? preprocessText(editor, range, text, transferableData) : text; if (logger.isDebugEnabled()) { final String transferableClasses = transferableData.stream().map(it -> it.getClass().getName()).collect(Collectors.joining(",")); logger.debug("Copy to '" + lastRegister + "' with transferable data: " + transferableClasses); } if (Character.isUpperCase(register)) { char lreg = Character.toLowerCase(register); Register r = registers.get(lreg); // Append the text if the lowercase register existed if (r != null) { r.addTextAndResetTransferableData(processedText); } // Set the text if the lowercase register didn't exist yet else { registers.put(lreg, new Register(lreg, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + processedText + "\""); } } // Put the text in the specified register else { registers.put(register, new Register(register, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + register + "' contains: \"" + processedText + "\""); } if (CLIPBOARD_REGISTERS.indexOf(register) >= 0) { ClipboardHandler.setClipboardText(processedText, new ArrayList<>(transferableData), text); } // Also add it to the unnamed register if the default wasn't specified if (register != UNNAMED_REGISTER && ".:/".indexOf(register) == -1) { registers.put(UNNAMED_REGISTER, new Register(UNNAMED_REGISTER, type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + UNNAMED_REGISTER + "' contains: \"" + processedText + "\""); } if (isDelete) { boolean smallInlineDeletion = (type == SelectionType.CHARACTER_WISE || type == SelectionType.BLOCK_WISE ) && editor.offsetToLogicalPosition(start).line == editor.offsetToLogicalPosition(end).line; // Deletes go into numbered registers only if text is smaller than a line, register is used or it's a special case if (!smallInlineDeletion || register != defaultRegister || isSmallDeletionSpecialCase(editor)) { // Old 1 goes to 2, etc. Old 8 to 9, old 9 is lost for (char d = '8'; d >= '1'; d Register t = registers.get(d); if (t != null) { t.setName((char)(d + 1)); registers.put((char)(d + 1), t); } } registers.put('1', new Register('1', type, processedText, new ArrayList<>(transferableData))); } // Deletes smaller than one line and without specified register go the the "-" register if (smallInlineDeletion && register == defaultRegister) { registers.put(SMALL_DELETION_REGISTER, new Register(SMALL_DELETION_REGISTER, type, processedText, new ArrayList<>(transferableData))); } } // Yanks also go to register 0 if the default register was used else if (register == defaultRegister) { registers.put('0', new Register('0', type, processedText, new ArrayList<>(transferableData))); if (logger.isDebugEnabled()) logger.debug("register '" + '0' + "' contains: \"" + processedText + "\""); } if (start != -1) { VimPlugin.getMark().setChangeMarks(editor, new TextRange(start, end)); } return true; } public @NotNull List<TextBlockTransferableData> getTransferableData(@NotNull Editor editor, @NotNull TextRange textRange, String text) { final List<TextBlockTransferableData> transferableDatas = new ArrayList<>(); final Project project = editor.getProject(); if (project == null) return new ArrayList<>(); final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) return new ArrayList<>(); DumbService.getInstance(project).withAlternativeResolveEnabled(() -> { for (CopyPastePostProcessor<? extends TextBlockTransferableData> processor : CopyPastePostProcessor.EP_NAME .getExtensionList()) { try { transferableDatas.addAll(processor.collectTransferableData(file, editor, textRange.getStartOffsets(), textRange.getEndOffsets())); } catch (IndexNotReadyException ignore) { } } }); transferableDatas.add(new CaretStateTransferableData(new int[]{0}, new int[]{text.length()})); // These data provided by {@link com.intellij.openapi.editor.richcopy.TextWithMarkupProcessor} doesn't work with // IdeaVim and I don't see a way to fix it transferableDatas.removeIf(it -> (it instanceof RtfTransferableData) || (it instanceof HtmlTransferableData)); return transferableDatas; } private String preprocessText(@NotNull Editor editor, @NotNull TextRange textRange, String text, List<TextBlockTransferableData> transferableDatas) { final Project project = editor.getProject(); if (project == null) return text; final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null) return text; String rawText = TextBlockTransferable.convertLineSeparators(text, "\n", transferableDatas); if (VimPlugin.getOptionService().isSet(OptionService.Scope.GLOBAL.INSTANCE, "ideacopypreprocess", "ideacopypreprocess")) { String escapedText; for (CopyPastePreProcessor processor : CopyPastePreProcessor.EP_NAME.getExtensionList()) { escapedText = processor.preprocessOnCopy(file, textRange.getStartOffsets(), textRange.getEndOffsets(), rawText); if (escapedText != null) { return escapedText; } } } return text; } private boolean isSmallDeletionSpecialCase(Editor editor) { Command currentCommand = CommandState.getInstance(editor).getExecutingCommand(); if (currentCommand != null) { Argument argument = currentCommand.getArgument(); if (argument != null) { Command motionCommand = argument.getMotion(); EditorActionHandlerBase action = motionCommand.getAction(); return action instanceof MotionPercentOrMatchAction || action instanceof MotionSentencePreviousStartAction || action instanceof MotionSentenceNextStartAction || action instanceof MotionGotoFileMarkAction || action instanceof SearchEntryFwdAction || action instanceof SearchEntryRevAction || action instanceof SearchAgainNextAction || action instanceof SearchAgainPreviousAction || action instanceof MotionParagraphNextAction || action instanceof MotionParagraphPreviousAction; } } return false; } /** * Get the last register selected by the user * * @return The register, null if no such register */ public @Nullable Register getLastRegister() { return getRegister(lastRegister); } public @Nullable Register getPlaybackRegister(char r) { if (PLAYBACK_REGISTERS.indexOf(r) != 0) { return getRegister(r); } else { return null; } } public @Nullable Register getRegister(char r) { // Uppercase registers actually get the lowercase register if (Character.isUpperCase(r)) { r = Character.toLowerCase(r); } return CLIPBOARD_REGISTERS.indexOf(r) >= 0 ? refreshClipboardRegister(r) : registers.get(r); } public void saveRegister(char r, Register register) { // Uppercase registers actually get the lowercase register if (Character.isUpperCase(r)) { r = Character.toLowerCase(r); } if (CLIPBOARD_REGISTERS.indexOf(r) >= 0) { ClipboardHandler.setClipboardText(register.getText(), new ArrayList<>(register.getTransferableData()), register.getRawText()); } registers.put(r, register); } /** * Gets the last register name selected by the user * * @return The register name */ public char getCurrentRegister() { return lastRegister; } /** * The register key for the default register. */ public char getDefaultRegister() { return defaultRegister; } public @NotNull List<Register> getRegisters() { final List<Register> res = new ArrayList<>(registers.values()); for (int i = 0; i < CLIPBOARD_REGISTERS.length(); i++) { final char r = CLIPBOARD_REGISTERS.charAt(i); final Register register = refreshClipboardRegister(r); if (register != null) { res.add(register); } } res.sort(Register.KeySorter.INSTANCE); return res; } public boolean startRecording(Editor editor, char register) { if (RECORDABLE_REGISTERS.indexOf(register) != -1) { CommandState.getInstance(editor).setRecording(true); recordRegister = register; recordList = new ArrayList<>(); return true; } else { return false; } } public void recordKeyStroke(KeyStroke key) { if (recordRegister != 0 && recordList != null) { recordList.add(key); } } public void recordText(@NotNull String text) { if (recordRegister != 0 && recordList != null) { recordList.addAll(StringHelper.stringToKeys(text)); } } public void setKeys(char register, @NotNull List<KeyStroke> keys) { registers.put(register, new Register(register, SelectionType.CHARACTER_WISE, keys)); } public void setKeys(char register, @NotNull List<KeyStroke> keys, SelectionType type) { registers.put(register, new Register(register, type, keys)); } public void finishRecording(Editor editor) { if (recordRegister != 0) { Register reg = null; if (Character.isUpperCase(recordRegister)) { reg = getRegister(recordRegister); } if (recordList != null) { if (reg == null) { reg = new Register(Character.toLowerCase(recordRegister), SelectionType.CHARACTER_WISE, recordList); registers.put(Character.toLowerCase(recordRegister), reg); } else { reg.addKeys(recordList); } } CommandState.getInstance(editor).setRecording(false); } recordRegister = 0; } public void saveData(final @NotNull Element element) { logger.debug("Save registers data"); final Element registersElement = new Element("registers"); if (logger.isTraceEnabled()) { logger.trace("Saving " + registers.size() + " registers"); } for (Character key : registers.keySet()) { final Register register = registers.get(key); if (logger.isTraceEnabled()) { logger.trace("Saving register '" + key + "'"); } final Element registerElement = new Element("register"); registerElement.setAttribute("name", String.valueOf(key)); registerElement.setAttribute("type", Integer.toString(register.getType().getValue())); final String text = register.getText(); if (text != null) { logger.trace("Save register as 'text'"); final Element textElement = new Element("text"); StringHelper.setSafeXmlText(textElement, text); registerElement.addContent(textElement); } else { logger.trace("Save register as 'keys'"); final Element keys = new Element("keys"); final List<KeyStroke> list = register.getKeys(); for (KeyStroke stroke : list) { final Element k = new Element("key"); k.setAttribute("char", Integer.toString(stroke.getKeyChar())); k.setAttribute("code", Integer.toString(stroke.getKeyCode())); k.setAttribute("mods", Integer.toString(stroke.getModifiers())); keys.addContent(k); } registerElement.addContent(keys); } registersElement.addContent(registerElement); } element.addContent(registersElement); logger.debug("Finish saving registers data"); } public void readData(final @NotNull Element element) { logger.debug("Read registers data"); final Element registersElement = element.getChild("registers"); if (registersElement != null) { logger.trace("'registers' element is not null"); final List<Element> registerElements = registersElement.getChildren("register"); if (logger.isTraceEnabled()) { logger.trace("Detected " + registerElements.size() + " register elements"); } for (Element registerElement : registerElements) { final char key = registerElement.getAttributeValue("name").charAt(0); if (logger.isTraceEnabled()) { logger.trace("Read register '" + key + "'"); } final Register register; final Element textElement = registerElement.getChild("text"); final String typeText = registerElement.getAttributeValue("type"); final SelectionType type = SelectionType.fromValue(Integer.parseInt(typeText)); if (textElement != null) { logger.trace("Register has 'text' element"); final String text = StringHelper.getSafeXmlText(textElement); if (text != null) { logger.trace("Register data parsed"); register = new Register(key, type, text, Collections.emptyList()); } else { logger.trace("Cannot parse register data"); register = null; } } else { logger.trace("Register has 'keys' element"); final Element keysElement = registerElement.getChild("keys"); final List<Element> keyElements = keysElement.getChildren("key"); final List<KeyStroke> strokes = new ArrayList<>(); for (Element keyElement : keyElements) { final int code = Integer.parseInt(keyElement.getAttributeValue("code")); final int modifiers = Integer.parseInt(keyElement.getAttributeValue("mods")); final char c = (char)Integer.parseInt(keyElement.getAttributeValue("char")); //noinspection MagicConstant strokes.add(c == KeyEvent.CHAR_UNDEFINED ? KeyStroke.getKeyStroke(code, modifiers) : KeyStroke.getKeyStroke(c)); } register = new Register(key, type, strokes); } logger.trace("Save register to vim registers"); registers.put(key, register); } } logger.debug("Finish reading registers data"); } private @Nullable Register refreshClipboardRegister(char r) { final Pair<String, List<TextBlockTransferableData>> clipboardData = ClipboardHandler.getClipboardTextAndTransferableData(); if (clipboardData == null) return null; final Register currentRegister = registers.get(r); final String text = clipboardData.getFirst(); final List<TextBlockTransferableData> transferableData = clipboardData.getSecond(); if (text != null) { if (currentRegister != null && text.equals(currentRegister.getText())) { return currentRegister; } return new Register(r, guessSelectionType(text), text, transferableData); } return null; } private @NotNull SelectionType guessSelectionType(@NotNull String text) { if (text.endsWith("\n")) { return SelectionType.LINE_WISE; } else { return SelectionType.CHARACTER_WISE; } } @Nullable @Override public Element getState() { Element element = new Element("registers"); saveData(element); return element; } @Override public void loadState(@NotNull Element state) { readData(state); } }
package com.minespaceships.mod.spaceship; import javax.vecmath.Vector3d; import com.minespaceships.util.BlockCopier; import com.minespaceships.util.Vec3Op; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; import net.minecraft.util.Vec3i; import net.minecraft.world.World; import net.minecraft.world.WorldServer; public class Spaceship { private BlockPos minPosition; private BlockPos maxPosition; private BlockPos span; private BlockPos origin; private WorldServer worldS; private WorldClient worldC; public Spaceship(final BlockPos minPosition,final BlockPos maxPosition, WorldClient worldC, WorldServer worldS){ setMeasurements(minPosition, maxPosition); this.worldC = worldC; this.worldS = worldS; } public Spaceship(final BlockPos minPosition, int dimX, int dimY, int dimZ, WorldClient worldC, WorldServer worldS){ BlockPos recSpan = new BlockPos(dimX, dimY, dimZ); setMeasurements(minPosition, ((BlockPos) recSpan).add(minPosition)); this.worldC = worldC; this.worldS = worldS; } public Spaceship(final BlockPos minSpan, final BlockPos origin, final BlockPos maxSpan, WorldClient worldC, WorldServer worldS){ setMeasurements(((BlockPos) minSpan).add(origin), ((BlockPos) maxSpan).add(origin)); this.origin = origin; this.worldC = worldC; this.worldS = worldS; } private void setMeasurements(final BlockPos minPos, final BlockPos maxPos){ minPosition = minPos; maxPosition = maxPos; span = ((BlockPos) maxPos).subtract(minPos); origin = Vec3Op.scale(span, 0.5); } public void copyTo(BlockPos addDirection){ //copyTo(addDirection, worldC); copyTo(addDirection, worldS); } public void copyTo(BlockPos addDirection, World world){ BlockPos add = new BlockPos(addDirection); for(int x = 0; x < span.getX(); x++){ for(int y = 0; y < span.getY(); y++){ for(int z = 0; z < span.getZ(); z++){ BlockPos Pos = new BlockPos(x,y,z); Pos = Pos.add(minPosition); BlockCopier.copyBlock(world, Pos, Pos.add(add)); } } } world.markBlockRangeForRenderUpdate(minPosition, maxPosition); } }