text
stringlengths
7
1.01M
import java.util.*; /* 1838. Frequency of the Most Frequent Element */ public class Solution { public int maxFrequency(int[] nums, int k) { Arrays.sort(nums); int n = nums.length; long total = 0; int l = 0, res = 1; for (int r = 1; r < n; ++r) { total += (long) (nums[r] - nums[r - 1]) * (r - l); while (total > k) { total -= nums[r] - nums[l]; ++l; } res = Math.max(res, r - l + 1); } return res; } }
package org.oulipo.streams.opcodes; import java.io.IOException; /** * Puts meta-data into <code>DocumentFile</code> */ public final class PutMetaDataOp extends Op { /** * Constructs <code>PutMetaDataOp</code> with specified indexes * */ public PutMetaDataOp(int subjectIndex, int predicateIndex, int objectIndex, byte objectType) { super(Op.PUT_META_DATA); } @Override public byte[] encode() throws IOException { return null; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/servicecontrol/v1/service_controller.proto package com.google.api.servicecontrol.v1; public interface ReportResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:google.api.servicecontrol.v1.ReportResponse) com.google.protobuf.MessageOrBuilder { /** * <pre> * Partial failures, one for each `Operation` in the request that failed * processing. There are three possible combinations of the RPC status: * 1. The combination of a successful RPC status and an empty `report_errors` * list indicates a complete success where all `Operations` in the * request are processed successfully. * 2. The combination of a successful RPC status and a non-empty * `report_errors` list indicates a partial success where some * `Operations` in the request succeeded. Each * `Operation` that failed processing has a corresponding item * in this list. * 3. A failed RPC status indicates a general non-deterministic failure. * When this happens, it's impossible to know which of the * 'Operations' in the request succeeded or failed. * </pre> * * <code>repeated .google.api.servicecontrol.v1.ReportResponse.ReportError report_errors = 1;</code> */ java.util.List<com.google.api.servicecontrol.v1.ReportResponse.ReportError> getReportErrorsList(); /** * <pre> * Partial failures, one for each `Operation` in the request that failed * processing. There are three possible combinations of the RPC status: * 1. The combination of a successful RPC status and an empty `report_errors` * list indicates a complete success where all `Operations` in the * request are processed successfully. * 2. The combination of a successful RPC status and a non-empty * `report_errors` list indicates a partial success where some * `Operations` in the request succeeded. Each * `Operation` that failed processing has a corresponding item * in this list. * 3. A failed RPC status indicates a general non-deterministic failure. * When this happens, it's impossible to know which of the * 'Operations' in the request succeeded or failed. * </pre> * * <code>repeated .google.api.servicecontrol.v1.ReportResponse.ReportError report_errors = 1;</code> */ com.google.api.servicecontrol.v1.ReportResponse.ReportError getReportErrors(int index); /** * <pre> * Partial failures, one for each `Operation` in the request that failed * processing. There are three possible combinations of the RPC status: * 1. The combination of a successful RPC status and an empty `report_errors` * list indicates a complete success where all `Operations` in the * request are processed successfully. * 2. The combination of a successful RPC status and a non-empty * `report_errors` list indicates a partial success where some * `Operations` in the request succeeded. Each * `Operation` that failed processing has a corresponding item * in this list. * 3. A failed RPC status indicates a general non-deterministic failure. * When this happens, it's impossible to know which of the * 'Operations' in the request succeeded or failed. * </pre> * * <code>repeated .google.api.servicecontrol.v1.ReportResponse.ReportError report_errors = 1;</code> */ int getReportErrorsCount(); /** * <pre> * Partial failures, one for each `Operation` in the request that failed * processing. There are three possible combinations of the RPC status: * 1. The combination of a successful RPC status and an empty `report_errors` * list indicates a complete success where all `Operations` in the * request are processed successfully. * 2. The combination of a successful RPC status and a non-empty * `report_errors` list indicates a partial success where some * `Operations` in the request succeeded. Each * `Operation` that failed processing has a corresponding item * in this list. * 3. A failed RPC status indicates a general non-deterministic failure. * When this happens, it's impossible to know which of the * 'Operations' in the request succeeded or failed. * </pre> * * <code>repeated .google.api.servicecontrol.v1.ReportResponse.ReportError report_errors = 1;</code> */ java.util.List<? extends com.google.api.servicecontrol.v1.ReportResponse.ReportErrorOrBuilder> getReportErrorsOrBuilderList(); /** * <pre> * Partial failures, one for each `Operation` in the request that failed * processing. There are three possible combinations of the RPC status: * 1. The combination of a successful RPC status and an empty `report_errors` * list indicates a complete success where all `Operations` in the * request are processed successfully. * 2. The combination of a successful RPC status and a non-empty * `report_errors` list indicates a partial success where some * `Operations` in the request succeeded. Each * `Operation` that failed processing has a corresponding item * in this list. * 3. A failed RPC status indicates a general non-deterministic failure. * When this happens, it's impossible to know which of the * 'Operations' in the request succeeded or failed. * </pre> * * <code>repeated .google.api.servicecontrol.v1.ReportResponse.ReportError report_errors = 1;</code> */ com.google.api.servicecontrol.v1.ReportResponse.ReportErrorOrBuilder getReportErrorsOrBuilder( int index); /** * <pre> * The actual config id used to process the request. * </pre> * * <code>string service_config_id = 2;</code> * @return The serviceConfigId. */ java.lang.String getServiceConfigId(); /** * <pre> * The actual config id used to process the request. * </pre> * * <code>string service_config_id = 2;</code> * @return The bytes for serviceConfigId. */ com.google.protobuf.ByteString getServiceConfigIdBytes(); /** * <pre> * The current service rollout id used to process the request. * </pre> * * <code>string service_rollout_id = 4;</code> * @return The serviceRolloutId. */ java.lang.String getServiceRolloutId(); /** * <pre> * The current service rollout id used to process the request. * </pre> * * <code>string service_rollout_id = 4;</code> * @return The bytes for serviceRolloutId. */ com.google.protobuf.ByteString getServiceRolloutIdBytes(); }
/* * MIT License * * Copyright (c) 2019 Consumer Agent Portal, LLC (TrustedChoice.com) * Superkick Ventures, LLC (Ask Kodiak) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.trustedchoice.askkodiak.v2.model.company; import java.util.List; import java.util.Map; @lombok.Data public class Companies { /** * The total count of companies returned by this query. */ private Integer count; /** * The number of companies in each page of results. */ private Integer companiesPerPage; /** * The page of results which the response represents. */ private Integer page; /** * The total number of result pages available. */ private Integer pages; /** * A map summarizing the filters (if any) applied to the query. */ private Map<String, String> filters; /** * An array of 0-n companies objects eligible for this code. * <p> * For documentation about the singleton company instances in this array see the documentation for * Company/GetCompany */ private List<Company> companies; }
package module0069_public_tests_unittests.a; import javax.rmi.ssl.*; import java.awt.datatransfer.*; import java.beans.beancontext.*; /** * Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut * labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. * Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. * * @see javax.net.ssl.ExtendedSSLSession * @see javax.rmi.ssl.SslRMIClientSocketFactory * @see java.awt.datatransfer.DataFlavor */ @SuppressWarnings("all") public abstract class Foo3<V> extends module0069_public_tests_unittests.a.Foo2<V> implements module0069_public_tests_unittests.a.IFoo3<V> { java.beans.beancontext.BeanContext f0 = null; java.io.File f1 = null; java.rmi.Remote f2 = null; public V element; public static Foo3 instance; public static Foo3 getInstance() { return instance; } public static <T> T create(java.util.List<T> input) { return module0069_public_tests_unittests.a.Foo2.create(input); } public String getName() { return module0069_public_tests_unittests.a.Foo2.getInstance().getName(); } public void setName(String string) { module0069_public_tests_unittests.a.Foo2.getInstance().setName(getName()); return; } public V get() { return (V)module0069_public_tests_unittests.a.Foo2.getInstance().get(); } public void set(Object element) { this.element = (V)element; module0069_public_tests_unittests.a.Foo2.getInstance().set(this.element); } public V call() throws Exception { return (V)module0069_public_tests_unittests.a.Foo2.getInstance().call(); } }
package gamejam.spy.gameObjects.tiles; public class SpikeTile { }
package Creational.AbstractFactory.GlobalCarFactory; public class CarFactory { private CarFactory() { // Prevent instantiation } public static Car buildCar(CarType model) { Car car = null; // Read location property somewhere from configuration Location location = Location.ASIA; // Use location specific car factory switch(location) { case USA: car = USACarFactory.buildCar(model); break; case ASIA: car = AsiaCarFactory.buildCar(model); break; default: car = DefaultCarFactory.buildCar(model); } return car; } }
package com.elmakers.mine.bukkit.utility; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.BlockFace; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.BlockVector; import org.bukkit.util.EulerAngle; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.data.SerializedLocation; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.configuration.TranslatingConfigurationSection; /** * This was originally part of EffectLib, but I wanted to make an independent copy to use for Magic. */ public class ConfigUtils { public static Random random = new Random(); public static List<ConfigurationSection> getNodeList(ConfigurationSection node, String path) { List<ConfigurationSection> results = new ArrayList<>(); List<Map<?, ?>> mapList = node.getMapList(path); for (Map<?, ?> map : mapList) { results.add(toConfigurationSection(node, map)); } return results; } public static ConfigurationSection newSection(ConfigurationSection parent) { return newSection(parent, ""); } public static ConfigurationSection newSection(ConfigurationSection parent, String path) { if (parent instanceof TranslatingConfigurationSection) { return ((TranslatingConfigurationSection)parent).newSection(path); } return new TranslatingConfigurationSection(parent, path); } public static ConfigurationSection toConfigurationSection(ConfigurationSection parent, Map<?, ?> nodeMap) { return toConfigurationSection(parent, "", nodeMap); } public static ConfigurationSection toConfigurationSection(ConfigurationSection parent, String path, Map<?, ?> nodeMap) { ConfigurationSection newSection = newSection(parent, path); for (Map.Entry<?, ?> entry : nodeMap.entrySet()) { newSection.set(entry.getKey().toString(), entry.getValue()); } return newSection; } public static ConfigurationSection convertConfigurationSection(Map<?, ?> nodeMap) { ConfigurationSection newSection = new MemoryConfiguration(); for (Map.Entry<?, ?> entry : nodeMap.entrySet()) { set(newSection, entry.getKey().toString(), entry.getValue()); } return newSection; } public static ConfigurationSection toStringConfiguration(Map<String, String> stringMap) { if (stringMap == null) return null; ConfigurationSection configMap = new MemoryConfiguration(); for (Map.Entry<String, String> entry : stringMap.entrySet()) { configMap.set(entry.getKey(), entry.getValue()); } return configMap; } public static void set(ConfigurationSection node, String path, Object value) { if (value == null) { node.set(path, null); return; } boolean isTrue = value.equals("true"); boolean isFalse = value.equals("false"); if (isTrue || isFalse) { node.set(path, isTrue); return; } try { Integer i = (value instanceof Integer) ? (Integer) value : Integer.parseInt(value.toString()); node.set(path, i); } catch (Exception ex) { try { double d; if (value instanceof Double) d = (Double) value; else if (value instanceof Float) d = (Float) value; else d = Double.parseDouble(value.toString()); node.set(path, d); } catch (Exception ex2) { node.set(path, value); } } } public static ConfigurationSection getConfigurationSection(ConfigurationSection base, String key) { ConfigurationSection section = base.getConfigurationSection(key); if (section != null) return section; Object value = base.get(key); if (value == null) return null; if (value instanceof ConfigurationSection) return (ConfigurationSection)value; if (value instanceof Map) { ConfigurationSection newChild = base.createSection(key); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)value; for (Map.Entry<String, Object> entry : map.entrySet()) { newChild.set(entry.getKey(), entry.getValue()); } base.set(key, newChild); return newChild; } return null; } public static boolean isMaxValue(String stringValue) { return stringValue.equalsIgnoreCase("infinite") || stringValue.equalsIgnoreCase("forever") || stringValue.equalsIgnoreCase("infinity") || stringValue.equalsIgnoreCase("max"); } @Nullable @SuppressWarnings("unchecked") public static List<Object> getList(ConfigurationSection section, String path) { List<Object> list = (List<Object>)section.getList(path); if (list != null) { return list; } Object o = section.get(path); return getList(o); } @Nullable @SuppressWarnings("unchecked") public static List<Object> getList(Object o) { if (o == null) { return null; } else if (o instanceof List) { return (List<Object>) o; } else if (o instanceof String) { return new ArrayList<>(Arrays.asList(StringUtils.split((String) o, ','))); } else { List<Object> single = new ArrayList<>(); single.add(o); return single; } } public static List<String> getStringList(ConfigurationSection section, String path, List<String> def) { List<String> list = getStringList(section, path); return list == null ? (def == null ? new ArrayList<>() : def) : list; } @Nullable public static List<String> getStringList(ConfigurationSection section, String path) { List<Object> raw = getList(section, path); return getStringList(raw); } @Nullable public static List<String> getStringList(ConfigurationSection section, String path, String delimiter) { if (section.isList(path)) { List<Object> raw = getList(section, path); return getStringList(raw); } String value = section.getString(path); if (value == null) { return null; } String[] pieces = StringUtils.split(value, delimiter); return Arrays.asList(pieces); } @Nullable public static List<String> getStringList(Object o) { List<Object> raw = getList(o); return getStringList(raw); } @Nullable public static List<String> getStringList(List<Object> rawList) { if (rawList == null) { return null; } List<String> list = new ArrayList<>(); for (Object o : rawList) { // This prevents weird behaviors when we're expecting a list of strings but given // a list of ConfigurationSections, Lists or other complex types if (o == null || o instanceof ConfigurationSection || o instanceof List || o instanceof Map) { continue; } list.add(o.toString()); } return list; } @Nullable public static List<PotionEffect> getPotionEffectObjects(ConfigurationSection baseConfig, String key, Logger log) { return getPotionEffectObjects(baseConfig, key, log, Integer.MAX_VALUE, 0, true, false); } @Nullable public static List<PotionEffect> getPotionEffectObjects(ConfigurationSection baseConfig, String key, Logger log, int defaultDuration) { return getPotionEffectObjects(baseConfig, key, log, defaultDuration, 0, true, true); } @Nullable public static List<PotionEffect> getPotionEffectObjects(ConfigurationSection baseConfig, String key, Logger log, int defaultDuration, int defaultAmplifier, boolean defaultAmbient, boolean defaultParticles) { List<PotionEffect> potionEffects = null; List<Object> genericList = getList(baseConfig, key); if (genericList != null && !genericList.isEmpty()) { potionEffects = new ArrayList<>(); for (Object genericEntry : genericList) { if (genericEntry instanceof String) { String typeString = (String)genericEntry; PotionEffectType effectType = PotionEffectType.getByName(typeString.toUpperCase()); if (effectType == null) { log.log(Level.WARNING, "Invalid potion effect type: " + typeString); continue; } int ticks = defaultDuration / 50; potionEffects.add(new PotionEffect(effectType, effectType.isInstant() ? 1 : ticks, defaultAmplifier, defaultAmbient, defaultParticles)); } else { ConfigurationSection potionEffectSection = genericEntry instanceof ConfigurationSection ? (ConfigurationSection)genericEntry : null; if (potionEffectSection == null && genericEntry instanceof Map) { potionEffectSection = toConfigurationSection(baseConfig, (Map<?, ?>)genericEntry); } if (potionEffectSection != null) { if (potionEffectSection.contains("type")) { PotionEffectType effectType = PotionEffectType.getByName(potionEffectSection.getString("type").toUpperCase()); if (effectType == null) { log.log(Level.WARNING, "Invalid potion effect type: " + potionEffectSection.getString("type", "(null)")); continue; } int ticks = Integer.MAX_VALUE; String duration = potionEffectSection.getString("duration"); if (duration == null || (!duration.equals("forever") && !duration.equals("infinite") && !duration.equals("infinity"))) { ticks = (int) (potionEffectSection.getLong("duration", defaultDuration) / 50); ticks = potionEffectSection.getInt("ticks", ticks); } int amplifier = potionEffectSection.getInt("amplifier", defaultAmplifier); boolean ambient = potionEffectSection.getBoolean("ambient", defaultAmbient); boolean particles = potionEffectSection.getBoolean("particles", defaultParticles); potionEffects.add(new PotionEffect(effectType, effectType.isInstant() ? 1 : ticks, amplifier, ambient, particles)); } else { Collection<String> types = potionEffectSection.getKeys(false); for (String type : types) { PotionEffectType effectType = PotionEffectType.getByName(type.toUpperCase()); if (effectType == null) { log.log(Level.WARNING, "Invalid potion effect type: " + type); continue; } int amplifier = potionEffectSection.getInt(type, defaultAmplifier); int ticks = defaultDuration / 50; potionEffects.add(new PotionEffect(effectType, effectType.isInstant() ? 1 : ticks, amplifier, defaultAmbient, defaultParticles)); } } } } } } return potionEffects; } @Nullable public static EulerAngle getEulerAngle(ConfigurationSection node, String path) { Vector vector = getVector(node, path, null); return vector == null ? null : new EulerAngle(vector.getX(), vector.getY(), vector.getZ()); } @Nullable public static Vector getVector(ConfigurationSection node, String path) { return getVector(node, path, null); } @Nullable public static Vector getVector(ConfigurationSection node, String path, Vector def) { return getVector(node, path, def, null, null); } @Nullable public static Vector getVector(ConfigurationSection node, String path, Vector def, Logger logger, String logContext) { Object o = node.get(path, null); if (o == null) { return def; } Vector result = toVector(o); if (result == null && logger != null) { if (logContext == null) { logContext = "unknown"; } logger.warning("Invalid vector in " + logContext + ": " + o); } return result; } @Nullable public static Vector toVector(Object o) { if (o instanceof Vector) { return (Vector)o; } if (o instanceof ConfigurationSection) { ConfigurationSection config = (ConfigurationSection)o; return new Vector(config.getDouble("x"), config.getDouble("y"), config.getDouble("z")); } if (o instanceof String) { try { String parse = (String)o; if (parse.isEmpty()) return null; // rand() coordinates can not use commas as the delimiter if (!parse.contains("r") && !parse.contains("R") && parse.contains(",")) { parse = parse.replace(" ", ""); parse = parse.replace(",", " "); } if (parse.contains("|")) { parse = parse.replace(" ", ""); parse = parse.replace("|", " "); } String[] pieces = StringUtils.split(parse, ' '); if (pieces.length < 3) return null; double x = parseDouble(pieces[0]); double y = parseDouble(pieces[1]); double z = parseDouble(pieces[2]); return new Vector(x, y, z); } catch (Exception ex) { return null; } } return null; } protected static double parseDouble(String s) throws NumberFormatException { if (s == null || s.isEmpty()) return 0; char firstChar = s.charAt(0); if (firstChar == 'r' || firstChar == 'R') { String[] pieces = StringUtils.split(s, "(,)"); double min = Double.parseDouble(pieces[1].trim()); double max = Double.parseDouble(pieces[2].trim()); return random.nextDouble() * (max - min) + min; } return Double.parseDouble(s); } @Nullable public static Location getLocation(ConfigurationSection node, String path) { String stringData = node.getString(path); if (stringData == null) { return null; } return toLocation(stringData); } @Nullable public static SerializedLocation getSerializedLocation(ConfigurationSection node, String path) { String stringData = node.getString(path); if (stringData == null) { return null; } return toSerializedLocation(stringData); } @Nullable public static BlockFace toBlockFace(String s) { BlockFace face = null; try { face = BlockFace.valueOf(s.toUpperCase()); } catch (Exception ex) { face = null; } return face; } public static String fromBlockFace(BlockFace face) { return face.name().toLowerCase(); } public static String fromVector(Vector vector) { if (vector == null) return ""; return vector.getX() + "," + vector.getY() + "," + vector.getZ(); } /** * Serialises a location as a relative offset to another location. * * <p>One of the following formats may be used, depending on the * availability of the locations, whether or not they are in the same * world and whether or not the pitch and the yaw are the same. * * <ul> * <li>{@code ""}, the empty string, when no location was specified, or the * center location was not valid. * <li>{@code "x,y,z"}, offsets relative to the center, with the same * orientation. * <li>{@code "x,y,z,yaw,pitch"}, offset relative to the center, with * absolute rotations. * <li>{@code "x,y,z,world,yaw,pitch"}, an absolute location an orientation * </ul> * * @param location The location to serialise. * @param relativeTo The center to make the location relative to. * @return The string representation. */ @Nonnull public static String fromLocation( @Nullable Location location, @Nullable Location relativeTo) { if (location == null || location.getWorld() == null) { // Invalid location return ""; } else if (relativeTo != null && relativeTo.getWorld() == null) { // Invalid center // FIXME: Shouldn't we just return a non-relative location? return ""; } else if (relativeTo == null || !relativeTo.getWorld().equals(location.getWorld())) { // No relative, or they are not in the same world return fromLocation(location); } // Make location relative to relativeTo location = location.clone(); location.subtract(relativeTo); String serialized = location.getX() + "," + location.getY() + "," + location.getZ(); if (location.getPitch() != relativeTo.getPitch() || location.getYaw() != relativeTo.getYaw()) { serialized += "," + location.getYaw() + "," + location.getPitch(); } return serialized; } @Nonnull public static String fromLocation(@Nullable Location location) { if (location == null) return ""; if (location.getWorld() == null) return ""; return location.getX() + "," + location.getY() + "," + location.getZ() + "," + location.getWorld().getName() + "," + location.getYaw() + "," + location.getPitch(); } public static String fromSerializedLocation(SerializedLocation location) { if (location == null) return ""; if (location.getWorld() == null) return ""; return location.getX() + "," + location.getY() + "," + location.getZ() + "," + location.getWorldName() + "," + location.getYaw() + "," + location.getPitch(); } @Nullable public static String getWorldName(String descriptor) { if (descriptor == null) return null; String[] pieces = StringUtils.split(descriptor, ','); return pieces.length > 3 ? pieces[3] : null; } @Nullable public static Location toLocation(Object o) { return toLocation(o, null); } @Nullable public static Location toLocation(Object o, Location relativeTo) { if (o instanceof Location) { return (Location)o; } SerializedLocation location = toSerializedLocation(o, relativeTo); return location == null ? null : location.asLocation(); } @Nullable public static SerializedLocation toSerializedLocation(Object o) { return toSerializedLocation(o, null); } @Nullable public static SerializedLocation toSerializedLocation(Object o, Location relativeTo) { if (o instanceof SerializedLocation) { return (SerializedLocation)o; } if (o instanceof String) { try { float pitch = 0; float yaw = 0; String[] pieces = StringUtils.split((String)o, ','); double x = parseDouble(pieces[0]); double y = parseDouble(pieces[1]); double z = parseDouble(pieces[2]); String world; if (relativeTo != null && (pieces.length == 3 || pieces.length == 5)) { world = relativeTo.getWorld().getName(); x += relativeTo.getX(); y += relativeTo.getY(); z += relativeTo.getZ(); if (pieces.length == 5) { yaw = Float.parseFloat(pieces[3]); pitch = Float.parseFloat(pieces[4]); } else { yaw = relativeTo.getYaw(); pitch = relativeTo.getPitch(); } } else { if (pieces.length > 3) { world = pieces[3]; } else { world = Bukkit.getWorlds().get(0).getName(); } if (pieces.length > 5) { yaw = Float.parseFloat(pieces[4]); pitch = Float.parseFloat(pieces[5]); } } return new SerializedLocation(world, new BlockVector(x, y, z), yaw, pitch); } catch (Exception ex) { return null; } } return null; } protected static int parseInt(String s) throws NumberFormatException { if (s == null || s.isEmpty()) return 0; char firstChar = s.charAt(0); if (firstChar == 'r' || firstChar == 'R') { String[] pieces = StringUtils.split(s, "(,)"); double min = Double.parseDouble(pieces[1].trim()); double max = Double.parseDouble(pieces[2].trim()); return (int)Math.floor(random.nextDouble() * (max - min) + min); } return (int)Math.floor(Double.parseDouble(s)); } public static double overrideDouble(String override, double value) { if (override == null || override.length() == 0) return value; try { if (override.startsWith("~")) { override = override.substring(1); value = value + parseDouble(override); } else if (override.startsWith("*")) { override = override.substring(1); value = value * parseDouble(override); } else { value = parseDouble(override); } } catch (Exception ex) { // ex.printStackTrace(); } return value; } protected static double overrideDouble(ConfigurationSection node, double value, String nodeName) { String override = node.getString(nodeName); return overrideDouble(override, value); } @Nullable public static World overrideWorld(MageController controller, ConfigurationSection node, String path, World world, boolean canCreateWorlds) { return overrideWorld(controller, node.getString(path), world, canCreateWorlds); } @Nullable public static World overrideWorld(MageController controller, String worldName, World world, boolean canCreateWorlds) { if (worldName == null || worldName.length() == 0) return null; if (worldName.charAt(0) == '~') { if (world == null) return null; String baseWorld = world.getName(); worldName = worldName.substring(1); worldName = worldName.trim(); if (worldName.charAt(0) == '-') { worldName = worldName.substring(1); worldName = worldName.trim(); worldName = baseWorld.replace(worldName, ""); } else { worldName = baseWorld + worldName; } } World worldOverride = Bukkit.getWorld(worldName); if (worldOverride == null) { if (canCreateWorlds && world != null) { Bukkit.getLogger().info("Creating/Loading world: " + worldName); worldOverride = controller.copyWorld(worldName, world); if (worldOverride == null) { Bukkit.getLogger().warning("Failed to load world: " + worldName); return null; } } else { Bukkit.getLogger().warning("Could not load world: " + worldName); return null; } } return worldOverride; } @Nullable public static Location overrideLocation(MageController controller, ConfigurationSection node, String basePath, Location location, boolean canCreateWorlds) { String xName = basePath + "x"; String yName = basePath + "y"; String zName = basePath + "z"; String dxName = basePath + "dx"; String dyName = basePath + "dy"; String dzName = basePath + "dz"; boolean hasPosition = node.contains(xName) || node.contains(yName) || node.contains(zName); boolean hasDirection = node.contains(dxName) || node.contains(dyName) || node.contains(dzName); World baseWorld = location == null ? null : location.getWorld(); World worldOverride = overrideWorld(controller, node, basePath + "world", baseWorld, canCreateWorlds); if (!hasPosition && !hasDirection && worldOverride == null) return null; if (location == null) { if (worldOverride == null) return null; location = new Location(worldOverride, 0, 0, 0); } else { location = location.clone(); if (worldOverride != null) { location.setWorld(worldOverride); } } if (hasPosition) { location.setX(overrideDouble(node, location.getX(), xName)); location.setY(overrideDouble(node, location.getY(), yName)); location.setZ(overrideDouble(node, location.getZ(), zName)); } if (hasDirection) { Vector direction = location.getDirection(); direction.setX(overrideDouble(node, direction.getX(), dxName)); direction.setY(overrideDouble(node, direction.getY(), dyName)); direction.setZ(overrideDouble(node, direction.getZ(), dzName)); location.setDirection(direction); } return location; } public static Color getColor(ConfigurationSection node, String path, Color def) { Color o = toColor(node.get(path)); return o == null ? def : o; } @Nullable public static Color toColor(Object o) { if (o == null) { return null; } else if (o instanceof Byte) { return Color.fromRGB((Byte) o); } else if (o instanceof Integer) { return Color.fromRGB((Integer) o); } else if (o instanceof Double) { return Color.fromRGB((int) (double) (Double) o); } else if (o instanceof Float) { return Color.fromRGB((int) (float) (Float) o); } else if (o instanceof Long) { return Color.fromRGB((int) (long) (Long) o); } else if (o instanceof String) { try { String s = (String)o; if (s.length() == 0) return null; if (s.charAt(0) == '#') { s = s.substring(1); } if (s.startsWith("rand")) { return Color.fromRGB(random.nextInt(16777216)); } int rgb = Integer.parseInt(s, 16); return Color.fromRGB(rgb); } catch (NumberFormatException ex) { return null; } } else if (o instanceof ConfigurationSection) { ConfigurationSection config = (ConfigurationSection)o; ColorHD color = new ColorHD(config); return color.getColor(); } return null; } public static Integer getInteger(ConfigurationSection node, String path, Integer def) { if (node.contains(path)) { String strVal = node.getString(path); try { return parseInt(strVal); } catch (NumberFormatException ex) { Bukkit.getLogger().warning("Failed to parse as integer: " + strVal); } } return def; } public static Double getDouble(ConfigurationSection node, String path, Double def) { if (node.contains(path)) { String strVal = node.getString(path); try { return parseDouble(strVal); } catch (NumberFormatException ex) { Bukkit.getLogger().warning("Failed to parse as number: " + strVal); } } return def; } public static Boolean getBoolean(ConfigurationSection node, String path, Boolean def) { if (node.contains(path)) return node.getBoolean(path); return def; } public static void addIfNotEmpty(String message, Collection<String> list) { if (message != null && !message.isEmpty()) { list.add(message); } } /** * Gets a list of integers. Non-valid entries will not be in the list. * There will be no null slots. If the list is not defined, the * default will be returned. 'null' can be passed for the default * and an empty list will be returned instead. The node must be * an actual list and not just an integer. * * @param section the ConfigurationSection to load the list from * @param path path to node (dot notation) */ public static List<Integer> getIntegerList(ConfigurationSection section, String path) { List<Object> raw = getList(section, path); if (raw == null) { return new ArrayList<>(); } List<Integer> list = new ArrayList<>(); for (Object o : raw) { Integer i = castInt(o); if (i != null) { list.add(i); } } return list; } /** * Casts a value to an integer. May return null. * * @param o the object to cast * @return an Integer, or null on failure */ @Nullable private static Integer castInt(Object o) { if (o == null) { return null; } else if (o instanceof Byte) { return (int) (Byte) o; } else if (o instanceof Integer) { return (Integer) o; } else if (o instanceof Double) { return (int) (double) (Double) o; } else if (o instanceof Float) { return (int) (float) (Float) o; } else if (o instanceof Long) { return (int) (long) (Long) o; } else if (o instanceof String) { try { return Integer.parseInt((String)o); } catch (NumberFormatException ex) { return null; } } else { return null; } } @Nullable public static Boolean getOptionalBoolean(ConfigurationSection configuration, String key, Boolean def) { return configuration.contains(key) ? (Boolean)configuration.getBoolean(key) : def; } @Nullable public static Boolean getOptionalBoolean(ConfigurationSection configuration, String key) { return getOptionalBoolean(configuration, key, null); } @Nullable public static Integer getOptionalInteger(ConfigurationSection configuration, String key, Integer def) { return configuration.contains(key) ? (Integer)configuration.getInt(key) : def; } @Nullable public static Integer getOptionalInteger(ConfigurationSection configuration, String key) { return getOptionalInteger(configuration, key, null); } @Nullable public static Double getOptionalDouble(ConfigurationSection configuration, String key) { return configuration.contains(key) ? configuration.getDouble(key) : null; } @Nullable public static Float getOptionalFloat(ConfigurationSection configuration, String key) { return configuration.contains(key) ? (float)configuration.getDouble(key) : null; } // This is here to replace the more efficient but broken by 1.18 CompatibilityUtils.getMap @Nonnull public static Map<String, Object> toMap(ConfigurationSection section) { return toTypedMap(section); } @SuppressWarnings("unchecked") public static <T> Map<String, T> toTypedMap(ConfigurationSection section) { Map<String, T> map = new LinkedHashMap<>(); Set<String> keys = section.getKeys(false); for (String key : keys) { map.put(key, (T)section.get(key)); } return map; } }
/** * This class is generated by jOOQ */ package org.jooq.test.mariadb.generatedclasses.tables.records; /** * This class is generated by jOOQ. * * VIEW */ @java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class VLibraryRecord extends org.jooq.impl.TableRecordImpl<org.jooq.test.mariadb.generatedclasses.tables.records.VLibraryRecord> implements org.jooq.Record2<java.lang.String, java.lang.String> { private static final long serialVersionUID = 1382111444; /** * Setter for <code>test.v_library.AUTHOR</code>. */ public void setAuthor(java.lang.String value) { setValue(0, value); } /** * Getter for <code>test.v_library.AUTHOR</code>. */ public java.lang.String getAuthor() { return (java.lang.String) getValue(0); } /** * Setter for <code>test.v_library.TITLE</code>. The book's title */ public void setTitle(java.lang.String value) { setValue(1, value); } /** * Getter for <code>test.v_library.TITLE</code>. The book's title */ public java.lang.String getTitle() { return (java.lang.String) getValue(1); } // ------------------------------------------------------------------------- // Record2 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public org.jooq.Row2<java.lang.String, java.lang.String> fieldsRow() { return (org.jooq.Row2) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Row2<java.lang.String, java.lang.String> valuesRow() { return (org.jooq.Row2) super.valuesRow(); } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.String> field1() { return org.jooq.test.mariadb.generatedclasses.tables.VLibrary.AUTHOR; } /** * {@inheritDoc} */ @Override public org.jooq.Field<java.lang.String> field2() { return org.jooq.test.mariadb.generatedclasses.tables.VLibrary.TITLE; } /** * {@inheritDoc} */ @Override public java.lang.String value1() { return getAuthor(); } /** * {@inheritDoc} */ @Override public java.lang.String value2() { return getTitle(); } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached VLibraryRecord */ public VLibraryRecord() { super(org.jooq.test.mariadb.generatedclasses.tables.VLibrary.V_LIBRARY); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ode.bpel.engine; import org.apache.ode.bpel.bdi.breaks.ActivityBreakpoint; import org.apache.ode.bpel.bdi.breaks.Breakpoint; import org.apache.ode.bpel.bdi.breaks.VariableModificationBreakpoint; import org.apache.ode.bpel.common.CorrelationKey; import org.apache.ode.bpel.dao.*; import org.apache.ode.bpel.iapi.BpelServer; import org.apache.ode.bpel.iapi.ProcessStore; import org.apache.ode.bpel.pmapi.*; import org.apache.ode.bpel.pmapi.TInstanceInfo.EventInfo; import org.apache.ode.bpel.runtime.breaks.ActivityBreakpointImpl; import org.apache.ode.utils.DOMUtils; import org.apache.ode.utils.uuid.UUIDGen; import org.w3c.dom.Node; import javax.xml.namespace.QName; import java.util.*; /** * Implementation of the instance/process management interaction. This class implements * the methods necessary to support process debugging. It also implements all the methods in the * newer Process/Instance Management interface (pmapi). * * @author Maciej Szefler <mszefler at gmail dot com> */ public class BpelManagementFacadeImpl extends ProcessAndInstanceManagementImpl implements BpelManagementFacade { private static UUIDGen _uuidGen = new UUIDGen(); public BpelManagementFacadeImpl(BpelServer server, ProcessStore store) { super(server, store); } public short getState(final Long iid) throws ManagementException { return dbexec(new BpelDatabase.Callable<Short>() { public Short run(BpelDAOConnection session) throws Exception { ProcessInstanceDAO instance = session.getInstance(iid); return Short.valueOf(instance.getState()); } }).shortValue(); } public Long getProcessInstance(String pid, final CorrelationKey ckey) throws ManagementException { return dbexec(_db.getProcessDb(QName.valueOf(pid)).new Callable<Long>() { public Long run(BpelDAOConnection session) throws Exception { Iterator<ProcessInstanceDAO> i = getProcessDAO().findInstance(ckey).iterator(); return (i.hasNext()) ? i.next().getInstanceId() : null; } }); } public EventInfoListDocument getEvents(final Long iid, final int startIdx, final int count) throws ManagementException { // TODO: this is a bit of hack, if there are two events with exactly the // same timestamp, we can have more events returned then requested. List<String> timeline; try { timeline = getEventTimeline("iid="+iid,null); } catch (Exception ex) { throw new ManagementException("Unable to retrieve timeline.", ex); } if (startIdx >= timeline.size()) return EventInfoListDocument.Factory.newInstance(); timeline = timeline.subList(startIdx,Math.min(timeline.size(),startIdx+count)); String startdt = timeline.get(0); String enddt = timeline.get(timeline.size()-1); return listEvents("iid="+iid,"timestamp>="+startdt +" " +"timestamp<="+enddt,0); } public int getEventCount(final Long iid) throws ManagementException { EventInfo einfo = getInstanceInfo(iid).getInstanceInfo().getEventInfo(); if (einfo == null) return 0; return einfo.getCount(); } public String getVariable(final Long iid, final Long scopeId, final String varName) throws ManagementException { return dbexec(new BpelDatabase.Callable<String>() { public String run(BpelDAOConnection session) throws Exception { ProcessInstanceDAO instance = session.getInstance(iid); if (instance == null) { throw new ManagementException("InstanceNotFound:" + iid); } ScopeDAO scope = instance.getScope(scopeId); if (scope == null) { throw new ManagementException("ScopeNotFound:" + scopeId); } XmlDataDAO var = scope.getVariable(varName); if (var == null) { throw new ManagementException("VarNotFound:" + varName); } return nodeToString(var); } }); } public Long[] getScopeInstancesForScope(final Long iid, final String scopeName) throws ManagementException { return dbexec(new BpelDatabase.Callable<Long[]>() { public Long[] run(BpelDAOConnection session) throws Exception { ProcessInstanceDAO instance = session.getInstance(iid); if (instance == null) { throw new ManagementException("InstanceNotFound:" + iid); } Collection<ScopeDAO> scopes = instance.getScopes(scopeName); List<Long>instanceIds = new ArrayList<Long>(scopes.size()); for(ScopeDAO i : scopes) { instanceIds.add(i.getScopeInstanceId()); } return instanceIds.toArray(new Long[scopes.size()]); } }); } public void setVariable(Long pid, Long scopeId, String varName, String data) { throw new UnsupportedOperationException(); } public void setCorrelation(final Long iid, final Long scopeId, final String correlationSet, final QName[] propertyNames, final CorrelationKey values) throws ManagementException { dbexec(new BpelDatabase.Callable<Object>() { public Object run(BpelDAOConnection session) throws Exception { ProcessInstanceDAO instance = session.getInstance(iid); if (instance == null) { throw new ManagementException("InstanceNotFound:" + iid); } CorrelationSetDAO correlationSetDAO = instance.getCorrelationSet(correlationSet); correlationSetDAO.setValue(propertyNames, values); return null; } }); } public CorrelationKey getCorrelation(final Long iid, final Long scopeId, final String correlationSet) throws ManagementException { return dbexec(new BpelDatabase.Callable<CorrelationKey>() { public CorrelationKey run(BpelDAOConnection session) throws Exception { ProcessInstanceDAO instance = session.getInstance(iid); if (instance == null) { throw new ManagementException("InstanceNotFound:" + iid); } CorrelationSetDAO corr = findCorrelationSetDAO(instance, scopeId, correlationSet); return corr.getValue(); } }); } public void step(final Long iid) throws ManagementException { // We need debugger support in order to resume (since we have to force // a reduction. If one is not available the getDebugger() method should // throw a ProcessingException DebuggerSupport debugSupport = getDebugger(iid); assert debugSupport != null : "getDebugger(Long) returned NULL!"; debugSupport.step(iid); } public QName getCompletedFault(final Long iid) throws ManagementException { return dbexec(new BpelDatabase.Callable<QName>() { public QName run(BpelDAOConnection session) throws Exception { ProcessInstanceDAO instance = session.getInstance(iid); if (instance == null) throw new ManagementException("InstanceNotFound:" + iid); return instance.getFault().getName(); } }); } public Breakpoint[] getGlobalBreakpoints(String procId) throws ManagementException { DebuggerSupport debuggerSupport = getDebugger(QName.valueOf(procId)); return debuggerSupport.getGlobalBreakpoints(); } public Breakpoint[] getBreakpoints(Long iid) throws ManagementException { DebuggerSupport debuggerSupport = getDebugger(iid); return debuggerSupport.getBreakpoints(iid); } public void removeGlobalBreakpoint(String procid, Breakpoint sp) throws ManagementException { DebuggerSupport debuggerSupport = getDebugger(QName.valueOf(procid)); debuggerSupport.removeGlobalBreakpoint(sp); } public void removeBreakpoint(Long iid, Breakpoint sp) throws ManagementException { DebuggerSupport debuggerSupport = getDebugger(iid); debuggerSupport.removeBreakpoint(iid, sp); } public ActivityBreakpoint addGlobalActivityBreakpoint(String procid, String activity) throws ManagementException { DebuggerSupport debuggerSupport = getDebugger(QName.valueOf(procid)); ActivityBreakpointImpl bp = new ActivityBreakpointImpl(_uuidGen.nextUUID(), activity); debuggerSupport.addGlobalBreakpoint(bp); return bp; } public ActivityBreakpoint addActivityBreakpoint(Long iid, String activity) throws ManagementException { DebuggerSupport debuggerSupport = getDebugger(iid); ActivityBreakpointImpl bp = new ActivityBreakpointImpl(_uuidGen.nextUUID(), activity); debuggerSupport.addBreakpoint(iid, bp); return bp; } public VariableModificationBreakpoint addVariableModificationBreakpoint(Long iid, String scopename, String variable) { throw new UnsupportedOperationException(); } public Date getStartTime(final Long iid) throws ManagementException { return dbexec(new BpelDatabase.Callable<Date>() { public Date run(BpelDAOConnection session) throws Exception { ProcessInstanceDAO instance = session.getInstance(iid); if (instance == null) throw new InstanceNotFoundException("InstanceNotFound:" + iid); return instance.getCreateTime(); } }); } private CorrelationSetDAO findCorrelationSetDAO(ProcessInstanceDAO instance, Long scopeId, String correlationSet) throws ManagementException { ScopeDAO scope = instance.getScope(scopeId); CorrelationSetDAO corr = null; do { corr = scope.getCorrelationSet(correlationSet); if(corr != null) break; scope = scope.getParentScope(); } while(scope != null); if(corr == null) throw new ManagementException("CorrelationSetNotFound:" + correlationSet); return corr; } private static String nodeToString(XmlDataDAO xml){ Node data = xml.get(); String str; if (data == null) { str = null; } else if (data.getNodeType() == Node.ELEMENT_NODE) { str = DOMUtils.domToString(data); } else { str = data.getNodeValue(); } return str; } }
/* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis; /* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.hisp.dhis.actions.LoginActions; import org.hisp.dhis.helpers.TestCleanUp; import org.hisp.dhis.helpers.extensions.ConfigurationExtension; import org.hisp.dhis.helpers.extensions.MetadataSetupExtension; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; /** * @author Gintare Vilkelyte <vilkelyte.gintare@gmail.com> */ @TestInstance( TestInstance.Lifecycle.PER_CLASS ) @ExtendWith( ConfigurationExtension.class ) @ExtendWith( MetadataSetupExtension.class ) public abstract class ApiTest { @AfterAll public void afterAll() { new LoginActions().loginAsDefaultUser(); new TestCleanUp().deleteCreatedEntities(); } }
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.transport.http.netty.http2.ssl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.transport.http.netty.contentaware.listeners.EchoMessageListener; import org.wso2.transport.http.netty.contract.HttpClientConnector; import org.wso2.transport.http.netty.contract.HttpWsConnectorFactory; import org.wso2.transport.http.netty.contract.ServerConnector; import org.wso2.transport.http.netty.contract.ServerConnectorFuture; import org.wso2.transport.http.netty.contract.config.SenderConfiguration; import org.wso2.transport.http.netty.contract.exceptions.ServerConnectorException; import org.wso2.transport.http.netty.contractimpl.DefaultHttpWsConnectorFactory; import org.wso2.transport.http.netty.util.TestUtil; import java.util.HashMap; import static org.wso2.transport.http.netty.contract.Constants.HTTPS_SCHEME; import static org.wso2.transport.http.netty.contract.Constants.HTTP_2_0; import static org.wso2.transport.http.netty.util.Http2Util.getH2ListenerConfigs; /** * Tests the behavior of HTTP2 client with disabled SSL. */ public class DisableSslTest { private static final Logger LOG = LoggerFactory.getLogger(DisableSslTest.class); private ServerConnector serverConnector; private HttpClientConnector http2ClientConnector; private HttpWsConnectorFactory connectorFactory; @BeforeClass public void setup() throws InterruptedException { HttpWsConnectorFactory factory = new DefaultHttpWsConnectorFactory(); serverConnector = factory .createServerConnector(TestUtil.getDefaultServerBootstrapConfig(), getH2ListenerConfigs()); ServerConnectorFuture future = serverConnector.start(); future.setHttpConnectorListener(new EchoMessageListener()); future.sync(); connectorFactory = new DefaultHttpWsConnectorFactory(); http2ClientConnector = connectorFactory .createHttpClientConnector(new HashMap<>(), getSenderConfigs()); } public static SenderConfiguration getSenderConfigs() { SenderConfiguration senderConfiguration = new SenderConfiguration(); senderConfiguration.disableSsl(); senderConfiguration.setHttpVersion(HTTP_2_0); senderConfiguration.setScheme(HTTPS_SCHEME); return senderConfiguration; } /** * This test case will test the functionality of disabling SSL in HTTP2 client and ALPN negotiation with 'h2'. */ @Test public void testHttp2Post() { TestUtil.testHttpsPost(http2ClientConnector, TestUtil.SERVER_PORT1); } @AfterClass public void cleanUp() throws ServerConnectorException { http2ClientConnector.close(); serverConnector.stop(); try { connectorFactory.shutdown(); } catch (InterruptedException e) { LOG.error("Interrupted while waiting for HttpWsFactory to shutdown", e); } } }
/* * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.codecentric.boot.admin.server.notify; import java.net.URI; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; import org.springframework.context.expression.MapAccessor; import org.springframework.expression.Expression; import org.springframework.expression.ParserContext; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.web.client.RestTemplate; import reactor.core.publisher.Mono; import de.codecentric.boot.admin.server.domain.entities.Instance; import de.codecentric.boot.admin.server.domain.entities.InstanceRepository; import de.codecentric.boot.admin.server.domain.events.InstanceEvent; import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent; import de.codecentric.boot.admin.server.domain.values.StatusInfo; /** * Notifier submitting events to opsgenie.com. * * @author Fernando Sure */ public class OpsGenieNotifier extends AbstractStatusChangeNotifier { private static final URI DEFAULT_URI = URI.create("https://api.opsgenie.com/v2/alerts"); private static final String DEFAULT_MESSAGE = "#{instance.registration.name}/#{instance.id} is #{instance.statusInfo.status}"; private final SpelExpressionParser parser = new SpelExpressionParser(); private RestTemplate restTemplate; /** * BASE URL for OpsGenie API */ private URI url = DEFAULT_URI; /** * Integration ApiKey */ @Nullable private String apiKey; /** * Comma separated list of actions that can be executed. */ @Nullable private String actions; /** * Field to specify source of alert. By default, it will be assigned to IP address of * incoming request */ @Nullable private String source; /** * Comma separated list of labels attached to the alert */ @Nullable private String tags; /** * The entity the alert is related to. */ @Nullable private String entity; /** * Default owner of the execution. If user is not specified, the system becomes owner * of the execution. */ @Nullable private String user; /** * Trigger description. SpEL template using event as root; */ private Expression description; public OpsGenieNotifier(InstanceRepository repository, RestTemplate restTemplate) { super(repository); this.restTemplate = restTemplate; this.description = parser.parseExpression(DEFAULT_MESSAGE, ParserContext.TEMPLATE_EXPRESSION); } @Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { return Mono.fromRunnable(() -> restTemplate.exchange(buildUrl(event, instance), HttpMethod.POST, createRequest(event, instance), Void.class)); } protected String buildUrl(InstanceEvent event, Instance instance) { if ((event instanceof InstanceStatusChangedEvent) && (StatusInfo.STATUS_UP.equals(((InstanceStatusChangedEvent) event).getStatusInfo().getStatus()))) { return String.format("%s/%s/close", url.toString(), generateAlias(instance)); } return url.toString(); } protected HttpEntity<?> createRequest(InstanceEvent event, Instance instance) { Map<String, Object> body = new HashMap<>(); if (user != null) { body.put("user", user); } if (source != null) { body.put("source", source); } if (event instanceof InstanceStatusChangedEvent && !StatusInfo.STATUS_UP.equals(((InstanceStatusChangedEvent) event).getStatusInfo().getStatus())) { body.put("message", getMessage(event, instance)); body.put("alias", generateAlias(instance)); body.put("description", getDescription(event, instance)); if (actions != null) { body.put("actions", actions); } if (tags != null) { body.put("tags", tags); } if (entity != null) { body.put("entity", entity); } Map<String, Object> details = new HashMap<>(); details.put("type", "link"); details.put("href", instance.getRegistration().getHealthUrl()); details.put("text", "Instance health-endpoint"); body.put("details", details); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set(HttpHeaders.AUTHORIZATION, "GenieKey " + apiKey); return new HttpEntity<>(body, headers); } protected String generateAlias(Instance instance) { return instance.getRegistration().getName() + "_" + instance.getId(); } @Nullable protected String getMessage(InstanceEvent event, Instance instance) { Map<String, Object> root = new HashMap<>(); root.put("event", event); root.put("instance", instance); root.put("lastStatus", getLastStatus(event.getInstance())); StandardEvaluationContext context = new StandardEvaluationContext(root); context.addPropertyAccessor(new MapAccessor()); return description.getValue(context, String.class); } protected String getDescription(InstanceEvent event, Instance instance) { return String.format("Instance %s (%s) went from %s to %s", instance.getRegistration().getName(), instance.getId(), getLastStatus(instance.getId()), ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus()); } public void setApiKey(@Nullable String apiKey) { this.apiKey = apiKey; } @Nullable public String getApiKey() { return apiKey; } public void setDescription(String description) { this.description = parser.parseExpression(description, ParserContext.TEMPLATE_EXPRESSION); } public String getMessage() { return description.getExpressionString(); } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @Nullable public String getActions() { return actions; } public void setActions(@Nullable String actions) { this.actions = actions; } @Nullable public String getSource() { return source; } public void setSource(@Nullable String source) { this.source = source; } @Nullable public String getTags() { return tags; } public void setTags(@Nullable String tags) { this.tags = tags; } @Nullable public String getEntity() { return entity; } public void setEntity(@Nullable String entity) { this.entity = entity; } @Nullable public String getUser() { return user; } public void setUser(@Nullable String user) { this.user = user; } public URI getUrl() { return url; } public void setUrl(URI url) { this.url = url; } }
package mage.cards.l; import java.util.UUID; import mage.abilities.Ability; import mage.abilities.common.SimpleActivatedAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.common.SacrificeTargetCost; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.AttachEffect; import mage.abilities.effects.common.continuous.BoostEnchantedEffect; import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect; import mage.abilities.effects.common.continuous.GainAbilitySourceEffect; import mage.abilities.keyword.EnchantAbility; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.AttachmentType; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.Zone; import mage.target.TargetPermanent; import mage.target.common.TargetControlledPermanent; import mage.target.common.TargetCreaturePermanent; /** * * @author LevelX2 */ public final class LunarchMantle extends CardImpl { static final String rule = "and has \"{1}, Sacrifice a permanent: This creature gains flying until end of turn.\""; public LunarchMantle(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{1}{W}"); this.subtype.add(SubType.AURA); // Enchant creature TargetPermanent auraTarget = new TargetCreaturePermanent(); this.getSpellAbility().addTarget(auraTarget); this.getSpellAbility().addEffect(new AttachEffect(Outcome.BoostCreature)); Ability ability = new EnchantAbility(auraTarget.getTargetName()); this.addAbility(ability); // Enchanted creature gets +2/+2 and has "{1}, Sacrifice a permanent: This creature gains flying until end of turn." SimpleStaticAbility ability2 = new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostEnchantedEffect(2, 2, Duration.WhileOnBattlefield)); Ability abilityToGain = new SimpleActivatedAbility(Zone.BATTLEFIELD, new GainAbilitySourceEffect(FlyingAbility.getInstance(), Duration.EndOfTurn), new ManaCostsImpl("{1}")); abilityToGain.addCost(new SacrificeTargetCost(new TargetControlledPermanent())); ability2.addEffect(new GainAbilityAttachedEffect(abilityToGain, AttachmentType.AURA, Duration.WhileOnBattlefield, rule)); this.addAbility(ability2); } private LunarchMantle(final LunarchMantle card) { super(card); } @Override public LunarchMantle copy() { return new LunarchMantle(this); } }
package com.railone.open.api.util; import com.railone.open.api.enums.CharsetEnum; import org.apache.commons.lang3.StringUtils; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.management.RuntimeErrorException; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Set; import java.util.TreeMap; public class HmacUtil { public static Mac MAC; private static String algorithm = "HmacSHA256"; static { try { MAC = Mac.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new RuntimeErrorException(new Error("Can't get Mac's instance.")); } } public static String sign(String timestamp, String action, TreeMap<String, Object> body, String secretKey) throws Exception { if (StringUtils.isEmpty(secretKey) || StringUtils.isEmpty(action)) { throw new Exception("secretKey error"); } String preHash = preHash(timestamp, action, body); System.out.println("origin sign data:{}" + preHash); byte[] secretKeyBytes = secretKey.getBytes(CharsetEnum.UTF_8.charset()); SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyBytes, algorithm); Mac mac = (Mac) MAC.clone(); mac.init(secretKeySpec); return Base64.getEncoder().encodeToString(mac.doFinal(preHash.getBytes(CharsetEnum.UTF_8.charset()))); } public static String preHash(String timestamp, String method, TreeMap<String, Object> body) throws UnsupportedEncodingException { StringBuilder preHash = new StringBuilder(); preHash.append(timestamp); preHash.append(method.toUpperCase()); if (body != null && body.size() > 0) { preHash.append(appendBody(body)); } return preHash.toString(); } public static String appendBody(TreeMap<String, Object> params) { StringBuilder str = new StringBuilder(""); Set<String> setKey = params.keySet(); for (String key : setKey) { str.append(key).append("=").append(String.valueOf(params.get(key))).append("&"); } String strBody = str.toString(); if (!StringUtils.isEmpty(strBody)) { //删除最后一个拼接符 strBody = strBody.substring(0, strBody.length() - 1); } return strBody; } }
package cn.geekhall.controller; import cn.geekhall.bean.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * UserController.java * * @author yiny */ @Controller @RequestMapping("/user") public class UserController { // http://localhost:8080/springmvc_04_controller/user/t1?username=%E6%9E%81%E5%AE%A2%E5%A0%82 @GetMapping("/t1") public String test1(@RequestParam("username") String name, Model model){ // 1. 接收前端参数 System.out.println("接收的前端参数:" + name); // 2. 将返回的结果传递给前端, Model model.addAttribute("msg", name); // 3。 视图跳转 return "test"; } // http://localhost:8080/springmvc_04_controller/user/t2?id=1&name=King&age=18 // 接收一个对象: id, name, age @GetMapping("/t2") public String test2(User user){ System.out.println(user); return "test"; } /** * ModelMap 继承了LinkedHashMap,所以它拥有LinkedHashMap的全部功能, * LinkedHashMap继承自HashMap,同时还维护了一个双向链表。 * @param modelMap * @return */ @GetMapping("/t3") public String test3(ModelMap modelMap){ return "jsontest"; } }
package cn.izern.case4.encryption; import cn.izern.case4.encryption.Digest.DigestAlgorithm; import cn.izern.case4.encryption.codec.HexCoder; import org.junit.Test; /** * 各种摘要算法 * * @author: zern * @since 1.0.0 */ public class DigestTest { @Test public void digest() { DigestAlgorithm[] digestAlgorithmValues = DigestAlgorithm.values(); for (DigestAlgorithm digestAlgorithm : digestAlgorithmValues) { System.out.println(Digest.digest("hello zern", digestAlgorithm, HexCoder.INSTANCE)); } } }
/* * Copyright 2013-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.aws.core.io.s3; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.AmazonS3URI; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.ConcurrentHashMap; /** * {@link AmazonS3} client factory that create clients for other regions based on the source client and a endpoint url. * Caches clients per region to enable re-use on a region base. * * @author Agim Emruli * @since 1.2 */ public class AmazonS3ClientFactory { private static final String CREDENTIALS_PROVIDER_FIELD_NAME = "awsCredentialsProvider"; private final ConcurrentHashMap<String, AmazonS3> clientCache = new ConcurrentHashMap<>(Regions.values().length); private final Field credentialsProviderField; public AmazonS3ClientFactory() { this.credentialsProviderField = ReflectionUtils.findField(AmazonS3Client.class, CREDENTIALS_PROVIDER_FIELD_NAME); Assert.notNull(this.credentialsProviderField, "Credentials Provider field not found, this class does not work with the current " + "AWS SDK release"); ReflectionUtils.makeAccessible(this.credentialsProviderField); } public AmazonS3 createClientForEndpointUrl(AmazonS3 prototype, String endpointUrl) { Assert.notNull(prototype, "AmazonS3 must not be null"); Assert.notNull(endpointUrl, "Endpoint Url must not be null"); String region = getRegion(endpointUrl); Assert.notNull(region, "Error detecting region from endpoint url:'" + endpointUrl + "'"); if (!this.clientCache.containsKey(region)) { AmazonS3ClientBuilder amazonS3ClientBuilder = buildAmazonS3ForRegion(prototype, region); this.clientCache.putIfAbsent(region, amazonS3ClientBuilder.build()); } return this.clientCache.get(region); } private static String getRegion(String endpointUrl) { Assert.notNull(endpointUrl, "Endpoint Url must not be null"); try { URI uri = new URI(endpointUrl); if ("s3.amazonaws.com".equals(uri.getHost())) { return Regions.DEFAULT_REGION.getName(); } else { return new AmazonS3URI(endpointUrl).getRegion(); } } catch (URISyntaxException e) { throw new RuntimeException("Malformed URL received for endpoint", e); } } private AmazonS3ClientBuilder buildAmazonS3ForRegion(AmazonS3 prototype, String region) { AmazonS3ClientBuilder clientBuilder = AmazonS3ClientBuilder.standard(); AmazonS3Client target = getAmazonS3ClientFromProxy(prototype); if (target != null) { AWSCredentialsProvider awsCredentialsProvider = (AWSCredentialsProvider) ReflectionUtils.getField(this.credentialsProviderField, target); clientBuilder.withCredentials(awsCredentialsProvider); } return clientBuilder.withRegion(region); } private static AmazonS3Client getAmazonS3ClientFromProxy(AmazonS3 amazonS3) { if (AopUtils.isAopProxy(amazonS3)) { Advised advised = (Advised) amazonS3; Object target = null; try { target = advised.getTargetSource().getTarget(); } catch (Exception e) { return null; } return target instanceof AmazonS3Client ? (AmazonS3Client) target : null; } else { return amazonS3 instanceof AmazonS3Client ? (AmazonS3Client) amazonS3 : null; } } }
package com.jjjzzzqqq.rpc.server; import com.ticknet.jjjzzzqqq.entity.RpcRequest; import com.ticknet.jjjzzzqqq.entity.RpcResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.Socket; /** * 实际进行过程调用的工作线程 * @author jjjzzzqqq */ public class WorkerThread implements Runnable { private static final Logger logger = LoggerFactory.getLogger(WorkerThread.class); private Socket socket; private Object service; public WorkerThread(Socket socket, Object service) { this.socket = socket; this.service = service; } @Override public void run() { try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) { //从socket输入流获取RpcRequest对象 RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject(); //根据接口名和方法名和方法参数动态调用服务实现类方法 Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes()); Object returnObject = method.invoke(service, rpcRequest.getParameters()); //通过socket输出流返回RpcResponse对象 objectOutputStream.writeObject(RpcResponse.success(returnObject)); objectOutputStream.flush(); } catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { logger.error("调用或发送时有错误发生:", e); } } }
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.web.util; import java.lang.reflect.InvocationTargetException; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Test cases for {@link ThrowableAnalyzer}. * * @author Andreas Senft */ @SuppressWarnings("unchecked") public class ThrowableAnalyzerTests { /** * An array of nested throwables for testing. The cause of element 0 is element 1, the * cause of element 1 is element 2 and so on. */ private Throwable[] testTrace; /** * Plain <code>ThrowableAnalyzer</code>. */ private ThrowableAnalyzer standardAnalyzer; /** * Enhanced <code>ThrowableAnalyzer</code> capable to process * <code>NonStandardException</code>s. */ private ThrowableAnalyzer nonstandardAnalyzer; @Before public void setUp() { // Set up test trace this.testTrace = new Throwable[7]; this.testTrace[6] = new IllegalArgumentException("Test_6"); this.testTrace[5] = new Throwable("Test_5", this.testTrace[6]); this.testTrace[4] = new InvocationTargetException(this.testTrace[5], "Test_4"); this.testTrace[3] = new Exception("Test_3", this.testTrace[4]); this.testTrace[2] = new NonStandardException("Test_2", this.testTrace[3]); this.testTrace[1] = new RuntimeException("Test_1", this.testTrace[2]); this.testTrace[0] = new Exception("Test_0", this.testTrace[1]); // Set up standard analyzer this.standardAnalyzer = new ThrowableAnalyzer(); // Set up nonstandard analyzer this.nonstandardAnalyzer = new ThrowableAnalyzer() { /** * @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap() */ @Override protected void initExtractorMap() { super.initExtractorMap(); // register extractor for NonStandardException registerExtractor(NonStandardException.class, new NonStandardExceptionCauseExtractor()); } }; } @Test public void testRegisterExtractorWithInvalidExtractor() { assertThatIllegalArgumentException().isThrownBy(() -> new ThrowableAnalyzer() { @Override protected void initExtractorMap() { // null is no valid extractor super.registerExtractor(Exception.class, null); } }); } @Test public void testGetRegisteredTypes() { Class[] registeredTypes = this.nonstandardAnalyzer.getRegisteredTypes(); for (int i = 0; i < registeredTypes.length; ++i) { Class clazz = registeredTypes[i]; // The most specific types have to occur first. for (int j = 0; j < i; ++j) { Class prevClazz = registeredTypes[j]; assertThat(prevClazz.isAssignableFrom(clazz)) .withFailMessage( "Unexpected order of registered classes: " + prevClazz + " is assignable from " + clazz) .isFalse(); } } } @Test public void testDetermineCauseChainWithNoExtractors() { ThrowableAnalyzer analyzer = new ThrowableAnalyzer() { /** * @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap() */ @Override protected void initExtractorMap() { // skip default initialization } }; assertThat(analyzer.getRegisteredTypes().length).withFailMessage("Unexpected number of registered types") .isZero(); Throwable t = this.testTrace[0]; Throwable[] chain = analyzer.determineCauseChain(t); // Without extractors only the root throwable is available assertThat(chain.length).as("Unexpected chain size").isEqualTo(1); assertThat(chain[0]).as("Unexpected chain entry").isEqualTo(t); } @Test public void testDetermineCauseChainWithDefaultExtractors() { ThrowableAnalyzer analyzer = this.standardAnalyzer; assertThat(analyzer.getRegisteredTypes().length).withFailMessage("Unexpected number of registered types") .isEqualTo(2); Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); // Element at index 2 is a NonStandardException which cannot be analyzed further // by default assertThat(chain.length).as("Unexpected chain size").isEqualTo(3); for (int i = 0; i < 3; ++i) { assertThat(chain[i]).withFailMessage("Unexpected chain entry: " + i).isEqualTo(this.testTrace[i]); } } @Test public void testDetermineCauseChainWithCustomExtractors() { ThrowableAnalyzer analyzer = this.nonstandardAnalyzer; Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); assertThat(chain.length).as("Unexpected chain size").isEqualTo(this.testTrace.length); for (int i = 0; i < chain.length; ++i) { assertThat(chain[i]).withFailMessage("Unexpected chain entry: " + i).isEqualTo(this.testTrace[i]); } } @Test public void testGetFirstThrowableOfTypeWithSuccess1() { ThrowableAnalyzer analyzer = this.nonstandardAnalyzer; Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); Throwable result = analyzer.getFirstThrowableOfType(Exception.class, chain); assertThat(result).as("null not expected").isNotNull(); assertThat(result).as("Unexpected throwable found").isEqualTo(this.testTrace[0]); } @Test public void testGetFirstThrowableOfTypeWithSuccess2() { ThrowableAnalyzer analyzer = this.nonstandardAnalyzer; Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); Throwable result = analyzer.getFirstThrowableOfType(NonStandardException.class, chain); assertThat(result).as("null not expected").isNotNull(); assertThat(result).as("Unexpected throwable found").isEqualTo(this.testTrace[2]); } @Test public void testGetFirstThrowableOfTypeWithFailure() { ThrowableAnalyzer analyzer = this.nonstandardAnalyzer; Throwable[] chain = analyzer.determineCauseChain(this.testTrace[0]); // IllegalStateException not in trace Throwable result = analyzer.getFirstThrowableOfType(IllegalStateException.class, chain); assertThat(result).as("null expected").isNull(); } @Test public void testVerifyThrowableHierarchyWithExactType() { Throwable throwable = new IllegalStateException("Test"); ThrowableAnalyzer.verifyThrowableHierarchy(throwable, IllegalStateException.class); // No exception expected } @Test public void testVerifyThrowableHierarchyWithCompatibleType() { Throwable throwable = new IllegalStateException("Test"); ThrowableAnalyzer.verifyThrowableHierarchy(throwable, Exception.class); // No exception expected } @Test public void testVerifyThrowableHierarchyWithNull() { assertThatIllegalArgumentException() .isThrownBy(() -> ThrowableAnalyzer.verifyThrowableHierarchy(null, Throwable.class)); } @Test public void testVerifyThrowableHierarchyWithNonmatchingType() { Throwable throwable = new IllegalStateException("Test"); assertThatIllegalArgumentException().isThrownBy( () -> ThrowableAnalyzer.verifyThrowableHierarchy(throwable, InvocationTargetException.class)); } /** * Exception for testing purposes. The cause is not retrievable by * {@link #getCause()}. */ public static final class NonStandardException extends Exception { private final Throwable cause; public NonStandardException(String message, Throwable cause) { super(message); this.cause = cause; } public Throwable resolveCause() { return this.cause; } } /** * <code>ThrowableCauseExtractor</code> for handling <code>NonStandardException</code> * instances. */ public static final class NonStandardExceptionCauseExtractor implements ThrowableCauseExtractor { @Override public Throwable extractCause(Throwable throwable) { ThrowableAnalyzer.verifyThrowableHierarchy(throwable, NonStandardException.class); return ((NonStandardException) throwable).resolveCause(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.qpid.protonj2.codec.decoders; import org.apache.qpid.protonj2.codec.DecodeException; import org.apache.qpid.protonj2.codec.DescribedTypeDecoder; import org.apache.qpid.protonj2.codec.StreamDescribedTypeDecoder; import org.apache.qpid.protonj2.codec.StreamTypeDecoder; import org.apache.qpid.protonj2.codec.TypeDecoder; /** * Abstract base for all Described Type decoders which implements the generic methods * common to all the implementations. * * @param <V> The type that this decoder handles. */ public abstract class AbstractDescribedTypeDecoder<V> implements DescribedTypeDecoder<V>, StreamDescribedTypeDecoder<V> { @Override public boolean isArrayType() { return false; } @Override public String toString() { return "DescribedTypeDecoder<" + getTypeClass().getSimpleName() + ">"; } @SuppressWarnings("unchecked") protected static <E> E checkIsExpectedTypeAndCast(Class<?> expected, TypeDecoder<?> actual) throws DecodeException { if (!expected.isAssignableFrom(actual.getClass())) { throw new DecodeException( "Expected " + expected + "encoding but got decoder for type: " + actual.getTypeClass().getName()); } return (E) expected.cast(actual); } @SuppressWarnings("unchecked") protected static <E> E checkIsExpectedTypeAndCast(Class<?> expected, StreamTypeDecoder<?> actual) throws DecodeException { if (!expected.isAssignableFrom(actual.getClass())) { throw new DecodeException( "Expected " + expected + "encoding but got decoder for type: " + actual.getTypeClass().getName()); } return (E) expected.cast(actual); } protected static void checkIsExpectedType(Class<?> expected, TypeDecoder<?> actual) throws DecodeException { if (!expected.isAssignableFrom(actual.getClass())) { throw new DecodeException( "Expected " + expected + "encoding but got decoder for type: " + actual.getTypeClass().getName()); } } protected static void checkIsExpectedType(Class<?> expected, StreamTypeDecoder<?> actual) throws DecodeException { if (!expected.isAssignableFrom(actual.getClass())) { throw new DecodeException( "Expected " + expected + "encoding but got decoder for type: " + actual.getTypeClass().getName()); } } }
/* * Copyright (C) 2020 Alberto Irurueta Carro (alberto@irurueta.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irurueta.navigation.inertial.calibration.accelerometer; import com.irurueta.algebra.AlgebraException; import com.irurueta.algebra.Matrix; import com.irurueta.algebra.WrongSizeException; import com.irurueta.navigation.LockedException; import com.irurueta.navigation.NotReadyException; import com.irurueta.navigation.frames.ECEFFrame; import com.irurueta.navigation.inertial.BodyKinematics; import com.irurueta.navigation.inertial.INSLooselyCoupledKalmanInitializerConfig; import com.irurueta.navigation.inertial.INSTightlyCoupledKalmanInitializerConfig; import com.irurueta.navigation.inertial.calibration.AccelerationTriad; import com.irurueta.navigation.inertial.calibration.AccelerometerBiasUncertaintySource; import com.irurueta.navigation.inertial.calibration.AccelerometerCalibrationSource; import com.irurueta.navigation.inertial.calibration.CalibrationException; import com.irurueta.navigation.inertial.calibration.StandardDeviationFrameBodyKinematics; import com.irurueta.navigation.inertial.estimators.ECEFKinematicsEstimator; import com.irurueta.numerical.fitting.FittingException; import com.irurueta.numerical.fitting.LevenbergMarquardtMultiVariateFitter; import com.irurueta.numerical.fitting.LevenbergMarquardtMultiVariateFunctionEvaluator; import com.irurueta.units.Acceleration; import com.irurueta.units.AccelerationConverter; import com.irurueta.units.AccelerationUnit; import java.util.Collection; /** * Estimates accelerometer biases, cross couplings and scaling factors. * <p> * This calibrator uses an iterative approach to find a minimum least squared error * solution. * <p> * To use this calibrator at least 4 measurements at different known frames must * be provided. In other words, accelerometer samples must be obtained at 4 * different positions, orientations and velocities (although typically velocities are * always zero). * <p> * Measured specific force is assumed to follow the model shown below: * <pre> * fmeas = ba + (I + Ma) * ftrue + w * </pre> * Where: * - fmeas is the measured specific force. This is a 3x1 vector. * - ba is accelerometer bias. Ideally, on a perfect accelerometer, this should be a * 3x1 zero vector. * - I is the 3x3 identity matrix. * - Ma is the 3x3 matrix containing cross-couplings and scaling factors. Ideally, on * a perfect accelerometer, this should be a 3x3 zero matrix. * - ftrue is ground-truth specific force. * - w is measurement noise. */ public class KnownFrameAccelerometerNonLinearLeastSquaresCalibrator implements KnownFrameAccelerometerCalibrator<StandardDeviationFrameBodyKinematics, KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener>, AccelerometerNonLinearCalibrator, UnknownBiasNonLinearAccelerometerCalibrator, AccelerometerCalibrationSource, AccelerometerBiasUncertaintySource, UnorderedStandardDeviationFrameBodyKinematicsAccelerometerCalibrator { /** * Indicates whether by default a common z-axis is assumed for both the accelerometer * and gyroscope. */ public static final boolean DEFAULT_USE_COMMON_Z_AXIS = false; /** * Required minimum number of measurements. */ public static final int MINIMUM_MEASUREMENTS = 4; /** * Number of unknowns when common z-axis is assumed for both the accelerometer * and gyroscope. */ private static final int COMMON_Z_AXIS_UNKNOWNS = 9; /** * Number of unknowns for the general case. */ private static final int GENERAL_UNKNOWNS = 12; /** * Levenberg-Marquardt fitter to find a non-linear solution. */ private final LevenbergMarquardtMultiVariateFitter mFitter = new LevenbergMarquardtMultiVariateFitter(); /** * Initial x-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). */ private double mInitialBiasX; /** * Initial y-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). */ private double mInitialBiasY; /** * Initial z-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). */ private double mInitialBiasZ; /** * Initial x scaling factor. */ private double mInitialSx; /** * Initial y scaling factor. */ private double mInitialSy; /** * Initial z scaling factor. */ private double mInitialSz; /** * Initial x-y cross coupling error. */ private double mInitialMxy; /** * Initial x-z cross coupling error. */ private double mInitialMxz; /** * Initial y-x cross coupling error. */ private double mInitialMyx; /** * Initial y-z cross coupling error. */ private double mInitialMyz; /** * Initial z-x cross coupling error. */ private double mInitialMzx; /** * Initial z-y cross coupling error. */ private double mInitialMzy; /** * Contains a collection of body kinematics measurements taken at different * frames (positions, orientations and velocities) and containing the standard * deviations of accelerometer and gyroscope measurements. * If a single device IMU needs to be calibrated, typically all measurements are * taken at the same position, with zero velocity and multiple orientations. * However, if we just want to calibrate a given IMU model (e.g. obtain * an average and less precise calibration for the IMU of a given phone model), * we could take measurements collected throughout the planet at multiple positions * while the phone remains static (e.g. while charging), hence each measurement * position will change, velocity will remain zero and orientation will be * typically constant at horizontal orientation while the phone remains on a * flat surface. */ private Collection<? extends StandardDeviationFrameBodyKinematics> mMeasurements; /** * This flag indicates whether z-axis is assumed to be common for accelerometer * and gyroscope. * When enabled, this eliminates 3 variables from Ma matrix. */ private boolean mCommonAxisUsed = DEFAULT_USE_COMMON_Z_AXIS; /** * Listener to handle events raised by this calibrator. */ private KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener mListener; /** * Estimated accelerometer biases for each IMU axis expressed in meter per squared * second (m/s^2). */ private double[] mEstimatedBiases; /** * Estimated accelerometer scale factors and cross coupling errors. * This is the product of matrix Ta containing cross coupling errors and Ka * containing scaling factors. * So tat: * <pre> * Ma = [sx mxy mxz] = Ta*Ka * [myx sy myz] * [mzx mzy sz ] * </pre> * Where: * <pre> * Ka = [sx 0 0 ] * [0 sy 0 ] * [0 0 sz] * </pre> * and * <pre> * Ta = [1 -alphaXy alphaXz ] * [alphaYx 1 -alphaYz] * [-alphaZx alphaZy 1 ] * </pre> * Hence: * <pre> * Ma = [sx mxy mxz] = Ta*Ka = [sx -sy * alphaXy sz * alphaXz ] * [myx sy myz] [sx * alphaYx sy -sz * alphaYz] * [mzx mzy sz ] [-sx * alphaZx sy * alphaZy sz ] * </pre> * This instance allows any 3x3 matrix however, typically alphaYx, alphaZx and alphaZy * are considered to be zero if the accelerometer z-axis is assumed to be the same * as the body z-axis. When this is assumed, myx = mzx = mzy = 0 and the Ma matrix * becomes upper diagonal: * <pre> * Ma = [sx mxy mxz] * [0 sy myz] * [0 0 sz ] * </pre> * Values of this matrix are unit-less. */ private Matrix mEstimatedMa; /** * Estimated covariance matrix for estimated parameters. */ private Matrix mEstimatedCovariance; /** * Estimated chi square value. */ private double mEstimatedChiSq; /** * Estimated mean square error respect to provided measurements. */ private double mEstimatedMse; /** * Indicates whether calibrator is running. */ private boolean mRunning; /** * Constructor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator() { } /** * Constructor. * * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements) { mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed) { mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed) { this(measurements); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed); mListener = listener; } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final double initialBiasX, final double initialBiasY, final double initialBiasZ) { try { setInitialBias(initialBiasX, initialBiasY, initialBiasZ); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final double initialBiasX, final double initialBiasY, final double initialBiasZ, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(initialBiasX, initialBiasY, initialBiasZ); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final double initialBiasX, final double initialBiasY, final double initialBiasZ) { this(initialBiasX, initialBiasY, initialBiasZ); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBiasX, initialBiasY, initialBiasZ); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ) { this(initialBiasX, initialBiasY, initialBiasZ); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ); mListener = listener; } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ) { try { setInitialBias(initialBiasX, initialBiasY, initialBiasZ); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(initialBiasX, initialBiasY, initialBiasZ); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ) { this(initialBiasX, initialBiasY, initialBiasZ); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBiasX, initialBiasY, initialBiasZ); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ) { this(initialBiasX, initialBiasY, initialBiasZ); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ); mListener = listener; } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz) { this(initialBiasX, initialBiasY, initialBiasZ); try { setInitialScalingFactors(initialSx, initialSy, initialSz); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mListener = listener; } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz) { this(initialBiasX, initialBiasY, initialBiasZ); try { setInitialScalingFactors(initialSx, initialSy, initialSz); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz); mListener = listener; } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) { this(initialBiasX, initialBiasY, initialBiasZ); try { setInitialScalingFactorsAndCrossCouplingErrors(initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. This is expressed in meters per squared * second (m/s^2). * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final double initialBiasX, final double initialBiasY, final double initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mListener = listener; } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) { this(initialBiasX, initialBiasY, initialBiasZ); try { setInitialScalingFactorsAndCrossCouplingErrors(initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) { this(initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) { this(commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBiasX initial x-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasY initial y-coordinate of accelerometer bias to be used * to find a solution. * @param initialBiasZ initial z-coordinate of accelerometer bias to be used * to find a solution. * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @param listener listener to handle events raised by this calibrator. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ, final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBiasX, initialBiasY, initialBiasZ, initialSx, initialSy, initialSz, initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); mListener = listener; } /** * Constructor. * * @param initialBias initial accelerometer bias to be used to find a solution. * This must have length 3 and is expressed in meters per * squared second (m/s^2). * @throws IllegalArgumentException if provided bias array does not have length 3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final double[] initialBias) { try { setInitialBias(initialBias); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param initialBias initial accelerometer bias to be used to find a solution. * This must have length 3 and is expressed in meters per * squared second (m/s^2). * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if provided bias array does not have length 3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final double[] initialBias, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(initialBias); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBias initial accelerometer bias to be used to find a solution. * This must have length 3 and is expressed in meters per * squared second (m/s^2). * @throws IllegalArgumentException if provided bias array does not have length 3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final double[] initialBias) { this(initialBias); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBias initial accelerometer bias to be used to find a solution. * This must have length 3 and is expressed in meters per * squared second (m/s^2). * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if provided bias array does not have length 3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final double[] initialBias, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBias); mListener = listener; } /** * Constructor * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial accelerometer bias to be used to find a solution. * This must have length 3 and is expressed in meters per * squared second (m/s^2). * @throws IllegalArgumentException if provided bias array does not have length 3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final double[] initialBias) { this(initialBias); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial accelerometer bias to be used to find a solution. * This must have length 3 and is expressed in meters per * squared second (m/s^2). * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if provided bias array does not have length 3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final double[] initialBias, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBias); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial accelerometer bias to be used to find a solution. * This must have length 3 and is expressed in meters per * squared second (m/s^2). * @throws IllegalArgumentException if provided bias array does not have length 3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final double[] initialBias) { this(commonAxisUsed, initialBias); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial accelerometer bias to be used to find a solution. * This must have length 3 and is expressed in meters per * squared second (m/s^2). * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if provided bias array does not have length 3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final double[] initialBias, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBias); mListener = listener; } /** * Constructor. * * @param initialBias initial bias to find a solution. * @throws IllegalArgumentException if provided bias matrix is not 3x1. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Matrix initialBias) { try { setInitialBias(initialBias); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param initialBias initial bias to find a solution. * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if provided bias matrix is not 3x1. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Matrix initialBias, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(initialBias); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBias initial bias to find a solution. * @throws IllegalArgumentException if provided bias matrix is not 3x1. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Matrix initialBias) { this(initialBias); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBias initial bias to find a solution. * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if provided bias matrix is not 3x1. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Matrix initialBias, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBias); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial bias to find a solution. * @throws IllegalArgumentException if provided bias matrix is not 3x1. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Matrix initialBias) { this(initialBias); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial bias to find a solution. * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if provided bias matrix is not 3x1. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Matrix initialBias, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBias); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial bias to find a solution. * @throws IllegalArgumentException if provided bias matrix is not 3x1. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Matrix initialBias) { this(commonAxisUsed, initialBias); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial bias to find a solution. * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if provided bias matrix is not 3x1. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Matrix initialBias, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBias); mListener = listener; } /** * Constructor. * * @param initialBias initial bias to find a solution. * @param initialMa initial scale factors and cross coupling errors matrix. * @throws IllegalArgumentException if either provided bias matrix is not 3x1 or * scaling and coupling error matrix is not 3x3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Matrix initialBias, final Matrix initialMa) { this(initialBias); try { setInitialMa(initialMa); } catch (final LockedException ignore) { // never happens } } /** * Constructor. * * @param initialBias initial bias to find a solution. * @param initialMa initial scale factors and cross coupling errors matrix. * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if either provided bias matrix is not 3x1 or * scaling and coupling error matrix is not 3x3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Matrix initialBias, final Matrix initialMa, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(initialBias, initialMa); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBias initial bias to find a solution. * @param initialMa initial scale factors and cross coupling errors matrix. * @throws IllegalArgumentException if either provided bias matrix is not 3x1 or * scaling and coupling error matrix is not 3x3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Matrix initialBias, final Matrix initialMa) { this(initialBias, initialMa); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param initialBias initial bias to find a solution. * @param initialMa initial scale factors and cross coupling errors matrix. * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if either provided bias matrix is not 3x1 or * scaling and coupling error matrix is not 3x3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final Matrix initialBias, final Matrix initialMa, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, initialBias, initialMa); mListener = listener; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial bias to find a solution. * @param initialMa initial scale factors and cross coupling errors matrix. * @throws IllegalArgumentException if either provided bias matrix is not 3x1 or * scaling and coupling error matrix is not 3x3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Matrix initialBias, final Matrix initialMa) { this(initialBias, initialMa); mCommonAxisUsed = commonAxisUsed; } /** * Constructor. * * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial bias to find a solution. * @param initialMa initial scale factors and cross coupling errors matrix. * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if either provided bias matrix is not 3x1 or * scaling and coupling error matrix is not 3x3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final boolean commonAxisUsed, final Matrix initialBias, final Matrix initialMa, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(commonAxisUsed, initialBias, initialMa); mListener = listener; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial bias to find a solution. * @param initialMa initial scale factors and cross coupling errors matrix. * @throws IllegalArgumentException if either provided bias matrix is not 3x1 or * scaling and coupling error matrix is not 3x3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Matrix initialBias, final Matrix initialMa) { this(commonAxisUsed, initialBias, initialMa); mMeasurements = measurements; } /** * Constructor. * * @param measurements collection of body kinematics measurements with standard * deviations taken at different frames (positions, orientations * and velocities). * @param commonAxisUsed indicates whether z-axis is assumed to be common for * accelerometer and gyroscope. * @param initialBias initial bias to find a solution. * @param initialMa initial scale factors and cross coupling errors matrix. * @param listener listener to handle events raised by this calibrator. * @throws IllegalArgumentException if either provided bias matrix is not 3x1 or * scaling and coupling error matrix is not 3x3. */ public KnownFrameAccelerometerNonLinearLeastSquaresCalibrator( final Collection<StandardDeviationFrameBodyKinematics> measurements, final boolean commonAxisUsed, final Matrix initialBias, final Matrix initialMa, final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) { this(measurements, commonAxisUsed, initialBias, initialMa); mListener = listener; } /** * Gets initial x-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). * * @return initial x-coordinate of accelerometer bias. */ @Override public double getInitialBiasX() { return mInitialBiasX; } /** * Sets initial x-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). * * @param initialBiasX initial x-coordinate of accelerometer bias. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBiasX(final double initialBiasX) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasX = initialBiasX; } /** * Gets initial y-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). * * @return initial y-coordinate of accelerometer bias. */ @Override public double getInitialBiasY() { return mInitialBiasY; } /** * Sets initial y-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). * * @param initialBiasY initial y-coordinate of accelerometer bias. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBiasY(final double initialBiasY) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasY = initialBiasY; } /** * Gets initial z-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). * * @return initial z-coordinate of accelerometer bias. */ @Override public double getInitialBiasZ() { return mInitialBiasZ; } /** * Sets initial z-coordinate of accelerometer bias to be used to find a solution. * This is expressed in meters per squared second (m/s^2). * * @param initialBiasZ initial z-coordinate of accelerometer bias. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBiasZ(final double initialBiasZ) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasZ = initialBiasZ; } /** * Gets initial x-coordinate of accelerometer bias to be used to find a solution. * * @return initial x-coordinate of accelerometer bias. */ @Override public Acceleration getInitialBiasXAsAcceleration() { return new Acceleration(mInitialBiasX, AccelerationUnit.METERS_PER_SQUARED_SECOND); } /** * Gets initial x-coordinate of accelerometer bias to be used to find a solution. * * @param result instance where result data will be stored. */ @Override public void getInitialBiasXAsAcceleration(final Acceleration result) { result.setValue(mInitialBiasX); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); } /** * Sets initial x-coordinate of accelerometer bias to be used to find a solution. * * @param initialBiasX initial x-coordinate of accelerometer bias. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBiasX(final Acceleration initialBiasX) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasX = convertAcceleration(initialBiasX); } /** * Gets initial y-coordinate of accelerometer bias to be used to find a solution. * * @return initial y-coordinate of accelerometer bias. */ @Override public Acceleration getInitialBiasYAsAcceleration() { return new Acceleration(mInitialBiasY, AccelerationUnit.METERS_PER_SQUARED_SECOND); } /** * Gets initial y-coordinate of accelerometer bias to be used to find a solution. * * @param result instance where result data will be stored. */ @Override public void getInitialBiasYAsAcceleration(final Acceleration result) { result.setValue(mInitialBiasY); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); } /** * Sets initial y-coordinate of accelerometer bias to be used to find a solution. * * @param initialBiasY initial y-coordinate of accelerometer bias. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBiasY(final Acceleration initialBiasY) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasY = convertAcceleration(initialBiasY); } /** * Gets initial z-coordinate of accelerometer bias to be used to find a solution. * * @return initial z-coordinate of accelerometer bias. */ @Override public Acceleration getInitialBiasZAsAcceleration() { return new Acceleration(mInitialBiasZ, AccelerationUnit.METERS_PER_SQUARED_SECOND); } /** * Gets initial z-coordinate of accelerometer bias to be used to find a solution. * * @param result instance where result data will be stored. */ @Override public void getInitialBiasZAsAcceleration(final Acceleration result) { result.setValue(mInitialBiasZ); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); } /** * Sets initial z-coordinate of accelerometer bias to be used to find a solution. * * @param initialBiasZ initial z-coordinate of accelerometer bias. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBiasZ(final Acceleration initialBiasZ) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasZ = convertAcceleration(initialBiasZ); } /** * Sets initial bias coordinates of accelerometer used to find a solution * expressed in meters per squared second (m/s^2). * * @param initialBiasX initial x-coordinate of accelerometer bias. * @param initialBiasY initial y-coordinate of accelerometer bias. * @param initialBiasZ initial z-coordinate of accelerometer bias. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBias(final double initialBiasX, final double initialBiasY, final double initialBiasZ) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasX = initialBiasX; mInitialBiasY = initialBiasY; mInitialBiasZ = initialBiasZ; } /** * Sets initial bias coordinates of accelerometer used to find a solution. * * @param initialBiasX initial x-coordinate of accelerometer bias. * @param initialBiasY initial y-coordinate of accelerometer bias. * @param initialBiasZ initial z-coordinate of accelerometer bias. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBias(final Acceleration initialBiasX, final Acceleration initialBiasY, final Acceleration initialBiasZ) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasX = convertAcceleration(initialBiasX); mInitialBiasY = convertAcceleration(initialBiasY); mInitialBiasZ = convertAcceleration(initialBiasZ); } /** * Gets initial bias coordinates of accelerometer used to find a solution. * * @return initial bias coordinates. */ @Override public AccelerationTriad getInitialBiasAsTriad() { return new AccelerationTriad( AccelerationUnit.METERS_PER_SQUARED_SECOND, mInitialBiasX, mInitialBiasY, mInitialBiasZ); } /** * Gets initial bias coordinates of accelerometer used to find a solution. * * @param result instance where result will be stored. */ @Override public void getInitialBiasAsTriad(final AccelerationTriad result) { result.setValueCoordinatesAndUnit( mInitialBiasX, mInitialBiasY, mInitialBiasZ, AccelerationUnit.METERS_PER_SQUARED_SECOND); } /** * Sets initial bias coordinates of accelerometer used to find a solution. * * @param initialBias initial bias coordinates to be set. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialBias(final AccelerationTriad initialBias) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialBiasX = convertAcceleration( initialBias.getValueX(), initialBias.getUnit()); mInitialBiasY = convertAcceleration( initialBias.getValueY(), initialBias.getUnit()); mInitialBiasZ = convertAcceleration( initialBias.getValueZ(), initialBias.getUnit()); } /** * Gets initial x scaling factor. * * @return initial x scaling factor. */ @Override public double getInitialSx() { return mInitialSx; } /** * Sets initial x scaling factor. * * @param initialSx initial x scaling factor. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialSx(final double initialSx) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialSx = initialSx; } /** * Gets initial y scaling factor. * * @return initial y scaling factor. */ @Override public double getInitialSy() { return mInitialSy; } /** * Sets initial y scaling factor. * * @param initialSy initial y scaling factor. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialSy(final double initialSy) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialSy = initialSy; } /** * Gets initial z scaling factor. * * @return initial z scaling factor. */ @Override public double getInitialSz() { return mInitialSz; } /** * Sets initial z scaling factor. * * @param initialSz initial z scaling factor. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialSz(final double initialSz) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialSz = initialSz; } /** * Gets initial x-y cross coupling error. * * @return initial x-y cross coupling error. */ @Override public double getInitialMxy() { return mInitialMxy; } /** * Sets initial x-y cross coupling error. * * @param initialMxy initial x-y cross coupling error. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialMxy(final double initialMxy) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialMxy = initialMxy; } /** * Gets initial x-z cross coupling error. * * @return initial x-z cross coupling error. */ @Override public double getInitialMxz() { return mInitialMxz; } /** * Sets initial x-z cross coupling error. * * @param initialMxz initial x-z cross coupling error. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialMxz(final double initialMxz) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialMxz = initialMxz; } /** * Gets initial y-x cross coupling error. * * @return initial y-x cross coupling error. */ @Override public double getInitialMyx() { return mInitialMyx; } /** * Sets initial y-x cross coupling error. * * @param initialMyx initial y-x cross coupling error. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialMyx(final double initialMyx) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialMyx = initialMyx; } /** * Gets initial y-z cross coupling error. * * @return initial y-z cross coupling error. */ @Override public double getInitialMyz() { return mInitialMyz; } /** * Sets initial y-z cross coupling error. * * @param initialMyz initial y-z cross coupling error. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialMyz(final double initialMyz) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialMyz = initialMyz; } /** * Gets initial z-x cross coupling error. * * @return initial z-x cross coupling error. */ @Override public double getInitialMzx() { return mInitialMzx; } /** * Sets initial z-x cross coupling error. * * @param initialMzx initial z-x cross coupling error. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialMzx(final double initialMzx) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialMzx = initialMzx; } /** * Gets initial z-y cross coupling error. * * @return initial z-y cross coupling error. */ @Override public double getInitialMzy() { return mInitialMzy; } /** * Sets initial z-y cross coupling error. * * @param initialMzy initial z-y cross coupling error. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialMzy(final double initialMzy) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialMzy = initialMzy; } /** * Sets initial scaling factors. * * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialScalingFactors( final double initialSx, final double initialSy, final double initialSz) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialSx = initialSx; mInitialSy = initialSy; mInitialSz = initialSz; } /** * Sets initial cross coupling errors. * * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialCrossCouplingErrors( final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) throws LockedException { if (mRunning) { throw new LockedException(); } mInitialMxy = initialMxy; mInitialMxz = initialMxz; mInitialMyx = initialMyx; mInitialMyz = initialMyz; mInitialMzx = initialMzx; mInitialMzy = initialMzy; } /** * Sets initial scaling factors and cross coupling errors. * * @param initialSx initial x scaling factor. * @param initialSy initial y scaling factor. * @param initialSz initial z scaling factor. * @param initialMxy initial x-y cross coupling error. * @param initialMxz initial x-z cross coupling error. * @param initialMyx initial y-x cross coupling error. * @param initialMyz initial y-z cross coupling error. * @param initialMzx initial z-x cross coupling error. * @param initialMzy initial z-y cross coupling error. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialScalingFactorsAndCrossCouplingErrors( final double initialSx, final double initialSy, final double initialSz, final double initialMxy, final double initialMxz, final double initialMyx, final double initialMyz, final double initialMzx, final double initialMzy) throws LockedException { if (mRunning) { throw new LockedException(); } setInitialScalingFactors(initialSx, initialSy, initialSz); setInitialCrossCouplingErrors(initialMxy, initialMxz, initialMyx, initialMyz, initialMzx, initialMzy); } /** * Gets initial bias to be used to find a solution as an array. * Array values are expressed in meters per squared second (m/s^2). * * @return array containing coordinates of initial bias. */ @Override public double[] getInitialBias() { final double[] result = new double[BodyKinematics.COMPONENTS]; getInitialBias(result); return result; } /** * Gets initial bias to be used to find a solution as an array. * Array values are expressed in meters per squared second (m/s^2). * * @param result instance where result data will be copied to. * @throws IllegalArgumentException if provided array does not have length 3. */ @Override public void getInitialBias(final double[] result) { if (result.length != BodyKinematics.COMPONENTS) { throw new IllegalArgumentException(); } result[0] = mInitialBiasX; result[1] = mInitialBiasY; result[2] = mInitialBiasZ; } /** * Sets initial bias to be used to find a solution as an array. * Array values are expressed in meters per squared second (m/s^2). * * @param initialBias initial bias to find a solution. * @throws LockedException if calibrator is currently running. * @throws IllegalArgumentException if provided array does not have length 3. */ @Override public void setInitialBias(final double[] initialBias) throws LockedException { if (mRunning) { throw new LockedException(); } if (initialBias.length != BodyKinematics.COMPONENTS) { throw new IllegalArgumentException(); } mInitialBiasX = initialBias[0]; mInitialBiasY = initialBias[1]; mInitialBiasZ = initialBias[2]; } /** * Gets initial bias to be used to find a solution as a column matrix. * Values are expressed in meters per squared second (m/s^2). * * @return initial bias to be used to find a solution as a column matrix. */ @Override public Matrix getInitialBiasAsMatrix() { Matrix result; try { result = new Matrix(BodyKinematics.COMPONENTS, 1); getInitialBiasAsMatrix(result); } catch (final WrongSizeException ignore) { // never happens result = null; } return result; } /** * Gets initial bias to be used to find a solution as a column matrix. * Values are expressed in meters per squared second (m/s^2). * * @param result instance where result data will be copied to. * @throws IllegalArgumentException if provided matrix is not 3x1. */ @Override public void getInitialBiasAsMatrix(final Matrix result) { if (result.getRows() != BodyKinematics.COMPONENTS || result.getColumns() != 1) { throw new IllegalArgumentException(); } result.setElementAtIndex(0, mInitialBiasX); result.setElementAtIndex(1, mInitialBiasY); result.setElementAtIndex(2, mInitialBiasZ); } /** * Sets initial bias to be used to find a solution as a column matrix with * values expressed in meters per squared second (m/s^2). * * @param initialBias initial bias to find a solution. * @throws LockedException if calibrator is currently running. * @throws IllegalArgumentException if provided matrix is not 3x1. */ @Override public void setInitialBias(final Matrix initialBias) throws LockedException { if (mRunning) { throw new LockedException(); } if (initialBias.getRows() != BodyKinematics.COMPONENTS || initialBias.getColumns() != 1) { throw new IllegalArgumentException(); } mInitialBiasX = initialBias.getElementAtIndex(0); mInitialBiasY = initialBias.getElementAtIndex(1); mInitialBiasZ = initialBias.getElementAtIndex(2); } /** * Gets initial scale factors and cross coupling errors matrix. * * @return initial scale factors and cross coupling errors matrix. */ @Override public Matrix getInitialMa() { Matrix result; try { result = new Matrix(BodyKinematics.COMPONENTS, BodyKinematics.COMPONENTS); getInitialMa(result); } catch (final WrongSizeException ignore) { // never happens result = null; } return result; } /** * Gets initial scale factors and cross coupling errors matrix. * * @param result instance where data will be stored. * @throws IllegalArgumentException if provided matrix is not 3x3. */ @Override public void getInitialMa(final Matrix result) { if (result.getRows() != BodyKinematics.COMPONENTS || result.getColumns() != BodyKinematics.COMPONENTS) { throw new IllegalArgumentException(); } result.setElementAtIndex(0, mInitialSx); result.setElementAtIndex(1, mInitialMyx); result.setElementAtIndex(2, mInitialMzx); result.setElementAtIndex(3, mInitialMxy); result.setElementAtIndex(4, mInitialSy); result.setElementAtIndex(5, mInitialMzy); result.setElementAtIndex(6, mInitialMxz); result.setElementAtIndex(7, mInitialMyz); result.setElementAtIndex(8, mInitialSz); } /** * Sets initial scale factors and cross coupling errors matrix. * * @param initialMa initial scale factors and cross coupling errors matrix. * @throws IllegalArgumentException if provided matrix is not 3x3. * @throws LockedException if calibrator is currently running. */ @Override public void setInitialMa(final Matrix initialMa) throws LockedException { if (mRunning) { throw new LockedException(); } if (initialMa.getRows() != BodyKinematics.COMPONENTS || initialMa.getColumns() != BodyKinematics.COMPONENTS) { throw new IllegalArgumentException(); } mInitialSx = initialMa.getElementAtIndex(0); mInitialMyx = initialMa.getElementAtIndex(1); mInitialMzx = initialMa.getElementAtIndex(2); mInitialMxy = initialMa.getElementAtIndex(3); mInitialSy = initialMa.getElementAtIndex(4); mInitialMzy = initialMa.getElementAtIndex(5); mInitialMxz = initialMa.getElementAtIndex(6); mInitialMyz = initialMa.getElementAtIndex(7); mInitialSz = initialMa.getElementAtIndex(8); } /** * Gets a collection of body kinematics measurements taken at different * frames (positions, orientations and velocities) and containing the standard * deviations of accelerometer and gyroscope measurements. * If a single device IMU needs to be calibrated, typically all measurements are * taken at the same position, with zero velocity and multiple orientations. * However, if we just want to calibrate a given IMU model (e.g. obtain * an average and less precise calibration for the IMU of a given phone model), * we could take measurements collected throughout the planet at multiple positions * while the phone remains static (e.g. while charging), hence each measurement * position will change, velocity will remain zero and orientation will be * typically constant at horizontal orientation while the phone remains on a * flat surface. * * @return a collection of body kinematics measurements taken at different * frames (positions, orientations and velocities). */ @Override public Collection<? extends StandardDeviationFrameBodyKinematics> getMeasurements() { return mMeasurements; } /** * Sets a collection of body kinematics measurements taken at different * frames (positions, orientations and velocities) and containing the standard * deviations of accelerometer and gyroscope measurements. * If a single device IMU needs to be calibrated, typically all measurements are * taken at the same position, with zero velocity and multiple orientations. * However, if we just want to calibrate a given IMU model (e.g. obtain * an average and less precise calibration for the IMU of a given phone model), * we could take measurements collected throughout the planet at multiple positions * while the phone remains static (e.g. while charging), hence each measurement * position will change, velocity will remain zero and orientation will be * typically constant at horizontal orientation while the phone remains on a * flat surface. * * @param measurements collection of body kinematics measurements taken at different * frames (positions, orientations and velocities). * @throws LockedException if calibrator is currently running. */ @Override public void setMeasurements( final Collection<? extends StandardDeviationFrameBodyKinematics> measurements) throws LockedException { if (mRunning) { throw new LockedException(); } mMeasurements = measurements; } /** * Indicates the type of measurement used by this calibrator. * * @return type of measurement used by this calibrator. */ @Override public AccelerometerCalibratorMeasurementType getMeasurementType() { return AccelerometerCalibratorMeasurementType.STANDARD_DEVIATION_FRAME_BODY_KINEMATICS; } /** * Indicates whether this calibrator requires ordered measurements in a * list or not. * * @return true if measurements must be ordered, false otherwise. */ @Override public boolean isOrderedMeasurementsRequired() { return false; } /** * Indicates whether this calibrator requires quality scores for each * measurement or not. * * @return true if quality scores are required, false otherwise. */ @Override public boolean isQualityScoresRequired() { return false; } /** * Indicates whether z-axis is assumed to be common for accelerometer and * gyroscope. * When enabled, this eliminates 3 variables from Ma matrix. * * @return true if z-axis is assumed to be common for accelerometer and gyroscope, * false otherwise. */ @Override public boolean isCommonAxisUsed() { return mCommonAxisUsed; } /** * Specifies whether z-axis is assumed to be common for accelerometer and * gyroscope. * When enabled, this eliminates 3 variables from Ma matrix. * * @param commonAxisUsed true if z-axis is assumed to be common for accelerometer * and gyroscope, false otherwise. * @throws LockedException if calibrator is currently running. */ @Override public void setCommonAxisUsed(final boolean commonAxisUsed) throws LockedException { if (mRunning) { throw new LockedException(); } mCommonAxisUsed = commonAxisUsed; } /** * Gets listener to handle events raised by this estimator. * * @return listener to handle events raised by this estimator. */ @Override public KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener getListener() { return mListener; } /** * Sets listener to handle events raised by this estimator. * * @param listener listener to handle events raised by this estimator. * @throws LockedException if calibrator is currently running. */ @Override public void setListener( final KnownFrameAccelerometerNonLinearLeastSquaresCalibratorListener listener) throws LockedException { if (mRunning) { throw new LockedException(); } mListener = listener; } /** * Gets minimum number of required measurements. * * @return minimum number of required measurements. */ @Override public int getMinimumRequiredMeasurements() { return MINIMUM_MEASUREMENTS; } /** * Indicates whether calibrator is ready to start. * * @return true if calibrator is ready, false otherwise. */ @Override public boolean isReady() { return mMeasurements != null && mMeasurements.size() >= MINIMUM_MEASUREMENTS; } /** * Indicates whether calibrator is currently running or not. * * @return true if calibrator is running, false otherwise. */ @Override public boolean isRunning() { return mRunning; } /** * Estimates accelerometer calibration parameters containing bias, scale factors * and cross-coupling errors. * * @throws LockedException if calibrator is currently running. * @throws NotReadyException if calibrator is not ready. * @throws CalibrationException if estimation fails for numerical reasons. */ @Override public void calibrate() throws LockedException, NotReadyException, CalibrationException { if (mRunning) { throw new LockedException(); } if (!isReady()) { throw new NotReadyException(); } try { mRunning = true; if (mListener != null) { mListener.onCalibrateStart(this); } if (mCommonAxisUsed) { calibrateCommonAxis(); } else { calibrateGeneral(); } if (mListener != null) { mListener.onCalibrateEnd(this); } } catch (final AlgebraException | FittingException | com.irurueta.numerical.NotReadyException e) { throw new CalibrationException(e); } finally { mRunning = false; } } /** * Gets array containing x,y,z components of estimated accelerometer biases * expressed in meters per squared second (m/s^2). * * @return array containing x,y,z components of estimated accelerometer biases. */ @Override public double[] getEstimatedBiases() { return mEstimatedBiases; } /** * Gets array containing x,y,z components of estimated accelerometer biases * expressed in meters per squared second (m/s^2). * * @param result instance where estimated accelerometer biases will be stored. * @return true if result instance was updated, false otherwise (when estimation * is not yet available). */ @Override public boolean getEstimatedBiases(final double[] result) { if (mEstimatedBiases != null) { System.arraycopy(mEstimatedBiases, 0, result, 0, mEstimatedBiases.length); return true; } else { return false; } } /** * Gets column matrix containing x,y,z components of estimated accelerometer biases * expressed in meters per squared second (m/s^2). * * @return column matrix containing x,y,z components of estimated accelerometer * biases. */ @Override public Matrix getEstimatedBiasesAsMatrix() { return mEstimatedBiases != null ? Matrix.newFromArray(mEstimatedBiases) : null; } /** * Gets column matrix containing x,y,z components of estimated accelerometer biases * expressed in meters per squared second (m/s^2). * * @param result instance where result data will be stored. * @return true if result was updated, false otherwise. * @throws WrongSizeException if provided result instance has invalid size. */ @Override public boolean getEstimatedBiasesAsMatrix(final Matrix result) throws WrongSizeException { if (mEstimatedBiases != null) { result.fromArray(mEstimatedBiases); return true; } else { return false; } } /** * Gets x coordinate of estimated accelerometer bias expressed in meters per * squared second (m/s^2). * * @return x coordinate of estimated accelerometer bias or null if not available. */ @Override public Double getEstimatedBiasFx() { return mEstimatedBiases != null ? mEstimatedBiases[0] : null; } /** * Gets y coordinate of estimated accelerometer bias expressed in meters per * squared second (m/s^2). * * @return y coordinate of estimated accelerometer bias or null if not available. */ @Override public Double getEstimatedBiasFy() { return mEstimatedBiases != null ? mEstimatedBiases[1] : null; } /** * Gets z coordinate of estimated accelerometer bias expressed in meters per * squared second (m/s^2). * * @return z coordinate of estimated accelerometer bias or null if not available. */ @Override public Double getEstimatedBiasFz() { return mEstimatedBiases != null ? mEstimatedBiases[2] : null; } /** * Gets x coordinate of estimated accelerometer bias. * * @return x coordinate of estimated accelerometer bias or null if not available. */ @Override public Acceleration getEstimatedBiasFxAsAcceleration() { return mEstimatedBiases != null ? new Acceleration(mEstimatedBiases[0], AccelerationUnit.METERS_PER_SQUARED_SECOND) : null; } /** * Gets x coordinate of estimated accelerometer bias. * * @param result instance where result will be stored. * @return true if result was updated, false if estimation is not available. */ @Override public boolean getEstimatedBiasFxAsAcceleration(final Acceleration result) { if (mEstimatedBiases != null) { result.setValue(mEstimatedBiases[0]); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets y coordinate of estimated accelerometer bias. * * @return y coordinate of estimated accelerometer bias or null if not available. */ @Override public Acceleration getEstimatedBiasFyAsAcceleration() { return mEstimatedBiases != null ? new Acceleration(mEstimatedBiases[1], AccelerationUnit.METERS_PER_SQUARED_SECOND) : null; } /** * Gets y coordinate of estimated accelerometer bias. * * @param result instance where result will be stored. * @return true if result was updated, false if estimation is not available. */ @Override public boolean getEstimatedBiasFyAsAcceleration(final Acceleration result) { if (mEstimatedBiases != null) { result.setValue(mEstimatedBiases[1]); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets z coordinate of estimated accelerometer bias. * * @return z coordinate of estimated accelerometer bias or null if not available. */ @Override public Acceleration getEstimatedBiasFzAsAcceleration() { return mEstimatedBiases != null ? new Acceleration(mEstimatedBiases[2], AccelerationUnit.METERS_PER_SQUARED_SECOND) : null; } /** * Gets z coordinate of estimated accelerometer bias. * * @param result instance where result will be stored. * @return true if result was updated, false if estimation is not available. */ @Override public boolean getEstimatedBiasFzAsAcceleration(final Acceleration result) { if (mEstimatedBiases != null) { result.setValue(mEstimatedBiases[2]); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets estimated accelerometer bias. * * @return estimated accelerometer bias or null if not available. */ @Override public AccelerationTriad getEstimatedBiasAsTriad() { return mEstimatedBiases != null ? new AccelerationTriad(AccelerationUnit.METERS_PER_SQUARED_SECOND, mEstimatedBiases[0], mEstimatedBiases[1], mEstimatedBiases[2]) : null; } /** * Gets estimated accelerometer bias. * * @param result instance where result will be stored. * @return true if estimated accelerometer bias is available and result was * modified, false otherwise. */ @Override public boolean getEstimatedBiasAsTriad(final AccelerationTriad result) { if (mEstimatedBiases != null) { result.setValueCoordinatesAndUnit( mEstimatedBiases[0], mEstimatedBiases[1], mEstimatedBiases[2], AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets estimated accelerometer scale factors and ross coupling errors. * This is the product of matrix Ta containing cross coupling errors and Ka * containing scaling factors. * So tat: * <pre> * Ma = [sx mxy mxz] = Ta*Ka * [myx sy myz] * [mzx mzy sz ] * </pre> * Where: * <pre> * Ka = [sx 0 0 ] * [0 sy 0 ] * [0 0 sz] * </pre> * and * <pre> * Ta = [1 -alphaXy alphaXz ] * [alphaYx 1 -alphaYz] * [-alphaZx alphaZy 1 ] * </pre> * Hence: * <pre> * Ma = [sx mxy mxz] = Ta*Ka = [sx -sy * alphaXy sz * alphaXz ] * [myx sy myz] [sx * alphaYx sy -sz * alphaYz] * [mzx mzy sz ] [-sx * alphaZx sy * alphaZy sz ] * </pre> * This instance allows any 3x3 matrix however, typically alphaYx, alphaZx and alphaZy * are considered to be zero if the accelerometer z-axis is assumed to be the same * as the body z-axis. When this is assumed, myx = mzx = mzy = 0 and the Ma matrix * becomes upper diagonal: * <pre> * Ma = [sx mxy mxz] * [0 sy myz] * [0 0 sz ] * </pre> * Values of this matrix are unit-less. * * @return estimated accelerometer scale factors and cross coupling errors, or null * if not available. */ @Override public Matrix getEstimatedMa() { return mEstimatedMa; } /** * Gets estimated x-axis scale factor. * * @return estimated x-axis scale factor or null if not available. */ @Override public Double getEstimatedSx() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(0, 0) : null; } /** * Gets estimated y-axis scale factor. * * @return estimated y-axis scale factor or null if not available. */ @Override public Double getEstimatedSy() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(1, 1) : null; } /** * Gets estimated z-axis scale factor. * * @return estimated z-axis scale factor or null if not available. */ @Override public Double getEstimatedSz() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(2, 2) : null; } /** * Gets estimated x-y cross-coupling error. * * @return estimated x-y cross-coupling error or null if not available. */ @Override public Double getEstimatedMxy() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(0, 1) : null; } /** * Gets estimated x-z cross-coupling error. * * @return estimated x-z cross-coupling error or null if not available. */ @Override public Double getEstimatedMxz() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(0, 2) : null; } /** * Gets estimated y-x cross-coupling error. * * @return estimated y-x cross-coupling error or null if not available. */ @Override public Double getEstimatedMyx() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(1, 0) : null; } /** * Gets estimated y-z cross-coupling error. * * @return estimated y-z cross-coupling error or null if not available. */ @Override public Double getEstimatedMyz() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(1, 2) : null; } /** * Gets estimated z-x cross-coupling error. * * @return estimated z-x cross-coupling error or null if not available. */ @Override public Double getEstimatedMzx() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(2, 0) : null; } /** * Gets estimated z-y cross-coupling error. * * @return estimated z-y cross-coupling error or null if not available. */ @Override public Double getEstimatedMzy() { return mEstimatedMa != null ? mEstimatedMa.getElementAt(2, 1) : null; } /** * Gets estimated covariance matrix for estimated calibration parameters. * Diagonal elements of the matrix contains variance for the following * parameters (following indicated order): bx, by, bz, sx, sy, sz, * mxy, mxz, myx, myz, mzx, mzy. * * @return estimated covariance matrix for estimated calibration parameters. */ @Override public Matrix getEstimatedCovariance() { return mEstimatedCovariance; } /** * Gets estimated chi square value. * * @return estimated chi square value. */ @Override public double getEstimatedChiSq() { return mEstimatedChiSq; } /** * Gets estimated mean square error respect to provided measurements. * * @return estimated mean square error respect to provided measurements. */ @Override public double getEstimatedMse() { return mEstimatedMse; } /** * Gets variance of estimated x coordinate of accelerometer bias expressed in (m^2/s^4). * * @return variance of estimated x coordinate of accelerometer bias or null if not available. */ public Double getEstimatedBiasFxVariance() { return mEstimatedCovariance != null ? mEstimatedCovariance.getElementAt(0, 0) : null; } /** * Gets standard deviation of estimated x coordinate of accelerometer bias expressed in * meters per squared second (m/s^2). * * @return standard deviation of estimated x coordinate of accelerometer bias or null if not * available. */ public Double getEstimatedBiasFxStandardDeviation() { final Double variance = getEstimatedBiasFxVariance(); return variance != null ? Math.sqrt(variance) : null; } /** * Gets standard deviation of estimated x coordinate of accelerometer bias. * * @return standard deviation of estimated x coordinate of accelerometer bias or null if not * available. */ public Acceleration getEstimatedBiasFxStandardDeviationAsAcceleration() { return mEstimatedCovariance != null ? new Acceleration(getEstimatedBiasFxStandardDeviation(), AccelerationUnit.METERS_PER_SQUARED_SECOND) : null; } /** * Gets standard deviation of estimated x coordinate of accelerometer bias. * * @param result instance where result will be stored. * @return true if standard deviation of estimated x coordinate of accelerometer bias is available, * false otherwise. */ public boolean getEstimatedBiasFxStandardDeviationAsAcceleration(final Acceleration result) { if (mEstimatedCovariance != null) { result.setValue(getEstimatedBiasFxStandardDeviation()); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets variance of estimated y coordinate of accelerometer bias expressed in (m^2/s^4). * * @return variance of estimated y coordinate of accelerometer bias or null if not available. */ public Double getEstimatedBiasFyVariance() { return mEstimatedCovariance != null ? mEstimatedCovariance.getElementAt(1, 1) : null; } /** * Gets standard deviation of estimated y coordinate of accelerometer bias expressed in * meters per squared second (m/s^2). * * @return standard deviation of estimated y coordinate of accelerometer bias or null if not * available. */ public Double getEstimatedBiasFyStandardDeviation() { final Double variance = getEstimatedBiasFyVariance(); return variance != null ? Math.sqrt(variance) : null; } /** * Gets standard deviation of estimated y coordinate of accelerometer bias. * * @return standard deviation of estimated y coordinate of accelerometer bias or null if not * available. */ public Acceleration getEstimatedBiasFyStandardDeviationAsAcceleration() { return mEstimatedCovariance != null ? new Acceleration(getEstimatedBiasFyStandardDeviation(), AccelerationUnit.METERS_PER_SQUARED_SECOND) : null; } /** * Gets standard deviation of estimated y coordinate of accelerometer bias. * * @param result instance where result will be stored. * @return true if standard deviation of estimated y coordinate of accelerometer bias is available, * false otherwise. */ public boolean getEstimatedBiasFyStandardDeviationAsAcceleration(final Acceleration result) { if (mEstimatedCovariance != null) { result.setValue(getEstimatedBiasFyStandardDeviation()); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets variance of estimated z coordinate of accelerometer bias expressed in (m^2/s^4). * * @return variance of estimated z coordinate of accelerometer bias or null if not available. */ public Double getEstimatedBiasFzVariance() { return mEstimatedCovariance != null ? mEstimatedCovariance.getElementAt(2, 2) : null; } /** * Gets standard deviation of estimated z coordinate of accelerometer bias expressed in * meters per squared second (m/s^2). * * @return standard deviation of estimated z coordinate of accelerometer bias or null if not * available. */ public Double getEstimatedBiasFzStandardDeviation() { final Double variance = getEstimatedBiasFzVariance(); return variance != null ? Math.sqrt(variance) : null; } /** * Gets standard deviation of estimated z coordinate of accelerometer bias. * * @return standard deviation of estimated z coordinate of accelerometer bias or null if not * available. */ public Acceleration getEstimatedBiasFzStandardDeviationAsAcceleration() { return mEstimatedCovariance != null ? new Acceleration(getEstimatedBiasFzStandardDeviation(), AccelerationUnit.METERS_PER_SQUARED_SECOND) : null; } /** * Gets standard deviation of estimated z coordinate of accelerometer bias. * * @param result instance where result will be stored. * @return true if standard deviation of estimated z coordinate of accelerometer bias is available, * false otherwise. */ public boolean getEstimatedBiasFzStandardDeviationAsAcceleration(final Acceleration result) { if (mEstimatedCovariance != null) { result.setValue(getEstimatedBiasFzStandardDeviation()); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets standard deviation of estimated accelerometer bias coordinates. * * @return standard deviation of estimated accelerometer bias coordinates. */ public AccelerationTriad getEstimatedBiasStandardDeviation() { return mEstimatedCovariance != null ? new AccelerationTriad(AccelerationUnit.METERS_PER_SQUARED_SECOND, getEstimatedBiasFxStandardDeviation(), getEstimatedBiasFyStandardDeviation(), getEstimatedBiasFzStandardDeviation()) : null; } /** * Gets standard deviation of estimated accelerometer bias coordinates. * * @param result instance where result will be stored. * @return true if standard deviation of accelerometer bias was available, false * otherwise. */ public boolean getEstimatedBiasStandardDeviation(final AccelerationTriad result) { if (mEstimatedCovariance != null) { result.setValueCoordinatesAndUnit( getEstimatedBiasFxStandardDeviation(), getEstimatedBiasFyStandardDeviation(), getEstimatedBiasFzStandardDeviation(), AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets average of estimated standard deviation of accelerometer bias coordinates expressed * in meters per squared second (m/s^2). * * @return average of estimated standard deviation of accelerometer bias coordinates or null * if not available. */ public Double getEstimatedBiasStandardDeviationAverage() { return mEstimatedCovariance != null ? (getEstimatedBiasFxStandardDeviation() + getEstimatedBiasFyStandardDeviation() + getEstimatedBiasFzStandardDeviation()) / 3.0 : null; } /** * Gets average of estimated standard deviation of accelerometer bias coordinates. * * @return average of estimated standard deviation of accelerometer bias coordinates or null. */ public Acceleration getEstimatedBiasStandardDeviationAverageAsAcceleration() { return mEstimatedCovariance != null ? new Acceleration(getEstimatedBiasStandardDeviationAverage(), AccelerationUnit.METERS_PER_SQUARED_SECOND) : null; } /** * Gets average of estimated standard deviation of accelerometer bias coordinates. * * @param result instance where result will be stored. * @return true if average of estimated standard deviation of accelerometer bias is available, * false otherwise. */ public boolean getEstimatedBiasStandardDeviationAverageAsAcceleration(final Acceleration result) { if (mEstimatedCovariance != null) { result.setValue(getEstimatedBiasStandardDeviationAverage()); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Gets norm of estimated standard deviation of accelerometer bias expressed in * meters per squared second (m/s^2). * This can be used as the initial accelerometer bias uncertainty for * {@link INSLooselyCoupledKalmanInitializerConfig} or {@link INSTightlyCoupledKalmanInitializerConfig}. * * @return norm of estimated standard deviation of accelerometer bias or null * if not available. */ @Override public Double getEstimatedBiasStandardDeviationNorm() { return mEstimatedCovariance != null ? Math.sqrt(getEstimatedBiasFxVariance() + getEstimatedBiasFyVariance() + getEstimatedBiasFzVariance()) : null; } /** * Gets norm of estimated standard deviation of accelerometer bias. * This can be used as the initial accelerometer bias uncertainty for * {@link INSLooselyCoupledKalmanInitializerConfig} or {@link INSTightlyCoupledKalmanInitializerConfig}. * * @return norm of estimated standard deviation of accelerometer bias or null * if not available. */ public Acceleration getEstimatedBiasStandardDeviationNormAsAcceleration() { return mEstimatedCovariance != null ? new Acceleration(getEstimatedBiasStandardDeviationNorm(), AccelerationUnit.METERS_PER_SQUARED_SECOND) : null; } /** * Gets norm of estimated standard deviation of accelerometer bias coordinates. * This can be used as the initial accelerometer bias uncertainty for * {@link INSLooselyCoupledKalmanInitializerConfig} or {@link INSTightlyCoupledKalmanInitializerConfig}. * * @param result instance where result will be stored. * @return true if norm of estimated standard deviation of accelerometer bias is * available, false otherwise. */ public boolean getEstimatedBiasStandardDeviationNormAsAcceleration(final Acceleration result) { if (mEstimatedCovariance != null) { result.setValue(getEstimatedBiasStandardDeviationNorm()); result.setUnit(AccelerationUnit.METERS_PER_SQUARED_SECOND); return true; } else { return false; } } /** * Internal method to perform calibration when common z-axis is assumed for both * the accelerometer and gyroscope. * * @throws AlgebraException if there are numerical errors. * @throws FittingException if no convergence to solution is found. * @throws com.irurueta.numerical.NotReadyException if fitter is not ready. */ private void calibrateCommonAxis() throws AlgebraException, FittingException, com.irurueta.numerical.NotReadyException { // The accelerometer model is: // fmeas = ba + (I + Ma) * ftrue + w // Ideally a least squares solution tries to minimize noise component, so: // fmeas = ba + (I + Ma) * ftrue // Hence: // [fmeasx] = [bx] + ( [1 0 0] + [sx mxy mxz]) [ftruex] // [fmeasy] = [by] [0 1 0] [myx sy myz] [ftruey] // [fmeasz] = [bz] [0 0 1] [mzx mzy sz ] [ftruez] // where myx = mzx = mzy = 0 // Hence: // [fmeasx] = [bx] + ( [1 0 0] + [sx mxy mxz]) [ftruex] // [fmeasy] = [by] [0 1 0] [0 sy myz] [ftruey] // [fmeasz] = [bz] [0 0 1] [0 0 sz ] [ftruez] // [fmeasx] = [bx] + [1+sx mxy mxz ][ftruex] // [fmeasy] [by] [0 1+sy myz ][ftruey] // [fmeasz] [bz] [0 0 1+sz][ftruez] // fmeasx = bx + (1+sx) * ftruex + mxy * ftruey + mxz * ftruez // fmeasy = by + (1+sy) * ftruey + myz * ftruez // fmeasz = bz + (1+sz) * ftruez // Where the unknowns are: bx, by, bz, sx, sy, sz, mxy mxz, myz // Reordering: // fmeasx = bx + ftruex + sx * ftruex + mxy * ftruey + mxz * ftruez // fmeasy = by + ftruey + sy * ftruey + myz * ftruez // fmeasz = bz + ftruez + sz * ftruez // fmeasx - ftruex = bx + sx * ftruex + mxy * ftruey + mxz * ftruez // fmeasy - ftruey = by + sy * ftruey + myz * ftruez // fmeasz - ftruez = bz + sz * ftruez // [1 0 0 ftruex 0 0 ftruey ftruez 0 ][bx ] = [fmeasx - ftruex] // [0 1 0 0 ftruey 0 0 0 ftruez][by ] [fmeasy - ftruey] // [0 0 1 0 0 ftruez 0 0 0 ][bz ] [fmeasz - ftruez] // [sx ] // [sy ] // [sz ] // [mxy] // [mxz] // [myz] mFitter.setFunctionEvaluator(new LevenbergMarquardtMultiVariateFunctionEvaluator() { @Override public int getNumberOfDimensions() { // Input points are true specific force coordinates return BodyKinematics.COMPONENTS; } @Override public int getNumberOfVariables() { // The multivariate function returns the components of measured specific force return BodyKinematics.COMPONENTS; } @Override public double[] createInitialParametersArray() { final double[] initial = new double[COMMON_Z_AXIS_UNKNOWNS]; initial[0] = mInitialBiasX; initial[1] = mInitialBiasY; initial[2] = mInitialBiasZ; initial[3] = mInitialSx; initial[4] = mInitialSy; initial[5] = mInitialSz; initial[6] = mInitialMxy; initial[7] = mInitialMxz; initial[8] = mInitialMyz; return initial; } @Override public void evaluate( final int i, final double[] point, final double[] result, final double[] params, final Matrix jacobian) { // We know that: // fmeasx = bx + ftruex + sx * ftruex + mxy * ftruey + mxz * ftruez // fmeasy = by + ftruey + sy * ftruey + myz * ftruez // fmeasz = bz + ftruez + sz * ftruez // Hence, the derivatives respect the parameters bx, by, bz, sx, sy, // sz, mxy, mxz, myz // d(fmeasx)/d(bx) = 1.0 // d(fmeasx)/d(by) = 0.0 // d(fmeasx)/d(bz) = 0.0 // d(fmeasx)/d(sx) = ftruex // d(fmeasx)/d(sy) = 0.0 // d(fmeasx)/d(sz) = 0.0 // d(fmeasx)/d(mxy) = ftruey // d(fmeasx)/d(mxz) = ftruez // d(fmeasx)/d(myz) = 0.0 // d(fmeasy)/d(bx) = 0.0 // d(fmeasy)/d(by) = 1.0 // d(fmeasy)/d(bz) = 0.0 // d(fmeasy)/d(sx) = 0.0 // d(fmeasy)/d(sy) = ftruey // d(fmeasy)/d(sz) = 0.0 // d(fmeasy)/d(mxy) = 0.0 // d(fmeasy)/d(mxz) = 0.0 // d(fmeasy)/d(myz) = ftruez // d(fmeasz)/d(bx) = 0.0 // d(fmeasz)/d(by) = 0.0 // d(fmeasz)/d(bz) = 1.0 // d(fmeasz)/d(sx) = 0.0 // d(fmeasz)/d(sy) = 0.0 // d(fmeasz)/d(sz) = ftruez // d(fmeasz)/d(mxy) = 0.0 // d(fmeasz)/d(mxz) = 0.0 // d(fmeasz)/d(myz) = 0.0 final double bx = params[0]; final double by = params[1]; final double bz = params[2]; final double sx = params[3]; final double sy = params[4]; final double sz = params[5]; final double mxy = params[6]; final double mxz = params[7]; final double myz = params[8]; final double ftruex = point[0]; final double ftruey = point[1]; final double ftruez = point[2]; result[0] = bx + ftruex + sx * ftruex + mxy * ftruey + mxz * ftruez; result[1] = by + ftruey + sy * ftruey + myz * ftruez; result[2] = bz + ftruez + sz * ftruez; jacobian.setElementAt(0, 0, 1.0); jacobian.setElementAt(0, 1, 0.0); jacobian.setElementAt(0, 2, 0.0); jacobian.setElementAt(0, 3, ftruex); jacobian.setElementAt(0, 4, 0.0); jacobian.setElementAt(0, 5, 0.0); jacobian.setElementAt(0, 6, ftruey); jacobian.setElementAt(0, 7, ftruez); jacobian.setElementAt(0, 8, 0.0); jacobian.setElementAt(1, 0, 0.0); jacobian.setElementAt(1, 1, 1.0); jacobian.setElementAt(1, 2, 0.0); jacobian.setElementAt(1, 3, 0.0); jacobian.setElementAt(1, 4, ftruey); jacobian.setElementAt(1, 5, 0.0); jacobian.setElementAt(1, 6, 0.0); jacobian.setElementAt(1, 7, 0.0); jacobian.setElementAt(1, 8, ftruez); jacobian.setElementAt(2, 0, 0.0); jacobian.setElementAt(2, 1, 0.0); jacobian.setElementAt(2, 2, 1.0); jacobian.setElementAt(2, 3, 0.0); jacobian.setElementAt(2, 4, 0.0); jacobian.setElementAt(2, 5, ftruez); jacobian.setElementAt(2, 6, 0.0); jacobian.setElementAt(2, 7, 0.0); jacobian.setElementAt(2, 8, 0.0); } }); setInputData(); mFitter.fit(); final double[] result = mFitter.getA(); final double bx = result[0]; final double by = result[1]; final double bz = result[2]; final double sx = result[3]; final double sy = result[4]; final double sz = result[5]; final double mxy = result[6]; final double mxz = result[7]; final double myz = result[8]; if (mEstimatedBiases == null) { mEstimatedBiases = new double[BodyKinematics.COMPONENTS]; } mEstimatedBiases[0] = bx; mEstimatedBiases[1] = by; mEstimatedBiases[2] = bz; if (mEstimatedMa == null) { mEstimatedMa = new Matrix(BodyKinematics.COMPONENTS, BodyKinematics.COMPONENTS); } else { mEstimatedMa.initialize(0.0); } mEstimatedMa.setElementAt(0, 0, sx); mEstimatedMa.setElementAt(0, 1, mxy); mEstimatedMa.setElementAt(1, 1, sy); mEstimatedMa.setElementAt(0, 2, mxz); mEstimatedMa.setElementAt(1, 2, myz); mEstimatedMa.setElementAt(2, 2, sz); mEstimatedCovariance = mFitter.getCovar(); // propagate covariance matrix so that all parameters are taken into // account in the order: bx, by, bz, sx, sy, sz, mxy, mxz, myx, // myz, mzx, mzy. // We define a lineal function mapping original parameters for the common // axis case to the general case // [bx'] = [1 0 0 0 0 0 0 0 0][bx] // [by'] [0 1 0 0 0 0 0 0 0][by] // [bz'] [0 0 1 0 0 0 0 0 0][bz] // [sx'] [0 0 0 1 0 0 0 0 0][sx] // [sy'] [0 0 0 0 1 0 0 0 0][sy] // [sz'] [0 0 0 0 0 1 0 0 0][sz] // [mxy'] [0 0 0 0 0 0 1 0 0][mxy] // [mxz'] [0 0 0 0 0 0 0 1 0][mxz] // [myx'] [0 0 0 0 0 0 0 0 0][myz] // [myz'] [0 0 0 0 0 0 0 0 1] // [mzx'] [0 0 0 0 0 0 0 0 0] // [mzy'] [0 0 0 0 0 0 0 0 0] // As defined in com.irurueta.statistics.MultivariateNormalDist, // if we consider the jacobian of the lineal application the matrix shown // above, then covariance can be propagated as follows final Matrix jacobian = Matrix.identity(GENERAL_UNKNOWNS, COMMON_Z_AXIS_UNKNOWNS); jacobian.setElementAt(8, 8, 0.0); jacobian.setElementAt(9, 8, 1.0); // propagated covariance is J * Cov * J' final Matrix jacobianTrans = jacobian.transposeAndReturnNew(); jacobian.multiply(mEstimatedCovariance); jacobian.multiply(jacobianTrans); mEstimatedCovariance = jacobian; mEstimatedChiSq = mFitter.getChisq(); mEstimatedMse = mFitter.getMse(); } /** * Internal method to perform general calibration. * * @throws AlgebraException if there are numerical errors. * @throws FittingException if no convergence to solution is found. * @throws com.irurueta.numerical.NotReadyException if fitter is not ready. */ private void calibrateGeneral() throws AlgebraException, FittingException, com.irurueta.numerical.NotReadyException { // The accelerometer model is: // fmeas = ba + (I + Ma) * ftrue + w // Ideally a least squares solution tries to minimize noise component, so: // fmeas = ba + (I + Ma) * ftrue // Hence: // [fmeasx] = [bx] + ( [1 0 0] + [sx mxy mxz]) [ftruex] // [fmeasy] = [by] [0 1 0] [myx sy myz] [ftruey] // [fmeasz] = [bz] [0 0 1] [mzx mzy sz ] [ftruez] // [fmeasx] = [bx] + [1+sx mxy mxz ][ftruex] // [fmeasy] [by] [myx 1+sy myz ][ftruey] // [fmeasz] [bz] [mzx mzy 1+sz][ftruez] // fmeasx = bx + (1+sx) * ftruex + mxy * ftruey + mxz * ftruez // fmeasy = by + myx * ftruex + (1+sy) * ftruey + myz * ftruez // fmeasz = bz + mzx * ftruex + mzy * ftruey + (1+sz) * ftruez // Where the unknowns are: bx, by, bz, sx, sy, sz, mxy mxz, myx, myz, mzx, mzy // Reordering: // fmeasx = bx + ftruex + sx * ftruex + mxy * ftruey + mxz * ftruez // fmeasy = by + myx * ftruex + ftruey + sy * ftruey + myz * ftruez // fmeasz = bz + mzx * ftruex + mzy * ftruey + ftruez + sz * ftruez // fmeasx - ftruex = bx + sx * ftruex + mxy * ftruey + mxz * ftruez // fmeasy - ftruey = by + myx * ftruex + sy * ftruey + myz * ftruez // fmeasz - ftruez = bz + mzx * ftruex + mzy * ftruey + sz * ftruez // [1 0 0 ftruex 0 0 ftruey ftruez 0 0 0 0 ][bx ] = [fmeasx - ftruex] // [0 1 0 0 ftruey 0 0 0 ftruex ftruez 0 0 ][by ] [fmeasy - ftruey] // [0 0 1 0 0 ftruez 0 0 0 0 ftruex ftruey][bz ] [fmeasz - ftruez] // [sx ] // [sy ] // [sz ] // [mxy] // [mxz] // [myx] // [myz] // [mzx] // [mzy] mFitter.setFunctionEvaluator(new LevenbergMarquardtMultiVariateFunctionEvaluator() { @Override public int getNumberOfDimensions() { // Input points are true specific force coordinates return BodyKinematics.COMPONENTS; } @Override public int getNumberOfVariables() { // The multivariate function returns the components of measured specific force return BodyKinematics.COMPONENTS; } @Override public double[] createInitialParametersArray() { final double[] initial = new double[GENERAL_UNKNOWNS]; initial[0] = mInitialBiasX; initial[1] = mInitialBiasY; initial[2] = mInitialBiasZ; initial[3] = mInitialSx; initial[4] = mInitialSy; initial[5] = mInitialSz; initial[6] = mInitialMxy; initial[7] = mInitialMxz; initial[8] = mInitialMyx; initial[9] = mInitialMyz; initial[10] = mInitialMzx; initial[11] = mInitialMzy; return initial; } @Override public void evaluate(final int i, final double[] point, final double[] result, final double[] params, final Matrix jacobian) { // We know that: // fmeasx = bx + ftruex + sx * ftruex + mxy * ftruey + mxz * ftruez // fmeasy = by + myx * ftruex + ftruey + sy * ftruey + myz * ftruez // fmeasz = bz + mzx * ftruex + mzy * ftruey + ftruez + sz * ftruez // Hence, the derivatives respect the parameters bx, by, bz, sx, sy, // sz, mxy, mxz, myx, myz, mzx and mzy is: // d(fmeasx)/d(bx) = 1.0 // d(fmeasx)/d(by) = 0.0 // d(fmeasx)/d(bz) = 0.0 // d(fmeasx)/d(sx) = ftruex // d(fmeasx)/d(sy) = 0.0 // d(fmeasx)/d(sz) = 0.0 // d(fmeasx)/d(mxy) = ftruey // d(fmeasx)/d(mxz) = ftruez // d(fmeasx)/d(myx) = 0.0 // d(fmeasx)/d(myz) = 0.0 // d(fmeasx)/d(mzx) = 0.0 // d(fmeasx)/d(mzy) = 0.0 // d(fmeasy)/d(bx) = 0.0 // d(fmeasy)/d(by) = 1.0 // d(fmeasy)/d(bz) = 0.0 // d(fmeasy)/d(sx) = 0.0 // d(fmeasy)/d(sy) = ftruey // d(fmeasy)/d(sz) = 0.0 // d(fmeasy)/d(mxy) = 0.0 // d(fmeasy)/d(mxz) = 0.0 // d(fmeasy)/d(myx) = ftruex // d(fmeasy)/d(myz) = ftruez // d(fmeasy)/d(mzx) = 0.0 // d(fmeasy)/d(mzy) = 0.0 // d(fmeasz)/d(bx) = 0.0 // d(fmeasz)/d(by) = 0.0 // d(fmeasz)/d(bz) = 1.0 // d(fmeasz)/d(sx) = 0.0 // d(fmeasz)/d(sy) = 0.0 // d(fmeasz)/d(sz) = ftruez // d(fmeasz)/d(mxy) = 0.0 // d(fmeasz)/d(mxz) = 0.0 // d(fmeasz)/d(myx) = 0.0 // d(fmeasz)/d(myz) = 0.0 // d(fmeasz)/d(mzx) = ftruex // d(fmeasz)/d(mzy) = ftruey final double bx = params[0]; final double by = params[1]; final double bz = params[2]; final double sx = params[3]; final double sy = params[4]; final double sz = params[5]; final double mxy = params[6]; final double mxz = params[7]; final double myx = params[8]; final double myz = params[9]; final double mzx = params[10]; final double mzy = params[11]; final double ftruex = point[0]; final double ftruey = point[1]; final double ftruez = point[2]; result[0] = bx + ftruex + sx * ftruex + mxy * ftruey + mxz * ftruez; result[1] = by + myx * ftruex + ftruey + sy * ftruey + myz * ftruez; result[2] = bz + mzx * ftruex + mzy * ftruey + ftruez + sz * ftruez; jacobian.setElementAt(0, 0, 1.0); jacobian.setElementAt(0, 1, 0.0); jacobian.setElementAt(0, 2, 0.0); jacobian.setElementAt(0, 3, ftruex); jacobian.setElementAt(0, 4, 0.0); jacobian.setElementAt(0, 5, 0.0); jacobian.setElementAt(0, 6, ftruey); jacobian.setElementAt(0, 7, ftruez); jacobian.setElementAt(0, 8, 0.0); jacobian.setElementAt(0, 9, 0.0); jacobian.setElementAt(0, 10, 0.0); jacobian.setElementAt(0, 11, 0.0); jacobian.setElementAt(1, 0, 0.0); jacobian.setElementAt(1, 1, 1.0); jacobian.setElementAt(1, 2, 0.0); jacobian.setElementAt(1, 3, 0.0); jacobian.setElementAt(1, 4, ftruey); jacobian.setElementAt(1, 5, 0.0); jacobian.setElementAt(1, 6, 0.0); jacobian.setElementAt(1, 7, 0.0); jacobian.setElementAt(1, 8, ftruex); jacobian.setElementAt(1, 9, ftruez); jacobian.setElementAt(1, 10, 0.0); jacobian.setElementAt(1, 11, 0.0); jacobian.setElementAt(2, 0, 0.0); jacobian.setElementAt(2, 1, 0.0); jacobian.setElementAt(2, 2, 1.0); jacobian.setElementAt(2, 3, 0.0); jacobian.setElementAt(2, 4, 0.0); jacobian.setElementAt(2, 5, ftruez); jacobian.setElementAt(2, 6, 0.0); jacobian.setElementAt(2, 7, 0.0); jacobian.setElementAt(2, 8, 0.0); jacobian.setElementAt(2, 9, 0.0); jacobian.setElementAt(2, 10, ftruex); jacobian.setElementAt(2, 11, ftruey); } }); setInputData(); mFitter.fit(); final double[] result = mFitter.getA(); final double bx = result[0]; final double by = result[1]; final double bz = result[2]; final double sx = result[3]; final double sy = result[4]; final double sz = result[5]; final double mxy = result[6]; final double mxz = result[7]; final double myx = result[8]; final double myz = result[9]; final double mzx = result[10]; final double mzy = result[11]; if (mEstimatedBiases == null) { mEstimatedBiases = new double[BodyKinematics.COMPONENTS]; } mEstimatedBiases[0] = bx; mEstimatedBiases[1] = by; mEstimatedBiases[2] = bz; if (mEstimatedMa == null) { mEstimatedMa = new Matrix(BodyKinematics.COMPONENTS, BodyKinematics.COMPONENTS); } else { mEstimatedMa.initialize(0.0); } mEstimatedMa.setElementAt(0, 0, sx); mEstimatedMa.setElementAt(1, 0, myx); mEstimatedMa.setElementAt(2, 0, mzx); mEstimatedMa.setElementAt(0, 1, mxy); mEstimatedMa.setElementAt(1, 1, sy); mEstimatedMa.setElementAt(2, 1, mzy); mEstimatedMa.setElementAt(0, 2, mxz); mEstimatedMa.setElementAt(1, 2, myz); mEstimatedMa.setElementAt(2, 2, sz); mEstimatedCovariance = mFitter.getCovar(); mEstimatedChiSq = mFitter.getChisq(); mEstimatedMse = mFitter.getMse(); } /** * Sets input data into Levenberg-Marquardt fitter. * * @throws WrongSizeException never happens. */ private void setInputData() throws WrongSizeException { // set input data using: // fmeasx = bx + ftruex + sx * ftruex + mxy * ftruey + mxz * ftruez // fmeasy = by + myx * ftruex + ftruey + sy * ftruey + myz * ftruez // fmeasz = bz + mzx * ftruex + mzy * ftruey + ftruez + sz * ftruez final BodyKinematics expectedKinematics = new BodyKinematics(); final int numMeasurements = mMeasurements.size(); final Matrix x = new Matrix(numMeasurements, BodyKinematics.COMPONENTS); final Matrix y = new Matrix(numMeasurements, BodyKinematics.COMPONENTS); final double[] specificForceStandardDeviations = new double[numMeasurements]; int i = 0; for (final StandardDeviationFrameBodyKinematics measurement : mMeasurements) { final BodyKinematics measuredKinematics = measurement.getKinematics(); final ECEFFrame ecefFrame = measurement.getFrame(); final ECEFFrame previousEcefFrame = measurement.getPreviousFrame(); final double timeInterval = measurement.getTimeInterval(); ECEFKinematicsEstimator.estimateKinematics(timeInterval, ecefFrame, previousEcefFrame, expectedKinematics); final double fMeasX = measuredKinematics.getFx(); final double fMeasY = measuredKinematics.getFy(); final double fMeasZ = measuredKinematics.getFz(); final double fTrueX = expectedKinematics.getFx(); final double fTrueY = expectedKinematics.getFy(); final double fTrueZ = expectedKinematics.getFz(); x.setElementAt(i, 0, fTrueX); x.setElementAt(i, 1, fTrueY); x.setElementAt(i, 2, fTrueZ); y.setElementAt(i, 0, fMeasX); y.setElementAt(i, 1, fMeasY); y.setElementAt(i, 2, fMeasZ); specificForceStandardDeviations[i] = measurement.getSpecificForceStandardDeviation(); i++; } mFitter.setInputData(x, y, specificForceStandardDeviations); } /** * Converts acceleration value and unit to meters per squared second. * * @param value acceleration value. * @param unit unit of acceleration value. * @return converted value. */ private static double convertAcceleration(final double value, final AccelerationUnit unit) { return AccelerationConverter.convert(value, unit, AccelerationUnit.METERS_PER_SQUARED_SECOND); } /** * Converts acceleration instance to meters per squared second. * * @param acceleration acceleration instance to be converted. * @return converted value. */ private static double convertAcceleration(final Acceleration acceleration) { return convertAcceleration(acceleration.getValue().doubleValue(), acceleration.getUnit()); } }
/* * #%L * hspc-client * %% * Copyright (C) 2014 - 2015 Healthcare Services Platform Consortium * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.hspconsortium.client.auth.credentialsflow; import ca.uhn.fhir.context.FhirContext; import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSVerifier; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jwt.SignedJWT; import org.apache.commons.lang.StringUtils; import org.hspconsortium.client.auth.Scopes; import org.hspconsortium.client.auth.SimpleScope; import org.hspconsortium.client.auth.access.AccessToken; import org.hspconsortium.client.auth.access.AccessTokenProvider; import org.hspconsortium.client.auth.access.JsonAccessTokenProvider; import org.hspconsortium.client.auth.credentials.ClientSecretCredentials; import org.hspconsortium.client.auth.credentials.JWTCredentials; import org.hspconsortium.client.session.clientcredentials.ClientCredentialsAccessTokenRequest; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.text.ParseException; import java.util.Date; import java.util.UUID; @Ignore public class ClientCredentialsTokenRequestTest { private FhirContext hapiFhirContext = FhirContext.forDstu2(); @Test public void testClientCredentialsAccessTokenRequest() { Scopes requestedScopes = new Scopes(); requestedScopes .add(new SimpleScope("launch")) .add(new SimpleScope("patient/*.read")); ClientSecretCredentials clientSecretCredentials = new ClientSecretCredentials("secret"); ClientCredentialsAccessTokenRequest tokenRequest = new ClientCredentialsAccessTokenRequest("test_client", clientSecretCredentials, requestedScopes); AccessTokenProvider tokenProvider = new JsonAccessTokenProvider(hapiFhirContext); AccessToken accessToken = tokenProvider.getAccessToken("http://localhost:8080/hspc-reference-authorization/token", tokenRequest); Assert.assertNotNull(accessToken); Assert.assertTrue(StringUtils.isNotBlank(accessToken.getValue())); } @Test public void testClientJWTCredentialsAccessTokenRequest() { Scopes requestedScopes = new Scopes(); requestedScopes .add(new SimpleScope("launch")) .add(new SimpleScope("patient/*.read")); // RSA signatures require a public and private RSA key pair, the public key // must be made known to the JWS recipient in order to verify the signatures Class currentClass = new Object() { }.getClass().getEnclosingClass(); String fileName = currentClass.getClassLoader().getResource("openid-connect-jwks/development.only.keystore.jwks").getFile(); JWKSet jwks = null; try { jwks = JWKSet.load(new File(fileName)); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } RSAKey rsaKey = (RSAKey) jwks.getKeys().get(0); JWTCredentials jwtCredentials = null; try { jwtCredentials = new JWTCredentials(rsaKey.toRSAPrivateKey()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } jwtCredentials.setIssuer("test_client_jwt"); jwtCredentials.setSubject("test_client_jwt"); // final String tokenProviderUrl = "http://localhost:8080/hspc-reference-authorization/token"; final String tokenProviderUrl = "http://lpv-hdsvnev02.co.ihc.com:8080/hspc-reference-authorization/token"; jwtCredentials.setAudience("http://localhost:8080/hspc-reference-authorization/token"); jwtCredentials.setTokenReference(UUID.randomUUID().toString()); jwtCredentials.setDuration(300L); ClientCredentialsAccessTokenRequest<JWTCredentials> tokenRequest = new ClientCredentialsAccessTokenRequest("test_client_jwt", jwtCredentials, requestedScopes); AccessTokenProvider tokenProvider = new JsonAccessTokenProvider(hapiFhirContext); AccessToken accessToken = tokenProvider.getAccessToken(tokenProviderUrl, tokenRequest); Assert.assertNotNull(accessToken); Assert.assertTrue(StringUtils.isNotBlank(accessToken.getValue())); try { SignedJWT signedJWT = SignedJWT.parse(accessToken.getValue()); JWSVerifier verifier = new RSASSAVerifier(rsaKey.toRSAPublicKey()); Assert.assertTrue(signedJWT.verify(verifier)); // Retrieve / verify the JWT claims according to the app requirements Assert.assertEquals(jwtCredentials.getIssuer(), signedJWT.getJWTClaimsSet().getAudience().get(0)); Assert.assertTrue(new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())); } catch (ParseException | InvalidKeySpecException | NoSuchAlgorithmException | JOSEException e) { e.printStackTrace(); } } @Test public void testClientJWTCredentialsAccessTokenRequestBehindProxy() { Scopes requestedScopes = new Scopes(); requestedScopes .add(new SimpleScope("launch")) .add(new SimpleScope("offline_access")) .add(new SimpleScope("system/*.read")); // RSA signatures require a public and private RSA key pair, the public key // must be made known to the JWS recipient in order to verify the signatures Class currentClass = new Object() { }.getClass().getEnclosingClass(); String fileName = currentClass.getClassLoader().getResource("openid-connect-jwks/development.only.keystore.jwks").getFile(); JWKSet jwks = null; try { jwks = JWKSet.load(new File(fileName)); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } RSAKey rsaKey = (RSAKey) jwks.getKeys().get(0); JWTCredentials jwtCredentials = null; try { jwtCredentials = new JWTCredentials(rsaKey.toRSAPrivateKey()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } jwtCredentials.setIssuer("test_client_jwt"); jwtCredentials.setSubject("test_client_jwt"); final String tokenProviderUrl = "https://sandbox.hspconsortium.org/dstu2/hspc-reference-authorization/token"; // final String tokenProviderUrl = "http://lpv-hdsvnev02.co.ihc.com:8080/hspc-reference-authorization/token"; // jwtCredentials.setAudience(tokenProviderUrl); // jwtCredentials.setAudience("http://localhost:8080/hspc-reference-authorization/"); jwtCredentials.setAudience("https://sandbox.hspconsortium.org/dstu2/hspc-reference-authorization/token"); jwtCredentials.setTokenReference(UUID.randomUUID().toString()); jwtCredentials.setDuration(300L); ClientCredentialsAccessTokenRequest<JWTCredentials> tokenRequest = new ClientCredentialsAccessTokenRequest("test_client_jwt", jwtCredentials, requestedScopes); AccessTokenProvider tokenProvider = new JsonAccessTokenProvider(hapiFhirContext); AccessToken accessToken = tokenProvider.getAccessToken(tokenProviderUrl, tokenRequest); Assert.assertNotNull(accessToken); Assert.assertTrue(StringUtils.isNotBlank(accessToken.getValue())); try { SignedJWT signedJWT = SignedJWT.parse(accessToken.getValue()); JWSVerifier verifier = new RSASSAVerifier(rsaKey.toRSAPublicKey()); Assert.assertTrue(signedJWT.verify(verifier)); // Retrieve / verify the JWT claims according to the app requirements Assert.assertEquals(jwtCredentials.getIssuer(), signedJWT.getJWTClaimsSet().getAudience().get(0)); Assert.assertTrue(new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())); } catch (ParseException | InvalidKeySpecException | NoSuchAlgorithmException | JOSEException e) { e.printStackTrace(); } } }
/* * ARX: Powerful Data Anonymization * Copyright 2012 - 2020 Fabian Prasser and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.deidentifier.arx.gui.view.impl.wizard; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; import org.deidentifier.arx.DataType; import org.deidentifier.arx.DataType.DataTypeWithRatioScale; import org.deidentifier.arx.aggregates.AggregateFunction; import org.deidentifier.arx.aggregates.HierarchyBuilderGroupingBased.Group; import org.deidentifier.arx.aggregates.HierarchyBuilderGroupingBased.Level; import org.deidentifier.arx.aggregates.HierarchyBuilderIntervalBased; import org.deidentifier.arx.aggregates.HierarchyBuilderIntervalBased.Interval; import org.deidentifier.arx.aggregates.HierarchyBuilderOrderBased; import org.deidentifier.arx.gui.resources.Resources; import org.deidentifier.arx.gui.view.impl.wizard.HierarchyWizard.HierarchyWizardView; /** * A base-class for grouping-based builders, i.e., order-based and interval-based builders * @author Fabian Prasser * * @param <T> */ public abstract class HierarchyWizardModelGrouping<T> extends HierarchyWizardModelAbstract<T>{ /** * This class represents a group. * * @author Fabian Prasser * @param <U> */ public static class HierarchyWizardGroupingGroup<U> { /** Var. */ public int size; /** Var. */ public AggregateFunction<U> function; /** * * * @param group */ public HierarchyWizardGroupingGroup(Group<U> group) { this.size = group.getSize(); this.function = group.getFunction(); } /** * * * @param size * @param function */ public HierarchyWizardGroupingGroup(int size, AggregateFunction<U> function) { this.size = size; this.function = function; } } /** * This class represents an interval. * * @author Fabian Prasser * @param <U> */ public static class HierarchyWizardGroupingInterval<U> { /** Min */ public U min; /** Max */ public U max; /** Functio */ public AggregateFunction<U> function; /** * * * @param interval */ public HierarchyWizardGroupingInterval(Interval<U> interval) { this.min = interval.getMin(); this.max = interval.getMax(); this.function = interval.getFunction(); } /** * * * @param min * @param max * @param function */ public HierarchyWizardGroupingInterval(U min, U max, AggregateFunction<U> function) { this.min = min; this.max = max; this.function = function; } } /** * This class represents an adjustment. * * @author Fabian Prasser * @param <U> */ public static class HierarchyWizardGroupingRange<U> { /** Snap */ public U snapBound; /** Coding */ public U bottomTopCodingBound; /** Extreme */ public U minMaxBound; /** * * * @param type * @param lower */ @SuppressWarnings("unchecked") public HierarchyWizardGroupingRange(DataType<U> type, boolean lower){ DataTypeWithRatioScale<U> dtype = (DataTypeWithRatioScale<U>)type; if (lower){ this.snapBound = dtype.getMinimum(); this.bottomTopCodingBound = dtype.getMinimum(); this.minMaxBound = dtype.getMinimum(); } else { this.snapBound = dtype.getMaximum(); this.bottomTopCodingBound = dtype.getMaximum(); this.minMaxBound = dtype.getMaximum(); } } } /** Var. */ private List<HierarchyWizardGroupingInterval<T>> intervals = new ArrayList<HierarchyWizardGroupingInterval<T>>(); /** Var. */ private List<List<HierarchyWizardGroupingGroup<T>>> groups = new ArrayList<List<HierarchyWizardGroupingGroup<T>>>(); /** Var. */ private DataType<T> type; /** Var. */ private boolean showIntervals = true; /** Var. */ private AggregateFunction<T> function; /** Var. */ private HierarchyWizardGroupingRange<T> lower = null; /** Var. */ private HierarchyWizardGroupingRange<T> upper = null; /** Var. */ private Object selected = null; /** Var. */ private HierarchyWizardEditorRenderer<T> renderer = new HierarchyWizardEditorRenderer<T>(this); /** Var. */ private List<HierarchyWizardView> components = new ArrayList<HierarchyWizardView>(); /** * Creates a new instance. * * @param data * @param type * @param intervals */ @SuppressWarnings("unchecked") public HierarchyWizardModelGrouping(String[] data, DataType<T> type, boolean intervals){ super(data); this.type = type; this.showIntervals = intervals; if (intervals) { // Check if (!(type instanceof DataTypeWithRatioScale)) { throw new IllegalArgumentException(Resources.getMessage("HierarchyWizardModelGrouping.0")); //$NON-NLS-1$ } // Prepare DataTypeWithRatioScale<T> dtype = (DataTypeWithRatioScale<T>)type; this.lower = new HierarchyWizardGroupingRange<T>(type, true); this.upper = new HierarchyWizardGroupingRange<T>(type, false); this.function = AggregateFunction.forType(type).createIntervalFunction(true, false); // Initialize if (data != null){ T min = null; T max = null; for (String date : data) { T value = dtype.parse(date); if (value != null) { if (min==null || dtype.compare(value, min) < 0) min = value; if (max==null || dtype.compare(value, max) > 0) max = value; } } if (equals(type, DataType.INTEGER)) { max = dtype.add(max, (T)Long.valueOf(1l)); // Add 1 } else if (equals(type, DataType.DECIMAL)) { max = dtype.add(max, (T)Double.valueOf(1d)); // Add 1 } else if (equals(type, DataType.DATE)) { max = dtype.add(max, (T)new Date(3600l * 1000l)); // Add 1 day } this.lower.minMaxBound = min; this.lower.snapBound = min; this.lower.bottomTopCodingBound = min; this.upper.minMaxBound = max; this.upper.snapBound = max; this.upper.bottomTopCodingBound = max; this.intervals.add(new HierarchyWizardGroupingInterval<T>(min, max, this.function)); } else { this.intervals.add(new HierarchyWizardGroupingInterval<T>(dtype.getMinimum(), dtype.getMaximum(), this.function)); } } else { this.function = AggregateFunction.forType(type).createSetFunction(); this.groups.add(new ArrayList<HierarchyWizardGroupingGroup<T>>()); this.groups.get(0).add(new HierarchyWizardGroupingGroup<T>(1, this.function)); } this.update(); } /** * Adds an element after the given one. * * @param selected */ @SuppressWarnings("unchecked") public void addAfter(Object selected) { if (selected instanceof HierarchyWizardGroupingInterval){ int index= intervals.indexOf(selected); if (index != -1){ T bound = ((HierarchyWizardGroupingInterval<T>)selected).max; intervals.add(index + 1, new HierarchyWizardGroupingInterval<T>(bound, bound, this.function)); update(); return; } } else if (selected instanceof HierarchyWizardGroupingGroup){ for (List<HierarchyWizardGroupingGroup<T>> list : groups){ int index= list.indexOf(selected); if (index != -1){ list.add(index + 1, new HierarchyWizardGroupingGroup<T>(1, this.function)); update(); return; } } } } /** * Adds an element before the given one. * * @param selected */ @SuppressWarnings("unchecked") public void addBefore(Object selected) { if (selected instanceof HierarchyWizardGroupingInterval){ int index= intervals.indexOf(selected); if (index != -1){ T bound = ((HierarchyWizardGroupingInterval<T>)selected).min; intervals.add(index, new HierarchyWizardGroupingInterval<T>(bound, bound, this.function)); update(); return; } } else if (selected instanceof HierarchyWizardGroupingGroup){ for (List<HierarchyWizardGroupingGroup<T>> list : groups){ int index= list.indexOf(selected); if (index != -1){ list.add(index, new HierarchyWizardGroupingGroup<T>(1, this.function)); update(); return; } } } } /** * Adds a column. * * @param selected */ public void addRight(Object selected) { int index = 0; if (selected instanceof HierarchyWizardGroupingGroup){ for (int i=0; i<groups.size(); i++){ if (groups.get(i).indexOf(selected) != -1) { index = i+1; } } } List<HierarchyWizardGroupingGroup<T>> list = new ArrayList<HierarchyWizardGroupingGroup<T>>(); groups.add(index, list); list.add(new HierarchyWizardGroupingGroup<T>(1, function)); update(); } /** * @return the type */ public DataType<T> getDataType() { return type; } /** * Returns the default aggregate function. * * @return */ public AggregateFunction<T> getDefaultFunction(){ return this.function; } /** * @return the intervals */ public List<HierarchyWizardGroupingInterval<T>> getIntervals() { return intervals; } /** * @return the lower */ public HierarchyWizardGroupingRange<T> getLowerRange() { return lower; } /** * @return the groups */ public List<List<HierarchyWizardGroupingGroup<T>>> getModelGroups() { return groups; } /** * @return the renderer */ public HierarchyWizardEditorRenderer<T> getRenderer() { return renderer; } /** * @return the selected */ public Object getSelectedElement() { return selected; } /** * @return the upper */ public HierarchyWizardGroupingRange<T> getUpperRange() { return upper; } /** * Is this the first interval. * * @param interval * @return */ public boolean isFirst(HierarchyWizardGroupingInterval<T> interval){ return intervals.indexOf(interval) == 0; } /** * Is this the last interval. * * @param interval * @return */ public boolean isLast(HierarchyWizardGroupingInterval<T> interval){ return intervals.indexOf(interval) == intervals.size()-1; } /** * @return the showIntervals */ public boolean isShowIntervals() { return showIntervals; } /** * Merges the interval down. * * @param selected */ public void mergeDown(Object selected) { if (selected instanceof HierarchyWizardGroupingInterval){ int index = intervals.indexOf(selected); if (index != -1) { AggregateFunction<T> function = intervals.get(index).function; T min = intervals.get(index-1).min; T max = intervals.get(index).max; intervals.remove(index-1); intervals.remove(index-1); intervals.add(index-1, new HierarchyWizardGroupingInterval<T>(min, max, function)); update(); } } } /** * Merges the interval up. * * @param selected */ public void mergeUp(Object selected) { if (selected instanceof HierarchyWizardGroupingInterval){ int index = intervals.indexOf(selected); if (index != -1) { AggregateFunction<T> function = intervals.get(index).function; T min = intervals.get(index).min; T max = intervals.get(index+1).max; intervals.remove(index); intervals.remove(index); intervals.add(index, new HierarchyWizardGroupingInterval<T>(min, max, function)); update(); } } } /** * Parses an interval-based spec. * * @param builder */ public void parse(HierarchyBuilderIntervalBased<T> builder){ this.type = builder.getDataType(); this.showIntervals = true; this.lower.minMaxBound = builder.getLowerRange().getMinMaxValue(); this.lower.snapBound = builder.getLowerRange().getSnapFrom(); this.lower.bottomTopCodingBound = builder.getLowerRange().getBottomTopCodingFrom(); this.upper.minMaxBound = builder.getUpperRange().getMinMaxValue(); this.upper.snapBound = builder.getUpperRange().getSnapFrom(); this.upper.bottomTopCodingBound = builder.getUpperRange().getBottomTopCodingFrom(); this.function = builder.getDefaultFunction(); this.intervals.clear(); this.groups.clear(); for (Interval<T> interval : builder.getIntervals()) { this.intervals.add(new HierarchyWizardGroupingInterval<T>(interval)); } for (Level<T> level : builder.getLevels()){ List<HierarchyWizardGroupingGroup<T>> list = new ArrayList<HierarchyWizardGroupingGroup<T>>(); this.groups.add(list); for (Group<T> group : level.getGroups()) { list.add(new HierarchyWizardGroupingGroup<T>(group)); } } update(); } /** * Parses an order-based spec. * * @param builder * @throws IllegalArgumentException */ public void parse(HierarchyBuilderOrderBased<T> builder) throws IllegalArgumentException{ if (builder.getComparator() != null) { try { Arrays.sort(this.data, builder.getComparator()); } catch (Exception e){ throw new IllegalArgumentException(Resources.getMessage("HierarchyWizardModelGrouping.1")); //$NON-NLS-1$ } } this.showIntervals = false; this.function = builder.getDefaultFunction(); this.intervals.clear(); this.groups.clear(); this.lower = null; this.upper = null; for (Level<T> level : builder.getLevels()){ List<HierarchyWizardGroupingGroup<T>> list = new ArrayList<HierarchyWizardGroupingGroup<T>>(); this.groups.add(list); for (Group<T> group : level.getGroups()) { list.add(new HierarchyWizardGroupingGroup<T>(group)); } } update(); } /** * Registers a part of the UI. * * @param component */ public void register(HierarchyWizardView component){ this.components.add(component); } /** * Removes the given object. * * @param selected */ public void remove(Object selected) { if (selected instanceof HierarchyWizardGroupingInterval){ Iterator<HierarchyWizardGroupingInterval<T>> iter = intervals.iterator(); while (iter.hasNext()){ if (iter.next().equals(selected)) { iter.remove(); selected = null; update(); return; } } } else if (selected instanceof HierarchyWizardGroupingGroup){ for (List<HierarchyWizardGroupingGroup<T>> list : groups){ Iterator<HierarchyWizardGroupingGroup<T>> iter = list.iterator(); while (iter.hasNext()){ if (iter.next().equals(selected)) { iter.remove(); if (list.isEmpty()) { groups.remove(list); } selected = null; update(); return; } } } } } /** * Sets the default aggregate function. * * @param function */ public void setDefaultFunction(AggregateFunction<T> function){ AggregateFunction<T> old = this.function; this.function = function; // Update for (HierarchyWizardGroupingInterval<T> interval : intervals) { if (interval.function == old){ interval.function = function; } } for (List<HierarchyWizardGroupingGroup<T>> list : groups) { for (HierarchyWizardGroupingGroup<T> group : list) { if (group.function == old){ group.function = function; } } } } /** * Updates the selected element. * * @param selected */ public void setSelectedElement(Object selected) { this.selected = selected; } /** * Update the model and all UI components. */ @Override public void update(){ super.update(); renderer.update(); updateUI(null); } /** * Update the model and all UI components, apart from the sender. * * @param sender */ public void update(HierarchyWizardView sender){ super.update(); renderer.update(); updateUI(sender); } /** * Update the UI components. */ @Override public void updateUI(HierarchyWizardView sender){ for (HierarchyWizardView c : components){ if (c != sender) { c.update(); } } } /** * Simple comparison of data types. * * @param type * @param other * @return */ private boolean equals(DataType<?> type, DataType<?> other){ return type.getDescription().getLabel().equals(other.getDescription().getLabel()); } }
package com.synopsys.integration.detectable.detectables.go.unit; import java.io.File; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import com.google.gson.GsonBuilder; import com.synopsys.integration.bdio.model.externalid.ExternalIdFactory; import com.synopsys.integration.detectable.ExecutableTarget; import com.synopsys.integration.detectable.detectable.exception.DetectableException; import com.synopsys.integration.detectable.detectable.executable.DetectableExecutableRunner; import com.synopsys.integration.detectable.detectable.executable.ExecutableFailedException; import com.synopsys.integration.detectable.detectables.go.gomod.GoModCliExtractor; import com.synopsys.integration.detectable.detectables.go.gomod.GoModCommandRunner; import com.synopsys.integration.detectable.detectables.go.gomod.GoModDependencyType; import com.synopsys.integration.detectable.detectables.go.gomod.parse.GoGraphParser; import com.synopsys.integration.detectable.detectables.go.gomod.parse.GoListParser; import com.synopsys.integration.detectable.detectables.go.gomod.parse.GoModWhyParser; import com.synopsys.integration.detectable.detectables.go.gomod.parse.GoVersionParser; import com.synopsys.integration.detectable.detectables.go.gomod.process.GoModGraphGenerator; import com.synopsys.integration.detectable.extraction.Extraction; import com.synopsys.integration.executable.Executable; import com.synopsys.integration.executable.ExecutableOutput; import com.synopsys.integration.executable.ExecutableRunnerException; @Disabled("Questionable value. Should be tested via Detectable tests. Having issues with Mockito. JM-01/2022") public class GoModCliExtractorTest { // These tests weren't updated to use the new json format for go the first call of go list, yet somehow still passing? // With the removal of -u, Mockito kept returning null for that first go list call instead of ExecutableOutput. // I think this test is redundant with the existence of GoModDetectableMinusWhyTest // Leaving it here for now to review one day. JM-01/2022 @Test public void handleMultipleReplacementsForOneComponentTest() throws ExecutableRunnerException, ExecutableFailedException, DetectableException { DetectableExecutableRunner executableRunner = Mockito.mock(DetectableExecutableRunner.class); File directory = new File(""); ExecutableTarget goExe = ExecutableTarget.forFile(new File("")); Answer<ExecutableOutput> executableAnswer = new Answer<ExecutableOutput>() { String[] goListArgs = { "list", "-m", "-json" }; String[] goListJsonArgs = { "list", "-m", "-json", "all" }; String[] goModGraphArgs = { "mod", "graph" }; @Override public ExecutableOutput answer(InvocationOnMock invocation) { Executable executable = invocation.getArgument(0, Executable.class); List<String> commandLine = executable.getCommandWithArguments(); ExecutableOutput result = null; if (commandLine.containsAll(Arrays.asList(goListJsonArgs))) { result = goListJsonOutput(); } else if (commandLine.containsAll(Arrays.asList(goListArgs))) { result = goListOutput(); } else if (commandLine.containsAll(Arrays.asList(goModGraphArgs))) { result = goModGraphOutput(); } else { result = new ExecutableOutput(0, "", ""); } return result; } }; GoModCliExtractor goModCliExtractor = buildGoModCliExtractor(executableRunner, executableAnswer); boolean wasSuccessful = true; Extraction extraction = goModCliExtractor.extract(directory, goExe); if (extraction.getError() instanceof ArrayIndexOutOfBoundsException) { wasSuccessful = false; } Assertions.assertTrue(wasSuccessful); } @Test public void handleGoModWhyExceptionTest() throws ExecutableRunnerException, ExecutableFailedException, DetectableException { DetectableExecutableRunner executableRunner = Mockito.mock(DetectableExecutableRunner.class); File directory = new File(""); ExecutableTarget goExe = ExecutableTarget.forFile(new File("")); Answer<ExecutableOutput> executableAnswer = new Answer<ExecutableOutput>() { String[] goListArgs = { "list", "-m", "-json" }; String[] goListJsonArgs = { "list", "-m", "-json", "all" }; String[] goModGraphArgs = { "mod", "graph" }; String[] goModWhyArgs = { "mod", "why", "-m", "all" }; @Override public ExecutableOutput answer(InvocationOnMock invocation) throws Throwable { Executable executable = invocation.getArgument(0, Executable.class); List<String> commandLine = executable.getCommandWithArguments(); ExecutableOutput result = null; if (commandLine.containsAll(Arrays.asList(goListJsonArgs))) { result = goListJsonOutput(); } else if (commandLine.containsAll(Arrays.asList(goListArgs))) { result = goListOutput(); } else if (commandLine.containsAll(Arrays.asList(goModGraphArgs))) { result = goModGraphOutput(); } else if (commandLine.containsAll(Arrays.asList(goModWhyArgs))) { throw new ExecutableRunnerException(new DetectableException("Unit Test Go Mod Why error")); } else { result = new ExecutableOutput(0, "", ""); } return result; } }; GoModCliExtractor goModCliExtractor = buildGoModCliExtractor(executableRunner, executableAnswer); boolean wasSuccessful = true; Extraction extraction = goModCliExtractor.extract(directory, goExe); if (extraction.getError() instanceof ArrayIndexOutOfBoundsException) { wasSuccessful = false; } Assertions.assertTrue(wasSuccessful); } private GoModCliExtractor buildGoModCliExtractor(DetectableExecutableRunner executableRunner, Answer<ExecutableOutput> executableAnswer) throws ExecutableRunnerException { Mockito.doAnswer(executableAnswer).when(executableRunner).execute(Mockito.any(Executable.class)); GoModWhyParser goModWhyParser = new GoModWhyParser(); GoVersionParser goVersionParser = new GoVersionParser(); GoModCommandRunner goModCommandRunner = new GoModCommandRunner(executableRunner); GoModGraphGenerator goModGraphGenerator = new GoModGraphGenerator(new ExternalIdFactory()); GoListParser goListParser = new GoListParser(new GsonBuilder().create()); GoGraphParser goGraphParser = new GoGraphParser(); ExternalIdFactory externalIdFactory = new ExternalIdFactory(); return new GoModCliExtractor( goModCommandRunner, goListParser, goGraphParser, goModWhyParser, goVersionParser, goModGraphGenerator, externalIdFactory, GoModDependencyType.UNUSED ); } private ExecutableOutput goListOutput() { String standardOutput = String.join("\n", Arrays.asList( "{", "\t\"Path\": \"git.daimler.com/c445/t1\",", "\t\"Main\": true,", "}" )); return new ExecutableOutput(0, standardOutput, ""); } private ExecutableOutput goListJsonOutput() { String standardOutput = String.join("\n", Arrays.asList( "{", "\t\"Path\": \"github.com/codegangsta/negroni\",", "\t\"Version\": \"v1.0.0\",", "\t\"Replace\": {", "\t\t\"Path\": \"github.com/codegangsta/negroni\",", "\t\t\"Version\": \"v2.0.0\"", "\t}", "}", "", "{", "\t\"Path\": \"github.com/sirupsen/logrus\",", "\t\"Version\": \"v1.1.1\",", "\t\"Replace\": {", "\t\t\"Path\": \"github.com/sirupsen/logrus\",", "\t\t\"Version\": \"v2.0.0\"", "\t}", "}" )); return new ExecutableOutput(0, standardOutput, ""); } private ExecutableOutput goModGraphOutput() { String standardOutput = String.join("\n", Arrays.asList( "github.com/codegangsta/negroni@v1.0.0 github.com/sirupsen/logrus@v1.1.1" )); return new ExecutableOutput(0, standardOutput, ""); } }
/** * Copyright (C) 2009-2017 Simonsoft Nordic AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.simonsoft.cms.testing.svn; import java.io.File; import java.io.InputStream; import javax.inject.Provider; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.SVNRevision; import org.tmatesoft.svn.core.wc.SVNWCUtil; import org.tmatesoft.svn.core.wc.admin.SVNAdminClient; import org.tmatesoft.svn.core.wc2.SvnOperationFactory; public class CmsTestRepository extends CmsRepositoryLocal { private static final long serialVersionUID = 1L; private SVNRepository svnkit; private String user; private String password; private boolean keep = false; private boolean renameAtKeep; public CmsTestRepository(SVNRepository svnkit, File repoFolder, String user, String password) { super(getUrl(svnkit), repoFolder); this.svnkit = svnkit; this.user = user; this.password = password; } /** * @param dumpfile from svnadmin dump * @return the instance */ public CmsTestRepository load(InputStream dumpfile) { SVNAdminClient svnadmin = new SVNAdminClient(SVNWCUtil.createDefaultAuthenticationManager(), null); try { svnadmin.doLoad(getAdminPath(), dumpfile); } catch (SVNException e) { throw new RuntimeException("Error not handled", e); } return this; } /** * Flags to test setup that the repository should be kept after tearDown, for manual investigation. */ public void keep() { this.keep = true; } public boolean isKeep() { return keep; } /** * @param keep see {@link #keep()} */ public void setKeep(boolean keep) { this.keep = keep; } /** * @return repository connection, authenticated */ public SVNRepository getSvnkit() { return svnkit; } /** * @return access to the new relatively maintainer friendly wc2 operations api */ public SvnOperationFactory getSvnkitOp() { SvnOperationFactory op = new SvnOperationFactory(); op.setAuthenticationManager(getSvnkit().getAuthenticationManager()); return op; } /** * @return for svnkit based impls that get repository provider injected */ public Provider<SVNRepository> getSvnkitProvider() { final CmsTestRepository repo = this; return new Provider<SVNRepository>() { @Override public SVNRepository get() { return repo.getSvnkit(); } }; } public SVNURL getUrlSvnkit() { try { return SVNURL.parseURIEncoded(getUrl()); } catch (SVNException e) { throw new IllegalStateException("Invalid internal repository URL " + getUrl()); } } public String getAuthenticatedUser() { return user; } public String getAuthenticatedPassword() { return password; } static String getUrl(SVNRepository repository) { try { SVNDirEntry info = repository.info("/", SVNRevision.HEAD.getNumber()); return info.getURL().toString(); } catch (SVNException e) { throw new RuntimeException("Failed to verify connection to test repository", e); } } void setRenameAtKeep(boolean renameAtKeep) { this.renameAtKeep = renameAtKeep; } boolean isRenameAtKeep() { return renameAtKeep; } }
package io.cucumber.core.options; public final class Constants { /** * File name of cucumber properties file: {@value} */ public static final String CUCUMBER_PROPERTIES_FILE_NAME = "cucumber.properties"; /** * Property name used to pass command line options: {@value} * <p> * When available it is recommended to use a property based alternative. * * @see RuntimeOptionsParser */ public static final String CUCUMBER_OPTIONS_PROPERTY_NAME = "cucumber.options"; /** * Property name used to select a specific object factory implementation: {@value} * * @see io.cucumber.core.backend.ObjectFactoryServiceLoader */ public static final String CUCUMBER_OBJECT_FACTORY_PROPERTY_NAME = "cucumber.object-factory"; private Constants() { } }
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.portal.io.xml; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import javax.sql.DataSource; import org.jasig.portal.io.xml.permission.ExternalPermissionOwner; import org.jasig.portal.io.xml.ssd.ExternalStylesheetDescriptor; import org.jasig.portal.io.xml.subscribedfragment.ExternalSubscribedFragments; import org.jasig.portal.io.xml.user.UserType; import org.jasig.portal.test.BasePortalJpaDaoTest; import org.jasig.portal.test.TimeZoneTestUtils; import org.jasig.portal.utils.ICounterStore; import org.jasig.portal.utils.Tuple; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ClassPathResource; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.jdbc.SimpleJdbcTestUtils; import org.w3c.dom.Element; import com.google.common.base.Function; /** * @author Eric Dalquist * @version $Revision$ */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:/org/jasig/portal/io/xml/importExportTestContext.xml") public class IdentityImportExportTest extends BasePortalJpaDaoTest { private static final TimeZoneTestUtils TIME_ZONE_TEST_UTILS = new TimeZoneTestUtils(); @BeforeClass public static void setupTZ() { TIME_ZONE_TEST_UTILS.beforeTest(); } @AfterClass public static void cleanupTZ() { TIME_ZONE_TEST_UTILS.afterTest(); } @Autowired private DataSource dataSource; @javax.annotation.Resource(name="stylesheetDescriptorImporterExporter") private IDataImporter<ExternalStylesheetDescriptor> stylesheetDescriptorImporter; @javax.annotation.Resource(name="stylesheetDescriptorImporterExporter") private IDataExporter<ExternalStylesheetDescriptor> stylesheetDescriptorExporter; @javax.annotation.Resource(name="userImporterExporter") private IDataImporter<UserType> userImporter; @javax.annotation.Resource(name="userImporterExporter") private IDataExporter<UserType> userExporter; @javax.annotation.Resource(name="permissionOwnerImporterExporter") private IDataImporter<ExternalPermissionOwner> permissionOwnerImporter; @javax.annotation.Resource(name="permissionOwnerImporterExporter") private IDataExporter<ExternalPermissionOwner> permissionOwnerExporter; @javax.annotation.Resource(name="fragmentDefinitionImporter") private IDataImporter<Tuple<String, Element>> fragmentDefinitionImporter; @javax.annotation.Resource(name="fragmentDefinitionExporter") private IDataExporter<Tuple<String, org.dom4j.Element>> fragmentDefinitionExporter; @javax.annotation.Resource(name="subscribedFragmentImporterExporter") private IDataImporter<ExternalSubscribedFragments> subscribedFragmentImporter; @javax.annotation.Resource(name="subscribedFragmentImporterExporter") private IDataExporter<ExternalSubscribedFragments> subscribedFragmentExporter; @Autowired private ICounterStore counterStore; private SimpleJdbcTemplate simpleJdbcTemplate; private int counter = 0; protected void runSql(final String sql) { if (simpleJdbcTemplate == null) { simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); } SimpleJdbcTestUtils.executeSqlScript(simpleJdbcTemplate, new ByteArrayResource(sql.getBytes()), false); } @Before public void setup() { simpleJdbcTemplate = null; counter = 0; when(counterStore.getNextId(anyString())).thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { return counter++; } }); //Needed for user import/export test runSql("CREATE TABLE UP_USER\n" + "(\n" + " USER_ID integer,\n" + " USER_NAME varchar(1000),\n" + " USER_DFLT_USR_ID integer,\n" + " USER_DFLT_LAY_ID integer,\n" + " NEXT_STRUCT_ID integer,\n" + " LST_CHAN_UPDT_DT timestamp,\n" + " CONSTRAINT SYS_IDX_01 PRIMARY KEY (USER_ID)\n" + ");"); runSql("CREATE INDEX UPU_DFLT_ID_IDX ON UP_USER(USER_DFLT_USR_ID);"); runSql("CREATE TABLE UP_LAYOUT_STRUCT\n" + "(\n" + " USER_ID integer NOT NULL,\n" + " LAYOUT_ID integer NOT NULL,\n" + " STRUCT_ID integer NOT NULL,\n" + " NEXT_STRUCT_ID integer,\n" + " CHLD_STRUCT_ID integer,\n" + " EXTERNAL_ID varchar(1000),\n" + " CHAN_ID integer,\n" + " NAME varchar(1000),\n" + " TYPE varchar(1000),\n" + " HIDDEN varchar(1000),\n" + " IMMUTABLE varchar(1000),\n" + " UNREMOVABLE varchar(1000),\n" + " CONSTRAINT SYS_IDX_03 PRIMARY KEY (LAYOUT_ID,USER_ID,STRUCT_ID)\n" + ");"); } @After public void cleanup() { runSql("DROP TABLE UP_USER"); runSql("DROP TABLE UP_LAYOUT_STRUCT"); } @Test public void testStylesheetDescriptor40ImportExport() throws Exception { final ClassPathResource stylesheetDescriptorResource = new ClassPathResource("/org/jasig/portal/io/xml/ssd/test_4-0.stylesheet-descriptor.xml"); IdentityImportExportTestUtilities.testIdentityImportExport(this.transactionOperations, this.stylesheetDescriptorImporter, this.stylesheetDescriptorExporter, stylesheetDescriptorResource, new Function<ExternalStylesheetDescriptor, String>() { @Override public String apply(ExternalStylesheetDescriptor input) { return input.getName(); } }); } @Test public void testPermissionOwner40ImportExport() throws Exception { final ClassPathResource permissionOwnerResource = new ClassPathResource("/org/jasig/portal/io/xml/permission-owner/test_4-0.permission-owner.xml"); IdentityImportExportTestUtilities.testIdentityImportExport(this.transactionOperations, this.permissionOwnerImporter, this.permissionOwnerExporter, permissionOwnerResource, new Function<ExternalPermissionOwner, String>() { @Override public String apply(ExternalPermissionOwner input) { return input.getFname(); } }); } @Test public void testUser40ImportExport() throws Exception { final ClassPathResource dataResource = new ClassPathResource("/org/jasig/portal/io/xml/user/test_4-0.user.xml"); IdentityImportExportTestUtilities.<UserType>testIdentityImportExport(this.transactionOperations, this.userImporter, this.userExporter, dataResource, new Function<UserType, String>() { @Override public String apply(UserType input) { return input.getUsername(); } }); } @Test public void testFragmentDefinition31ImportExport() throws Exception { final ClassPathResource dataResource = new ClassPathResource("/org/jasig/portal/io/xml/fragment-definition/academic-tab_3-1.fragment-definition.xml"); IdentityImportExportTestUtilities.<Tuple<String, Element>>testIdentityImportExport(this.transactionOperations, this.fragmentDefinitionImporter, this.fragmentDefinitionExporter, dataResource, new Function<Tuple<String, Element>, String>() { @Override public String apply(Tuple<String, Element> input) { return "Academics Tab"; } }); } @Test public void testSubscribedFragment40ImportExport() throws Exception { runSql("INSERT INTO UP_USER (USER_ID, USER_NAME, USER_DFLT_USR_ID, USER_DFLT_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT) " + "VALUES (1, 'admin', 0, 0, 0, null)"); runSql("INSERT INTO UP_USER (USER_ID, USER_NAME, USER_DFLT_USR_ID, USER_DFLT_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT) " + "VALUES (2, 'mum-lo-campus-apps', 0, 0, 0, null)"); runSql("INSERT INTO UP_USER (USER_ID, USER_NAME, USER_DFLT_USR_ID, USER_DFLT_LAY_ID, NEXT_STRUCT_ID, LST_CHAN_UPDT_DT) " + "VALUES (3, 'mum-lo-cg', 0, 0, 0, null)"); final ClassPathResource permissionOwnerResource = new ClassPathResource("/org/jasig/portal/io/xml/subscribed-fragment/test_4-0.subscribed-fragment.xml"); IdentityImportExportTestUtilities.testIdentityImportExport(this.transactionOperations, this.subscribedFragmentImporter, this.subscribedFragmentExporter, permissionOwnerResource, new Function<ExternalSubscribedFragments, String>() { @Override public String apply(ExternalSubscribedFragments input) { return input.getUsername(); } }); } }
/* * Copyright 2015 Palantir Technologies, Inc. All rights reserved. * * Licensed under the BSD-3 License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.lock.impl; import java.util.Map; import javax.annotation.concurrent.ThreadSafe; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.palantir.lock.LockClient; @ThreadSafe @VisibleForTesting public class LockClientIndices { private final Map<LockClient, Integer> indexByClient = Maps.newConcurrentMap(); private final Map<Integer, LockClient> clientByIndex = Maps.newConcurrentMap(); public LockClientIndices() { indexByClient.put(LockClient.ANONYMOUS, -1); clientByIndex.put(-1, LockClient.ANONYMOUS); } int toIndex(LockClient client) { Integer index = indexByClient.get(client); if (index != null) { return index; } synchronized (this) { index = indexByClient.get(client); if (index != null) { return index; } int newIndex = indexByClient.size(); indexByClient.put(client, newIndex); clientByIndex.put(newIndex, client); return newIndex; } } LockClient fromIndex(int index) { return Preconditions.checkNotNull(clientByIndex.get(index)); } Iterable<LockClient> fromIndices(Iterable<Integer> indices) { return Iterables.transform(indices, new Function<Integer, LockClient>() { @Override public LockClient apply(Integer index) { return fromIndex(index); } }); } }
package com.seizedays.semall.webutils.configs; import feign.Request; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FeignConfig { @Value("${service.feign.connectTimeout:60000}") private int connectTimeout; @Value("${service.feign.readTimeOut:60000}") private int readTimeout; @Bean public Request.Options options() { return new Request.Options(connectTimeout, readTimeout); } }
package it.unimol.tracker; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.concurrent.CopyOnWriteArraySet; import java.util.regex.Pattern; public class TelegramBot extends TelegramLongPollingBot { private final Pattern SPACE_REGEX = Pattern.compile("\\s"); private final Pattern NAME_REGEX = Pattern.compile("^[a-zA-Z0-9]+$"); private final Pattern SEED_REGEX = Pattern.compile("^https:\\/\\/www\\.subito\\.it\\/annunci.*"); private final int WAITING_TIME = 60000; private String[] commands; private String helpMessage; private String botMessage; private CopyOnWriteArraySet<User> users; private MongoDatabase database; public TelegramBot() { this.commands = new String[]{"/start", "/stop", "/new", "/delete", "/list", "/result", "/help"}; this.helpMessage = "You can use the following commands for:\n" + "1. /start - start the bot\n" + "2. /stop - stop the bot\n" + "3. /new - insert a new research. Please use this format: [/new researchName researchUrl]; researchName uniquely identify a research and must be an alphanumeric string; researchUrl must be related to the first search page\n" + "4. /delete - delete the specified research. Please use this format: [/delete researchName]\n" + "5. /list - show all active researches\n" + "5. /result - get all ads for the specified research. Please use this format: [/result researchName]\n" + "7. /help - show help message"; this.users = new CopyOnWriteArraySet<>(); this.connectToDatabase(); } @Override public void onUpdateReceived(Update update) { if (update.hasMessage() && update.getMessage().hasText()) { this.logUser(update); long chatID = update.getMessage().getChatId(); String userMessage = update.getMessage().getText(); String[] str = SPACE_REGEX.split(userMessage); String command = str[0]; SendMessage sendMessage = new SendMessage(); User user = this.getUserByChatID(chatID); try { if (!user.isActive()) { if (command.equals("/start")) this.performStartCommand(user); } else { if (command.equals("/stop")) { this.performStopCommand(user); } else if (command.equals("/new")) { this.performNewCommand(user, userMessage); } else if (command.equals("/help")) { this.botMessage = this.helpMessage; } else if (Arrays.asList(this.commands).contains(command)) { if (!user.getResearch().isEmpty()) { if (command.equals("/delete")) this.performDeleteCommand(user, userMessage); else if (command.equals("/list")) this.performListCommand(user); else if (command.equals("/result")) this.performResultCommand(user, userMessage); } else { this.botMessage = "Attention, there is no research to operate on!"; } } else { this.botMessage = "Unknown command!"; } } sendMessage.setChatId(String.valueOf(chatID)); sendMessage.setText(this.botMessage); execute(sendMessage); this.botMessage = ""; this.dbSaveMessage(update); } catch (TelegramApiException ignored) { } } } @Override public String getBotUsername() { return "SubitoTracker_bot"; } @Override public String getBotToken() { return System.getenv("BOT_TOKEN"); } private void performStartCommand(User user) { this.botMessage = "Welcome " + user.getFirstName() + "!\n" + this.helpMessage; user.setState(State.ACTIVE); Thread startThread = new Thread(() -> { while (user.isActive()) { if (!user.getResearch().isEmpty()) { try { for (Research research : user.getResearch()) research.resetResearchThread(); for (Research research : user.getResearch()) research.getResearchThread().start(); for (Research research : user.getResearch()) research.getResearchThread().join(); for (Research research : user.getResearch()) this.checkNewAds(user, research); Thread.sleep(WAITING_TIME); } catch (InterruptedException | TelegramApiException ignored) { } } } }); startThread.start(); } private void checkNewAds(User user, Research research) throws TelegramApiException, InterruptedException { CopyOnWriteArraySet<String> newAdsUrl = new CopyOnWriteArraySet<>(research.getCrawledAdsUrl()); newAdsUrl.removeAll(research.getAdsUrl()); if (!newAdsUrl.isEmpty()) { SendMessage sendMessage = new SendMessage(); sendMessage.setChatId(user.getChatID()); sendMessage.setText("New ads for " + research.getName() + " research!"); execute(sendMessage); for (String adUrl : newAdsUrl) { sendMessage.setText(adUrl); execute(sendMessage); Thread.sleep(150); } research.updateAds(); this.dbUpdateResearchAndAds(user); } } private void performStopCommand(User user) { this.botMessage = "See you soon!"; user.setState(State.INACTIVE); } private void performNewCommand(User user, String userMessage) { String[] str = SPACE_REGEX.split(userMessage); String name = str[1]; String seed = str[2]; if (str.length == 3 && NAME_REGEX.matcher(name).matches() && SEED_REGEX.matcher(seed).matches()) { boolean successfullyAdded = user.newResearch(name, seed); if (successfullyAdded) { this.botMessage = "Research added!"; this.dbUpdateResearchAndAds(user); } else { this.botMessage = "Attention, this research already exists!"; } } else { this.botMessage = "Invalid /new command!"; } } private void performDeleteCommand(User user, String userMessage) { String[] str = SPACE_REGEX.split(userMessage); String name = str[1]; if (str.length == 2 && NAME_REGEX.matcher(name).matches()) { boolean successfullyDeleted = user.deleteResearch(name); if (successfullyDeleted) { this.botMessage = "Research removed!"; this.dbDeleteResearch(user, name); } else { this.botMessage = "Attention, this research does not exist!"; } } else { this.botMessage = "Invalid /delete command!"; } } private void performListCommand(User user) { StringBuilder list = new StringBuilder(); list.append("Active research:\n"); for (Research research : user.getResearch()) list.append("[" + research.getName() + "," + research.getSeed() + "]\n"); this.botMessage = list.toString(); } private void performResultCommand(User user, String userMessage) throws TelegramApiException { String[] str = SPACE_REGEX.split(userMessage); String name = str[1]; if (str.length == 2 && NAME_REGEX.matcher(name).matches()) { Research research = user.getResearchByName(name); if (research != null) { SendMessage sendMessage = new SendMessage(); sendMessage.setChatId(user.getChatID()); for (Ad ad : research.getAds()) { sendMessage.setText(ad.getUrl()); execute(sendMessage); } this.botMessage = "Here are the ads for " + research.getName() + " research!"; } else { this.botMessage = "Attention, this research does not exist!"; } } else { this.botMessage = "Invalid /result command!"; } } private User getUserByChatID(long chatID) { if (!this.users.isEmpty()) for (User user : this.users) if (user.getChatID().equals(Long.toString(chatID))) return user; return null; } private void connectToDatabase() { MongoClient client = new MongoClient(System.getenv("MONGO_HOST"), 27017); this.database = client.getDatabase("subitoTracker"); this.retrieveData(); } private void logUser(Update update) { long chatID = update.getMessage().getChatId(); User user = this.getUserByChatID(chatID); if (user == null) { String firstName = update.getMessage().getChat().getFirstName(); String lastName = update.getMessage().getChat().getLastName(); String username = update.getMessage().getChat().getUserName(); User newUser = new User(Long.toString(chatID), firstName, lastName, username); this.users.add(newUser); this.dbInsertNewUser(newUser); } } private void dbSaveMessage(Update update) { DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); MongoCollection<Document> messagesCollection = this.database.getCollection("messages"); Document messageDocument = new Document("userId", Long.toString(update.getMessage().getChatId())) .append("date", /*dateFormat.format(new Date())*/ new Date()) .append("userMessage", update.getMessage().getText()) .append("botMessage", this.botMessage); messagesCollection.insertOne(messageDocument); } //Performed only if the program is closed (few times) private void retrieveData() { MongoCollection<Document> trackerCollection = this.database.getCollection("tracker"); for (Document document : trackerCollection.find()) { String chatID = (String) document.get("userId"); String firstName = (String) document.get("firstName"); String lastName = (String) document.get("lastName"); String username = (String) document.get("username"); User user = new User(chatID, firstName, lastName, username); this.users.add(user); ArrayList<Document> researchDocument = (ArrayList<Document>) document.get("research"); if (researchDocument != null) { for (Document researchDoc : researchDocument) { String name = (String) researchDoc.get("name"); String seed = (String) researchDoc.get("seed"); Research research = new Research(name, seed); user.getResearch().add(research); ArrayList<Document> adsDocument = (ArrayList<Document>) researchDoc.get("ads"); for (Document adDoc : adsDocument) { String ID = (String) adDoc.get("adId"); String url = (String) adDoc.get("url"); String category = (String) adDoc.get("category"); String title = (String) adDoc.get("title"); int price = (int) adDoc.get("price"); String location = (String) adDoc.get("location"); String description = (String) adDoc.get("description"); Ad ad = new Ad(url, ID, category, title, price, description, location); research.getAds().add(ad); } } } } } private void dbInsertNewUser(User user) { MongoCollection<Document> trackerCollection = this.database.getCollection("tracker"); Document userDocument = new Document("userId", user.getChatID()) .append("firstName", user.getFirstName()) .append("lastName", user.getLastName()) .append("username", user.getUsername()); trackerCollection.insertOne(userDocument); } private void dbUpdateResearchAndAds(User user) { MongoCollection<Document> trackerCollection = this.database.getCollection("tracker"); BasicDBObject queryObj = new BasicDBObject("userId", user.getChatID()); List<BasicDBObject> researchObj = new ArrayList<>(); for (Research research : user.getResearch()) { List<BasicDBObject> adsObj = new ArrayList<>(); for (Ad ad : research.getAds()) { adsObj.add(new BasicDBObject("adId", ad.getID()) .append("url", ad.getUrl()) .append("category", ad.getCategory()) .append("title", ad.getTitle()) .append("price", ad.getPrice()) .append("location", ad.getLocation()) .append("description", ad.getDescription())); } researchObj.add(new BasicDBObject("name", research.getName()) .append("seed", research.getSeed()) .append("ads", adsObj)); } BasicDBObject updateObj = new BasicDBObject("research", researchObj); trackerCollection.updateOne(queryObj, new BasicDBObject("$set", updateObj)); } private void dbDeleteResearch(User user, String name) { MongoCollection<Document> trackerCollection = this.database.getCollection("tracker"); BasicDBObject queryObj = new BasicDBObject("userId", user.getChatID()); BasicDBObject updateObj = new BasicDBObject("research", new BasicDBObject("name", name)); trackerCollection.updateOne(queryObj, new BasicDBObject("$pull", updateObj)); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.s3a; import com.amazonaws.ClientConfiguration; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.S3ClientOptions; import com.amazonaws.services.s3.model.AmazonS3Exception; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.reflect.FieldUtils; import com.amazonaws.AmazonClientException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.contract.ContractTestUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.File; import java.net.URI; import java.lang.reflect.Field; import org.apache.hadoop.security.ProviderUtils; import org.apache.hadoop.security.alias.CredentialProvider; import org.apache.hadoop.security.alias.CredentialProviderFactory; import org.apache.hadoop.util.VersionInfo; import org.apache.http.HttpStatus; import org.junit.rules.TemporaryFolder; public class TestS3AConfiguration { private static final String EXAMPLE_ID = "AKASOMEACCESSKEY"; private static final String EXAMPLE_KEY = "RGV0cm9pdCBSZ/WQgY2xl/YW5lZCB1cAEXAMPLE"; private Configuration conf; private S3AFileSystem fs; private static final Logger LOG = LoggerFactory.getLogger(TestS3AConfiguration.class); private static final String TEST_ENDPOINT = "test.fs.s3a.endpoint"; @Rule public Timeout testTimeout = new Timeout(30 * 60 * 1000); @Rule public final TemporaryFolder tempDir = new TemporaryFolder(); /** * Test if custom endpoint is picked up. * <p/> * The test expects TEST_ENDPOINT to be defined in the Configuration * describing the endpoint of the bucket to which TEST_FS_S3A_NAME points * (f.i. "s3-eu-west-1.amazonaws.com" if the bucket is located in Ireland). * Evidently, the bucket has to be hosted in the region denoted by the * endpoint for the test to succeed. * <p/> * More info and the list of endpoint identifiers: * http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region * * @throws Exception */ @Test public void testEndpoint() throws Exception { conf = new Configuration(); String endpoint = conf.getTrimmed(TEST_ENDPOINT, ""); if (endpoint.isEmpty()) { LOG.warn("Custom endpoint test skipped as " + TEST_ENDPOINT + "config " + "setting was not detected"); } else { conf.set(Constants.ENDPOINT, endpoint); fs = S3ATestUtils.createTestFileSystem(conf); AmazonS3Client s3 = fs.getAmazonS3Client(); String endPointRegion = ""; // Differentiate handling of "s3-" and "s3." based endpoint identifiers String[] endpointParts = StringUtils.split(endpoint, '.'); if (endpointParts.length == 3) { endPointRegion = endpointParts[0].substring(3); } else if (endpointParts.length == 4) { endPointRegion = endpointParts[1]; } else { fail("Unexpected endpoint"); } assertEquals("Endpoint config setting and bucket location differ: ", endPointRegion, s3.getBucketLocation(fs.getUri().getHost())); } } @Test public void testProxyConnection() throws Exception { conf = new Configuration(); conf.setInt(Constants.MAX_ERROR_RETRIES, 2); conf.set(Constants.PROXY_HOST, "127.0.0.1"); conf.setInt(Constants.PROXY_PORT, 1); String proxy = conf.get(Constants.PROXY_HOST) + ":" + conf.get(Constants.PROXY_PORT); try { fs = S3ATestUtils.createTestFileSystem(conf); fail("Expected a connection error for proxy server at " + proxy); } catch (AmazonClientException e) { if (!e.getMessage().contains(proxy + " refused")) { throw e; } } } @Test public void testProxyPortWithoutHost() throws Exception { conf = new Configuration(); conf.unset(Constants.PROXY_HOST); conf.setInt(Constants.MAX_ERROR_RETRIES, 2); conf.setInt(Constants.PROXY_PORT, 1); try { fs = S3ATestUtils.createTestFileSystem(conf); fail("Expected a proxy configuration error"); } catch (IllegalArgumentException e) { String msg = e.toString(); if (!msg.contains(Constants.PROXY_HOST) && !msg.contains(Constants.PROXY_PORT)) { throw e; } } } @Test public void testAutomaticProxyPortSelection() throws Exception { conf = new Configuration(); conf.unset(Constants.PROXY_PORT); conf.setInt(Constants.MAX_ERROR_RETRIES, 2); conf.set(Constants.PROXY_HOST, "127.0.0.1"); conf.set(Constants.SECURE_CONNECTIONS, "true"); try { fs = S3ATestUtils.createTestFileSystem(conf); fail("Expected a connection error for proxy server"); } catch (AmazonClientException e) { if (!e.getMessage().contains("443")) { throw e; } } conf.set(Constants.SECURE_CONNECTIONS, "false"); try { fs = S3ATestUtils.createTestFileSystem(conf); fail("Expected a connection error for proxy server"); } catch (AmazonClientException e) { if (!e.getMessage().contains("80")) { throw e; } } } @Test public void testUsernameInconsistentWithPassword() throws Exception { conf = new Configuration(); conf.setInt(Constants.MAX_ERROR_RETRIES, 2); conf.set(Constants.PROXY_HOST, "127.0.0.1"); conf.setInt(Constants.PROXY_PORT, 1); conf.set(Constants.PROXY_USERNAME, "user"); try { fs = S3ATestUtils.createTestFileSystem(conf); fail("Expected a connection error for proxy server"); } catch (IllegalArgumentException e) { String msg = e.toString(); if (!msg.contains(Constants.PROXY_USERNAME) && !msg.contains(Constants.PROXY_PASSWORD)) { throw e; } } conf = new Configuration(); conf.setInt(Constants.MAX_ERROR_RETRIES, 2); conf.set(Constants.PROXY_HOST, "127.0.0.1"); conf.setInt(Constants.PROXY_PORT, 1); conf.set(Constants.PROXY_PASSWORD, "password"); try { fs = S3ATestUtils.createTestFileSystem(conf); fail("Expected a connection error for proxy server"); } catch (IllegalArgumentException e) { String msg = e.toString(); if (!msg.contains(Constants.PROXY_USERNAME) && !msg.contains(Constants.PROXY_PASSWORD)) { throw e; } } } @Test public void testCredsFromCredentialProvider() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.newFile("test.jks"); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, jks.toString()); provisionAccessKeys(conf); S3AFileSystem s3afs = new S3AFileSystem(); conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM"); S3AFileSystem.AWSAccessKeys creds = s3afs.getAWSAccessKeys(new URI("s3a://foobar"), conf); assertEquals("AccessKey incorrect.", EXAMPLE_ID, creds.getAccessKey()); assertEquals("SecretKey incorrect.", EXAMPLE_KEY, creds.getAccessSecret()); } void provisionAccessKeys(final Configuration conf) throws Exception { // add our creds to the provider final CredentialProvider provider = CredentialProviderFactory.getProviders(conf).get(0); provider.createCredentialEntry(Constants.ACCESS_KEY, EXAMPLE_ID.toCharArray()); provider.createCredentialEntry(Constants.SECRET_KEY, EXAMPLE_KEY.toCharArray()); provider.flush(); } @Test public void testCredsFromUserInfo() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.newFile("test.jks"); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, jks.toString()); provisionAccessKeys(conf); S3AFileSystem s3afs = new S3AFileSystem(); conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM"); URI uriWithUserInfo = new URI("s3a://123:456@foobar"); S3AFileSystem.AWSAccessKeys creds = s3afs.getAWSAccessKeys(uriWithUserInfo, conf); assertEquals("AccessKey incorrect.", "123", creds.getAccessKey()); assertEquals("SecretKey incorrect.", "456", creds.getAccessSecret()); } @Test public void testIDFromUserInfoSecretFromCredentialProvider() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.newFile("test.jks"); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, jks.toString()); provisionAccessKeys(conf); S3AFileSystem s3afs = new S3AFileSystem(); conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM"); URI uriWithUserInfo = new URI("s3a://123@foobar"); S3AFileSystem.AWSAccessKeys creds = s3afs.getAWSAccessKeys(uriWithUserInfo, conf); assertEquals("AccessKey incorrect.", "123", creds.getAccessKey()); assertEquals("SecretKey incorrect.", EXAMPLE_KEY, creds.getAccessSecret()); } @Test public void testSecretFromCredentialProviderIDFromConfig() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.newFile("test.jks"); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, jks.toString()); // add our creds to the provider final CredentialProvider provider = CredentialProviderFactory.getProviders(conf).get(0); provider.createCredentialEntry(Constants.SECRET_KEY, EXAMPLE_KEY.toCharArray()); provider.flush(); S3AFileSystem s3afs = new S3AFileSystem(); conf.set(Constants.ACCESS_KEY, EXAMPLE_ID); S3AFileSystem.AWSAccessKeys creds = s3afs.getAWSAccessKeys(new URI("s3a://foobar"), conf); assertEquals("AccessKey incorrect.", EXAMPLE_ID, creds.getAccessKey()); assertEquals("SecretKey incorrect.", EXAMPLE_KEY, creds.getAccessSecret()); } @Test public void testIDFromCredentialProviderSecretFromConfig() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.newFile("test.jks"); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, jks.toString()); // add our creds to the provider final CredentialProvider provider = CredentialProviderFactory.getProviders(conf).get(0); provider.createCredentialEntry(Constants.ACCESS_KEY, EXAMPLE_ID.toCharArray()); provider.flush(); S3AFileSystem s3afs = new S3AFileSystem(); conf.set(Constants.SECRET_KEY, EXAMPLE_KEY); S3AFileSystem.AWSAccessKeys creds = s3afs.getAWSAccessKeys(new URI("s3a://foobar"), conf); assertEquals("AccessKey incorrect.", EXAMPLE_ID, creds.getAccessKey()); assertEquals("SecretKey incorrect.", EXAMPLE_KEY, creds.getAccessSecret()); } @Test public void testExcludingS3ACredentialProvider() throws Exception { // set up conf to have a cred provider final Configuration conf = new Configuration(); final File file = tempDir.newFile("test.jks"); final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider( file.toURI()); conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH, "jceks://s3a/foobar," + jks.toString()); // first make sure that the s3a based provider is removed Configuration c = ProviderUtils.excludeIncompatibleCredentialProviders( conf, S3AFileSystem.class); String newPath = conf.get( CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH); assertFalse("Provider Path incorrect", newPath.contains("s3a://")); // now let's make sure the new path is created by the S3AFileSystem // and the integration still works. Let's provision the keys through // the altered configuration instance and then try and access them // using the original config with the s3a provider in the path. provisionAccessKeys(c); S3AFileSystem s3afs = new S3AFileSystem(); conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM"); URI uriWithUserInfo = new URI("s3a://123:456@foobar"); S3AFileSystem.AWSAccessKeys creds = s3afs.getAWSAccessKeys(uriWithUserInfo, conf); assertEquals("AccessKey incorrect.", "123", creds.getAccessKey()); assertEquals("SecretKey incorrect.", "456", creds.getAccessSecret()); } @Test public void shouldBeAbleToSwitchOnS3PathStyleAccessViaConfigProperty() throws Exception { conf = new Configuration(); conf.set(Constants.PATH_STYLE_ACCESS, Boolean.toString(true)); assertTrue(conf.getBoolean(Constants.PATH_STYLE_ACCESS, false)); try { fs = S3ATestUtils.createTestFileSystem(conf); assertNotNull(fs); AmazonS3Client s3 = fs.getAmazonS3Client(); assertNotNull(s3); S3ClientOptions clientOptions = getField(s3, S3ClientOptions.class, "clientOptions"); assertTrue("Expected to find path style access to be switched on!", clientOptions.isPathStyleAccess()); byte[] file = ContractTestUtils.toAsciiByteArray("test file"); ContractTestUtils.writeAndRead(fs, new Path("/path/style/access/testFile"), file, file.length, conf.getInt(Constants.FS_S3A_BLOCK_SIZE, file.length), false, true); } catch (final AmazonS3Exception e) { LOG.error("Caught exception: ", e); // Catch/pass standard path style access behaviour when live bucket // isn't in the same region as the s3 client default. See // http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html assertEquals(e.getStatusCode(), HttpStatus.SC_MOVED_PERMANENTLY); } } @Test public void testDefaultUserAgent() throws Exception { conf = new Configuration(); fs = S3ATestUtils.createTestFileSystem(conf); assertNotNull(fs); AmazonS3Client s3 = fs.getAmazonS3Client(); assertNotNull(s3); ClientConfiguration awsConf = getField(s3, ClientConfiguration.class, "clientConfiguration"); assertEquals("Hadoop " + VersionInfo.getVersion(), awsConf.getUserAgent()); } @Test public void testCustomUserAgent() throws Exception { conf = new Configuration(); conf.set(Constants.USER_AGENT_PREFIX, "MyApp"); fs = S3ATestUtils.createTestFileSystem(conf); assertNotNull(fs); AmazonS3Client s3 = fs.getAmazonS3Client(); assertNotNull(s3); ClientConfiguration awsConf = getField(s3, ClientConfiguration.class, "clientConfiguration"); assertEquals("MyApp, Hadoop " + VersionInfo.getVersion(), awsConf.getUserAgent()); } /** * Reads and returns a field from an object using reflection. If the field * cannot be found, is null, or is not the expected type, then this method * fails the test. * * @param target object to read * @param fieldType type of field to read, which will also be the return type * @param fieldName name of field to read * @return field that was read * @throws IllegalAccessException if access not allowed */ private static <T> T getField(Object target, Class<T> fieldType, String fieldName) throws IllegalAccessException { Object obj = FieldUtils.readField(target, fieldName, true); assertNotNull(String.format( "Could not read field named %s in object with class %s.", fieldName, target.getClass().getName()), obj); assertTrue(String.format( "Unexpected type found for field named %s, expected %s, actual %s.", fieldName, fieldType.getName(), obj.getClass().getName()), fieldType.isAssignableFrom(obj.getClass())); return fieldType.cast(obj); } }
/** * Copyright (C) 2018 - present McLeod Moores Software Limited. All rights reserved. */ package com.mcleodmoores.web.json.convention; import java.util.Map; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.financial.convention.FixedLegRollDateConvention; import com.opengamma.financial.convention.StubType; import com.opengamma.financial.convention.daycount.DayCounts; import com.opengamma.id.ExternalIdBundle; import com.opengamma.util.money.Currency; import com.opengamma.util.time.Tenor; /** * Custom JSON builder to convert a {@link FixedLegRollDateConvention} to JSON and back again. */ public final class FixedLegRollDateConventionJsonBuilder extends ConventionJsonBuilder<FixedLegRollDateConvention> { /** * Static instance. */ public static final FixedLegRollDateConventionJsonBuilder INSTANCE = new FixedLegRollDateConventionJsonBuilder(); @Override FixedLegRollDateConvention fromJson(final String json, final Map<String, String> attributes) { final FixedLegRollDateConvention convention = fromJSON(FixedLegRollDateConvention.class, json); convention.setAttributes(attributes); return convention; } @Override FixedLegRollDateConvention getCopy(final FixedLegRollDateConvention convention) { return convention.clone(); } @Override public String getTemplate() { return toJSON(new FixedLegRollDateConvention("", ExternalIdBundle.EMPTY, Tenor.THREE_MONTHS, DayCounts.ACT_360, Currency.USD, ExternalSchemes.financialRegionId("US"), StubType.NONE, false, 0)); } private FixedLegRollDateConventionJsonBuilder() { } }
/* * Copyright 2008 Android4ME * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.emerge.xml2axml.parser.axml.resources.content.res; import java.io.IOException; /** * @author Dmitry Skiba * * Block of strings, used in binary xml and arsc. * * TODO: * - implement get() * */ public class StringBlock { /** * Reads whole (including chunk type) string block from stream. * Stream must be at the chunk type. */ public static StringBlock read(IntReader reader) throws IOException { ChunkUtil.readCheckType(reader,CHUNK_TYPE); int chunkSize=reader.readInt(); int stringCount=reader.readInt(); int styleOffsetCount=reader.readInt(); /*?*/reader.readInt(); int stringsOffset=reader.readInt(); int stylesOffset=reader.readInt(); StringBlock block=new StringBlock(); block.m_stringOffsets=reader.readIntArray(stringCount); if (styleOffsetCount!=0) { block.m_styleOffsets=reader.readIntArray(styleOffsetCount); } { int size=((stylesOffset==0)?chunkSize:stylesOffset)-stringsOffset; if ((size%4)!=0) { throw new IOException("String data size is not multiple of 4 ("+size+")."); } block.m_strings=reader.readIntArray(size/4); } if (stylesOffset!=0) { int size=(chunkSize-stylesOffset); if ((size%4)!=0) { throw new IOException("Style data size is not multiple of 4 ("+size+")."); } block.m_styles=reader.readIntArray(size/4); } return block; } /** * Returns number of strings in block. */ public int getCount() { return m_stringOffsets!=null? m_stringOffsets.length: 0; } /** * Returns raw string (without any styling information) at specified index. */ public String getString(int index) { if (index<0 || m_stringOffsets==null || index>=m_stringOffsets.length) { return null; } int offset=m_stringOffsets[index]; int length=getShort(m_strings,offset); StringBuilder result=new StringBuilder(length); for (;length!=0;length-=1) { offset+=2; result.append((char)getShort(m_strings,offset)); } return result.toString(); } /** * Not yet implemented. * * Returns string with style information (if any). */ public CharSequence get(int index) { return getString(index); } /** * Returns string with style tags (html-like). */ public String getHTML(int index) { String raw=getString(index); if (raw==null) { return raw; } int[] style=getStyle(index); if (style==null) { return raw; } StringBuilder html=new StringBuilder(raw.length()+32); int offset=0; while (true) { int i=-1; for (int j=0;j!=style.length;j+=3) { if (style[j+1]==-1) { continue; } if (i==-1 || style[i+1]>style[j+1]) { i=j; } } int start=((i!=-1)?style[i+1]:raw.length()); for (int j=0;j!=style.length;j+=3) { int end=style[j+2]; if (end==-1 || end>=start) { continue; } if (offset<=end) { html.append(raw,offset,end+1); offset=end+1; } style[j+2]=-1; html.append('<'); html.append('/'); html.append(getString(style[j])); html.append('>'); } if (offset<start) { html.append(raw,offset,start); offset=start; } if (i==-1) { break; } html.append('<'); html.append(getString(style[i])); html.append('>'); style[i+1]=-1; } return html.toString(); } /** * Finds index of the string. * Returns -1 if the string was not found. */ public int find(String string) { if (string==null) { return -1; } for (int i=0;i!=m_stringOffsets.length;++i) { int offset=m_stringOffsets[i]; int length=getShort(m_strings,offset); if (length!=string.length()) { continue; } int j=0; for (;j!=length;++j) { offset+=2; if (string.charAt(j)!=getShort(m_strings,offset)) { break; } } if (j==length) { return i; } } return -1; } ///////////////////////////////////////////// implementation private StringBlock() { } /** * Returns style information - array of int triplets, * where in each triplet: * * first int is index of tag name ('b','i', etc.) * * second int is tag start index in string * * third int is tag end index in string */ private int[] getStyle(int index) { if (m_styleOffsets==null || m_styles==null || index>=m_styleOffsets.length) { return null; } int offset=m_styleOffsets[index]/4; int style[]; { int count=0; for (int i=offset;i<m_styles.length;++i) { if (m_styles[i]==-1) { break; } count+=1; } if (count==0 || (count%3)!=0) { return null; } style=new int[count]; } for (int i=offset,j=0;i<m_styles.length;) { if (m_styles[i]==-1) { break; } style[j++]=m_styles[i++]; } return style; } private static final int getShort(int[] array,int offset) { int value=array[offset/4]; if ((offset%4)/2==0) { return (value & 0xFFFF); } else { return (value >>> 16); } } private int[] m_stringOffsets; private int[] m_strings; private int[] m_styleOffsets; private int[] m_styles; private static final int CHUNK_TYPE=0x001C0001; }
/** * Copyright 2016 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package com.github.ambry.tools.admin; import com.codahale.metrics.MetricRegistry; import com.github.ambry.account.Account; import com.github.ambry.account.Container; import com.github.ambry.clustermap.ClusterAgentsFactory; import com.github.ambry.clustermap.ClusterMap; import com.github.ambry.clustermap.DataNodeId; import com.github.ambry.clustermap.PartitionId; import com.github.ambry.clustermap.ReplicaId; import com.github.ambry.commons.BlobId; import com.github.ambry.commons.ServerErrorCode; import com.github.ambry.config.ClusterMapConfig; import com.github.ambry.config.ConnectionPoolConfig; import com.github.ambry.config.RouterConfig; import com.github.ambry.config.SSLConfig; import com.github.ambry.config.VerifiableProperties; import com.github.ambry.messageformat.BlobProperties; import com.github.ambry.messageformat.BlobType; import com.github.ambry.network.BlockingChannelConnectionPool; import com.github.ambry.network.ConnectedChannel; import com.github.ambry.network.ConnectionPool; import com.github.ambry.network.Port; import com.github.ambry.network.PortType; import com.github.ambry.protocol.PutRequest; import com.github.ambry.protocol.PutResponse; import com.github.ambry.tools.util.ToolUtils; import com.github.ambry.utils.ByteBufferInputStream; import com.github.ambry.utils.Utils; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import joptsimple.ArgumentAcceptingOptionSpec; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; /** * Supports uploading files from a directory to a specific partition on a single colo * Steps: * 1. For each file, generate the blob id with the given partition * 2. Generate Blob props, usermetadata and blob content * 3. PutRequest is made to every replica in the specified partition and datacenter, * or a single replica if a hostname and port is specified * 4. Write the output to out file */ public class DirectoryUploader { private PartitionId partitionId; private DataNodeId dataNodeId = null; private final ConnectionPool connectionPool; private final short blobIdVersion; private DirectoryUploader() throws Exception { Properties properties = new Properties(); properties.setProperty("router.hostname", "localhost"); properties.setProperty("router.datacenter.name", "localDC"); ToolUtils.addClusterMapProperties(properties); VerifiableProperties vProps = new VerifiableProperties(properties); ConnectionPoolConfig connectionPoolConfig = new ConnectionPoolConfig(vProps); SSLConfig sslConfig = new SSLConfig(vProps); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(vProps); blobIdVersion = new RouterConfig(vProps).routerBlobidCurrentVersion; connectionPool = new BlockingChannelConnectionPool(connectionPoolConfig, sslConfig, clusterMapConfig, new MetricRegistry()); connectionPool.start(); } private void setPartitionId(ClusterMap clusterMap, String partitionStr, boolean enableVerboseLogging) { for (PartitionId writablePartition : clusterMap.getWritablePartitionIds(null)) { if (writablePartition.toString().equalsIgnoreCase(partitionStr)) { partitionId = writablePartition; break; } } if (partitionId == null) { throw new IllegalArgumentException("Partition " + partitionStr + " is not writable/available"); } if (enableVerboseLogging) { System.out.println("Chosen partition " + partitionId); } } /** * Specify a data node to write to by hostname and port. If this is specified, only this node will be written to. * This node must be in the defined partition and data center. * * @param clusterMap used to find data node corresponding to hostname and port * @param hostname the hostname of the data node * @param port the port number of the data node * @param enableVerboseLogging true to emit verbose log messages */ private void setDataNodeId(ClusterMap clusterMap, String hostname, int port, boolean enableVerboseLogging) { dataNodeId = clusterMap.getDataNodeId(hostname, port); if (dataNodeId == null) { throw new IllegalArgumentException("Node at " + hostname + ":" + port + " not found"); } boolean inPartition = false; for (ReplicaId replicaId : partitionId.getReplicaIds()) { if (replicaId.getDataNodeId().equals(dataNodeId)) { inPartition = true; break; } } if (!inPartition) { throw new IllegalArgumentException("Node at " + hostname + ":" + port + " not in partition " + partitionId); } if (enableVerboseLogging) { System.out.println("Chosen node " + dataNodeId); } } public void walkDirectoryToCreateBlobs(String path, FileWriter writer, String datacenter, byte datacenterId, boolean enableVerboseLogging) throws InterruptedException { File root = new File(path); File[] list = root.listFiles(); Random random = new Random(); if (list == null) { return; } for (File f : list) { if (!f.isDirectory()) { System.out.println("File :" + f.getAbsoluteFile()); if (f.length() > Integer.MAX_VALUE) { System.out.println("File length is " + f.length()); throw new IllegalArgumentException("File length is " + f.length() + "; files larger than " + Integer.MAX_VALUE + " cannot be put using this tool."); } BlobProperties props = new BlobProperties(f.length(), "migration", Account.UNKNOWN_ACCOUNT_ID, Container.UNKNOWN_CONTAINER_ID, false); byte[] usermetadata = new byte[1]; FileInputStream stream = null; try { int replicaCount = 0; BlobId blobId = new BlobId(blobIdVersion, BlobId.BlobIdType.NATIVE, datacenterId, props.getAccountId(), props.getContainerId(), partitionId, false); List<ReplicaId> successList = new ArrayList<>(); List<ReplicaId> failureList = new ArrayList<>(); for (ReplicaId replicaId : blobId.getPartition().getReplicaIds()) { if (replicaId.getDataNodeId().getDatacenterName().equalsIgnoreCase(datacenter)) { // If a node was specified, only write to that node instead of all nodes of a partition if (dataNodeId != null && !dataNodeId.equals(replicaId.getDataNodeId())) { continue; } replicaCount += 1; try { stream = new FileInputStream(f); AtomicInteger correlationId = new AtomicInteger(random.nextInt(100000)); if (writeToAmbryReplica(props, ByteBuffer.wrap(usermetadata), stream, blobId, replicaId, correlationId, enableVerboseLogging)) { successList.add(replicaId); } else { failureList.add(replicaId); } } catch (Exception e) { System.out.println("Exception thrown on replica " + replicaId); } finally { if (stream != null) { stream.close(); } } } } System.out.println( "Successfuly put blob " + blobId + " to " + successList + ", but failed in " + failureList + "\n"); if (successList.size() == replicaCount) { writer.write( "blobId|" + blobId.getID() + "|source|" + f.getAbsolutePath() + "|fileSize|" + f.length() + "|\n"); } // failed blobs are not written to the out file } catch (FileNotFoundException e) { System.out.println("File not found path : " + f.getAbsolutePath() + " exception : " + e); } catch (IOException e) { System.out.println("IOException when writing to migration log " + e); } finally { try { if (stream != null) { stream.close(); } } catch (Exception e) { System.out.println("Error while closing file stream " + e); } } } } } /** * Adding a blob to a particular server. * @param stream stream containing the actual blob * @param blobId blob id generated by ambry * @param replicaId replica to which the blob has to be added * @param correlationId coorelation id to uniquely identify the call * @return true if write succeeds, else false * @throws Exception */ private boolean writeToAmbryReplica(BlobProperties blobProperties, ByteBuffer userMetaData, InputStream stream, BlobId blobId, ReplicaId replicaId, AtomicInteger correlationId, boolean enableVerboseLogging) throws Exception { ArrayList<BlobId> blobIds = new ArrayList<BlobId>(); blobIds.add(blobId); ConnectedChannel blockingChannel = null; try { blockingChannel = connectionPool.checkOutConnection(replicaId.getDataNodeId().getHostname(), new Port(replicaId.getDataNodeId().getPort(), PortType.PLAINTEXT), 100000); int size = (int) blobProperties.getBlobSize(); ByteBufferInputStream blobStream = new ByteBufferInputStream(stream, size); PutRequest putRequest = new PutRequest(correlationId.incrementAndGet(), "consumerThread", blobId, blobProperties, userMetaData, blobStream.getByteBuffer(), size, BlobType.DataBlob, null); if (enableVerboseLogging) { System.out.println("Put Request to a replica : " + putRequest + " for blobId " + blobId); } PutResponse putResponse = getPutResponseFromStream(blockingChannel, putRequest, connectionPool); if (putResponse == null) { System.out.println("PutResponse to a replica " + replicaId + " failed with null Response for blobId " + blobId); blockingChannel = null; return false; } else { if (putResponse.getError() != ServerErrorCode.No_Error && putResponse.getError() != ServerErrorCode.Blob_Already_Exists) { System.out.println( "PutResponse to a replica " + replicaId + " failed with Error code " + putResponse.getError() + " for blobId " + blobId); return false; } return true; } } finally { if (stream != null) { stream.close(); } if (blockingChannel != null) { connectionPool.checkInConnection(blockingChannel); } } } /** * Method to send PutRequest and receive PutResponse to and from a blocking channel. If it fails, blocking channel is destroyed * * @param blockingChannel BlockingChannel used to send and receive request and response * @param putRequest PutRequest which has to be sent through the blockingchannel * @param connectionPool ConnectionPool from which connections are checked out * @return PutResponse the response from the PutRequest made */ private static PutResponse getPutResponseFromStream(ConnectedChannel blockingChannel, PutRequest putRequest, ConnectionPool connectionPool) { PutResponse putResponse = null; try { blockingChannel.send(putRequest); InputStream stream = blockingChannel.receive().getInputStream(); putResponse = PutResponse.readFrom(new DataInputStream(stream)); } catch (Exception exception) { connectionPool.destroyConnection(blockingChannel); System.out.println("Unknown Exception Error" + exception); return null; } return putResponse; } public static void main(String args[]) { FileWriter writer = null; try { OptionParser parser = new OptionParser(); ArgumentAcceptingOptionSpec<String> rootDirectoryOpt = parser.accepts("rootDirectory", "The root folder from which all the files will be migrated") .withRequiredArg() .describedAs("root_directory") .ofType(String.class); ArgumentAcceptingOptionSpec<String> hardwareLayoutOpt = parser.accepts("hardwareLayout", "The path of the hardware layout file") .withRequiredArg() .describedAs("hardware_layout") .ofType(String.class); ArgumentAcceptingOptionSpec<String> partitionLayoutOpt = parser.accepts("partitionLayout", "The path of the partition layout file") .withRequiredArg() .describedAs("partition_layout") .ofType(String.class); ArgumentAcceptingOptionSpec<Boolean> verboseLoggingOpt = parser.accepts("enableVerboseLogging", "Enables verbose logging") .withOptionalArg() .describedAs("Enable verbose logging") .ofType(Boolean.class) .defaultsTo(false); ArgumentAcceptingOptionSpec<String> partitionOpt = parser.accepts("partition", "The partition to which the put calls to be made against") .withRequiredArg() .describedAs("partition") .ofType(String.class); ArgumentAcceptingOptionSpec<String> datacenterOpt = parser.accepts("datacenter", "The datacenter to which the put calls to be made against") .withRequiredArg() .describedAs("datacenter") .ofType(String.class); ArgumentAcceptingOptionSpec<String> outFileOpt = parser.accepts("outFile", "The file to which output should be redirected") .withRequiredArg() .describedAs("outFile") .ofType(String.class); // Optional arguments for defining a specific node to write to. ArgumentAcceptingOptionSpec<String> nodeHostnameOpt = parser.accepts("nodeHostname", "The hostname of the node to put to (if specifying single node)") .withOptionalArg() .describedAs("nodeHostname") .ofType(String.class); ArgumentAcceptingOptionSpec<Integer> nodePortOpt = parser.accepts("nodePort", "The port of the node to put to (if specifying single node)") .withOptionalArg() .describedAs("nodePort") .ofType(Integer.class); OptionSet options = parser.parse(args); ArrayList<OptionSpec> listOpt = new ArrayList<>(); listOpt.add(rootDirectoryOpt); listOpt.add(hardwareLayoutOpt); listOpt.add(partitionLayoutOpt); listOpt.add(partitionOpt); listOpt.add(datacenterOpt); listOpt.add(outFileOpt); ToolUtils.ensureOrExit(listOpt, options, parser); System.out.println("Starting to parse arguments"); boolean enableVerboseLogging = options.has(verboseLoggingOpt); if (enableVerboseLogging) { System.out.println("Enabled verbose logging"); } String rootDirectory = options.valueOf(rootDirectoryOpt); if (enableVerboseLogging) { System.out.println("Parsed rootdir " + rootDirectory); } String hardwareLayoutPath = options.valueOf(hardwareLayoutOpt); if (enableVerboseLogging) { System.out.println("Parsed Hardware layout " + hardwareLayoutPath); } String partitionLayoutPath = options.valueOf(partitionLayoutOpt); if (enableVerboseLogging) { System.out.println("Parsed partition layout " + partitionLayoutPath); } String partition = options.valueOf(partitionOpt); if (enableVerboseLogging) { System.out.println("Parsed partition " + partition); } partition = "Partition[" + partition + "]"; String datacenter = options.valueOf(datacenterOpt); if (enableVerboseLogging) { System.out.println("Parsed datacenter " + datacenter); } String nodeHostname = options.valueOf(nodeHostnameOpt); if (enableVerboseLogging && nodeHostname != null) { System.out.println("Parsed node hostname " + nodeHostname); } Integer nodePort = options.valueOf(nodePortOpt); if (enableVerboseLogging && nodePort != null) { System.out.println("Parsed node port " + nodePort); } String outFile = options.valueOf(outFileOpt); if (enableVerboseLogging) { System.out.println("Parsed outFile " + outFile); System.out.println("Done parsing all args"); } VerifiableProperties vprops = new VerifiableProperties((new Properties())); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(vprops); ClusterMap map = ((ClusterAgentsFactory) Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, hardwareLayoutPath, partitionLayoutPath)).getClusterMap(); File logFile = new File(outFile); writer = new FileWriter(logFile); DirectoryUploader directoryUploader = new DirectoryUploader(); directoryUploader.setPartitionId(map, partition, enableVerboseLogging); if (nodeHostname != null && nodePort != null) { directoryUploader.setDataNodeId(map, nodeHostname, nodePort, enableVerboseLogging); } directoryUploader.walkDirectoryToCreateBlobs(rootDirectory, writer, datacenter, map.getLocalDatacenterId(), enableVerboseLogging); } catch (Exception e) { System.err.println("Error on exit " + e); } finally { if (writer != null) { try { writer.close(); } catch (Exception e) { System.out.println("Error when closing the writer"); } } } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.spi.block; import com.facebook.presto.spi.type.Type; import com.google.common.collect.ImmutableList; import io.airlift.slice.Slice; import it.unimi.dsi.fastutil.Hash.Strategy; import it.unimi.dsi.fastutil.objects.Object2LongOpenCustomHashMap; import org.testng.annotations.Test; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.TypeUtils.writeNativeValue; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static io.airlift.slice.Slices.utf8Slice; import static org.testng.Assert.assertEquals; public class TestBlockRetainedSizeBreakdown { private static final int EXPECTED_ENTRIES = 100; @Test public void testArrayBlock() { BlockBuilder arrayBlockBuilder = new ArrayBlockBuilder(BIGINT, new BlockBuilderStatus(), EXPECTED_ENTRIES); for (int i = 0; i < EXPECTED_ENTRIES; i++) { BlockBuilder arrayElementBuilder = arrayBlockBuilder.beginBlockEntry(); writeNativeValue(BIGINT, arrayElementBuilder, castIntegerToObject(i, BIGINT)); arrayBlockBuilder.closeEntry(); } checkRetainedSize(arrayBlockBuilder.build(), false); } @Test public void testByteArrayBlock() { BlockBuilder blockBuilder = new ByteArrayBlockBuilder(new BlockBuilderStatus(), EXPECTED_ENTRIES); for (int i = 0; i < EXPECTED_ENTRIES; i++) { blockBuilder.writeByte(i); } checkRetainedSize(blockBuilder.build(), false); } @Test public void testDictionaryBlock() { Block keyDictionaryBlock = createSliceArrayBlock(EXPECTED_ENTRIES); int[] keyIds = new int[EXPECTED_ENTRIES]; for (int i = 0; i < keyIds.length; i++) { keyIds[i] = i; } checkRetainedSize(new DictionaryBlock(EXPECTED_ENTRIES, keyDictionaryBlock, keyIds), false); } @Test public void testFixedWidthBlock() { BlockBuilder blockBuilder = new FixedWidthBlockBuilder(8, new BlockBuilderStatus(), EXPECTED_ENTRIES); writeEntries(EXPECTED_ENTRIES, blockBuilder, DOUBLE); checkRetainedSize(blockBuilder.build(), true); } @Test public void testIntArrayBlock() { BlockBuilder blockBuilder = new IntArrayBlockBuilder(new BlockBuilderStatus(), EXPECTED_ENTRIES); writeEntries(EXPECTED_ENTRIES, blockBuilder, INTEGER); checkRetainedSize(blockBuilder.build(), false); } @Test public void testInterleavedBlock() { BlockBuilder blockBuilder = new InterleavedBlockBuilder(ImmutableList.of(INTEGER, INTEGER), new BlockBuilderStatus(), EXPECTED_ENTRIES); writeEntries(EXPECTED_ENTRIES, blockBuilder, INTEGER); checkRetainedSize(blockBuilder.build(), false); } @Test public void testLongArrayBlock() { BlockBuilder blockBuilder = new LongArrayBlockBuilder(new BlockBuilderStatus(), EXPECTED_ENTRIES); writeEntries(EXPECTED_ENTRIES, blockBuilder, BIGINT); checkRetainedSize(blockBuilder.build(), false); } @Test public void testRunLengthEncodedBlock() { BlockBuilder blockBuilder = new LongArrayBlockBuilder(new BlockBuilderStatus(), 1); writeEntries(1, blockBuilder, BIGINT); checkRetainedSize(new RunLengthEncodedBlock(blockBuilder.build(), 1), false); } @Test public void testShortArrayBlock() { BlockBuilder blockBuilder = new ShortArrayBlockBuilder(new BlockBuilderStatus(), EXPECTED_ENTRIES); for (int i = 0; i < EXPECTED_ENTRIES; i++) { blockBuilder.writeShort(i); } checkRetainedSize(blockBuilder.build(), false); } @Test public void testSliceArrayBlock() { checkRetainedSize(createSliceArrayBlock(EXPECTED_ENTRIES), true); } @Test public void testVariableWidthBlock() { BlockBuilder blockBuilder = new VariableWidthBlockBuilder(new BlockBuilderStatus(), EXPECTED_ENTRIES, 4); writeEntries(EXPECTED_ENTRIES, blockBuilder, VARCHAR); checkRetainedSize(blockBuilder.build(), false); } private static final class ObjectStrategy implements Strategy<Object> { @Override public int hashCode(Object object) { return System.identityHashCode(object); } @Override public boolean equals(Object left, Object right) { return left == right; } } private static void checkRetainedSize(Block block, boolean getRegionCreateNewObjects) { AtomicLong objectSize = new AtomicLong(); Object2LongOpenCustomHashMap<Object> trackedObjects = new Object2LongOpenCustomHashMap<>(new ObjectStrategy()); BiConsumer<Object, Long> consumer = (object, size) -> { objectSize.addAndGet(size); trackedObjects.addTo(object, 1); }; block.retainedBytesForEachPart(consumer); assertEquals(objectSize.get(), block.getRetainedSizeInBytes()); Block copyBlock = block.getRegion(0, block.getPositionCount() / 2); copyBlock.retainedBytesForEachPart(consumer); assertEquals(objectSize.get(), block.getRetainedSizeInBytes() + copyBlock.getRetainedSizeInBytes()); assertEquals(trackedObjects.getLong(block), 1); assertEquals(trackedObjects.getLong(copyBlock), 1); trackedObjects.remove(block); trackedObjects.remove(copyBlock); for (long value : trackedObjects.values()) { assertEquals(value, getRegionCreateNewObjects ? 1 : 2); } } private static void writeEntries(int expectedEntries, BlockBuilder blockBuilder, Type type) { for (int i = 0; i < expectedEntries; i++) { writeNativeValue(type, blockBuilder, castIntegerToObject(i, type)); } } private static Object castIntegerToObject(int value, Type type) { if (type == INTEGER || type == TINYINT || type == BIGINT) { return (long) value; } if (type == VARCHAR) { return String.valueOf(value); } if (type == DOUBLE) { return (double) value; } throw new UnsupportedOperationException(); } private static Block createSliceArrayBlock(int entries) { Slice[] sliceArray = new Slice[entries]; for (int i = 0; i < entries; i++) { sliceArray[i] = utf8Slice(i + ""); } return new SliceArrayBlock(sliceArray.length, sliceArray); } }
package foundation.rpg.sample.language.ast; import foundation.rpg.parser.Element; import foundation.rpg.parser.UnexpectedInputException; // Generated token element wrapper for grammar parser. public class ElementGt implements Element<State> { private final foundation.rpg.common.symbols.Gt symbol; public ElementGt(foundation.rpg.common.symbols.Gt symbol) { this.symbol = symbol; } @Override public State accept(State state) throws UnexpectedInputException { return state.visitGt(symbol); } @Override public String toString() { return symbol.toString(); } }
package domain; public class FT { private String TID; private String FID; private int TC; public FT(){} public FT(String Fid, String Tid, int tc) { FID=Fid; TID=Tid; TC=tc; } public String getTID() { return TID; } public void setTID(String tID) { TID = tID; } public String getFID() { return FID; } public void setFID(String fID) { FID = fID; } public int getTC() { return TC; } public void setTC(int tc) { TC = tc; } }
package com.tvd12.ezyfox.codec; import java.nio.ByteBuffer; import java.util.Queue; public class MsgPackByteToObjectDecoder implements EzyByteToObjectDecoder { protected final EzyDefaultDecodeHandlers handlers; protected final EzyMessageDeserializer deserializer; public MsgPackByteToObjectDecoder( EzyMessageDeserializer deserializer, int maxSize) { this.deserializer = deserializer; this.handlers = EzyDefaultDecodeHandlers.builder() .maxSize(maxSize) .build(); } @Override public Object decode(EzyMessage message) throws Exception { return deserializer.deserialize(message.getContent()); } @Override public Object decode(EzyMessage message, byte[] decryptionKey) throws Exception { byte[] encryptedContent = message.getContent(); if(message.getHeader().isEncrypted()) encryptedContent = decryptMessageContent(encryptedContent, decryptionKey); return deserializer.deserialize(encryptedContent); } protected byte[] decryptMessageContent( byte[] content, byte[] decryptionKey) throws Exception { return content; } @Override public void decode(ByteBuffer bytes, Queue<EzyMessage> out) throws Exception { handlers.handle(bytes, out); } @Override public void reset() { handlers.reset(); } }
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.client.naming.beat; import com.alibaba.nacos.api.common.Constants; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.CommonParams; import com.alibaba.nacos.api.naming.NamingResponseCode; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.utils.NamingUtils; import com.alibaba.nacos.client.monitor.MetricsMonitor; import com.alibaba.nacos.client.naming.net.NamingProxy; import com.alibaba.nacos.client.naming.utils.UtilAndComs; import com.alibaba.nacos.common.lifecycle.Closeable; import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.common.utils.ThreadUtils; import com.fasterxml.jackson.databind.JsonNode; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER; /** * Beat reactor. * * @author harold */ public class BeatReactor implements Closeable { private final ScheduledExecutorService executorService; private final NamingProxy serverProxy; private boolean lightBeatEnabled = false; public final Map<String, BeatInfo> dom2Beat = new ConcurrentHashMap<String, BeatInfo>(); public BeatReactor(NamingProxy serverProxy) { this(serverProxy, UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT); } public BeatReactor(NamingProxy serverProxy, int threadCount) { this.serverProxy = serverProxy; this.executorService = new ScheduledThreadPoolExecutor(threadCount, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r); thread.setDaemon(true); thread.setName("com.alibaba.nacos.naming.beat.sender"); return thread; } }); } /** * Add beat information. * * @param serviceName service name * @param beatInfo beat information */ public void addBeatInfo(String serviceName, BeatInfo beatInfo) { NAMING_LOGGER.info("[BEAT] adding beat: {} to beat map.", beatInfo); String key = buildKey(serviceName, beatInfo.getIp(), beatInfo.getPort()); BeatInfo existBeat = null; //fix #1733 if ((existBeat = dom2Beat.remove(key)) != null) { existBeat.setStopped(true); } dom2Beat.put(key, beatInfo); executorService.schedule(new BeatTask(beatInfo), beatInfo.getPeriod(), TimeUnit.MILLISECONDS); MetricsMonitor.getDom2BeatSizeMonitor().set(dom2Beat.size()); } /** * Remove beat information. * * @param serviceName service name * @param ip ip of beat information * @param port port of beat information */ public void removeBeatInfo(String serviceName, String ip, int port) { NAMING_LOGGER.info("[BEAT] removing beat: {}:{}:{} from beat map.", serviceName, ip, port); BeatInfo beatInfo = dom2Beat.remove(buildKey(serviceName, ip, port)); if (beatInfo == null) { return; } beatInfo.setStopped(true); MetricsMonitor.getDom2BeatSizeMonitor().set(dom2Beat.size()); } /** * Build new beat information. * * @param instance instance * @return new beat information */ public BeatInfo buildBeatInfo(Instance instance) { return buildBeatInfo(instance.getServiceName(), instance); } /** * Build new beat information. * * @param groupedServiceName service name with group name, format: ${groupName}@@${serviceName} * @param instance instance * @return new beat information */ public BeatInfo buildBeatInfo(String groupedServiceName, Instance instance) { BeatInfo beatInfo = new BeatInfo(); beatInfo.setServiceName(groupedServiceName); beatInfo.setIp(instance.getIp()); beatInfo.setPort(instance.getPort()); beatInfo.setCluster(instance.getClusterName()); beatInfo.setWeight(instance.getWeight()); beatInfo.setMetadata(instance.getMetadata()); beatInfo.setScheduled(false); beatInfo.setPeriod(instance.getInstanceHeartBeatInterval()); return beatInfo; } public String buildKey(String serviceName, String ip, int port) { return serviceName + Constants.NAMING_INSTANCE_ID_SPLITTER + ip + Constants.NAMING_INSTANCE_ID_SPLITTER + port; } @Override public void shutdown() throws NacosException { String className = this.getClass().getName(); NAMING_LOGGER.info("{} do shutdown begin", className); ThreadUtils.shutdownThreadPool(executorService, NAMING_LOGGER); NAMING_LOGGER.info("{} do shutdown stop", className); } class BeatTask implements Runnable { BeatInfo beatInfo; public BeatTask(BeatInfo beatInfo) { this.beatInfo = beatInfo; } @Override public void run() { if (beatInfo.isStopped()) { return; } long nextTime = beatInfo.getPeriod(); try { JsonNode result = serverProxy.sendBeat(beatInfo, BeatReactor.this.lightBeatEnabled); long interval = result.get("clientBeatInterval").asLong(); boolean lightBeatEnabled = false; if (result.has(CommonParams.LIGHT_BEAT_ENABLED)) { lightBeatEnabled = result.get(CommonParams.LIGHT_BEAT_ENABLED).asBoolean(); } BeatReactor.this.lightBeatEnabled = lightBeatEnabled; if (interval > 0) { nextTime = interval; } int code = NamingResponseCode.OK; if (result.has(CommonParams.CODE)) { code = result.get(CommonParams.CODE).asInt(); } if (code == NamingResponseCode.RESOURCE_NOT_FOUND) { Instance instance = new Instance(); instance.setPort(beatInfo.getPort()); instance.setIp(beatInfo.getIp()); instance.setWeight(beatInfo.getWeight()); instance.setMetadata(beatInfo.getMetadata()); instance.setClusterName(beatInfo.getCluster()); instance.setServiceName(beatInfo.getServiceName()); instance.setInstanceId(instance.getInstanceId()); instance.setEphemeral(true); try { serverProxy.registerService(beatInfo.getServiceName(), NamingUtils.getGroupName(beatInfo.getServiceName()), instance); } catch (Exception ignore) { } } } catch (NacosException ex) { NAMING_LOGGER.error("[CLIENT-BEAT] failed to send beat: {}, code: {}, msg: {}", JacksonUtils.toJson(beatInfo), ex.getErrCode(), ex.getErrMsg()); } //嵌套执行调度任务 executorService.schedule(new BeatTask(beatInfo), nextTime, TimeUnit.MILLISECONDS); } } }
package seedu.address.logic.parser; import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.HashSet; import java.util.Set; import seedu.address.commons.core.index.Index; import seedu.address.commons.util.StringUtil; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.book.Cost; import seedu.address.model.book.Isbn; import seedu.address.model.book.Name; import seedu.address.model.book.Price; import seedu.address.model.book.Quantity; import seedu.address.model.tag.Tag; /** * Contains utility methods used for parsing strings in the various *Parser classes. */ public class ParserUtil { public static final String MESSAGE_INVALID_INDEX = "Index is not a non-zero unsigned integer."; /** * Parses {@code oneBasedIndex} into an {@code Index} and returns it. Leading and trailing whitespaces will be * trimmed. * @throws ParseException if the specified index is invalid (not non-zero unsigned integer). */ public static Index parseIndex(String oneBasedIndex) throws ParseException { String trimmedIndex = oneBasedIndex.trim(); if (!StringUtil.isNonZeroUnsignedInteger(trimmedIndex)) { throw new ParseException(MESSAGE_INVALID_INDEX); } return Index.fromOneBased(Integer.parseInt(trimmedIndex)); } /** * Parses a {@code String name} into a {@code Name}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code name} is invalid. */ public static Name parseName(String name) throws ParseException { requireNonNull(name); String trimmedName = name.trim(); if (!Name.isValidName(trimmedName)) { throw new ParseException(Name.MESSAGE_NAME_CONSTRAINTS); } return new Name(trimmedName); } /** * Parses a {@code String phone} into a {@code Isbn}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code isbn} is invalid. */ public static Isbn parseIsbn(String isbn) throws ParseException { requireNonNull(isbn); String trimmedIsbn = isbn.trim(); if (!Isbn.isValidIsbn(trimmedIsbn)) { throw new ParseException(Isbn.MESSAGE_ISBN_CONSTRAINTS); } return new Isbn(trimmedIsbn); } /** * Parses a {@code String quantity} into an {@code Quantity}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code quantity} is invalid. */ public static Quantity parseQuantity(String quantity) throws ParseException { requireNonNull(quantity); String trimmedQuantity = quantity.trim(); if (!Quantity.isValidQuantity(trimmedQuantity)) { throw new ParseException(Quantity.MESSAGE_QUANTITY_CONSTRAINTS); } return new Quantity(trimmedQuantity); } /** * Parses a {@code String price} into an {@code Price}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code price} is invalid. */ public static Price parsePrice(String price) throws ParseException { requireNonNull(price); String trimmedPrice = price.trim(); if (!Price.isValidPrice(trimmedPrice)) { throw new ParseException(Price.MESSAGE_PRICE_CONSTRAINTS); } return new Price(trimmedPrice); } /** * Parses a {@code String cost} into an {@code Cost}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code cost} is invalid. */ public static Cost parseCost(String cost) throws ParseException { requireNonNull(cost); String trimmedCost = cost.trim(); if (!Cost.isValidCost(trimmedCost)) { throw new ParseException(Cost.MESSAGE_COST_CONSTRAINTS); } return new Cost(trimmedCost); } /** * Parses a {@code String tag} into a {@code Tag}. * Leading and trailing whitespaces will be trimmed. * * @throws ParseException if the given {@code tag} is invalid. */ public static Tag parseTag(String tag) throws ParseException { requireNonNull(tag); String trimmedTag = tag.trim(); if (!Tag.isValidTagName(trimmedTag)) { throw new ParseException(Tag.MESSAGE_TAG_CONSTRAINTS); } return new Tag(trimmedTag); } /** * Parses {@code Collection<String> tags} into a {@code Set<Tag>}. */ public static Set<Tag> parseTags(Collection<String> tags) throws ParseException { requireNonNull(tags); final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(parseTag(tagName)); } return tagSet; } }
// SPDX-License-Identifier: Apache-2.0 // Copyright Contributors to the OpenTimelineIO Project. package io.opentimeline.opentimelineio; import io.opentimeline.opentime.TimeRange; import io.opentimeline.opentimelineio.exception.OpenTimelineIOException; import java.util.List; public class Algorithms { /** * Flatten a Stack, into a single Track. * Note that the 1st Track is the bottom one, and the last is the top. * * @param inStack stack to flatten * @return flattened track */ public native Track flattenStack(Stack inStack) throws OpenTimelineIOException; /** * Flatten a Stack, into a single Track. * Note that the 1st Track is the bottom one, and the last is the top. * * @param tracks list of tracks to flatten * @return flattened track */ public Track flattenStack(List<Track> tracks) throws OpenTimelineIOException{ Track[] trackArray = new Track[tracks.size()]; trackArray = tracks.toArray(trackArray); return flattenStackNative(trackArray); } private native Track flattenStackNative(Track[] tracks) throws OpenTimelineIOException; /** * Returns a new track that is a copy of the inTrack, but with items * outside the trimRange removed and items on the ends trimmed to the * trimRange. Note that the track is never expanded, only shortened. * Please note that you could do nearly the same thing non-destructively by * just setting the Track's source_range but sometimes you want to really cut * away the stuff outside and that's what this function is meant for. * * @param inTrack track to be trimmed * @param trimRange this is the range, which the track will be trimmed to * @return trimmed track */ public native Track trackTrimmedToRange(Track inTrack, TimeRange trimRange) throws OpenTimelineIOException; /** * Returns a new timeline that is a copy of the inTimeline, but with items * outside the trimRange removed and items on the ends trimmed to the * trimRange. Note that the timeline is never expanded, only shortened. * Please note that you could do nearly the same thing non-destructively by * just setting the Track's sourceRange but sometimes you want to really cut * away the stuff outside and that's what this function is meant for. * * @param inTimeline timeline to be trimmed * @param trimRange this is the range, which the timeline will be trimmed to * @return trimmed timeline */ public Timeline timelineTrimmedToRange(Timeline inTimeline, TimeRange trimRange) throws OpenTimelineIOException { Timeline newTimeline = (Timeline) inTimeline.deepCopy(); Stack stack = inTimeline.getTracks(); Stack newStack = newTimeline.getTracks(); List<Composable> tracks = stack.getChildren(); for (int i = 0; i < tracks.size(); i++) { Track trimmedTrack = this.trackTrimmedToRange((Track) tracks.get(i), trimRange); newStack.setChild(i, trimmedTrack); } return newTimeline; } }
package com.example.demo.infrastructure.scalars; import com.netflix.graphql.dgs.DgsComponent; import com.netflix.graphql.dgs.DgsRuntimeWiring; import graphql.scalars.ExtendedScalars; import graphql.schema.idl.RuntimeWiring; /** * graphql-java provides optional scalars in the graphql-java-extended-scalars library. * We can wire a scalar from this library by adding the scalar to the RuntimeWiring. */ @DgsComponent public class DateTimeScalar { @DgsRuntimeWiring public RuntimeWiring.Builder addScalar(RuntimeWiring.Builder builder) { return builder.scalar(ExtendedScalars.DateTime); } }
package ca.weblite.objc; import ca.weblite.nativeutils.NativeUtils; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.Union; import com.sun.jna.ptr.ByReference; import com.sun.jna.ptr.ByteByReference; import com.sun.jna.ptr.DoubleByReference; import com.sun.jna.ptr.FloatByReference; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.ptr.ShortByReference; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.BitSet; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * A Java class with static methods that interact with the Objective-C runtime. * These methods wrap the *very* low level methods provided by the Runtime class * to provide a slightly higher level of abstraction. * * <p>It is helpful to perform a static import of the methods in this class if you * will be using the objc runtime library, as it contains many utility methods * to deal with Objective-C primitives. E.g. the cls() method can return the * Pointer to a class given its name. The clsName() returns the name of the * class specified by a Pointer(). </p> * * <p>There are also many variants of the msg() method for sendng messages to * objects in the Objective-C runtime.</p> * * @author shannah * @see <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html">Objective-C Runtime Reference</a> * @version $Id: $Id * @since 1.1 */ public class RuntimeUtils { /** * Short reference to the runtime instance for interacting with Objective-C */ public static Runtime rt = Runtime.INSTANCE; /** * Flag to indicate whether the jcocoa native library was loaded successfully. * If it fails to load, then this flag will be false. Therefore, if this * flag is false, you shouldn't try to use the the api at all. */ public static boolean loaded = false; static { String jnaNosys = System.getProperty("jna.nosys", "true"); try { if (! Boolean.parseBoolean(jnaNosys)) System.loadLibrary("jcocoa"); else NativeUtils.loadLibraryFromJar("/libjcocoa.dylib"); loaded = true; } catch (UnsatisfiedLinkError err){ err.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } init(); } /** * Returns a pointer to the class for specific class name. * <pre> * {@code * Pointer nsObject = cls("NSObject"); * }</pre> * * @param name The name of the class to retrieve. * @return The pointer to the class structure. */ public static Pointer cls(String name){ return rt.objc_lookUpClass(name); } /** * Returns a pointer to a class given a Peerable object which wraps * the pointer. Effectively this just calls peer.getPeer() and * returns its value. A convenience method. * * @param peer The peer object that is wrapping the Objective-C class * object. * @return A Pointer to the Objective-C class. */ public static Pointer cls(Peerable peer){ return peer.getPeer(); } /** * Returns the name of an objective C class specified by the given class pointer. * * @param cls The pointer to the class whose name we wish to retrieve. * @return The name of the class. * @see Runtime#class_getName(Pointer) */ public static String clsName(Pointer cls){ return rt.class_getName(cls); } /** * A wrapper for the clsName() method given a Peerable object that wraps * the class pointer. This will return the class name. * * @param peer a {@link ca.weblite.objc.Peerable} object. * @see Runtime#class_getName(Pointer) * @return a {@link java.lang.String} object. */ public static String clsName(Peerable peer){ return clsName(peer.getPeer()); } /** * Returns a pointer to the selector specified by the given selector name. * * @param name a {@link java.lang.String} object. * @return Pointer to an Objective-C message selector. * @see <a href="http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocSelectors.html">Objective-C Selectors Reference</a> */ public static Pointer sel(String name){ return rt.sel_getUid(name); } /** * Returns a pointer to the selector that is wrapped by a Peerable object. * * @param peer a {@link ca.weblite.objc.Peerable} object. * @return Pointer to a specified selector. */ public static Pointer sel(Peerable peer){ return peer.getPeer(); } /** * Returns the name of a selector. * * @param sel Pointer to a selector. * @return The name of the selector. */ public static String selName(Pointer sel){ return rt.sel_getName(sel); } /** * Returns the name of a selector. * * @return The name of the selector. * @param peer a {@link ca.weblite.objc.Peerable} object. */ public static String selName(Peerable peer){ return selName(peer.getPeer()); } /** * Sends a message to a specified class using the given selector. * * @param cls The name of the class. * @param msg The name of the selector. * @param args The arguments passed to the method. These are passed raw * and will not be coerced. * @return The result of the message. This may be a pointer, if the message * returns a pointer, or a value, if the method returns a BOOL, long, int, * short, byte, or char. Note that you cannot use this method for * messages that return float and double values. For these, you <em>must</em> * use msgDouble(). This is because doubles and floats are handled using * a different underlying runtime function (objc_msgSend_fpret). Alternatively * you can use the variation of msg() that takes coerceInput and coerceOutput * boolean values, as this will automatically choose the correct underlying * message function depending on the return type reported by the message * signature. * @see #msgDouble(String, String, Object...) */ public static long msg(String cls, String msg, Object... args){ return msg(cls(cls), msg, args); } /** * Sends a message to a specified class using the given selector. * * @param cls The name of the class. * @param msg The name of the selector. * @param args The arguments passed to the method. These are passed raw * and will not be coerced. * @return The result of the message. This may be a pointer, if the message * returns a pointer, or a value, if the method returns a BOOL, long, int, * short, byte, or char. Note that you cannot use this method for * messages that return float and double values. For these, you <em>must</em> * use msgDouble(). This is because doubles and floats are handled using * a different underlying runtime function (objc_msgSend_fpret). Alternatively * you can use the variation of msg() that takes coerceInput and coerceOutput * boolean values, as this will automatically choose the correct underlying * message function depending on the return type reported by the message * signature. * @see #msgDouble(String, Pointer, Object...) */ public static long msg(String cls, Pointer msg, Object... args){ return msg(cls(cls), msg, args); } /** * Sends a message to a specified class using the given selector. * * @param msg The name of the selector. * @param args The arguments passed to the method. These are passed raw * and will not be coerced. * @return The result of the message. This may be a pointer, if the message * returns a pointer, or a value, if the method returns a BOOL, long, int, * short, byte, or char. Note that you cannot use this method for * messages that return float and double values. For these, you <em>must</em> * use msgDouble(). This is because doubles and floats are handled using * a different underlying runtime function (objc_msgSend_fpret). Alternatively * you can use the variation of msg() that takes coerceInput and coerceOutput * boolean values, as this will automatically choose the correct underlying * message function depending on the return type reported by the message * signature. * @see #msgDouble(Pointer, String, Object...) * @param receiver a {@link com.sun.jna.Pointer} object. */ public static long msg(Pointer receiver, String msg, Object... args){ return rt.objc_msgSend(receiver, sel(msg), args); } /** * Sends a message to a specified class using the given selector. * * @param args The arguments passed to the method. These are passed raw * and will not be coerced. * @return The result of the message. This may be a pointer, if the message * returns a pointer, or a value, if the method returns a BOOL, long, int, * short, byte, or char. Note that you cannot use this method for * messages that return float and double values. For these, you <em>must</em> * use msgDouble(). This is because doubles and floats are handled using * a different underlying runtime function (objc_msgSend_fpret). Alternatively * you can use the variation of msg() that takes coerceInput and coerceOutput * boolean values, as this will automatically choose the correct underlying * message function depending on the return type reported by the message * signature. * @see #msgDouble(Pointer, Pointer, Object...) * @param receiver a {@link com.sun.jna.Pointer} object. * @param selector a {@link com.sun.jna.Pointer} object. */ public static long msg(Pointer receiver, Pointer selector, Object... args){ return rt.objc_msgSend(receiver, selector, args); } /** * Wrapper around msg() that returns a Pointer. This should only be used for * sending messages that return Pointers (or Objects). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return A Pointer return value of the message. */ public static Pointer msgPointer(Pointer receiver, Pointer selector, Object... args){ long res = msg(receiver, selector, args); return new Pointer(res); } /** * Wrapper around msg() that returns a Pointer. This should only be used for * sending messages that return Pointers (or Objects). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return A Pointer return value of the message. */ public static Pointer msgPointer(Pointer receiver, String selector, Object... args){ return msgPointer(receiver, sel(selector), args); } /** * Wrapper around msg() that returns a Pointer. This should only be used for * sending messages that return Pointers (or Objects). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return A Pointer return value of the message. */ public static Pointer msgPointer(String receiver, Pointer selector, Object... args){ return msgPointer(cls(receiver), selector, args); } /** * Wrapper around msg() that returns a Pointer. This should only be used for * sending messages that return Pointers (or Objects). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return A Pointer return value of the message. */ public static Pointer msgPointer(String receiver, String selector, Object... args){ return msgPointer(cls(receiver), sel(selector), args); } /** * Wrapper around msg() that returns an int. This should only be used for * sending messages that return int-compatible numeric values. E.g. * byte, bool, long, int, short. Do not use this if the message will return * something else (like a float, double, string, or pointer). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return An int value returned by the message. */ public static int msgInt(Pointer receiver, Pointer selector, Object... args){ long res = msg(receiver, selector, args); return new Long(res).intValue(); } /** * Wrapper around msg() that returns an int. This should only be used for * sending messages that return int-compatible numeric values. E.g. * byte, bool, long, int, short. Do not use this if the message will return * something else (like a float, double, string, or pointer). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return An int value returned by the message. */ public static int msgInt(String receiver, Pointer selector, Object... args){ return msgInt(cls(receiver), selector, args); } /** * Wrapper around msg() that returns an int. This should only be used for * sending messages that return int-compatible numeric values. E.g. * byte, bool, long, int, short. Do not use this if the message will return * something else (like a float, double, string, or pointer). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return An int value returned by the message. */ public static int msgInt(String receiver, String selector, Object... args){ return msgInt(cls(receiver), sel(selector), args); } /** * Wrapper around msg() that returns an int. This should only be used for * sending messages that return int-compatible numeric values. E.g. * byte, bool, long, int, short. Do not use this if the message will return * something else (like a float, double, string, or pointer). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return An int value returned by the message. */ public static int msgInt(Pointer receiver, String selector, Object... args){ return msgInt(receiver, sel(selector), args); } /** * Wrapper around msg() that returns a boolean value. This should only be used * for sending messages that return boolean-compatible numeric values. Essentially * any non-zero value is interpreted (and returned) as true. Zero values are * interpreted as false. * * @param receiver The target of the message. * @param selector The selector for the message. * @param args Arguments passed to the message. * @return Boolean return value of the message. */ public static boolean msgBoolean(Pointer receiver, Pointer selector, Object... args){ long res = msg(receiver, selector, args); return res > 0L ? true : false; } /** * Wrapper around msg() that returns a boolean value. This should only be used * for sending messages that return boolean-compatible numeric values. Essentially * any non-zero value is interpreted (and returned) as true. Zero values are * interpreted as false. * * @param receiver The target of the message. * @param selector The selector for the message. * @param args Arguments passed to the message. * @return Boolean return value of the message. */ public static boolean msgBoolean(String receiver, Pointer selector, Object... args){ return msgBoolean(cls(receiver), selector, args); } /** * Wrapper around msg() that returns a boolean value. This should only be used * for sending messages that return boolean-compatible numeric values. Essentially * any non-zero value is interpreted (and returned) as true. Zero values are * interpreted as false. * * @param receiver The target of the message. * @param selector The selector for the message. * @param args Arguments passed to the message. * @return Boolean return value of the message. */ public static boolean msgBoolean(String receiver, String selector, Object... args){ return msgBoolean(cls(receiver), sel(selector), args); } /** * Wrapper around msg() that returns a boolean value. This should only be used * for sending messages that return boolean-compatible numeric values. Essentially * any non-zero value is interpreted (and returned) as true. Zero values are * interpreted as false. * * @param receiver The target of the message. * @param selector The selector for the message. * @param args Arguments passed to the message. * @return Boolean return value of the message. */ public static boolean msgBoolean(Pointer receiver, String selector, Object... args){ return msgBoolean(receiver, sel(selector), args); } /** * Wrapper around msg() that returns a string value. This should only be used * for messages that return a CString. Do not use this for messages that * return numeric values or Pointers to objects (e.g. NSString). Use the * msg() variant that takes coerceInputs and coerceOutputs parameters if you * want NSStrings to be automatically converted to java Strings. * * @param receiver The target of the message. * @param selector The selector for the message. * @param args Arguments passed to the message. * @return The string return value of the message. */ public static String msgString(Pointer receiver, Pointer selector, Object... args){ long res = msg(receiver, selector, args); return new Pointer(res).getString(0); } /** * Wrapper around msg() that returns a string value. This should only be used * for messages that return a CString. Do not use this for messages that * return numeric values or Pointers to objects (e.g. NSString). Use the * msg() variant that takes coerceInputs and coerceOutputs parameters if you * want NSStrings to be automatically converted to java Strings. * * @param receiver The target of the message. * @param selector The selector for the message. * @param args Arguments passed to the message. * @return The string return value of the message. */ public static String msgString(String receiver, Pointer selector, Object... args){ return msgString(cls(receiver), selector, args); } /** * Wrapper around msg() that returns a string value. This should only be used * for messages that return a CString. Do not use this for messages that * return numeric values or Pointers to objects (e.g. NSString). Use the * msg() variant that takes coerceInputs and coerceOutputs parameters if you * want NSStrings to be automatically converted to java Strings. * * @param receiver The target of the message. * @param selector The selector for the message. * @param args Arguments passed to the message. * @return The string return value of the message. */ public static String msgString(String receiver, String selector, Object... args){ return msgString(cls(receiver), sel(selector), args); } /** * Wrapper around msg() that returns a string value. This should only be used * for messages that return a CString. Do not use this for messages that * return numeric values or Pointers to objects (e.g. NSString). Use the * msg() variant that takes coerceInputs and coerceOutputs parameters if you * want NSStrings to be automatically converted to java Strings. * * @param receiver The target of the message. * @param selector The selector for the message. * @param args Arguments passed to the message. * @return The string return value of the message. */ public static String msgString(Pointer receiver, String selector, Object... args){ return msgString(receiver, sel(selector), args); } /** * Sends a message that returns a double value. This variant must be used * if the method returns a float or a double. It doesn't actually wrap the * primitive msg() method.. Rather it uses a different core Objective-C method, * objc_msgSend_fpret(). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return The double return value of the message */ public static double msgDouble(Pointer receiver, Pointer selector, Object... args){ return rt.objc_msgSend_fpret(receiver, selector, args); } /** * Sends a message that returns a double value. This variant must be used * if the method returns a float or a double. It doesn't actually wrap the * primitive msg() method.. Rather it uses a different core Objective-C method, * objc_msgSend_fpret(). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return The double return value of the message */ public static double msgDouble(String receiver, Pointer selector, Object... args){ return msgDouble(cls(receiver), selector, args); } /** * Sends a message that returns a double value. This variant must be used * if the method returns a float or a double. It doesn't actually wrap the * primitive msg() method.. Rather it uses a different core Objective-C method, * objc_msgSend_fpret(). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return The double return value of the message */ public static double msgDouble(String receiver, String selector, Object... args){ return msgDouble(cls(receiver), sel(selector), args); } /** * Sends a message that returns a double value. This variant must be used * if the method returns a float or a double. It doesn't actually wrap the * primitive msg() method.. Rather it uses a different core Objective-C method, * objc_msgSend_fpret(). * * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments passed to the message. * @return The double return value of the message */ public static double msgDouble(Pointer receiver, String selector, Object... args){ return msgDouble(receiver, sel(selector), args); } /** * Sends a message with the option of coercing the inputs and outputs. This variant * uses a higher level of abstraction than the standard msg() and msgXXX() methods. * If coerceReturn and coerceArgs are set to true, then this method will * convert the inputs from Java inputs to the corresponding Objective-C inputs. * Further it will return values that are more appropriate for use in Java. * * <p>Furthermore, this variant is smart about which variable of msg() to call * behind the scenes. E.g. if the message signature specifies that this message * returns a double, it will automatically use the double variant of msg().</p> * * @param coerceReturn If true, then the return value will be mapped to an appropriate * Java value using the TypeMapper class. * @param coerceArgs If true, then the inputs will be mapped from Java to appropriate * C values using the TypeMapper class. * @param receiver The target of the message. * @param selector The selector for the message. * @param args The arguments to be passed in the message. * @return The return value of the message. This may be a Pointer or a value depending * on the return type of the message. */ public static Object msg(boolean coerceReturn, boolean coerceArgs, Pointer receiver, Pointer selector, Object... args){ Object[] originalArgs = args; Pointer methodSignature = msgPointer(receiver, "methodSignatureForSelector:", selector); int numArgs = (int)msg(methodSignature, "numberOfArguments"); if ( numArgs ==2 && numArgs != args.length+2 ){ throw new RuntimeException("Wrong argument count. The selector "+selName(selector)+" requires "+(numArgs-2)+" arguments, but received "+args.length); } long returnTypePtr = msg(methodSignature, "methodReturnType"); String returnTypeSignature = new Pointer(returnTypePtr).getString(0); if ( numArgs == 0 && returnTypeSignature == null ){ return msg(receiver, selector, args); } if ( coerceArgs && args.length > 0 ){ originalArgs = Arrays.copyOf(args, args.length); for ( int i=0; i<args.length; i++ ){ ByteByReference out = new ByteByReference(); long out2 = (long)msg(methodSignature, "getArgumentTypeAtIndex:", i+2); String argumentTypeSignature = new Pointer(out2).getString(0); args[i] = TypeMapper.getInstance().jToC(args[i], argumentTypeSignature, TypeMapper.getInstance()); } } String prefixes = "rnNoORV"; int offset = 0; while ( prefixes.indexOf(returnTypeSignature.charAt(offset)) != -1 ){ offset++; if ( offset > returnTypeSignature.length()-1 ){ break; } } if ( offset > 0 ){ returnTypeSignature = returnTypeSignature.substring(offset); } String returnTypeFirstChar = returnTypeSignature.substring(0,1); if ( "[{(".indexOf(returnTypeFirstChar) ==-1 ){ // We are not returning a structure so we'll just // do the message. // We need to handle doubles and floats separately if ( "df".indexOf(returnTypeFirstChar) != -1 ){ Object res = msgDouble(receiver, selector, args); for ( int i=0; i<args.length; i++){ Proxy.release(args[i]); } return res; } else { long result = msg(receiver, selector, args); if ( coerceReturn ){ Object res2 = TypeMapper.getInstance().cToJ(result, returnTypeSignature, TypeMapper.getInstance()); for ( int i=0; i<args.length; i++){ Proxy.release(args[i]); } return res2; } else { for ( int i=0; i<args.length; i++){ Proxy.release(args[i]); } return result; } } } Object output = msg(receiver, selector, args); for ( int i=0; i<args.length; i++){ Proxy.release(args[i]); } return output; } /** * Returns the size of an array that is specified in a signature. * * @param signature The signature for a parameter using <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html">Objective-C type encodings</a>. * @return The size of the array. * @see <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html">Objective-C Type Encodings</a> */ public static int arraySize(String signature){ int typeIndex = 2; String digits = "0123456789"; while ( digits.indexOf(signature.charAt(typeIndex++)) != -1 ){} return Integer.parseInt(signature.substring(1, typeIndex)); } /** * Returns the pointer to the Native peer for a Peerable object. * * @param peer a {@link ca.weblite.objc.Peerable} object. * @return The Pointer to a native peer. */ public static Pointer addr(Peerable peer){ return peer.getPeer(); } /** * Sends a batch of messages in sequence. * * @param messages a {@link ca.weblite.objc.Message} object. * @return a {@link java.lang.Object} object. */ public static Object msg(Message... messages){ for ( int i=0; i<messages.length; i++){ if ( i>0 ){ messages[i].previous = messages[i-1]; } if ( i< messages.length-1 ){ messages[i].next = messages[i+1]; } } for ( int i=0; i<messages.length; i++){ Message m = messages[i]; if ( m.receiver == Pointer.NULL ){ m.receiver = (Pointer)m.previous.result; } m.beforeRequest(); if ( m.status == Message.STATUS_SKIPPED ){ continue; } else if ( m.status == Message.STATUS_CANCELLED){ break; } else { boolean coerceInput = false; boolean coerceOutput = false; if ( i == messages.length -1 ){ coerceInput = m.coerceInput; coerceOutput = m.coerceOutput; } try { m.result = msg(coerceOutput, coerceInput, m.receiver, m.selector, m.args.toArray(new Object[m.args.size()])); } catch (Exception ex){ m.error = ex; } m.status = Message.STATUS_COMPLETED; } } if ( messages.length > 0 ){ return messages[messages.length-1].result; } else { throw new RuntimeException("Message queue was empty"); } } /** * Converts a Java string to an NSString object. * * @param str The Java string to convert. * @return Pointer to the NSString that corresponds to this string. */ public static Pointer str(String str){ return msgPointer("NSString", "stringWithUTF8String:", str); } /** * Converts A native NSString object to a Java string. * * @param str a {@link com.sun.jna.Pointer} object. * @return A Java string. */ public static String str(Pointer str){ long ptr = msg(str, "UTF8String"); return new Pointer(ptr).getString(0); } /** * Wraps the given value in the appropriate ByReference subclass according * to the provided signature. This is a useful method in cases where * you need to pass a parameter to a C-function by reference, but you don't * necessarily know what type of data it is. * * @param val The value to be wrapped in a byReference. * @param signature The signature (using <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html">Objective-C type encodings</a>) of the value. * @return A pointer to the reference that can be passed in a C function. * @see <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html">Objective-C Type Encodings</a> */ public static Pointer getAsReference(Object val, String signature){ return getAsReferenceWrapper(val, signature).getPointer(); } /** * Wraps the given value in the appropriate ByReference subclass according * to the provided signature. This is a useful method in cases where * you need to pass a parameter to a C-function by reference, but you don't * necessarily know what type of data it is. * * @param val The value to be wrapped in a byReference. * @param signature The signature (using <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html">Objective-C type encodings</a>) of the value. * @return The ByReference object that contains the pointer that can be passed * to a c function. * @see <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html">Objective-C Type Encodings</a> */ public static ByReference getAsReferenceWrapper(Object val, String signature){ String prefixes = "rnNoORV"; int offset = 0; while ( prefixes.indexOf(signature.charAt(offset)) != -1 ){ offset++; if ( offset > signature.length()-1 ){ break; } } if ( offset > 0 ){ signature = signature.substring(offset); } String firstChar = signature.substring(0,1); String numeric = "iIsSlLqQfd"; //String firstChar = signature.substring(0,1); switch ( signature.charAt(0)){ case 'i': case 'I': if ( !int.class.isInstance(val) ){ if ( Number.class.isInstance(val) ){ val = ((Number)val).intValue(); } else if ( String.class.isInstance(val)){ val = Integer.parseInt((String)val); } else { throw new RuntimeException("Attempt to pass ineligible value to int: "+val); } } return new IntByReference((Integer)val); case 's': case 'S': if ( !short.class.isInstance(val) ){ if ( Number.class.isInstance(val) ){ val = ((Number)val).shortValue(); } else if ( String.class.isInstance(val)){ val = new Integer(Integer.parseInt((String)val)).shortValue(); } else { throw new RuntimeException("Attempt to pass ineligible value to short: "+val); } } return new ShortByReference((Short)val); case 'l': case 'L': case 'q': case 'Q': if ( !long.class.isInstance(val) ){ if ( Number.class.isInstance(val) ){ val = ((Number)val).longValue(); } else if ( String.class.isInstance(val)){ val = new Long(Long.parseLong((String)val)).longValue(); } else { throw new RuntimeException("Attempt to pass ineligible value to long: "+val); } } return new LongByReference((Long)val); case 'f': if ( !float.class.isInstance(val) ){ if ( Number.class.isInstance(val) ){ val = ((Number)val).floatValue(); } else if ( String.class.isInstance(val)){ val = new Float(Float.parseFloat((String)val)).floatValue(); } else { throw new RuntimeException("Attempt to pass ineligible value to long: "+val); } } return new FloatByReference((Float)val); case 'd': if ( !double.class.isInstance(val) ){ if ( Number.class.isInstance(val) ){ val = ((Number)val).doubleValue(); } else if ( String.class.isInstance(val)){ val = new Double(Double.parseDouble((String)val)).doubleValue(); } else { throw new RuntimeException("Attempt to pass ineligible value to long: "+val); } } return new DoubleByReference((Double)val); case 'B': case 'b': case 'c': case 'C': if (Boolean.class.isInstance(val)) { val = (byte) (Boolean.TRUE.equals(val) ? 1 : 0); } else if (Number.class.isInstance(val)) { val = ((Number) val).byteValue(); } else if (String.class.isInstance(val)) { val = new Byte(Byte.parseByte((String) val)).byteValue(); } else { throw new RuntimeException("Attempt to pass ineligible value to byte: " + val); } return new ByteByReference((Byte) val); case 'v': return null; case '^': default: ////System.out.println("Outputting pointer by reference for value "+val+" and signature "+signature); if ( val == null ){ try { throw new RuntimeException("Checking stack trace for val "+val+" and signature "+signature); } catch (Exception ex){ ex.printStackTrace(System.err); } } if ( Pointer.class.isInstance(val) ){ return new PointerByReference((Pointer)val); } else if ( Long.class.isInstance(val) || long.class.isInstance(val)){ return new PointerByReference(new Pointer((Long)val)); } else { throw new RuntimeException("Don't know what to do for conversion of value "+val+" and signature "+signature); } } } /** * Initializes the libjcocoa library. This is called when the class is first * loaded. It sets up the JNI environment that will be used there forward. */ public static native void init(); /** * Registers a Java object with the Objective-C runtime so that it can begin * to receive messages from it. This will create an Objective-C proxy * that passes messages to the Recipient object. This step is automatically * handled by the NSObject class inside its init() method. * * @param client a {@link ca.weblite.objc.Recipient} object. * @return a long. */ public static native long createProxy(Recipient client); /** * Returns the Java peer recipient for a native Objective-C object if it * exists. This will return null if nsObject is not an WLProxy object * that has been previously registered with a Recipient. * * @param nsObject a long. * @return a {@link ca.weblite.objc.Recipient} object. */ public static native Recipient getJavaPeer(long nsObject); }
/* * Copyright (c) 2002-2021 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.javascript.regexp.mozilla.js1_2; import org.junit.Test; import org.junit.runner.RunWith; import com.gargoylesoftware.htmlunit.BrowserRunner; import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts; import com.gargoylesoftware.htmlunit.WebDriverTestCase; /** * Tests originally in '/js/src/tests/js1_2/regexp/hexadecimal.js'. * * @author Ahmed Ashour */ @RunWith(BrowserRunner.class) public class HexadecimalTest extends WebDriverTestCase { /** * Tests testString.match(new RegExp(testPattern)). * @throws Exception if the test fails */ @Test @Alerts("ABCDEFGHIJKLMNOPQRSTUVWXYZ") public void test1() throws Exception { final String initialScript = "testPattern = '\\\\x41\\\\x42\\\\x43\\\\x44\\\\x45\\\\x46\\\\x47\\\\x48\\\\x49" + "\\\\x4A\\\\x4B\\\\x4C\\\\x4D\\\\x4E\\\\x4F\\\\x50\\\\x51\\\\x52\\\\x53\\\\x54\\\\x55\\\\x56\\\\x57" + "\\\\x58\\\\x59\\\\x5A';" + "var testString = '12345ABCDEFGHIJKLMNOPQRSTUVWXYZ67890';"; test(initialScript, "testString.match(new RegExp(testPattern))"); } /** * Tests testString.match(new RegExp(testPattern)). * @throws Exception if the test fails */ @Test @Alerts("abcdefghijklmnopqrstuvwxyz") public void test2() throws Exception { final String initialScript = "var testPattern = '\\\\x61\\\\x62\\\\x63\\\\x64\\\\x65\\\\x66\\\\x67\\\\x68" + "\\\\x69\\\\x6A\\\\x6B\\\\x6C\\\\x6D\\\\x6E\\\\x6F\\\\x70\\\\x71\\\\x72\\\\x73\\\\x74\\\\x75\\\\x76" + "\\\\x77\\\\x78\\\\x79\\\\x7A';" + "var testString = '12345AabcdefghijklmnopqrstuvwxyzZ67890';"; test(initialScript, "testString.match(new RegExp(testPattern))"); } /** * Tests testString.match(new RegExp(testPattern)). * @throws Exception if the test fails */ @Test @Alerts(" !\"#$%&'()*+,-./0123") public void test3() throws Exception { final String initialScript = "var testPattern = '\\\\x20\\\\x21\\\\x22\\\\x23\\\\x24\\\\x25\\\\x26\\\\x27" + "\\\\x28\\\\x29\\\\x2A\\\\x2B\\\\x2C\\\\x2D\\\\x2E\\\\x2F\\\\x30\\\\x31\\\\x32\\\\x33';" + "var testString = 'abc !\"#$%&\\'()*+,-./0123ZBC';"; test(initialScript, "testString.match(new RegExp(testPattern))"); } /** * Tests testString.match(new RegExp(testPattern)). * @throws Exception if the test fails */ @Test @Alerts("456789:;<=>?@") public void test4() throws Exception { final String initialScript = "var testPattern = '\\\\x34\\\\x35\\\\x36\\\\x37\\\\x38\\\\x39\\\\x3A\\\\x3B" + "\\\\x3C\\\\x3D\\\\x3E\\\\x3F\\\\x40';" + "var testString = '123456789:;<=>?@ABC';"; test(initialScript, "testString.match(new RegExp(testPattern))"); } /** * Tests testString.match(new RegExp(testPattern)). * @throws Exception if the test fails */ @Test @Alerts("{|}~") public void test5() throws Exception { final String initialScript = "var testPattern = '\\\\x7B\\\\x7C\\\\x7D\\\\x7E';" + "var testString = '1234{|}~ABC';"; test(initialScript, "testString.match(new RegExp(testPattern))"); } /** * Tests 'canthisbeFOUND'.match(new RegExp('[A-\\x5A]+')). * @throws Exception if the test fails */ @Test @Alerts("FOUND") public void test6() throws Exception { test("'canthisbeFOUND'.match(new RegExp('[A-\\\\x5A]+'))"); } /** * Tests 'canthisbeFOUND'.match(new RegExp('[\\x61-\\x7A]+')). * @throws Exception if the test fails */ @Test @Alerts("canthisbe") public void test7() throws Exception { test("'canthisbeFOUND'.match(new RegExp('[\\\\x61-\\\\x7A]+'))"); } /** * Tests 'canthisbeFOUND'.match(/[\x61-\x7A]+/). * @throws Exception if the test fails */ @Test @Alerts("canthisbe") public void test8() throws Exception { test("'canthisbeFOUND'.match(/[\\x61-\\x7A]+/)"); } private void test(final String script) throws Exception { test(null, script); } private void test(final String initialScript, final String script) throws Exception { String html = "<html><head><title>foo</title><script>\n"; if (initialScript != null) { html += initialScript + ";\n"; } html += " alert(" + script + ");\n" + "</script></head><body>\n" + "</body></html>"; loadPageWithAlerts2(html); } }
/* * Copyright (c) 2002-2014 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gargoylesoftware.htmlunit.html; import java.util.Map; import com.gargoylesoftware.htmlunit.SgmlPage; /** * Wrapper for the HTML element "s", a strike-through text style. * * @version $Revision: 8931 $ * @author Ahmed Ashour * @author Ronald Brill * @author Frank Danek */ public class HtmlS extends HtmlElement { /** The HTML tag represented by this element. */ public static final String TAG_NAME = "s"; /** * Creates a new instance. * * @param qualifiedName the qualified name of the element type to instantiate * @param page the page that contains this element * @param attributes the initial attributes */ HtmlS(final String qualifiedName, final SgmlPage page, final Map<String, DomAttr> attributes) { super(qualifiedName, page, attributes); } /** * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br/> * * Returns the default display style. * * @return the default display style. */ @Override public DisplayStyle getDefaultStyleDisplay() { return DisplayStyle.INLINE; } }
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.graphics.drawable.animated; public final class R { private R() {} public static final class attr { private attr() {} public static final int font = 0x7f03007b; public static final int fontProviderAuthority = 0x7f03007d; public static final int fontProviderCerts = 0x7f03007e; public static final int fontProviderFetchStrategy = 0x7f03007f; public static final int fontProviderFetchTimeout = 0x7f030080; public static final int fontProviderPackage = 0x7f030081; public static final int fontProviderQuery = 0x7f030082; public static final int fontStyle = 0x7f030083; public static final int fontWeight = 0x7f030084; } public static final class bool { private bool() {} public static final int abc_action_bar_embed_tabs = 0x7f040000; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f050049; public static final int notification_icon_bg_color = 0x7f05004a; public static final int ripple_material_light = 0x7f05005b; public static final int secondary_text_default_material_light = 0x7f05005d; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f06004a; public static final int compat_button_inset_vertical_material = 0x7f06004b; public static final int compat_button_padding_horizontal_material = 0x7f06004c; public static final int compat_button_padding_vertical_material = 0x7f06004d; public static final int compat_control_corner_material = 0x7f06004e; public static final int notification_action_icon_size = 0x7f060059; public static final int notification_action_text_size = 0x7f06005a; public static final int notification_big_circle_margin = 0x7f06005b; public static final int notification_content_margin_start = 0x7f06005c; public static final int notification_large_icon_height = 0x7f06005d; public static final int notification_large_icon_width = 0x7f06005e; public static final int notification_main_column_padding_top = 0x7f06005f; public static final int notification_media_narrow_margin = 0x7f060060; public static final int notification_right_icon_size = 0x7f060061; public static final int notification_right_side_padding_top = 0x7f060062; public static final int notification_small_icon_background_padding = 0x7f060063; public static final int notification_small_icon_size_as_large = 0x7f060064; public static final int notification_subtext_size = 0x7f060065; public static final int notification_top_pad = 0x7f060066; public static final int notification_top_pad_large_text = 0x7f060067; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f07006d; public static final int notification_bg = 0x7f07006e; public static final int notification_bg_low = 0x7f07006f; public static final int notification_bg_low_normal = 0x7f070070; public static final int notification_bg_low_pressed = 0x7f070071; public static final int notification_bg_normal = 0x7f070072; public static final int notification_bg_normal_pressed = 0x7f070073; public static final int notification_icon_background = 0x7f070074; public static final int notification_template_icon_bg = 0x7f070075; public static final int notification_template_icon_low_bg = 0x7f070076; public static final int notification_tile_bg = 0x7f070077; public static final int notify_panel_notification_icon_bg = 0x7f070078; } public static final class id { private id() {} public static final int action_container = 0x7f08000e; public static final int action_divider = 0x7f080010; public static final int action_image = 0x7f080011; public static final int action_text = 0x7f080017; public static final int actions = 0x7f080018; public static final int async = 0x7f080020; public static final int blocking = 0x7f080024; public static final int chronometer = 0x7f08002c; public static final int forever = 0x7f08003a; public static final int icon = 0x7f080040; public static final int icon_group = 0x7f080041; public static final int info = 0x7f080046; public static final int italic = 0x7f080047; public static final int line1 = 0x7f080049; public static final int line3 = 0x7f08004a; public static final int normal = 0x7f080053; public static final int notification_background = 0x7f080054; public static final int notification_main_column = 0x7f080055; public static final int notification_main_column_container = 0x7f080056; public static final int right_icon = 0x7f080065; public static final int right_side = 0x7f080066; public static final int text = 0x7f080088; public static final int text2 = 0x7f080089; public static final int time = 0x7f08008d; public static final int title = 0x7f08008e; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f090005; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0a001c; public static final int notification_action_tombstone = 0x7f0a001d; public static final int notification_template_custom_big = 0x7f0a0024; public static final int notification_template_icon_group = 0x7f0a0025; public static final int notification_template_part_chronometer = 0x7f0a0029; public static final int notification_template_part_time = 0x7f0a002a; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0c0040; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0d00fa; public static final int TextAppearance_Compat_Notification_Info = 0x7f0d00fb; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0d00fd; public static final int TextAppearance_Compat_Notification_Time = 0x7f0d0100; public static final int TextAppearance_Compat_Notification_Title = 0x7f0d0102; public static final int Widget_Compat_NotificationActionContainer = 0x7f0d016b; public static final int Widget_Compat_NotificationActionText = 0x7f0d016c; } public static final class styleable { private styleable() {} public static final int[] FontFamily = { 0x7f03007d, 0x7f03007e, 0x7f03007f, 0x7f030080, 0x7f030081, 0x7f030082 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x7f03007b, 0x7f030083, 0x7f030084 }; public static final int FontFamilyFont_font = 0; public static final int FontFamilyFont_fontStyle = 1; public static final int FontFamilyFont_fontWeight = 2; } }
package ui; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import aya.Aya; // Initial implementation from // http://stackoverflow.com/questions/33067009/make-java-textarea-as-inputstream-to-run-shell-command-in-interactive-mode-using public class TextPaneInputStream extends InputStream { final InputLine field; final BlockingQueue<Byte> q; public TextPaneInputStream() { this.field = new InputLine(); q = new LinkedBlockingQueue<>(); field.addKeyListener(new KeyListener() { @Override public void keyReleased(KeyEvent e) { if(e.getKeyChar()=='\n'){ String str = field.getText() + "\r\n"; //q.add(str); for (byte b : str.getBytes(StandardCharsets.UTF_8)) { q.add(b); } field.clear(); } } @Override public void keyPressed(KeyEvent arg0) {} @Override public void keyTyped(KeyEvent arg0) {} }); } //private String s; //int pos; private byte out_byte; @Override public int read() throws IOException { //while (null == s || s.length() <= pos) { try { out_byte = q.take(); //pos = 0; } catch (InterruptedException ex) { ex.printStackTrace(Aya.getInstance().getErr()); } //} System.out.println("Sending byte: " + out_byte); return out_byte; } @Override public boolean markSupported() { return false; } byte[] buffer = new byte[1024]; @Override public int read(byte[] b, int off, int len) throws IOException { int byte_count = 0; byte prev = '\0'; byte cur = '\0'; while (true) { try { cur = q.take(); buffer[byte_count] = cur; byte_count++; if (prev == (byte)'\r' && cur == (byte)'\n') { break; } prev = cur; } catch (InterruptedException ex) { ex.printStackTrace(Aya.getInstance().getErr()); } } System.arraycopy(buffer, 0, b, off, byte_count); return byte_count; } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } public InputLine getInputLine() { return field; } }
package br.com.u2d.nfe.schema_4.inutNFe; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java de TUf. * * <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe. * <p> * <pre> * &lt;simpleType name="TUf"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="AC"/> * &lt;enumeration value="AL"/> * &lt;enumeration value="AM"/> * &lt;enumeration value="AP"/> * &lt;enumeration value="BA"/> * &lt;enumeration value="CE"/> * &lt;enumeration value="DF"/> * &lt;enumeration value="ES"/> * &lt;enumeration value="GO"/> * &lt;enumeration value="MA"/> * &lt;enumeration value="MG"/> * &lt;enumeration value="MS"/> * &lt;enumeration value="MT"/> * &lt;enumeration value="PA"/> * &lt;enumeration value="PB"/> * &lt;enumeration value="PE"/> * &lt;enumeration value="PI"/> * &lt;enumeration value="PR"/> * &lt;enumeration value="RJ"/> * &lt;enumeration value="RN"/> * &lt;enumeration value="RO"/> * &lt;enumeration value="RR"/> * &lt;enumeration value="RS"/> * &lt;enumeration value="SC"/> * &lt;enumeration value="SE"/> * &lt;enumeration value="SP"/> * &lt;enumeration value="TO"/> * &lt;enumeration value="EX"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "TUf", namespace = "http://www.portalfiscal.inf.br/nfe") @XmlEnum public enum TUf { AC, AL, AM, AP, BA, CE, DF, ES, GO, MA, MG, MS, MT, PA, PB, PE, PI, PR, RJ, RN, RO, RR, RS, SC, SE, SP, TO, EX; public String value() { return name(); } public static TUf fromValue(String v) { return valueOf(v); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.http.fileupload.impl; import org.apache.tomcat.util.http.fileupload.FileUploadException; /** * This exception is thrown, if a requests permitted size * is exceeded. */ public abstract class SizeException extends FileUploadException { /** * Serial version UID, being used, if serialized. */ private static final long serialVersionUID = -8776225574705254126L; /** * The actual size of the request. */ private final long actual; /** * The maximum permitted size of the request. */ private final long permitted; /** * Creates a new instance. * * @param message The detail message. * @param actual The actual number of bytes in the request. * @param permitted The requests size limit, in bytes. */ protected SizeException(String message, long actual, long permitted) { super(message); this.actual = actual; this.permitted = permitted; } /** * Retrieves the actual size of the request. * * @return The actual size of the request. * @since 1.3 */ public long getActualSize() { return actual; } /** * Retrieves the permitted size of the request. * * @return The permitted size of the request. * @since 1.3 */ public long getPermittedSize() { return permitted; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.uima.util.impl; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.uima.UIMAFramework; import org.apache.uima.resource.ResourceConfigurationException; import org.apache.uima.resource.impl.RelativePathResolver_impl; import org.apache.uima.util.Level; import org.apache.uima.util.Settings; //@formatter:off /** * Class that reads properties files containing external parameter overrides used by the * ExternalOverrideSettings_impl class. * * Similar to java.util.Properties but: * supports UTF-8 files * reverses priority in that duplicate key values are ignored, i.e. values cannot be changed * arrays are represented as strings, e.g. '[elem1,elem2]', and can span multiple lines * '\' can be used to escape $ [ , ] and the line-end * * @author burn */ //@formatter:on public class Settings_impl implements Settings { protected static final String LOG_RESOURCE_BUNDLE = "org.apache.uima.impl.log_messages"; private BufferedReader rdr; private Map<String, String> map; // Thread-local map of properties being resolved +for detecting circular references. private ThreadLocal<HashMap<String, Integer>> tlResolving = new ThreadLocal<HashMap<String, Integer>>() { @Override protected synchronized HashMap<String, Integer> initialValue() { return new HashMap<>(); } }; /* * Regex that matches ${...} non-greedy so stops on first '}' -- hence key cannot contain '}' */ private Pattern evalPattern = Pattern.compile("\\$\\{.*?\\}"); public Settings_impl() { map = new HashMap<>(); } /** * Return a set of keys of all properties in the map * * @return - set of strings */ @Override public Set<String> getKeys() { return map.keySet(); } /** * Load properties from an input stream. Existing properties are not changed and a warning is * logged if the new value is different. May be called multiple times, so effective search is in * load order. Arrays are enclosed in [] and the elements may be separated by <code>,</code> or * new-line, so can span multiple lines without using a final \ * * @param in * - Stream holding properties * @throws IOException * if name characters illegal */ @Override public void load(InputStream in) throws IOException { // Process each logical line (after blanks & comments removed and continuations extended) rdr = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); String line; final String legalPunc = "./-~_"; // Acceptable punctuation characters while ((line = getLine()) != null) { // Remove surrounding white-space and split on first '=' or ':' or white-space String[] parts = line.split("\\s*[:=\\s]\\s*", 2); String name = parts[0]; // Restrict names to alphanumeric plus "joining" punctuation: ./-~_ boolean validName = name.length() > 0; for (int i = 0; i < name.length() && validName; ++i) { validName = Character.isLetterOrDigit(name.charAt(i)) || legalPunc.indexOf(name.charAt(i)) >= 0; } if (!validName) { throw new IOException( "Invalid name '" + name + "' --- characters must be alphanumeric or " + legalPunc); } String value; // When RHS is empty get a split only for the := separators if (parts.length == 1) { value = ""; } else { value = parts[1]; if (value.length() > 0 && value.charAt(0) == '[') { value = getArray(value); } } if (!map.containsKey(name)) { map.put(name, value); } else { if (!value.equals(map.get(name))) { // Key {0} already in use ... ignoring value "{1}" UIMAFramework.getLogger(this.getClass()).logrb(Level.CONFIG, this.getClass().getName(), "load", LOG_RESOURCE_BUNDLE, "UIMA_external_override_ignored__CONFIG", new Object[] { name, value }); } } } } /** * Load properties from the comma-separated list of resources specified in the system property * UimaExternalOverrides Resource names may be specified with a prefix of "file:" or "path:". If * the prefix is "path:" the name must use the Java-style dotted format, similar to an import by * name. The name is converted to a URL with a suffix of ".settings" and is looked up in the * datapath and classpath. If the prefix is "file:" or is omitted the filesystem is searched. * Resources are loaded in list order. Duplicate properties are ignored so entries in a file * override any in following files. * * @throws ResourceConfigurationException * wraps IOException */ @Override public void loadSystemDefaults() throws ResourceConfigurationException { String fnames = System.getProperty("UimaExternalOverrides"); if (fnames != null) { RelativePathResolver_impl relativePathResolver = new RelativePathResolver_impl(); for (String fname : fnames.split(",")) { UIMAFramework.getLogger(this.getClass()).logrb(Level.CONFIG, this.getClass().getName(), "loadSystemDefaults", LOG_RESOURCE_BUNDLE, "UIMA_external_overrides_load__CONFIG", new Object[] { fname }); try { InputStream is = null; if (fname.startsWith("path:")) { // Convert to a url and search the datapath & classpath URL relativeUrl = new URL("file", "", fname.substring(5).replace('.', '/') + ".settings"); URL relPath = relativePathResolver.resolveRelativePath(relativeUrl); if (relPath != null) { is = relPath.openStream(); } else { throw new FileNotFoundException(fname + " - not found in the datapath or classpath."); } } else { // Files may have an optional "file:" prefix if (fname.startsWith("file:")) { fname = fname.substring(5); } File f = new File(fname); if (f.exists()) { is = new FileInputStream(fname); } else { throw new FileNotFoundException(fname + " - not in filesystem."); } } try { load(is); } finally { is.close(); } } catch (IOException e) { throw new ResourceConfigurationException( ResourceConfigurationException.EXTERNAL_OVERRIDE_ERROR, new Object[] { fname }, e); } } } } /** * Look up the value for a property. Recursively evaluate the value replacing references ${key} * with the value of the key. Nested references such as ${name-${suffix}} are supported. * Exceptions are thrown for circular references and undefined references. To avoid evaluation and * get ${key} in the output escape the $ or {, e.g. \${key} Arrays are returned as a * comma-separated string, e.g. "[elem1,elem2]" Note: escape characters are not removed as they * may affect array separators. * * Used by getSetting and getSettingArray * * @param name * - name to look up * @return - value of property * @throws ResourceConfigurationException * if the value references an undefined property */ @Override public String lookUp(String name) throws ResourceConfigurationException { return lookUp(name, name); } private String lookUp(String from, String name) throws ResourceConfigurationException { // Maintain a set of variables being expanded so can recognize infinite recursion // Needs to be thread-local as multiple threads may be evaluating properties HashMap<String, Integer> resolving = tlResolving.get(); if (resolving.containsKey(name)) { System.err.println("Circular evaluation of property: '" + name + "' - definitions are:"); for (String s : resolving.keySet()) { System.err.println(resolving.get(s) + ": " + s + " = " + map.get(s)); } // Circular reference to external override variable "{0}" when evaluating "{1}" throw new ResourceConfigurationException( ResourceConfigurationException.EXTERNAL_OVERRIDE_CIRCULAR_REFERENCE, new Object[] { name, from }); } // Add the name for the duration of the lookup resolving.put(name, resolving.size()); try { return resolve(from, map.get(name)); } finally { resolving.remove(name); } } /** * Replace variable references in a string. * * @param value * - String to scan for variable references * @return - value with all references resolved and escapes processed * @throws Exception * - */ public String resolve(String value) throws Exception { return unescape(resolve(value, value)); } private String resolve(String from, String value) throws ResourceConfigurationException { if (value == null) { return null; } Matcher matcher = evalPattern.matcher(value); if (!matcher.find()) { return value; } StringBuilder result = new StringBuilder(value.length() + 100); // If this ${ is escaped then simply remove the \ and expand everything after the ${ if (isEscaped(value, matcher.start())) { result.append(value.substring(0, matcher.start() - 1)); result.append("${"); result.append(resolve(from, value.substring(matcher.start() + 2))); return result.toString(); } // Find start of variable, expand all that follows, and then look for the end // so that nested entries are supported, e.g. ${name${suffix}} result.append(value.substring(0, matcher.start())); String remainder = resolve(from, value.substring(matcher.start() + 2)); int end = remainder.indexOf('}'); // If ending } missing leave the ${ as-is // If there is no variable treat as if omitted, i.e. '${}' => '' if (end < 0) { result.append("${"); result.append(remainder); } else { String key = remainder.substring(0, end); if (end > 0) { String val = lookUp(from, key); if (val == null) { // Undefined reference to external override variable "{0}" when // evaluating "{1}" throw new ResourceConfigurationException( ResourceConfigurationException.EXTERNAL_OVERRIDE_INVALID, new Object[] { key, from }); } result.append(val); } result.append(remainder.substring(end + 1)); } return result.toString(); } /** * @see org.apache.uima.util.Settings#getSetting(java.lang.String) */ @Override public String getSetting(String name) throws ResourceConfigurationException { String value = lookUp(name, name); if (value == null) { return null; } // Arrays start with '[' and end with an ] that is not escaped if (value.length() >= 2 && value.charAt(0) == '[' && value.charAt(value.length() - 1) == ']' && value.charAt(value.length() - 2) != '\\') { // External override value for "{0}" has the wrong type (scalar or array) throw new ResourceConfigurationException( ResourceConfigurationException.EXTERNAL_OVERRIDE_TYPE_MISMATCH, new Object[] { name }); } return unescape(value); // Process escape characters after checking for array syntax } /** * @see org.apache.uima.util.Settings#getSettingArray(java.lang.String) */ @Override public String[] getSettingArray(String name) throws ResourceConfigurationException { String value = lookUp(name, name); if (value == null) { return null; } if (!(value.length() >= 2 && value.charAt(0) == '[' && value.charAt(value.length() - 1) == ']' && value.charAt(value.length() - 2) != '\\')) { // External override value for "{0}" has the wrong type (scalar or array) throw new ResourceConfigurationException( ResourceConfigurationException.EXTERNAL_OVERRIDE_TYPE_MISMATCH, new Object[] { name }); } value = value.substring(1, value.length() - 1); if (value.length() == 0) { // If an empty string create a 0-length array return Constants.EMPTY_STRING_ARRAY; } // Split on commas but rejoin tokens if a comma is escaped String[] tokens = value.split(","); int nTokens = tokens.length; int last = tokens.length - 1; for (int i = 0; i < last; ++i) { if (endsWithEscape(tokens[i])) { tokens[i + 1] = tokens[i] + "," + tokens[i + 1]; tokens[i] = null; --nTokens; } } if (endsWithEscape(tokens[last])) { tokens[last] += ","; } String[] result = new String[nTokens]; int i = 0; for (String token : tokens) { if (token != null) { result[i++] = unescape(token.trim()); } } return result; } // Final step is to process any escapes by replacing \x by x private String unescape(String token) { int next = token.indexOf('\\'); if (next < 0) { return token; } StringBuilder result = new StringBuilder(token.length()); int last = 0; // For each '\' found copy up to it and restart the search after the // next char while (next >= 0) { result.append(token.substring(last, next)); last = next + 1; next = token.indexOf('\\', last + 1); } result.append(token.substring(last)); return result.toString(); } private boolean endsWithEscape(String line) { int i = line.length(); while (i > 0 && line.charAt(i - 1) == '\\') { --i; } // If change in i is odd then ended with an unescaped \ return ((line.length() - i) % 2 != 0); } /* * Create a string representing an array from one or more logical lines Assert: line length &gt; 0 */ private String getArray(String line) throws IOException { int iend = line.indexOf(']'); while (iend >= 0 && isEscaped(line, iend)) { iend = line.indexOf(']', iend + 1); } if (iend >= 0) { // Found the closing ']' - remainder of line must be empty if (iend + 1 < line.length()) { throw new IOException("Syntax error - invalid character(s) '" + line.substring(iend + 1, line.length()) + "' after end of array"); } return line; } // If line doesn't end with a , add one and append the next line(s) // Don't add a , if line has only '[' or ']' String nextline = getLine(); if (nextline == null) { throw new IOException("Premature EOF - missing ']'"); } iend = line.length() - 1; if ((line.charAt(iend) == ',' && !isEscaped(line, iend)) || line.equals("[") || nextline.charAt(0) == ']') { return line + getArray(nextline); } else { return line + "," + getArray(nextline); } } /* * Reads a logical line from the input stream following the Java Properties class rules. Ignore * blank lines or comments (first non-blank is '#' or '!'). An un-escaped final '\' marks a * continuation line. Leading and trailing whitespace is removed from each physical line, and * hence from the logical line. */ private String getLine() throws IOException { String line = rdr.readLine(); if (line == null) { return null; } // If line is blank or a comment discard it and get another String trimmed = line.trim(); if (trimmed.length() == 0 || trimmed.charAt(0) == '#' || trimmed.charAt(0) == '!') { return getLine(); } // Check the untrimmed line to see if it should be continued if (!isEscaped(line, line.length())) { return trimmed; } return extendLine(trimmed); } /* * Remove final \ and append another line (or lines) */ private String extendLine(String line) throws IOException { // Line must be continued ... remove the final \ and append the next line, etc. int ilast = line.length() - 1; String next = rdr.readLine(); if (next == null) { next = ""; } // Append the trimmed line but check the untrimmed line for a final \ line = line.substring(0, ilast) + next.trim(); if (!isEscaped(next, next.length())) { return line.trim(); // Complete line may need more trimming } return extendLine(line); } /* * Check if a character in the string is escaped, i.e. preceded by an odd number of '\'s Correctly * returns false if ichar &le; 0 */ private boolean isEscaped(String line, int ichar) { int i = ichar - 1; while (i >= 0 && line.charAt(i) == '\\') { --i; } // Difference will be one more than number of '\'s return ((ichar - i) % 2 == 0); } }
package com.ms.silverking.cloud.ring; /** * disjoint: * aaaaaa * bbbbbb * isomorphic: * aaaaaa * bbbbbb * abPartial: * aaaaaa * bbbbbb * baPartial: * aaaaaa * bbbbbb * aSubsumesB: * aaaaaa aaaaaaaa aaaaaa * bbbb bbbb bbbb * bSubsumesA: * aaaa aaaa aaaa * bbbbbb bbbbbbbb bbbbbb * wrappedPartial: * aaaa aaaa aaaaaa * bbbbbb bbbb bbbb * (due to wrapping, a contains both the start and end of b and vice versa) * <p> * nonIdenticalAllRingspace: * a&b both contain the entire ringspace, but have distinct starts and ends * We currently prevent this by normalizing all entire ringspace RingRegions * This type is included for completeness */ public enum IntersectionType {disjoint, isomorphic, abPartial, baPartial, aSubsumesB, bSubsumesA, wrappedPartial, nonIdenticalAllRingspace}
package com.fdmgroup.entities; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class SiteUser{ @Id private String username; private String password; private String firstName; private String lastName; private String email; private String address; private String postcode; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPostcode() { return postcode; } public void setPostcode(String postcode) { this.postcode = postcode; } }
package com.browserstack.client.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) public class Platform implements Serializable { @JsonProperty("os") private String os; @JsonProperty("os_display_name") private String osDisplayName; /** * @return The os */ @JsonProperty("os") public String getOs() { return os; } /** * @param os The os */ @JsonProperty("os") public void setOs(String os) { this.os = os; } /** * @return The os_display_name */ @JsonProperty("os_display_name") public String getOsDisplayName() { return osDisplayName; } /** * @param osDisplayName The os_display_name */ @JsonProperty("os_display_name") public void setOsDisplayName(String osDisplayName) { this.osDisplayName = osDisplayName; } }
package com.cmu.project.pianogame.MainActivity.Fragments.ShopFragments; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cmu.project.pianogame.MainActivity.Adapter.ThemeAdapter; import com.cmu.project.pianogame.MainActivity.Service.Firebase; import com.cmu.project.pianogame.Database.Theme; import com.cmu.project.pianogame.Database.ThemeList; import com.cmu.project.pianogame.R; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ThemeFragment extends Fragment { private RecyclerView rectheme; private ThemeAdapter themeAdapter; private List<ThemeList> mThemeList; private String cur_theme; private DatabaseReference reference; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_theme, container, false); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); rectheme = view.findViewById(R.id.rectheme); rectheme.setHasFixedSize(true); rectheme.setLayoutManager(linearLayoutManager); reference = FirebaseDatabase.getInstance().getReference("Themes").child(Firebase.getCurrent().getUid()); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Theme theme = dataSnapshot.getValue(Theme.class); cur_theme = theme.getCur_theme(); themeList(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); return view; } private void themeList() { reference = FirebaseDatabase.getInstance().getReference("ThemeList"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { mThemeList = new ArrayList<>(); for (DataSnapshot postsnap: dataSnapshot.getChildren()) { ThemeList themeList = postsnap.getValue(ThemeList.class); mThemeList.add(themeList); } Collections.sort(mThemeList, new Comparator<ThemeList>() { @Override public int compare(ThemeList obj1, ThemeList obj2) { if (obj1.getNumber() > obj2.getNumber()) { return 1; } else { return -1; } } }); themeAdapter = new ThemeAdapter(getContext(), mThemeList, cur_theme); rectheme.setAdapter(themeAdapter); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
package com.company.transfer.service; import com.company.transfer.dao.AccountsDAO; import com.company.transfer.dao.TransfersDAO; import com.company.transfer.handlers.common.Answer; import com.company.transfer.lock.TransferLock; import com.company.transfer.lock.TransferLockImpl; import com.company.transfer.model.Account; import com.company.transfer.model.Transfer; import com.company.transfer.model.common.ErrorMessage; import lombok.Builder; import java.util.Optional; import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; public class TransferProcessorImpl implements TransferProcessor { private TransfersDAO transfersDAO; private AccountsDAO accountsDAO; private Transfer transfer; private Account source; private Account target; private Answer answer; @Override public Answer process() throws Exception { try (TransferLock transferLock = new TransferLockImpl(transfer)) { transferLock.lock(); if (!findSource() || !findTarget()) { return answer; } if (!decreaseSourceBalance()) { return answer; } if (!increaseTargetBalance()) { return answer; } return Answer.created(transfersDAO.insert(transfer, source, target)); } } private boolean decreaseSourceBalance() { if (transfer.getAmount().compareTo(source.getBalance()) > 0) { answer = new Answer(HTTP_BAD_REQUEST, ErrorMessage.errorBuilder() .errorCode("NotEnoughMoney") .errorMessage("Account " + source.getId() + " has no enough money on the balance") .build() ); return false; } source = Account.builder() .id(source.getId()) .balance(source.getBalance().subtract(transfer.getAmount())) .build(); return true; } private boolean increaseTargetBalance() { target = Account.builder() .id(target.getId()) .balance(target.getBalance().add(transfer.getAmount())) .build(); return true; } private boolean findSource() { Optional<Account> account = accountsDAO.getAccount(transfer.getSourceAccountId()); if (!account.isPresent()) { answer = notFoundAccountAnswer(transfer.getSourceAccountId()); return false; } source = account.get(); return true; } private boolean findTarget() { Optional<Account> account = accountsDAO.getAccount(transfer.getTargetAccountId()); if (!account.isPresent()) { answer = notFoundAccountAnswer(transfer.getTargetAccountId()); return false; } target = account.get(); return true; } private Answer notFoundAccountAnswer(Long accountId) { return new Answer(HTTP_NOT_FOUND, ErrorMessage.errorBuilder() .errorCode("AccountNotFound") .errorMessage("The account with ID " + accountId + " is not found.") .build() ); } @Builder TransferProcessorImpl(TransfersDAO transfersDAO, AccountsDAO accountsDAO, Transfer transfer) { this.transfersDAO = transfersDAO; this.accountsDAO = accountsDAO; this.transfer = transfer; } }
package com.kelvinhanma.todo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.kelvinhanma.todo.data.Task; import butterknife.BindView; import butterknife.ButterKnife; public class EditActivity extends Activity implements AdapterView.OnItemSelectedListener { @BindView(R.id.eTaskName) EditText myEditText; @BindView(R.id.btnEditItem) Button mySaveButton; @BindView(R.id.editDesc) EditText myDescEditText; @BindView(R.id.editPriority) Spinner myPrioritySpinner; private Task myTask; private int myPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); ButterKnife.bind(this); Intent i = getIntent(); assert i.hasExtra(TaskAdapter.TASK_KEY); myPosition = i.getIntExtra(TaskAdapter.POSITION, -1); assert myPosition != -1; myTask = i.getParcelableExtra(TaskAdapter.TASK_KEY); myEditText.setText(myTask.getName()); myDescEditText.setText(myTask.getDescription()); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priority_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); myPrioritySpinner.setAdapter(adapter); myPrioritySpinner.setOnItemSelectedListener(this); myPrioritySpinner.setSelection(Task.Priority.getIndex(myTask.getPriority())); } public void onSaveItem(View view) { String name = myEditText.getText().toString(); if (name.isEmpty()) { Toast.makeText(this, "Task name cannot be empty.", Toast.LENGTH_SHORT).show(); return; } myTask.setName(name); myTask.setDescription(myDescEditText.getText().toString()); Intent i = new Intent(); i.putExtra(TaskAdapter.TASK_KEY, myTask); i.putExtra(TaskAdapter.POSITION, myPosition); setResult(RESULT_OK, i); finish(); } @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long l) { myTask.setPriority(Task.Priority.valueOf(parent.getItemAtPosition(pos).toString().toUpperCase())); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }
package ru.aserdyuchenko.set.task_3; import java.util.Arrays; import java.util.Iterator; /** * @author anton. * @param <E> - element. */ public class MyHashTable<E> implements Iterable<E> { /** * @param objects - objects. */ private Object[] objects; /** * Constructor. */ public MyHashTable() { this.objects = new Object[2]; } /** * Add elemetn. * @param e - new element. */ public void add(E e) { int arrayIndex = e.hashCode() / 1000; if (needNewSize(arrayIndex)) createNewSize(arrayIndex); if (isOrigin(e)) objects[arrayIndex] = e; } @Override public int hashCode() { return Arrays.hashCode(objects); } /** * Check element. * @param value - element. * @return true if element origin. */ private boolean isOrigin(E value) { int valueIndex = value.hashCode() / 1000; return (objects[valueIndex] != null && objects[valueIndex].equals(value)) ? false : true; } /** * Check size. * @return result of ckeck. */ private boolean needNewSize(int arrayIndex) { return arrayIndex > objects.length - 1; } /** * Create new size for container. */ private void createNewSize(int newSize) { Object[] newObject = new Object[newSize + 2]; System.arraycopy(objects, 0, newObject, 0, objects.length); this.objects = newObject; } @Override public Iterator<E> iterator() { return new Iterator<E>() { private int currentIndex = 0; @Override public boolean hasNext() { while (objects[currentIndex] == null && currentIndex < objects.length - 1) { currentIndex++; } return objects[currentIndex++] != null ? true : false; } @Override public E next() { while (objects[currentIndex] == null && currentIndex < objects.length - 1) { currentIndex++; } return (E) objects[currentIndex++]; } }; } }
/* * Copyright 2004-2014 Brian McCallister * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.skife.jdbi.v2.sqlobject; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.JDBITests; import org.skife.jdbi.v2.Something; import java.util.UUID; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @Category(JDBITests.class) public class TestClasspathStatementLocator { private Handle handle; @Before public void setUp() throws Exception { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:" + UUID.randomUUID()); DBI dbi = new DBI(ds); dbi.registerMapper(new SomethingMapper()); handle = dbi.open(); handle.execute("create table something (id int primary key, name varchar(100))"); } @After public void tearDown() throws Exception { handle.execute("drop table something"); handle.close(); } @Test public void testBam() throws Exception { handle.execute("insert into something (id, name) values (6, 'Martin')"); Something s = handle.attach(Cromulence.class).findById(6L); assertThat(s.getName(), equalTo("Martin")); } static interface Cromulence { @SqlQuery public Something findById(@Bind("id") Long id); } }
package tech.teslex.telegroo.telegram.api.types; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.util.List; /** * This object contains information about a poll. */ @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class Poll { /** * Unique poll identifier */ private String id; /** * Poll question, 1-255 characters */ private String question; /** * List of poll options */ private List<PollOption> options; /** * True, if the poll is closed */ @JsonProperty(value = "is_closed") private Boolean isClosed; }
package supply.me.server.povoador; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.search.Document; import com.google.appengine.api.search.Field; import com.google.appengine.api.search.GeoPoint; import com.google.appengine.api.search.Index; import com.google.appengine.api.search.IndexSpec; import com.google.appengine.api.search.PutException; import com.google.appengine.api.search.SearchServiceFactory; import com.google.appengine.api.search.StatusCode; import supply.me.server.datastore.Fornecedor; /** * Classe que insere produtos para fazer a busca funcionar. * Esta classe somente será usada uma vez a cada novo deploy do app * @author carvalhorr * */ @SuppressWarnings("serial") public class PovoadorServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("application/json"); povoar(); resp.getWriter().write("[\"status\": \"OK\"]"); } private void povoar() { criarFornecedor1(); criarFornecedor2(); criarFornecedor3(); } private void criarFornecedor1() { Fornecedor f = addFornecedor(1, "Papelaria", "Papelaria da esquina.", -23.60135, -46.68607); addProduto(f, "Bloco de papel com 10 folhas", "Bloco de papel com 10 folhas Papelzinho."); addProduto(f, "Borracha retangular", "Borracha retangular de 20x50mm Borrachuda."); } private void criarFornecedor2() { Fornecedor f = addFornecedor( 2, "Material de limpeza Inc.", "Empresa especializada em fornecimento de materiais de limpeza para escritorio.", -23.59941, -46.68178); addProduto(f, "Papel higienico dupla face Carinho 100 mts", "Papel higienico dupla face marca Carinho 10 rolos de 100 metros."); addProduto(f, "Papel higienico dupla face Carinho 50 mts", "Papel higienico dupla face marca Carinho 10 rolos de 50 metros."); addProduto(f, "Sabão em pó 10kg Homo", "Pacote de 10kg de sabao em po da marca Homo."); addProduto(f, "Sabão em pó 5kg Homo", "Pacote de 5kg de sabao em po da marca Homo."); addProduto(f, "Detergente liquido para chao Limpura 4l", "Detergente liquido Limpura pra limpeza de chao com 4l."); addProduto(f, "Detergente liquido para banheiro Limpura 2l", "Detergente liquido Limpura pra limpeza de banheiro com 2l."); } private void criarFornecedor3() { Fornecedor f = addFornecedor(3, "Material para escritorio", "Fornecedora de suprimentos para escritorio em geral.", -23.59962, -46.68786); addProduto(f, "Papel A3/50", "Pacote de papel A3 com 50 folhas."); addProduto(f, "Papel A3/100", "Pacote de papel A3 com 100 folhas."); addProduto(f, "Papel A4/50", "Pacote de papel A4 com 50 folhas."); addProduto(f, "Papel A4/100", "Pacote de papel A4 com 100 folhas."); addProduto(f, "Grampo tamanho 1 com 100", "Grampo de cobre para grampeador com 100 tamanho 1."); addProduto(f, "Grampo tamanho 2 com 100", "Grampo de cobre para grampeador com 100 tamanho 2."); } private Fornecedor addFornecedor(long id, String nome, String desc, double lat, double lng) { Fornecedor f = new Fornecedor(); f.setId(id); f.setNome(nome); f.setDescricao(desc); f.setLatitude(lat); f.setLongitude(lng); return f; } private void addProduto(Fornecedor fornecedor, String nome, String descricao) { Document doc = Document .newBuilder() .addField(Field.newBuilder().setName("nome").setText(nome)) .addField( Field.newBuilder().setName("descricao") .setText(descricao)) .addField( Field.newBuilder().setName("nome_fornecedor") .setText(fornecedor.getNome())) .addField( Field.newBuilder().setName("descricao_fornecedor") .setText(fornecedor.getDescricao())) .addField( Field.newBuilder() .setName("posicao") .setGeoPoint( new GeoPoint(fornecedor.getLatitude(), fornecedor.getLongitude()))) .build(); indexADocument("produtos", doc); } public void indexADocument(String indexName, Document document) { IndexSpec indexSpec = IndexSpec.newBuilder().setName(indexName).build(); Index index = SearchServiceFactory.getSearchService().getIndex( indexSpec); try { index.put(document); } catch (PutException e) { if (StatusCode.TRANSIENT_ERROR.equals(e.getOperationResult() .getCode())) { // retry putting the document } } } }
/* * Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @author IBM Corp. * * Copyright IBM Corp. 1999-2000. All rights reserved. */ package javax.management.modelmbean; import static com.sun.jmx.defaults.JmxProperties.MODELMBEAN_LOGGER; import static com.sun.jmx.mbeanserver.Util.cast; import com.sun.jmx.mbeanserver.GetPropertyAction; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.lang.reflect.Constructor; import java.security.AccessController; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.logging.Level; import javax.management.Descriptor; import javax.management.ImmutableDescriptor; import javax.management.MBeanException; import javax.management.RuntimeOperationsException; import sun.reflect.misc.ReflectUtil; /** {@collect.stats} * This class represents the metadata set for a ModelMBean element. A * descriptor is part of the ModelMBeanInfo, * ModelMBeanNotificationInfo, ModelMBeanAttributeInfo, * ModelMBeanConstructorInfo, and ModelMBeanParameterInfo. * <P> * A descriptor consists of a collection of fields. Each field is in * fieldname=fieldvalue format. Field names are not case sensitive, * case will be preserved on field values. * <P> * All field names and values are not predefined. New fields can be * defined and added by any program. Some fields have been predefined * for consistency of implementation and support by the * ModelMBeanInfo, ModelMBeanAttributeInfo, ModelMBeanConstructorInfo, * ModelMBeanNotificationInfo, ModelMBeanOperationInfo and ModelMBean * classes. * * <p>The <b>serialVersionUID</b> of this class is <code>-6292969195866300415L</code>. * * @since 1.5 */ @SuppressWarnings("serial") // serialVersionUID not constant public class DescriptorSupport implements javax.management.Descriptor { // Serialization compatibility stuff: // Two serial forms are supported in this class. The selected form depends // on system property "jmx.serial.form": // - "1.0" for JMX 1.0 // - any other value for JMX 1.1 and higher // // Serial version for old serial form private static final long oldSerialVersionUID = 8071560848919417985L; // // Serial version for new serial form private static final long newSerialVersionUID = -6292969195866300415L; // // Serializable fields in old serial form private static final ObjectStreamField[] oldSerialPersistentFields = { new ObjectStreamField("descriptor", HashMap.class), new ObjectStreamField("currClass", String.class) }; // // Serializable fields in new serial form private static final ObjectStreamField[] newSerialPersistentFields = { new ObjectStreamField("descriptor", HashMap.class) }; // // Actual serial version and serial form private static final long serialVersionUID; /** {@collect.stats} * @serialField descriptor HashMap The collection of fields representing this descriptor */ private static final ObjectStreamField[] serialPersistentFields; private static final String serialForm; static { String form = null; boolean compat = false; try { GetPropertyAction act = new GetPropertyAction("jmx.serial.form"); form = AccessController.doPrivileged(act); compat = "1.0".equals(form); // form may be null } catch (Exception e) { // OK: No compat with 1.0 } serialForm = form; if (compat) { serialPersistentFields = oldSerialPersistentFields; serialVersionUID = oldSerialVersionUID; } else { serialPersistentFields = newSerialPersistentFields; serialVersionUID = newSerialVersionUID; } } // // END Serialization compatibility stuff /* Spec says that field names are case-insensitive, but that case is preserved. This means that we need to be able to map from a name that may differ in case to the actual name that is used in the HashMap. Thus, descriptorMap is a TreeMap with a Comparator that ignores case. Previous versions of this class had a field called "descriptor" of type HashMap where the keys were directly Strings. This is hard to reconcile with the required semantics, so we fabricate that field virtually during serialization and deserialization but keep the real information in descriptorMap. */ private transient SortedMap<String, Object> descriptorMap; private static final String currClass = "DescriptorSupport"; /** {@collect.stats} * Descriptor default constructor. * Default initial descriptor size is 20. It will grow as needed.<br> * Note that the created empty descriptor is not a valid descriptor * (the method {@link #isValid isValid} returns <CODE>false</CODE>) */ public DescriptorSupport() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "DescriptorSupport()" , "Constructor"); } init(null); } /** {@collect.stats} * Descriptor constructor. Takes as parameter the initial * capacity of the Map that stores the descriptor fields. * Capacity will grow as needed.<br> Note that the created empty * descriptor is not a valid descriptor (the method {@link * #isValid isValid} returns <CODE>false</CODE>). * * @param initNumFields The initial capacity of the Map that * stores the descriptor fields. * * @exception RuntimeOperationsException for illegal value for * initNumFields (&lt;= 0) * @exception MBeanException Wraps a distributed communication Exception. */ public DescriptorSupport(int initNumFields) throws MBeanException, RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(initNumFields = " + initNumFields + ")", "Constructor"); } if (initNumFields <= 0) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(initNumFields)", "Illegal arguments: initNumFields <= 0"); } final String msg = "Descriptor field limit invalid: " + initNumFields; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } init(null); } /** {@collect.stats} * Descriptor constructor taking a Descriptor as parameter. * Creates a new descriptor initialized to the values of the * descriptor passed in parameter. * * @param inDescr the descriptor to be used to initialize the * constructed descriptor. If it is null or contains no descriptor * fields, an empty Descriptor will be created. */ public DescriptorSupport(DescriptorSupport inDescr) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(Descriptor)", "Constructor"); } if (inDescr == null) init(null); else init(inDescr.descriptorMap); } /** {@collect.stats} * <p>Descriptor constructor taking an XML String.</p> * * <p>The format of the XML string is not defined, but an * implementation must ensure that the string returned by * {@link #toXMLString() toXMLString()} on an existing * descriptor can be used to instantiate an equivalent * descriptor using this constructor.</p> * * <p>In this implementation, all field values will be created * as Strings. If the field values are not Strings, the * programmer will have to reset or convert these fields * correctly.</p> * * @param inStr An XML-formatted string used to populate this * Descriptor. The format is not defined, but any * implementation must ensure that the string returned by * method {@link #toXMLString toXMLString} on an existing * descriptor can be used to instantiate an equivalent * descriptor when instantiated using this constructor. * * @exception RuntimeOperationsException If the String inStr * passed in parameter is null * @exception XMLParseException XML parsing problem while parsing * the input String * @exception MBeanException Wraps a distributed communication Exception. */ /* At some stage we should rewrite this code to be cleverer. Using a StringTokenizer as we do means, first, that we accept a lot of bogus strings without noticing they are bogus, and second, that we split the string being parsed at characters like > even if they occur in the middle of a field value. */ public DescriptorSupport(String inStr) throws MBeanException, RuntimeOperationsException, XMLParseException { /* parse an XML-formatted string and populate internal * structure with it */ if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String = '" + inStr + "')", "Constructor"); } if (inStr == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String = null)", "Illegal arguments"); } final String msg = "String in parameter is null"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } final String lowerInStr = inStr.toLowerCase(); if (!lowerInStr.startsWith("<descriptor>") || !lowerInStr.endsWith("</descriptor>")) { throw new XMLParseException("No <descriptor>, </descriptor> pair"); } // parse xmlstring into structures init(null); // create dummy descriptor: should have same size // as number of fields in xmlstring // loop through structures and put them in descriptor StringTokenizer st = new StringTokenizer(inStr, "<> \t\n\r\f"); boolean inFld = false; boolean inDesc = false; String fieldName = null; String fieldValue = null; while (st.hasMoreTokens()) { // loop through tokens String tok = st.nextToken(); if (tok.equalsIgnoreCase("FIELD")) { inFld = true; } else if (tok.equalsIgnoreCase("/FIELD")) { if ((fieldName != null) && (fieldValue != null)) { fieldName = fieldName.substring(fieldName.indexOf('"') + 1, fieldName.lastIndexOf('"')); final Object fieldValueObject = parseQuotedFieldValue(fieldValue); setField(fieldName, fieldValueObject); } fieldName = null; fieldValue = null; inFld = false; } else if (tok.equalsIgnoreCase("DESCRIPTOR")) { inDesc = true; } else if (tok.equalsIgnoreCase("/DESCRIPTOR")) { inDesc = false; fieldName = null; fieldValue = null; inFld = false; } else if (inFld && inDesc) { // want kw=value, eg, name="myname" value="myvalue" int eq_separator = tok.indexOf("="); if (eq_separator > 0) { String kwPart = tok.substring(0,eq_separator); String valPart = tok.substring(eq_separator+1); if (kwPart.equalsIgnoreCase("NAME")) fieldName = valPart; else if (kwPart.equalsIgnoreCase("VALUE")) fieldValue = valPart; else { // xml parse exception final String msg = "Expected `name' or `value', got `" + tok + "'"; throw new XMLParseException(msg); } } else { // xml parse exception final String msg = "Expected `keyword=value', got `" + tok + "'"; throw new XMLParseException(msg); } } } // while tokens if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(XMLString)", "Exit"); } } /** {@collect.stats} * Constructor taking field names and field values. Neither array * can be null. * * @param fieldNames String array of field names. No elements of * this array can be null. * @param fieldValues Object array of the corresponding field * values. Elements of the array can be null. The * <code>fieldValue</code> must be valid for the * <code>fieldName</code> (as defined in method {@link #isValid * isValid}) * * <p>Note: array sizes of parameters should match. If both arrays * are empty, then an empty descriptor is created.</p> * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. The array lengths must be equal. * If the descriptor construction fails for any reason, this * exception will be thrown. * */ public DescriptorSupport(String[] fieldNames, Object[] fieldValues) throws RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(fieldNames,fieldObjects)", "Constructor"); } if ((fieldNames == null) || (fieldValues == null) || (fieldNames.length != fieldValues.length)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(fieldNames,fieldObjects)", "Illegal arguments"); } final String msg = "Null or invalid fieldNames or fieldValues"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } /* populate internal structure with fields */ init(null); for (int i=0; i < fieldNames.length; i++) { // setField will throw an exception if a fieldName is be null. // the fieldName and fieldValue will be validated in setField. setField(fieldNames[i], fieldValues[i]); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(fieldNames,fieldObjects)", "Exit"); } } /** {@collect.stats} * Constructor taking fields in the <i>fieldName=fieldValue</i> * format. * * @param fields String array with each element containing a * field name and value. If this array is null or empty, then the * default constructor will be executed. Null strings or empty * strings will be ignored. * * <p>All field values should be Strings. If the field values are * not Strings, the programmer will have to reset or convert these * fields correctly. * * <p>Note: Each string should be of the form * <i>fieldName=fieldValue</i>. The field name * ends at the first {@code =} character; for example if the String * is {@code a=b=c} then the field name is {@code a} and its value * is {@code b=c}. * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. The field must contain an * "=". "=fieldValue", "fieldName", and "fieldValue" are illegal. * FieldName cannot be null. "fieldName=" will cause the value to * be null. If the descriptor construction fails for any reason, * this exception will be thrown. * */ public DescriptorSupport(String... fields) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String... fields)", "Constructor"); } init(null); if (( fields == null ) || ( fields.length == 0)) return; init(null); for (int i=0; i < fields.length; i++) { if ((fields[i] == null) || (fields[i].equals(""))) { continue; } int eq_separator = fields[i].indexOf("="); if (eq_separator < 0) { // illegal if no = or is first character if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String... fields)", "Illegal arguments: field does not have " + "'=' as a name and value separator"); } final String msg = "Field in invalid format: no equals sign"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } String fieldName = fields[i].substring(0,eq_separator); String fieldValue = null; if (eq_separator < fields[i].length()) { // = is not in last character fieldValue = fields[i].substring(eq_separator+1); } if (fieldName.equals("")) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String... fields)", "Illegal arguments: fieldName is empty"); } final String msg = "Field in invalid format: no fieldName"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } setField(fieldName,fieldValue); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "Descriptor(String... fields)", "Exit"); } } private void init(Map<String, ?> initMap) { descriptorMap = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER); if (initMap != null) descriptorMap.putAll(initMap); } // Implementation of the Descriptor interface public synchronized Object getFieldValue(String fieldName) throws RuntimeOperationsException { if ((fieldName == null) || (fieldName.equals(""))) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValue(String fieldName)", "Illegal arguments: null field name"); } final String msg = "Fieldname requested is null"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } Object retValue = descriptorMap.get(fieldName); if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValue(String fieldName = " + fieldName + ")", "Returns '" + retValue + "'"); } return(retValue); } public synchronized void setField(String fieldName, Object fieldValue) throws RuntimeOperationsException { // field name cannot be null or empty if ((fieldName == null) || (fieldName.equals(""))) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setField(fieldName,fieldValue)", "Illegal arguments: null or empty field name"); } final String msg = "Field name to be set is null or empty"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } if (!validateField(fieldName, fieldValue)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setField(fieldName,fieldValue)", "Illegal arguments"); } final String msg = "Field value invalid: " + fieldName + "=" + fieldValue; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setField(fieldName,fieldValue)", "Entry: setting '" + fieldName + "' to '" + fieldValue + "'"); } // Since we do not remove any existing entry with this name, // the field will preserve whatever case it had, ignoring // any difference there might be in fieldName. descriptorMap.put(fieldName, fieldValue); } public synchronized String[] getFields() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFields()", "Entry"); } int numberOfEntries = descriptorMap.size(); String[] responseFields = new String[numberOfEntries]; Set returnedSet = descriptorMap.entrySet(); int i = 0; Object currValue = null; Map.Entry currElement = null; if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFields()", "Returning " + numberOfEntries + " fields"); } for (Iterator iter = returnedSet.iterator(); iter.hasNext(); i++) { currElement = (Map.Entry) iter.next(); if (currElement == null) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFields()", "Element is null"); } } else { currValue = currElement.getValue(); if (currValue == null) { responseFields[i] = currElement.getKey() + "="; } else { if (currValue instanceof java.lang.String) { responseFields[i] = currElement.getKey() + "=" + currValue.toString(); } else { responseFields[i] = currElement.getKey() + "=(" + currValue.toString() + ")"; } } } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFields()", "Exit"); } return responseFields; } public synchronized String[] getFieldNames() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldNames()", "Entry"); } int numberOfEntries = descriptorMap.size(); String[] responseFields = new String[numberOfEntries]; Set returnedSet = descriptorMap.entrySet(); int i = 0; if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldNames()", "Returning " + numberOfEntries + " fields"); } for (Iterator iter = returnedSet.iterator(); iter.hasNext(); i++) { Map.Entry currElement = (Map.Entry) iter.next(); if (( currElement == null ) || (currElement.getKey() == null)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldNames()", "Field is null"); } } else { responseFields[i] = currElement.getKey().toString(); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldNames()", "Exit"); } return responseFields; } public synchronized Object[] getFieldValues(String... fieldNames) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValues(String... fieldNames)", "Entry"); } // if fieldNames == null return all values // if fieldNames is String[0] return no values final int numberOfEntries = (fieldNames == null) ? descriptorMap.size() : fieldNames.length; final Object[] responseFields = new Object[numberOfEntries]; int i = 0; if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValues(String... fieldNames)", "Returning " + numberOfEntries + " fields"); } if (fieldNames == null) { for (Iterator iter = descriptorMap.values().iterator(); iter.hasNext(); i++) responseFields[i] = iter.next(); } else { for (i=0; i < fieldNames.length; i++) { if ((fieldNames[i] == null) || (fieldNames[i].equals(""))) { responseFields[i] = null; } else { responseFields[i] = getFieldValue(fieldNames[i]); } } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "getFieldValues(String... fieldNames)", "Exit"); } return responseFields; } public synchronized void setFields(String[] fieldNames, Object[] fieldValues) throws RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setFields(fieldNames,fieldValues)", "Entry"); } if ((fieldNames == null) || (fieldValues == null) || (fieldNames.length != fieldValues.length)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setFields(fieldNames,fieldValues)", "Illegal arguments"); } final String msg = "fieldNames and fieldValues are null or invalid"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } for (int i=0; i < fieldNames.length; i++) { if (( fieldNames[i] == null) || (fieldNames[i].equals(""))) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setFields(fieldNames,fieldValues)", "Null field name encountered at element " + i); } final String msg = "fieldNames is null or invalid"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, msg); } setField(fieldNames[i], fieldValues[i]); } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "setFields(fieldNames,fieldValues)", "Exit"); } } /** {@collect.stats} * Returns a new Descriptor which is a duplicate of the Descriptor. * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. If the descriptor construction * fails for any reason, this exception will be thrown. */ public synchronized Object clone() throws RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "clone()", "Entry"); } return(new DescriptorSupport(this)); } public synchronized void removeField(String fieldName) { if ((fieldName == null) || (fieldName.equals(""))) { return; } descriptorMap.remove(fieldName); } /** {@collect.stats} * Compares this descriptor to the given object. The objects are equal if * the given object is also a Descriptor, and if the two Descriptors have * the same field names (possibly differing in case) and the same * associated values. The respective values for a field in the two * Descriptors are equal if the following conditions hold:</p> * * <ul> * <li>If one value is null then the other must be too.</li> * <li>If one value is a primitive array then the other must be a primitive * array of the same type with the same elements.</li> * <li>If one value is an object array then the other must be too and * {@link java.util.Arrays#deepEquals(Object[],Object[]) Arrays.deepEquals} * must return true.</li> * <li>Otherwise {@link Object#equals(Object)} must return true.</li> * </ul> * * @param o the object to compare with. * * @return {@code true} if the objects are the same; {@code false} * otherwise. * */ // XXXX TODO: This is not very efficient! // Note: this Javadoc is copied from javax.management.Descriptor // due to 6369229. public synchronized boolean equals(Object o) { if (o == this) return true; return new ImmutableDescriptor(descriptorMap).equals(o); } /** {@collect.stats} * <p>Returns the hash code value for this descriptor. The hash * code is computed as the sum of the hash codes for each field in * the descriptor. The hash code of a field with name {@code n} * and value {@code v} is {@code n.toLowerCase().hashCode() ^ h}. * Here {@code h} is the hash code of {@code v}, computed as * follows:</p> * * <ul> * <li>If {@code v} is null then {@code h} is 0.</li> * <li>If {@code v} is a primitive array then {@code h} is computed using * the appropriate overloading of {@code java.util.Arrays.hashCode}.</li> * <li>If {@code v} is an object array then {@code h} is computed using * {@link java.util.Arrays#deepHashCode(Object[]) Arrays.deepHashCode}.</li> * <li>Otherwise {@code h} is {@code v.hashCode()}.</li> * </ul> * * @return A hash code value for this object. * */ // XXXX TODO: This is not very efficient! // Note: this Javadoc is copied from javax.management.Descriptor // due to 6369229. public synchronized int hashCode() { return new ImmutableDescriptor(descriptorMap).hashCode(); } /** {@collect.stats} * Returns true if all of the fields have legal values given their * names. * <P> * This implementation does not support interoperating with a directory * or lookup service. Thus, conforming to the specification, no checking is * done on the <i>"export"</i> field. * <P> * Otherwise this implementation returns false if: * <P> * <UL> * <LI> name and descriptorType fieldNames are not defined, or * null, or empty, or not String * <LI> class, role, getMethod, setMethod fieldNames, if defined, * are null or not String * <LI> persistPeriod, currencyTimeLimit, lastUpdatedTimeStamp, * lastReturnedTimeStamp if defined, are null, or not a Numeric * String or not a Numeric Value >= -1 * <LI> log fieldName, if defined, is null, or not a Boolean or * not a String with value "t", "f", "true", "false". These String * values must not be case sensitive. * <LI> visibility fieldName, if defined, is null, or not a * Numeric String or a not Numeric Value >= 1 and <= 4 * <LI> severity fieldName, if defined, is null, or not a Numeric * String or not a Numeric Value >= 0 and <= 6<br> * <LI> persistPolicy fieldName, if defined, is null, or not one of * the following strings:<br> * "OnUpdate", "OnTimer", "NoMoreOftenThan", "OnUnregister", "Always", * "Never". These String values must not be case sensitive.<br> * </UL> * * @exception RuntimeOperationsException If the validity checking * fails for any reason, this exception will be thrown. */ public synchronized boolean isValid() throws RuntimeOperationsException { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "isValid()", "Entry"); } // verify that the descriptor is valid, by iterating over each field... Set returnedSet = descriptorMap.entrySet(); if (returnedSet == null) { // null descriptor, not valid if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "isValid()", "Returns false (null set)"); } return false; } // must have a name and descriptor type field String thisName = (String)(this.getFieldValue("name")); String thisDescType = (String)(getFieldValue("descriptorType")); if ((thisName == null) || (thisDescType == null) || (thisName.equals("")) || (thisDescType.equals(""))) { return false; } // According to the descriptor type we validate the fields contained for (Iterator iter = returnedSet.iterator(); iter.hasNext();) { Map.Entry currElement = (Map.Entry) iter.next(); if (currElement != null) { if (currElement.getValue() != null) { // validate the field valued... if (validateField((currElement.getKey()).toString(), (currElement.getValue()).toString())) { continue; } else { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "isValid()", "Field " + currElement.getKey() + "=" + currElement.getValue() + " is not valid"); } return false; } } } } // fell through, all fields OK if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "isValid()", "Returns true"); } return true; } // worker routine for isValid() // name is not null // descriptorType is not null // getMethod and setMethod are not null // persistPeriod is numeric // currencyTimeLimit is numeric // lastUpdatedTimeStamp is numeric // visibility is 1-4 // severity is 0-6 // log is T or F // role is not null // class is not null // lastReturnedTimeStamp is numeric private boolean validateField(String fldName, Object fldValue) { if ((fldName == null) || (fldName.equals(""))) return false; String SfldValue = ""; boolean isAString = false; if ((fldValue != null) && (fldValue instanceof java.lang.String)) { SfldValue = (String) fldValue; isAString = true; } boolean nameOrDescriptorType = (fldName.equalsIgnoreCase("Name") || fldName.equalsIgnoreCase("DescriptorType")); if (nameOrDescriptorType || fldName.equalsIgnoreCase("SetMethod") || fldName.equalsIgnoreCase("GetMethod") || fldName.equalsIgnoreCase("Role") || fldName.equalsIgnoreCase("Class")) { if (fldValue == null || !isAString) return false; if (nameOrDescriptorType && SfldValue.equals("")) return false; return true; } else if (fldName.equalsIgnoreCase("visibility")) { long v; if ((fldValue != null) && (isAString)) { v = toNumeric(SfldValue); } else if (fldValue instanceof java.lang.Integer) { v = ((Integer)fldValue).intValue(); } else return false; if (v >= 1 && v <= 4) return true; else return false; } else if (fldName.equalsIgnoreCase("severity")) { long v; if ((fldValue != null) && (isAString)) { v = toNumeric(SfldValue); } else if (fldValue instanceof java.lang.Integer) { v = ((Integer)fldValue).intValue(); } else return false; return (v >= 0 && v <= 6); } else if (fldName.equalsIgnoreCase("PersistPolicy")) { return (((fldValue != null) && (isAString)) && ( SfldValue.equalsIgnoreCase("OnUpdate") || SfldValue.equalsIgnoreCase("OnTimer") || SfldValue.equalsIgnoreCase("NoMoreOftenThan") || SfldValue.equalsIgnoreCase("Always") || SfldValue.equalsIgnoreCase("Never") || SfldValue.equalsIgnoreCase("OnUnregister"))); } else if (fldName.equalsIgnoreCase("PersistPeriod") || fldName.equalsIgnoreCase("CurrencyTimeLimit") || fldName.equalsIgnoreCase("LastUpdatedTimeStamp") || fldName.equalsIgnoreCase("LastReturnedTimeStamp")) { long v; if ((fldValue != null) && (isAString)) { v = toNumeric(SfldValue); } else if (fldValue instanceof java.lang.Number) { v = ((Number)fldValue).longValue(); } else return false; return (v >= -1); } else if (fldName.equalsIgnoreCase("log")) { return ((fldValue instanceof java.lang.Boolean) || (isAString && (SfldValue.equalsIgnoreCase("T") || SfldValue.equalsIgnoreCase("true") || SfldValue.equalsIgnoreCase("F") || SfldValue.equalsIgnoreCase("false") ))); } // default to true, it is a field we aren't validating (user etc.) return true; } /** {@collect.stats} * <p>Returns an XML String representing the descriptor.</p> * * <p>The format is not defined, but an implementation must * ensure that the string returned by this method can be * used to build an equivalent descriptor when instantiated * using the constructor {@link #DescriptorSupport(String) * DescriptorSupport(String inStr)}.</p> * * <p>Fields which are not String objects will have toString() * called on them to create the value. The value will be * enclosed in parentheses. It is not guaranteed that you can * reconstruct these objects unless they have been * specifically set up to support toString() in a meaningful * format and have a matching constructor that accepts a * String in the same format.</p> * * <p>If the descriptor is empty the following String is * returned: &lt;Descriptor&gt;&lt;/Descriptor&gt;</p> * * @return the XML string. * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. If the XML formatted string * construction fails for any reason, this exception will be * thrown. */ public synchronized String toXMLString() { final StringBuilder buf = new StringBuilder("<Descriptor>"); Set returnedSet = descriptorMap.entrySet(); for (Iterator iter = returnedSet.iterator(); iter.hasNext(); ) { final Map.Entry currElement = (Map.Entry) iter.next(); final String name = currElement.getKey().toString(); Object value = currElement.getValue(); String valueString = null; /* Set valueString to non-null if and only if this is a string that cannot be confused with the encoding of an object. If it could be so confused (surrounded by parentheses) then we call makeFieldValue as for any non-String object and end up with an encoding like "(java.lang.String/(thing))". */ if (value instanceof String) { final String svalue = (String) value; if (!svalue.startsWith("(") || !svalue.endsWith(")")) valueString = quote(svalue); } if (valueString == null) valueString = makeFieldValue(value); buf.append("<field name=\"").append(name).append("\" value=\"") .append(valueString).append("\"></field>"); } buf.append("</Descriptor>"); return buf.toString(); } private static final String[] entities = { " &#32;", "\"&quot;", "<&lt;", ">&gt;", "&&amp;", "\r&#13;", "\t&#9;", "\n&#10;", "\f&#12;", }; private static final Map<String,Character> entityToCharMap = new HashMap<String,Character>(); private static final String[] charToEntityMap; static { char maxChar = 0; for (int i = 0; i < entities.length; i++) { final char c = entities[i].charAt(0); if (c > maxChar) maxChar = c; } charToEntityMap = new String[maxChar + 1]; for (int i = 0; i < entities.length; i++) { final char c = entities[i].charAt(0); final String entity = entities[i].substring(1); charToEntityMap[c] = entity; entityToCharMap.put(entity, new Character(c)); } } private static boolean isMagic(char c) { return (c < charToEntityMap.length && charToEntityMap[c] != null); } /* * Quote the string so that it will be acceptable to the (String) * constructor. Since the parsing code in that constructor is fairly * stupid, we're obliged to quote apparently innocuous characters like * space, <, and >. In a future version, we should rewrite the parser * and only quote " plus either \ or & (depending on the quote syntax). */ private static String quote(String s) { boolean found = false; for (int i = 0; i < s.length(); i++) { if (isMagic(s.charAt(i))) { found = true; break; } } if (!found) return s; final StringBuilder buf = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (isMagic(c)) buf.append(charToEntityMap[c]); else buf.append(c); } return buf.toString(); } private static String unquote(String s) throws XMLParseException { if (!s.startsWith("\"") || !s.endsWith("\"")) throw new XMLParseException("Value must be quoted: <" + s + ">"); final StringBuilder buf = new StringBuilder(); final int len = s.length() - 1; for (int i = 1; i < len; i++) { final char c = s.charAt(i); final int semi; final Character quoted; if (c == '&' && (semi = s.indexOf(';', i + 1)) >= 0 && ((quoted = entityToCharMap.get(s.substring(i, semi+1))) != null)) { buf.append(quoted); i = semi; } else buf.append(c); } return buf.toString(); } /** {@collect.stats} * Make the string that will go inside "..." for a value that is not * a plain String. * @throws RuntimeOperationsException if the value cannot be encoded. */ private static String makeFieldValue(Object value) { if (value == null) return "(null)"; Class<?> valueClass = value.getClass(); try { valueClass.getConstructor(String.class); } catch (NoSuchMethodException e) { final String msg = "Class " + valueClass + " does not have a public " + "constructor with a single string arg"; final RuntimeException iae = new IllegalArgumentException(msg); throw new RuntimeOperationsException(iae, "Cannot make XML descriptor"); } catch (SecurityException e) { // OK: we'll pretend the constructor is there // too bad if it's not: we'll find out when we try to // reconstruct the DescriptorSupport } final String quotedValueString = quote(value.toString()); return "(" + valueClass.getName() + "/" + quotedValueString + ")"; } /* * Parse a field value from the XML produced by toXMLString(). * Given a descriptor XML containing <field name="nnn" value="vvv">, * the argument to this method will be "vvv" (a string including the * containing quote characters). If vvv begins and ends with parentheses, * then it may contain: * - the characters "null", in which case the result is null; * - a value of the form "some.class.name/xxx", in which case the * result is equivalent to `new some.class.name("xxx")'; * - some other string, in which case the result is that string, * without the parentheses. */ private static Object parseQuotedFieldValue(String s) throws XMLParseException { s = unquote(s); if (s.equalsIgnoreCase("(null)")) return null; if (!s.startsWith("(") || !s.endsWith(")")) return s; final int slash = s.indexOf('/'); if (slash < 0) { // compatibility: old code didn't include class name return s.substring(1, s.length() - 1); } final String className = s.substring(1, slash); final Constructor<?> constr; try { final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader == null) { ReflectUtil.checkPackageAccess(className); } final Class<?> c = Class.forName(className, false, contextClassLoader); constr = c.getConstructor(new Class[] {String.class}); } catch (Exception e) { throw new XMLParseException(e, "Cannot parse value: <" + s + ">"); } final String arg = s.substring(slash + 1, s.length() - 1); try { return constr.newInstance(new Object[] {arg}); } catch (Exception e) { final String msg = "Cannot construct instance of " + className + " with arg: <" + s + ">"; throw new XMLParseException(e, msg); } } /** {@collect.stats} * Returns <pv>a human readable string representing the * descriptor</pv>. The string will be in the format of * "fieldName=fieldValue,fieldName2=fieldValue2,..."<br> * * If there are no fields in the descriptor, then an empty String * is returned.<br> * * If a fieldValue is an object then the toString() method is * called on it and its returned value is used as the value for * the field enclosed in parenthesis. * * @exception RuntimeOperationsException for illegal value for * field Names or field Values. If the descriptor string fails * for any reason, this exception will be thrown. */ public synchronized String toString() { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "toString()", "Entry"); } String respStr = ""; String[] fields = getFields(); if ((fields == null) || (fields.length == 0)) { if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "toString()", "Empty Descriptor"); } return respStr; } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "toString()", "Printing " + fields.length + " fields"); } for (int i=0; i < fields.length; i++) { if (i == (fields.length - 1)) { respStr = respStr.concat(fields[i]); } else { respStr = respStr.concat(fields[i] + ", "); } } if (MODELMBEAN_LOGGER.isLoggable(Level.FINEST)) { MODELMBEAN_LOGGER.logp(Level.FINEST, DescriptorSupport.class.getName(), "toString()", "Exit returning " + respStr); } return respStr; } // utility to convert to int, returns -2 if bogus. private long toNumeric(String inStr) { long result = -2; try { result = java.lang.Long.parseLong(inStr); } catch (Exception e) { return -2; } return result; } /** {@collect.stats} * Deserializes a {@link DescriptorSupport} from an {@link * ObjectInputStream}. */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = in.readFields(); Map<String, Object> descriptor = cast(fields.get("descriptor", null)); init(null); if (descriptor != null) { descriptorMap.putAll(descriptor); } } /** {@collect.stats} * Serializes a {@link DescriptorSupport} to an {@link ObjectOutputStream}. */ /* If you set jmx.serial.form to "1.2.0" or "1.2.1", then we are bug-compatible with those versions. Specifically, field names are forced to lower-case before being written. This contradicts the spec, which, though it does not mention serialization explicitly, does say that the case of field names is preserved. But in 1.2.0 and 1.2.1, this requirement was not met. Instead, field names in the descriptor map were forced to lower case. Those versions expect this to have happened to a descriptor they deserialize and e.g. getFieldValue will not find a field whose name is spelt with a different case. */ private void writeObject(ObjectOutputStream out) throws IOException { ObjectOutputStream.PutField fields = out.putFields(); boolean compat = "1.0".equals(serialForm); if (compat) fields.put("currClass", currClass); /* Purge the field "targetObject" from the DescriptorSupport before * serializing since the referenced object is typically not * serializable. We do this here rather than purging the "descriptor" * variable below because that HashMap doesn't do case-insensitivity. * See CR 6332962. */ SortedMap<String, Object> startMap = descriptorMap; if (startMap.containsKey("targetObject")) { startMap = new TreeMap<String, Object>(descriptorMap); startMap.remove("targetObject"); } final HashMap<String, Object> descriptor; if (compat || "1.2.0".equals(serialForm) || "1.2.1".equals(serialForm)) { descriptor = new HashMap<String, Object>(); for (Map.Entry<String, Object> entry : startMap.entrySet()) descriptor.put(entry.getKey().toLowerCase(), entry.getValue()); } else descriptor = new HashMap<String, Object>(startMap); fields.put("descriptor", descriptor); out.writeFields(); } }
/** * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.waveprotocol.wave.concurrencycontrol.client; import org.waveprotocol.wave.concurrencycontrol.common.ChannelException; import org.waveprotocol.wave.model.operation.OperationException; import org.waveprotocol.wave.model.operation.TransformException; import org.waveprotocol.wave.model.operation.wave.TransformedWaveletDelta; import org.waveprotocol.wave.model.version.HashedVersion; import java.util.List; /** * This allows a class to listen for operations from the server arriving from * the ServerConnection. A class that implements this interface would register * with a ServerConnection to receive the operations. * * @author zdwang@google.com (David Wang) */ public interface ServerConnectionListener { /** * Called when the wave is (re-)opened and before receiving deltas from the * server. * * @param connectVersion The signature of the wave at the version at which the * wave is opened (non-null). * @param currentVersion The signature of the wave at the server's current * version (non-null). */ public void onOpen(HashedVersion connectVersion, HashedVersion currentVersion) throws ChannelException; /** * Called when a delta is received from the server. * * @param delta * @throws TransformException There is an operation in the process of * transforming the received operation. * @throws OperationException Failed to apply the server operation to the * client's editor. */ public void onServerDelta(TransformedWaveletDelta delta) throws TransformException, OperationException; /** * Called when deltas are received from the server. This is significant * because, having a list of deltas means that if the client needs to resend * deltas to the server using the CVS model, it only needs to send them at the * end of all the transformation, rather than once per server delta which is * wasteful as we can already tell if there are more server messages, they * will be nacked. * * @param deltas * @throws TransformException There is an operation in the process of * transforming the received operations. * @throws OperationException Failed to apply the server operation to the * client's editor. */ public void onServerDeltas(List<TransformedWaveletDelta> deltas) throws TransformException, OperationException; /** * Called when acknowledgement is received from the server for an operation * issued by this client. * * @param operationsApplied Number of operations to ack. * @param signature The signature after the client operations being applied on * the server. * @throws TransformException There is an operation in the process of * transforming any existing operations. * @throws OperationException */ public void onSuccess(int operationsApplied, HashedVersion signature) throws TransformException, OperationException; /** * Called when the server advertises that the delta at some version has been * committed to persistent storage. The client can clear any cache that is * used for recovery before that version. */ public void onCommit(long version); }
package com.example.contest_2019_1.part_activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import com.autonavi.amap.mapcore.interfaces.INavigateArrow; import com.example.contest_2019_1.R; import java.util.Calendar; public class Pro6_2 extends AppCompatActivity { String date = ""; Boolean isFirst = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.pro6_2); DatePicker pro6_dataprcker = findViewById(R.id.pro6_dataprcker); final TextView txt_pro6_2_date = findViewById(R.id.txt_pro6_2_date); Button btn_pro6_next2 = findViewById(R.id.btn_pro6_next2); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); btn_pro6_next2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Pro6_2.this, Pro6_3.class); intent.putExtra("date",date); startActivity(intent); } }); pro6_dataprcker.init(year, month, day, new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { if (isFirst){ date = year+"-"+monthOfYear+"-"+dayOfMonth; isFirst = false; }else { date = date+"\n"+year+"-"+monthOfYear+"-"+dayOfMonth; } txt_pro6_2_date.setText(date); } }); } }
package mont.gonzalo.phiuba.model; import android.os.Build; import android.support.annotation.RequiresApi; import android.util.Range; import java.io.Serializable; public class UserCourse implements Serializable { private Course course; private CourseStatus status; private CathedraSchedule schedule; private Integer calification = 0; public UserCourse(Course course, CourseStatus status, Integer calif) { this.course = course; this.status = status; this.calification = calif; } public UserCourse(Course course, CourseStatus status) { this(course, status, null); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public boolean inRange(Integer i) { return getCalificationRange().contains(i); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) static protected Range getCalificationRange() { return new Range<Integer>(1, 10); } public Integer getCalification() { return calification; } public void setCalification(Integer calification) { this.calification = calification; } public CathedraSchedule getSchedule() { return schedule; } public void setSchedule(CathedraSchedule schedule) { this.schedule = schedule; } public CourseStatus getStatus() { return status; } public void setStatus(CourseStatus status) { this.status = status; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } }
package questao8; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JRadioButton; import javax.swing.JButton; import javax.swing.SwingConstants; import javax.swing.JTextArea; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class ViewSexo extends JFrame { private JPanel contentPane; private JTextField Campo_Nome; protected JTextArea Campo_Resultado; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ViewSexo frame = new ViewSexo(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ViewSexo() { setTitle("Definir Sexo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel("Digite o Nome:"); lblNewLabel.setBounds(10, 11, 101, 14); contentPane.add(lblNewLabel); Campo_Nome = new JTextField(); Campo_Nome.setBounds(133, 8, 240, 20); contentPane.add(Campo_Nome); Campo_Nome.setColumns(10); JLabel lblNewLabel_1 = new JLabel("Informe o Sexo:"); lblNewLabel_1.setBounds(10, 50, 117, 14); contentPane.add(lblNewLabel_1); JRadioButton Campo_Feminino = new JRadioButton("Feminino"); Campo_Feminino.setBounds(133, 46, 109, 23); contentPane.add(Campo_Feminino); JRadioButton Campo_Masculino = new JRadioButton("Masculino"); Campo_Masculino.setBounds(264, 46, 109, 23); contentPane.add(Campo_Masculino); JButton Campo_Verificar = new JButton("Verificar"); Campo_Verificar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String Nome=Campo_Nome.getText(); if(Campo_Feminino.isSelected()) { JOptionPane . showMessageDialog(null,"\n"+"Nome: "+Nome+"\n"+"Sexo: Feminino"); } else { if(Campo_Masculino.isSelected()) { JOptionPane . showMessageDialog(null,"\n"+"Nome: "+Nome+"\n"+"Sexo: Masculino"); } } } }); Campo_Verificar.setBounds(192, 93, 89, 23); contentPane.add(Campo_Verificar); } }
package com.senla.rakickaya.courseplanner.ui.actions.students; import java.util.List; import com.senla.rakickaya.courseplanner.api.beans.IStudent; import com.senla.rakickaya.courseplanner.api.data_exchange.IRequest; import com.senla.rakickaya.courseplanner.api.data_exchange.IResponse; import com.senla.rakickaya.courseplanner.api.data_exchange.enums.TagsRequest; import com.senla.rakickaya.courseplanner.api.data_exchange.enums.TagsResponse; import com.senla.rakickaya.courseplanner.api.facade.IFacade; import com.senla.rakickaya.courseplanner.di.ServiceDI; import com.senla.rakickaya.courseplanner.facade.dataExchange.RequestBuilder; import com.senla.rakickaya.courseplanner.ui.api.actions.IAction; import com.senla.rakickaya.courseplanner.ui.util.input.Input; import com.senla.rakickaya.courseplanner.ui.util.printer.Printer; public class StudentRemoval implements IAction { private ServiceDI service = ServiceDI.getInstance(); private IFacade facade = (IFacade) service.getObject(IFacade.class); @Override public void execute() { IResponse response = facade.getAllStudents(); @SuppressWarnings("unchecked") List<IStudent> students = (List<IStudent>) response.getObject(TagsResponse.DATA); Printer.showList(students); Input input = Input.getInstance(); Printer.show("Input the number to remove the Course"); int n = input.getInt(); IRequest request = new RequestBuilder() .setHead(TagsRequest.ID_STUDENT, String.valueOf(students.get(n - 1).getId())).build(); IResponse studentResponse = facade.removeStudent(request); Printer.show(studentResponse.getObject(TagsResponse.MESSAGE).toString()); } }
package com.code.model; public class Contato { private Integer id; private String nome; private String telefone; private String email; private String nascimento; private String endereco; public static Contato contatoSave; public static Contato getContatoSave() { return contatoSave; } public static void setContatoSave(Contato contatoSave) { Contato.contatoSave = contatoSave; } public Contato() { } public Contato(Integer id, String nome, String telefone, String email, String nascimento, String endereco) { this.id = id; this.nome = nome; this.telefone = telefone; this.email = email; this.nascimento = nascimento; this.endereco = endereco; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNascimento() { return nascimento; } public void setNascimento(String nascimento) { this.nascimento = nascimento; } public String getEndereco() { return endereco; } public void setEndereco(String endereco) { this.endereco = endereco; } @Override public String toString() { return "Contato{" + "id=" + id + ", nome=" + nome + ", telefone=" + telefone + ", email=" + email + ", nascimento=" + nascimento + ", endereco=" + endereco + '}'; } }
package adamin90.com.qqd.moled.wandetail; import java.util.ArrayList; import java.util.List; import javax.annotation.Generated; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; @Generated("org.jsonschema2pojo") public class Datas { @SerializedName("id") @Expose private String id; @SerializedName("uid") @Expose private String uid; @SerializedName("tid") @Expose private String tid; @SerializedName("title") @Expose private String title; @SerializedName("content") @Expose private String content; @SerializedName("desc") @Expose private String desc; @SerializedName("godate") @Expose private String godate; @SerializedName("starttime") @Expose private String starttime; @SerializedName("stoptime") @Expose private String stoptime; @SerializedName("address") @Expose private String address; @SerializedName("charge") @Expose private String charge; @SerializedName("contact") @Expose private String contact; @SerializedName("status") @Expose private String status; @SerializedName("sort") @Expose private String sort; @SerializedName("x_point") @Expose private String xPoint; @SerializedName("y_point") @Expose private String yPoint; @SerializedName("point_address") @Expose private String pointAddress; @SerializedName("vote") @Expose private String vote; @SerializedName("author") @Expose private String author; @SerializedName("signup") @Expose private String signup; @SerializedName("tname") @Expose private String tname; @SerializedName("imgs") @Expose private List<Img> imgs = new ArrayList<Img>(); @SerializedName("rnums") @Expose private String rnums; @SerializedName("rdatas") @Expose private List<Rdata> rdatas = new ArrayList<Rdata>(); /** * * @return * The id */ public String getId() { return id; } /** * * @param id * The id */ public void setId(String id) { this.id = id; } /** * * @return * The uid */ public String getUid() { return uid; } /** * * @param uid * The uid */ public void setUid(String uid) { this.uid = uid; } /** * * @return * The tid */ public String getTid() { return tid; } /** * * @param tid * The tid */ public void setTid(String tid) { this.tid = tid; } /** * * @return * The title */ public String getTitle() { return title; } /** * * @param title * The title */ public void setTitle(String title) { this.title = title; } /** * * @return * The content */ public String getContent() { return content; } /** * * @param content * The content */ public void setContent(String content) { this.content = content; } /** * * @return * The desc */ public String getDesc() { return desc; } /** * * @param desc * The desc */ public void setDesc(String desc) { this.desc = desc; } /** * * @return * The godate */ public String getGodate() { return godate; } /** * * @param godate * The godate */ public void setGodate(String godate) { this.godate = godate; } /** * * @return * The starttime */ public String getStarttime() { return starttime; } /** * * @param starttime * The starttime */ public void setStarttime(String starttime) { this.starttime = starttime; } /** * * @return * The stoptime */ public String getStoptime() { return stoptime; } /** * * @param stoptime * The stoptime */ public void setStoptime(String stoptime) { this.stoptime = stoptime; } /** * * @return * The address */ public String getAddress() { return address; } /** * * @param address * The address */ public void setAddress(String address) { this.address = address; } /** * * @return * The charge */ public String getCharge() { return charge; } /** * * @param charge * The charge */ public void setCharge(String charge) { this.charge = charge; } /** * * @return * The contact */ public String getContact() { return contact; } /** * * @param contact * The contact */ public void setContact(String contact) { this.contact = contact; } /** * * @return * The status */ public String getStatus() { return status; } /** * * @param status * The status */ public void setStatus(String status) { this.status = status; } /** * * @return * The sort */ public String getSort() { return sort; } /** * * @param sort * The sort */ public void setSort(String sort) { this.sort = sort; } /** * * @return * The xPoint */ public String getXPoint() { return xPoint; } /** * * @param xPoint * The x_point */ public void setXPoint(String xPoint) { this.xPoint = xPoint; } /** * * @return * The yPoint */ public String getYPoint() { return yPoint; } /** * * @param yPoint * The y_point */ public void setYPoint(String yPoint) { this.yPoint = yPoint; } /** * * @return * The pointAddress */ public String getPointAddress() { return pointAddress; } /** * * @param pointAddress * The point_address */ public void setPointAddress(String pointAddress) { this.pointAddress = pointAddress; } /** * * @return * The vote */ public String getVote() { return vote; } /** * * @param vote * The vote */ public void setVote(String vote) { this.vote = vote; } /** * * @return * The author */ public String getAuthor() { return author; } /** * * @param author * The author */ public void setAuthor(String author) { this.author = author; } /** * * @return * The signup */ public String getSignup() { return signup; } /** * * @param signup * The signup */ public void setSignup(String signup) { this.signup = signup; } /** * * @return * The tname */ public String getTname() { return tname; } /** * * @param tname * The tname */ public void setTname(String tname) { this.tname = tname; } /** * * @return * The imgs */ public List<Img> getImgs() { return imgs; } /** * * @param imgs * The imgs */ public void setImgs(List<Img> imgs) { this.imgs = imgs; } /** * * @return * The rnums */ public String getRnums() { return rnums; } /** * * @param rnums * The rnums */ public void setRnums(String rnums) { this.rnums = rnums; } /** * * @return * The rdatas */ public List<Rdata> getRdatas() { return rdatas; } /** * * @param rdatas * The rdatas */ public void setRdatas(List<Rdata> rdatas) { this.rdatas = rdatas; } }
package de.karzek.diettracker.presentation.main.cookbook.recipeDetails.adapter.viewHolder; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import de.karzek.diettracker.R; import de.karzek.diettracker.presentation.main.cookbook.recipeDetails.adapter.itemWrapper.RecipeDetailsViewItemWrapper; /** * Created by MarjanaKarzek on 30.05.2018. * * @author Marjana Karzek * @version 1.0 * @date 30.05.2018 */ public class RecipeDetailsIngredientsAndPortionsTitleViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.recipe_details_ingredients_title) TextView title; @BindView(R.id.expandable_nutrition_details_action) ImageButton arrow; private Context context; private boolean expanded = false; private OnExpandNutritionDetailsViewClickListener onExpandNutritionDetailsViewClickListener; public RecipeDetailsIngredientsAndPortionsTitleViewHolder(ViewGroup viewGroup, OnExpandNutritionDetailsViewClickListener onExpandNutritionDetailsViewClickListener) { super(LayoutInflater.from(viewGroup.getContext()) .inflate(R.layout.viewholder_recipe_details_ingredients_title_and_portions, viewGroup, false)); ButterKnife.bind(this, itemView); context = viewGroup.getContext(); this.onExpandNutritionDetailsViewClickListener = onExpandNutritionDetailsViewClickListener; } public void bind(RecipeDetailsViewItemWrapper item) { title.setText(item.getTitle()); } @OnClick(R.id.expandable_nutrition_details_action) void onExpandNutritionDetailsViewClicked(){ expanded = !expanded; if(expanded) arrow.setImageDrawable(context.getDrawable(R.drawable.ic_expand_less_primary_text)); else arrow.setImageDrawable(context.getDrawable(R.drawable.ic_expand_more_primary_text)); onExpandNutritionDetailsViewClickListener.onExpandNutritionDetailsViewClicked(); } public interface OnExpandNutritionDetailsViewClickListener { void onExpandNutritionDetailsViewClicked(); } }
/* * Copyright ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.enterchain.enter.tests.acceptance.mining; import org.enterchain.enter.cli.config.NetworkName; import org.enterchain.enter.tests.acceptance.dsl.AcceptanceTestBase; import org.enterchain.enter.tests.acceptance.dsl.account.Account; import org.enterchain.enter.tests.acceptance.dsl.node.Node; import org.enterchain.enter.tests.acceptance.dsl.node.configuration.BesuNodeConfigurationBuilder; import org.junit.Before; import org.junit.Test; public class KeccakMiningAcceptanceTest extends AcceptanceTestBase { private Node minerNode; @Before public void setUp() throws Exception { minerNode = besu.create( new BesuNodeConfigurationBuilder() .name("miner1") .devMode(false) .network(NetworkName.ECIP1049_DEV) .miningEnabled() .jsonRpcEnabled() .webSocketEnabled() .build()); cluster.start(minerNode); } @Test public void shouldMineTransactions() { final Account sender = accounts.createAccount("account1"); final Account receiver = accounts.createAccount("account2"); minerNode.execute(accountTransactions.createTransfer(sender, 50)); cluster.verify(sender.balanceEquals(50)); minerNode.execute(accountTransactions.createIncrementalTransfers(sender, receiver, 1)); cluster.verify(receiver.balanceEquals(1)); minerNode.execute(accountTransactions.createIncrementalTransfers(sender, receiver, 2)); cluster.verify(receiver.balanceEquals(3)); minerNode.execute(accountTransactions.createIncrementalTransfers(sender, receiver, 3)); cluster.verify(receiver.balanceEquals(6)); minerNode.execute(accountTransactions.createIncrementalTransfers(sender, receiver, 4)); cluster.verify(receiver.balanceEquals(10)); minerNode.execute(accountTransactions.createIncrementalTransfers(sender, receiver, 5)); cluster.verify(receiver.balanceEquals(15)); } }
/* * Copyright 2017-2020 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.micronaut.cli.io.support; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * A ResourcePatternResolver implementation that is able to resolve a * specified resource location path into one or more matching Resources. * The source path may be a simple path which has a one-to-one mapping to a * target Resource, or alternatively * may contain the special "<code>classpath*:</code>" prefix and/or * internal Ant-style regular expressions (matched using AntPathMatcher). * Both of the latter are effectively wildcards. * * <p><b>No Wildcards:</b> * * <p>In the simple case, if the specified location path does not start with the * <code>"classpath*:</code>" prefix, and does not contain a PathMatcher pattern, * this resolver will simply return a single resource via a * <code>getResource()</code> call on the underlying <code>ResourceLoader</code>. * Examples are real URLs such as "<code>file:C:/context.xml</code>", pseudo-URLs * such as "<code>classpath:/context.xml</code>", and simple unprefixed paths * such as "<code>/WEB-INF/context.xml</code>". The latter will resolve in a * fashion specific to the underlying <code>ResourceLoader</code> (e.g. * <code>ServletContextResource</code> for a <code>WebApplicationContext</code>). * * <p><b>Ant-style Patterns:</b> * * <p>When the path location contains an Ant-style pattern, e.g.: * <pre> * /WEB-INF/*-context.xml * com/mycompany/**&#47;applicationContext.xml * file:C:/some/path/*-context.xml * classpath:com/mycompany/**&#47;applicationContext.xml</pre> * the resolver follows a more complex but defined procedure to try to resolve * the wildcard. It produces a <code>Resource</code> for the path up to the last * non-wildcard segment and obtains a <code>URL</code> from it. If this URL is * not a "<code>jar:</code>" URL or container-specific variant (e.g. * "<code>zip:</code>" in WebLogic, "<code>wsjar</code>" in WebSphere", etc.), * then a <code>java.io.File</code> is obtained from it, and used to resolve the * wildcard by walking the filesystem. In the case of a jar URL, the resolver * either gets a <code>java.net.JarURLConnection</code> from it, or manually parses * the jar URL, and then traverses the contents of the jar file, to resolve the * wildcards. * * <p><b>Implications on portability:</b> * * <p>If the specified path is already a file URL (either explicitly, or * implicitly because the base <code>ResourceLoader</code> is a filesystem one, * then wildcarding is guaranteed to work in a completely portable fashion. * * <p>If the specified path is a classpath location, then the resolver must * obtain the last non-wildcard path segment URL via a * <code>Classloader.getResource()</code> call. Since this is just a * node of the path (not the file at the end) it is actually undefined * (in the ClassLoader Javadocs) exactly what sort of a URL is returned in * this case. In practice, it is usually a <code>java.io.File</code> representing * the directory, where the classpath resource resolves to a filesystem * location, or a jar URL of some sort, where the classpath resource resolves * to a jar location. Still, there is a portability concern on this operation. * * <p>If a jar URL is obtained for the last non-wildcard segment, the resolver * must be able to get a <code>java.net.JarURLConnection</code> from it, or * manually parse the jar URL, to be able to walk the contents of the jar, * and resolve the wildcard. This will work in most environments, but will * fail in others, and it is strongly recommended that the wildcard * resolution of resources coming from jars be thoroughly tested in your * specific environment before you rely on it. * * <p><b><code>classpath*:</code> Prefix:</b> * * <p>There is special support for retrieving multiple class path resources with * the same name, via the "<code>classpath*:</code>" prefix. For example, * "<code>classpath*:META-INF/beans.xml</code>" will find all "beans.xml" * files in the class path, be it in "classes" directories or in JAR files. * This is particularly useful for autodetecting config files of the same name * at the same location within each jar file. Internally, this happens via a * <code>ClassLoader.getResources()</code> call, and is completely portable. * * <p>The "classpath*:" prefix can also be combined with a PathMatcher pattern in * the rest of the location path, for example "classpath*:META-INF/*-beans.xml". * In this case, the resolution strategy is fairly simple: a * <code>ClassLoader.getResources()</code> call is used on the last non-wildcard * path segment to get all the matching resources in the class loader hierarchy, * and then off each resource the same PathMatcher resolution strategy described * above is used for the wildcard subpath. * * <p><b>Other notes:</b> * * <p><b>WARNING:</b> Note that "<code>classpath*:</code>" when combined with * Ant-style patterns will only work reliably with at least one root directory * before the pattern starts, unless the actual target files reside in the file * system. This means that a pattern like "<code>classpath*:*.xml</code>" will * <i>not</i> retrieve files from the root of jar files but rather only from the * root of expanded directories. This originates from a limitation in the JDK's * <code>ClassLoader.getResources()</code> method which only returns file system * locations for a passed-in empty String (indicating potential roots to search). * * <p><b>WARNING:</b> Ant-style patterns with "classpath:" resources are not * guaranteed to find matching resources if the root package to search is available * in multiple class path locations. This is because a resource such as<pre> * com/mycompany/package1/service-context.xml * </pre>may be in only one location, but when a path such as<pre> * classpath:com/mycompany/**&#47;service-context.xml * </pre>is used to try to resolve it, the resolver will work off the (first) URL * returned by <code>getResource("com/mycompany");</code>. If this base package * node exists in multiple classloader locations, the actual end resource may * not be underneath. Therefore, preferably, use "<code>classpath*:</code>" with the same * Ant-style pattern in such a case, which will search <i>all</i> class path * locations that contain the root package. * * @author Juergen Hoeller * @author Colin Sampaleanu * @author Marius Bogoevici * @author Costin Leau * @see java.lang.ClassLoader#getResources(String) * @since 1.0.2 */ public class PathMatchingResourcePatternResolver { private static final String CLASSPATH_ALL_URL_PREFIX = "classpath*:"; private final ResourceLoader resourceLoader; private AntPathMatcher pathMatcher = new AntPathMatcher(); /** * Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader. * <p>ClassLoader access will happen via the thread context class loader. */ public PathMatchingResourcePatternResolver() { resourceLoader = new DefaultResourceLoader(); } /** * Create a new PathMatchingResourcePatternResolver with a DefaultResourceLoader. * * @param classLoader the ClassLoader to load classpath resources with, * or <code>null</code> for using the thread context class loader * at the time of actual resource access */ public PathMatchingResourcePatternResolver(ClassLoader classLoader) { resourceLoader = new DefaultResourceLoader(classLoader); } /** * Create a new PathMatchingResourcePatternResolver. * <p>ClassLoader access will happen via the thread context class loader. * * @param resourceLoader the ResourceLoader to load root directories and * actual resources with */ public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } /** * @return The ResourceLoader that this pattern resolver works with. */ public ResourceLoader getResourceLoader() { return resourceLoader; } /** * @return The ClassLoader that this pattern resolver works with * (never <code>null</code>). */ public ClassLoader getClassLoader() { return getResourceLoader().getClassLoader(); } /** * Set the PathMatcher implementation to use for this * resource pattern resolver. Default is AntPathMatcher. * * @param pathMatcher The path matcher */ public void setPathMatcher(AntPathMatcher pathMatcher) { this.pathMatcher = pathMatcher; } /** * @return The PathMatcher that this resource pattern resolver uses. */ public AntPathMatcher getPathMatcher() { return pathMatcher; } /** * @param location The location * @return The resource */ public Resource getResource(String location) { return getResourceLoader().getResource(location); } /** * @param locationPattern The location pattern * @return The resources * @throws IOException if there is an error */ public Resource[] getResources(String locationPattern) throws IOException { if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) { // a class path resource (multiple resources for same name possible) if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) { // a class path resource pattern return findPathMatchingResources(locationPattern); } // all class path resources with the given name return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length())); } // Only look for a pattern after a prefix here // (to not get fooled by a pattern symbol in a strange prefix). int prefixEnd = locationPattern.indexOf(":") + 1; if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) { // a file pattern return findPathMatchingResources(locationPattern); } // a single resource with the given name return new Resource[]{getResourceLoader().getResource(locationPattern)}; } /** * Find all class location resources with the given location via the ClassLoader. * * @param location the absolute path within the classpath * @return the result as Resource array * @throws IOException in case of I/O errors * @see java.lang.ClassLoader#getResources * @see #convertClassLoaderURL */ @SuppressWarnings("MagicNumber") protected Resource[] findAllClassPathResources(String location) throws IOException { String path = location; if (path.startsWith("/")) { path = path.substring(1); } Enumeration<URL> resourceUrls = getClassLoader().getResources(path); Set<Resource> result = new LinkedHashSet<Resource>(16); while (resourceUrls.hasMoreElements()) { URL url = resourceUrls.nextElement(); result.add(convertClassLoaderURL(url)); } return result.toArray(new Resource[0]); } /** * Convert the given URL as returned from the ClassLoader into a Resource object. * <p>The default implementation simply creates a UrlResource instance. * * @param url a URL as returned from the ClassLoader * @return the corresponding Resource object * @see java.lang.ClassLoader#getResources */ protected Resource convertClassLoaderURL(URL url) { return new UrlResource(url); } /** * Find all resources that match the given location pattern via the * Ant-style PathMatcher. Supports resources in jar files and zip files * and in the file system. * * @param locationPattern the location pattern to match * @return the result as Resource array * @throws IOException in case of I/O errors * @see #doFindPathMatchingJarResources * @see #doFindPathMatchingFileResources */ @SuppressWarnings("MagicNumber") protected Resource[] findPathMatchingResources(String locationPattern) throws IOException { String rootDirPath = determineRootDir(locationPattern); String subPattern = locationPattern.substring(rootDirPath.length()); Resource[] rootDirResources = getResources(rootDirPath); Set<Resource> result = new LinkedHashSet<Resource>(16); for (Resource rootDirResource : rootDirResources) { rootDirResource = resolveRootDirResource(rootDirResource); if (isJarResource(rootDirResource)) { result.addAll(doFindPathMatchingJarResources(rootDirResource, subPattern)); } else { result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern)); } } return result.toArray(new Resource[0]); } /** * Determine the root directory for the given location. * <p>Used for determining the starting point for file matching, * resolving the root directory location to a <code>java.io.File</code> * and passing it into <code>retrieveMatchingFiles</code>, with the * remainder of the location as pattern. * <p>Will return "/WEB-INF/" for the pattern "/WEB-INF/*.xml", * for example. * * @param location the location to check * @return the part of the location that denotes the root directory * @see #retrieveMatchingFiles */ protected String determineRootDir(String location) { int prefixEnd = location.indexOf(":") + 1; int rootDirEnd = location.length(); while (rootDirEnd > prefixEnd && getPathMatcher().isPattern(location.substring(prefixEnd, rootDirEnd))) { rootDirEnd = location.lastIndexOf('/', rootDirEnd - 2) + 1; } if (rootDirEnd == 0) { rootDirEnd = prefixEnd; } return location.substring(0, rootDirEnd); } /** * Resolve the specified resource for path matching. * <p>The default implementation detects an Equinox OSGi "bundleresource:" * / "bundleentry:" URL and resolves it into a standard jar file URL that * can be traversed using Spring's standard jar file traversal algorithm. * * @param original the resource to resolve * @return the resolved resource (may be identical to the passed-in resource) * @throws IOException in case of resolution failure */ protected Resource resolveRootDirResource(Resource original) throws IOException { return original; } /** * @param resource the resource handle to check (usually the root directory to start path matching from) * @return Whether the given resource handle indicates a jar resource that the <code>doFindPathMatchingJarResources</code> * method can handle. * The default implementation checks against the URL protocols "jar", "zip" and "wsjar" (the latter are used by * BEA WebLogic Server and IBM WebSphere, respectively, but can be treated like jar files). * @throws IOException if there is an error * @see #doFindPathMatchingJarResources */ protected boolean isJarResource(Resource resource) throws IOException { return ResourceUtils.isJarURL(resource.getURL()); } /** * Find all resources in jar files that match the given location pattern * via the Ant-style PathMatcher. * * @param rootDirResource the root directory as Resource * @param subPattern the sub pattern to match (below the root directory) * @return the Set of matching Resource instances * @throws IOException in case of I/O errors * @see java.net.JarURLConnection */ @SuppressWarnings("MagicNumber") protected Set<Resource> doFindPathMatchingJarResources(Resource rootDirResource, String subPattern) throws IOException { URLConnection con = rootDirResource.getURL().openConnection(); JarFile jarFile; String jarFileUrl; String rootEntryPath; boolean newJarFile = false; if (con instanceof JarURLConnection) { // Should usually be the case for traditional JAR files. JarURLConnection jarCon = (JarURLConnection) con; ResourceUtils.useCachesIfNecessary(jarCon); jarFile = jarCon.getJarFile(); jarFileUrl = jarCon.getJarFileURL().toExternalForm(); JarEntry jarEntry = jarCon.getJarEntry(); rootEntryPath = (jarEntry != null ? jarEntry.getName() : ""); } else { // No JarURLConnection -> need to resort to URL file parsing. // We'll assume URLs of the format "jar:path!/entry", with the protocol // being arbitrary as long as following the entry format. // We'll also handle paths with and without leading "file:" prefix. String urlFile = rootDirResource.getURL().getFile(); int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR); if (separatorIndex != -1) { jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length()); jarFile = getJarFile(jarFileUrl); } else { jarFile = new JarFile(urlFile); jarFileUrl = urlFile; rootEntryPath = ""; } newJarFile = true; } try { if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) { // Root entry path must end with slash to allow for proper matching. // The Sun JRE does not return a slash here, but BEA JRockit does. rootEntryPath = rootEntryPath + "/"; } Set<Resource> result = new LinkedHashSet<Resource>(8); for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); if (entryPath.startsWith(rootEntryPath)) { String relativePath = entryPath.substring(rootEntryPath.length()); if (getPathMatcher().match(subPattern, relativePath)) { result.add(rootDirResource.createRelative(relativePath)); } } } return result; } finally { // Close jar file, but only if freshly obtained - // not from JarURLConnection, which might cache the file reference. if (newJarFile) { jarFile.close(); } } } /** * Resolve the given jar file URL into a JarFile object. * * @param jarFileUrl The jar file URL * @return The jar file. * @throws IOException if there is an error */ protected JarFile getJarFile(String jarFileUrl) throws IOException { if (jarFileUrl.startsWith(ResourceUtils.FILE_URL_PREFIX)) { try { return new JarFile(ResourceUtils.toURI(jarFileUrl).getSchemeSpecificPart()); } catch (URISyntaxException ex) { // Fallback for URLs that are not valid URIs (should hardly ever happen). return new JarFile(jarFileUrl.substring(ResourceUtils.FILE_URL_PREFIX.length())); } } return new JarFile(jarFileUrl); } /** * Find all resources in the file system that match the given location pattern * via the Ant-style PathMatcher. * * @param rootDirResource the root directory as Resource * @param subPattern the sub pattern to match (below the root directory) * @return the Set of matching Resource instances * @throws IOException in case of I/O errors * @see #retrieveMatchingFiles */ protected Set<Resource> doFindPathMatchingFileResources(Resource rootDirResource, String subPattern) throws IOException { File rootDir; try { rootDir = rootDirResource.getFile().getAbsoluteFile(); } catch (IOException ex) { return Collections.emptySet(); } return doFindMatchingFileSystemResources(rootDir, subPattern); } /** * Find all resources in the file system that match the given location pattern * via the Ant-style PathMatcher. * * @param rootDir the root directory in the file system * @param subPattern the sub pattern to match (below the root directory) * @return the Set of matching Resource instances * @throws IOException in case of I/O errors * @see #retrieveMatchingFiles */ protected Set<Resource> doFindMatchingFileSystemResources(File rootDir, String subPattern) throws IOException { Set<File> matchingFiles = retrieveMatchingFiles(rootDir, subPattern); Set<Resource> result = new LinkedHashSet<Resource>(matchingFiles.size()); for (File file : matchingFiles) { result.add(new FileSystemResource(file)); } return result; } /** * Retrieve files that match the given path pattern, * checking the given directory and its subdirectories. * * @param rootDir the directory to start from * @param pattern the pattern to match against, * relative to the root directory * @return the Set of matching File instances * @throws IOException if directory contents could not be retrieved */ @SuppressWarnings("MagicNumber") protected Set<File> retrieveMatchingFiles(File rootDir, String pattern) throws IOException { if (!rootDir.exists()) { // Silently skip non-existing directories. return Collections.emptySet(); } if (!rootDir.isDirectory()) { // Complain louder if it exists but is no directory. return Collections.emptySet(); } if (!rootDir.canRead()) { return Collections.emptySet(); } String fullPattern = rootDir.getAbsolutePath().replace(File.separator, "/"); if (!pattern.startsWith("/")) { fullPattern += "/"; } fullPattern = fullPattern + pattern.replace(File.separator, "/"); Set<File> result = new LinkedHashSet<File>(8); doRetrieveMatchingFiles(fullPattern, rootDir, result); return result; } /** * Recursively retrieve files that match the given pattern, * adding them to the given result list. * * @param fullPattern the pattern to match against, * with prepended root directory path * @param dir the current directory * @param result the Set of matching File instances to add to * @throws IOException if directory contents could not be retrieved */ protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException { File[] dirContents = dir.listFiles(); if (dirContents == null) { return; } for (File content : dirContents) { String currPath = content.getAbsolutePath().replace(File.separator, "/"); if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) { if (content.canRead()) { doRetrieveMatchingFiles(fullPattern, content, result); } } if (getPathMatcher().match(fullPattern, currPath)) { result.add(content); } } } }
package com.commerce.backend.dto; import com.commerce.backend.validator.PasswordMatches; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; @Getter @Setter @ToString @NoArgsConstructor @PasswordMatches public class PasswordResetDTO { @NotNull @NotEmpty private String oldPassword; @NotNull @NotEmpty private String newPassword; @NotNull @NotEmpty private String newPasswordConfirm; }
package com.customize.test.self.factory_method; /** * @author phil * @date 2020/11/20 22:26 */ public class StaticFactory { public static YoungPeople getYoungPeople(String name){ YoungPeople youngPeople = new YoungPeople(); youngPeople.setId(1); youngPeople.setName(name); return youngPeople; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.core.common; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.commons.io.FileUtils; import org.apache.pinot.spi.config.table.TableConfig; import org.apache.pinot.spi.config.table.TableType; import org.apache.pinot.spi.data.DimensionFieldSpec; import org.apache.pinot.spi.data.FieldSpec; import org.apache.pinot.spi.data.MetricFieldSpec; import org.apache.pinot.spi.data.Schema; import org.apache.pinot.common.segment.ReadMode; import org.apache.pinot.spi.data.readers.GenericRow; import org.apache.pinot.core.data.readers.GenericRowRecordReader; import org.apache.pinot.core.indexsegment.IndexSegment; import org.apache.pinot.core.indexsegment.generator.SegmentGeneratorConfig; import org.apache.pinot.core.indexsegment.immutable.ImmutableSegmentLoader; import org.apache.pinot.core.segment.creator.impl.SegmentIndexCreationDriverImpl; import org.apache.pinot.spi.utils.builder.TableConfigBuilder; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class DataFetcherTest { private static final String SEGMENT_NAME = "dataFetcherTestSegment"; private static final String INDEX_DIR_PATH = FileUtils.getTempDirectoryPath() + File.separator + SEGMENT_NAME; private static final int NUM_ROWS = 1000; private static final String DIMENSION_NAME = "dimension"; private static final String INT_METRIC_NAME = "int_metric"; private static final String LONG_METRIC_NAME = "long_metric"; private static final String FLOAT_METRIC_NAME = "float_metric"; private static final String DOUBLE_METRIC_NAME = "double_metric"; private static final String NO_DICT_INT_METRIC_NAME = "no_dict_int_metric"; private static final String NO_DICT_LONG_METRIC_NAME = "no_dict_long_metric"; private static final String NO_DICT_FLOAT_METRIC_NAME = "no_dict_float_metric"; private static final String NO_DICT_DOUBLE_METRIC_NAME = "no_dict_double_metric"; private static final int MAX_STEP_LENGTH = 5; private final long _randomSeed = System.currentTimeMillis(); private final Random _random = new Random(_randomSeed); private final String _errorMessage = "Random seed is: " + _randomSeed; private final String[] _dimensionValues = new String[NUM_ROWS]; private final int[] _intMetricValues = new int[NUM_ROWS]; private final long[] _longMetricValues = new long[NUM_ROWS]; private final float[] _floatMetricValues = new float[NUM_ROWS]; private final double[] _doubleMetricValues = new double[NUM_ROWS]; private DataFetcher _dataFetcher; @BeforeClass private void setup() throws Exception { List<GenericRow> rows = new ArrayList<>(NUM_ROWS); // Generate random dimension and metric values. for (int i = 0; i < NUM_ROWS; i++) { double randomDouble = _random.nextDouble(); String randomDoubleString = String.valueOf(randomDouble); _dimensionValues[i] = randomDoubleString; _intMetricValues[i] = (int) randomDouble; _longMetricValues[i] = (long) randomDouble; _floatMetricValues[i] = (float) randomDouble; _doubleMetricValues[i] = randomDouble; HashMap<String, Object> map = new HashMap<>(); map.put(DIMENSION_NAME, _dimensionValues[i]); map.put(INT_METRIC_NAME, _intMetricValues[i]); map.put(LONG_METRIC_NAME, _longMetricValues[i]); map.put(FLOAT_METRIC_NAME, _floatMetricValues[i]); map.put(DOUBLE_METRIC_NAME, _doubleMetricValues[i]); map.put(NO_DICT_INT_METRIC_NAME, _intMetricValues[i]); map.put(NO_DICT_LONG_METRIC_NAME, _longMetricValues[i]); map.put(NO_DICT_FLOAT_METRIC_NAME, _floatMetricValues[i]); map.put(NO_DICT_DOUBLE_METRIC_NAME, _doubleMetricValues[i]); GenericRow genericRow = new GenericRow(); genericRow.init(map); rows.add(genericRow); } // Create an index segment with the random dimension and metric values. final Schema schema = new Schema(); schema.addField(new DimensionFieldSpec(DIMENSION_NAME, FieldSpec.DataType.STRING, true)); schema.addField(new MetricFieldSpec(INT_METRIC_NAME, FieldSpec.DataType.INT)); schema.addField(new MetricFieldSpec(LONG_METRIC_NAME, FieldSpec.DataType.LONG)); schema.addField(new MetricFieldSpec(FLOAT_METRIC_NAME, FieldSpec.DataType.FLOAT)); schema.addField(new MetricFieldSpec(DOUBLE_METRIC_NAME, FieldSpec.DataType.DOUBLE)); schema.addField(new MetricFieldSpec(NO_DICT_INT_METRIC_NAME, FieldSpec.DataType.INT)); schema.addField(new MetricFieldSpec(NO_DICT_LONG_METRIC_NAME, FieldSpec.DataType.LONG)); schema.addField(new MetricFieldSpec(NO_DICT_FLOAT_METRIC_NAME, FieldSpec.DataType.FLOAT)); schema.addField(new MetricFieldSpec(NO_DICT_DOUBLE_METRIC_NAME, FieldSpec.DataType.DOUBLE)); TableConfig tableConfig = new TableConfigBuilder(TableType.OFFLINE).setTableName("test").build(); SegmentGeneratorConfig config = new SegmentGeneratorConfig(tableConfig, schema); FileUtils.deleteQuietly(new File(INDEX_DIR_PATH)); config.setOutDir(INDEX_DIR_PATH); config.setSegmentName(SEGMENT_NAME); config.setRawIndexCreationColumns(Arrays .asList(NO_DICT_INT_METRIC_NAME, NO_DICT_LONG_METRIC_NAME, NO_DICT_FLOAT_METRIC_NAME, NO_DICT_DOUBLE_METRIC_NAME)); SegmentIndexCreationDriverImpl driver = new SegmentIndexCreationDriverImpl(); driver.init(config, new GenericRowRecordReader(rows)); driver.build(); IndexSegment indexSegment = ImmutableSegmentLoader.load(new File(INDEX_DIR_PATH, SEGMENT_NAME), ReadMode.heap); Map<String, DataSource> dataSourceMap = new HashMap<>(); for (String column : indexSegment.getPhysicalColumnNames()) { dataSourceMap.put(column, indexSegment.getDataSource(column)); } // Get a data fetcher for the index segment. _dataFetcher = new DataFetcher(dataSourceMap); } @Test public void testFetchSingleIntValues() { testFetchSingleIntValues(INT_METRIC_NAME); testFetchSingleIntValues(NO_DICT_INT_METRIC_NAME); } @Test public void testFetchSingleLongValues() { testFetchSingleLongValues(LONG_METRIC_NAME); testFetchSingleLongValues(NO_DICT_LONG_METRIC_NAME); } @Test public void testFetchSingleFloatValues() { testFetchSingleFloatValues(FLOAT_METRIC_NAME); testFetchSingleFloatValues(NO_DICT_FLOAT_METRIC_NAME); } @Test public void testFetchSingleDoubleValues() { testFetchSingleDoubleValues(DOUBLE_METRIC_NAME); testFetchSingleDoubleValues(NO_DICT_DOUBLE_METRIC_NAME); } public void testFetchSingleIntValues(String column) { int[] docIds = new int[NUM_ROWS]; int length = 0; for (int i = _random.nextInt(MAX_STEP_LENGTH); i < NUM_ROWS; i += _random.nextInt(MAX_STEP_LENGTH) + 1) { docIds[length++] = i; } int[] intValues = new int[length]; _dataFetcher.fetchIntValues(column, docIds, length, intValues); for (int i = 0; i < length; i++) { Assert.assertEquals(intValues[i], _intMetricValues[docIds[i]], _errorMessage); } } public void testFetchSingleLongValues(String column) { int[] docIds = new int[NUM_ROWS]; int length = 0; for (int i = _random.nextInt(MAX_STEP_LENGTH); i < NUM_ROWS; i += _random.nextInt(MAX_STEP_LENGTH) + 1) { docIds[length++] = i; } long[] longValues = new long[length]; _dataFetcher.fetchLongValues(column, docIds, length, longValues); for (int i = 0; i < length; i++) { Assert.assertEquals(longValues[i], _longMetricValues[docIds[i]], _errorMessage); } } public void testFetchSingleFloatValues(String column) { int[] docIds = new int[NUM_ROWS]; int length = 0; for (int i = _random.nextInt(MAX_STEP_LENGTH); i < NUM_ROWS; i += _random.nextInt(MAX_STEP_LENGTH) + 1) { docIds[length++] = i; } float[] floatValues = new float[length]; _dataFetcher.fetchFloatValues(column, docIds, length, floatValues); for (int i = 0; i < length; i++) { Assert.assertEquals(floatValues[i], _floatMetricValues[docIds[i]], _errorMessage); } } public void testFetchSingleDoubleValues(String column) { int[] docIds = new int[NUM_ROWS]; int length = 0; for (int i = _random.nextInt(MAX_STEP_LENGTH); i < NUM_ROWS; i += _random.nextInt(MAX_STEP_LENGTH) + 1) { docIds[length++] = i; } double[] doubleValues = new double[length]; _dataFetcher.fetchDoubleValues(column, docIds, length, doubleValues); for (int i = 0; i < length; i++) { Assert.assertEquals(doubleValues[i], _doubleMetricValues[docIds[i]], _errorMessage); } } @Test public void testFetchSingleStringValues() { int[] docIds = new int[NUM_ROWS]; int length = 0; for (int i = _random.nextInt(MAX_STEP_LENGTH); i < NUM_ROWS; i += _random.nextInt(MAX_STEP_LENGTH) + 1) { docIds[length++] = i; } String[] stringValues = new String[length]; _dataFetcher.fetchStringValues(DIMENSION_NAME, docIds, length, stringValues); for (int i = 0; i < length; i++) { Assert.assertEquals(stringValues[i], _dimensionValues[docIds[i]], _errorMessage); } } @AfterClass public void cleanUp() { FileUtils.deleteQuietly(new File(INDEX_DIR_PATH)); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.raptor; import com.facebook.presto.raptor.metadata.ForMetadata; import com.facebook.presto.raptor.metadata.MetadataDao; import com.facebook.presto.raptor.metadata.MetadataDaoUtils; import com.facebook.presto.raptor.metadata.ShardManager; import com.facebook.presto.raptor.metadata.ShardNode; import com.facebook.presto.raptor.metadata.Table; import com.facebook.presto.raptor.metadata.TableColumn; import com.facebook.presto.raptor.metadata.ViewResult; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorColumnHandle; import com.facebook.presto.spi.ConnectorInsertTableHandle; import com.facebook.presto.spi.ConnectorMetadata; import com.facebook.presto.spi.ConnectorOutputTableHandle; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.ConnectorTableHandle; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.SchemaTablePrefix; import com.facebook.presto.spi.ViewNotFoundException; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multimaps; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.VoidTransactionCallback; import org.skife.jdbi.v2.exceptions.UnableToExecuteStatementException; import javax.annotation.Nullable; import javax.inject.Inject; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import static com.facebook.presto.raptor.RaptorColumnHandle.SAMPLE_WEIGHT_COLUMN_NAME; import static com.facebook.presto.raptor.metadata.MetadataDaoUtils.createMetadataTablesWithRetry; import static com.facebook.presto.raptor.metadata.SqlUtils.runIgnoringConstraintViolation; import static com.facebook.presto.raptor.util.Types.checkType; import static com.facebook.presto.spi.StandardErrorCode.ALREADY_EXISTS; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.not; public class RaptorMetadata implements ConnectorMetadata { private final IDBI dbi; private final MetadataDao dao; private final ShardManager shardManager; private final String connectorId; @Inject public RaptorMetadata(RaptorConnectorId connectorId, @ForMetadata IDBI dbi, ShardManager shardManager) { checkNotNull(connectorId, "connectorId is null"); this.connectorId = connectorId.toString(); this.dbi = checkNotNull(dbi, "dbi is null"); this.dao = dbi.onDemand(MetadataDao.class); this.shardManager = checkNotNull(shardManager, "shardManager is null"); createMetadataTablesWithRetry(dao); } @Override public List<String> listSchemaNames(ConnectorSession session) { return dao.listSchemaNames(connectorId); } @Override public ConnectorTableHandle getTableHandle(ConnectorSession session, SchemaTableName tableName) { return getTableHandle(tableName); } private ConnectorTableHandle getTableHandle(SchemaTableName tableName) { checkNotNull(tableName, "tableName is null"); Table table = dao.getTableInformation(connectorId, tableName.getSchemaName(), tableName.getTableName()); if (table == null) { return null; } List<TableColumn> tableColumns = dao.getTableColumns(table.getTableId()); checkArgument(!tableColumns.isEmpty(), "Table %s does not have any columns", tableName); RaptorColumnHandle countColumnHandle = null; RaptorColumnHandle sampleWeightColumnHandle = null; for (TableColumn tableColumn : tableColumns) { if (SAMPLE_WEIGHT_COLUMN_NAME.equals(tableColumn.getColumnName())) { sampleWeightColumnHandle = getRaptorColumnHandle(tableColumn); } if (countColumnHandle == null && tableColumn.getDataType().getJavaType().isPrimitive()) { countColumnHandle = getRaptorColumnHandle(tableColumn); } } if (sampleWeightColumnHandle != null) { sampleWeightColumnHandle = new RaptorColumnHandle(connectorId, SAMPLE_WEIGHT_COLUMN_NAME, sampleWeightColumnHandle.getColumnId(), BIGINT); } return new RaptorTableHandle( connectorId, tableName.getSchemaName(), tableName.getTableName(), table.getTableId(), sampleWeightColumnHandle); } @Override public ConnectorTableMetadata getTableMetadata(ConnectorTableHandle tableHandle) { RaptorTableHandle raptorTableHandle = checkType(tableHandle, RaptorTableHandle.class, "tableHandle"); SchemaTableName tableName = new SchemaTableName(raptorTableHandle.getSchemaName(), raptorTableHandle.getTableName()); List<ColumnMetadata> columns = FluentIterable .from(dao.getTableColumns(raptorTableHandle.getTableId())) .transform(TableColumn.columnMetadataGetter()) .filter(not(isSampleWeightColumn())) .toList(); checkArgument(!columns.isEmpty(), "Table %s does not have any columns", tableName); return new ConnectorTableMetadata(tableName, columns); } @Override public List<SchemaTableName> listTables(ConnectorSession session, @Nullable String schemaNameOrNull) { return dao.listTables(connectorId, schemaNameOrNull); } @Override public Map<String, ConnectorColumnHandle> getColumnHandles(ConnectorTableHandle tableHandle) { RaptorTableHandle raptorTableHandle = checkType(tableHandle, RaptorTableHandle.class, "tableHandle"); ImmutableMap.Builder<String, ConnectorColumnHandle> builder = ImmutableMap.builder(); for (TableColumn tableColumn : dao.listTableColumns(raptorTableHandle.getTableId())) { if (tableColumn.getColumnName().equals(SAMPLE_WEIGHT_COLUMN_NAME)) { continue; } builder.put(tableColumn.getColumnName(), getRaptorColumnHandle(tableColumn)); } return builder.build(); } @Override public ConnectorColumnHandle getSampleWeightColumnHandle(ConnectorTableHandle tableHandle) { return checkType(tableHandle, RaptorTableHandle.class, "tableHandle").getSampleWeightColumnHandle(); } @Override public boolean canCreateSampledTables(ConnectorSession session) { return true; } @Override public ColumnMetadata getColumnMetadata(ConnectorTableHandle tableHandle, ConnectorColumnHandle columnHandle) { long tableId = checkType(tableHandle, RaptorTableHandle.class, "tableHandle").getTableId(); long columnId = checkType(columnHandle, RaptorColumnHandle.class, "columnHandle").getColumnId(); TableColumn tableColumn = dao.getTableColumn(tableId, columnId); checkState(tableColumn != null, "no column with id %s exists", columnId); return tableColumn.toColumnMetadata(); } @Override public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix) { checkNotNull(prefix, "prefix is null"); ImmutableListMultimap.Builder<SchemaTableName, ColumnMetadata> columns = ImmutableListMultimap.builder(); for (TableColumn tableColumn : dao.listTableColumns(connectorId, prefix.getSchemaName(), prefix.getTableName())) { if (tableColumn.getColumnName().equals(SAMPLE_WEIGHT_COLUMN_NAME)) { continue; } ColumnMetadata columnMetadata = new ColumnMetadata(tableColumn.getColumnName(), tableColumn.getDataType(), tableColumn.getOrdinalPosition(), false); columns.put(tableColumn.getTable(), columnMetadata); } return Multimaps.asMap(columns.build()); } @Override public ConnectorTableHandle createTable(ConnectorSession session, final ConnectorTableMetadata tableMetadata) { Long tableId = dbi.inTransaction(new TransactionCallback<Long>() { @Override public Long inTransaction(final Handle handle, TransactionStatus status) throws Exception { // Ignore exception if table already exists return runIgnoringConstraintViolation(new Callable<Long>() { @Override public Long call() throws Exception { MetadataDao dao = handle.attach(MetadataDao.class); long tableId = dao.insertTable(connectorId, tableMetadata.getTable().getSchemaName(), tableMetadata.getTable().getTableName()); int ordinalPosition = 0; for (ColumnMetadata column : tableMetadata.getColumns()) { long columnId = ordinalPosition + 1; dao.insertColumn(tableId, columnId, column.getName(), ordinalPosition, column.getType().getTypeSignature().toString()); ordinalPosition++; } if (tableMetadata.isSampled()) { dao.insertColumn(tableId, ordinalPosition + 1, SAMPLE_WEIGHT_COLUMN_NAME, ordinalPosition, StandardTypes.BIGINT); } return tableId; } }, null); } }); checkState(tableId != null, "table %s already exists", tableMetadata.getTable()); RaptorColumnHandle sampleWeightColumnHandle = null; if (tableMetadata.isSampled()) { sampleWeightColumnHandle = new RaptorColumnHandle(connectorId, SAMPLE_WEIGHT_COLUMN_NAME, tableMetadata.getColumns().size() + 1, BIGINT); } return new RaptorTableHandle( connectorId, tableMetadata.getTable().getSchemaName(), tableMetadata.getTable().getTableName(), tableId, sampleWeightColumnHandle); } @Override public void dropTable(ConnectorTableHandle tableHandle) { final RaptorTableHandle raptorHandle = checkType(tableHandle, RaptorTableHandle.class, "tableHandle"); dbi.inTransaction(new VoidTransactionCallback() { @Override protected void execute(Handle handle, TransactionStatus status) throws Exception { shardManager.dropTableShards(raptorHandle.getTableId()); MetadataDaoUtils.dropTable(dao, raptorHandle.getTableId()); } }); } @Override public void renameTable(ConnectorTableHandle tableHandle, final SchemaTableName newTableName) { final RaptorTableHandle table = checkType(tableHandle, RaptorTableHandle.class, "tableHandle"); dbi.inTransaction(new VoidTransactionCallback() { @Override protected void execute(Handle handle, TransactionStatus status) throws Exception { MetadataDao dao = handle.attach(MetadataDao.class); dao.renameTable(table.getTableId(), newTableName.getSchemaName(), newTableName.getTableName()); } }); } @Override public ConnectorOutputTableHandle beginCreateTable(ConnectorSession session, ConnectorTableMetadata tableMetadata) { ImmutableList.Builder<RaptorColumnHandle> columnHandles = ImmutableList.builder(); ImmutableList.Builder<Type> columnTypes = ImmutableList.builder(); long maxColumnId = 0; for (ColumnMetadata column : tableMetadata.getColumns()) { long columnId = column.getOrdinalPosition() + 1; maxColumnId = Math.max(maxColumnId, columnId); columnHandles.add(new RaptorColumnHandle(connectorId, column.getName(), columnId, column.getType())); columnTypes.add(column.getType()); } RaptorColumnHandle sampleWeightColumnHandle = null; if (tableMetadata.isSampled()) { sampleWeightColumnHandle = new RaptorColumnHandle(connectorId, SAMPLE_WEIGHT_COLUMN_NAME, maxColumnId + 1, BIGINT); columnHandles.add(sampleWeightColumnHandle); columnTypes.add(BIGINT); } return new RaptorOutputTableHandle( tableMetadata.getTable().getSchemaName(), tableMetadata.getTable().getTableName(), columnHandles.build(), columnTypes.build(), sampleWeightColumnHandle); } @Override public void commitCreateTable(ConnectorOutputTableHandle outputTableHandle, Collection<String> fragments) { final RaptorOutputTableHandle table = checkType(outputTableHandle, RaptorOutputTableHandle.class, "outputTableHandle"); long tableId = dbi.inTransaction(new TransactionCallback<Long>() { @Override public Long inTransaction(Handle dbiHandle, TransactionStatus status) { MetadataDao dao = dbiHandle.attach(MetadataDao.class); long tableId = dao.insertTable(connectorId, table.getSchemaName(), table.getTableName()); for (int i = 0; i < table.getColumnTypes().size(); i++) { RaptorColumnHandle column = table.getColumnHandles().get(i); Type columnType = table.getColumnTypes().get(i); dao.insertColumn(tableId, i + 1, column.getColumnName(), i, columnType.getTypeSignature().toString()); } return tableId; } }); shardManager.commitTable(tableId, parseFragments(fragments), Optional.<String>absent()); } @Override public ConnectorInsertTableHandle beginInsert(ConnectorSession session, ConnectorTableHandle tableHandle) { long tableId = checkType(tableHandle, RaptorTableHandle.class, "tableHandle").getTableId(); ImmutableList.Builder<RaptorColumnHandle> columnHandles = ImmutableList.builder(); ImmutableList.Builder<Type> columnTypes = ImmutableList.builder(); for (TableColumn column : dao.getTableColumns(tableId)) { columnHandles.add(new RaptorColumnHandle(connectorId, column.getColumnName(), column.getColumnId(), column.getDataType())); columnTypes.add(column.getDataType()); } String externalBatchId = session.getProperties().get("external_batch_id"); return new RaptorInsertTableHandle(connectorId, tableId, columnHandles.build(), columnTypes.build(), externalBatchId); } @Override public void commitInsert(ConnectorInsertTableHandle insertHandle, Collection<String> fragments) { RaptorInsertTableHandle handle = checkType(insertHandle, RaptorInsertTableHandle.class, "insertHandle"); long tableId = handle.getTableId(); Optional<String> externalBatchId = Optional.fromNullable(handle.getExternalBatchId()); shardManager.commitTable(tableId, parseFragments(fragments), externalBatchId); } @Override public void createView(ConnectorSession session, SchemaTableName viewName, final String viewData, boolean replace) { final String schemaName = viewName.getSchemaName(); final String tableName = viewName.getTableName(); if (replace) { dbi.inTransaction(new VoidTransactionCallback() { @Override protected void execute(Handle handle, TransactionStatus status) throws Exception { MetadataDao dao = handle.attach(MetadataDao.class); dao.dropView(connectorId, schemaName, tableName); dao.insertView(connectorId, schemaName, tableName, viewData); } }); return; } try { dao.insertView(connectorId, schemaName, tableName, viewData); } catch (UnableToExecuteStatementException e) { if (viewExists(session, viewName)) { throw new PrestoException(ALREADY_EXISTS, "View already exists: " + viewName); } throw e; } } @Override public void dropView(ConnectorSession session, SchemaTableName viewName) { if (!viewExists(session, viewName)) { throw new ViewNotFoundException(viewName); } dao.dropView(connectorId, viewName.getSchemaName(), viewName.getTableName()); } @Override public List<SchemaTableName> listViews(ConnectorSession session, String schemaNameOrNull) { return dao.listViews(connectorId, schemaNameOrNull); } @Override public Map<SchemaTableName, String> getViews(ConnectorSession session, SchemaTablePrefix prefix) { ImmutableMap.Builder<SchemaTableName, String> map = ImmutableMap.builder(); for (ViewResult view : dao.getViews(connectorId, prefix.getSchemaName(), prefix.getTableName())) { map.put(view.getName(), view.getData()); } return map.build(); } private boolean viewExists(ConnectorSession session, SchemaTableName viewName) { return !getViews(session, viewName.toSchemaTablePrefix()).isEmpty(); } private RaptorColumnHandle getRaptorColumnHandle(TableColumn tableColumn) { return new RaptorColumnHandle(connectorId, tableColumn.getColumnName(), tableColumn.getColumnId(), tableColumn.getDataType()); } private static List<ShardNode> parseFragments(Collection<String> fragments) { ImmutableList.Builder<ShardNode> shards = ImmutableList.builder(); for (String fragment : fragments) { Iterator<String> split = Splitter.on(':').split(fragment).iterator(); String nodeId = split.next(); UUID shardUuid = UUID.fromString(split.next()); shards.add(new ShardNode(shardUuid, nodeId)); } return shards.build(); } private static Predicate<ColumnMetadata> isSampleWeightColumn() { return new Predicate<ColumnMetadata>() { @Override public boolean apply(ColumnMetadata input) { return input.getName().equals(SAMPLE_WEIGHT_COLUMN_NAME); } }; } }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.offlinepages; /** Set of system conditions to trigger background processing. */ public class TriggerConditions { private final boolean mRequirePowerConnected; private final int mMinimumBatteryPercentage; private final boolean mRequireUnmeteredNetwork; /** * Creates set of device, network, and power conditions for triggering processing. * @param requirePowerConnected whether to require that device is connected to power * @param minimumBatteryPercentage minimum percentage (0-100) of remaining battery power * @param requireUnmeteredNetwork whether to require connection to unmetered network */ public TriggerConditions(boolean requirePowerConnected, int minimumBatteryPercentage, boolean requireUnmeteredNetwork) { mRequirePowerConnected = requirePowerConnected; mMinimumBatteryPercentage = minimumBatteryPercentage; mRequireUnmeteredNetwork = requireUnmeteredNetwork; } /** Returns whether connection to power is required. */ public boolean requirePowerConnected() { return mRequirePowerConnected; } /** Returns the minimum battery percentage that is required. */ public int getMinimumBatteryPercentage() { return mMinimumBatteryPercentage; } /** Returns whether connection to an unmetered network is required. */ public boolean requireUnmeteredNetwork() { return mRequireUnmeteredNetwork; } @Override public int hashCode() { int hash = 13; hash = hash * 31 + (mRequirePowerConnected ? 1 : 0); hash = hash * 31 + mMinimumBatteryPercentage; hash = hash * 31 + (mRequireUnmeteredNetwork ? 1 : 0); return hash; } @Override public boolean equals(Object other) { if (!(other instanceof TriggerConditions)) return false; TriggerConditions otherTriggerConditions = (TriggerConditions) other; return mRequirePowerConnected == otherTriggerConditions.mRequirePowerConnected && mMinimumBatteryPercentage == otherTriggerConditions.mMinimumBatteryPercentage && mRequireUnmeteredNetwork == otherTriggerConditions.mRequireUnmeteredNetwork; } }
public class OutOfTimeException extends Exception { }
package org.jooby.spec; import static org.junit.Assert.assertEquals; import java.io.File; import java.nio.file.Path; import java.util.List; import org.jooby.Jooby; import org.junit.Test; import apps.PetApp; public class ImportAppTest { private Path basedir = new File(System.getProperty("user.dir")).toPath(); @Test public void importApp() throws Exception { RouteProcessor processor = new RouteProcessor(); Jooby app = new PetApp(); List<RouteSpec> specs = processor.process(app, basedir); assertEquals(2, specs.size()); RouteSpec route = specs.get(0); assertEquals("GET", route.method()); assertEquals("/api/blogs/:id", route.pattern()); assertEquals("Get by ID.", route.doc().get()); assertEquals(1, route.params().size()); assertEquals("id", route.params().get(0).name()); assertEquals(RouteParamType.PATH, route.params().get(0).paramType()); assertEquals("int", route.params().get(0).type().getTypeName()); assertEquals(null, route.params().get(0).value()); route = specs.get(1); assertEquals("GET", route.method()); assertEquals("/api/pets/:id", route.pattern()); assertEquals("apps.model.Pet", route.response().type().getTypeName()); assertEquals("Get a pet by ID.", route.doc().get()); assertEquals(1, route.params().size()); assertEquals("id", route.params().get(0).name()); assertEquals(RouteParamType.PATH, route.params().get(0).paramType()); assertEquals("int", route.params().get(0).type().getTypeName()); assertEquals(null, route.params().get(0).value()); } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.markdown.braces; import com.intellij.codeInsight.highlighting.PairedBraceMatcherAdapter; import com.intellij.lang.BracePair; import com.intellij.lang.PairedBraceMatcher; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import org.intellij.plugins.markdown.lang.MarkdownLanguage; import org.intellij.plugins.markdown.lang.MarkdownTokenTypes; import org.jetbrains.annotations.NotNull; public class MarkdownBraceMatcher extends PairedBraceMatcherAdapter { public MarkdownBraceMatcher() { super(new MyPairedBraceMatcher(), MarkdownLanguage.INSTANCE); } private static class MyPairedBraceMatcher implements PairedBraceMatcher { @NotNull @Override public BracePair[] getPairs() { return new BracePair[]{ new BracePair(MarkdownTokenTypes.LPAREN, MarkdownTokenTypes.RPAREN, false), new BracePair(MarkdownTokenTypes.LBRACKET, MarkdownTokenTypes.RBRACKET, false), new BracePair(MarkdownTokenTypes.LT, MarkdownTokenTypes.GT, false), new BracePair(MarkdownTokenTypes.CODE_FENCE_START, MarkdownTokenTypes.CODE_FENCE_END, true) }; } @Override public boolean isPairedBracesAllowedBeforeType(@NotNull IElementType lbraceType, IElementType type) { return type == null || type == MarkdownTokenTypes.WHITE_SPACE || type == MarkdownTokenTypes.EOL || type == MarkdownTokenTypes.RPAREN || type == MarkdownTokenTypes.RBRACKET || type == MarkdownTokenTypes.GT; } @Override public int getCodeConstructStart(PsiFile file, int openingBraceOffset) { return openingBraceOffset; } } }
package cn.ykf.thread; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.Scanner; /** * @author YuKaiFan <1092882580@qq.com> * @date 2020-10-13 */ public class EchoHandler implements Runnable { private Socket socket; public EchoHandler(Socket socket) { this.socket = socket; } @Override public void run() { try (final Scanner in = new Scanner(socket.getInputStream(), "UTF-8"); final PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8), true)) { // 向客户端进行响应 out.println("Hello! Enter Q to quit"); // 接收客户端数据 while (in.hasNextLine()) { final String line = in.nextLine(); if ("Q".equals(line.trim())) { break; } out.println("Echo: " + line); } } catch (IOException e) { e.printStackTrace(); } } }
package com.example.activitytest.state; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.SparseArray; import com.example.activitytest.R; import com.example.activitytest.activity.BasicActivityA; import butterknife.ButterKnife; import butterknife.OnClick; import icepick.Icepick; import icepick.State; public class StateRestoreDemoActivity extends AppCompatActivity { public static final String TAG = StateRestoreDemoActivity.class.getSimpleName(); @State SparseArray<Fragment.SavedState> savedStateSparseArray = new SparseArray<>(); // 如果我们保存了Fragment的引用, 并且只new一次, tab2的状态是会自动保存并恢复的 // tab1中的状态没有恢复是因为View没有id private Fragment tab1Fragment; private Fragment tab2Fragment; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate() " + savedInstanceState); super.onCreate(savedInstanceState); setContentView(R.layout.activity_state_restore_demo); ButterKnife.bind(this); Icepick.restoreInstanceState(this, savedInstanceState); // initFragments(); } @Override protected void onRestart() { Log.i(TAG, "onRestart()"); super.onRestart(); } @Override protected void onStart() { Log.i(TAG, "onStart()"); super.onStart(); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { Log.e(TAG, "onRestoreInstanceState(): " + savedInstanceState); super.onRestoreInstanceState(savedInstanceState); } @Override protected void onResume() { Log.i(TAG, "onResume()"); super.onResume(); } @Override protected void onPause() { Log.i(TAG, "onPause()"); super.onPause(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.e(TAG, "onSaveInstanceState(): " + outState); Icepick.saveInstanceState(this, outState); } @Override protected void onStop() { Log.i(TAG, "onStop()"); super.onStop(); } @OnClick(R.id.button_open_another_activity) void onOpenAnotherActivity() { startActivity(new Intent(this, BasicActivityA.class)); } @OnClick(R.id.tab1) void onTab1Clicked() { // save current tab Fragment tab2Fragment = getSupportFragmentManager().findFragmentByTag(Tab2Fragment.TAG); if (tab2Fragment != null) { saveFragmentState(1, tab2Fragment); } // restore last state Tab1Fragment tab1Fragment = new Tab1Fragment(); restoreFragmentState(0, tab1Fragment); // show new tab getSupportFragmentManager().beginTransaction() .replace(R.id.content_container, tab1Fragment, Tab1Fragment.TAG) .commit(); } @OnClick(R.id.tab2) void onTab2Clicked() { Fragment tab1Fragment = getSupportFragmentManager().findFragmentByTag(Tab1Fragment.TAG); if (tab1Fragment != null) { saveFragmentState(0, tab1Fragment); } Tab2Fragment tab2Fragment = new Tab2Fragment(); restoreFragmentState(1, tab2Fragment); getSupportFragmentManager().beginTransaction() .replace(R.id.content_container, tab2Fragment, Tab2Fragment.TAG) .commit(); // 如果我们每次都传入新的实例, 则上一个实例的状态是无法传到新的实例的 // 所以我们需要手动保存和恢复 } @OnClick(R.id.button_add_detail_fragment) void addDetail() { getSupportFragmentManager().beginTransaction() .replace(R.id.content_container, new DetailFragment(), Tab2Fragment.TAG) .addToBackStack(DetailFragment.TAG) .commit(); } private void saveFragmentState(int index, Fragment fragment) { Fragment.SavedState savedState = getSupportFragmentManager().saveFragmentInstanceState(fragment); savedStateSparseArray.put(index, savedState); } private void restoreFragmentState(int index, Fragment fragment) { Fragment.SavedState savedState = savedStateSparseArray.get(index); fragment.setInitialSavedState(savedState); } private void initFragments() { tab1Fragment = getSupportFragmentManager().findFragmentByTag(Tab1Fragment.TAG); if (tab1Fragment == null) { tab1Fragment = new Tab1Fragment(); } tab2Fragment = getSupportFragmentManager().findFragmentByTag(Tab2Fragment.TAG); if (tab2Fragment == null) { tab2Fragment = new Tab2Fragment(); } } }
package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; import static org.hamcrest.core.StringContains.containsString; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import org.tron.api.GrpcAPI.TransactionExtention; import org.tron.api.WalletGrpc; import org.tron.api.WalletSolidityGrpc; import org.tron.common.crypto.ECKey; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Utils; import org.tron.core.Wallet; import stest.tron.wallet.common.client.Configuration; import stest.tron.wallet.common.client.Parameter.CommonConstant; import stest.tron.wallet.common.client.utils.PublicMethed; @Slf4j public class ClearAbi006 { private final String testNetAccountKey = Configuration.getByPath("testng.conf") .getString("foundationAccount.key2"); private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); private Long maxFeeLimit = Configuration.getByPath("testng.conf") .getLong("defaultParameter.maxFeeLimit"); private ManagedChannel channelSolidity = null; private ManagedChannel channelFull = null; private WalletGrpc.WalletBlockingStub blockingStubFull = null; private ManagedChannel channelFull1 = null; private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; private String fullnode = Configuration.getByPath("testng.conf") .getStringList("fullnode.ip.list").get(0); private String fullnode1 = Configuration.getByPath("testng.conf") .getStringList("fullnode.ip.list").get(1); private String soliditynode = Configuration.getByPath("testng.conf") .getStringList("solidityNode.ip.list").get(0); byte[] contractAddress = null; ECKey ecKey1 = new ECKey(Utils.getRandom()); byte[] contractExcAddress = ecKey1.getAddress(); String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); ECKey ecKey2 = new ECKey(Utils.getRandom()); byte[] contractExcAddress1 = ecKey2.getAddress(); String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); @BeforeSuite public void beforeSuite() { Wallet wallet = new Wallet(); Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); } /** * constructor. */ @BeforeClass(enabled = true) public void beforeClass() { PublicMethed.printAddress(contractExcKey); channelFull = ManagedChannelBuilder.forTarget(fullnode) .usePlaintext(true) .build(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) .usePlaintext(true) .build(); blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) .usePlaintext(true) .build(); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); } @Test(enabled = false, description = "Clear a uninitialized account") public void testClearAbi() { Assert.assertTrue(PublicMethed .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, blockingStubFull)); PublicMethed.waitProduceNextBlock(blockingStubFull); TransactionExtention transactionExtention = PublicMethed .clearContractAbiForExtention(contractExcAddress1, contractExcAddress, contractExcKey, blockingStubFull); Assert.assertThat(transactionExtention.getResult().getCode().toString(), containsString("CONTRACT_VALIDATE_ERROR")); Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), containsString("contract validate error : Contract not exists")); } /** * constructor. */ @AfterClass public void shutdown() throws InterruptedException { if (channelFull != null) { channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); } if (channelFull1 != null) { channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); } if (channelSolidity != null) { channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); } } }
package com.rjv.graphql.example.resource; import com.rjv.graphql.example.service.CustomerGraphQLService; import graphql.ExecutionResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/rest/customer-service") public class CustomerResource { @Autowired private CustomerGraphQLService customerGraphQLService; @PostMapping public ResponseEntity<ExecutionResult> getCustomer(@RequestBody String query){ ExecutionResult execute = customerGraphQLService.getGraphQL().execute(query); return new ResponseEntity<>(execute, HttpStatus.OK); } }
package org.ormfux.common.utils.testcollectionutils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.ArrayList; import java.util.Arrays; import org.junit.Test; import org.ormfux.common.utils.CollectionUtils; public class SelectFirstTest { @Test public void testNonEmptyHit() { assertEquals("1hit", CollectionUtils.selectFirst(Arrays.asList("1nohit", "2hit", "1hit", "3"), value -> value.startsWith("1hit"))); } @Test public void testNonEmptyNoHit() { assertNull(CollectionUtils.selectFirst(Arrays.asList("1nohit", "2hit", "1hit", "3"), value -> value.startsWith("4hit"))); } @Test public void testEmpty() { assertNull(CollectionUtils.selectFirst(new ArrayList<String>(), value -> value.startsWith("4hit"))); } @Test(expected = NullPointerException.class) public void testNullSource() { CollectionUtils.selectFirst(null, value -> true); } @Test(expected = NullPointerException.class) public void testNullCondition() { CollectionUtils.selectFirst(new ArrayList<>(), null); } }
package perf; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.lucene.analysis.CharArraySet; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.codecs.Codec; import org.apache.lucene.codecs.DocValuesFormat; import org.apache.lucene.codecs.PostingsFormat; import org.apache.lucene.index.ConcurrentMergeScheduler; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.NoDeletionPolicy; import org.apache.lucene.index.Term; import org.apache.lucene.index.TieredMergePolicy; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.SearcherManager; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TotalHits; import org.apache.lucene.search.spell.DirectSpellChecker; import org.apache.lucene.store.Directory; import org.apache.lucene.store.MMapDirectory; import org.apache.lucene.store.NIOFSDirectory; import org.apache.lucene.store.NRTCachingDirectory; import perf.IndexThreads.Mode; // cd /a/lucene/trunk/checkout // ln -s /path/to/lucene/util/perf . // ant compile; javac -cp ../modules/analysis/build/common/classes/java:build/classes/java:build/classes/test perf/NRTPerfTest.java perf/LineFileDocs.java // java -Xmx2g -Xms2g -server -Xbatch -cp .:lib/junit-4.7.jar:../modules/analysis/build/common/classes/java:build/classes/java:build/classes/test perf.NRTPerfTest MMapDirectory /p/lucene/indices/wikimedium.clean.svn.Standard.nd10M/index multi /lucene/data/enwiki-20110115-lines-1k-fixed.txt 17 1000 1000 2 1 1 update 1 no // TODO // - maybe target certain MB/sec update rate...? // - hmm: we really should have a separate line file, shuffled, that holds the IDs for each line; this way we can update doc w/ same original doc and then we can assert hit counts match // - share *Task code from SearchPerfTest public class NRTPerfTest { static final class MergedReaderWarmer implements IndexWriter.IndexReaderWarmer { private final String field; MergedReaderWarmer(String field) { this.field = field; } @Override public void warm(LeafReader reader) throws IOException { final long t0 = System.currentTimeMillis(); //System.out.println("DO WARM: " + reader); IndexSearcher s = new IndexSearcher(reader); s.setQueryCache(null); // don't bench the cache s.search(new TermQuery(new Term(field, "10")), 10); // Warm terms dict & index: /* final TermsEnum te = reader.fields().terms("body").iterator(); long sumDocs = 0; DocsEnum docs = null; int counter = 0; final List<BytesRef> terms = new ArrayList<BytesRef>(); while(te.next() != null) { docs = te.docs(null, docs); if (counter++ % 50 == 0) { terms.add(new BytesRef(te.term())); } int docID; while((docID = docs.nextDoc()) != DocsEnum.NO_MORE_DOCS) { sumDocs += docID; } } Collections.reverse(terms); System.out.println("warm: " + terms.size() + " terms"); for(BytesRef term : terms) { sumDocs += reader.docFreq("body", term); } */ final long t1 = System.currentTimeMillis(); System.out.println("warm took " + (t1-t0) + " msec"); //NativePosixUtil.mlockTermsDict(reader, "id"); } } static final class ReopenThread extends Thread { private final double reopenPerSec; private final SearcherManager manager; private final AtomicInteger[] reopensByTime; private final double runTimeSec; ReopenThread(double reopenPerSec, SearcherManager manager, AtomicInteger[] reopensByTime, double runTimeSec) { this.reopenPerSec = reopenPerSec; this.manager = manager; this.reopensByTime = reopensByTime; this.runTimeSec = runTimeSec; } @Override public void run() { try { final long startMS = System.currentTimeMillis(); final long stopMS = startMS + (long) (runTimeSec * 1000); int reopenCount = 1; while (true) { final long t = System.currentTimeMillis(); if (t >= stopMS) { break; } final long sleepMS = startMS + (long) (1000*(reopenCount/reopenPerSec)) - System.currentTimeMillis(); if (sleepMS < 0) { System.out.println("WARNING: reopen fell behind by " + Math.abs(sleepMS) + " ms"); } else { Thread.sleep(sleepMS); } IndexSearcher curS = manager.acquire(); try { final long tStart = System.nanoTime(); manager.maybeRefresh(); ++reopenCount; IndexSearcher newS = manager.acquire(); try { if (curS != newS) { System.out.println("Reopen: " + String.format("%9.4f", (System.nanoTime() - tStart)/1000000.0) + " msec"); reopensByTime[currentQT.get()].incrementAndGet(); } else { System.out.println("WARNING: no changes on reopen"); } } finally { manager.release(newS); } } finally { manager.release(curS); } } } catch (Exception e) { throw new RuntimeException(e); } } } static class RandomTaskSource implements TaskSource { private final List<Task> tasks; private final AtomicInteger nextTask = new AtomicInteger(); private final int numTasks; public RandomTaskSource(TaskParser taskParser, String tasksFile, Random random) throws IOException, ParseException { tasks = LocalTaskSource.loadTasks(taskParser, tasksFile); numTasks = tasks.size(); Collections.shuffle(tasks, random); System.out.println("TASK LEN=" + tasks.size()); } @Override public List<Task> getAllTasks() { return tasks; } @Override public Task nextTask() { final int next = nextTask.getAndIncrement() % numTasks; return tasks.get(next); } @Override public void taskDone(Task task, long queueTimeNS, TotalHits toalHitCount) {} } static final AtomicInteger currentQT = new AtomicInteger(); static AtomicInteger[] docsIndexedByTime; static AtomicInteger[] searchesByTime; static AtomicLong[] totalUpdateTimeByTime; static int statsEverySec; public static void main(String[] args) throws Exception { final String dirImpl = args[0]; final String dirPath = args[1]; final String commit = args[2]; final String lineDocFile = args[3]; final long seed = Long.parseLong(args[4]); final double docsPerSec = Double.parseDouble(args[5]); final double runTimeSec = Double.parseDouble(args[6]); final int numSearchThreads = Integer.parseInt(args[7]); int numIndexThreads = Integer.parseInt(args[8]); if (numIndexThreads > docsPerSec) { System.out.println("INFO: numIndexThreads higher than docsPerSec, adjusting numIndexThreads"); numIndexThreads = (int) Math.max(1, docsPerSec); } final double reopenPerSec = Double.parseDouble(args[9]); final Mode mode = Mode.valueOf(args[10].toUpperCase(Locale.ROOT)); statsEverySec = Integer.parseInt(args[11]); final boolean doCommit = args[12].equals("yes"); final double mergeMaxWriteMBPerSec = Double.parseDouble(args[13]); if (mergeMaxWriteMBPerSec != 0.0) { throw new IllegalArgumentException("mergeMaxWriteMBPerSec must be 0.0 until LUCENE-3202 is done"); } final String tasksFile = args[14]; if (Files.notExists(Paths.get(tasksFile))) { throw new FileNotFoundException("tasks file not found " + tasksFile); } final boolean hasProcMemInfo = Files.exists(Paths.get("/proc/meminfo")); System.out.println("DIR=" + dirImpl); System.out.println("Index=" + dirPath); System.out.println("Commit=" + commit); System.out.println("LineDocs=" + lineDocFile); System.out.println("Docs/sec=" + docsPerSec); System.out.println("Run time sec=" + runTimeSec); System.out.println("NumSearchThreads=" + numSearchThreads); System.out.println("NumIndexThreads=" + numIndexThreads); System.out.println("Reopen/sec=" + reopenPerSec); System.out.println("Mode=" + mode); System.out.println("tasksFile=" + tasksFile); System.out.println("Record stats every " + statsEverySec + " seconds"); final int count = (int) ((runTimeSec / statsEverySec) + 2); docsIndexedByTime = new AtomicInteger[count]; searchesByTime = new AtomicInteger[count]; totalUpdateTimeByTime = new AtomicLong[count]; final AtomicInteger reopensByTime[] = new AtomicInteger[count]; for (int i = 0; i < count; i++) { docsIndexedByTime[i] = new AtomicInteger(); searchesByTime[i] = new AtomicInteger(); totalUpdateTimeByTime[i] = new AtomicLong(); reopensByTime[i] = new AtomicInteger(); } System.out.println("Max merge MB/sec = " + (mergeMaxWriteMBPerSec <= 0.0 ? "unlimited" : mergeMaxWriteMBPerSec)); final Random random = new Random(seed); final LineFileDocs docs = new LineFileDocs(lineDocFile, true, false, false, false, false, null, Collections.emptyMap(), null, true, null, 0); final Directory dir0; if (dirImpl.equals("MMapDirectory")) { dir0 = new MMapDirectory(Paths.get(dirPath)); } else if (dirImpl.equals("NIOFSDirectory")) { dir0 = new NIOFSDirectory(Paths.get(dirPath)); } else { docs.close(); throw new RuntimeException("unknown directory impl \"" + dirImpl + "\""); } //final NRTCachingDirectory dir = new NRTCachingDirectory(dir0, 10, 200.0, mergeMaxWriteMBPerSec); final NRTCachingDirectory dir = new NRTCachingDirectory(dir0, 20, 400.0); //final MergeScheduler ms = dir.getMergeScheduler(); //final Directory dir = dir0; //final MergeScheduler ms = new ConcurrentMergeScheduler(); final String field = "body"; // Open an IW on the requested commit point, but, don't // delete other (past or future) commit points: // TODO take Analyzer as parameter StandardAnalyzer analyzer = new StandardAnalyzer(CharArraySet.EMPTY_SET); final IndexWriterConfig conf = new IndexWriterConfig(analyzer); conf.setIndexDeletionPolicy(NoDeletionPolicy.INSTANCE); conf.setRAMBufferSizeMB(256.0); //iwc.setMergeScheduler(ms); /* final Codec codec = new Lucene86Codec() { @Override public PostingsFormat getPostingsFormatForField(String field) { return PostingsFormat.forName("Lucene50"); } private final DocValuesFormat direct = DocValuesFormat.forName("Direct"); @Override public DocValuesFormat getDocValuesFormatForField(String field) { return direct; } }; conf.setCodec(codec); */ /* iwc.setMergePolicy(new LogByteSizeMergePolicy()); ((LogMergePolicy) iwc.getMergePolicy()).setUseCompoundFile(false); ((LogMergePolicy) iwc.getMergePolicy()).setMergeFactor(30); ((LogByteSizeMergePolicy) iwc.getMergePolicy()).setMaxMergeMB(10000.0); System.out.println("USING LOG BS MP"); */ TieredMergePolicy tmp = new TieredMergePolicy(); tmp.setNoCFSRatio(0.0); tmp.setMaxMergedSegmentMB(1000000.0); //tmp.setReclaimDeletesWeight(3.0); //tmp.setMaxMergedSegmentMB(7000.0); conf.setMergePolicy(tmp); if (!commit.equals("none")) { conf.setIndexCommit(PerfUtils.findCommitPoint(commit, dir)); } // Make sure merges run @ higher prio than indexing: final ConcurrentMergeScheduler cms = (ConcurrentMergeScheduler) conf.getMergeScheduler(); cms.setMaxMergesAndThreads(4, 1); conf.setMergedSegmentWarmer(new MergedReaderWarmer(field)); final IndexWriter w = new IndexWriter(dir, conf); // w.setInfoStream(System.out); IndexThreads.UpdatesListener updatesListener = new IndexThreads.UpdatesListener() { long startTimeNS; @Override public void beforeUpdate() { startTimeNS = System.nanoTime(); } @Override public void afterUpdate() { int idx = currentQT.get(); totalUpdateTimeByTime[idx].addAndGet(System.nanoTime() - startTimeNS); docsIndexedByTime[idx].incrementAndGet(); } }; IndexWriter.DocStats stats = w.getDocStats(); IndexThreads indexThreads = new IndexThreads(random, w, new AtomicBoolean(false), docs, numIndexThreads, -1, false, false, mode, (float) (docsPerSec / numIndexThreads), updatesListener, -1.0, stats.maxDoc); // NativePosixUtil.mlockTermsDict(startR, "id"); final SearcherManager manager = new SearcherManager(w, null); IndexSearcher s = manager.acquire(); try { System.out.println("Reader=" + s.getIndexReader()); } finally { manager.release(s); } final DirectSpellChecker spellChecker = new DirectSpellChecker(); final IndexState indexState = new IndexState(manager, null, field, spellChecker, "FastVectorHighlighter", null, null); final QueryParser qp = new QueryParser(field, analyzer); TaskParser taskParser = new TaskParser(indexState, qp, field, 10, random, null, true); final TaskSource tasks = new RandomTaskSource(taskParser, tasksFile, random) { @Override public void taskDone(Task task, long queueTimeNS, TotalHits toalHitCount) { searchesByTime[currentQT.get()].incrementAndGet(); } }; System.out.println("Task repeat count 1"); System.out.println("Tasks file " + tasksFile); System.out.println("Num task per cat 20"); final TaskThreads taskThreads = new TaskThreads(tasks, indexState, numSearchThreads); final ReopenThread reopenThread = new ReopenThread(reopenPerSec, manager, reopensByTime, runTimeSec); reopenThread.setName("ReopenThread"); reopenThread.setPriority(4+Thread.currentThread().getPriority()); System.out.println("REOPEN PRI " + reopenThread.getPriority()); indexThreads.start(); reopenThread.start(); taskThreads.start(); Thread.currentThread().setPriority(5+Thread.currentThread().getPriority()); System.out.println("TIMER PRI " + Thread.currentThread().getPriority()); //System.out.println("Start: " + new Date()); final long startMS = System.currentTimeMillis(); final long stopMS = startMS + (long) (runTimeSec * 1000); int lastQT = -1; while (true) { final long t = System.currentTimeMillis(); if (t >= stopMS) { break; } final int qt = (int) ((t-startMS)/statsEverySec/1000); currentQT.set(qt); if (qt != lastQT) { final int prevQT = lastQT; lastQT = qt; if (prevQT > 0) { final String other; if (hasProcMemInfo) { other = " D=" + getLinuxDirtyBytes(); } else { other = ""; } int prev = prevQT - 1; System.out.println(String.format("QT %d searches=%d docs=%d reopens=%s totUpdateTime=%d", prev, searchesByTime[prev].get(), docsIndexedByTime[prev].get(), reopensByTime[prev].get() + other, TimeUnit.NANOSECONDS.toMillis(totalUpdateTimeByTime[prev].get()))); } } Thread.sleep(25); } taskThreads.stop(); reopenThread.join(); indexThreads.stop(); System.out.println("By time:"); for (int i = 0; i < searchesByTime.length - 2; i++) { System.out.println(String.format(" %d searches=%d docs=%d reopens=%d totUpdateTime=%d", i*statsEverySec, searchesByTime[i].get(), docsIndexedByTime[i].get(), reopensByTime[i].get(), TimeUnit.NANOSECONDS.toMillis(totalUpdateTimeByTime[i].get()))); } manager.close(); if (doCommit) { w.close(); } else { w.rollback(); } } private static long getLinuxDirtyBytes() throws Exception { final BufferedReader br = new BufferedReader(new FileReader("/proc/meminfo"), 4096); int dirtyKB = -1; try { while(true) { String line = br.readLine(); if (line == null) { break; } else if (line.startsWith("Dirty:")) { final String trimmed = line.trim(); dirtyKB = Integer.parseInt(trimmed.substring(7, trimmed.length()-3).trim()); break; } } } catch (Exception e) { e.printStackTrace(System.out); } finally { br.close(); } return dirtyKB; } }
/* Copyright [2020] [Intergral GmbH] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.nerdvision.redact.pii.regex; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class EmailRedactorTest { private EmailRedactor emailRedactor; @Before public void setUp() throws Exception { emailRedactor = new EmailRedactor(); } @Test public void emailRedactor() { assertEquals( "my email is EMAIL_ADDRESS.", emailRedactor.redact( "my email is asdasd@nerd.vision." ) ); assertEquals( "my email is EMAIL_ADDRESS.", emailRedactor.redact( "my email is asdasdsad@googlemail.com." ) ); assertEquals( "my email is EMAIL_ADDRESS.", emailRedactor.redact( "my email is asdasdsad@nerdviion.io." ) ); assertEquals( "my email is EMAIL_ADDRESS.", emailRedactor.redact( "my email is asdasdsad_donnelly+somefilter@nerdviion.io." ) ); assertEquals( "my email is EMAIL_ADDRESS.", emailRedactor.redact( "my email is a.s.d_d_d_f_e_r_g_e.y+somefilter@nerdviion.io." ) ); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.example.micrometer; import java.util.Random; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; @Component public class ScheduledRouteBuilder extends RouteBuilder { static final String TIMER_ROUTE_ID = "timer:foo"; private Random random = new Random(System.currentTimeMillis()); @Override public void configure() throws Exception { from("timer:foo?period=1000&fixedRate=true") .routeId(TIMER_ROUTE_ID) .setHeader("random").exchange(exchange -> random.nextInt(100)) .log(LoggingLevel.INFO, "Delay is ${header.random}") .to("direct:bar"); from("direct:bar") .routeId("direct:bar") .to("micrometer:summary:summary?value=${header.random}") .to("micrometer:timer:timer?action=start") .delay().exchange(exchange -> random.nextInt(100)) .to("micrometer:timer:timer?action=stop"); } }
package com.thebhakti; /** * Created by Yeshveer on 11/17/2018. */ class ChatMsg2 { String id,name,msg,userType,time,seen; public ChatMsg2(String id, String name, String msg, String userType, String time,String seen) { this.id=id; this.name=name; this.msg=msg; this.userType=userType; this.time=time; this.seen=seen; } // create gettter and setter method public String getId() { return id; } public String getSeen() { return seen; } public void setSeen(String seen) { this.seen = seen; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.cluster.server.member; import org.apache.iotdb.cluster.client.ClientCategory; import org.apache.iotdb.cluster.client.ClientManager; import org.apache.iotdb.cluster.config.ClusterConstant; import org.apache.iotdb.cluster.config.ClusterDescriptor; import org.apache.iotdb.cluster.exception.CheckConsistencyException; import org.apache.iotdb.cluster.exception.LogExecutionException; import org.apache.iotdb.cluster.exception.SnapshotInstallationException; import org.apache.iotdb.cluster.exception.UnknownLogTypeException; import org.apache.iotdb.cluster.log.Log; import org.apache.iotdb.cluster.log.LogApplier; import org.apache.iotdb.cluster.log.LogParser; import org.apache.iotdb.cluster.log.Snapshot; import org.apache.iotdb.cluster.log.applier.AsyncDataLogApplier; import org.apache.iotdb.cluster.log.applier.DataLogApplier; import org.apache.iotdb.cluster.log.logtypes.AddNodeLog; import org.apache.iotdb.cluster.log.logtypes.CloseFileLog; import org.apache.iotdb.cluster.log.logtypes.RemoveNodeLog; import org.apache.iotdb.cluster.log.manage.FilePartitionedSnapshotLogManager; import org.apache.iotdb.cluster.log.manage.PartitionedSnapshotLogManager; import org.apache.iotdb.cluster.log.snapshot.FileSnapshot; import org.apache.iotdb.cluster.log.snapshot.PartitionedSnapshot; import org.apache.iotdb.cluster.log.snapshot.PullSnapshotTask; import org.apache.iotdb.cluster.log.snapshot.PullSnapshotTaskDescriptor; import org.apache.iotdb.cluster.metadata.CSchemaProcessor; import org.apache.iotdb.cluster.partition.NodeAdditionResult; import org.apache.iotdb.cluster.partition.NodeRemovalResult; import org.apache.iotdb.cluster.partition.PartitionGroup; import org.apache.iotdb.cluster.partition.slot.SlotManager; import org.apache.iotdb.cluster.partition.slot.SlotManager.SlotStatus; import org.apache.iotdb.cluster.partition.slot.SlotNodeAdditionResult; import org.apache.iotdb.cluster.partition.slot.SlotNodeRemovalResult; import org.apache.iotdb.cluster.partition.slot.SlotPartitionTable; import org.apache.iotdb.cluster.partition.slot.SlotTimePartitionFilter; import org.apache.iotdb.cluster.query.LocalQueryExecutor; import org.apache.iotdb.cluster.query.manage.ClusterQueryManager; import org.apache.iotdb.cluster.rpc.thrift.ElectionRequest; import org.apache.iotdb.cluster.rpc.thrift.Node; import org.apache.iotdb.cluster.rpc.thrift.PullSnapshotRequest; import org.apache.iotdb.cluster.rpc.thrift.PullSnapshotResp; import org.apache.iotdb.cluster.rpc.thrift.RaftNode; import org.apache.iotdb.cluster.rpc.thrift.SendSnapshotRequest; import org.apache.iotdb.cluster.server.NodeCharacter; import org.apache.iotdb.cluster.server.PullSnapshotHintService; import org.apache.iotdb.cluster.server.Response; import org.apache.iotdb.cluster.server.heartbeat.DataHeartbeatThread; import org.apache.iotdb.cluster.server.monitor.NodeReport.DataMemberReport; import org.apache.iotdb.cluster.server.monitor.NodeStatusManager; import org.apache.iotdb.cluster.server.monitor.Peer; import org.apache.iotdb.cluster.server.monitor.Timer; import org.apache.iotdb.cluster.server.monitor.Timer.Statistic; import org.apache.iotdb.cluster.utils.IOUtils; import org.apache.iotdb.cluster.utils.StatusUtils; import org.apache.iotdb.common.rpc.thrift.TEndPoint; import org.apache.iotdb.common.rpc.thrift.TSStatus; import org.apache.iotdb.commons.concurrent.IoTDBThreadPoolFactory; import org.apache.iotdb.commons.conf.IoTDBConstant; import org.apache.iotdb.commons.exception.IllegalPathException; import org.apache.iotdb.commons.exception.MetadataException; import org.apache.iotdb.commons.path.PartialPath; import org.apache.iotdb.commons.service.JMXService; import org.apache.iotdb.commons.utils.TestOnly; import org.apache.iotdb.db.conf.IoTDBDescriptor; import org.apache.iotdb.db.engine.StorageEngine; import org.apache.iotdb.db.engine.storagegroup.DataRegion.TimePartitionFilter; import org.apache.iotdb.db.exception.BatchProcessException; import org.apache.iotdb.db.exception.StorageEngineException; import org.apache.iotdb.db.exception.metadata.PathNotExistException; import org.apache.iotdb.db.exception.metadata.StorageGroupNotSetException; import org.apache.iotdb.db.qp.executor.PlanExecutor; import org.apache.iotdb.db.qp.physical.BatchPlan; import org.apache.iotdb.db.qp.physical.PhysicalPlan; import org.apache.iotdb.db.qp.physical.crud.InsertMultiTabletsPlan; import org.apache.iotdb.db.qp.physical.crud.InsertPlan; import org.apache.iotdb.db.qp.physical.crud.InsertRowPlan; import org.apache.iotdb.db.qp.physical.crud.InsertRowsOfOneDevicePlan; import org.apache.iotdb.db.qp.physical.crud.InsertRowsPlan; import org.apache.iotdb.db.qp.physical.crud.InsertTabletPlan; import org.apache.iotdb.db.qp.physical.sys.FlushPlan; import org.apache.iotdb.db.qp.physical.sys.LogPlan; import org.apache.iotdb.db.service.IoTDB; import org.apache.iotdb.rpc.TSStatusCode; import org.apache.iotdb.tsfile.utils.Pair; import org.apache.thrift.protocol.TProtocolFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import static org.apache.iotdb.cluster.config.ClusterConstant.THREAD_POLL_WAIT_TERMINATION_TIME_S; public class DataGroupMember extends RaftMember implements DataGroupMemberMBean { private final String mbeanName; private static final Logger logger = LoggerFactory.getLogger(DataGroupMember.class); /** * The MetaGroupMember that in charge of the DataGroupMember. Mainly for providing partition table * and MetaLogManager. */ private MetaGroupMember metaGroupMember; /** The thread pool that runs the pull snapshot tasks. Pool size is the # of CPU cores. */ private ExecutorService pullSnapshotService; /** * When the member applies a pulled snapshot, it register hints in this service which will * periodically inform the data source that one member has pulled snapshot. */ private PullSnapshotHintService pullSnapshotHintService; /** * "queryManger" records the remote nodes which have queried this node, and the readers or * executors this member has created for those queries. When the queries end, an EndQueryRequest * will be sent to this member and related resources will be released. */ private ClusterQueryManager queryManager; /** * "slotManager" tracks the status of slots during data transfers so that we can know whether the * slot has non-pulled data. */ protected SlotManager slotManager; private LocalQueryExecutor localQueryExecutor; LogApplier dataLogApplier; /** * When a new partition table is installed, all data members will be checked if unchanged. If not, * such members will be removed. */ private boolean unchanged; private LastAppliedPatitionTableVersion lastAppliedPartitionTableVersion; @TestOnly public DataGroupMember(PartitionGroup nodes) { // constructor for test this.name = "Data-" + nodes.getHeader().getNode().getInternalIp() + "-" + nodes.getHeader().getNode().getDataPort() + "-raftId-" + nodes.getRaftId() + ""; allNodes = nodes; mbeanName = String.format( "%s:%s=%s%d", "org.apache.iotdb.cluster.service", IoTDBConstant.JMX_TYPE, "DataMember", getRaftGroupId()); setQueryManager(new ClusterQueryManager()); localQueryExecutor = new LocalQueryExecutor(this); lastAppliedPartitionTableVersion = new LastAppliedPatitionTableVersion(getMemberDir()); } DataGroupMember(TProtocolFactory factory, PartitionGroup nodes, MetaGroupMember metaGroupMember) { // The name is used in JMX, so we have to avoid to use "(" "," "=" ")" super( "Data-" + nodes.getHeader().getNode().getInternalIp() + "-" + nodes.getHeader().getNode().getDataPort() + "-raftId-" + nodes.getRaftId() + "", new ClientManager( ClusterDescriptor.getInstance().getConfig().isUseAsyncServer(), ClientManager.Type.DataGroupClient)); this.metaGroupMember = metaGroupMember; allNodes = nodes; mbeanName = String.format( "%s:%s=%s%d", "org.apache.iotdb.cluster.service", IoTDBConstant.JMX_TYPE, "DataMember", getRaftGroupId()); setQueryManager(new ClusterQueryManager()); slotManager = new SlotManager(ClusterConstant.SLOT_NUM, getMemberDir(), getName()); dataLogApplier = new DataLogApplier(metaGroupMember, this); if (ClusterDescriptor.getInstance().getConfig().isUseAsyncApplier() && ClusterDescriptor.getInstance().getConfig().getReplicationNum() != 1) { dataLogApplier = new AsyncDataLogApplier(dataLogApplier, name); } logManager = new FilePartitionedSnapshotLogManager( dataLogApplier, metaGroupMember.getPartitionTable(), allNodes.get(0), thisNode, this); initPeerMap(); term.set(logManager.getHardState().getCurrentTerm()); voteFor = logManager.getHardState().getVoteFor(); localQueryExecutor = new LocalQueryExecutor(this); lastAppliedPartitionTableVersion = new LastAppliedPatitionTableVersion(getMemberDir()); } /** * Start heartbeat, catch-up, pull snapshot services and start all unfinished pull-snapshot-tasks. * Calling the method twice does not induce side effects. */ @Override public void start() { if (heartBeatService != null) { return; } logger.info("Starting DataGroupMember {}... RaftGroupID: {}", name, getRaftGroupId()); JMXService.registerMBean(this, mbeanName); super.start(); heartBeatService.submit(new DataHeartbeatThread(this)); pullSnapshotService = IoTDBThreadPoolFactory.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), "pullSnapshot"); pullSnapshotHintService = new PullSnapshotHintService(this); pullSnapshotHintService.start(); resumePullSnapshotTasks(); } /** * Stop heartbeat, catch-up and pull snapshot services and release all query resources. Calling * the method twice does not induce side effects. */ @Override public void stop() { logger.info("Stopping DataGroupMember {}... RaftGroupID: {}", name, getRaftGroupId()); JMXService.deregisterMBean(mbeanName); super.stop(); if (pullSnapshotService != null) { pullSnapshotService.shutdownNow(); try { pullSnapshotService.awaitTermination(THREAD_POLL_WAIT_TERMINATION_TIME_S, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("Unexpected interruption when waiting for pullSnapshotService to end", e); } pullSnapshotService = null; pullSnapshotHintService.stop(); } try { getQueryManager().endAllQueries(); } catch (StorageEngineException e) { logger.error("Cannot release queries of {}", name, e); } logger.info("{}: stopped", name); } @Override long checkElectorLogProgress(ElectionRequest electionRequest) { Node elector = electionRequest.getElector(); // check if the node is in the group if (!allNodes.contains(elector)) { logger.info( "{}: the elector {} is not in the data group {}, so reject this election.", name, getPartitionGroup(), elector); return Response.RESPONSE_NODE_IS_NOT_IN_GROUP; } return super.checkElectorLogProgress(electionRequest); } /** * The first node (on the hash ring) in this data group is the header. It determines the duty * (what range on the ring do the group take responsibility for) of the group and although other * nodes in this may change, this node is unchangeable unless the data group is dismissed. It is * also the identifier of this data group. */ @Override public RaftNode getHeader() { return allNodes.getHeader(); } public ClusterQueryManager getQueryManager() { return queryManager; } protected void setQueryManager(ClusterQueryManager queryManager) { this.queryManager = queryManager; } public static class Factory { private TProtocolFactory protocolFactory; private MetaGroupMember metaGroupMember; public Factory(TProtocolFactory protocolFactory, MetaGroupMember metaGroupMember) { this.protocolFactory = protocolFactory; this.metaGroupMember = metaGroupMember; } public DataGroupMember create(PartitionGroup partitionGroup) { return new DataGroupMember(protocolFactory, partitionGroup, metaGroupMember); } } public boolean preAddNode(Node node) { if (logger.isDebugEnabled()) { logger.debug("{}: start to pre adding node {}", name, node); } synchronized (allNodes) { if (allNodes.contains(node)) { return false; } int insertIndex = -1; // find the position to insert the new node, the nodes are ordered by their identifiers for (int i = 0; i < allNodes.size() - 1; i++) { Node prev = allNodes.get(i); Node next = allNodes.get(i + 1); if (prev.nodeIdentifier < node.nodeIdentifier && node.nodeIdentifier < next.nodeIdentifier || prev.nodeIdentifier < node.nodeIdentifier && next.nodeIdentifier < prev.nodeIdentifier || node.nodeIdentifier < next.nodeIdentifier && next.nodeIdentifier < prev.nodeIdentifier) { insertIndex = i + 1; break; } } if (insertIndex > 0) { allNodes.add(insertIndex, node); peerMap.putIfAbsent(node, new Peer(logManager.getLastLogIndex())); // if the local node is the last node and the insertion succeeds, this node should leave // the group logger.debug("{}: Node {} is inserted into the data group {}", name, node, allNodes); } return insertIndex > 0; } } /** * Try to add a Node into the group to which the member belongs. * * @return true if this node should leave the group because of the addition of the node, false * otherwise */ public boolean addNode(Node node, NodeAdditionResult result) { if (logger.isDebugEnabled()) { logger.debug("{}: start to add node {}", name, node); } // mark slots that do not belong to this group any more Set<Integer> lostSlots = ((SlotNodeAdditionResult) result) .getLostSlots() .getOrDefault(getHeader(), Collections.emptySet()); for (Integer lostSlot : lostSlots) { slotManager.setToSending(lostSlot, false); } slotManager.save(); synchronized (allNodes) { preAddNode(node); if (allNodes.contains(node) && allNodes.size() > config.getReplicationNum()) { // remove the last node because the group size is fixed to replication number Node removedNode = allNodes.remove(allNodes.size() - 1); peerMap.remove(removedNode); if (removedNode.equals(leader.get()) && !removedNode.equals(thisNode)) { // if the leader is removed, also start an election immediately synchronized (term) { setCharacter(NodeCharacter.ELECTOR); setLeader(null); } synchronized (getHeartBeatWaitObject()) { getHeartBeatWaitObject().notifyAll(); } } return removedNode.equals(thisNode); } return false; } } /** * Deserialize and install a snapshot sent by the leader. The type of the snapshot must be * currently PartitionedSnapshot with FileSnapshot inside. */ public void receiveSnapshot(SendSnapshotRequest request) throws SnapshotInstallationException { logger.info( "{}: received a snapshot from {} with size {}", name, request.getHeader(), request.getSnapshotBytes().length); PartitionedSnapshot<FileSnapshot> snapshot = new PartitionedSnapshot<>(FileSnapshot.Factory.INSTANCE); snapshot.deserialize(ByteBuffer.wrap(request.getSnapshotBytes())); if (logger.isDebugEnabled()) { logger.debug("{} received a snapshot {}", name, snapshot); } snapshot.getDefaultInstaller(this).install(snapshot, -1, false); } /** Send the requested snapshots to the applier node. */ public PullSnapshotResp getSnapshot(PullSnapshotRequest request) throws IOException { // if the requester pulls the snapshots because the header of the group is removed, then the // member should no longer receive new data if (request.isRequireReadOnly()) { setReadOnly(); } // Make sure local data is complete. if (character != NodeCharacter.LEADER && lastAppliedPartitionTableVersion.getVersion() != metaGroupMember.getPartitionTable().getLastMetaLogIndex()) { return null; } List<Integer> requiredSlots = request.getRequiredSlots(); for (Integer requiredSlot : requiredSlots) { // wait if the data of the slot is in another node slotManager.waitSlot(requiredSlot); } if (logger.isDebugEnabled()) { logger.debug( "{}: {} slots are requested, first:{}, last: {}", name, requiredSlots.size(), requiredSlots.get(0), requiredSlots.get(requiredSlots.size() - 1)); } // If the logs between [currCommitLogIndex, currLastLogIndex] are committed after the // snapshot is generated, they will be invisible to the new slot owner and thus lost forever long currLastLogIndex = logManager.getLastLogIndex(); logger.info( "{}: Waiting for logs to commit before snapshot, {}/{}", name, logManager.getCommitLogIndex(), currLastLogIndex); while (logManager.getCommitLogIndex() < currLastLogIndex) { try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("{}: Unexpected interruption when waiting for logs to commit", name, e); } } // this synchronized should work with the one in AppendEntry when a log is going to commit, // which may prevent the newly arrived data from being invisible to the new header. synchronized (logManager) { PullSnapshotResp resp = new PullSnapshotResp(); Map<Integer, ByteBuffer> resultMap = new HashMap<>(); ((PartitionedSnapshotLogManager) logManager) .takeSnapshotForSpecificSlots(requiredSlots, false); PartitionedSnapshot<Snapshot> allSnapshot = (PartitionedSnapshot) logManager.getSnapshot(); for (int requiredSlot : requiredSlots) { Snapshot snapshot = allSnapshot.getSnapshot(requiredSlot); if (snapshot != null) { resultMap.put(requiredSlot, snapshot.serialize()); } } resp.setSnapshotBytes(resultMap); logger.debug("{}: Sending {} snapshots to the requester", name, resultMap.size()); return resp; } } /** Pull snapshots from the previous holders after newNode joins the cluster. */ public void pullNodeAdditionSnapshots(List<Integer> slots, Node newNode) { // group the slots by their owners Map<PartitionGroup, List<Integer>> holderSlotsMap = new HashMap<>(); synchronized (logManager) { logger.info("{} pulling {} slots from remote", name, slots.size()); PartitionedSnapshot<Snapshot> snapshot = (PartitionedSnapshot) logManager.getSnapshot(); Map<Integer, PartitionGroup> prevHolders = ((SlotPartitionTable) metaGroupMember.getPartitionTable()) .getPreviousNodeMap(new RaftNode(newNode, getRaftGroupId())); for (int slot : slots) { // skip the slot if the corresponding data is already replicated locally if (snapshot.getSnapshot(slot) == null) { PartitionGroup group = prevHolders.get(slot); if (group != null) { holderSlotsMap.computeIfAbsent(group, n -> new ArrayList<>()).add(slot); } } } } // pull snapshots from each owner's data group for (Entry<PartitionGroup, List<Integer>> entry : holderSlotsMap.entrySet()) { List<Integer> nodeSlots = entry.getValue(); PullSnapshotTaskDescriptor taskDescriptor = new PullSnapshotTaskDescriptor(entry.getKey(), nodeSlots, false); pullFileSnapshot(taskDescriptor, null); } } /** * Pull FileSnapshots (timeseries schemas and lists of TsFiles) of "nodeSlots" from one of the * "prevHolders". The actual pulling will be performed in a separate thread. * * @param descriptor * @param snapshotSave set to the corresponding disk file if the task is resumed from disk, or set * ot null otherwise */ private void pullFileSnapshot(PullSnapshotTaskDescriptor descriptor, File snapshotSave) { // If this node is the member of previous holder, it's unnecessary to pull data again if (descriptor.getPreviousHolders().contains(thisNode)) { logger.info( "{}: {} and other {} don't need to pull because there already has such data locally", name, descriptor.getSlots().get(0), descriptor.getSlots().size() - 1); // inform the previous holders that one member has successfully pulled snapshot directly registerPullSnapshotHint(descriptor); return; } Iterator<Integer> iterator = descriptor.getSlots().iterator(); while (iterator.hasNext()) { Integer nodeSlot = iterator.next(); SlotStatus status = slotManager.getStatus(nodeSlot); if (status != SlotStatus.NULL) { // the pulling may already be issued during restart, skip it in that case iterator.remove(); } else { // mark the slot as pulling to control reads and writes of the pulling slot slotManager.setToPulling( nodeSlot, descriptor.getPreviousHolders().getHeader().getNode(), false); } } slotManager.save(); if (descriptor.getSlots().isEmpty()) { return; } if (logger.isInfoEnabled()) { logger.info( "{}: {} and other {} slots are set to pulling", name, descriptor.getSlots().get(0), descriptor.getSlots().size() - 1); } pullSnapshotService.submit( new PullSnapshotTask<>(descriptor, this, FileSnapshot.Factory.INSTANCE, snapshotSave)); } /** Restart all unfinished pull-snapshot-tasks of the member. */ private void resumePullSnapshotTasks() { File snapshotTaskDir = new File(getPullSnapshotTaskDir()); if (!snapshotTaskDir.exists()) { return; } File[] files = snapshotTaskDir.listFiles(); if (files != null) { for (File file : files) { if (!file.getName().endsWith(PullSnapshotTask.TASK_SUFFIX)) { continue; } try (DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)))) { PullSnapshotTaskDescriptor descriptor = new PullSnapshotTaskDescriptor(); descriptor.deserialize(dataInputStream); pullFileSnapshot(descriptor, file); } catch (IOException e) { logger.error("Cannot resume pull-snapshot-task in file {}", file, e); try { Files.delete(file.toPath()); } catch (IOException ex) { logger.debug("Cannot remove pull snapshot task file {}", file, e); } } } } } /** @return a directory that stores the information of ongoing pulling snapshot tasks. */ public String getPullSnapshotTaskDir() { return getMemberDir() + "snapshot_task" + File.separator; } /** @return the path of the directory that is provided exclusively for the member. */ private String getMemberDir() { return IoTDBDescriptor.getInstance().getConfig().getSystemDir() + File.separator + "raft" + File.separator + getHeader().getNode().nodeIdentifier + File.separator + getRaftGroupId() + File.separator; } public MetaGroupMember getMetaGroupMember() { return metaGroupMember; } /** * If the member is the leader, let all members in the group close the specified partition of a * storage group, else just return false. */ boolean closePartition(String storageGroupName, long partitionId, boolean isSeq) { if (character != NodeCharacter.LEADER) { return false; } CloseFileLog log = new CloseFileLog(storageGroupName, partitionId, isSeq); synchronized (logManager) { log.setCurrLogTerm(getTerm().get()); log.setCurrLogIndex(logManager.getLastLogIndex() + 1); logManager.append(log); logger.info("Send the close file request of {} to other nodes", log); } try { return appendLogInGroup(log); } catch (LogExecutionException e) { logger.error("Cannot close partition {}#{} seq:{}", storageGroupName, partitionId, isSeq, e); } return false; } public boolean flushFileWhenDoSnapshot( Map<String, List<Pair<Long, Boolean>>> storageGroupPartitions, List<Integer> requiredSlots, boolean needLeader) { if (needLeader && character != NodeCharacter.LEADER) { return false; } Map<PartialPath, List<Pair<Long, Boolean>>> localDataMemberStorageGroupPartitions = new HashMap<>(); for (Entry<String, List<Pair<Long, Boolean>>> entry : storageGroupPartitions.entrySet()) { List<Pair<Long, Boolean>> localListPair = new ArrayList<>(); String storageGroupName = entry.getKey(); List<Pair<Long, Boolean>> tmpPairList = entry.getValue(); for (Pair<Long, Boolean> pair : tmpPairList) { long timestamp = pair.left * StorageEngine.getTimePartitionInterval(); int slotId = SlotPartitionTable.getSlotStrategy() .calculateSlotByTime(storageGroupName, timestamp, ClusterConstant.SLOT_NUM); if (requiredSlots.contains(slotId)) { localListPair.add(pair); } } try { localDataMemberStorageGroupPartitions.put(new PartialPath(storageGroupName), localListPair); } catch (IllegalPathException e) { // ignore } } if (localDataMemberStorageGroupPartitions.size() <= 0) { logger.info("{}: have no data to flush", name); return true; } FlushPlan flushPlan = new FlushPlan(null, true, localDataMemberStorageGroupPartitions); try { PlanExecutor.flushSpecifiedStorageGroups(flushPlan); return true; } catch (StorageGroupNotSetException e) { logger.error("Some SGs are missing while flushing", e); } return false; } /** * Execute a non-query plan. If the member is a leader, a log for the plan will be created and * process through the raft procedure, otherwise the plan will be forwarded to the leader. * * @param plan a non-query plan. */ @Override public TSStatus executeNonQueryPlan(PhysicalPlan plan) { if (ClusterDescriptor.getInstance().getConfig().getReplicationNum() == 1) { try { if (plan instanceof LogPlan) { Log log; try { log = LogParser.getINSTANCE().parse(((LogPlan) plan).getLog()); } catch (UnknownLogTypeException e) { logger.error("Can not parse LogPlan {}", plan, e); return StatusUtils.PARSE_LOG_ERROR; } handleChangeMembershipLogWithoutRaft(log); } else { ((DataLogApplier) dataLogApplier).applyPhysicalPlan(plan); } return StatusUtils.OK; } catch (Exception e) { Throwable cause = IOUtils.getRootCause(e); boolean hasCreated = false; try { if (plan instanceof InsertPlan && ClusterDescriptor.getInstance().getConfig().isEnableAutoCreateSchema()) { if (plan instanceof InsertRowsPlan || plan instanceof InsertMultiTabletsPlan) { if (e instanceof BatchProcessException) { for (TSStatus status : ((BatchProcessException) e).getFailingStatus()) { if (status.getCode() == TSStatusCode.TIMESERIES_NOT_EXIST.getStatusCode()) { hasCreated = createTimeseriesForFailedInsertion(((InsertPlan) plan)); ((BatchPlan) plan).getResults().clear(); break; } } } } else if (cause instanceof PathNotExistException) { hasCreated = createTimeseriesForFailedInsertion(((InsertPlan) plan)); } } } catch (MetadataException | CheckConsistencyException ex) { logger.error("{}: Cannot auto-create timeseries for {}", name, plan, e); return StatusUtils.getStatus(StatusUtils.EXECUTE_STATEMENT_ERROR, ex.getMessage()); } if (hasCreated) { return executeNonQueryPlan(plan); } return handleLogExecutionException(plan, cause); } } else { TSStatus status = executeNonQueryPlanWithKnownLeader(plan); if (!StatusUtils.NO_LEADER.equals(status)) { return status; } long startTime = Timer.Statistic.DATA_GROUP_MEMBER_WAIT_LEADER.getOperationStartTime(); waitLeader(); Timer.Statistic.DATA_GROUP_MEMBER_WAIT_LEADER.calOperationCostTimeFromStart(startTime); return executeNonQueryPlanWithKnownLeader(plan); } } @Override ClientCategory getClientCategory() { return ClientCategory.DATA; } @Override public String getMBeanName() { return mbeanName; } private void handleChangeMembershipLogWithoutRaft(Log log) { if (log instanceof AddNodeLog) { if (!metaGroupMember .getPartitionTable() .deserialize(((AddNodeLog) log).getPartitionTable())) { return; } preAddNode(((AddNodeLog) log).getNewNode()); setAndSaveLastAppliedPartitionTableVersion(((AddNodeLog) log).getMetaLogIndex()); } else if (log instanceof RemoveNodeLog) { if (!metaGroupMember .getPartitionTable() .deserialize(((RemoveNodeLog) log).getPartitionTable())) { return; } preRemoveNode(((RemoveNodeLog) log).getRemovedNode()); setAndSaveLastAppliedPartitionTableVersion(((RemoveNodeLog) log).getMetaLogIndex()); } else { logger.error("Unsupported log: {}", log); } } private TSStatus executeNonQueryPlanWithKnownLeader(PhysicalPlan plan) { if (character == NodeCharacter.LEADER) { long startTime = Statistic.DATA_GROUP_MEMBER_LOCAL_EXECUTION.getOperationStartTime(); TSStatus status = processPlanLocally(plan); boolean hasCreated = false; try { if (plan instanceof InsertPlan && ClusterDescriptor.getInstance().getConfig().isEnableAutoCreateSchema()) { if (plan instanceof InsertRowsPlan || plan instanceof InsertMultiTabletsPlan) { if (status.getCode() == TSStatusCode.MULTIPLE_ERROR.getStatusCode()) { for (TSStatus tmpStatus : status.getSubStatus()) { if (tmpStatus.getCode() == TSStatusCode.TIMESERIES_NOT_EXIST.getStatusCode()) { hasCreated = createTimeseriesForFailedInsertion(((InsertPlan) plan)); ((BatchPlan) plan).getResults().clear(); break; } } } } else { if (status.getCode() == TSStatusCode.TIMESERIES_NOT_EXIST.getStatusCode()) { hasCreated = createTimeseriesForFailedInsertion(((InsertPlan) plan)); } } } } catch (MetadataException | CheckConsistencyException e) { logger.error("{}: Cannot auto-create timeseries for {}", name, plan, e); return StatusUtils.getStatus(StatusUtils.EXECUTE_STATEMENT_ERROR, e.getMessage()); } if (hasCreated) { status = processPlanLocally(plan); } Statistic.DATA_GROUP_MEMBER_LOCAL_EXECUTION.calOperationCostTimeFromStart(startTime); if (status != null) { return status; } } else if (leader.get() != null && !ClusterConstant.EMPTY_NODE.equals(leader.get())) { long startTime = Timer.Statistic.DATA_GROUP_MEMBER_FORWARD_PLAN.getOperationStartTime(); TSStatus result = forwardPlan(plan, leader.get(), getHeader()); Timer.Statistic.DATA_GROUP_MEMBER_FORWARD_PLAN.calOperationCostTimeFromStart(startTime); if (!StatusUtils.NO_LEADER.equals(result)) { result.setRedirectNode( new TEndPoint(leader.get().getClientIp(), leader.get().getClientPort())); return result; } } return StatusUtils.NO_LEADER; } private boolean createTimeseriesForFailedInsertion(InsertPlan plan) throws CheckConsistencyException, IllegalPathException { logger.debug("create time series for failed insertion {}", plan); // apply measurements according to failed measurements if (plan instanceof InsertMultiTabletsPlan) { for (InsertTabletPlan insertPlan : ((InsertMultiTabletsPlan) plan).getInsertTabletPlanList()) { if (insertPlan.getFailedMeasurements() != null) { insertPlan.getPlanFromFailed(); } } } if (plan instanceof InsertRowsPlan) { for (InsertRowPlan insertPlan : ((InsertRowsPlan) plan).getInsertRowPlanList()) { if (insertPlan.getFailedMeasurements() != null) { insertPlan.getPlanFromFailed(); } } } if (plan instanceof InsertRowsOfOneDevicePlan) { for (InsertRowPlan insertPlan : ((InsertRowsOfOneDevicePlan) plan).getRowPlans()) { if (insertPlan.getFailedMeasurements() != null) { insertPlan.getPlanFromFailed(); } } } if (plan.getFailedMeasurements() != null) { plan.getPlanFromFailed(); } return ((CSchemaProcessor) IoTDB.schemaProcessor).createTimeseries(plan); } /** * When the node does not play a member in a group any more, the corresponding local data should * be removed. */ public void removeLocalData(List<Integer> slots) { if (slots.isEmpty()) { return; } Set<Integer> slotSet = new HashSet<>(slots); List<PartialPath> allStorageGroupNames = IoTDB.schemaProcessor.getAllStorageGroupPaths(); TimePartitionFilter filter = (storageGroupName, timePartitionId) -> { int slot = SlotPartitionTable.getSlotStrategy() .calculateSlotByPartitionNum( storageGroupName, timePartitionId, ClusterConstant.SLOT_NUM); /** * If this slot is just held by different raft groups in the same node, it should keep the * data of slot. */ if (((SlotPartitionTable) metaGroupMember.getPartitionTable()) .judgeHoldSlot(thisNode, slot)) { return false; } return slotSet.contains(slot); }; for (PartialPath sg : allStorageGroupNames) { StorageEngine.getInstance().removePartitions(sg, filter); } for (Integer slot : slots) { slotManager.setToNull(slot, false); } slotManager.save(); if (logger.isInfoEnabled()) { logger.info( "{}: data of {} and other {} slots are removed", name, slots.get(0), slots.size() - 1); } } public void preRemoveNode(Node removedNode) { if (logger.isDebugEnabled()) { logger.debug("{}: start to pre remove node {}", name, removedNode); } synchronized (allNodes) { if (allNodes.contains(removedNode) && allNodes.size() == config.getReplicationNum()) { // update the group if the deleted node was in it PartitionGroup newGroup = metaGroupMember.getPartitionTable().getPartitionGroup(getHeader()); if (newGroup == null) { return; } Node newNodeToGroup = newGroup.get(newGroup.size() - 1); allNodes.add(newNodeToGroup); peerMap.putIfAbsent(newNodeToGroup, new Peer(logManager.getLastLogIndex())); } } } /** * Return a TimePartitionFilter that tells whether a time partition is managed by this member. * * @return a TimePartitionFilter that tells whether a time partition is managed by this member. */ public TimePartitionFilter getTimePartitionFilter() { Set<Integer> slotSet = new HashSet<>( ((SlotPartitionTable) metaGroupMember.getPartitionTable()).getNodeSlots(getHeader())); return new SlotTimePartitionFilter(slotSet); } /** * When a node is removed and IT IS NOT THE HEADER of the group, the member should take over some * slots from the removed group, and add a new node to the group the removed node was in the * group. */ @SuppressWarnings("java:S2445") // the reference of allNodes is unchanged public void removeNode(Node removedNode) { if (logger.isDebugEnabled()) { logger.debug("{}: start to remove node {}", name, removedNode); } synchronized (allNodes) { preRemoveNode(removedNode); if (allNodes.contains(removedNode)) { // update the group if the deleted node was in it allNodes.remove(removedNode); peerMap.remove(removedNode); if (removedNode.equals(leader.get())) { // if the leader is removed, also start an election immediately synchronized (term) { setCharacter(NodeCharacter.ELECTOR); setLeader(null); } synchronized (getHeartBeatWaitObject()) { getHeartBeatWaitObject().notifyAll(); } } } } } public void pullSlots(NodeRemovalResult removalResult) { List<Integer> slotsToPull = ((SlotNodeRemovalResult) removalResult).getNewSlotOwners().get(getHeader()); if (slotsToPull != null) { // pull the slots that should be taken over PullSnapshotTaskDescriptor taskDescriptor = new PullSnapshotTaskDescriptor( removalResult.getRemovedGroup(getRaftGroupId()), new ArrayList<>(slotsToPull), true); pullFileSnapshot(taskDescriptor, null); } } /** * Generate a report containing the character, leader, term, last log term, last log index, header * and readOnly or not of this member. */ public DataMemberReport genReport() { long prevLastLogIndex = lastReportedLogIndex; lastReportedLogIndex = logManager.getLastLogIndex(); return new DataMemberReport( character, leader.get(), term.get(), logManager.getLastLogTerm(), lastReportedLogIndex, logManager.getCommitLogIndex(), logManager.getCommitLogTerm(), getHeader(), readOnly, NodeStatusManager.getINSTANCE().getLastResponseLatency(getHeader().getNode()), lastHeartbeatReceivedTime, prevLastLogIndex, logManager.getMaxHaveAppliedCommitIndex()); } @TestOnly public void setMetaGroupMember(MetaGroupMember metaGroupMember) { this.metaGroupMember = metaGroupMember; this.localQueryExecutor = new LocalQueryExecutor(this); } @TestOnly void setLogManager(PartitionedSnapshotLogManager<Snapshot> logManager) { if (this.logManager != null) { this.logManager.close(); } this.logManager = logManager; super.setLogManager(logManager); initPeerMap(); } public SlotManager getSlotManager() { return slotManager; } public boolean onSnapshotInstalled(List<Integer> slots) { if (getMetaGroupMember().getPartitionTable().getAllNodes().contains(thisNode)) { getMetaGroupMember() .syncLocalApply(getMetaGroupMember().getPartitionTable().getLastMetaLogIndex(), false); } if (logger.isDebugEnabled()) { logger.debug( "{} received one replication snapshot installed of slot {} and other {} slots", name, slots.get(0), slots.size() - 1); } List<Integer> removableSlots = new ArrayList<>(); for (Integer slot : slots) { int sentReplicaNum = slotManager.sentOneReplication(slot, false); if (sentReplicaNum >= config.getReplicationNum()) { removableSlots.add(slot); } } slotManager.save(); removeLocalData(removableSlots); return true; } public void registerPullSnapshotHint(PullSnapshotTaskDescriptor descriptor) { pullSnapshotHintService.registerHint(descriptor); } /** * Find the groups that should be queried due to data migration. When a slot is in the status of * PULLING or PULLING_WRITABLE, the read of it should merge result to guarantee integrity. */ public Map<PartitionGroup, Set<Integer>> getPreviousHolderSlotMap() { Map<PartitionGroup, Set<Integer>> holderSlotMap = new HashMap<>(); RaftNode header = getHeader(); Map<RaftNode, Map<Integer, PartitionGroup>> previousHolderMap = ((SlotPartitionTable) getMetaGroupMember().getPartitionTable()).getPreviousNodeMap(); if (previousHolderMap.containsKey(header)) { for (Entry<Integer, PartitionGroup> entry : previousHolderMap.get(header).entrySet()) { int slot = entry.getKey(); PartitionGroup holder = entry.getValue(); if (slotManager.checkSlotInDataMigrationStatus(slot)) { holderSlotMap.computeIfAbsent(holder, n -> new HashSet<>()).add(slot); } } } return holderSlotMap; } public LocalQueryExecutor getLocalQueryExecutor() { return localQueryExecutor; } @TestOnly public void setLocalQueryExecutor(LocalQueryExecutor localQueryExecutor) { this.localQueryExecutor = localQueryExecutor; } public boolean isUnchanged() { return unchanged; } public void setUnchanged(boolean unchanged) { this.unchanged = unchanged; } public void setAndSaveLastAppliedPartitionTableVersion(long version) { lastAppliedPartitionTableVersion.setVersion(version); lastAppliedPartitionTableVersion.save(); } private class LastAppliedPatitionTableVersion { private static final String VERSION_FILE_NAME = "LAST_PARTITION_TABLE_VERSION"; private long version = -1; private String filePath; public LastAppliedPatitionTableVersion(String memberDir) { this.filePath = memberDir + File.separator + VERSION_FILE_NAME; load(); } private void load() { File versionFile = new File(filePath); if (!versionFile.exists()) { return; } try (FileInputStream fileInputStream = new FileInputStream(filePath); DataInputStream dataInputStream = new DataInputStream(fileInputStream)) { version = dataInputStream.readLong(); } catch (Exception e) { logger.warn("Cannot deserialize last partition table version from {}", filePath, e); } } public synchronized void save() { File versionFile = new File(filePath); if (!versionFile.getParentFile().exists() && !versionFile.getParentFile().mkdirs()) { logger.warn("Cannot mkdirs for {}", versionFile); } try (FileOutputStream outputStream = new FileOutputStream(versionFile); DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) { dataOutputStream.writeLong(version); } catch (IOException e) { logger.warn("Last partition table version in {} cannot be saved", filePath, e); } } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } } }
/* * Copyright 2020 ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package tech.pegasys.teku.storage.api; import com.google.common.primitives.UnsignedLong; import java.util.Optional; import org.apache.tuweni.bytes.Bytes32; import tech.pegasys.teku.datastructures.blocks.SignedBeaconBlock; import tech.pegasys.teku.datastructures.state.BeaconState; import tech.pegasys.teku.util.async.SafeFuture; public class StubStorageQueryChannel implements StorageQueryChannel { @Override public SafeFuture<Optional<SignedBeaconBlock>> getFinalizedBlockAtSlot(UnsignedLong slot) { return SafeFuture.completedFuture(Optional.empty()); } @Override public SafeFuture<Optional<SignedBeaconBlock>> getLatestFinalizedBlockAtSlot(UnsignedLong slot) { return SafeFuture.completedFuture(Optional.empty()); } @Override public SafeFuture<Optional<SignedBeaconBlock>> getBlockByBlockRoot(Bytes32 blockRoot) { return SafeFuture.completedFuture(Optional.empty()); } @Override public SafeFuture<Optional<BeaconState>> getLatestFinalizedStateAtSlot(UnsignedLong slot) { return SafeFuture.completedFuture(Optional.empty()); } @Override public SafeFuture<Optional<BeaconState>> getFinalizedStateByBlockRoot(Bytes32 blockRoot) { return SafeFuture.completedFuture(Optional.empty()); } }
package com.alibaba.csp.sentinel.dashboard.rule.nacos; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * @author zhangxiaolong * @since 1.7.2 */ @Component("paramFlowRuleNacosProvider") public class ParamFlowRuleNacosProvider implements DynamicRuleProvider<List<ParamFlowRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String, List<ParamFlowRuleEntity>> converter; @Override public List<ParamFlowRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName + NacosConfigUtil.PARAM_FLOW_DATA_ID_POSTFIX, NacosConfigUtil.GROUP_ID, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } return converter.convert(rules); } }
package io.cosmos.common; public class ProdEnv extends EnvBase { public String GetRestServerUrl(){ return "https://stargate.evaio.net"; } }
package com.deer.wms.bill.manage.service; import com.deer.wms.bill.manage.model.MtAloneAuditNodeOpinionTab; import com.deer.wms.bill.manage.model.MtAloneAuditNodeOpinionTabParams; import com.deer.wms.bill.manage.model.MtAloneAuditNodeOpinionTabVo; import com.deer.wms.project.seed.core.service.Service; import java.util.List; /** * Created by gtt on 2019/07/18. */ public interface MtAloneAuditNodeOpinionTabService extends Service<MtAloneAuditNodeOpinionTab, Integer> { List<MtAloneAuditNodeOpinionTabVo> findList(MtAloneAuditNodeOpinionTabParams params) ; }
package com.nurseryapi.model.response.lookup; import com.nurseryapi.entity.lookup.MajorEntity; import com.nurseryapi.utils.Mapper; import lombok.Getter; import lombok.Setter; @Setter @Getter public class MajorResponse { private Long id; private String label; /** * * @param majorEntity */ public MajorResponse(MajorEntity majorEntity) { Mapper.map(majorEntity, this); } }
package com.brain.jd.domain; /** * @author : Brian * @date : 2017/7/19 */ public class RTopCategoryBean { // "id": 分类id, // "bannerUrl": "分类图片路径", // "name": "分类名称" private double id; private String bannerUrl; private String name; @Override public String toString() { return "RTopCategoryBean{" + "id=" + id + ", bannerUrl='" + bannerUrl + '\'' + ", name='" + name + '\'' + '}'; } public double getId() { return id; } public void setId(double id) { this.id = id; } public String getBannerUrl() { return bannerUrl; } public void setBannerUrl(String bannerUrl) { this.bannerUrl = bannerUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.ssrs.platform.extend.item; import com.ssrs.platform.MenuManager; import com.ssrs.platform.extend.ILogType; import com.ssrs.platform.model.Menu; import java.util.HashMap; import java.util.Map; /** * 用户菜单操作日志 * * @author ssrs */ public class UserMenuLog implements ILogType { public static final String ID = "UserMenuLog"; private Map<String, String> map; @Override public String getExtendItemID() { return ID; } @Override public String getExtendItemName() { return "用户菜单操作日志"; } @Override public Map<String, String> getSubTypes() { if (map == null) { map = new HashMap<>(); Map<String, Menu> menus = MenuManager.getMenus(); if (menus != null && menus.size() > 0) { for (Menu menu : menus.values()) { map.put("Visit " + menu.getId(), menu.getName()); } } } return map; } @Override public String decodeMessage(String msg) { return msg; } }
package June2021AppleLeetcode; import java.util.List; public class _0093RestoreIPAddress { public static void main(String[] args) { System.out.println(restoreIpAddresses("25525511135")); System.out.println(restoreIpAddresses("0000")); System.out.println(restoreIpAddresses("1111")); System.out.println(restoreIpAddresses("010010")); System.out.println(restoreIpAddresses("101023")); } public static List<String> restoreIpAddresses(String s) { } }
package org.apereo.cas.mgmt; import lombok.Data; import java.io.Serializable; /** * Component to represent a commit message. * * @author Misagh Moayyed * @since 6.3 */ @Data public class CommitMessage implements Serializable { private String message; private String title; }
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.wire; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import java.util.Map; /** * Alluxio job worker information. */ public final class AlluxioJobWorkerInfo { private Map<String, String> mConfiguration; private long mStartTimeMs; private long mUptimeMs; private String mVersion; /** * Creates a new instance of {@link AlluxioJobWorkerInfo}. */ public AlluxioJobWorkerInfo() {} /** * @return the configuration */ public Map<String, String> getConfiguration() { return mConfiguration; } /** * @return the start time (in milliseconds) */ public long getStartTimeMs() { return mStartTimeMs; } /** * @return the uptime (in milliseconds) */ public long getUptimeMs() { return mUptimeMs; } /** * @return the version */ public String getVersion() { return mVersion; } /** * @param configuration the configuration to use * @return the Alluxio job worker information */ public AlluxioJobWorkerInfo setConfiguration(Map<String, String> configuration) { mConfiguration = configuration; return this; } /** * @param startTimeMs the start time to use (in milliseconds) * @return the Alluxio job worker information */ public AlluxioJobWorkerInfo setStartTimeMs(long startTimeMs) { mStartTimeMs = startTimeMs; return this; } /** * @param uptimeMs the uptime to use (in milliseconds) * @return the Alluxio job worker information */ public AlluxioJobWorkerInfo setUptimeMs(long uptimeMs) { mUptimeMs = uptimeMs; return this; } /** * @param version the version to use * @return the Alluxio job worker information */ public AlluxioJobWorkerInfo setVersion(String version) { mVersion = version; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AlluxioJobWorkerInfo)) { return false; } AlluxioJobWorkerInfo that = (AlluxioJobWorkerInfo) o; return Objects.equal(mConfiguration, that.mConfiguration) && mStartTimeMs == that.mStartTimeMs && mUptimeMs == that.mUptimeMs && Objects.equal(mVersion, that.mVersion); } @Override public int hashCode() { return Objects.hashCode(mConfiguration, mStartTimeMs, mUptimeMs, mVersion); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("configuration", mConfiguration) .add("start time", mStartTimeMs) .add("uptime", mUptimeMs) .add("version", mVersion) .toString(); } }