language
stringclasses
5 values
text
stringlengths
15
988k
Java
public class QuestionTimer { private static final Integer START_TIME = 30; private Timeline _timeline; private IntegerProperty _time = new SimpleIntegerProperty(START_TIME); private Label _timerLabel; private Button _submitButton; private SpeakProcess _speak; /** * Create Question Timer helper * * @param timerLabel * @param submit * @param speak */ public QuestionTimer(final Label timerLabel, final Button submit, final SpeakProcess speak) { _timerLabel = timerLabel; _submitButton = submit; _speak = speak; } /** * Used to bind updates in the time value to the label displayed to the user. */ public final void setBinding() { _timerLabel.textProperty().bind(_time.asString()); } /** * Used to start a countdown for a specified amount of time. */ public void startCountdown() { if (_timeline != null) { _timeline.stop(); } _time.set(START_TIME); _timeline = new Timeline(); _timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(START_TIME + 1), new KeyValue(_time, 0))); while (!_speak.isDone()) { // Blocking. Wait till speak process is finished. } _timeline.playFromStart(); _timeline.setOnFinished(event -> _submitButton.fireEvent(new ActionEvent())); } /** * Used to stop the current running countdown. */ public void stopCountdown() { _timeline.stop(); } }
Java
@EnableCaching @EnableFeignClients @SpringBootApplication public class OutfitrApplication { public static void main(String[] args) { SpringApplication.run(OutfitrApplication.class, args); } }
Java
public final class TreeHashUtil { /** * Calculate the hash tree root of the provided value * * @param value */ public static Bytes32 hash_tree_root(Bytes value) { return SSZ.hashTreeRoot(value); } /** */ public static Bytes32 hash_tree_root(Exit exit) { // todo: check that this is right return SSZ.hashTreeRoot(exit.toBytes()); } /** * Calculate the hash tree root of the BeaconState provided * * @param attestationDataAndCustodyBit * @return */ public static Bytes32 hash_tree_root(AttestationDataAndCustodyBit attestationDataAndCustodyBit) { // todo: check that this is right return SSZ.hashTreeRoot(attestationDataAndCustodyBit.toBytes()); } /** * Calculate the hash tree root of the list of validators provided * * @param validators */ public static Bytes32 validatorListHashTreeRoot(List<Validator> validators) { return hash_tree_root( SSZ.encode( writer -> { writer.writeBytesList( validators.stream().map(item -> item.toBytes()).collect(Collectors.toList())); })); } /** * Calculate the hash tree root of the list of integers provided. * * <p><b>WARNING: This assume 64-bit encoding is intended for the integers provided.</b> * * @param integers * @return */ public static Bytes32 integerListHashTreeRoot(List<Integer> integers) { return hash_tree_root( SSZ.encode( // TODO This can be replaced with writeUInt64List(List) once implemented in Cava. writer -> { writer.writeUIntList(64, integers); })); } /** * Calculate the hash tree root of the BeaconState provided * * @param state */ public static Bytes32 hash_tree_root(BeaconState state) { return hash_tree_root(state.toBytes()); } }
Java
public class Updater { private static final int THREAD_POOL_SIZE = Math.max(2, Runtime.getRuntime().availableProcessors()); private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(THREAD_POOL_SIZE); private static final Map<Updateable, UpdateTime> UPDATEABLES = new ConcurrentHashMap<>(); private static final Timer TIMER = new Timer(); private static final TimerTask TASK = new TimerTask() { @Override public void run() { try { updateAll(); } catch (Exception ex) { System.err.println(ex); } } }; static { System.out.println(String.format("Updater: created a FixedThreadPool with size = %d", THREAD_POOL_SIZE)); TIMER.scheduleAtFixedRate(TASK, 0, 100); } protected static final boolean updateAll() { final long timestamp = Standard.getCurrentTime(); final List<Updateable> toRemove = UPDATEABLES.keySet().stream().filter((updateable) -> { try { return UPDATEABLES.get(updateable).isRemove(); } catch (Exception ex) { return true; } }).collect(Collectors.toList()); toRemove.stream().forEach((updateable) -> { UPDATEABLES.remove(updateable); }); toRemove.clear(); UPDATEABLES.keySet().stream().filter((updateable) -> { if (!updateable.wantsUpdate(timestamp)) { return false; } try { final UpdateTime updateTime = UPDATEABLES.get(updateable); if (updateTime.isUpdating()) { return false; } return updateTime.needsUpdate(timestamp); } catch (Exception ex) { System.err.println(ex); return false; } }).forEach((updateable) -> { try { final UpdateTime updateTime = UPDATEABLES.get(updateable); updateTime.setIsUpdating(true); submit(() -> { try { final long deltaTime = updateable.update(timestamp); updateTime.update(timestamp, deltaTime); if (deltaTime < 0) { updateTime.setRemove(true); } } catch (Exception ex) { ex.printStackTrace(); } updateTime.setIsUpdating(false); }); } catch (Exception ex) { System.err.println(ex); } }); return true; } public static final boolean addUpdateable(Updateable updateable) { if (updateable == null) { return false; } if (!UPDATEABLES.containsKey(updateable)) { UPDATEABLES.put(updateable, new UpdateTime()); return true; } return false; } public static final boolean removeUpdateable(Updateable updateable) { if (updateable == null) { return true; } if (UPDATEABLES.containsKey(updateable)) { UPDATEABLES.remove(updateable); return true; } return false; } public static final Map<Updateable, UpdateTime> getUpdateablesWithTimestamps() { return UPDATEABLES; } public static final Set<Updateable> getUpdateables() { return UPDATEABLES.keySet(); } public static final boolean kill(long timeout, TimeUnit unit) { try { TIMER.cancel(); TIMER.purge(); submit(() -> { try { UPDATEABLES.keySet().stream().forEach((updateable) -> { updateable.delete(); }); } catch (Exception ex) { System.err.println(ex); } }); EXECUTOR.shutdown(); EXECUTOR.awaitTermination(timeout, unit); EXECUTOR.shutdownNow(); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } } public static final Future<?> submit(Runnable run) { if (run == null) { return null; } return EXECUTOR.submit(run); } }
Java
public class TemplateScannerTest { static final String text0 = "\n<!-- ignored -->{{Constraint:Type|class=Q1048835\n|relation=instance<!-- ignored -->}}" + "\n{{Constraint:Value <!-- ignored \n \n -->type|class=Q5|relation<!---->=instance}}<!-- nothing here -->" + "\n{<!--ignored --->{Constraint:Target required claim|property=P21}}" + "\n{{Constraint:One of|values=<!-- ignored-->{{Q|6581097}}, {{Q|6581072}}, {{Q|1097630}}, {{Q|44148}}, {{Q|43445}}, {{Q|1052281}}, {{Q|2449503}}, {{Q|48270}}, {{Q|1399232}}, {{Q|3277905}}, {{Q|746411}}, {{Q|350374}}, {{Q|660882}}}}" + "\n"; static final String text1 = "== Constraint item ==\n" + "<code><nowiki>{{</nowiki><nowiki>Constraint:Item|property=P107|item=Q386724|item2=Q215627|item3=Q43229}}</nowiki></code> (yes, organization is already there) "; static final String text2 = "== Constraint item ==\n" + "<code><nowiki>{{Constraint:Item|property=P107|item=Q386724|item2=Q215627|item3=Q43229}}</nowiki></code> (yes, organization is already there) "; static final String text3 = "== Constraint item ==\n" + "<code>&lt;nowiki>{{Constraint:Item|property=P107|item=Q386724|item2=Q215627|item3=Q43229}}</nowiki></code> (yes, organization is already there) "; @Test public void testScannerMultipleTemplates() { List<String> expected = new ArrayList<String>(); expected.add("{{Constraint:Type|class=Q1048835\n|relation=instance}}"); expected.add("{{Constraint:Value type|class=Q5|relation=instance}}"); expected.add("{{Constraint:Target required claim|property=P21}}"); expected.add("{{Constraint:One of|values={{Q|6581097}}, {{Q|6581072}}, {{Q|1097630}}, {{Q|44148}}, {{Q|43445}}, {{Q|1052281}}, {{Q|2449503}}, {{Q|48270}}, {{Q|1399232}}, {{Q|3277905}}, {{Q|746411}}, {{Q|350374}}, {{Q|660882}}}}"); TemplateScanner scanner = new TemplateScanner(); Assert.assertEquals(expected, scanner.getTemplates(text0)); } @Test public void testScannerWithNowiki() { List<String> expected = new ArrayList<String>(); TemplateScanner scanner = new TemplateScanner(); Assert.assertEquals(expected, scanner.getTemplates(text1)); Assert.assertEquals(expected, scanner.getTemplates(text2)); expected.add("{{Constraint:Item|property=P107|item=Q386724|item2=Q215627|item3=Q43229}}"); Assert.assertEquals(expected, scanner.getTemplates(text3)); } @Test public void testScannerMultipleTemplatesMultipleLines() { String str = "" + "{{Property documentation\n" + "|description=FIPS code for US states (numeric or alpha) per former FIPS 5-2 standard, see {{Q|917824}}. See also: <br>\n" + "**{{P|774}}\n" + "**{{P|882}}\n" + "**{{P|901}}\n" + "|infobox parameter=\n" + "|datatype=string\n" + "|domain=places: US states and certain other associated areas\n" + "|allowed values=\\d\\d or \\D\\D: see [[:en:Federal Information Processing Standard state code]]\n" + "|suggested values=\n" + "|source=[[en:Federal_Information_Processing_Standard_state_code]], http://www.census.gov/geo/reference/ansi_statetables.html\n" + "|example= {{Q|173}} => \"AL\" and \"01\"\n" + "|filter=\n" + "|robot and gadget jobs=\n" + "|proposed by=13\n" + "}}\n" + "\n" + "\n" + "{{Constraint:Format|pattern=<nowiki>\\d\\d|\\D\\D</nowiki>}}\n" + "{{Constraint:Unique value}}\n" + "{{Constraint:Item|property=P17|item=Q30|exceptions= {{Q|695}}, {{Q|702}}, {{Q|709}} }}\n" + "{{Constraint:Item|property=P132|exceptions= {{Q|695}}, {{Q|702}}, {{Q|709}}, {{Q|16645}} }}\n"; List<String> expected = new ArrayList<String>(); expected.add("{{Property documentation\n" + "|description=FIPS code for US states (numeric or alpha) per former FIPS 5-2 standard, see {{Q|917824}}. See also: <br>\n" + "**{{P|774}}\n" + "**{{P|882}}\n" + "**{{P|901}}\n" + "|infobox parameter=\n" + "|datatype=string\n" + "|domain=places: US states and certain other associated areas\n" + "|allowed values=\\d\\d or \\D\\D: see [[:en:Federal Information Processing Standard state code]]\n" + "|suggested values=\n" + "|source=[[en:Federal_Information_Processing_Standard_state_code]], http://www.census.gov/geo/reference/ansi_statetables.html\n" + "|example= {{Q|173}} => \"AL\" and \"01\"\n" + "|filter=\n" + "|robot and gadget jobs=\n" + "|proposed by=13\n" + "}}"); expected.add("{{Constraint:Format|pattern=<nowiki>\\d\\d|\\D\\D</nowiki>}}"); expected.add("{{Constraint:Unique value}}"); expected.add("{{Constraint:Item|property=P17|item=Q30|exceptions= {{Q|695}}, {{Q|702}}, {{Q|709}} }}"); expected.add("{{Constraint:Item|property=P132|exceptions= {{Q|695}}, {{Q|702}}, {{Q|709}}, {{Q|16645}} }}"); TemplateScanner scanner = new TemplateScanner(); Assert.assertEquals(expected, scanner.getTemplates(str)); } }
Java
public class Person { private String name; private String employeeId; public Person(String employeeId, String name) { this.employeeId = employeeId; this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; if (getName() != null ? !getName().equals(person.getName()) : person.getName() != null) return false; return getEmployeeId() != null ? getEmployeeId().equals(person.getEmployeeId()) : person.getEmployeeId() == null; } @Override public int hashCode() { int result = getName() != null ? getName().hashCode() : 0; result = 31 * result + (getEmployeeId() != null ? getEmployeeId().hashCode() : 0); return result; } }
Java
public class FindFirstAndLastPositionOfElementInSortedArray_33 { public int[] searchRange(int[] nums, int target) { if (nums.length == 0) { return new int[] {-1, -1}; } int ans = largestSmallerThanTarget(nums, target + 1); if (ans == -1 || nums[ans] != target) { return new int[] {-1, -1}; } return new int[] {largestSmallerThanTarget(nums, target) + 1, ans}; } private int largestSmallerThanTarget(int[] nums, int target) { int left = 0; int right = nums.length - 1; int ans = -1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] >= target) { right = mid - 1; } else { ans = mid; left = mid + 1; } } return ans; } }
Java
public class RmTreeShellCommand implements ShellCommand { /** * Name of the command. */ private static final String COMMAND_NAME = "rmtree"; /** * Description of the command. */ private static final List<String> COMMAND_DESCRIPTION = new ArrayList<>(); static { COMMAND_DESCRIPTION.add("Command expects a single argument: directory name."); COMMAND_DESCRIPTION.add("Removes every file/folder in that directory."); } @Override public ShellStatus executeCommand(Environment env, String arguments) { if (arguments.equals("")) { env.writeln("You must provide exactly one argument: the path of the directory to clear."); return ShellStatus.CONTINUE; } Path workingDirectory = env.getCurrentDirectory(); Path path = workingDirectory.resolve(Util.parseArgument(arguments)); if (!Files.isDirectory(path)) { env.writeln("Given path isn't a directory on your system."); return ShellStatus.CONTINUE; } try { Files.walkFileTree(path, new FileVisitor<Path>() { @Override public FileVisitResult postVisitDirectory(Path dir, IOException arg1) throws IOException { if (dir.equals(path)) { return FileVisitResult.CONTINUE; } Files.delete(dir); env.writeln("Deleted directory " + dir.toAbsolutePath().normalize().toString()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes arg1) throws IOException { if (dir.equals(path)) { return FileVisitResult.CONTINUE; } env.writeln("Entering directory " + dir.toAbsolutePath().normalize().toString()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes arg1) throws IOException { Files.delete(file); env.writeln("Deleted file " + file.toAbsolutePath().normalize().toString()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException arg1) throws IOException { env.writeln("Failed to delete file: " + file.toAbsolutePath().normalize().toString()); return FileVisitResult.CONTINUE; } }); } catch (IOException e1) { env.writeln("Error while traversing the directory."); } return ShellStatus.CONTINUE; } @Override public String getCommandName() { return COMMAND_NAME; } @Override public List<String> getCommandDescription() { return COMMAND_DESCRIPTION; } }
Java
public abstract class AbstractAnalyticVolatilityCubeProduct implements AnalyticVolatilityCubeProduct { @Override public double getValue(final double evaluationTime, final AnalyticModel model) { throw new IllegalArgumentException("The product " + this.getClass() + " cannot be valued against a model " + model.getClass() + "." + "It requires a model of type " + VolatilityCubeModel.class + "."); } @Override public Object getValue(final double evaluationTime, final Model model) { throw new IllegalArgumentException("The product " + this.getClass() + " cannot be valued against a model " + model.getClass() + "." + "It requires a model of type " + VolatilityCubeModel.class + "."); } /** * Return the valuation of the product at time 0 using the given model. * The model has to implement the modes of {@link VolatilityCubeModel}. * * @param model The model under which the product is valued. * @return The value of the product using the given model. */ public double getValue(final VolatilityCubeModel model) { return getValue(0.0, model); } }
Java
class TimestampAvroSchemaFieldAssembler implements IAvroSchemaFieldAssembler { public void assembleAvroSchemaField(FieldAssembler<Schema> fieldAssembler, ICacheFieldMeta fieldMeta) { Schema timestampMilliType = LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG)); fieldAssembler.name(fieldMeta.getName()) .doc(TypesResolver.getTypeTimestamp()) .type(SchemaBuilder.unionOf().type(timestampMilliType).and().nullType().endUnion()).noDefault(); } }
Java
public class StringContentProvider extends BytesContentProvider { public StringContentProvider(String content) { this(content, StandardCharsets.UTF_8); } public StringContentProvider(String content, String encoding) { this(content, Charset.forName(encoding)); } public StringContentProvider(String content, Charset charset) { this("text/plain;charset=" + charset.name(), content, charset); } public StringContentProvider(String contentType, String content, Charset charset) { super(contentType, content.getBytes(charset)); } }
Java
@AutoService(Module.class) public class RunlevelModule extends Module { static final String prefix = "fallout.module.runlevel."; static final PropertySpec<Ensemble.Role> roleSpec = PropertySpecBuilder.create(prefix) .name("role") .description("The role to transition to the new runlevel") .optionsArray(Ensemble.Role.values()) .required() .build(); static final PropertySpec<String> nodeGroupSpec = PropertySpecBuilder.nodeGroup(prefix); static final PropertySpec<NodeGroup.State> runlevelSpec = PropertySpecBuilder.create(prefix) .name("runlevel") .description("The target runlevel") .options(NodeGroup.State.DESTROYED, NodeGroup.State.STOPPED, NodeGroup.State.STARTED_SERVICES_UNCONFIGURED, NodeGroup.State.STARTED_SERVICES_CONFIGURED, NodeGroup.State.STARTED_SERVICES_RUNNING) .build(); @Override public String prefix() { return prefix; } @Override public String name() { return "runlevel"; } @Override public String description() { return "A module that transitions a role to a runlevel"; } @Override public List<PropertySpec> getModulePropertySpecs() { return ImmutableList.<PropertySpec>builder() .add(runlevelSpec, roleSpec, nodeGroupSpec) .build(); } @Override public Set<Class<? extends Provider>> getRequiredProviders() { return ImmutableSet.of(); } @Override public List<Product> getSupportedProducts() { return Product.everything(); } @Override public void run(Ensemble ensemble, PropertyGroup properties) { emit(Operation.Type.invoke); NodeGroup targetGroup = ensemble.getGroup(roleSpec.value(properties), nodeGroupSpec.value(properties)); NodeGroup.State stateToTransitionTo = runlevelSpec.value(properties); boolean transitioned = false; if (targetGroup.getState().ordinal() > NodeGroup.State.STARTED_SERVICES_UNCONFIGURED.ordinal() && stateToTransitionTo.ordinal() <= NodeGroup.State.STARTED_SERVICES_UNCONFIGURED.ordinal()) { logger.error("Trying to transition down from {} to {}. This operation will destroy test artifacts" + "and will not be allowed.", targetGroup.getState(), stateToTransitionTo); } else { try { transitioned = targetGroup.transitionState(stateToTransitionTo).join().wasSuccessful(); } catch (Exception e) { logger.error("Failed to transition with error {}", e); } } if (transitioned) { emit(Operation.Type.ok, targetGroup.getState()); } else { emit(Operation.Type.fail); } } }
Java
public class _03_DiferenciaMinutos { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); // En las siguientes variables se guardaran // las dos horas introducidas por el usuario String primeraHora, segundaHora; // En la siguiente variable se indicara si las horas // introducidas son correctas boolean horasValidas = true; /** * Le pedimos al usuario que nos introduzca las dos horas. */ do { System.out.print("Introduce la primera hora: "); primeraHora = scan.nextLine(); System.out.print("Introduce la segunda hora: "); segundaHora = scan.nextLine(); horasValidas = true; /** * Comprobamos si las horas son validas. * Si no los son imprimimos un mensaje de error y le asignamos a la variable * horasValidas el valor FALSE para que el bucle se vuelva a repetir */ if(!validarHora(primeraHora) || !validarHora(segundaHora)) { System.out.println("El formato de la hora no es correcto."); horasValidas = false; } } while (!horasValidas); /** * Separamos las horas de los minutos. */ String[] primeraHoraSplit = primeraHora.split(":"); String[] segundaHoraSplit = segundaHora.split(":"); // Calculamos la diferencia int diferencia = minutosDiferencia(primeraHoraSplit, segundaHoraSplit); // Imprimimos el resultado String unidad = (diferencia == 1) ? "min" : "mins"; System.out.println("Diferencia en minutos entre las dos horas: " + diferencia + " " + unidad); } /** * Calcula la diferencia en minutos entre dos horas dadas. * * @param primeraHora La primera hora * @param segundaHora La segunda hora * @return La diferencia entre las dos horas */ public static int minutosDiferencia(String[] primeraHora, String[] segundaHora) { // Calculamos el total minutos de la primera hora int totalMinutosPrimeraHora = (Integer.parseInt(primeraHora[0]) * 60) + Integer.parseInt(primeraHora[1]); // Calculamos el total minutos de la segunda hora int totalMinutosSegundaHora = (Integer.parseInt(segundaHora[0]) * 60) + Integer.parseInt(segundaHora[1]); // Calculamos la diferencia int diferencia = Math.abs(totalMinutosPrimeraHora - totalMinutosSegundaHora); // Devolvemos la diferencia entre ambas horas return diferencia; } /** * Comprueba si la hora indicada tiene un fomato correcto. * * @param hora La hora a comprobar * @return True si el formato de la hora es correcto y false en caso contrario */ public static boolean validarHora(String hora) { // Una hora valida no puede contener mas // de 5 caracteres if(5 != hora.length()) { return false; } // Separamos las horas de los minutos String[] horasSplit = hora.split(":"); // Si horasSplit contiene mas de dos elementos el formato // no sera correcto if(horasSplit.length != 2) { return false; } int horasTotal = Integer.parseInt(horasSplit[0]); int minutosTotal = Integer.parseInt(horasSplit[1]); // Comprobamos si las horas son validas // Es decir no pueden ser menor que 00 y mayor que 23 if(horasTotal < 0 || horasTotal > 23) { return false; } // Comprobamos si los minutos son validos // Es decir no pueden ser menor que 00 y mayor que 59 if(minutosTotal < 0 || minutosTotal > 59) { return false; } // Si todas las validaciones son correctas devolvemos true return true; } }
Java
public class ExactNumberFormat extends NumberFormat { private final NumberFormat delegate; public ExactNumberFormat(NumberFormat delegate) { this.delegate = delegate; } @Override public Number parse(String source, ParsePosition parsePosition) { return delegate.parse(source, parsePosition); } @Override public StringBuffer format(Object number, StringBuffer result, FieldPosition fieldPosition) { // NumberFormat sometimes applies type narrowing / widening; // especially, for decimal values, it widens float -> double and // narrows BigDecimal -> double, then formats the resulting double. // This poses a problem for floats. The float -> double widening // may alter the original value; however, if we first convert float -> BigDecimal, // then let NumberFormat do the BigDecimal -> double narrowing, the result // *seems* exact for all floats. // To be on the safe side, let's convert all floating-point numbers to BigDecimals // before formatting. if (number instanceof Float || number instanceof Double) { try { number = CodecUtils.toBigDecimal((Number) number); } catch (ArithmeticException ignored) { // happens in rare cases, e.g. with Double.NaN } } return delegate.format(number, result, fieldPosition); } @Override public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) { return delegate.format(number, result, fieldPosition); } @Override public StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition) { return delegate.format(number, result, fieldPosition); } }
Java
public class PlatformMonitoringEventHandler extends MonitoringEventHandler<PlatformMonitoringEvent> { public static final PlatformMonitoringEventHandler INSTANCE = new PlatformMonitoringEventHandler(); /** * Creates an instance. */ private PlatformMonitoringEventHandler() { super(PlatformMonitoringEvent.class); } @Override protected void handle(PlatformMonitoringEvent event, SystemState state) { state.getPlatform().setValue(event.getObservable(), event.getObservation(), event.getKey()); } }
Java
public class CacheableJrxXmlModelUtil extends JrxXmlModelUtil { public static final String XSD_CACHE_NAME = "xsdCache"; public static final String XSD_URL_CACHE_NAME = "xsdUrlCache"; private static LoadingCache<String, XSSchema> schemaCache = null; private static LoadingCache<String, String[]> schemaUrlCache = null; public static CacheableJrxXmlModelUtil newInstance() { return new CacheableJrxXmlModelUtil(); } protected CacheableJrxXmlModelUtil() { super(); } @Override public String[] addSchema(URL xmlSchemaUrl) throws SAXException { String[] namespaceUriArray = getSchemaUrlCache().getIfPresent(xmlSchemaUrl.toString()); if (namespaceUriArray == null) { namespaceUriArray = super.addSchema(xmlSchemaUrl); getSchemaUrlCache().put(xmlSchemaUrl.toString(), namespaceUriArray); for (String namespaceUri : namespaceUriArray) { XSSchema xsSchema = super.getSchema(namespaceUri); getSchemaCache().put(namespaceUri, xsSchema); } } return namespaceUriArray; } @Override public String addSchema(XSSchema xsSchema) { String namespaceUri = xsSchema.getTargetNamespace(); if (!getSchemaCache().asMap().containsKey(namespaceUri)) { getSchemaCache().put(namespaceUri, xsSchema); } return super.addSchema(xsSchema); } @Override public XSSchema getSchema(String namespaceUri) { XSSchema xsSchema = super.getSchema(namespaceUri); if (xsSchema != null) return xsSchema; xsSchema = getSchemaCache().getIfPresent(namespaceUri); if (xsSchema != null) { super.addSchema(xsSchema); } return xsSchema; } @Override protected boolean hasSchemas() { return getSchemaCache().size() > 0; } @Override protected boolean hasSchema(String namespaceUri) { return getSchemaCache().asMap().containsKey(namespaceUri); } protected static LoadingCache<String, XSSchema> getSchemaCache() { if (schemaCache != null) { return schemaCache; } synchronized (schemaCache) { schemaCache = CacheUtil.createCache(200, 300, TimeUnit.SECONDS); } return schemaCache; } protected static LoadingCache<String, String[]> getSchemaUrlCache() { if (schemaUrlCache != null) { return schemaUrlCache; } synchronized (schemaUrlCache) { schemaUrlCache = CacheUtil.createCache(200, 300, TimeUnit.SECONDS); } return schemaUrlCache; } }
Java
public class JiveTable extends JTable { private static final long serialVersionUID = -7140811933957438525L; private JiveTable.JiveTableModel tableModel; public JiveTable(String[] headers, Integer[] columnsToUseRenderer) { tableModel = new JiveTable.JiveTableModel(headers, 0, false); this.setModel(tableModel); getTableHeader().setReorderingAllowed(false); setGridColor(java.awt.Color.white); setRowHeight(20); getColumnModel().setColumnMargin(0); setSelectionBackground(new java.awt.Color(57, 109, 206)); setSelectionForeground(java.awt.Color.white); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setRowSelectionAllowed(false); } public TableCellRenderer getCellRenderer(int row, int column) { if (column == 3 || column == 4) { return new JiveTable.JButtonRenderer(false); } else if (column == 1) { return new JiveTable.JLabelRenderer(false); } else { return super.getCellRenderer(row, column); } } public void add(List<Object> list) { for (Object aList : list) { Object[] newRow = (Object[]) aList; tableModel.addRow(newRow); } } public Object[] getSelectedObject() { int selectedRow = getSelectedRow(); if (selectedRow < 0) { return null; } int columnCount = getColumnCount(); Object[] obj = new Object[columnCount]; for (int j = 0; j < columnCount; j++) { Object objs = tableModel.getValueAt(selectedRow, j); obj[j] = objs; } return obj; } public class JiveTableModel extends DefaultTableModel { private static final long serialVersionUID = -2072664365332767844L; private boolean _isEditable; /** * Use the JiveTableModel in order to better handle the table. This allows * for consistency throughout the product. * * @param columnNames - String array of columnNames * @param numRows - initial number of rows * @param isEditable - true if the cells are editable, false otherwise. */ public JiveTableModel(Object[] columnNames, int numRows, boolean isEditable) { super(columnNames, numRows); _isEditable = isEditable; } /** * Returns true if cell is editable. */ public boolean isCellEditable(int row, int column) { return _isEditable; } } class JLabelRenderer extends JLabel implements TableCellRenderer { private static final long serialVersionUID = 4387574944818048720L; Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; public JLabelRenderer(boolean isBordered) { super(); } public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { final String text = ((JLabel)color).getText(); setText(text); final Icon icon = ((JLabel)color).getIcon(); setIcon(icon); if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); } else { setForeground(Color.black); setBackground(Color.white); if (row % 2 == 0) { //setBackground( new Color( 156, 207, 255 ) ); } } if (isBordered) { if (isSelected) { if (selectedBorder == null) { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getSelectionBackground()); } setBorder(selectedBorder); } else { if (unselectedBorder == null) { unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getBackground()); } setBorder(unselectedBorder); } } return this; } } class JButtonRenderer extends JButton implements TableCellRenderer { private static final long serialVersionUID = -5287214156125954342L; Border unselectedBorder = null; Border selectedBorder = null; boolean isBordered = true; public JButtonRenderer(boolean isBordered) { super(); //this.isBordered = isBordered; //setOpaque(true); //MUST do this for background to show up. } public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) { final String text = ((JButton)color).getText(); setText(text); final Icon icon = ((JButton)color).getIcon(); setIcon(icon); if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); } else { setForeground(Color.black); setBackground(Color.white); if (row % 2 == 0) { //setBackground( new Color( 156, 207, 255 ) ); } } if (isBordered) { if (isSelected) { if (selectedBorder == null) { selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getSelectionBackground()); } setBorder(selectedBorder); } else { if (unselectedBorder == null) { unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5, table.getBackground()); } setBorder(unselectedBorder); } } return this; } } public JiveTable.JiveTableModel getTableModel() { return tableModel; } }
Java
public class IOLoadProbe extends Thread{ Sigar sigarImpl; SigarProxy sigar; int measurePeriod; long averageNumberOfReads; long averageNumberOfWrites; String fsRoot; ReadCalculator readCalculator; WriteCalculator writeCalculator; /** * Shared synchronized queue to store results of the measurements */ protected static MeasurementQueue queue; public IOLoadProbe(String fsRoot,int measurePeriod){ this.sigarImpl = new Sigar(); this.sigar=SigarProxyCache.newInstance(sigarImpl); this.fsRoot = fsRoot; this.measurePeriod = measurePeriod; queue = new MeasurementQueue(fsRoot); } @Override public void run() { // start two threads that measure number of read/write requests this.readCalculator = new ReadCalculator(measurePeriod); this.writeCalculator = new WriteCalculator(measurePeriod); readCalculator.start(); writeCalculator.start(); // calculate I/O load until someone interrupts us while(true) { try { //averageNumberOfReads = readCalculator.getAverageNumberOfReads(); averageNumberOfReads = queue.getReadMeasurement(); System.out.println("Average number of reads per "+ this.measurePeriod+ " ms: "+ averageNumberOfReads); //averageNumberOfWrites = writeCalculator.getAverageNumberOfWrites(); averageNumberOfWrites = queue.getWriteMeasurement(); System.out.println("Average number of writes per "+ this.measurePeriod+ " ms: "+ averageNumberOfWrites); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Java
class MeasurementQueue{ String fsRoot; // maximal number of read/write measurements that can be stored in the queue int maxMeasurements = 1; int readMeasurements = 0; int writeMeasurements = 0; long averageReads = 0; long averageWrites = 0; public MeasurementQueue(String fsRoot){ this.fsRoot = fsRoot; } public synchronized void setReadMeasurement(long numberOfReads) throws InterruptedException{ while(readMeasurements >= maxMeasurements){ wait(); } // save average reads here this.averageReads = numberOfReads; readMeasurements++; notifyAll(); } public synchronized long getReadMeasurement() throws InterruptedException{ while(readMeasurements == 0){ wait(); } // read the value readMeasurements--; long safeValue = averageReads; notifyAll(); return safeValue; } public synchronized void setWriteMeasurement(long numberOfWrites) throws InterruptedException{ while(writeMeasurements >=maxMeasurements){ wait(); } // save average writes here this.averageWrites = numberOfWrites; writeMeasurements++; notifyAll(); } public synchronized long getWriteMeasurement() throws InterruptedException{ while(writeMeasurements == 0){ wait(); } // get average reads here writeMeasurements--; // save the value here to avoid dirty read long safeValue = averageWrites; notifyAll(); return safeValue; } public String getFsRoot(){ return this.fsRoot; } }
Java
class ReadCalculator extends Thread{ Sigar sigarImpl; SigarProxy sigar; long averageNumberOfReads = 0; long averageNumberOfWrites = 0; int measurePeriod = 5000; String fsRoot; public ReadCalculator(int measurePeriod){ this.sigarImpl = new Sigar(); this.sigar=SigarProxyCache.newInstance(sigarImpl); this.fsRoot = IOLoadProbe.queue.getFsRoot(); this.measurePeriod = measurePeriod; this.setName("Read/Write counter"); } public void run(){ while(true){ try { //averageNumberOfReads = this.calculateAverageNumberOfReads(measurePeriod, fsRoot); IOLoadProbe.queue.setReadMeasurement(this.calculateAverageNumberOfReads(measurePeriod, fsRoot)); } catch (SigarException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private long calculateAverageNumberOfReads(int measurePeriod, String fsRoot) throws SigarException, InterruptedException { long totalNumberOfRequests = 0; int smallCyclePeriod = 1000; ArrayList<Long> measurements = new ArrayList<Long>(); for(int i=0;i<measurePeriod; i+=smallCyclePeriod){ long intermediateResult = this.getReadRequestsPerSecond(fsRoot); measurements.add(intermediateResult); totalNumberOfRequests+=intermediateResult; } return totalNumberOfRequests/measurements.size(); } /** * Measure number of read requests per one second * @param fsRoot * @return * @throws SigarException * @throws InterruptedException */ private long getReadRequestsPerSecond(String fsRoot) throws SigarException, InterruptedException { int milis = 1000; long numberOfReads = 0; long readRequestsPerSecond = 0; this.sigar = SigarProxyCache.newInstance(sigarImpl); FileSystemUsage fsUsage = sigar.getFileSystemUsage(fsRoot); long initNumberOfReads = fsUsage.getDiskReads(); Thread.sleep(milis); this.sigar = SigarProxyCache.newInstance(sigarImpl); fsUsage = sigar.getFileSystemUsage(fsRoot); numberOfReads = fsUsage.getDiskReads(); readRequestsPerSecond = numberOfReads - initNumberOfReads; if(readRequestsPerSecond < 0){ System.out.println("Value can not be negative!"); readRequestsPerSecond = 0; } return readRequestsPerSecond; } // public double getAverageReadSpeed(String fsRoot) throws SigarException, InterruptedException // { // int measureInterval = 500; // int counter = 0; // ArrayList<Long> bytesOnEachInterval = new ArrayList<Long>(); // FileSystemUsage fsUsage = null; // long initReadBytes = 0; // long readBytes = 0; // long speedChange = 0; // // fsUsage = sigar.getFileSystemUsage(fsRoot); // initReadBytes = fsUsage.getDiskReadBytes(); // // save the number of read bytes over each measure interval // for (int i = counter;i<=measurePeriod; i+=measureInterval){ // Thread.sleep(measureInterval); // System.out.println("Measuring cycle..."); // this.sigar = SigarProxyCache.newInstance(sigarImpl); // fsUsage = sigar.getFileSystemUsage(fsRoot); // readBytes = fsUsage.getDiskReadBytes(); // if(readBytes > initReadBytes){ // speedChange = readBytes - initReadBytes; // bytesOnEachInterval.add(speedChange); // initReadBytes = readBytes; // System.out.println("Speed change in the interval: " + speedChange); // } // counter+=measureInterval; // } // return this.getAverageSpeed(bytesOnEachInterval, measureInterval); // } }
Java
class WriteCalculator extends Thread{ Sigar sigarImpl; SigarProxy sigar; long averageNumberOfReads = 0; long averageNumberOfWrites = 0; int measurePeriod = 5000; String fsRoot; public WriteCalculator(int measurePeriod){ this.sigarImpl = new Sigar(); this.sigar=SigarProxyCache.newInstance(sigarImpl); this.fsRoot = IOLoadProbe.queue.getFsRoot(); this.measurePeriod = measurePeriod; this.setName("Write counter"); } public void run(){ while(true){ try { //averageNumberOfWrites = this.calculateAverageNumberOfWrites(measurePeriod, fsRoot); IOLoadProbe.queue.setWriteMeasurement(this.calculateAverageNumberOfWrites(measurePeriod, fsRoot)); } catch (SigarException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private long calculateAverageNumberOfWrites(int measurePeriod, String fsRoot) throws SigarException, InterruptedException { long totalNumberOfRequests = 0; int smallCyclePeriod = 1000; ArrayList<Long> measurements = new ArrayList<Long>(); for(int i=0;i<measurePeriod; i+=smallCyclePeriod){ long intermediateResult = this.getWriteRequestsPerSecond(fsRoot); measurements.add(intermediateResult); totalNumberOfRequests+=intermediateResult; } return totalNumberOfRequests/measurements.size(); } /** * Measure number of write requests per one second * @param fsRoot * @return * @throws SigarException * @throws InterruptedException */ public long getWriteRequestsPerSecond(String fsRoot) throws SigarException, InterruptedException { int milis = 1000; long numberOfWrites = 0; long writeRequestsPerSecond = 0; this.sigar = SigarProxyCache.newInstance(sigarImpl); FileSystemUsage fsUsage = sigar.getFileSystemUsage(fsRoot); long initNumberOfWrites = fsUsage.getDiskWrites(); Thread.sleep(milis); this.sigar = SigarProxyCache.newInstance(sigarImpl); fsUsage = this.sigar.getFileSystemUsage(fsRoot); numberOfWrites = fsUsage.getDiskWrites(); writeRequestsPerSecond = numberOfWrites - initNumberOfWrites; if(writeRequestsPerSecond < 0){ System.out.println("Value can not be negative!"); writeRequestsPerSecond = 0; } return writeRequestsPerSecond; } }
Java
public class Setting { private String name; private float value; /** * Constructor, must pass both a name and its setting * * @param name - the name of the setting in the file * @param setting - the value of the setting */ public Setting(String name, float value) { this.name = name; this.value = value; } /** * Returns the name of the setting * * @return String name */ public String getName() { return name; } /** * Returns the value of the setting * * @return String value */ public float getValue() { return value; } /** * Returns a string representation of the setting in the form name=value * * @return String setting */ public String toString() { return name + ": " + value; } /** * Returns the setting object defined in an input string * * @param input - the input string in the same format as Setting.toString() * @return Setting - the setting representation of the string */ public static Setting convertToSetting(String input) { String[] splitInput = input.split("(:)|(//)"); if (splitInput.length < 2) return new Setting("", 0); String name = splitInput[0].trim(); float value = Float.parseFloat(splitInput[1].trim()); return new Setting(name, value); } }
Java
public class Engineer extends Profession { /** * Constructor. * @param name Name. */ public Engineer(String name) { super(name); } /** * To build for house. * @param house House. */ public void buildHouse(House house) { } }
Java
public class DefaultGUIDCookieStrategy implements GUIDCookieStrategy { private static final Logger LOG = Logger.getLogger(DefaultGUIDCookieStrategy.class); private final SecureRandom random; private final MessageDigest sha; private CookieGenerator cookieGenerator; public DefaultGUIDCookieStrategy() throws NoSuchAlgorithmException { random = SecureRandom.getInstance("SHA1PRNG"); sha = MessageDigest.getInstance("SHA-1"); Assert.notNull(random); Assert.notNull(sha); } @Override public void setCookie(final HttpServletRequest request, final HttpServletResponse response) { if (!request.isSecure()) { // We must not generate the cookie for insecure requests, otherwise there is not point doing this at all throw new IllegalStateException("Cannot set GUIDCookie on an insecure request!"); } final String guid = createGUID(); getCookieGenerator().addCookie(response, guid); request.getSession().setAttribute(RequireHardLoginBeforeControllerHandler.SECURE_GUID_SESSION_KEY, guid); if (LOG.isInfoEnabled()) { LOG.info("Setting guid cookie and session attribute: " + guid); } } @Override public void deleteCookie(final HttpServletRequest request, final HttpServletResponse response) { if (!request.isSecure()) { LOG.error("Cannot remove secure GUIDCookie during an insecure request. I should have been called from a secure page."); } else { // Its a secure page, we can delete the cookie getCookieGenerator().removeCookie(response); } } protected String createGUID() { final String randomNum = String.valueOf(getRandom().nextInt()); final byte[] result = getSha().digest(randomNum.getBytes()); return String.valueOf(Hex.encodeHex(result)); } protected CookieGenerator getCookieGenerator() { return cookieGenerator; } /** * @param cookieGenerator * the cookieGenerator to set */ @Required public void setCookieGenerator(final CookieGenerator cookieGenerator) { this.cookieGenerator = cookieGenerator; } protected SecureRandom getRandom() { return random; } protected MessageDigest getSha() { return sha; } }
Java
public class MovieProCommentBean { /** * data : [{"approve":23,"approved":false,"authInfo":"极客电影联合发起人,时光网前主编","avatarurl":"https://img.meituan.net/avatar/ba75f3b26f20cfb0fa933684fc963a19145729.jpg","cityName":"北京","content":"四星之作!期待限制级完整版再添一星。《蝙蝠侠:黑暗骑士》之后,超级英雄电影鲜有如此的悲壮与震撼!休叔封爪,狼叔绝唱,一代X战警落幕,令人唏嘘。末尾小狼女将十字架改作X标志,便是泪闸决堤之时。","created":1488849151000,"filmView":false,"gender":1,"id":99108226,"isMajor":false,"juryLevel":2,"movieId":247875,"nick":"子虚Brad","nickName":"子虚Brad","oppose":0,"pro":true,"reply":0,"score":4,"spoiler":0,"startTime":"2017-03-07 09:12:31","supportComment":false,"supportLike":true,"sureViewed":1,"tagList":{},"time":"2017-03-07 09:12","userId":228944158,"userLevel":5,"vipInfo":"猫眼星级专业评委","vipType":3},{"approve":14,"approved":false,"authInfo":"《齐鲁晚报》资深电影记者、影评人","avatarurl":"https://img.meituan.net/avatar/01e9ecdf77b88dd1f205a0be2d8464d078480.jpg","cityName":"济南","content":"一部中年危机电影,亲情片,有着西部片、公路片的包装形式。现在的动作血腥场景,刚刚好,作为一个相对传统的观众,对删减十多分钟持正面评价。本来是部7分片,给8分的原因,是实在看不上那些一味追求所谓科幻的片,这部片西部电影、公路电影的外壳,虽然老套,却是我喜欢的。","created":1488808016000,"filmView":false,"id":99090659,"isMajor":false,"juryLevel":1,"movieId":247875,"nick":"倪自放","nickName":"倪自放","oppose":0,"pro":true,"reply":0,"score":4,"spoiler":0,"startTime":"2017-03-06 21:49:03","supportComment":false,"supportLike":true,"sureViewed":1,"tagList":{"fixed":[{"id":1,"name":"好评"},{"id":4,"name":"购票"}]},"time":"2017-03-06 21:49","userId":307620960,"userLevel":4,"vipInfo":"猫眼专业评委","vipType":3},{"approve":41,"approved":false,"authInfo":"电影学博士,《电影艺术》编辑","avatarurl":"https://img.meituan.net/avatar/bdaf2279ab008c7564ae9c21c06b355e58882.jpg","cityName":"北京","content":"英雄垂垂老矣、童话落幕散场,看得我心都碎了,从头哭到尾。还好有强悍凶猛的小萝莉,多少带来一点抚慰。 超级英雄系列电影取代古典类型电影,已经是视听效果为导向的好莱坞的一个必然趋势。然而,《金刚狼3》提供了一条全新的路径,使得原本只注重感官享受的超级英雄电影,有可能获得一种原本属于古典类型电影的社会功能属性。与《原野奇侠》的互文关系,让这部另类的超级英雄电影成为类型融合与衍变的新场域\u2014\u2014西部电影和公路电影的主题、场景、对抗模式等都全面被纳入。这些尝试,使《金刚狼3》成为X战警系列最有深度和最具情感力量的一部,虽然观赏性可能稍弱(也可能是删节的缘故)。","created":1488798870000,"filmView":false,"id":99077709,"isMajor":false,"juryLevel":1,"movieId":247875,"nick":"lanxinshui","nickName":"刘起","oppose":0,"pro":true,"reply":0,"score":4.5,"spoiler":0,"startTime":"2017-03-06 19:14:30","supportComment":false,"supportLike":true,"sureViewed":1,"tagList":{"fixed":[{"id":1,"name":"好评"},{"id":4,"name":"购票"}]},"time":"2017-03-06 19:14","userId":328285948,"userLevel":2,"vipInfo":"猫眼专业评委","vipType":3},{"approve":10,"approved":false,"authInfo":"腾讯娱乐电影频道主编","avatarurl":"https://img.meituan.net/avatar/ec84937c47cdddf6188ee70dd36ee21492000.jpg","cityName":"北京","content":"就记住了女狼的脸,过目不忘。希望以后为她单开一篇。这是一部老一代Xman为新一代Xman让路的电影,让路就让路吧,有必要搞这么惨吗?要不要脸?","created":1488787431000,"filmView":false,"gender":1,"id":99060575,"isMajor":false,"juryLevel":2,"movieId":247875,"nick":"红胡子曾","nickName":"大宝剑","oppose":0,"pro":true,"reply":0,"score":3.5,"spoiler":0,"startTime":"2017-03-06 16:03:51","supportComment":false,"supportLike":true,"sureViewed":1,"tagList":{"fixed":[{"id":4,"name":"购票"}]},"time":"2017-03-06 16:03","userId":9491608,"userLevel":5,"vipInfo":"猫眼星级专业评委","vipType":3}] * paging : {"hasMore":true,"limit":4,"offset":0,"total":29} */ private PagingBean paging; private List<DataBean> data; public PagingBean getPaging() { return paging; } public void setPaging(PagingBean paging) { this.paging = paging; } public List<DataBean> getData() { return data; } public void setData(List<DataBean> data) { this.data = data; } public static class PagingBean { /** * hasMore : true * limit : 4 * offset : 0 * total : 29 */ private boolean hasMore; private int limit; private int offset; private int total; public boolean isHasMore() { return hasMore; } public void setHasMore(boolean hasMore) { this.hasMore = hasMore; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } } public static class DataBean { /** * approve : 23 * approved : false * authInfo : 极客电影联合发起人,时光网前主编 * avatarurl : https://img.meituan.net/avatar/ba75f3b26f20cfb0fa933684fc963a19145729.jpg * cityName : 北京 * content : 四星之作!期待限制级完整版再添一星。《蝙蝠侠:黑暗骑士》之后,超级英雄电影鲜有如此的悲壮与震撼!休叔封爪,狼叔绝唱,一代X战警落幕,令人唏嘘。末尾小狼女将十字架改作X标志,便是泪闸决堤之时。 * created : 1488849151000 * filmView : false * gender : 1 * id : 99108226 * isMajor : false * juryLevel : 2 * movieId : 247875 * nick : 子虚Brad * nickName : 子虚Brad * oppose : 0 * pro : true * reply : 0 * score : 4 * spoiler : 0 * startTime : 2017-03-07 09:12:31 * supportComment : false * supportLike : true * sureViewed : 1 * tagList : {} * time : 2017-03-07 09:12 * userId : 228944158 * userLevel : 5 * vipInfo : 猫眼星级专业评委 * vipType : 3 */ private int approve; private boolean approved; private String authInfo; private String avatarurl; private String cityName; private String content; private long created; private boolean filmView; private int gender; private int id; private boolean isMajor; private int juryLevel; private int movieId; private String nick; private String nickName; private int oppose; private boolean pro; private int reply; private double score; private int spoiler; private String startTime; private boolean supportComment; private boolean supportLike; private int sureViewed; private TagListBean tagList; private String time; private int userId; private int userLevel; private String vipInfo; private int vipType; public int getApprove() { return approve; } public void setApprove(int approve) { this.approve = approve; } public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } public String getAuthInfo() { return authInfo; } public void setAuthInfo(String authInfo) { this.authInfo = authInfo; } public String getAvatarurl() { return avatarurl; } public void setAvatarurl(String avatarurl) { this.avatarurl = avatarurl; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public long getCreated() { return created; } public void setCreated(long created) { this.created = created; } public boolean isFilmView() { return filmView; } public void setFilmView(boolean filmView) { this.filmView = filmView; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isIsMajor() { return isMajor; } public void setIsMajor(boolean isMajor) { this.isMajor = isMajor; } public int getJuryLevel() { return juryLevel; } public void setJuryLevel(int juryLevel) { this.juryLevel = juryLevel; } public int getMovieId() { return movieId; } public void setMovieId(int movieId) { this.movieId = movieId; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public int getOppose() { return oppose; } public void setOppose(int oppose) { this.oppose = oppose; } public boolean isPro() { return pro; } public void setPro(boolean pro) { this.pro = pro; } public int getReply() { return reply; } public void setReply(int reply) { this.reply = reply; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public int getSpoiler() { return spoiler; } public void setSpoiler(int spoiler) { this.spoiler = spoiler; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public boolean isSupportComment() { return supportComment; } public void setSupportComment(boolean supportComment) { this.supportComment = supportComment; } public boolean isSupportLike() { return supportLike; } public void setSupportLike(boolean supportLike) { this.supportLike = supportLike; } public int getSureViewed() { return sureViewed; } public void setSureViewed(int sureViewed) { this.sureViewed = sureViewed; } public TagListBean getTagList() { return tagList; } public void setTagList(TagListBean tagList) { this.tagList = tagList; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getUserLevel() { return userLevel; } public void setUserLevel(int userLevel) { this.userLevel = userLevel; } public String getVipInfo() { return vipInfo; } public void setVipInfo(String vipInfo) { this.vipInfo = vipInfo; } public int getVipType() { return vipType; } public void setVipType(int vipType) { this.vipType = vipType; } public static class TagListBean { } } }
Java
public class StockSeriesBase extends VisualBaseWithBounds { public StockSeriesBase() { js.setLength(0); js.append("var stockSeriesBase").append(++variableIndex).append(" = anychart.core.stock.series.base();"); jsBase = "stockSeriesBase" + variableIndex; } protected StockSeriesBase(String jsBase) { js.setLength(0); this.jsBase = jsBase; } protected StockSeriesBase(StringBuilder js, String jsBase, boolean isChain) { this.js = js; this.jsBase = jsBase; this.isChain = isChain; } protected String getJsBase() { return jsBase; } private TableMapping getData; /** * Gets data for the series. */ public TableMapping getData() { if (getData == null) getData = new TableMapping(jsBase + ".data()"); return getData; } private TableMapping data; private DataTable data1; private String data2; private String data3; private String mappingSettings; private String csvSettings; /** * Sets data for the series. */ public StockSeriesBase setData(TableMapping data, String mappingSettings, String csvSettings) { if (jsBase == null) { this.data = null; this.data1 = null; this.data2 = null; this.data3 = null; this.data = data; this.mappingSettings = mappingSettings; this.csvSettings = csvSettings; } else { this.data = data; this.mappingSettings = mappingSettings; this.csvSettings = csvSettings; if (!isChain) { js.append(jsBase); isChain = true; } js.append(data.generateJs()); js.append(String.format(Locale.US, ".data(%s, %s, %s)", ((data != null) ? data.getJsBase() : "null"), wrapQuotes(mappingSettings), wrapQuotes(csvSettings))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".data(%s, %s, %s);", ((data != null) ? data.getJsBase() : "null"), wrapQuotes(mappingSettings), wrapQuotes(csvSettings))); js.setLength(0); } } return this; } /** * Sets data for the series. */ public StockSeriesBase setData(DataTable data1, String mappingSettings, String csvSettings) { if (jsBase == null) { this.data = null; this.data1 = null; this.data2 = null; this.data3 = null; this.data1 = data1; this.mappingSettings = mappingSettings; this.csvSettings = csvSettings; } else { this.data1 = data1; this.mappingSettings = mappingSettings; this.csvSettings = csvSettings; if (!isChain) { js.append(jsBase); isChain = true; } js.append(data1.generateJs()); js.append(String.format(Locale.US, ".data(%s, %s, %s)", ((data1 != null) ? data1.getJsBase() : "null"), wrapQuotes(mappingSettings), wrapQuotes(csvSettings))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".data(%s, %s, %s);", ((data1 != null) ? data1.getJsBase() : "null"), wrapQuotes(mappingSettings), wrapQuotes(csvSettings))); js.setLength(0); } } return this; } /** * Sets data for the series. */ public StockSeriesBase setData(String data2, String mappingSettings, String csvSettings) { if (jsBase == null) { this.data = null; this.data1 = null; this.data2 = null; this.data3 = null; this.data2 = data2; this.mappingSettings = mappingSettings; this.csvSettings = csvSettings; } else { this.data2 = data2; this.mappingSettings = mappingSettings; this.csvSettings = csvSettings; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".data(%s, %s, %s)", wrapQuotes(data2), wrapQuotes(mappingSettings), wrapQuotes(csvSettings))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".data(%s, %s, %s);", wrapQuotes(data2), wrapQuotes(mappingSettings), wrapQuotes(csvSettings))); js.setLength(0); } } return this; } private StateSettings getHovered; /** * Getter for hovered state settings. */ public StateSettings getHovered() { if (getHovered == null) getHovered = new StateSettings(jsBase + ".hovered()"); return getHovered; } private String hovered; /** * Setter for hovered state settings. */ public StockSeriesBase setHovered(String hovered) { if (jsBase == null) { this.hovered = hovered; } else { this.hovered = hovered; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".hovered(%s)", wrapQuotes(hovered))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".hovered(%s);", wrapQuotes(hovered))); js.setLength(0); } } return this; } private LegendItemSettings getLegendItem; /** * Gets the current legend item setting for series. */ public LegendItemSettings getLegendItem() { if (getLegendItem == null) getLegendItem = new LegendItemSettings(jsBase + ".legendItem()"); return getLegendItem; } private String legendItem; /** * Sets the legend item setting for series. */ public StockSeriesBase setLegendItem(String legendItem) { if (jsBase == null) { this.legendItem = legendItem; } else { this.legendItem = legendItem; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".legendItem(%s)", wrapQuotes(legendItem))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".legendItem(%s);", wrapQuotes(legendItem))); js.setLength(0); } } return this; } private UiMarkersFactory getMarkers; /** * Getter for the data markers. */ public UiMarkersFactory getMarkers() { if (getMarkers == null) getMarkers = new UiMarkersFactory(jsBase + ".markers()"); return getMarkers; } private String markers; private Boolean markers1; private String markers2; /** * Setter for the data markers. */ public StockSeriesBase setMarkers(String markers) { if (jsBase == null) { this.markers = null; this.markers1 = null; this.markers2 = null; this.markers = markers; } else { this.markers = markers; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".markers(%s)", wrapQuotes(markers))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".markers(%s);", wrapQuotes(markers))); js.setLength(0); } } return this; } /** * Setter for the data markers. */ public StockSeriesBase setMarkers(Boolean markers1) { if (jsBase == null) { this.markers = null; this.markers1 = null; this.markers2 = null; this.markers1 = markers1; } else { this.markers1 = markers1; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".markers(%b)", markers1)); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".markers(%b);", markers1)); js.setLength(0); } } return this; } private Number maxPointWidth; private String maxPointWidth1; /** * Setter for the maximum point width. */ public StockSeriesBase setMaxPointWidth(Number maxPointWidth) { if (jsBase == null) { this.maxPointWidth = null; this.maxPointWidth1 = null; this.maxPointWidth = maxPointWidth; } else { this.maxPointWidth = maxPointWidth; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".maxPointWidth(%s)", maxPointWidth)); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".maxPointWidth(%s);", maxPointWidth)); js.setLength(0); } } return this; } /** * Setter for the maximum point width. */ public StockSeriesBase setMaxPointWidth(String maxPointWidth1) { if (jsBase == null) { this.maxPointWidth = null; this.maxPointWidth1 = null; this.maxPointWidth1 = maxPointWidth1; } else { this.maxPointWidth1 = maxPointWidth1; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".maxPointWidth(%s)", wrapQuotes(maxPointWidth1))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".maxPointWidth(%s);", wrapQuotes(maxPointWidth1))); js.setLength(0); } } return this; } private Number minPointLength; private String minPointLength1; /** * Setter for the minimum point length. */ public StockSeriesBase setMinPointLength(Number minPointLength) { if (jsBase == null) { this.minPointLength = null; this.minPointLength1 = null; this.minPointLength = minPointLength; } else { this.minPointLength = minPointLength; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".minPointLength(%s)", minPointLength)); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".minPointLength(%s);", minPointLength)); js.setLength(0); } } return this; } /** * Setter for the minimum point length. */ public StockSeriesBase setMinPointLength(String minPointLength1) { if (jsBase == null) { this.minPointLength = null; this.minPointLength1 = null; this.minPointLength1 = minPointLength1; } else { this.minPointLength1 = minPointLength1; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".minPointLength(%s)", wrapQuotes(minPointLength1))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".minPointLength(%s);", wrapQuotes(minPointLength1))); js.setLength(0); } } return this; } private String name; /** * Sets the series name. */ public StockSeriesBase setName(String name) { if (jsBase == null) { this.name = name; } else { this.name = name; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".name(%s)", wrapQuotes(name))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".name(%s);", wrapQuotes(name))); js.setLength(0); } } return this; } private StateSettings getNormal; /** * Getter for normal state settings. */ public StateSettings getNormal() { if (getNormal == null) getNormal = new StateSettings(jsBase + ".normal()"); return getNormal; } private String normal; /** * Setter for normal state settings. */ public StockSeriesBase setNormal(String normal) { if (jsBase == null) { this.normal = normal; } else { this.normal = normal; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".normal(%s)", wrapQuotes(normal))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".normal(%s);", wrapQuotes(normal))); js.setLength(0); } } return this; } private Number pointWidth; private String pointWidth1; /** * Setter for the point width settings. */ public StockSeriesBase setPointWidth(Number pointWidth) { if (jsBase == null) { this.pointWidth = null; this.pointWidth1 = null; this.pointWidth = pointWidth; } else { this.pointWidth = pointWidth; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".pointWidth(%s)", pointWidth)); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".pointWidth(%s);", pointWidth)); js.setLength(0); } } return this; } /** * Setter for the point width settings. */ public StockSeriesBase setPointWidth(String pointWidth1) { if (jsBase == null) { this.pointWidth = null; this.pointWidth1 = null; this.pointWidth1 = pointWidth1; } else { this.pointWidth1 = pointWidth1; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".pointWidth(%s)", wrapQuotes(pointWidth1))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".pointWidth(%s);", wrapQuotes(pointWidth1))); js.setLength(0); } } return this; } private RenderingSettings getRendering; /** * Getter for the series rendering. */ public RenderingSettings getRendering() { if (getRendering == null) getRendering = new RenderingSettings(jsBase + ".rendering()"); return getRendering; } private String rendering; /** * Setter for the series rendering settings. */ public StockSeriesBase setRendering(String rendering) { if (jsBase == null) { this.rendering = rendering; } else { this.rendering = rendering; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".rendering(%s)", wrapQuotes(rendering))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".rendering(%s);", wrapQuotes(rendering))); js.setLength(0); } } return this; } private String seriesType; /** * Setter for switching of the series type. */ public StockSeriesBase setSeriesType(String seriesType) { if (jsBase == null) { this.seriesType = seriesType; } else { this.seriesType = seriesType; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".seriesType(%s)", wrapQuotes(seriesType))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".seriesType(%s);", wrapQuotes(seriesType))); js.setLength(0); } } return this; } private Tooltip getTooltip; /** * Getter for the current tooltip. */ public Tooltip getTooltip() { if (getTooltip == null) getTooltip = new Tooltip(jsBase + ".tooltip()"); return getTooltip; } private String tooltip; private Boolean tooltip1; /** * Setter for the tooltip. */ public StockSeriesBase setTooltip(String tooltip) { if (jsBase == null) { this.tooltip = null; this.tooltip1 = null; this.tooltip = tooltip; } else { this.tooltip = tooltip; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".tooltip(%s)", wrapQuotes(tooltip))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".tooltip(%s);", wrapQuotes(tooltip))); js.setLength(0); } } return this; } /** * Setter for the tooltip. */ public StockSeriesBase setTooltip(Boolean tooltip1) { if (jsBase == null) { this.tooltip = null; this.tooltip1 = null; this.tooltip1 = tooltip1; } else { this.tooltip1 = tooltip1; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".tooltip(%b)", tooltip1)); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".tooltip(%b);", tooltip1)); js.setLength(0); } } return this; } private ScatterBase getYScale; /** * Getter for the current Y-scale. */ public ScatterBase getYScale() { if (getYScale == null) getYScale = new ScatterBase(jsBase + ".yScale()"); return getYScale; } private ScatterBase yScale; private String yScale1; private ScaleTypes yScale2; private String yScale3; /** * Setter for the Y-scale. */ public StockSeriesBase setYScale(ScatterBase yScale) { if (jsBase == null) { this.yScale = null; this.yScale1 = null; this.yScale2 = null; this.yScale3 = null; this.yScale = yScale; } else { this.yScale = yScale; if (isChain) { js.append(";"); isChain = false; } js.append(yScale.generateJs()); js.append(jsBase); js.append(String.format(Locale.US, ".yScale(%s);", ((yScale != null) ? yScale.getJsBase() : "null"))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".yScale(%s);", ((yScale != null) ? yScale.getJsBase() : "null"))); js.setLength(0); } } return this; } /** * Setter for the Y-scale. */ public StockSeriesBase setYScale(String yScale1) { if (jsBase == null) { this.yScale = null; this.yScale1 = null; this.yScale2 = null; this.yScale3 = null; this.yScale1 = yScale1; } else { this.yScale1 = yScale1; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".yScale(%s)", wrapQuotes(yScale1))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".yScale(%s);", wrapQuotes(yScale1))); js.setLength(0); } } return this; } /** * Setter for the Y-scale. */ public StockSeriesBase setYScale(ScaleTypes yScale2) { if (jsBase == null) { this.yScale = null; this.yScale1 = null; this.yScale2 = null; this.yScale3 = null; this.yScale2 = yScale2; } else { this.yScale2 = yScale2; if (!isChain) { js.append(jsBase); isChain = true; } js.append(String.format(Locale.US, ".yScale(%s)", ((yScale2 != null) ? yScale2.generateJs() : "null"))); if (isRendered) { onChangeListener.onChange(String.format(Locale.US, jsBase + ".yScale(%s);", ((yScale2 != null) ? yScale2.generateJs() : "null"))); js.setLength(0); } } return this; } private String generateJSgetData() { if (getData != null) { return getData.generateJs(); } return ""; } private String generateJSgetHovered() { if (getHovered != null) { return getHovered.generateJs(); } return ""; } private String generateJSgetLegendItem() { if (getLegendItem != null) { return getLegendItem.generateJs(); } return ""; } private String generateJSgetMarkers() { if (getMarkers != null) { return getMarkers.generateJs(); } return ""; } private String generateJSgetNormal() { if (getNormal != null) { return getNormal.generateJs(); } return ""; } private String generateJSgetRendering() { if (getRendering != null) { return getRendering.generateJs(); } return ""; } private String generateJSgetTooltip() { if (getTooltip != null) { return getTooltip.generateJs(); } return ""; } private String generateJSgetYScale() { if (getYScale != null) { return getYScale.generateJs(); } return ""; } protected String generateJsGetters() { StringBuilder jsGetters = new StringBuilder(); jsGetters.append(super.generateJsGetters()); jsGetters.append(generateJSgetData()); jsGetters.append(generateJSgetHovered()); jsGetters.append(generateJSgetLegendItem()); jsGetters.append(generateJSgetMarkers()); jsGetters.append(generateJSgetNormal()); jsGetters.append(generateJSgetRendering()); jsGetters.append(generateJSgetTooltip()); jsGetters.append(generateJSgetYScale()); return jsGetters.toString(); } @Override protected String generateJs() { if (isChain) { js.append(";"); isChain = false; } js.append(generateJsGetters()); String result = js.toString(); js.setLength(0); return result; } }
Java
public class LibraryMenu extends Menu { private PlaylistTable fakeTable; public JPopupMenu create(LibraryTree parent, Playlist playlist, ArrayList<Track> tracks) { if (fakeTable == null) { fakeTable = new PlaylistTable(playlist, new ArrayList<PlaylistColumn>()); fakeTable.dispose(); } ActionMap aMap = parent.getActionMap(); JPopupMenu popup = new JPopupMenu(); JMenuItem sendToCurrent = new JMenuItem(aMap.get(SEND_TO_CURRENT)); sendToCurrent.setIcon(Images.getEmptyIcon()); sendToCurrent.setAccelerator(SEND_TO_CURRENT.getKeyStroke()); popup.add(sendToCurrent); JMenuItem sendToNew = new JMenuItem(aMap.get(SEND_TO_NEW)); sendToNew.setAccelerator(SEND_TO_NEW.getKeyStroke()); popup.add(sendToNew); JMenuItem addToCurrent = new JMenuItem(aMap.get(ADD_TO_CURRENT)); addToCurrent.setAccelerator(ADD_TO_CURRENT.getKeyStroke()); popup.add(addToCurrent); popup.addSeparator(); TracksMenu tracksMenu = new TracksMenu(); JPopupMenu menu = tracksMenu.create(fakeTable, playlist, tracks); for (Component component : menu.getComponents()) { popup.add(component); } return popup; } public static void addMenu(JMenu menu) { } }
Java
public class PropertyUtil { private PropertyUtil() { // closed } /** * Checks the given string is not blank * * @param val * @return a <code>boolean</code> value, true if given string not null and * blank, false otherwise */ public static boolean notBlank(String val) { if (val != null && val.length() > 0) { return true; } return false; } /** * Returns the int value of given string if it is a number and less than * allowed value, otherwise default value * * @param stringVal * @param defaultVals * @return a <code>int</code> value, either the given value if its valid or * the default value */ public static int getEnvVarOrDefault(String stringVal, int... defaultVals) { int allowedMin, allowedMax, defaultVal; if (defaultVals.length > 2) { defaultVal = defaultVals[0]; allowedMin = defaultVals[1]; allowedMax = defaultVals[2]; } else if (defaultVals.length > 1) { defaultVal = defaultVals[0]; allowedMin = 0; allowedMax = defaultVals[1]; } else { defaultVal = defaultVals[0]; allowedMin = 0; allowedMax = Integer.MAX_VALUE; } if (PropertyUtil.notBlank(stringVal)) { try { int value = Integer.parseInt(stringVal); if (allowedMin <= value && value <= allowedMax) { return value; } } catch (Exception e) { return defaultVal; } } return defaultVal; } }
Java
public class TestOwnershipCache { @Rule public TestName runtime = new TestName(); private static OwnershipCache createOwnershipCache() { ClientConfig clientConfig = new ClientConfig(); return new OwnershipCache(clientConfig, null, NullStatsReceiver.get(), NullStatsReceiver.get()); } private static SocketAddress createSocketAddress(int port) { return new InetSocketAddress("127.0.0.1", port); } @Test(timeout = 60000) public void testUpdateOwner() { OwnershipCache cache = createOwnershipCache(); SocketAddress addr = createSocketAddress(1000); String stream = runtime.getMethodName(); assertTrue("Should successfully update owner if no owner exists before", cache.updateOwner(stream, addr)); assertEquals("Owner should be " + addr + " for stream " + stream, addr, cache.getOwner(stream)); assertTrue("Should successfully update owner if old owner is same", cache.updateOwner(stream, addr)); assertEquals("Owner should be " + addr + " for stream " + stream, addr, cache.getOwner(stream)); } @Test(timeout = 60000) public void testRemoveOwnerFromStream() { OwnershipCache cache = createOwnershipCache(); int initialPort = 2000; int numProxies = 2; int numStreamsPerProxy = 2; for (int i = 0; i < numProxies; i++) { SocketAddress addr = createSocketAddress(initialPort + i); for (int j = 0; j < numStreamsPerProxy; j++) { String stream = runtime.getMethodName() + "_" + i + "_" + j; cache.updateOwner(stream, addr); } } Map<String, SocketAddress> ownershipMap = cache.getStreamOwnerMapping(); assertEquals("There should be " + (numProxies * numStreamsPerProxy) + " entries in cache", numProxies * numStreamsPerProxy, ownershipMap.size()); Map<SocketAddress, Set<String>> ownershipDistribution = cache.getStreamOwnershipDistribution(); assertEquals("There should be " + numProxies + " proxies cached", numProxies, ownershipDistribution.size()); String stream = runtime.getMethodName() + "_0_0"; SocketAddress owner = createSocketAddress(initialPort); // remove non-existent mapping won't change anything SocketAddress nonExistentAddr = createSocketAddress(initialPort + 999); cache.removeOwnerFromStream(stream, nonExistentAddr, "remove-non-existent-addr"); assertEquals("Owner " + owner + " should not be removed", owner, cache.getOwner(stream)); ownershipMap = cache.getStreamOwnerMapping(); assertEquals("There should be " + (numProxies * numStreamsPerProxy) + " entries in cache", numProxies * numStreamsPerProxy, ownershipMap.size()); // remove existent mapping should remove ownership mapping cache.removeOwnerFromStream(stream, owner, "remove-owner"); assertNull("Owner " + owner + " should be removed", cache.getOwner(stream)); ownershipMap = cache.getStreamOwnerMapping(); assertEquals("There should be " + (numProxies * numStreamsPerProxy - 1) + " entries left in cache", numProxies * numStreamsPerProxy - 1, ownershipMap.size()); ownershipDistribution = cache.getStreamOwnershipDistribution(); assertEquals("There should still be " + numProxies + " proxies cached", numProxies, ownershipDistribution.size()); Set<String> ownedStreams = ownershipDistribution.get(owner); assertEquals("There should be only " + (numStreamsPerProxy - 1) + " streams owned for " + owner, numStreamsPerProxy - 1, ownedStreams.size()); assertFalse("Stream " + stream + " should not be owned by " + owner, ownedStreams.contains(stream)); } @Test(timeout = 60000) public void testRemoveAllStreamsFromOwner() { OwnershipCache cache = createOwnershipCache(); int initialPort = 2000; int numProxies = 2; int numStreamsPerProxy = 2; for (int i = 0; i < numProxies; i++) { SocketAddress addr = createSocketAddress(initialPort + i); for (int j = 0; j < numStreamsPerProxy; j++) { String stream = runtime.getMethodName() + "_" + i + "_" + j; cache.updateOwner(stream, addr); } } Map<String, SocketAddress> ownershipMap = cache.getStreamOwnerMapping(); assertEquals("There should be " + (numProxies * numStreamsPerProxy) + " entries in cache", numProxies * numStreamsPerProxy, ownershipMap.size()); Map<SocketAddress, Set<String>> ownershipDistribution = cache.getStreamOwnershipDistribution(); assertEquals("There should be " + numProxies + " proxies cached", numProxies, ownershipDistribution.size()); SocketAddress owner = createSocketAddress(initialPort); // remove non-existent host won't change anything SocketAddress nonExistentAddr = createSocketAddress(initialPort + 999); cache.removeAllStreamsFromOwner(nonExistentAddr); ownershipMap = cache.getStreamOwnerMapping(); assertEquals("There should still be " + (numProxies * numStreamsPerProxy) + " entries in cache", numProxies * numStreamsPerProxy, ownershipMap.size()); ownershipDistribution = cache.getStreamOwnershipDistribution(); assertEquals("There should still be " + numProxies + " proxies cached", numProxies, ownershipDistribution.size()); // remove existent host should remove ownership mapping cache.removeAllStreamsFromOwner(owner); ownershipMap = cache.getStreamOwnerMapping(); assertEquals("There should be " + ((numProxies - 1) * numStreamsPerProxy) + " entries left in cache", (numProxies - 1) * numStreamsPerProxy, ownershipMap.size()); ownershipDistribution = cache.getStreamOwnershipDistribution(); assertEquals("There should be " + (numProxies - 1) + " proxies cached", numProxies - 1, ownershipDistribution.size()); assertFalse("Host " + owner + " should not be cached", ownershipDistribution.containsKey(owner)); } @Test(timeout = 60000) public void testReplaceOwner() { OwnershipCache cache = createOwnershipCache(); int initialPort = 2000; int numProxies = 2; int numStreamsPerProxy = 2; for (int i = 0; i < numProxies; i++) { SocketAddress addr = createSocketAddress(initialPort + i); for (int j = 0; j < numStreamsPerProxy; j++) { String stream = runtime.getMethodName() + "_" + i + "_" + j; cache.updateOwner(stream, addr); } } Map<String, SocketAddress> ownershipMap = cache.getStreamOwnerMapping(); assertEquals("There should be " + (numProxies * numStreamsPerProxy) + " entries in cache", numProxies * numStreamsPerProxy, ownershipMap.size()); Map<SocketAddress, Set<String>> ownershipDistribution = cache.getStreamOwnershipDistribution(); assertEquals("There should be " + numProxies + " proxies cached", numProxies, ownershipDistribution.size()); String stream = runtime.getMethodName() + "_0_0"; SocketAddress oldOwner = createSocketAddress(initialPort); SocketAddress newOwner = createSocketAddress(initialPort + 999); cache.updateOwner(stream, newOwner); assertEquals("Owner of " + stream + " should be changed from " + oldOwner + " to " + newOwner, newOwner, cache.getOwner(stream)); ownershipMap = cache.getStreamOwnerMapping(); assertEquals("There should be " + (numProxies * numStreamsPerProxy) + " entries in cache", numProxies * numStreamsPerProxy, ownershipMap.size()); assertEquals("Owner of " + stream + " should be " + newOwner, newOwner, ownershipMap.get(stream)); ownershipDistribution = cache.getStreamOwnershipDistribution(); assertEquals("There should be " + (numProxies + 1) + " proxies cached", numProxies + 1, ownershipDistribution.size()); Set<String> oldOwnedStreams = ownershipDistribution.get(oldOwner); assertEquals("There should be only " + (numStreamsPerProxy - 1) + " streams owned by " + oldOwner, numStreamsPerProxy - 1, oldOwnedStreams.size()); assertFalse("Stream " + stream + " should not be owned by " + oldOwner, oldOwnedStreams.contains(stream)); Set<String> newOwnedStreams = ownershipDistribution.get(newOwner); assertEquals("There should be only " + (numStreamsPerProxy - 1) + " streams owned by " + newOwner, 1, newOwnedStreams.size()); assertTrue("Stream " + stream + " should be owned by " + newOwner, newOwnedStreams.contains(stream)); } }
Java
public final class AklToussaintHeuristic { @Conditional public static boolean _mut84858 = false, _mut84859 = false, _mut84860 = false, _mut84861 = false, _mut84862 = false, _mut84863 = false, _mut84864 = false, _mut84865 = false, _mut84866 = false, _mut84867 = false, _mut84868 = false, _mut84869 = false, _mut84870 = false, _mut84871 = false, _mut84872 = false, _mut84873 = false, _mut84874 = false, _mut84875 = false, _mut84876 = false, _mut84877 = false, _mut84878 = false, _mut84879 = false, _mut84880 = false, _mut84881 = false, _mut84882 = false, _mut84883 = false, _mut84884 = false, _mut84885 = false, _mut84886 = false, _mut84887 = false, _mut84888 = false, _mut84889 = false, _mut84890 = false, _mut84891 = false, _mut84892 = false, _mut84893 = false, _mut84894 = false, _mut84895 = false, _mut84896 = false, _mut84897 = false, _mut84898 = false, _mut84899 = false, _mut84900 = false, _mut84901 = false, _mut84902 = false, _mut84903 = false, _mut84904 = false, _mut84905 = false, _mut84906 = false, _mut84907 = false, _mut84908 = false, _mut84909 = false, _mut84910 = false, _mut84911 = false, _mut84912 = false, _mut84913 = false, _mut84914 = false, _mut84915 = false, _mut84916 = false, _mut84917 = false, _mut84918 = false, _mut84919 = false, _mut84920 = false; /** * Hide utility constructor. */ private AklToussaintHeuristic() { } /** * Returns a point set that is reduced by all points for which it is safe to assume * that they are not part of the convex hull. * * @param points the original point set * @return a reduced point set, useful as input for convex hull algorithms */ public static Collection<Vector2D> reducePoints(final Collection<Vector2D> points) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53"); // find the leftmost point int size = 0; Vector2D minX = null; Vector2D maxX = null; Vector2D minY = null; Vector2D maxY = null; for (Vector2D p : points) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53"); if ((_mut84863 ? (minX == null && ROR_less(p.getX(), minX.getX(), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84858, _mut84859, _mut84860, _mut84861, _mut84862)) : (minX == null || ROR_less(p.getX(), minX.getX(), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84858, _mut84859, _mut84860, _mut84861, _mut84862)))) { minX = p; } if ((_mut84869 ? (maxX == null && ROR_greater(p.getX(), maxX.getX(), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84864, _mut84865, _mut84866, _mut84867, _mut84868)) : (maxX == null || ROR_greater(p.getX(), maxX.getX(), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84864, _mut84865, _mut84866, _mut84867, _mut84868)))) { maxX = p; } if ((_mut84875 ? (minY == null && ROR_less(p.getY(), minY.getY(), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84870, _mut84871, _mut84872, _mut84873, _mut84874)) : (minY == null || ROR_less(p.getY(), minY.getY(), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84870, _mut84871, _mut84872, _mut84873, _mut84874)))) { minY = p; } if ((_mut84881 ? (maxY == null && ROR_greater(p.getY(), maxY.getY(), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84876, _mut84877, _mut84878, _mut84879, _mut84880)) : (maxY == null || ROR_greater(p.getY(), maxY.getY(), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84876, _mut84877, _mut84878, _mut84879, _mut84880)))) { maxY = p; } size++; } if (ROR_less(size, 4, "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84882, _mut84883, _mut84884, _mut84885, _mut84886)) { return points; } final List<Vector2D> quadrilateral = buildQuadrilateral(minY, maxX, maxY, minX); // if the quadrilateral is not well formed, e.g. only 2 points, do not attempt to reduce if (ROR_less(quadrilateral.size(), 3, "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53", _mut84887, _mut84888, _mut84889, _mut84890, _mut84891)) { return points; } final List<Vector2D> reducedPoints = new ArrayList<Vector2D>(quadrilateral); for (final Vector2D p : points) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.reducePoints_53"); // in which case they can not be part of the convex hull if (!insideQuadrilateral(p, quadrilateral)) { reducedPoints.add(p); } } return reducedPoints; } /** * Build the convex quadrilateral with the found corner points (with min/max x/y coordinates). * * @param points the respective points with min/max x/y coordinate * @return the quadrilateral */ private static List<Vector2D> buildQuadrilateral(final Vector2D... points) { List<Vector2D> quadrilateral = new ArrayList<Vector2D>(); for (Vector2D p : points) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.buildQuadrilateral_105"); if (!quadrilateral.contains(p)) { quadrilateral.add(p); } } return quadrilateral; } /** * Checks if the given point is located within the convex quadrilateral. * @param point the point to check * @param quadrilateralPoints the convex quadrilateral, represented by 4 points * @return {@code true} if the point is inside the quadrilateral, {@code false} otherwise */ private static boolean insideQuadrilateral(final Vector2D point, final List<Vector2D> quadrilateralPoints) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.insideQuadrilateral_121"); Vector2D p1 = quadrilateralPoints.get(0); Vector2D p2 = quadrilateralPoints.get(1); if ((_mut84892 ? (point.equals(p1) && point.equals(p2)) : (point.equals(p1) || point.equals(p2)))) { return true; } // get the location of the point relative to the first two vertices final double last = point.crossProduct(p1, p2); final int size = quadrilateralPoints.size(); // loop through the rest of the vertices for (int i = 1; ROR_less(i, size, "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.insideQuadrilateral_121", _mut84916, _mut84917, _mut84918, _mut84919, _mut84920); i++) { br.ufmg.labsoft.mutvariants.schematalib.SchemataLibMethods.listener.listen("org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.insideQuadrilateral_121"); p1 = p2; p2 = quadrilateralPoints.get(ROR_equals((AOR_plus(i, 1, "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.insideQuadrilateral_121", _mut84893, _mut84894, _mut84895, _mut84896)), size, "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.insideQuadrilateral_121", _mut84897, _mut84898, _mut84899, _mut84900, _mut84901) ? 0 : AOR_plus(i, 1, "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.insideQuadrilateral_121", _mut84902, _mut84903, _mut84904, _mut84905)); if ((_mut84906 ? (point.equals(p1) && point.equals(p2)) : (point.equals(p1) || point.equals(p2)))) { return true; } // -x * -y = +xy, x * y = +xy, -x * y = -xy, x * -y = -xy if (ROR_less(AOR_multiply(last, point.crossProduct(p1, p2), "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.insideQuadrilateral_121", _mut84907, _mut84908, _mut84909, _mut84910), 0, "org.apache.commons.math3.geometry.euclidean.twod.hull.AklToussaintHeuristic.insideQuadrilateral_121", _mut84911, _mut84912, _mut84913, _mut84914, _mut84915)) { return false; } } return true; } }
Java
public class ValueInputPane extends HBox implements RecentValuesListener { public static final int DEFAULT_WIDTH = 300; public static final int INTEGER_WIDTH = 75; private final ChangeListener<Number> recentValueSelectionListener; private final ComboBox<String> recentValuesCombo; private final TextInputControl field; private final String parameterId; private static final Logger LOGGER = Logger.getLogger(ValueInputPane.class.getName()); public ValueInputPane(final PluginParameter<?> parameter) { this(parameter, DEFAULT_WIDTH, null); } public ValueInputPane(final PluginParameter<?> parameter, int defaultWidth) { this(parameter, defaultWidth, null); } /** * Primary constructor * * @param parameter parameter to link to value * @param defaultWidth default width (in pixels) * @param suggestedHeight suggested hight (in lines) */ public ValueInputPane(final PluginParameter<?> parameter, int defaultWidth, Integer suggestedHeight) { if (suggestedHeight == null) { suggestedHeight = 1; } parameterId = parameter.getId(); final boolean isLabel = StringParameterType.isLabel(parameter); if (isLabel) { field = null; recentValuesCombo = null; recentValueSelectionListener = null; final Label l = new Label(parameter.getStringValue().replace(SeparatorConstants.NEWLINE, " ")); l.setWrapText(true); l.setPrefWidth(defaultWidth); getChildren().add(l); parameter.addListener((final PluginParameter<?> pluginParameter, final ParameterChange change) -> { Platform.runLater(() -> { switch (change) { case VALUE: // Don't change the value if it isn't necessary. // Setting the text changes the cursor position, which makes it look like text is // being entered right-to-left. final String param = parameter.getStringValue(); if (!l.getText().equals(param)) { l.setText(param); } break; case VISIBLE: l.setManaged(parameter.isVisible()); l.setVisible(parameter.isVisible()); this.setVisible(parameter.isVisible()); this.setManaged(parameter.isVisible()); break; default: break; } }); }); } else { final boolean isPassword = PasswordParameterType.ID.equals(parameter.getType().getId()); if (isPassword) { recentValuesCombo = null; } else { recentValuesCombo = new ComboBox<>(); recentValuesCombo.setEditable(false); recentValuesCombo.setTooltip(new Tooltip("Recent values")); recentValuesCombo.setMaxWidth(5); List<String> recentValues = RecentParameterValues.getRecentValues(parameterId); if (recentValues != null) { recentValuesCombo.setItems(FXCollections.observableList(recentValues)); } else { recentValuesCombo.setDisable(true); } ListCell<String> button = new ListCell<String>() { @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); setText("..."); } }; recentValuesCombo.setButtonCell(button); } if (isPassword) { field = new PasswordField(); } else if (suggestedHeight > 1) { field = new TextArea(); ((TextArea) field).setWrapText(true); ((TextArea) field).setPrefRowCount(suggestedHeight); } else { field = new TextField(); Platform.runLater(() -> { TextFields.bindAutoCompletion((TextField) field, recentValuesCombo.getItems()); }); } field.setPromptText(parameter.getDescription()); if (parameter.getObjectValue() != null) { field.setText(parameter.getStringValue()); } field.setPrefWidth(defaultWidth); if (recentValuesCombo != null) { recentValueSelectionListener = (ov, t, t1) -> { String value = recentValuesCombo.getValue(); if (value != null) { field.setText(recentValuesCombo.getValue()); } }; recentValuesCombo.getSelectionModel().selectedIndexProperty().addListener(recentValueSelectionListener); } else { recentValueSelectionListener = null; } if (parameter.getParameterValue().getGuiInit() != null) { parameter.getParameterValue().getGuiInit().init(field); } // If parameter is enabled, ensure widget is both enabled and editable. field.setEditable(parameter.isEnabled()); field.setDisable(!parameter.isEnabled()); field.setManaged(parameter.isVisible()); field.setVisible(parameter.isVisible()); this.setManaged(parameter.isVisible()); this.setVisible(parameter.isVisible()); if (recentValuesCombo != null) { recentValuesCombo.setDisable(!parameter.isEnabled()); } field.addEventFilter(KeyEvent.KEY_PRESSED, (KeyEvent event) -> { if (event.getCode() == KeyCode.DELETE) { IndexRange selection = field.getSelection(); if (selection.getLength() == 0) { field.deleteNextChar(); } else { field.deleteText(selection); } event.consume(); } else if (event.isShortcutDown() && event.isShiftDown() && (event.getCode() == KeyCode.RIGHT)) { field.selectNextWord(); event.consume(); } else if (event.isShortcutDown() && event.isShiftDown() && (event.getCode() == KeyCode.LEFT)) { field.selectPreviousWord(); event.consume(); } else if (event.isShortcutDown() && (event.getCode() == KeyCode.RIGHT)) { field.nextWord(); event.consume(); } else if (event.isShortcutDown() && (event.getCode() == KeyCode.LEFT)) { field.previousWord(); event.consume(); } else if (event.isShiftDown() && (event.getCode() == KeyCode.RIGHT)) { field.selectForward(); event.consume(); } else if (event.isShiftDown() && (event.getCode() == KeyCode.LEFT)) { field.selectBackward(); event.consume(); } else if (event.isShortcutDown() && (event.getCode() == KeyCode.A)) { field.selectAll(); event.consume(); } else if (event.getCode() == KeyCode.ESCAPE) { event.consume(); } else { // Do nothing } }); final Tooltip tooltip = new Tooltip(""); tooltip.setStyle("-fx-text-fill: white;"); field.textProperty().addListener((ObservableValue<? extends String> ov, String t, String t1) -> { String error = parameter.validateString(field.getText()); if (error != null) { tooltip.setText(error); field.setTooltip(tooltip); field.setId("invalid"); } else { tooltip.setText(""); field.setTooltip(null); field.setId(""); } parameter.setStringValue(field.getText()); }); parameter.addListener((final PluginParameter<?> pluginParameter, final ParameterChange change) -> { Platform.runLater(() -> { switch (change) { case VALUE: // Don't change the value if it isn't necessary. // Setting the text changes the cursor position, which makes it look like text is // being entered right-to-left. final String param = parameter.getStringValue(); if (!field.getText().equals(param)) { if (param != null) { field.setText(param); } else { field.setText(""); } } break; case ENABLED: // If enabled, then ensure widget is both editable and enabled. field.setEditable(pluginParameter.isEnabled()); field.setDisable(!pluginParameter.isEnabled()); recentValuesCombo.setDisable(!pluginParameter.isEnabled()); break; case VISIBLE: field.setManaged(parameter.isVisible()); field.setVisible(parameter.isVisible()); this.setVisible(parameter.isVisible()); this.setManaged(parameter.isVisible()); break; default: LOGGER.log(Level.FINE, "ignoring parameter change type {0}.", change); break; } }); }); HBox fieldAndRecentValues = new HBox(); fieldAndRecentValues.setSpacing(2); fieldAndRecentValues.getChildren().add(field); if (!isPassword) { fieldAndRecentValues.getChildren().add(recentValuesCombo); getChildren().add(fieldAndRecentValues); RecentParameterValues.addListener(this); } else { getChildren().add(fieldAndRecentValues); } } } @Override public void recentValuesChanged(final RecentValuesChangeEvent e) { if (recentValuesCombo != null && parameterId.equals(e.getId())) { recentValuesCombo.getSelectionModel().selectedIndexProperty().removeListener(recentValueSelectionListener); final List<String> recentValues = e.getNewValues(); if (recentValues != null) { recentValuesCombo.setItems(FXCollections.observableList(recentValues)); recentValuesCombo.setDisable(false); } else { final List<String> empty = Collections.emptyList(); recentValuesCombo.setItems(FXCollections.observableList(empty)); recentValuesCombo.setDisable(true); } recentValuesCombo.setPromptText("..."); recentValuesCombo.getSelectionModel().selectedIndexProperty().addListener(recentValueSelectionListener); } } }
Java
@NeverClassInline public static class A { @NeverInline public void ensureNotRepackaged() { TestClass.packageProtectedMethodToDisableRepackage(); } }
Java
@NeverClassInline public static class B { @NeverInline public Runnable foo() { C c = new C(); // This synthetic lambda class uses package protected access to C. Its context will initially // be B, thus the synthetic will internally be B-$$Synthetic. The lambda can be repackaged // together with the accessed class C. However, once A and B are merged as A, the context // implicitly changes. If repackaging does not either see or adjust the context, the result // will be that the external synthetic lambda will become A-$$Synthetic, // with the consequence that the call to repackaged.C.protectedMethod() will throw IAE. return () -> { System.out.println("B::foo"); c.packageProtectedMethod(); }; } }
Java
public class DateDeserializer implements JsonDeserializer<Date> { @Override public Date deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { Date dd = new Date(); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); dd = dateFormat.parse(je.getAsString()); } catch (ParseException ex) { Logger.getLogger(DateDeserializer.class.getName()).log(Level.SEVERE, null, ex); } return dd; } }
Java
public class PersonComboBoxModel extends DefaultComboBoxModel { /** Generated serial version uid */ private static final long serialVersionUID = -164842922152566685L; /** List of persons in the database */ private List<Person> persons; /** Change listener on list of persons */ private ChangeListener personsChangeListener; /** * Instatiate an instance of a PersonComboBoxModel. */ public PersonComboBoxModel() { personsChangeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { retrievePersons(); } }; MangoController.getInstance().addPersonsChangeListener( personsChangeListener); retrievePersons(); } /** * Regrab the persons from the database and fire a contents * changed event. */ private void retrievePersons() { this.persons = MangoController.getInstance().getAllPersons(); this.fireContentsChanged(persons, 0, persons.size()); } /** * @return the number of <code>People</code> in the model. */ @Override public int getSize() { return persons.size(); } /** * @return the <code>Person</code> at the specified index in the * model. */ @Override public Object getElementAt(int index) { return persons.get(index).getName(); } /** * Get the person at the specified index. * * @param index * The index we are interested in * @return a reference to the person at the specified index. */ public Person getPersonAt(int index) { return persons.get(index); } }
Java
public class OpendapGrid extends Grid { // Variables // --------- /** The OPeNDAP connection used for data. */ private DConnect2 connect; /** The starting data coordinate from the last access hint. */ private int[] start; /** The ending data coordinate from the last access hint. */ private int[] end; /** The stride along each dimension from the last access hint. */ private int[] stride; /** The actual number of columns from the last access hint. */ private int dataCols; /** The bounding rectangle for this data. */ private Rectangle dataRect; //////////////////////////////////////////////////////////// /** * Creates a new grid. * * @param grid the prototype grid upon which to base this one. * @param url the OPeNDAP dataset URL to use for data. */ public OpendapGrid ( Grid grid, String url ) throws IOException { // Initialize // ---------- super (grid); connect = new DConnect2 (url, true); // Create zero size start and end // ------------------------------ start = new int[] {0, 0}; end = new int[] {-1, -1}; stride = new int[] {1, 1}; } // OpendapGrid constructor //////////////////////////////////////////////////////////// public void setAccessHint ( int[] start, int[] end, int[] stride ) { // Check for subset // ---------------- if (dataRect != null && Arrays.equals (this.stride, stride)) { if (dataRect.contains (start[0], start[1], end[0] - start[0] + 1, end[1] - start[1] + 1)) return; } // if // Create constraint expression // ---------------------------- StringBuffer buffer = new StringBuffer(); for (int i = 0; i < start.length; i++) { buffer.append ("["); buffer.append (Integer.toString (start[i])); buffer.append (":"); buffer.append (Integer.toString (stride[i])); buffer.append (":"); buffer.append (Integer.toString (end[i])); buffer.append ("]"); } // for String constraint = buffer.toString(); // Read data using constraint // -------------------------- try { DataDDS dds = connect.getData ("?" + getName() + constraint, null); PrimitiveVector vector = ((DVector) dds.getVariable (getName())).getPrimitiveVector(); Object data = vector.getInternalStorage(); setData (data); } // try catch (Exception e) { throw new RuntimeException ("Error getting data: " + e.getMessage()); } // catch // Save constraint values // ---------------------- this.start = (int[]) start.clone(); this.end = (int[]) end.clone(); this.stride = (int[]) stride.clone(); dataCols = (int) Math.ceil (((end[COLS] - start[COLS] + 1)/(float)stride[COLS])); dataRect = new Rectangle ( start[0], start[1], end[0] - start[0] + 1, end[1] - start[1] + 1 ); } // setAccessHint //////////////////////////////////////////////////////////// public void setValue ( int row, int col, double val ) { throw new UnsupportedOperationException ("Cannot set values"); } // setValue //////////////////////////////////////////////////////////// public void setValue ( DataLocation loc, double val ) { throw new UnsupportedOperationException ("Cannot set values"); } // setValue //////////////////////////////////////////////////////////// public void setValue ( int index, double val ) { throw new UnsupportedOperationException ("Cannot set values"); } // setValue //////////////////////////////////////////////////////////// public double interpolate ( DataLocation loc ) { throw new UnsupportedOperationException ("Cannot interpolate values"); } // interpolate //////////////////////////////////////////////////////////// public Object getData () { throw new UnsupportedOperationException ("Cannot get data"); } // getData //////////////////////////////////////////////////////////// public Object getData ( int[] start, int[] count ) { throw new UnsupportedOperationException ("Cannot get data"); } // getData //////////////////////////////////////////////////////////// public double getValue ( int row, int col ) { if (row < start[ROWS] || row > end[ROWS] || col < start[COLS] || col > end[COLS]) return (Double.NaN); int index = ((row - start[ROWS])/stride[ROWS]) * dataCols + ((col - start[COLS])/stride[COLS]); return (getValue (index, data)); } // getValue //////////////////////////////////////////////////////////// public double getValue ( int index ) { return (getValue (index/dims[COLS], index%dims[COLS])); } // getValue //////////////////////////////////////////////////////////// }
Java
abstract class ContextualSearchHeuristic { /** * Gets whether this heuristic's condition was satisfied or not if it is enabled. * In the case of a Tap heuristic, if the condition is satisfied the Tap is suppressed. * This heuristic may be called in logResultsSeen regardless of whether the condition was * satisfied. * @return True iff this heuristic is enabled and its condition is satisfied. */ protected abstract boolean isConditionSatisfiedAndEnabled(); /** * Optionally logs this heuristic's condition state. Up to the heuristic to determine exactly * what to log and whether to log at all. Default is to not log anything. */ protected void logConditionState() {} /** * Optionally logs whether results would have been seen if this heuristic had its condition * satisfied, and possibly some associated data for profiling (up to the heuristic to decide). * Default is to not log anything. * @param wasSearchContentViewSeen Whether the panel contents were seen. * @param wasActivatedByTap Whether the panel was activated by a Tap or not. */ protected void logResultsSeen(boolean wasSearchContentViewSeen, boolean wasActivatedByTap) {} /** * Optionally logs data about the duration the panel was viewed and /or opened. * Default is to not log anything. * @param panelViewDurationMs The duration that the panel was viewed (Peek and opened) by the * user. This should always be a positive number, since this method is only called when * the panel has been viewed (Peeked). * @param panelOpenDurationMs The duration that the panel was opened, or 0 if it was never * opened. */ protected void logPanelViewedDurations(long panelViewDurationMs, long panelOpenDurationMs) {} /** * @return Whether this heuristic should be considered when logging aggregate metrics for Tap * suppression. */ protected boolean shouldAggregateLogForTapSuppression() { return false; } /** * @return Whether this heuristic's condition would have been satisfied, causing a tap * suppression, if it were enabled through VariationsAssociatedData. If the feature is * enabled through VariationsAssociatedData then this method should return false. */ protected boolean isConditionSatisfiedForAggregateLogging() { return false; } /** * Logs the heuristic to UMA and UKM through Ranker logging for the purpose of Tap Suppression. * @param recorder A logger to log to. */ protected void logRankerTapSuppression(ContextualSearchInteractionRecorder recorder) { // Default is to not log. } /** * Logs a Ranker outcome using the heuristic for the purpose of Ranker Tap Suppression. * @param recorder A logger to log to. */ protected void logRankerTapSuppressionOutcome(ContextualSearchInteractionRecorder recorder) { // Default is to not log. } /** * Allows a heuristic to override a machine-learning model's Tap Suppression. */ protected boolean shouldOverrideMlTapSuppression() { return false; } /** * Clamps an input value into a range of 1-10 inclusive. * @param value The value to limit. * @return A value that's at least 1 and at most 10. */ protected int clamp(int value) { return Math.max(1, Math.min(10, value)); } }
Java
public class EndDeviceAssetImpl extends AssetContainerImpl implements EndDeviceAsset { /** * The default value of the '{@link #isDisconnect() <em>Disconnect</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDisconnect() * @generated * @ordered */ protected static final boolean DISCONNECT_EDEFAULT = false; /** * The cached value of the '{@link #isDisconnect() <em>Disconnect</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDisconnect() * @generated * @ordered */ protected boolean disconnect = DISCONNECT_EDEFAULT; /** * The default value of the '{@link #isRelayCapable() <em>Relay Capable</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isRelayCapable() * @generated * @ordered */ protected static final boolean RELAY_CAPABLE_EDEFAULT = false; /** * The cached value of the '{@link #isRelayCapable() <em>Relay Capable</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isRelayCapable() * @generated * @ordered */ protected boolean relayCapable = RELAY_CAPABLE_EDEFAULT; /** * The cached value of the '{@link #getReadings() <em>Readings</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReadings() * @generated * @ordered */ protected EList<Reading> readings; /** * The cached value of the '{@link #getServiceDeliveryPoint() <em>Service Delivery Point</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getServiceDeliveryPoint() * @generated * @ordered */ protected ServiceDeliveryPoint serviceDeliveryPoint; /** * The default value of the '{@link #isMetrology() <em>Metrology</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isMetrology() * @generated * @ordered */ protected static final boolean METROLOGY_EDEFAULT = false; /** * The cached value of the '{@link #isMetrology() <em>Metrology</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isMetrology() * @generated * @ordered */ protected boolean metrology = METROLOGY_EDEFAULT; /** * The default value of the '{@link #getRatedVoltage() <em>Rated Voltage</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRatedVoltage() * @generated * @ordered */ protected static final float RATED_VOLTAGE_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getRatedVoltage() <em>Rated Voltage</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRatedVoltage() * @generated * @ordered */ protected float ratedVoltage = RATED_VOLTAGE_EDEFAULT; /** * The default value of the '{@link #getRatedCurrent() <em>Rated Current</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRatedCurrent() * @generated * @ordered */ protected static final float RATED_CURRENT_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getRatedCurrent() <em>Rated Current</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRatedCurrent() * @generated * @ordered */ protected float ratedCurrent = RATED_CURRENT_EDEFAULT; /** * The default value of the '{@link #getTimeZoneOffset() <em>Time Zone Offset</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTimeZoneOffset() * @generated * @ordered */ protected static final float TIME_ZONE_OFFSET_EDEFAULT = 0.0F; /** * The cached value of the '{@link #getTimeZoneOffset() <em>Time Zone Offset</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTimeZoneOffset() * @generated * @ordered */ protected float timeZoneOffset = TIME_ZONE_OFFSET_EDEFAULT; /** * The cached value of the '{@link #getServiceLocation() <em>Service Location</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getServiceLocation() * @generated * @ordered */ protected ServiceLocation serviceLocation; /** * The cached value of the '{@link #getEndDeviceControls() <em>End Device Controls</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEndDeviceControls() * @generated * @ordered */ protected EList<EndDeviceControl> endDeviceControls; /** * The cached value of the '{@link #getEndDeviceModel() <em>End Device Model</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEndDeviceModel() * @generated * @ordered */ protected EndDeviceModel endDeviceModel; /** * The default value of the '{@link #isReadRequest() <em>Read Request</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isReadRequest() * @generated * @ordered */ protected static final boolean READ_REQUEST_EDEFAULT = false; /** * The cached value of the '{@link #isReadRequest() <em>Read Request</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isReadRequest() * @generated * @ordered */ protected boolean readRequest = READ_REQUEST_EDEFAULT; /** * The default value of the '{@link #isDstEnabled() <em>Dst Enabled</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDstEnabled() * @generated * @ordered */ protected static final boolean DST_ENABLED_EDEFAULT = false; /** * The cached value of the '{@link #isDstEnabled() <em>Dst Enabled</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDstEnabled() * @generated * @ordered */ protected boolean dstEnabled = DST_ENABLED_EDEFAULT; /** * The default value of the '{@link #getPhaseCount() <em>Phase Count</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPhaseCount() * @generated * @ordered */ protected static final int PHASE_COUNT_EDEFAULT = 0; /** * The cached value of the '{@link #getPhaseCount() <em>Phase Count</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPhaseCount() * @generated * @ordered */ protected int phaseCount = PHASE_COUNT_EDEFAULT; /** * The cached value of the '{@link #getDeviceFunctions() <em>Device Functions</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDeviceFunctions() * @generated * @ordered */ protected EList<DeviceFunction> deviceFunctions; /** * The default value of the '{@link #isReverseFlowHandling() <em>Reverse Flow Handling</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isReverseFlowHandling() * @generated * @ordered */ protected static final boolean REVERSE_FLOW_HANDLING_EDEFAULT = false; /** * The cached value of the '{@link #isReverseFlowHandling() <em>Reverse Flow Handling</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isReverseFlowHandling() * @generated * @ordered */ protected boolean reverseFlowHandling = REVERSE_FLOW_HANDLING_EDEFAULT; /** * The default value of the '{@link #isDemandResponse() <em>Demand Response</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDemandResponse() * @generated * @ordered */ protected static final boolean DEMAND_RESPONSE_EDEFAULT = false; /** * The cached value of the '{@link #isDemandResponse() <em>Demand Response</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isDemandResponse() * @generated * @ordered */ protected boolean demandResponse = DEMAND_RESPONSE_EDEFAULT; /** * The cached value of the '{@link #getCustomer() <em>Customer</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCustomer() * @generated * @ordered */ protected Customer customer; /** * The default value of the '{@link #getAmrSystem() <em>Amr System</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAmrSystem() * @generated * @ordered */ protected static final String AMR_SYSTEM_EDEFAULT = null; /** * The cached value of the '{@link #getAmrSystem() <em>Amr System</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAmrSystem() * @generated * @ordered */ protected String amrSystem = AMR_SYSTEM_EDEFAULT; /** * The default value of the '{@link #isLoadControl() <em>Load Control</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isLoadControl() * @generated * @ordered */ protected static final boolean LOAD_CONTROL_EDEFAULT = false; /** * The cached value of the '{@link #isLoadControl() <em>Load Control</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isLoadControl() * @generated * @ordered */ protected boolean loadControl = LOAD_CONTROL_EDEFAULT; /** * The default value of the '{@link #isOutageReport() <em>Outage Report</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isOutageReport() * @generated * @ordered */ protected static final boolean OUTAGE_REPORT_EDEFAULT = false; /** * The cached value of the '{@link #isOutageReport() <em>Outage Report</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isOutageReport() * @generated * @ordered */ protected boolean outageReport = OUTAGE_REPORT_EDEFAULT; /** * The cached value of the '{@link #getEndDeviceGroups() <em>End Device Groups</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEndDeviceGroups() * @generated * @ordered */ protected EList<EndDeviceGroup> endDeviceGroups; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EndDeviceAssetImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MeteringPackage.Literals.END_DEVICE_ASSET; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isDisconnect() { return disconnect; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDisconnect(boolean newDisconnect) { boolean oldDisconnect = disconnect; disconnect = newDisconnect; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__DISCONNECT, oldDisconnect, disconnect)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isRelayCapable() { return relayCapable; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRelayCapable(boolean newRelayCapable) { boolean oldRelayCapable = relayCapable; relayCapable = newRelayCapable; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__RELAY_CAPABLE, oldRelayCapable, relayCapable)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Reading> getReadings() { if (readings == null) { readings = new EObjectWithInverseResolvingEList<Reading>(Reading.class, this, MeteringPackage.END_DEVICE_ASSET__READINGS, MeteringPackage.READING__END_DEVICE_ASSET); } return readings; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ServiceDeliveryPoint getServiceDeliveryPoint() { if (serviceDeliveryPoint != null && serviceDeliveryPoint.eIsProxy()) { InternalEObject oldServiceDeliveryPoint = (InternalEObject)serviceDeliveryPoint; serviceDeliveryPoint = (ServiceDeliveryPoint)eResolveProxy(oldServiceDeliveryPoint); if (serviceDeliveryPoint != oldServiceDeliveryPoint) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT, oldServiceDeliveryPoint, serviceDeliveryPoint)); } } return serviceDeliveryPoint; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ServiceDeliveryPoint basicGetServiceDeliveryPoint() { return serviceDeliveryPoint; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetServiceDeliveryPoint(ServiceDeliveryPoint newServiceDeliveryPoint, NotificationChain msgs) { ServiceDeliveryPoint oldServiceDeliveryPoint = serviceDeliveryPoint; serviceDeliveryPoint = newServiceDeliveryPoint; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT, oldServiceDeliveryPoint, newServiceDeliveryPoint); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setServiceDeliveryPoint(ServiceDeliveryPoint newServiceDeliveryPoint) { if (newServiceDeliveryPoint != serviceDeliveryPoint) { NotificationChain msgs = null; if (serviceDeliveryPoint != null) msgs = ((InternalEObject)serviceDeliveryPoint).eInverseRemove(this, MeteringPackage.SERVICE_DELIVERY_POINT__END_DEVICE_ASSETS, ServiceDeliveryPoint.class, msgs); if (newServiceDeliveryPoint != null) msgs = ((InternalEObject)newServiceDeliveryPoint).eInverseAdd(this, MeteringPackage.SERVICE_DELIVERY_POINT__END_DEVICE_ASSETS, ServiceDeliveryPoint.class, msgs); msgs = basicSetServiceDeliveryPoint(newServiceDeliveryPoint, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT, newServiceDeliveryPoint, newServiceDeliveryPoint)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isMetrology() { return metrology; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMetrology(boolean newMetrology) { boolean oldMetrology = metrology; metrology = newMetrology; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__METROLOGY, oldMetrology, metrology)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getRatedVoltage() { return ratedVoltage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRatedVoltage(float newRatedVoltage) { float oldRatedVoltage = ratedVoltage; ratedVoltage = newRatedVoltage; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__RATED_VOLTAGE, oldRatedVoltage, ratedVoltage)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getRatedCurrent() { return ratedCurrent; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRatedCurrent(float newRatedCurrent) { float oldRatedCurrent = ratedCurrent; ratedCurrent = newRatedCurrent; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__RATED_CURRENT, oldRatedCurrent, ratedCurrent)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public float getTimeZoneOffset() { return timeZoneOffset; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTimeZoneOffset(float newTimeZoneOffset) { float oldTimeZoneOffset = timeZoneOffset; timeZoneOffset = newTimeZoneOffset; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__TIME_ZONE_OFFSET, oldTimeZoneOffset, timeZoneOffset)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ServiceLocation getServiceLocation() { if (serviceLocation != null && serviceLocation.eIsProxy()) { InternalEObject oldServiceLocation = (InternalEObject)serviceLocation; serviceLocation = (ServiceLocation)eResolveProxy(oldServiceLocation); if (serviceLocation != oldServiceLocation) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION, oldServiceLocation, serviceLocation)); } } return serviceLocation; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ServiceLocation basicGetServiceLocation() { return serviceLocation; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetServiceLocation(ServiceLocation newServiceLocation, NotificationChain msgs) { ServiceLocation oldServiceLocation = serviceLocation; serviceLocation = newServiceLocation; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION, oldServiceLocation, newServiceLocation); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setServiceLocation(ServiceLocation newServiceLocation) { if (newServiceLocation != serviceLocation) { NotificationChain msgs = null; if (serviceLocation != null) msgs = ((InternalEObject)serviceLocation).eInverseRemove(this, CustomersPackage.SERVICE_LOCATION__END_DEVICE_ASSETS, ServiceLocation.class, msgs); if (newServiceLocation != null) msgs = ((InternalEObject)newServiceLocation).eInverseAdd(this, CustomersPackage.SERVICE_LOCATION__END_DEVICE_ASSETS, ServiceLocation.class, msgs); msgs = basicSetServiceLocation(newServiceLocation, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION, newServiceLocation, newServiceLocation)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<EndDeviceControl> getEndDeviceControls() { if (endDeviceControls == null) { endDeviceControls = new EObjectWithInverseResolvingEList<EndDeviceControl>(EndDeviceControl.class, this, MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS, MeteringPackage.END_DEVICE_CONTROL__END_DEVICE_ASSET); } return endDeviceControls; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EndDeviceModel getEndDeviceModel() { if (endDeviceModel != null && endDeviceModel.eIsProxy()) { InternalEObject oldEndDeviceModel = (InternalEObject)endDeviceModel; endDeviceModel = (EndDeviceModel)eResolveProxy(oldEndDeviceModel); if (endDeviceModel != oldEndDeviceModel) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL, oldEndDeviceModel, endDeviceModel)); } } return endDeviceModel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EndDeviceModel basicGetEndDeviceModel() { return endDeviceModel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetEndDeviceModel(EndDeviceModel newEndDeviceModel, NotificationChain msgs) { EndDeviceModel oldEndDeviceModel = endDeviceModel; endDeviceModel = newEndDeviceModel; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL, oldEndDeviceModel, newEndDeviceModel); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEndDeviceModel(EndDeviceModel newEndDeviceModel) { if (newEndDeviceModel != endDeviceModel) { NotificationChain msgs = null; if (endDeviceModel != null) msgs = ((InternalEObject)endDeviceModel).eInverseRemove(this, AssetModelsPackage.END_DEVICE_MODEL__END_DEVICE_ASSETS, EndDeviceModel.class, msgs); if (newEndDeviceModel != null) msgs = ((InternalEObject)newEndDeviceModel).eInverseAdd(this, AssetModelsPackage.END_DEVICE_MODEL__END_DEVICE_ASSETS, EndDeviceModel.class, msgs); msgs = basicSetEndDeviceModel(newEndDeviceModel, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL, newEndDeviceModel, newEndDeviceModel)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isReadRequest() { return readRequest; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setReadRequest(boolean newReadRequest) { boolean oldReadRequest = readRequest; readRequest = newReadRequest; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__READ_REQUEST, oldReadRequest, readRequest)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isDstEnabled() { return dstEnabled; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDstEnabled(boolean newDstEnabled) { boolean oldDstEnabled = dstEnabled; dstEnabled = newDstEnabled; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__DST_ENABLED, oldDstEnabled, dstEnabled)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getPhaseCount() { return phaseCount; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPhaseCount(int newPhaseCount) { int oldPhaseCount = phaseCount; phaseCount = newPhaseCount; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__PHASE_COUNT, oldPhaseCount, phaseCount)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<DeviceFunction> getDeviceFunctions() { if (deviceFunctions == null) { deviceFunctions = new EObjectWithInverseResolvingEList<DeviceFunction>(DeviceFunction.class, this, MeteringPackage.END_DEVICE_ASSET__DEVICE_FUNCTIONS, MeteringPackage.DEVICE_FUNCTION__END_DEVICE_ASSET); } return deviceFunctions; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isReverseFlowHandling() { return reverseFlowHandling; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setReverseFlowHandling(boolean newReverseFlowHandling) { boolean oldReverseFlowHandling = reverseFlowHandling; reverseFlowHandling = newReverseFlowHandling; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__REVERSE_FLOW_HANDLING, oldReverseFlowHandling, reverseFlowHandling)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isDemandResponse() { return demandResponse; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDemandResponse(boolean newDemandResponse) { boolean oldDemandResponse = demandResponse; demandResponse = newDemandResponse; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__DEMAND_RESPONSE, oldDemandResponse, demandResponse)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Customer getCustomer() { if (customer != null && customer.eIsProxy()) { InternalEObject oldCustomer = (InternalEObject)customer; customer = (Customer)eResolveProxy(oldCustomer); if (customer != oldCustomer) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, MeteringPackage.END_DEVICE_ASSET__CUSTOMER, oldCustomer, customer)); } } return customer; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Customer basicGetCustomer() { return customer; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetCustomer(Customer newCustomer, NotificationChain msgs) { Customer oldCustomer = customer; customer = newCustomer; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__CUSTOMER, oldCustomer, newCustomer); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCustomer(Customer newCustomer) { if (newCustomer != customer) { NotificationChain msgs = null; if (customer != null) msgs = ((InternalEObject)customer).eInverseRemove(this, CustomersPackage.CUSTOMER__END_DEVICE_ASSETS, Customer.class, msgs); if (newCustomer != null) msgs = ((InternalEObject)newCustomer).eInverseAdd(this, CustomersPackage.CUSTOMER__END_DEVICE_ASSETS, Customer.class, msgs); msgs = basicSetCustomer(newCustomer, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__CUSTOMER, newCustomer, newCustomer)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getAmrSystem() { return amrSystem; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setAmrSystem(String newAmrSystem) { String oldAmrSystem = amrSystem; amrSystem = newAmrSystem; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__AMR_SYSTEM, oldAmrSystem, amrSystem)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isLoadControl() { return loadControl; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLoadControl(boolean newLoadControl) { boolean oldLoadControl = loadControl; loadControl = newLoadControl; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__LOAD_CONTROL, oldLoadControl, loadControl)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isOutageReport() { return outageReport; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOutageReport(boolean newOutageReport) { boolean oldOutageReport = outageReport; outageReport = newOutageReport; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, MeteringPackage.END_DEVICE_ASSET__OUTAGE_REPORT, oldOutageReport, outageReport)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<EndDeviceGroup> getEndDeviceGroups() { if (endDeviceGroups == null) { endDeviceGroups = new EObjectWithInverseResolvingEList.ManyInverse<EndDeviceGroup>(EndDeviceGroup.class, this, MeteringPackage.END_DEVICE_ASSET__END_DEVICE_GROUPS, MeteringPackage.END_DEVICE_GROUP__END_DEVICE_ASSETS); } return endDeviceGroups; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MeteringPackage.END_DEVICE_ASSET__READINGS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getReadings()).basicAdd(otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT: if (serviceDeliveryPoint != null) msgs = ((InternalEObject)serviceDeliveryPoint).eInverseRemove(this, MeteringPackage.SERVICE_DELIVERY_POINT__END_DEVICE_ASSETS, ServiceDeliveryPoint.class, msgs); return basicSetServiceDeliveryPoint((ServiceDeliveryPoint)otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION: if (serviceLocation != null) msgs = ((InternalEObject)serviceLocation).eInverseRemove(this, CustomersPackage.SERVICE_LOCATION__END_DEVICE_ASSETS, ServiceLocation.class, msgs); return basicSetServiceLocation((ServiceLocation)otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getEndDeviceControls()).basicAdd(otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL: if (endDeviceModel != null) msgs = ((InternalEObject)endDeviceModel).eInverseRemove(this, AssetModelsPackage.END_DEVICE_MODEL__END_DEVICE_ASSETS, EndDeviceModel.class, msgs); return basicSetEndDeviceModel((EndDeviceModel)otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__DEVICE_FUNCTIONS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getDeviceFunctions()).basicAdd(otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__CUSTOMER: if (customer != null) msgs = ((InternalEObject)customer).eInverseRemove(this, CustomersPackage.CUSTOMER__END_DEVICE_ASSETS, Customer.class, msgs); return basicSetCustomer((Customer)otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_GROUPS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getEndDeviceGroups()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case MeteringPackage.END_DEVICE_ASSET__READINGS: return ((InternalEList<?>)getReadings()).basicRemove(otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT: return basicSetServiceDeliveryPoint(null, msgs); case MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION: return basicSetServiceLocation(null, msgs); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS: return ((InternalEList<?>)getEndDeviceControls()).basicRemove(otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL: return basicSetEndDeviceModel(null, msgs); case MeteringPackage.END_DEVICE_ASSET__DEVICE_FUNCTIONS: return ((InternalEList<?>)getDeviceFunctions()).basicRemove(otherEnd, msgs); case MeteringPackage.END_DEVICE_ASSET__CUSTOMER: return basicSetCustomer(null, msgs); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_GROUPS: return ((InternalEList<?>)getEndDeviceGroups()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case MeteringPackage.END_DEVICE_ASSET__DISCONNECT: return isDisconnect(); case MeteringPackage.END_DEVICE_ASSET__RELAY_CAPABLE: return isRelayCapable(); case MeteringPackage.END_DEVICE_ASSET__READINGS: return getReadings(); case MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT: if (resolve) return getServiceDeliveryPoint(); return basicGetServiceDeliveryPoint(); case MeteringPackage.END_DEVICE_ASSET__METROLOGY: return isMetrology(); case MeteringPackage.END_DEVICE_ASSET__RATED_VOLTAGE: return getRatedVoltage(); case MeteringPackage.END_DEVICE_ASSET__RATED_CURRENT: return getRatedCurrent(); case MeteringPackage.END_DEVICE_ASSET__TIME_ZONE_OFFSET: return getTimeZoneOffset(); case MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION: if (resolve) return getServiceLocation(); return basicGetServiceLocation(); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS: return getEndDeviceControls(); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL: if (resolve) return getEndDeviceModel(); return basicGetEndDeviceModel(); case MeteringPackage.END_DEVICE_ASSET__READ_REQUEST: return isReadRequest(); case MeteringPackage.END_DEVICE_ASSET__DST_ENABLED: return isDstEnabled(); case MeteringPackage.END_DEVICE_ASSET__PHASE_COUNT: return getPhaseCount(); case MeteringPackage.END_DEVICE_ASSET__DEVICE_FUNCTIONS: return getDeviceFunctions(); case MeteringPackage.END_DEVICE_ASSET__REVERSE_FLOW_HANDLING: return isReverseFlowHandling(); case MeteringPackage.END_DEVICE_ASSET__DEMAND_RESPONSE: return isDemandResponse(); case MeteringPackage.END_DEVICE_ASSET__CUSTOMER: if (resolve) return getCustomer(); return basicGetCustomer(); case MeteringPackage.END_DEVICE_ASSET__AMR_SYSTEM: return getAmrSystem(); case MeteringPackage.END_DEVICE_ASSET__LOAD_CONTROL: return isLoadControl(); case MeteringPackage.END_DEVICE_ASSET__OUTAGE_REPORT: return isOutageReport(); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_GROUPS: return getEndDeviceGroups(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case MeteringPackage.END_DEVICE_ASSET__DISCONNECT: setDisconnect((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__RELAY_CAPABLE: setRelayCapable((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__READINGS: getReadings().clear(); getReadings().addAll((Collection<? extends Reading>)newValue); return; case MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT: setServiceDeliveryPoint((ServiceDeliveryPoint)newValue); return; case MeteringPackage.END_DEVICE_ASSET__METROLOGY: setMetrology((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__RATED_VOLTAGE: setRatedVoltage((Float)newValue); return; case MeteringPackage.END_DEVICE_ASSET__RATED_CURRENT: setRatedCurrent((Float)newValue); return; case MeteringPackage.END_DEVICE_ASSET__TIME_ZONE_OFFSET: setTimeZoneOffset((Float)newValue); return; case MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION: setServiceLocation((ServiceLocation)newValue); return; case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS: getEndDeviceControls().clear(); getEndDeviceControls().addAll((Collection<? extends EndDeviceControl>)newValue); return; case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL: setEndDeviceModel((EndDeviceModel)newValue); return; case MeteringPackage.END_DEVICE_ASSET__READ_REQUEST: setReadRequest((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__DST_ENABLED: setDstEnabled((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__PHASE_COUNT: setPhaseCount((Integer)newValue); return; case MeteringPackage.END_DEVICE_ASSET__DEVICE_FUNCTIONS: getDeviceFunctions().clear(); getDeviceFunctions().addAll((Collection<? extends DeviceFunction>)newValue); return; case MeteringPackage.END_DEVICE_ASSET__REVERSE_FLOW_HANDLING: setReverseFlowHandling((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__DEMAND_RESPONSE: setDemandResponse((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__CUSTOMER: setCustomer((Customer)newValue); return; case MeteringPackage.END_DEVICE_ASSET__AMR_SYSTEM: setAmrSystem((String)newValue); return; case MeteringPackage.END_DEVICE_ASSET__LOAD_CONTROL: setLoadControl((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__OUTAGE_REPORT: setOutageReport((Boolean)newValue); return; case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_GROUPS: getEndDeviceGroups().clear(); getEndDeviceGroups().addAll((Collection<? extends EndDeviceGroup>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case MeteringPackage.END_DEVICE_ASSET__DISCONNECT: setDisconnect(DISCONNECT_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__RELAY_CAPABLE: setRelayCapable(RELAY_CAPABLE_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__READINGS: getReadings().clear(); return; case MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT: setServiceDeliveryPoint((ServiceDeliveryPoint)null); return; case MeteringPackage.END_DEVICE_ASSET__METROLOGY: setMetrology(METROLOGY_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__RATED_VOLTAGE: setRatedVoltage(RATED_VOLTAGE_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__RATED_CURRENT: setRatedCurrent(RATED_CURRENT_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__TIME_ZONE_OFFSET: setTimeZoneOffset(TIME_ZONE_OFFSET_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION: setServiceLocation((ServiceLocation)null); return; case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS: getEndDeviceControls().clear(); return; case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL: setEndDeviceModel((EndDeviceModel)null); return; case MeteringPackage.END_DEVICE_ASSET__READ_REQUEST: setReadRequest(READ_REQUEST_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__DST_ENABLED: setDstEnabled(DST_ENABLED_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__PHASE_COUNT: setPhaseCount(PHASE_COUNT_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__DEVICE_FUNCTIONS: getDeviceFunctions().clear(); return; case MeteringPackage.END_DEVICE_ASSET__REVERSE_FLOW_HANDLING: setReverseFlowHandling(REVERSE_FLOW_HANDLING_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__DEMAND_RESPONSE: setDemandResponse(DEMAND_RESPONSE_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__CUSTOMER: setCustomer((Customer)null); return; case MeteringPackage.END_DEVICE_ASSET__AMR_SYSTEM: setAmrSystem(AMR_SYSTEM_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__LOAD_CONTROL: setLoadControl(LOAD_CONTROL_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__OUTAGE_REPORT: setOutageReport(OUTAGE_REPORT_EDEFAULT); return; case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_GROUPS: getEndDeviceGroups().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case MeteringPackage.END_DEVICE_ASSET__DISCONNECT: return disconnect != DISCONNECT_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__RELAY_CAPABLE: return relayCapable != RELAY_CAPABLE_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__READINGS: return readings != null && !readings.isEmpty(); case MeteringPackage.END_DEVICE_ASSET__SERVICE_DELIVERY_POINT: return serviceDeliveryPoint != null; case MeteringPackage.END_DEVICE_ASSET__METROLOGY: return metrology != METROLOGY_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__RATED_VOLTAGE: return ratedVoltage != RATED_VOLTAGE_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__RATED_CURRENT: return ratedCurrent != RATED_CURRENT_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__TIME_ZONE_OFFSET: return timeZoneOffset != TIME_ZONE_OFFSET_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__SERVICE_LOCATION: return serviceLocation != null; case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_CONTROLS: return endDeviceControls != null && !endDeviceControls.isEmpty(); case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_MODEL: return endDeviceModel != null; case MeteringPackage.END_DEVICE_ASSET__READ_REQUEST: return readRequest != READ_REQUEST_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__DST_ENABLED: return dstEnabled != DST_ENABLED_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__PHASE_COUNT: return phaseCount != PHASE_COUNT_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__DEVICE_FUNCTIONS: return deviceFunctions != null && !deviceFunctions.isEmpty(); case MeteringPackage.END_DEVICE_ASSET__REVERSE_FLOW_HANDLING: return reverseFlowHandling != REVERSE_FLOW_HANDLING_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__DEMAND_RESPONSE: return demandResponse != DEMAND_RESPONSE_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__CUSTOMER: return customer != null; case MeteringPackage.END_DEVICE_ASSET__AMR_SYSTEM: return AMR_SYSTEM_EDEFAULT == null ? amrSystem != null : !AMR_SYSTEM_EDEFAULT.equals(amrSystem); case MeteringPackage.END_DEVICE_ASSET__LOAD_CONTROL: return loadControl != LOAD_CONTROL_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__OUTAGE_REPORT: return outageReport != OUTAGE_REPORT_EDEFAULT; case MeteringPackage.END_DEVICE_ASSET__END_DEVICE_GROUPS: return endDeviceGroups != null && !endDeviceGroups.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (disconnect: "); result.append(disconnect); result.append(", relayCapable: "); result.append(relayCapable); result.append(", metrology: "); result.append(metrology); result.append(", ratedVoltage: "); result.append(ratedVoltage); result.append(", ratedCurrent: "); result.append(ratedCurrent); result.append(", timeZoneOffset: "); result.append(timeZoneOffset); result.append(", readRequest: "); result.append(readRequest); result.append(", dstEnabled: "); result.append(dstEnabled); result.append(", phaseCount: "); result.append(phaseCount); result.append(", reverseFlowHandling: "); result.append(reverseFlowHandling); result.append(", demandResponse: "); result.append(demandResponse); result.append(", amrSystem: "); result.append(amrSystem); result.append(", loadControl: "); result.append(loadControl); result.append(", outageReport: "); result.append(outageReport); result.append(')'); return result.toString(); } }
Java
public class ManagedDataTable extends DataTable { private final static long serialVersionUID = 1; private BooleanArray occupied = new BooleanArray(); private int maxRow; /** returns true if the given row contains an object * @param row the row in the table * @return true if the given row contains an object */ public boolean hasRow(int row) { if (row < 0) { return false; } return occupied.get(row); } /** * Returns the max row that contains data. */ public int getMaxRow() { return maxRow; } /** Removes the given row from the table. * @param row The row to be removed */ @Override public void removeRow(int row) { if (occupied.get(row)) { super.removeRow(row); occupied.remove(row); if (row == maxRow) { maxRow = 0; for (int i = row ; i >= 0 ; --i) { if (occupied.get(i)) { maxRow = i; break; } } } } } /** Stores a boolean value in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putBoolean(int row, int col, boolean value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putBoolean(row, col, value); } /** Stores a byte value in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putByte(int row, int col, byte value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putByte(row, col, value); } /** Stores a short value in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putShort(int row, int col, short value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putShort(row, col, value); } /** Stores an int value in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putInt(int row, int col, int value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putInt(row, col, value); } /** Stores a long value in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putLong(int row, int col, long value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putLong(row, col, value); } /** Stores a double value in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putDouble(int row, int col, double value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putDouble(row, col, value); } /** Stores a float value in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putFloat(int row, int col, float value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putFloat(row, col, value); } /** Stores an String in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putString(int row, int col, String value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putString(row, col, value); } /** Stores an byte array in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putByteArray(int row, int col, byte[] value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putByteArray(row, col, value); } /** Stores an short array in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putShortArray(int row, int col, short[] value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putShortArray(row, col, value); } /** Stores an int array in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putIntArray(int row, int col, int[] value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putIntArray(row, col, value); } /** Stores a float array in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putFloatArray(int row, int col, float[] value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putFloatArray(row, col, value); } /** Stores a double array in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putDoubleArray(int row, int col, double[] value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putDoubleArray(row, col, value); } /** Stores an long array in the table at the given row * and column. Note - all values in a given column must be * of the same type. * @param row The row into the table (specifies which object) * @param col The column of the table. (specifies which field) * @param value The value to store. */ @Override public void putLongArray(int row, int col, long[] value) { maxRow = Math.max(maxRow, row); occupied.put(row,true); super.putLongArray(row, col, value); } }
Java
public class RelParser extends LineFilter { private final RelMap rels = new RelMap(true); private final List<LineMatcher> matchers = new ArrayList<LineMatcher>(); private int processedLines = 0; private int matchedLines = 0; public RelParser(String ruleFile) throws IOException, LineFilter.FilterException { BufferedReader reader = new BufferedReader(new FileReader(ruleFile)); String rule; while ((rule = reader.readLine()) != null) { matchers.add(new LineMatcher(rule)); } } public void parse(String inFile) throws IOException, LineFilter.FilterException { run(inFile, null); } @Override public void init() { processedLines = 0; matchedLines = 0; } @Override public void preProcessLine(String line) { boolean matchedAny = false; for (LineMatcher m : matchers) { if (m.match(line)) { matchedAny = true; } } processedLines++; if (matchedAny) { matchedLines++; } } @Override public void cleanup() { rels.clear(); } public int getProcessedLines() { return processedLines; } public int getMatchedLines() { return matchedLines; } private class LineMatcher { private final Pattern linePat; private final int[] param2group; private final String relStr; public LineMatcher(String matchSpec) throws LineFilter.FilterException { // To showcase how this code works, we will use a running example: // matchSpec = "src<%A> sink<%B>:RevFlow(%B,%A)" List<String> toks = StringHelper.split(matchSpec, ":"); checkSpec(toks.size() == 2, matchSpec); String matchStr = toks.get(0); String relAdderStr = toks.get(1); // matchStr = "src<%A> sink<%B>" // relAdderStr = "RevFlow(%B,%A)" Map<String,Integer> matcher2group = new HashMap<String,Integer>(); Pattern outPat = Pattern.compile("^[^<>]*"); Pattern inPat = Pattern.compile("^<([^<>]+)>"); StringBuffer sb = new StringBuffer(); int currGroup = 1; do { // 1st pass: // matchStr = "src<%A> sink<%B>" // sb = "" // matcher2group = {} // 2nd pass: // matchStr = " sink<%B>" // sb = "src([0-9]+)" // matcher2group = {"%A" -> 1} Matcher outMat = outPat.matcher(matchStr); outMat.lookingAt(); sb.append(Pattern.quote(outMat.group())); matchStr = matchStr.substring(outMat.end()); if (matchStr.equals("")) { break; } // 1st pass: // matchStr = "<%A> sink<%B>" // sb = "src" // matcher2group = {} // 2nd pass: // matchStr = "<%B>" // sb = "src([0-9]+) sink" // matcher2group = {"%A" -> 1} Matcher inMat = inPat.matcher(matchStr); inMat.lookingAt(); matcher2group.put(inMat.group(1), new Integer(currGroup)); currGroup++; sb.append("([0-9]+)"); matchStr = matchStr.substring(inMat.end()); // 1st pass: // matchStr = " sink<%B>" // sb = "src([0-9]+)" // matcher2group = {"%A" -> 1} // 2nd pass: // matchStr = "" // sb = "src([0-9]+) sink([0-9]+)" // matcher2group = {"%A" -> 1, "%B" -> 2} } while (!matchStr.equals("")); linePat = Pattern.compile(sb.toString()); List<String> relAndParams = StringHelper.split(relAdderStr, "("); checkSpec(relAndParams.size() == 2, matchSpec); relStr = relAndParams.get(0); String paramsStr = relAndParams.get(1); checkSpec(paramsStr.endsWith(")"), matchSpec); paramsStr = paramsStr.substring(0, paramsStr.length() - 1); // relStr = "RevFlow" // paramsStr = "%B,%A" List<String> params = StringHelper.split(paramsStr, ","); int num_params = params.size(); param2group = new int[num_params]; for (int i = 0; i < num_params; i++) { param2group[i] = matcher2group.get(params.get(i)).intValue(); } // param2group = [2,1] // This means: To construct a tuple to add to RevFlow, take the // second group matched by linePat and use it as the first element, // and take ths first group matched by linePat and use it as the // second element. // We retrieve the relation from the map at this point, to force // Petablox to open it, so that it gets saved as empty even if no // lines match. rels.get(relStr); } private void checkSpec(boolean assertion, String matchSpec) throws LineFilter.FilterException { if (!assertion) { String msg = "Invalid match specification: " + matchSpec; throw new LineFilter.FilterException(msg); } } public boolean match(String line) { Matcher m = linePat.matcher(line); if (m.matches()) { // the whole line must match int[] params = new int[param2group.length]; for (int i = 0; i < param2group.length; i++) { params[i] = Integer.parseInt(m.group(param2group[i])); } // TODO: We have to retrieve the ProgramRel from the map on the // parent object instead of caching a local reference, to make // sure we renew our reference whenever the relation is removed // from memory. rels.get(relStr).add(params); return true; } return false; } } }
Java
public class PermissionCrudTest extends TestSuiteBase { private CosmosAsyncDatabase createdDatabase; private CosmosAsyncUser createdUser; private final String databaseId = CosmosDatabaseForTest.generateId(); private CosmosAsyncClient client; @Factory(dataProvider = "clientBuilders") public PermissionCrudTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void createPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); //create getPermission CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .setId(UUID.randomUUID().toString()) .setPermissionMode(PermissionMode.READ) .setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); Mono<CosmosAsyncPermissionResponse> createObservable = createdUser.createPermission(permissionSettings, null); // validate getPermission creation CosmosResponseValidator<CosmosAsyncPermissionResponse> validator = new CosmosResponseValidator.Builder<CosmosAsyncPermissionResponse>() .withId(permissionSettings.getId()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); validateSuccess(createObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void readPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); // create permission CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .setId(UUID.randomUUID().toString()) .setPermissionMode(PermissionMode.READ) .setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); CosmosAsyncPermissionResponse readBackPermission = createdUser.createPermission(permissionSettings, null) .block(); // read Permission Mono<CosmosAsyncPermissionResponse> readObservable = readBackPermission.getPermission().read(null); // validate permission read CosmosResponseValidator<CosmosAsyncPermissionResponse> validator = new CosmosResponseValidator.Builder<CosmosAsyncPermissionResponse>() .withId(permissionSettings.getId()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); validateSuccess(readObservable, validator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void deletePermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); // create getPermission CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .setId(UUID.randomUUID().toString()) .setPermissionMode(PermissionMode.READ) .setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); CosmosAsyncPermissionResponse readBackPermission = createdUser.createPermission(permissionSettings, null) .block(); // delete Mono<CosmosAsyncPermissionResponse> deleteObservable = readBackPermission.getPermission() .delete(null); // validate delete permission CosmosResponseValidator<CosmosAsyncPermissionResponse> validator = new CosmosResponseValidator.Builder<CosmosAsyncPermissionResponse>() .nullResource() .build(); validateSuccess(deleteObservable, validator); waitIfNeededForReplicasToCatchUp(getClientBuilder()); // attempt to read the getPermission which was deleted Mono<CosmosAsyncPermissionResponse> readObservable = readBackPermission.getPermission() .read( null); FailureValidator notFoundValidator = new FailureValidator.Builder().resourceNotFound().build(); validateFailure(readObservable, notFoundValidator); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void upsertPermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); // create permission CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .setId(UUID.randomUUID().toString()) .setPermissionMode(PermissionMode.READ) .setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); CosmosAsyncPermissionResponse readBackPermissionResponse = createdUser.createPermission(permissionSettings, null) .block(); CosmosPermissionProperties readBackPermission = readBackPermissionResponse.getProperties(); // read Permission Mono<CosmosAsyncPermissionResponse> readObservable = readBackPermissionResponse.getPermission() .read( null); // validate getPermission creation CosmosResponseValidator<CosmosAsyncPermissionResponse> validator = new CosmosResponseValidator.Builder<CosmosAsyncPermissionResponse>() .withId(readBackPermission.getId()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); validateSuccess(readObservable, validator); //update getPermission readBackPermission = readBackPermission.setPermissionMode(PermissionMode.ALL); Mono<CosmosAsyncPermissionResponse> updateObservable = createdUser.upsertPermission(readBackPermission, null); // validate permission update CosmosResponseValidator<CosmosAsyncPermissionResponse> validatorForUpdate = new CosmosResponseValidator.Builder<CosmosAsyncPermissionResponse>() .withId(readBackPermission.getId()) .withPermissionMode(PermissionMode.ALL) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); validateSuccess(updateObservable, validatorForUpdate); } @Test(groups = { "simple" }, timeOut = TIMEOUT) public void replacePermission() throws Exception { createdUser = safeCreateUser(client, createdDatabase.getId(), getUserDefinition()); String id = UUID.randomUUID().toString(); // create permission CosmosPermissionProperties permissionSettings = new CosmosPermissionProperties() .setId(id) .setPermissionMode(PermissionMode.READ) .setResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc="); CosmosAsyncPermissionResponse readBackPermissionResponse = createdUser.createPermission(permissionSettings, null) .block(); // read Permission Mono<CosmosAsyncPermissionResponse> readObservable = readBackPermissionResponse.getPermission() .read(null); // validate getPermission creation CosmosResponseValidator<CosmosAsyncPermissionResponse> validator = new CosmosResponseValidator.Builder<CosmosAsyncPermissionResponse>() .withId(readBackPermissionResponse.getPermission().id()) .withPermissionMode(PermissionMode.READ) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); validateSuccess(readObservable, validator); //update getPermission CosmosPermissionProperties readBackPermission = readBackPermissionResponse.getProperties(); readBackPermission = readBackPermission.setPermissionMode(PermissionMode.ALL); CosmosAsyncPermission cosmosPermission = createdUser.getPermission(id); Mono<CosmosAsyncPermissionResponse> updateObservable = readBackPermissionResponse.getPermission() .replace(readBackPermission, null); // validate permission replace CosmosResponseValidator<CosmosAsyncPermissionResponse> validatorForUpdate = new CosmosResponseValidator.Builder<CosmosAsyncPermissionResponse>() .withId(readBackPermission.getId()) .withPermissionMode(PermissionMode.ALL) .withPermissionResourceLink("dbs/AQAAAA==/colls/AQAAAJ0fgTc=") .notNullEtag() .build(); validateSuccess(updateObservable, validatorForUpdate); } @BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT) public void before_PermissionCrudTest() { client = getClientBuilder().buildAsyncClient(); createdDatabase = createDatabase(client, databaseId); } @AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { safeClose(client); } private static CosmosUserProperties getUserDefinition() { return new CosmosUserProperties() .setId(UUID.randomUUID().toString()); } }
Java
public final class RobotUtils { private RobotUtils() { } /** * Get a value if it exists, or a default value if it's null. * * @param <T> The type to get. * @param value The value to test. * @param defaultValue The default value for if value is null. * @return A null safe value */ public static <T> T getValueOrDefault(final T value, final T defaultValue) { return value == null ? defaultValue : value; } /** * Clear all preferences from the robot. * <p> * This is a destructive operation. */ public static void clearPreferences() { final Preferences prefs = Preferences.getInstance(); for (final String key : prefs.getKeys()) { prefs.remove(key); } } /** * Map an array of {@code double} primitives to a {@link Double} array. * * @param args The array of doubles to map. * @return The array of boxed values. */ public static Double[] toBoxed(final double... args) { return DoubleStream.of(args).boxed().toArray(Double[]::new); } /** * Clamp a value between bounds. * * @param minBound The lowest possible value. * @param maxBound The highest possible value. * @param value The value to clamp. * @return The provided value, clamped between minBound and maxBound. */ public static double clamp(final double minBound, final double maxBound, final double value) { return Math.max(minBound, Math.min(value, maxBound)); } /** * Clamp a value between bounds. * * @param minBound The lowest possible value. * @param maxBound The highest possible value. * @param value The value to clamp. * @return The provided value, clamped between minBound and maxBound. */ public static float clamp(final float minBound, final float maxBound, final float value) { return Math.max(minBound, Math.min(value, maxBound)); } /** * Clamp a value between bounds. * * @param minBound The lowest possible value. * @param maxBound The highest possible value. * @param value The value to clamp. * @return The provided value, clamped between minBound and maxBound. */ public static int clamp(final int minBound, final int maxBound, final int value) { return Math.max(minBound, Math.min(value, maxBound)); } /** * Clamp a value between bounds. * * @param minBound The lowest possible value. * @param maxBound The highest possible value. * @param value The value to clamp. * @return The provided value, clamped between minBound and maxBound. */ public static long clamp(final long minBound, final long maxBound, final long value) { return Math.max(minBound, Math.min(value, maxBound)); } /** * Sign Preserving Square * * @param value The value to multiply. * @return The square of the given value, preserving sign. */ public static double sps(final double value) { return Math.copySign(value * value, value); } /** * Sign Preserving Power * * @param value The value to multiply. * @param exp The value to exponentiate by. * @return The square of the given value, preserving sign. */ public static double sppow(final double value, final double exp) { return Math.copySign(Math.pow(value, exp), value); } /** * Negate a boolean supplier. * * @param func The base function * @return A function that returns true when func returns false, and vice versa. */ public static BooleanSupplier not(final BooleanSupplier func) { return () -> !func.getAsBoolean(); } /** * Get the MAC address * * @return The robot's MAC address as a string. */ public static String getMACAddress() { try { final NetworkInterface iface = NetworkInterface.getByName("eth0"); final byte[] mac = iface.getHardwareAddress(); if (mac == null) { // happens on windows sometimes throw new SocketException(); } final StringJoiner sb = new StringJoiner(":"); for (final byte octet : mac) { sb.add(String.format("%02X", octet)); } return sb.toString(); } catch (SocketException e) { return "SocketException"; } } }
Java
@Component public class RepositoryWrapper implements Repository { @Autowired BlockchainImpl blockchain; public RepositoryWrapper() { } @Override public AccountState createAccount(byte[] addr) { return blockchain.getRepository().createAccount(addr); } @Override public boolean isExist(byte[] addr) { return blockchain.getRepository().isExist(addr); } @Override public AccountState getAccountState(byte[] addr) { return blockchain.getRepository().getAccountState(addr); } @Override public void delete(byte[] addr) { blockchain.getRepository().delete(addr); } @Override public BigInteger increaseNonce(byte[] addr) { return blockchain.getRepository().increaseNonce(addr); } @Override public BigInteger setNonce(byte[] addr, BigInteger nonce) { return blockchain.getRepository().setNonce(addr, nonce); } @Override public BigInteger getNonce(byte[] addr) { return blockchain.getRepository().getNonce(addr); } @Override public ContractDetails getContractDetails(byte[] addr) { return blockchain.getRepository().getContractDetails(addr); } @Override public boolean hasContractDetails(byte[] addr) { return blockchain.getRepository().hasContractDetails(addr); } @Override public void saveCode(byte[] addr, byte[] code) { blockchain.getRepository().saveCode(addr, code); } @Override public byte[] getCode(byte[] addr) { return blockchain.getRepository().getCode(addr); } @Override public byte[] getCodeHash(byte[] addr) { return blockchain.getRepository().getCodeHash(addr); } @Override public void addStorageRow(byte[] addr, DataWord key, DataWord value) { blockchain.getRepository().addStorageRow(addr, key, value); } @Override public DataWord getStorageValue(byte[] addr, DataWord key) { return blockchain.getRepository().getStorageValue(addr, key); } @Override public BigInteger getBalance(byte[] addr) { return blockchain.getRepository().getBalance(addr); } @Override public BigInteger addBalance(byte[] addr, BigInteger value) { return blockchain.getRepository().addBalance(addr, value); } @Override public Set<byte[]> getAccountsKeys() { return blockchain.getRepository().getAccountsKeys(); } @Override public void dumpState(Block block, long gasUsed, int txNumber, byte[] txHash) { blockchain.getRepository().dumpState(block, gasUsed, txNumber, txHash); } @Override public Repository startTracking() { return blockchain.getRepository().startTracking(); } @Override public void flush() { blockchain.getRepository().flush(); } @Override public void flushNoReconnect() { blockchain.getRepository().flushNoReconnect(); } @Override public void commit() { blockchain.getRepository().commit(); } @Override public void rollback() { blockchain.getRepository().rollback(); } @Override public void syncToRoot(byte[] root) { blockchain.getRepository().syncToRoot(root); } @Override public boolean isClosed() { return blockchain.getRepository().isClosed(); } @Override public void close() { blockchain.getRepository().close(); } @Override public void reset() { blockchain.getRepository().reset(); } @Override public void updateBatch(HashMap<ByteArrayWrapper, AccountState> accountStates, HashMap<ByteArrayWrapper, ContractDetails> contractDetailes) { blockchain.getRepository().updateBatch(accountStates, contractDetailes); } @Override public byte[] getRoot() { return blockchain.getRepository().getRoot(); } @Override public void loadAccount(byte[] addr, HashMap<ByteArrayWrapper, AccountState> cacheAccounts, HashMap<ByteArrayWrapper, ContractDetails> cacheDetails) { blockchain.getRepository().loadAccount(addr, cacheAccounts, cacheDetails); } @Override public Repository getSnapshotTo(byte[] root) { return blockchain.getRepository().getSnapshotTo(root); } @Override public int getStorageSize(byte[] addr) { return blockchain.getRepository().getStorageSize(addr); } @Override public Set<DataWord> getStorageKeys(byte[] addr) { return blockchain.getRepository().getStorageKeys(addr); } @Override public Map<DataWord, DataWord> getStorage(byte[] addr, @Nullable Collection<DataWord> keys) { return blockchain.getRepository().getStorage(addr, keys); } }
Java
public final class NormalizationTransform implements MetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(NormalizationTransform.class); private static final String DEFAULT_DSTYPE = DataSourceType.RATE.name(); static Counter newCounter(String name) { Counter c = Monitors.newCounter(name); DefaultMonitorRegistry.getInstance().register(c); return c; } @VisibleForTesting static final Counter HEARTBEAT_EXCEEDED = newCounter("servo.norm.heartbeatExceeded"); private final MetricObserver observer; private final long heartbeatMillis; private final long stepMillis; private final Map<MonitorConfig, NormalizedValue> cache; /** * Creates a new instance with the specified sampling and heartbeat interval using the default * clock implementation. * * @param observer downstream observer to forward values after rates have been normalized * to step boundaries * @param step sampling interval in milliseconds * @param heartbeat how long to keep values before dropping them and treating new samples * as first report * (in milliseconds) * @deprecated Please use a constructor that specifies the the timeunit explicitly. */ @Deprecated public NormalizationTransform(MetricObserver observer, long step, long heartbeat) { this(observer, step, heartbeat, TimeUnit.MILLISECONDS, ClockWithOffset.INSTANCE); } /** * Creates a new instance with the specified sampling and heartbeat interval and the * specified clock implementation. * * @param observer downstream observer to forward values after rates have been normalized * to step boundaries * @param step sampling interval in milliseconds * @param heartbeat how long to keep values before dropping them and treating new samples as * first report (in milliseconds) * @param clock The {@link com.netflix.servo.util.Clock} to use for getting * the current time. * @deprecated Please use a constructor that specifies the the timeunit explicitly. */ @Deprecated public NormalizationTransform(MetricObserver observer, long step, final long heartbeat, final Clock clock) { this(observer, step, heartbeat, TimeUnit.MILLISECONDS, ClockWithOffset.INSTANCE); } /** * Creates a new instance with the specified sampling and heartbeat interval and the * specified clock implementation. * * @param observer downstream observer to forward values after rates have been normalized * to step boundaries * @param step sampling interval * @param heartbeat how long to keep values before dropping them and treating new samples * as first report * @param unit {@link java.util.concurrent.TimeUnit} in which step and heartbeat * are specified. */ public NormalizationTransform(MetricObserver observer, long step, long heartbeat, TimeUnit unit) { this(observer, step, heartbeat, unit, ClockWithOffset.INSTANCE); } /** * Creates a new instance with the specified sampling and heartbeat interval and the specified * clock implementation. * * @param observer downstream observer to forward values after rates have been normalized * to step boundaries * @param step sampling interval * @param heartbeat how long to keep values before dropping them and treating new samples * as first report * @param unit The {@link java.util.concurrent.TimeUnit} in which step * and heartbeat are specified. * @param clock The {@link com.netflix.servo.util.Clock} * to use for getting the current time. */ public NormalizationTransform(MetricObserver observer, long step, final long heartbeat, TimeUnit unit, final Clock clock) { this.observer = Preconditions.checkNotNull(observer, "observer"); Preconditions.checkArgument(step > 0, "step must be positive"); this.stepMillis = unit.toMillis(step); Preconditions.checkArgument(heartbeat > 0, "heartbeat must be positive"); this.heartbeatMillis = unit.toMillis(heartbeat); this.cache = new LinkedHashMap<MonitorConfig, NormalizedValue>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry<MonitorConfig, NormalizedValue> eldest) { final long lastMod = eldest.getValue().lastUpdateTime; if (lastMod < 0) { return false; } final long now = clock.now(); final boolean expired = (now - lastMod) > heartbeatMillis; if (expired) { HEARTBEAT_EXCEEDED.increment(); LOGGER.debug("heartbeat interval exceeded, expiring {}", eldest.getKey()); } return expired; } }; } private static String getDataSourceType(Metric m) { final TagList tags = m.getConfig().getTags(); final String value = tags.getValue(DataSourceType.KEY); if (value != null) { return value; } else { return DEFAULT_DSTYPE; } } private static boolean isGauge(String dsType) { return dsType.equals(DataSourceType.GAUGE.name()); } private static boolean isRate(String dsType) { return dsType.equals(DataSourceType.RATE.name()); } private static boolean isNormalized(String dsType) { return dsType.equals(DataSourceType.NORMALIZED.name()); } private static boolean isInformational(String dsType) { return dsType.equals(DataSourceType.INFORMATIONAL.name()); } private Metric normalize(Metric m, long stepBoundary) { NormalizedValue normalizedValue = cache.get(m.getConfig()); if (normalizedValue == null) { normalizedValue = new NormalizedValue(); cache.put(m.getConfig(), normalizedValue); } double value = normalizedValue.updateAndGet(m.getTimestamp(), m.getNumberValue().doubleValue()); return new Metric(m.getConfig(), stepBoundary, value); } /** * {@inheritDoc} */ @Override public void update(List<Metric> metrics) { Preconditions.checkNotNull(metrics, "metrics"); final List<Metric> newMetrics = new ArrayList<>(metrics.size()); for (Metric m : metrics) { long offset = m.getTimestamp() % stepMillis; long stepBoundary = m.getTimestamp() - offset; String dsType = getDataSourceType(m); if (isGauge(dsType) || isNormalized(dsType)) { Metric atStepBoundary = new Metric(m.getConfig(), stepBoundary, m.getValue()); newMetrics.add(atStepBoundary); // gauges are not normalized } else if (isRate(dsType)) { Metric normalized = normalize(m, stepBoundary); if (normalized != null) { newMetrics.add(normalized); } } else if (!isInformational(dsType)) { // unknown type - use a safe fallback newMetrics.add(m); // we cannot normalize this } } observer.update(newMetrics); } /** * {@inheritDoc} */ @Override public String getName() { return observer.getName(); } private static final long NO_PREVIOUS_UPDATE = -1L; private class NormalizedValue { private long lastUpdateTime = NO_PREVIOUS_UPDATE; private double lastValue = 0.0; private double weightedValue(long offset, double value) { double weight = (double) offset / stepMillis; return value * weight; } double updateAndGet(long timestamp, double value) { double result = Double.NaN; if (timestamp > lastUpdateTime) { if (lastUpdateTime > 0 && timestamp - lastUpdateTime > heartbeatMillis) { lastUpdateTime = NO_PREVIOUS_UPDATE; lastValue = 0.0; } long offset = timestamp % stepMillis; long stepBoundary = timestamp - offset; if (lastUpdateTime < stepBoundary) { if (lastUpdateTime != NO_PREVIOUS_UPDATE) { long intervalOffset = lastUpdateTime % stepMillis; lastValue += weightedValue(stepMillis - intervalOffset, value); result = lastValue; } else if (offset == 0) { result = value; } else { result = weightedValue(stepMillis - offset, value); } lastValue = weightedValue(offset, value); } else { // Didn't cross step boundary, so update is more frequent than step // and we just need to // add in the weighted value long intervalOffset = timestamp - lastUpdateTime; lastValue += weightedValue(intervalOffset, value); result = lastValue; } } lastUpdateTime = timestamp; return result; } } }
Java
public class TableUtil { static Table newTable(Database database, int type, HsqlName tableHsqlName) { switch (type) { case TableBase.TEMP_TEXT_TABLE : case TableBase.TEXT_TABLE : { return new TextTable(database, tableHsqlName, type); } default : { return new Table(database, tableHsqlName, type); } } } static TableDerived newSubqueryTable(Database database, QueryExpression queryExpression) { HsqlName name = database.nameManager.getSubqueryTableName(); try { return new TableDerived(database, name, TableBase.SYSTEM_SUBQUERY, queryExpression); } catch (Exception e) { return null; } } static Table newLookupTable(Database database) { try { TableDerived table = TableUtil.newSubqueryTable(database, null); ColumnSchema column = new ColumnSchema(HsqlNameManager.getAutoColumnName(0), Type.SQL_INTEGER, false, true, null); table.addColumn(column); table.createPrimaryKey(new int[]{ 0 }); return table; } catch (HsqlException e) { return null; } } /** * For table subqueries */ static void setTableColumnsForSubquery(Table table, QueryExpression queryExpression, boolean fullIndex) { table.columnList = queryExpression.getColumns(); table.columnCount = queryExpression.getColumnCount(); table.createPrimaryKey(); if (fullIndex) { int[] colIndexes = null; colIndexes = table.getNewColumnMap(); ArrayUtil.fillSequence(colIndexes); table.fullIndex = table.createIndexForColumns(colIndexes); } } static void setTableColumnsForSubquery(Table table, Type[] types, boolean fullIndex) { addAutoColumns(table, types); table.createPrimaryKey(); if (fullIndex) { int[] colIndexes = null; colIndexes = table.getNewColumnMap(); ArrayUtil.fillSequence(colIndexes); table.fullIndex = table.createIndexForColumns(colIndexes); } } public static void addAutoColumns(Table table, Type[] colTypes) { for (int i = 0; i < colTypes.length; i++) { ColumnSchema column = new ColumnSchema(HsqlNameManager.getAutoColumnName(i), colTypes[i], true, false, null); table.addColumnNoCheck(column); } } public static void setColumnsInSchemaTable(Table table, HsqlName[] columnNames, Type[] columnTypes) { for (int i = 0; i < columnNames.length; i++) { HsqlName columnName = columnNames[i]; columnName = table.database.nameManager.newColumnSchemaHsqlName( table.getName(), columnName); ColumnSchema column = new ColumnSchema(columnName, columnTypes[i], true, false, null); table.addColumn(column); } table.setColumnStructures(); } public static void updateColumnTypes(Table tbl, Type[] finalTypes) { if (tbl.columnCount != finalTypes.length) { throw Error.error("Column type mismatch in WITH query."); } for (int idx = 0; idx < finalTypes.length; idx += 1) { tbl.colTypes[idx] = finalTypes[idx]; } } }
Java
@ApiModel(description = "Informasjon on tiltak") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2019-11-27T10:31:32.432+01:00") public class Tiltak { @JsonProperty("datoFraOgMed") private String datoFraOgMed = null; @JsonProperty("datoTil") private String datoTil = null; @JsonProperty("kilde") private String kilde = null; @JsonProperty("type") private Kode type = null; public Tiltak datoFraOgMed(String datoFraOgMed) { this.datoFraOgMed = datoFraOgMed; return this; } /** * Dato gyldig, format (ISO-8601): yyyy-MM-dd * @return datoFraOgMed **/ @JsonProperty("datoFraOgMed") @ApiModelProperty(example = "2015-12-15", value = "Dato gyldig, format (ISO-8601): yyyy-MM-dd") public String getDatoFraOgMed() { return datoFraOgMed; } public void setDatoFraOgMed(String datoFraOgMed) { this.datoFraOgMed = datoFraOgMed; } public Tiltak datoTil(String datoTil) { this.datoTil = datoTil; return this; } /** * Dato til når informasjonen er gyldig, format (ISO-8601): yyyy-MM-dd * @return datoTil **/ @JsonProperty("datoTil") @ApiModelProperty(example = "2016-09-11", value = "Dato til når informasjonen er gyldig, format (ISO-8601): yyyy-MM-dd") public String getDatoTil() { return datoTil; } public void setDatoTil(String datoTil) { this.datoTil = datoTil; } public Tiltak kilde(String kilde) { this.kilde = kilde; return this; } /** * Get kilde * @return kilde **/ @JsonProperty("kilde") @ApiModelProperty(value = "") public String getKilde() { return kilde; } public void setKilde(String kilde) { this.kilde = kilde; } public Tiltak type(Kode type) { this.type = type; return this; } /** * Get type * @return type **/ @JsonProperty("type") @ApiModelProperty(value = "") public Kode getType() { return type; } public void setType(Kode type) { this.type = type; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Tiltak tiltak = (Tiltak) o; return Objects.equals(this.datoFraOgMed, tiltak.datoFraOgMed) && Objects.equals(this.datoTil, tiltak.datoTil) && Objects.equals(this.kilde, tiltak.kilde) && Objects.equals(this.type, tiltak.type); } @Override public int hashCode() { return Objects.hash(datoFraOgMed, datoTil, kilde, type); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tiltak {\n"); sb.append(" datoFraOgMed: ").append(toIndentedString(datoFraOgMed)).append("\n"); sb.append(" datoTil: ").append(toIndentedString(datoTil)).append("\n"); sb.append(" kilde: ").append(toIndentedString(kilde)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
Java
public class SitemapPage extends WebPage { @SpringBean private GoogleSitemapGenerator sitemapGenerator; /** * Constructor */ public SitemapPage() { Label sitemap = new Label("sitemap", sitemapGenerator.run(this)); sitemap.setRenderBodyOnly(true); sitemap.setEscapeModelStrings(false); add(sitemap); } /** * {@inheritDoc} */ @Override protected void configureResponse(WebResponse response) { super.configureResponse(response); response.setContentType("text/xml"); } }
Java
@Entity("orgs") public class Organization { @Id public String name; @Indexed(value = IndexDirection.ASC, name = "", unique = false, dropDups = false, background = false, sparse = false, expireAfterSeconds = -1) public Date created; @Version("v") public long version; public Organization() { } public Organization(final String name) { this.name = name; } }
Java
public abstract class AbstractJpaPersistenceTest { protected EntityManager em; protected CriteriaBuilderFactory cbf; @Before public void init() { Properties properties = new Properties(); properties.put("javax.persistence.jdbc.url", "jdbc:h2:mem:test;INIT=CREATE SCHEMA IF NOT EXISTS TEST"); properties.put("javax.persistence.jdbc.user", "admin"); properties.put("javax.persistence.jdbc.password", "admin"); properties.put("javax.persistence.jdbc.driver", "org.h2.Driver"); EntityManagerFactory factory = createEntityManagerFactory("TestsuiteBase", applyProperties(properties)); em = factory.createEntityManager(); CriteriaBuilderConfiguration config = Criteria.getDefault(); config = configure(config); cbf = config.createCriteriaBuilderFactory(); } @After public void destruct() { em.getEntityManagerFactory() .close(); } protected abstract Class<?>[] getEntityClasses(); protected CriteriaBuilderConfiguration configure(CriteriaBuilderConfiguration config) { return config; } protected Properties applyProperties(Properties properties) { return properties; } private EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { MutablePersistenceUnitInfo persistenceUnitInfo = new MutablePersistenceUnitInfo(); persistenceUnitInfo.setPersistenceUnitName(persistenceUnitName); persistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL); persistenceUnitInfo.setExcludeUnlistedClasses(true); try { URL url = AbstractJpaPersistenceTest.class.getClassLoader() .getResource(""); persistenceUnitInfo.setPersistenceUnitRootUrl(url); } catch (Exception ex) { throw new RuntimeException(ex); } for (Class<?> clazz : getEntityClasses()) { persistenceUnitInfo.addManagedClassName(clazz.getName()); } return createEntityManagerFactory(persistenceUnitInfo, properties); } private static EntityManagerFactory createEntityManagerFactory(PersistenceUnitInfo persistenceUnitInfo, Map properties) { EntityManagerFactory factory = null; Map props = properties; if (props == null) { props = Collections.EMPTY_MAP; } PersistenceProviderResolver resolver = PersistenceProviderResolverHolder.getPersistenceProviderResolver(); List<PersistenceProvider> providers = resolver.getPersistenceProviders(); Map<String, Throwable> exceptions = new HashMap<String, Throwable>(); StringBuffer foundProviders = null; for (PersistenceProvider provider : providers) { String providerName = provider.getClass() .getName(); try { factory = provider.createContainerEntityManagerFactory(persistenceUnitInfo, props); } catch (Exception e) { // capture the exception details and give other providers a chance exceptions.put(providerName, e); } if (factory != null) { // we're done return factory; } else { // update the list of providers we have tried if (foundProviders == null) { foundProviders = new StringBuffer(providerName); } else { foundProviders.append(", "); foundProviders.append(providerName); } } } // make sure our providers list is initialized for the exceptions below if (foundProviders == null) { foundProviders = new StringBuffer("NONE"); } if (exceptions.isEmpty()) { // throw an exception with the PU name and providers we tried throw new PersistenceException("No persistence providers available for \"" + persistenceUnitInfo .getPersistenceUnitName() + "\" after trying the following discovered implementations: " + foundProviders); } else { // we encountered one or more exceptions, so format and throw as a single exception throw createPersistenceException( "Explicit persistence provider error(s) occurred for \"" + persistenceUnitInfo.getPersistenceUnitName() + "\" after trying the following discovered implementations: " + foundProviders, exceptions); } } private static PersistenceException createPersistenceException(String msg, Map<String, Throwable> failures) { String newline = System.getProperty("line.separator"); StringWriter strWriter = new StringWriter(); strWriter.append(msg); if (failures.size() <= 1) { // we caught an exception, so include it as the cause Throwable t = null; for (String providerName : failures.keySet()) { t = failures.get(providerName); strWriter.append(" from provider: "); strWriter.append(providerName); break; } return new PersistenceException(strWriter.toString(), t); } else { // we caught multiple exceptions, so format them into the message string and don't set a cause strWriter.append(" with the following failures:"); strWriter.append(newline); for (String providerName : failures.keySet()) { strWriter.append(providerName); strWriter.append(" returned: "); failures.get(providerName) .printStackTrace(new PrintWriter(strWriter)); } strWriter.append(newline); return new PersistenceException(strWriter.toString()); } } }
Java
public class ServiceTemplateImpl extends AbstractServiceTemplate { private final static Logger LOG = LoggerFactory.getLogger(ServiceTemplateImpl.class); private TServiceTemplate serviceTemplate = null; private AbstractTopologyTemplate topologyTemplate = null; private DefinitionsImpl definitions = null; /** * Constructor * * @param serviceTemplate a JAXB TServiceTemplate * @param definitionsImpl a DefinitionsImpl */ public ServiceTemplateImpl(final TServiceTemplate serviceTemplate, final DefinitionsImpl definitionsImpl) { this.serviceTemplate = serviceTemplate; this.definitions = definitionsImpl; this.setUpTopologyTemplate(); } /** * {@inheritDoc} */ @Override public AbstractTopologyTemplate getTopologyTemplate() { return this.topologyTemplate; } /** * Sets the TopologyTemplate of this ServiceTemplate * * @param topologyTemplate an AbstractTopologyTemplate */ public void setTopologyTemplate(final AbstractTopologyTemplate topologyTemplate) { this.topologyTemplate = topologyTemplate; } /** * Initializes the internal TopologyTemplate of this ServiceTemplate */ private void setUpTopologyTemplate() { this.topologyTemplate = new TopologyTemplateImpl(this.serviceTemplate.getTopologyTemplate(), this.definitions, this.getQName()); } /** * {@inheritDoc} */ @Override public String getTargetNamespace() { if (this.serviceTemplate.getTargetNamespace() == null) { ServiceTemplateImpl.LOG.warn("TargetNamespace of ServiceTemplate {} is null!", this.getId()); } return this.serviceTemplate.getTargetNamespace(); } /** * {@inheritDoc} */ @Override public String getId() { if (this.serviceTemplate.getId() == null) { ServiceTemplateImpl.LOG.warn("Id of ServiceTemplate is null"); } return this.serviceTemplate.getId(); } /** * {@inheritDoc} */ @Override public String getName() { return this.serviceTemplate.getName(); } /** * {@inheritDoc} */ @Override public QName getQName() { String namespace = this.getTargetNamespace(); if (namespace == null) { namespace = this.definitions.getTargetNamespace(); } final String id = this.getId(); return new QName(namespace, id); } /** * {@inheritDoc} */ @Override public AbstractBoundaryDefinitions getBoundaryDefinitions() { if (this.serviceTemplate.getBoundaryDefinitions() != null) { return new BoundaryDefinitionsImpl(this.serviceTemplate.getBoundaryDefinitions()); } else { return null; } } /** * {@inheritDoc} */ @Override public boolean hasBuildPlan() { if (this.serviceTemplate.getPlans() != null) { final TPlans plans = this.serviceTemplate.getPlans(); final List<TPlan> plans2 = plans.getPlan(); ServiceTemplateImpl.LOG.debug("Checking whether ServiceTemplate {} has no BuildPlan", this.getQName().toString()); for (final TPlan plan : plans.getPlan()) { ServiceTemplateImpl.LOG.debug("Checking Plan {} of Type {}", plan.getId(), plan.getPlanType()); if (plan.getPlanType().trim() .equals("http://docs.oasis-open.org/tosca/ns/2011/12/PlanTypes/BuildPlan")) { return true; } } } return false; } @Override public boolean hasTerminationPlan() { if (this.serviceTemplate.getPlans() != null) { final TPlans plans = this.serviceTemplate.getPlans(); final List<TPlan> plans2 = plans.getPlan(); ServiceTemplateImpl.LOG.debug("Checking whether ServiceTemplate {} has no TerminationPlan", this.getQName().toString()); for (final TPlan plan : plans.getPlan()) { ServiceTemplateImpl.LOG.debug("Checking Plan {} of Type {}", plan.getId(), plan.getPlanType()); if (plan.getPlanType().trim() .equals("http://docs.oasis-open.org/tosca/ns/2011/12/PlanTypes/TerminationPlan")) { return true; } } } return false; } @Override public Map<String, String> getTags() { final Map<String, String> tags = new HashMap<>(); if (this.serviceTemplate.getTags() == null) { return tags; } else if (this.serviceTemplate.getTags().getTag() == null) { return tags; } for (final TTag tag : this.serviceTemplate.getTags().getTag()) { tags.put(tag.getName(), tag.getValue()); } return tags; } }
Java
public class CompactDiskJavaDBDAO implements CompactDiskDAO { String connectionURL; String connectionUsername; String connectionPassword; /** * Creates a Database Access Object with default connection parameters. */ public CompactDiskJavaDBDAO() { this("jdbc:derby://localhost:1527/CD_DATABASE", "app", "app"); } /** * Creates a Database Access Object with given connection parameters. * * @param url String URL with database name * @param username String username for connect to the database * @param password String password for connect to the database */ public CompactDiskJavaDBDAO(String url, String username, String password) { this.connectionURL = url; this.connectionUsername = username; this.connectionPassword = password; //Check whether Database and table exist or not. //If not, create the database and table structure with some dummy data. try { Connection con = DriverManager.getConnection(connectionURL + ";create=true", connectionUsername, connectionPassword); ResultSet rs = con.getMetaData().getTables(null, null, "COMPACTDISK", null); if (!rs.next()) { con.prepareStatement("CREATE TABLE COMPACTDISK(" + "DISK_ID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY(START WITH 1, INCREMENT BY 1), " + "DISK_TITLE VARCHAR(32) DEFAULT 'not available' NOT NULL, " + "DISK_ARTIST VARCHAR(32) DEFAULT 'not available' NOT NULL, " + "DISK_COUNTRY VARCHAR(32) DEFAULT 'not available' NOT NULL, " + "DISK_PRICE VARCHAR(32) DEFAULT 'not available' NOT NULL, " + "DISK_YEAR VARCHAR(32) DEFAULT 'not available' NOT NULL)").executeUpdate(); con.prepareStatement("INSERT INTO APP.COMPACTDISK (DISK_TITLE, DISK_ARTIST, DISK_COUNTRY, DISK_PRICE, DISK_YEAR) VALUES ('Thriller', 'Michael Jackson', 'USA', '480', '1982')").executeUpdate(); con.prepareStatement("INSERT INTO APP.COMPACTDISK (DISK_TITLE, DISK_ARTIST, DISK_COUNTRY, DISK_PRICE, DISK_YEAR) VALUES ('SremmLife', 'Rae Sremmurd', 'USA', '250', '2015')").executeUpdate(); con.prepareStatement("INSERT INTO APP.COMPACTDISK (DISK_TITLE, DISK_ARTIST, DISK_COUNTRY, DISK_PRICE, DISK_YEAR) VALUES ('Their Greatest Hits', 'Eagles', 'USA', '400', '1976')").executeUpdate(); con.prepareStatement("INSERT INTO APP.COMPACTDISK (DISK_TITLE, DISK_ARTIST, DISK_COUNTRY, DISK_PRICE, DISK_YEAR) VALUES ('Dangerous', 'Michael Jackson', 'USA', '450', '1991')").executeUpdate(); con.prepareStatement("INSERT INTO APP.COMPACTDISK (DISK_TITLE, DISK_ARTIST, DISK_COUNTRY, DISK_PRICE, DISK_YEAR) VALUES ('Nevermind', 'Nirvana', 'USA', '400', '1991')").executeUpdate(); con.prepareStatement("INSERT INTO APP.COMPACTDISK (DISK_TITLE, DISK_ARTIST, DISK_COUNTRY, DISK_PRICE, DISK_YEAR) VALUES ('Appetite for Destruction', 'Guns N Roses', 'USA', '320', '1987')").executeUpdate(); con.prepareStatement("INSERT INTO APP.COMPACTDISK (DISK_TITLE, DISK_ARTIST, DISK_COUNTRY, DISK_PRICE, DISK_YEAR) VALUES ('Nawa Ridma', 'Sunil Edirisinghe', 'Sri Lanka', '150', '2000')").executeUpdate(); con.prepareStatement("INSERT INTO APP.COMPACTDISK (DISK_TITLE, DISK_ARTIST, DISK_COUNTRY, DISK_PRICE, DISK_YEAR) VALUES ('Vasanthaye', 'Bathiya and Santhush', 'Sri Lanka', '150', '2003')").executeUpdate(); } con.close(); } catch (SQLException ex) { System.err.println(ex.getMessage()); } } /** * Returns all Compact Disks currently available * * @return ArrayList containing all CompactDisks */ @Override public ArrayList<CompactDisk> getAll() { String query = "SELECT * FROM COMPACTDISK"; return executeFetchQuery(query); } /** * Returns the CompactDisk that matches with given ID * * @param id Disk ID of the CompactDisk * @return CompactDisk that matches with given ID */ @Override public CompactDisk getByID(int id) { ArrayList<CompactDisk> compact_disk_set = new ArrayList<>(); String query = "SELECT * FROM COMPACTDISK WHERE DISK_ID=" + id; return executeFetchQuery(query).get(0); } /** * Returns all CompactDisks that matches with given values. Blank fields * will be considered as "anything" when searching. * * @param compact_disk CompactDisk that contains search values * @return ArrayList containing all CompactDisks that matches with search * values */ @Override public ArrayList<CompactDisk> searchCD(CompactDisk compact_disk) { // Since price and year are numbers we cant use as same way other fields doese. // Only if it is empty, the string will be repacced with %%. // Otherwise search with exact number rather than a part of number. String price = "".equals(compact_disk.getDiskPrice().replaceAll("\\s+", "")) ? "%%" : compact_disk.getDiskPrice(); String year = "".equals(compact_disk.getDiskYear().replaceAll("\\s+", "")) ? "%%" : compact_disk.getDiskYear(); String query = "SELECT * FROM COMPACTDISK WHERE " + "DISK_TITLE LIKE '%" + compact_disk.getDiskTitle() + "%' AND " + "DISK_ARTIST LIKE '%" + compact_disk.getDiskArtist() + "%' AND " + "DISK_COUNTRY LIKE '%" + compact_disk.getDiskCountry() + "%' AND " + "DISK_PRICE LIKE '" + price + "' AND " + "DISK_YEAR LIKE '" + year + "'"; return executeFetchQuery(query); } /** * Add new CompactDisk. Disk ID will be auto generated. All other fields * must be filled with valid data. * * @param compact_disk CompactDisk to be added * @return true if CompactDisk was successfully added, otherwise false */ @Override public boolean addCompactDisk(CompactDisk compact_disk) { String query = "INSERT INTO COMPACTDISK(DISK_TITLE,DISK_ARTIST,DISK_COUNTRY,DISK_PRICE,DISK_YEAR) " + "VALUES('" + compact_disk.getDiskTitle() + "','" + compact_disk.getDiskArtist() + "','" + compact_disk.getDiskCountry() + "','" + compact_disk.getDiskPrice() + "','" + compact_disk.getDiskYear() + "')"; return executeModifyQuery(query); } /** * Update existing CompactDisk. Disk ID can not be updated. All fields must * be filled with valid data. * * @param compact_disk CompactDisk to be updated * @return true if CompactDisk was successfully updated, otherwise false */ @Override public boolean updateCompactDisk(CompactDisk compact_disk) { String query = "UPDATE COMPACTDISK SET DISK_TITLE='" + compact_disk.getDiskTitle() + "',DISK_ARTIST='" + compact_disk.getDiskArtist() + "',DISK_COUNTRY='" + compact_disk.getDiskCountry() + "',DISK_PRICE='" + compact_disk.getDiskPrice() + "',DISK_YEAR='" + compact_disk.getDiskYear() + "' WHERE DISK_ID=" + compact_disk.getDiskId(); return executeModifyQuery(query); } /** * Delete existing CompactDisk * * @param disk_id Disk ID of the CompactDisk to be deleted * @return true if CompactDisk was successfully deleted, otherwise false */ @Override public boolean deleteCompactDisk(int disk_id) { String query = "DELETE FROM COMPACTDISK WHERE DISK_ID=" + disk_id; return executeModifyQuery(query); } /** * Modify or Update any data in the database by executing a SQL query. To * fetch data from database, use executeFetchQuery() method instead of this. * * @param query String SQL query to do any modification to the data * @return true if SQL query was successfully executed, otherwise false */ private boolean executeModifyQuery(String query) { try { Connection con = DriverManager.getConnection(connectionURL, connectionUsername, connectionPassword); PreparedStatement ps = con.prepareStatement(query); int i = ps.executeUpdate(); ps.close(); con.close(); return i > 0; } catch (Exception ex) { System.err.println(ex.getMessage()); return false; } } /** * Select or Fetch any data from the database by executing a SQL query. * * @param query String SQL query to select data from database * @return ArrayList containing all CompactDisk that matches with the SQL * query */ private ArrayList<CompactDisk> executeFetchQuery(String query) { ResultSet result_set; ArrayList<CompactDisk> compact_disk_set = new ArrayList<>(); try { Connection con = DriverManager.getConnection(connectionURL, connectionUsername, connectionPassword); PreparedStatement ps = con.prepareStatement(query); result_set = ps.executeQuery(); while (result_set.next()) { CompactDisk compact_disk = new CompactDisk(); compact_disk.setDiskId(result_set.getInt("DISK_ID")); compact_disk.setDiskTitle(result_set.getString("DISK_TITLE")); compact_disk.setDiskArtist(result_set.getString("DISK_ARTIST")); compact_disk.setDiskCountry(result_set.getString("DISK_COUNTRY")); compact_disk.setDiskPrice(result_set.getString("DISK_PRICE")); compact_disk.setDiskYear(result_set.getString("DISK_YEAR")); compact_disk_set.add(compact_disk); } ps.close(); con.close(); } catch (SQLException ex) { System.err.println(ex.getMessage()); } return compact_disk_set; } }
Java
@ProjectGenerationConfiguration @ConditionalOnBuildSystem(GradleBuildSystem.ID) public class GradleProjectGenerationConfiguration { private final IndentingWriterFactory indentingWriterFactory; public GradleProjectGenerationConfiguration(IndentingWriterFactory indentingWriterFactory) { this.indentingWriterFactory = indentingWriterFactory; } @Bean public GradleBuild gradleBuild(ObjectProvider<BuildItemResolver> buildItemResolver, ObjectProvider<BuildCustomizer<?>> buildCustomizers) { return createGradleBuild(buildItemResolver.getIfAvailable(), buildCustomizers.orderedStream().collect(Collectors.toList())); } @SuppressWarnings("unchecked") private GradleBuild createGradleBuild(BuildItemResolver buildItemResolver, List<BuildCustomizer<?>> buildCustomizers) { GradleBuild build = (buildItemResolver != null) ? new GradleBuild(buildItemResolver) : new GradleBuild(); LambdaSafe.callbacks(BuildCustomizer.class, buildCustomizers, build) .invoke((customizer) -> customizer.customize(build)); return build; } @Bean public BuildCustomizer<GradleBuild> defaultGradleBuildCustomizer(ProjectDescription description) { return (build) -> build.settings().sourceCompatibility(description.getLanguage().jvmVersion()); } @Bean public GradleConfigurationBuildCustomizer gradleConfigurationBuildCustomizer() { return new GradleConfigurationBuildCustomizer(); } @Bean @ConditionalOnLanguage(JavaLanguage.ID) public BuildCustomizer<GradleBuild> javaPluginContributor() { return (build) -> build.plugins().add("java"); } @Bean @ConditionalOnPackaging(WarPackaging.ID) public BuildCustomizer<GradleBuild> warPluginContributor() { return (build) -> build.plugins().add("war"); } @Bean @ConditionalOnGradleVersion({ "4", "5" }) BuildCustomizer<GradleBuild> springBootPluginContributor(ProjectDescription description, ObjectProvider<DependencyManagementPluginVersionResolver> versionResolver, InitializrMetadata metadata) { return new SpringBootPluginBuildCustomizer(description, versionResolver .getIfAvailable(() -> new InitializrDependencyManagementPluginVersionResolver(metadata))); } @Bean @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) public GradleBuildProjectContributor gradleBuildProjectContributor(GroovyDslGradleBuildWriter buildWriter, GradleBuild build) { return new GradleBuildProjectContributor(buildWriter, build, this.indentingWriterFactory, "build.gradle"); } @Bean @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) public GradleBuildProjectContributor gradleKtsBuildProjectContributor(KotlinDslGradleBuildWriter buildWriter, GradleBuild build) { return new GradleBuildProjectContributor(buildWriter, build, this.indentingWriterFactory, "build.gradle.kts"); } /** * Configuration specific to projects using Gradle 3. */ @Configuration @ConditionalOnGradleVersion("3") @ConditionalOnBuildSystem(GradleBuildSystem.ID) static class Gradle3ProjectGenerationConfiguration { @Bean Gradle3BuildWriter gradleBuildWriter() { return new Gradle3BuildWriter(); } @Bean GradleWrapperContributor gradle3WrapperContributor() { return new GradleWrapperContributor("3"); } @Bean Gradle3SettingsGradleProjectContributor settingsGradleProjectContributor(GradleBuild build) { return new Gradle3SettingsGradleProjectContributor(build); } @Bean BuildCustomizer<GradleBuild> springBootPluginContributor(ProjectDescription description) { return (build) -> { build.buildscript((buildscript) -> buildscript.dependency( "org.springframework.boot:spring-boot-gradle-plugin:" + description.getPlatformVersion())); build.plugins().apply("org.springframework.boot"); }; } } /** * Configuration specific to projects using Gradle 4. */ @Configuration @ConditionalOnGradleVersion("4") @ConditionalOnBuildSystem(GradleBuildSystem.ID) static class Gradle4ProjectGenerationConfiguration { @Bean GradleWrapperContributor gradle4WrapperContributor() { return new GradleWrapperContributor("4"); } } /** * Configuration specific to projects using Gradle 5. */ @Configuration @ConditionalOnGradleVersion("5") static class Gradle5ProjectGenerationConfiguration { @Bean GradleWrapperContributor gradle4WrapperContributor() { return new GradleWrapperContributor("5"); } } /** * Configuration specific to projects using Gradle (Groovy DSL) 4 or 5. */ @Configuration @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) @ConditionalOnGradleVersion({ "4", "5" }) static class Gradle4Or5ProjectGenerationConfiguration { @Bean GroovyDslGradleBuildWriter gradleBuildWriter() { return new GroovyDslGradleBuildWriter(); } @Bean SettingsGradleProjectContributor settingsGradleProjectContributor(GradleBuild build, IndentingWriterFactory indentingWriterFactory) { return new SettingsGradleProjectContributor(build, indentingWriterFactory, new GroovyDslGradleSettingsWriter(), "settings.gradle"); } @Bean @ConditionalOnPlatformVersion("2.2.0.M3") BuildCustomizer<GradleBuild> testTaskContributor() { return (build) -> build.tasks().customize("test", (test) -> test.invoke("useJUnitPlatform")); } @Bean GradleAnnotationProcessorScopeBuildCustomizer gradleAnnotationProcessorScopeBuildCustomizer() { return new GradleAnnotationProcessorScopeBuildCustomizer(); } } /** * Configuration specific to projects using Gradle (Kotlin DSL). */ @Configuration @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) @ConditionalOnGradleVersion("5") static class GradleKtsProjectGenerationConfiguration { @Bean KotlinDslGradleBuildWriter gradleKtsBuildWriter() { return new KotlinDslGradleBuildWriter(); } @Bean SettingsGradleProjectContributor settingsGradleKtsProjectContributor(GradleBuild build, IndentingWriterFactory indentingWriterFactory) { return new SettingsGradleProjectContributor(build, indentingWriterFactory, new KotlinDslGradleSettingsWriter(), "settings.gradle.kts"); } @Bean @ConditionalOnPlatformVersion("2.2.0.M3") BuildCustomizer<GradleBuild> testTaskContributor() { return (build) -> build.tasks().customizeWithType("Test", (test) -> test.invoke("useJUnitPlatform")); } @Bean GradleAnnotationProcessorScopeBuildCustomizer gradleAnnotationProcessorScopeBuildCustomizer() { return new GradleAnnotationProcessorScopeBuildCustomizer(); } } }
Java
@Configuration @ConditionalOnGradleVersion("3") @ConditionalOnBuildSystem(GradleBuildSystem.ID) static class Gradle3ProjectGenerationConfiguration { @Bean Gradle3BuildWriter gradleBuildWriter() { return new Gradle3BuildWriter(); } @Bean GradleWrapperContributor gradle3WrapperContributor() { return new GradleWrapperContributor("3"); } @Bean Gradle3SettingsGradleProjectContributor settingsGradleProjectContributor(GradleBuild build) { return new Gradle3SettingsGradleProjectContributor(build); } @Bean BuildCustomizer<GradleBuild> springBootPluginContributor(ProjectDescription description) { return (build) -> { build.buildscript((buildscript) -> buildscript.dependency( "org.springframework.boot:spring-boot-gradle-plugin:" + description.getPlatformVersion())); build.plugins().apply("org.springframework.boot"); }; } }
Java
@Configuration @ConditionalOnGradleVersion("4") @ConditionalOnBuildSystem(GradleBuildSystem.ID) static class Gradle4ProjectGenerationConfiguration { @Bean GradleWrapperContributor gradle4WrapperContributor() { return new GradleWrapperContributor("4"); } }
Java
@Configuration @ConditionalOnGradleVersion("5") static class Gradle5ProjectGenerationConfiguration { @Bean GradleWrapperContributor gradle4WrapperContributor() { return new GradleWrapperContributor("5"); } }
Java
@Configuration @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_GROOVY) @ConditionalOnGradleVersion({ "4", "5" }) static class Gradle4Or5ProjectGenerationConfiguration { @Bean GroovyDslGradleBuildWriter gradleBuildWriter() { return new GroovyDslGradleBuildWriter(); } @Bean SettingsGradleProjectContributor settingsGradleProjectContributor(GradleBuild build, IndentingWriterFactory indentingWriterFactory) { return new SettingsGradleProjectContributor(build, indentingWriterFactory, new GroovyDslGradleSettingsWriter(), "settings.gradle"); } @Bean @ConditionalOnPlatformVersion("2.2.0.M3") BuildCustomizer<GradleBuild> testTaskContributor() { return (build) -> build.tasks().customize("test", (test) -> test.invoke("useJUnitPlatform")); } @Bean GradleAnnotationProcessorScopeBuildCustomizer gradleAnnotationProcessorScopeBuildCustomizer() { return new GradleAnnotationProcessorScopeBuildCustomizer(); } }
Java
@Configuration @ConditionalOnBuildSystem(id = GradleBuildSystem.ID, dialect = GradleBuildSystem.DIALECT_KOTLIN) @ConditionalOnGradleVersion("5") static class GradleKtsProjectGenerationConfiguration { @Bean KotlinDslGradleBuildWriter gradleKtsBuildWriter() { return new KotlinDslGradleBuildWriter(); } @Bean SettingsGradleProjectContributor settingsGradleKtsProjectContributor(GradleBuild build, IndentingWriterFactory indentingWriterFactory) { return new SettingsGradleProjectContributor(build, indentingWriterFactory, new KotlinDslGradleSettingsWriter(), "settings.gradle.kts"); } @Bean @ConditionalOnPlatformVersion("2.2.0.M3") BuildCustomizer<GradleBuild> testTaskContributor() { return (build) -> build.tasks().customizeWithType("Test", (test) -> test.invoke("useJUnitPlatform")); } @Bean GradleAnnotationProcessorScopeBuildCustomizer gradleAnnotationProcessorScopeBuildCustomizer() { return new GradleAnnotationProcessorScopeBuildCustomizer(); } }
Java
public class DAGRTaskNode extends GenericActionNode { private static final Logger LOGGER = Logger.getLogger(DAGRTaskNode.class); private ProcessInfo processInfo = new ProcessInfo(); private DAGTaskNode dagTaskNode = null; private static final String UPLOADBASEDIRECTORY = "upload.base-directory"; /** * This constructor is used to set node id and process information. * * @param dagTaskNode An instance of ActionNode class which a workflow triggers the execution of a task. */ public DAGRTaskNode(DAGTaskNode dagTaskNode) { setId(dagTaskNode.getId()); processInfo = dagTaskNode.getProcessInfo(); this.dagTaskNode = dagTaskNode; } public ProcessInfo getProcessInfo() { return processInfo; } public String getName() { String nodeName = "R_" + getId() + "_" + processInfo.getProcessName().replace(' ', '_'); return nodeName.substring(0, Math.min(nodeName.length(), 45)); } @Override public String getDAG() { String homeDir = System.getProperty("user.home"); //ProcessDAO processDAO = new ProcessDAO(); GetParentProcessType getParentProcessType = new GetParentProcessType(); if (this.getProcessInfo().getParentProcessId() == 0) { return ""; } StringBuilder ret = new StringBuilder(); ret.append("\ndef "+ getName()+"_pc():\n" + "\tcommand='sh "+ homeDir+"/bdre/bdre-scripts/deployment/Rhadoop.sh "+homeDir + "/bdre_apps/" + processInfo.getBusDomainId().toString()+"/" + getParentProcessType.getParentProcessTypeId(processInfo.getParentProcessId())+"/"+ processInfo.getParentProcessId().toString() + "/" + getRFile(getId(), "r-file")+ " "+getArguments("param")+"',\n" + "\tbash_output = subprocess.Popen(command,shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE )\n" + "\tout,err = bash_output.communicate()\n"+ "\tlogger.info(\"out is \"+str(out))\n"+ "\tlogger.info(\"err is \"+str(err))\n"+ "\tif(bash_output.returncode != 0):\n" + "\t\treturn '"+getTermNode().getName() +"'\n" + "\telse:\n" + "\t\treturn '"+getToNode().getName() +"'\n" + "\ndef f_"+ getName()+"():\n" + "\t"+ getName()+".set_downstream("+ getToNode().getName()+")\n" + "\t"+ getName()+".set_downstream("+ getTermNode().getName()+")\n" + getName()+" = BranchPythonOperator(task_id='" + getName()+"', python_callable="+getName()+"_pc, dag=dag)\n" ); try { FileWriter fw = new FileWriter(homeDir+"/defFile.txt", true); fw.write("\nf_"+getName()+"()"); fw.close(); } catch (IOException e){ System.out.println("e = " + e); } return ret.toString(); } /** * This method gets the required arguments for running the R Script * * @param configGroup config_group entry in properties table for arguments * @return String containing arguments to be appended to workflow string. */ public String getArguments(String configGroup) { GetProperties getProperties = new GetProperties(); java.util.Properties argumentProperty = getProperties.getProperties(getId().toString(), configGroup); String arguments=""; if(!argumentProperty.isEmpty()) { arguments = " " + argumentProperty.values().toString().substring(1, argumentProperty.values().toString().length() - 1); } return arguments; } /** * This method gets the required R Script file for running the R Script * * @param pid process-id of R Script * @param configGroup config_group entry in properties table "rScript" for arguments * @return String containing arguments to be appended to workflow string. */ public String getRFile(Integer pid, String configGroup) { GetProperties getProperties = new GetProperties(); java.util.Properties rScript = getProperties.getProperties(getId().toString(), configGroup); Enumeration e = rScript.propertyNames(); LOGGER.info("rScript = " + rScript.size()); StringBuilder addRScript = new StringBuilder(); if (rScript.size() > 1) { throw new BDREException("Can Handle only 1 input file in R action, process type=" + processInfo.getProcessTypeId()); } else if (rScript.isEmpty()) { addRScript.append("r/" + getId() + ".R"); } else { while (e.hasMoreElements()) { String key = (String) e.nextElement(); addRScript.append(rScript.getProperty(key)); } } return addRScript.toString(); } }
Java
public class MapBindingIntegrationTest extends GWTTestCase { @Override public String getModuleName() { return "org.jboss.errai.databinding.DataBindingTestModule"; } @Override protected void gwtSetUp() throws Exception { new DataBindingModuleBootstrapper().run(); } public void testMapWithNonBindableProperties() throws Exception { final Map<String, PropertyType> propertyTypes = new HashMap<>(); propertyTypes.put("str", new PropertyType(String.class)); propertyTypes.put("num", new PropertyType(Integer.class)); final DataBinder<Map<String, Object>> binder = DataBinder.forMap(propertyTypes); final TextBox strTextBox = new TextBox(); final IntegerBox numIntBox = new IntegerBox(); binder .bind(strTextBox, "str") .bind(numIntBox, "num"); final Map<String, Object> map = binder.getModel(); assertNotNull(map); map.put("str", "foo"); assertEquals("foo", strTextBox.getValue()); map.put("num", 42); assertEquals(Integer.valueOf(42), numIntBox.getValue()); } public void testMapWithBindableProperties() throws Exception { final Map<String, PropertyType> propertyTypes = new HashMap<>(); propertyTypes.put("list", new PropertyType(List.class, false, true)); propertyTypes.put("bindable", new PropertyType(TestModel.class, true, false)); final DataBinder<Map<String, Object>> binder = DataBinder.forMap(propertyTypes); final IntegerBox ageIntBox = new IntegerBox(); final ListComponent<String, TextBox> component = forIsWidgetComponent(TextBox::new, c -> {}).inDiv(); binder .bind(component, "list", Convert.identityConverter(List.class)) .bind(ageIntBox, "bindable.age"); final Map<String, Object> map = binder.getModel(); assertNotNull(map); map.put("bindable", new TestModel()); final TestModel model = (TestModel) map.get("bindable"); model.setAge(99); assertTrue("TestModel is not proxied.", model instanceof BindableProxy); assertEquals(Integer.valueOf(99), ageIntBox.getValue()); map.put("list", new ArrayList<>()); final List<String> list = (List<String>) map.get("list"); assertTrue("List value was not proxied.", list instanceof BindableListWrapper); list.add("moogah"); try { assertEquals("moogah", component.getComponent(0).getValue()); } catch (final AssertionError ae) { throw ae; } catch (final Throwable t) { throw new AssertionError("Component not added for list entry.", t); } } public void testMapWithBindableMap() throws Exception { final Map<String, PropertyType> innerMapPropertyTypes = new HashMap<>(); innerMapPropertyTypes.put("str", new PropertyType(String.class)); innerMapPropertyTypes.put("num", new PropertyType(Integer.class)); final Map<String, PropertyType> outerMapPropertyTypes = new HashMap<>(); outerMapPropertyTypes.put("map", new MapPropertyType(innerMapPropertyTypes)); final DataBinder<Map<String, Object>> binder = DataBinder.forMap(outerMapPropertyTypes); final TextBox strTextBox = new TextBox(); final IntegerBox numIntBox = new IntegerBox(); binder .bind(strTextBox, "map.str") .bind(numIntBox, "map.num"); final Map<String, Object> outerMap = binder.getModel(); assertNotNull(outerMap); outerMap.put("map", new HashMap<>()); final Map<String, Object> innerMap = (Map<String, Object>) outerMap.get("map"); innerMap.put("str", "foo"); assertEquals("foo", strTextBox.getValue()); innerMap.put("num", 42); assertEquals(Integer.valueOf(42), numIntBox.getValue()); } public void testPutAllUpdatesWidgets() throws Exception { final Map<String, PropertyType> propertyTypes = new HashMap<>(); propertyTypes.put("str", new PropertyType(String.class)); propertyTypes.put("num", new PropertyType(Integer.class)); final DataBinder<Map<String, Object>> binder = DataBinder.forMap(propertyTypes); final TextBox strTextBox = new TextBox(); final IntegerBox numIntBox = new IntegerBox(); binder .bind(strTextBox, "str") .bind(numIntBox, "num"); final Map<String, Object> map = binder.getModel(); assertNotNull(map); final Map<String, Object> otherMap = new HashMap<>(); otherMap.put("str", "foo"); otherMap.put("num", 42); map.putAll(otherMap); assertEquals("foo", strTextBox.getValue()); assertEquals(Integer.valueOf(42), numIntBox.getValue()); } public void testPutAllThrowsErrorForUnrecognizedProperties() throws Exception { final Map<String, PropertyType> propertyTypes = new HashMap<>(); propertyTypes.put("str", new PropertyType(String.class)); propertyTypes.put("num", new PropertyType(Integer.class)); final DataBinder<Map<String, Object>> binder = DataBinder.forMap(propertyTypes); final TextBox strTextBox = new TextBox(); final IntegerBox numIntBox = new IntegerBox(); binder .bind(strTextBox, "str") .bind(numIntBox, "num"); final Map<String, Object> map = binder.getModel(); assertNotNull(map); final Map<String, Object> otherMap = new HashMap<>(); otherMap.put("nonexistent", "foible"); try { map.putAll(otherMap); fail("Putting non-existent property into map did not cause an exception."); } catch (final NonExistingPropertyException ex) { // success } catch (final AssertionError ae) { throw ae; } catch (final Throwable t) { throw new AssertionError("Wrong exception thrown: " + t.getMessage(), t); } } }
Java
public class CallResponderTest { static HelpCallResponder callResponder = mock(HelpCallResponder.class); @Test public void testSendRoomInfo() throws Exception { Mockito.doCallRealMethod().when(callResponder).sendRoomInfo(new Long(0)); Mockito.doCallRealMethod().when(callResponder).sendRoomInfo(null); try { callResponder.sendRoomInfo(null); } catch (Exception e) { fail("send room info failed"); } try { callResponder.sendRoomInfo(new Long(0)); } catch (Exception e) { fail("send room info failed"); } } @Test public void testSendHelpSummary() throws Exception { Mockito.doCallRealMethod().when(callResponder).sendHelpSummary(null); try { callResponder.sendHelpSummary(null); } catch (Exception e) { fail("send help summary failed"); } } @Test public void testSendConnectedMessage() throws Exception { Mockito.doCallRealMethod().when(callResponder).sendConnectedMessage(null); try { callResponder.sendConnectedMessage(null); } catch (Exception e) { fail("send connected failed"); } } }
Java
public final class Float64x2Prototype extends OrdinaryObject implements Initializable { private static final SIMDType SIMD_TYPE = SIMDType.Float64x2; private static final int VECTOR_LENGTH = SIMDType.Float64x2.getVectorLength(); public Float64x2Prototype(Realm realm) { super(realm); } @Override public void initialize(Realm realm) { createProperties(realm, this, Properties.class); } /** * Properties of the SIMD.Float64x2 Prototype Object */ public enum Properties { ; private static SIMDValue thisSIMDValue(ExecutionContext cx, Object value, String method) { if (value instanceof SIMDValue) { return (SIMDValue) value; } if (!(value instanceof SIMDObject)) { throw newTypeError(cx, Messages.Key.SIMDInvalidThis, SIMD_TYPE + method, Type.of(value).toString()); } SIMDObject object = (SIMDObject) value; if (object.getData().getType() != SIMD_TYPE) { throw newTypeError(cx, Messages.Key.SIMDInvalidType); } return object.getData(); } @Prototype public static final Intrinsics __proto__ = Intrinsics.ObjectPrototype; /** * SIMDConstructor.prototype.constructor */ @Value(name = "constructor") public static final Intrinsics constructor = Intrinsics.SIMD_Float64x2; /** * SIMDConstructor.prototype.valueOf() * * @param cx * the execution context * @param thisValue * the function this-value * @return the SIMD value */ @Function(name = "valueOf", arity = 0) public static Object valueOf(ExecutionContext cx, Object thisValue) { /* steps 1-3 */ return thisSIMDValue(cx, thisValue, ".valueOf"); } /** * SIMDConstructor.prototype.toLocaleString( [ reserved1 [, reserved2 ] ) * * @param cx * the execution context * @param thisValue * the function this-value * @param locales * the optional locales array * @param options * the optional options object * @return the locale specific string representation */ @Function(name = "toLocaleString", arity = 0) public static Object toLocaleString(ExecutionContext cx, Object thisValue, Object locales, Object options) { /* steps 1-2 */ SIMDValue value = thisSIMDValue(cx, thisValue, ".toLocaleString"); /* step 3 */ // FIXME: spec issue - retrieve list separator from locale? String separator = cx.getRealm().getListSeparator(); /* step 4 */ CharSequence[] list = new CharSequence[VECTOR_LENGTH]; /* step 5 */ for (int i = 0; i < VECTOR_LENGTH; ++i) { double element = value.asDouble()[i]; /* steps 5.a-c */ list[i] = ToString(cx, Invoke(cx, element, "toLocaleString", locales, options)); } /* step 7 */ String t = SIMD_TYPE.name(); /* steps 6, 8 */ // FIXME: spec - add assertion no abrupt completion possible String e = ArrayJoin(list, separator); /* step 9 */ // FIXME: spec bug - "SIMD" not prepended. return String.format("SIMD.%s(%s)", t, e); } /** * SIMDConstructor.prototype.toString() * * @param cx * the execution context * @param thisValue * the function this-value * @return the string representation */ @Function(name = "toString", arity = 0) public static Object toString(ExecutionContext cx, Object thisValue) { /* steps 1-2 */ SIMDValue value = thisSIMDValue(cx, thisValue, ".toString"); /* step 3 */ return SIMD.ToString(value); } /** * SIMDConstructor.prototype [ @@toStringTag ] */ @Value(name = "[Symbol.toStringTag]", symbol = BuiltinSymbol.toStringTag, attributes = @Attributes(writable = false, enumerable = false, configurable = true)) public static final String toStringTag = "SIMD." + SIMD_TYPE.name(); /** * SIMDConstructor.prototype [ @@toPrimitive ] ( hint ) * * @param cx * the execution context * @param thisValue * the function this-value * @param hint * the ToPrimitive hint string * @return the primitive value for this SIMD object */ @Function(name = "[Symbol.toPrimitive]", arity = 1, symbol = BuiltinSymbol.toPrimitive, attributes = @Attributes(writable = false, enumerable = false, configurable = true)) public static Object toPrimitive(ExecutionContext cx, Object thisValue, Object hint) { /* step 1 (omitted) */ /* step 2 */ // FIXME: spec bug? - inconsistent simd type checks when compared to wrapper case. if (thisValue instanceof SIMDValue) { return thisValue; } /* steps 3-6 */ return thisSIMDValue(cx, thisValue, "[Symbol.toPrimitive]"); } } }
Java
public class EcdhAkem implements AKEM { @Override public KeyPair keyGen() { try { return KeyPairGenerator.getInstance("X25519").generateKeyPair(); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } } @Override public Pair<SecretKey, byte[]> authEncap(PrivateKey senderPrivateKey, PublicKey recipientPublicKey) { var ephemeralKeys = keyGen(); var ephemeralSharedSecret = ecdh(ephemeralKeys.getPrivate(), recipientPublicKey); var staticSharedSecret = ecdh(senderPrivateKey, recipientPublicKey); var ephemeralPublicKey = ephemeralKeys.getPublic().getEncoded(); var key = new SecretKeySpec(Utils.sha256(ephemeralSharedSecret, staticSharedSecret, ephemeralPublicKey), "AES"); Arrays.fill(ephemeralSharedSecret, (byte) 0); Arrays.fill(staticSharedSecret, (byte) 0); // Note: Java's getEncoded() will return the public key in X.509 format, where it is prefixed by an algorithm // identifier and DER-encoded. This adds a few bytes of unnecessary overhead but is otherwise harmless. return new Pair<>(key, ephemeralPublicKey); } @Override public Optional<SecretKey> authDecap(PublicKey senderPublicKey, PrivateKey recipientPrivateKey, byte[] encapsulatedKey) { try { var keyFactory = KeyFactory.getInstance("X25519"); var ephemeralPublicKey = keyFactory.generatePublic(new X509EncodedKeySpec(encapsulatedKey)); var ephemeralSharedSecret = ecdh(recipientPrivateKey, ephemeralPublicKey); var staticSharedSecret = ecdh(recipientPrivateKey, senderPublicKey); var key = new SecretKeySpec(Utils.sha256(ephemeralSharedSecret, staticSharedSecret, encapsulatedKey), "AES"); Arrays.fill(ephemeralSharedSecret, (byte) 0); Arrays.fill(staticSharedSecret, (byte) 0); return Optional.of(key); } catch (GeneralSecurityException e) { Logger.getLogger("EcdhKem").log(Level.WARNING, "Unable to recover ECDH-KEM encapsulated key", e); return Optional.empty(); } } }
Java
public class StubDataSource implements DataSource { private String user; private String password; private PrintWriter logWriter; private SQLException throwException; private long connectionAcquistionTime = 0; private int loginTimeout; public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setURL(String url) { // we don't care } /** {@inheritDoc} */ @Override public PrintWriter getLogWriter() throws SQLException { return logWriter; } /** {@inheritDoc} */ @Override public void setLogWriter(PrintWriter out) throws SQLException { this.logWriter = out; } /** {@inheritDoc} */ @Override public void setLoginTimeout(int seconds) throws SQLException { this.loginTimeout = seconds; } /** {@inheritDoc} */ @Override public int getLoginTimeout() throws SQLException { return loginTimeout; } /** {@inheritDoc} */ public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return (T) this; } throw new SQLException("Wrapped DataSource is not an instance of " + iface); } /** {@inheritDoc} */ @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } /** {@inheritDoc} */ @Override public Connection getConnection() throws SQLException { if (throwException != null) { throw throwException; } if (connectionAcquistionTime > 0) { UtilityElf.quietlySleep(connectionAcquistionTime); } return new StubConnection(); } /** {@inheritDoc} */ @Override public Connection getConnection(String username, String password) throws SQLException { return new StubConnection(); } public void setThrowException(SQLException e) { this.throwException = e; } public void setConnectionAcquistionTime(long connectionAcquisitionTime) { this.connectionAcquistionTime = connectionAcquisitionTime; } }
Java
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OptimizedPoddingAdRuleSlot") public class OptimizedPoddingAdRuleSlot extends BaseAdRuleSlot { }
Java
public class PayPalTemplateTest { /** * Object on test. */ private final PayPalTemplate template = new PayPalTemplate(); /** * Tests whether a JSON response could be parsed or not. * * @throws IOException - If file could not be read. * @throws NoSuchFieldException - If access field is not found * @throws SecurityException - If not accessible * @throws IllegalAccessException - Illegal access to field * @throws IllegalArgumentException - If argument is not valid */ @Test public void testIfResponseCouldBeParsed() throws IOException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { template.setAccessToken("test"); InputStream stream = getClass().getResourceAsStream("/paypal-api-openidconnect-response.json"); ObjectMapper mapper = new ObjectMapper(); PayPalProfile userProfile = mapper.readValue(stream, PayPalProfile.class); Assert.assertEquals("Prabhakar", userProfile.getFamilyName()); Assert.assertEquals("abhijith@hotmail.com", userProfile.getEmail()); Assert.assertNull(userProfile.getLocale()); } }
Java
public class NotSavedException extends IOException { public NotSavedException(String message) { super(message); } }
Java
public class RequestProcessor { private Pattern metricExcludesPattern; private Pattern displayIncludesPattern; private Pattern nonPageExtensionPattern; public RequestProcessor(Set<String> metricExcludes, Set<String> displayIncludes, Set<String> nonPageExtensions) { this.metricExcludesPattern = createPattern(metricExcludes); this.displayIncludesPattern = createPattern(displayIncludes); initialiseNonPageExtensionPatternPattern(nonPageExtensions); } public String removeParam(String request) { if (StringUtils.isNotBlank(request)) { String[] results = request.split("\\?"); return results[0]; } return request; } public boolean isPage(String request) { return !SPIDER_REQUEST.equals(request) && isNotMatch(request, nonPageExtensionPattern); } public boolean isToMonitor(String request) { return isNotMatch(request, metricExcludesPattern); } public void processMetrics(String page, Integer bandwidth, boolean isPageView, ApacheLogMetrics apacheLogMetrics, boolean isSuccessfulHit, Long responseTime) { if (isPageView) { if (isMatch(page, displayIncludesPattern)) { apacheLogMetrics.getPageMetrics() .incrementGroupAndMemberMetrics(page, bandwidth, isPageView, isSuccessfulHit, responseTime); } else { apacheLogMetrics.getPageMetrics() .incrementGroupMetrics(bandwidth, isPageView, isSuccessfulHit, responseTime); } } } private void initialiseNonPageExtensionPatternPattern(Set<String> rawNonPageExtensions) { if (rawNonPageExtensions == null || rawNonPageExtensions.isEmpty()) { rawNonPageExtensions = getDefaultNonPageExtensions(); } Set<String> nonPageExtensions = new HashSet<String>(); for (String extension : rawNonPageExtensions) { if (extension.startsWith(".")) { nonPageExtensions.add(".*" + Pattern.quote(extension)); } else { nonPageExtensions.add(".*\\." + Pattern.quote(extension)); } } this.nonPageExtensionPattern = createPattern(nonPageExtensions); } }
Java
public class DefaultErrorHandler implements ErrorHandler { private boolean initialized = false; private final Widget inputWidget; private HelpBlock validationStateHelpBlock = null; private HasValidationState validationStateParent = null; /** * Default error handler. * * @param parent the parent of this error handler. */ public DefaultErrorHandler(Widget widget) { super(); assert widget != null; this.inputWidget = widget; this.inputWidget.addAttachHandler(new Handler() { @Override public void onAttachOrDetach(AttachEvent event) { init(); } }); } /** {@inheritDoc} */ @Override public void cleanup() { } /** {@inheritDoc} */ @Override public void clearErrors() { if (validationStateParent == null) { return; } validationStateParent.setValidationState(ValidationState.NONE); if (validationStateHelpBlock != null) validationStateHelpBlock.setText(""); } /** * Find the sibling {@link HelpBlock}. * * @param widget the {@link Widget} to search. * @return the found {@link HelpBlock} of null if not found. */ private HelpBlock findHelpBlock(Widget widget) { if (widget instanceof HelpBlock) return (HelpBlock) widget; // Try and find the HelpBlock in the children of the given widget. if (widget instanceof HasWidgets) { for (Widget w : (HasWidgets) widget) { if (w instanceof HelpBlock) return (HelpBlock) w; } } if (!(widget instanceof HasValidationState)) { // Try and find the HelpBlock in the parent of widget. return findHelpBlock(widget.getParent()); } return null; } /** * Initialize the instance. We find the parent {@link HasValidationState} and sibling {@link HelpBlock} * only 1 time on initialization. */ public void init() { if (initialized) return; Widget parent = inputWidget.getParent(); while (parent != null && !parent.getClass().getName().equals("com.google.gwt.user.client.ui.Widget")) { if (parent instanceof HasValidationState) { validationStateParent = (HasValidationState) parent; validationStateHelpBlock = findHelpBlock(inputWidget); } parent = parent.getParent(); } if (inputWidget.isAttached() || validationStateParent != null) { initialized = true; } } /** {@inheritDoc} */ @Override public void showErrors(List<EditorError> errors) { init(); // clearErrors(); String errorMsg = ""; if (validationStateParent != null) { validationStateParent.setValidationState(errors.size() <= 0 ? ValidationState.NONE : ValidationState.ERROR); for (int index = 0; index < errors.size(); index++) { errorMsg = errors.get(0).getMessage(); if (index + 1 < errors.size()) errorMsg += "; "; } } if (validationStateHelpBlock != null) { validationStateHelpBlock.setText(errorMsg); } } }
Java
public abstract class AdminPage extends Page { /** Shortcut to the admin service async. */ protected static final AdminServiceAsync SERVICE_ASYNC = Admin.SERVICE_ASYNC; /** * Creates a new AdminPage. * @param title displayable title of the page; can be <code>null</code> * @param pageName page name to be logged */ public AdminPage( final String title, final String pageName ) { super( title, pageName ); } }
Java
@BeanDefinition public class DbSecurityMasterFactoryBean extends AbstractDbMasterFactoryBean<DbSecurityMaster> { /** * The cache manager for the detail. */ @PropertyDefinition private CacheManager _cacheManager; /** * Creates an instance. */ public DbSecurityMasterFactoryBean() { super(DbSecurityMaster.class); } //------------------------------------------------------------------------- @Override public DbSecurityMaster createObject() { DbSecurityMaster master = new DbSecurityMaster(getDbConnector()); if (getUniqueIdScheme() != null) { master.setUniqueIdScheme(getUniqueIdScheme()); } if (getMaxRetries() != null) { master.setMaxRetries(getMaxRetries()); } if (getJmsConnector() != null) { JmsChangeManager cm = new JmsChangeManager(getJmsConnector().ensureTopicName(getJmsChangeManagerTopic())); master.setChangeManager(cm); cm.start(); } if (getCacheManager() != null) { master.setDetailProvider(new EHCachingSecurityMasterDetailProvider(new HibernateSecurityMasterDetailProvider(), getCacheManager())); } return master; } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code DbSecurityMasterFactoryBean}. * @return the meta-bean, not null */ public static DbSecurityMasterFactoryBean.Meta meta() { return DbSecurityMasterFactoryBean.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(DbSecurityMasterFactoryBean.Meta.INSTANCE); } @Override public DbSecurityMasterFactoryBean.Meta metaBean() { return DbSecurityMasterFactoryBean.Meta.INSTANCE; } @Override protected Object propertyGet(String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -1452875317: // cacheManager return getCacheManager(); } return super.propertyGet(propertyName, quiet); } @Override protected void propertySet(String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case -1452875317: // cacheManager setCacheManager((CacheManager) newValue); return; } super.propertySet(propertyName, newValue, quiet); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { DbSecurityMasterFactoryBean other = (DbSecurityMasterFactoryBean) obj; return JodaBeanUtils.equal(getCacheManager(), other.getCacheManager()) && super.equals(obj); } return false; } @Override public int hashCode() { int hash = 7; hash += hash * 31 + JodaBeanUtils.hashCode(getCacheManager()); return hash ^ super.hashCode(); } //----------------------------------------------------------------------- /** * Gets the cache manager for the detail. * @return the value of the property */ public CacheManager getCacheManager() { return _cacheManager; } /** * Sets the cache manager for the detail. * @param cacheManager the new value of the property */ public void setCacheManager(CacheManager cacheManager) { this._cacheManager = cacheManager; } /** * Gets the the {@code cacheManager} property. * @return the property, not null */ public final Property<CacheManager> cacheManager() { return metaBean().cacheManager().createProperty(this); } //----------------------------------------------------------------------- /** * The meta-bean for {@code DbSecurityMasterFactoryBean}. */ public static class Meta extends AbstractDbMasterFactoryBean.Meta<DbSecurityMaster> { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code cacheManager} property. */ private final MetaProperty<CacheManager> _cacheManager = DirectMetaProperty.ofReadWrite( this, "cacheManager", DbSecurityMasterFactoryBean.class, CacheManager.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap(), "cacheManager"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -1452875317: // cacheManager return _cacheManager; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends DbSecurityMasterFactoryBean> builder() { return new DirectBeanBuilder<DbSecurityMasterFactoryBean>(new DbSecurityMasterFactoryBean()); } @Override public Class<? extends DbSecurityMasterFactoryBean> beanType() { return DbSecurityMasterFactoryBean.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code cacheManager} property. * @return the meta-property, not null */ public final MetaProperty<CacheManager> cacheManager() { return _cacheManager; } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
Java
public static class Meta extends AbstractDbMasterFactoryBean.Meta<DbSecurityMaster> { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code cacheManager} property. */ private final MetaProperty<CacheManager> _cacheManager = DirectMetaProperty.ofReadWrite( this, "cacheManager", DbSecurityMasterFactoryBean.class, CacheManager.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap(), "cacheManager"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -1452875317: // cacheManager return _cacheManager; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends DbSecurityMasterFactoryBean> builder() { return new DirectBeanBuilder<DbSecurityMasterFactoryBean>(new DbSecurityMasterFactoryBean()); } @Override public Class<? extends DbSecurityMasterFactoryBean> beanType() { return DbSecurityMasterFactoryBean.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code cacheManager} property. * @return the meta-property, not null */ public final MetaProperty<CacheManager> cacheManager() { return _cacheManager; } }
Java
public class ServiceBusFuncIntegrationTests { //@Test public void functionChainingTest() throws Exception { String connectionString = "service-bus-connection-string-here"; String inQueueName = "in-queue"; String outQueueName = "out-queue"; String producerFuncUrl = "https://your-function-here.azurewebsites.net/api/ServiceBusProducerFunc"; String funcKey = "func-key-here"; int numItems = 100; // if higher than 1000 need to update clean queue method below // clear out queues ClearQueue(connectionString, inQueueName); ClearQueue(connectionString, outQueueName); CloseableHttpClient httpTextClient = HttpClientBuilder.create().build(); URIBuilder builder; // POST a bunch of http try { builder = new URIBuilder(producerFuncUrl); // Prepare the URI for the REST API method. URI uri = builder.build(); for(int i = 0; i<numItems; i++){ HttpPost request = new HttpPost(uri); // Request headers. request.setHeader("Content-Type", "application/json"); request.setHeader("x-functions-key", funcKey); HttpEntity requestEntity = new StringEntity("{'name': 'david', 'favouriteFruit': 'bananas'}"); request.setEntity(requestEntity); HttpResponse response = httpTextClient.execute(request); int status = response.getStatusLine().getStatusCode(); assertEquals(204, status); } }catch(Exception e){ } // wait a bit... Thread.sleep(2000); // check queue 2 QueueClient getQ = new QueueClient(new ConnectionStringBuilder(connectionString, outQueueName), ReceiveMode.RECEIVEANDDELETE); ManagementClient manageClt = new ManagementClient(new ConnectionStringBuilder(connectionString, outQueueName)); QueueRuntimeInfo info = manageClt.getQueueRuntimeInfo(outQueueName); long msgCount = info.getMessageCountDetails().getActiveMessageCount(); assertEquals(numItems, msgCount); } private void ClearQueue(String connectionString, String queueName) throws Exception { // other than deleting + recreating the queue, it seems this is the best way to clear it :/ QueueClient getQ = new QueueClient(new ConnectionStringBuilder(connectionString, queueName), ReceiveMode.RECEIVEANDDELETE); getQ.setPrefetchCount(1000); getQ.registerMessageHandler(new IMessageHandler() { @Override public CompletableFuture<Void> onMessageAsync(IMessage message) { return null; } @Override public void notifyException(Throwable exception, ExceptionPhase phase) {} }); Thread.sleep(5000); getQ.close(); } }
Java
@RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class GeneratorBridge<S, T> implements Generator<S> { // START REQUIRED ARGUMENTS /** The generator that accepts the destination type */ private final Generator<T> generator; /** Maps the source-type to one or more instances of the destination type */ private final CheckedFunction<S, Stream<T>, ?> bridge; // END REQUIRED ARGUMENTS /** * Creates a bridge that maps ONE-TO-ONE from source to destination (i.e. one call to the * generator for each source item) * * @param <S> source-type * @param <T> destination-type * @param generator the generator that accepts the destination type * @param bridge maps a source-item to one destination-item * @return a generator that accepts source-types as iterators, but actually calls a generator * that uses destination types */ public static <S, T> GeneratorBridge<S, T> createOneToOne( Generator<T> generator, CheckedFunction<S, T, ?> bridge) { return new GeneratorBridge<>(generator, item -> Stream.of(bridge.apply(item))); } /** * Creates a bridge that maps ONE-TO-MANY from source to destination (i.e. one or more calls to * the generator for each source item) * * @param <S> source-type * @param <T> destination-type * @param generator the generator that accepts the destination type * @param bridge maps a source-item to one or more destination-items * @return a generator that accepts source-types as iterators, but actually calls a generator * that uses destination types */ public static <S, T> GeneratorBridge<S, T> createOneToMany( Generator<T> generator, CheckedFunction<S, Stream<T>, ?> bridge) { return new GeneratorBridge<>(generator, bridge); } @Override public void write(S element, OutputNameStyle outputNameStyle, ElementOutputter outputter) throws OutputWriteFailedException { convertAndExecute( element, convertedElement -> generator.write(convertedElement, outputNameStyle, outputter)); } @Override public void writeWithIndex( S element, String index, IndexableOutputNameStyle outputNameStyle, ElementOutputter outputter) throws OutputWriteFailedException { convertAndExecute( element, convertedElement -> generator.writeWithIndex( convertedElement, index, outputNameStyle, outputter)); } /** Converts an element to <b>one or more target elements</b>, and runs a consumer on each. */ private void convertAndExecute( S element, CheckedConsumer<T, OutputWriteFailedException> function) throws OutputWriteFailedException { try { Stream<T> bridgedElement = bridge.apply(element); CheckedStream.forEach( bridgedElement, OutputWriteFailedException.class, function::accept); } catch (Exception e) { throw new OutputWriteFailedException(e); } } }
Java
public class CityUtil { public static String[] stringCitys = new String[]{ "阿里","日喀则","喀什","阿图什","和田","阿拉尔","阿克苏","伊宁","博乐","库尔勒","石河子", "吐鲁番","乌鲁木齐","昌吉","五家渠","塔城","克拉玛依","阿勒泰","景洪","西沙","三亚","乐东", "五指山","东方","昌江","白沙","儋州","保亭","陵水","万宁","琼中","屯昌","琼海","文昌","临高", "崇左","防城港","北海","钦州","澄迈","定安","海口","湛江","茂名","阳江","南沙","中沙","珠海", "普洱","临沧","德宏","保山","怒江","大理","香格里拉","丽江","山南","拉萨","林芝","那曲","昌都", "玉树","甘孜","红河","玉溪","楚雄","昆明","文山","百色","兴义","攀枝花","曲靖","凉山","昭通", "水城","安顺","贵阳","毕节","南宁","贵港","来宾","河池","柳州","玉林","云浮","肇庆","梧州", "桂林","贺州","都匀","凯里","遵义","铜仁","永州","怀化","邵阳","娄底","雅安","乐山","眉山", "宜宾","泸州","自贡","资阳","内江","成都","重庆","遂宁","南充","广安","阿坝","德阳","绵阳", "巴中","武都","广元","恩施","吉首","张家界","益阳","常德","宜昌","荆州","达州","汉中","安康", "神农架","荆门","襄阳","十堰","格尔木","果洛","海南","海西","海北","张掖","哈密","嘉峪关","酒泉", "合作","黄南","海东","临夏","兰州","天水","定西","白银","平凉","固原","西宁","武威","金昌", "中卫","吴忠","银川","阿左旗","石嘴山","宝鸡","杨凌","西安","咸阳","铜川","渭南","庆阳","商洛", "运城","三门峡","洛阳","临汾","延安","吕梁","榆林","朔州","乌海","临河","鄂尔多斯","包头", "呼和浩特","江门","佛山","中山","广州","东莞","清远","深圳","惠州","河源","韶关","汕尾","汕头", "揭阳","潮州","梅州","漳州","厦门","龙岩","郴州","赣州","衡阳","湘潭","株洲","萍乡","吉安", "宜春","新余","三明","抚州","泉州","莆田","南平","福州","宁德","温州","长沙","岳阳","潜江", "天门","仙桃","咸宁","黄石","孝感","武汉","鄂州","黄冈","南昌","鹰潭","上饶","景德镇","九江", "安庆","池州","铜陵","随州","信阳","南阳","驻马店","漯河","周口","六安","合肥","阜阳","淮南", "蚌埠","宿州","衢州","丽水","金华","黄山","绍兴","杭州","湖州","嘉兴","台州","宁波","舟山", "宣城","芜湖","马鞍山","滁州","南京","镇江","苏州","无锡","常州","南通","扬州","淮安","泰州", "盐城","上海","平顶山","许昌","济源","郑州","开封","晋城","焦作","新乡","长治","鹤壁","濮阳", "安阳","亳州","商丘","淮北","徐州","枣庄","菏泽","济宁","聊城","泰安","莱芜","晋中","太原", "阳泉","邯郸","邢台","忻州","石家庄","衡水","德州","济南","淄博","滨州","保定","沧州","天津", "宿迁","临沂","连云港","日照","青岛","潍坊","东营","烟台","威海","大连","大同","集宁","张家口", "廊坊","北京","承德","锡林浩特","唐山","秦皇岛","葫芦岛","朝阳","营口","锦州","盘锦","阜新", "鞍山","辽阳","沈阳","赤峰","通辽","丹东","本溪","抚顺","通化","白山","铁岭","辽源","四平", "长春","吉林","延吉","牡丹江","乌兰浩特","白城","海拉尔","松原","哈尔滨","大庆","齐齐哈尔", "绥化","伊春","大兴安岭","黑河","鸡西","七台河","佳木斯","鹤岗","双鸭山" }; public static ArrayList<String> getCityList() { if (stringCitysFromAssets.size() > 0) { return stringCitysFromAssets; } for (int i=0;i<stringCitys.length;i++) { stringCitysFromAssets.add(stringCitys[i]); } return stringCitysFromAssets; } public static ArrayList<String> stringCitysFromAssets = new ArrayList<String>(); public static ArrayList<String> getCityListFromAssets(Context context) { if (stringCitysFromAssets.size() > 0) { return stringCitysFromAssets; } InputStreamReader inputReader = null; try { inputReader = new InputStreamReader(context.getResources().getAssets().open("city-utf8.txt") ); BufferedReader bufReader = new BufferedReader(inputReader); String line = null; //always get .阿里 for first line,unbelievable while((line = bufReader.readLine()) != null) { stringCitysFromAssets.add(line); } } catch (Exception e) { e.printStackTrace(); } finally { if (inputReader != null) { try { inputReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return stringCitysFromAssets; } }
Java
public class HiveConnectionWrapper implements Connectable,Supplier<HiveConnection> { private static String DRIVER_NAME = "org.apache.hive.jdbc.HiveDriver"; private final String jdbcUrl; private final String username; private final String password; private HiveConnection connection = null; public HiveConnectionWrapper(String jdbcUrl, String username, String password) { this.jdbcUrl = jdbcUrl; this.username = username; this.password = password; } @Override public void connect() throws ConnectionException { try { Class.forName(DRIVER_NAME); } catch (ClassNotFoundException e) { throw new ConnectionException(e, "Cannot load the hive JDBC driver"); } try { Connection conn = DriverManager.getConnection(jdbcUrl, username, password); connection = (HiveConnection)conn; } catch (SQLException e) { throw new ConnectionException(e, "Cannot open a hive connection with connect string " + jdbcUrl); } } @Override public void reconnect() throws ConnectionException { } @Override public void disconnect() throws ConnectionException { if (connection != null) { try { connection.close(); } catch (SQLException e) { throw new ConnectionException(e, "Cannot close the hive connection with connect string " + jdbcUrl); } } } public Optional<HiveConnection> getConnection() { return Optional.fromNullable(connection); } @Override public boolean isOpen() { try { return connection != null && !connection.isClosed() && connection.isValid(100); } catch (SQLException e) { // in case of an SQ error just return return false; } } /** * Retrieves an instance of the appropriate type. The returned object may or * may not be a new instance, depending on the implementation. * * @return an instance of the appropriate type */ @Override public HiveConnection get() { return null; } }
Java
public class Front { private int numberOfPoints_ ; private int dimension_ ; public Point[] points_ ; private boolean maximizing_ ; public int nPoints_ ; private Comparator pointComparator ; public Front() { maximizing_ = true ; pointComparator = new PointComparator(maximizing_) ; } public Front (int numberOfPoints, int dimension, SolutionSet solutionSet) { maximizing_ = true ; pointComparator = new PointComparator(maximizing_) ; numberOfPoints_ = numberOfPoints ; dimension_ = dimension ; nPoints_ = numberOfPoints_ ; points_ = new Point[numberOfPoints_] ; for (int i = 0 ; i < numberOfPoints_; i++) { double [] p = new double[dimension] ; for (int j = 0 ; j < dimension; j++) { p[j] = solutionSet.get(i).getObjective(j) ; } points_[i] = new Point(p) ; } } public Front (int numberOfPoints, int dimension) { maximizing_ = true ; pointComparator = new PointComparator(maximizing_) ; numberOfPoints_ = numberOfPoints ; dimension_ = dimension ; nPoints_ = numberOfPoints_ ; points_ = new Point[numberOfPoints_] ; for (int i = 0 ; i < numberOfPoints_; i++) { double [] p = new double[dimension] ; for (int j = 0 ; j < dimension; j++) { p[j] = 0.0 ; } points_[i] = new Point(p) ; } } public Front(int numberOfPoints, int dimension, List<double[]> listOfPoints) { maximizing_ = true ; pointComparator = new PointComparator(maximizing_) ; numberOfPoints_ = numberOfPoints ; dimension_ = dimension ; points_ = new Point[numberOfPoints_] ; for (int i = 0 ; i < numberOfPoints_; i++) { points_[i] = new Point(listOfPoints.get(i)) ; } } public void readFront(String fileName) throws IOException { FileInputStream fis = new FileInputStream(fileName) ; InputStreamReader isr = new InputStreamReader(fis) ; BufferedReader br = new BufferedReader(isr) ; List<double []> list = new ArrayList<double []>(); int numberOfObjectives = 0; String aux = br.readLine(); while (aux!= null) { StringTokenizer st = new StringTokenizer(aux); int i = 0; numberOfObjectives = st.countTokens(); ////System.out.println("objectives: " + getNumberOfObjectives); double [] vector = new double[st.countTokens()]; while (st.hasMoreTokens()) { double value = new Double(st.nextToken()); vector[i] = value; i++; } list.add(vector); aux = br.readLine(); } numberOfPoints_ = list.size() ; dimension_ = numberOfObjectives ; points_ = new Point[numberOfPoints_] ; nPoints_ = numberOfPoints_ ; for (int i = 0 ; i < numberOfPoints_; i++) { points_[i] = new Point(list.get(i)) ; } } public void loadFront(SolutionSet solutionSet, int notLoadingIndex) { if (notLoadingIndex >= 0 && notLoadingIndex < solutionSet.size()) { numberOfPoints_ = solutionSet.size()-1; } else { numberOfPoints_ = solutionSet.size(); } nPoints_ = numberOfPoints_; dimension_ = solutionSet.get(0).getNumberOfObjectives(); points_ = new Point[numberOfPoints_]; int index = 0; for (int i = 0; i < solutionSet.size(); i++) { if (i != notLoadingIndex) { double [] vector = new double[dimension_]; for (int j = 0; j < dimension_; j++) { vector[j] = solutionSet.get(i).getObjective(j); } points_[index++] = new Point(vector); } } } public void printFront() { System.out.println("Objectives: " + dimension_) ; System.out.println("Number of points: " + numberOfPoints_) ; for (Point point : points_) { System.out.println(point) ; } } public int getNumberOfObjectives() { return dimension_ ; } public int getNumberOfPoints() { return numberOfPoints_; } public Point getPoint(int index) { return points_[index] ; } public Point[] getPoints() { return points_ ; } public void setToMazimize() { maximizing_ = true ; pointComparator = new PointComparator(maximizing_) ; } public void setToMinimize() { maximizing_ = false ; pointComparator = new PointComparator(maximizing_) ; } public void sort() { Arrays.sort(points_, pointComparator); } public Point getReferencePoint() { Point referencePoint = new Point(dimension_) ; double [] maxObjectives = new double[numberOfPoints_] ; for (int i = 0; i < numberOfPoints_; i++) maxObjectives[i] = 0 ; for (int i = 0; i < points_.length; i++) for (int j = 0 ; j < dimension_; j++) if (maxObjectives[j] < points_[i].objectives_[j]) maxObjectives[j] = points_[i].objectives_[j] ; //for (int i = 0; i < solution.getNumberOfObjectives(); i++) { // if (maxObjectives[i] < referencePoint_.objectives_[i]) // referencePoint_.objectives_[i] = maxObjectives[i] ; // // } for (int i = 0; i < dimension_; i++) referencePoint.objectives_[i] = maxObjectives[i] ; return referencePoint ; } }
Java
class Object_15_Test extends domts.DOMTestCase { @BeforeEach void setup() { // check if loaded documents are supported for content type String contentType = getContentType(); preload(contentType, "object", false); } @Test @DisplayName("http://www.w3.org/2001/DOM_Test_Suite/level2/html/object15") void run() throws Throwable { NodeList nodeList; Node testNode; String vcodetype; Node doc; doc = (Node) load("object", false); nodeList = ((Document) /*Node */doc).getElementsByTagName("object"); assertTrue(equalsSize(2, nodeList), "Asize"); testNode = nodeList.item(1); vcodetype = ((HTMLObjectElement) /*Node */testNode).getCodeType(); assertEquals("image/gif", vcodetype, "codeTypeLink"); } }
Java
public abstract class QueryAction { protected org.nlpcn.es4sql.domain.Query query; protected Client client; public QueryAction(Client client, Query query) { this.client = client; this.query = query; } protected void updateRequestWithStats(Select select, SearchRequestBuilder request) { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.STATS && hint.getParams() != null && 0 < hint.getParams().length) { request.setStats(Arrays.stream(hint.getParams()).map(Object::toString).toArray(String[]::new)); } } } protected void updateRequestWithCollapse(Select select, SearchRequestBuilder request) throws SqlParseException { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.COLLAPSE && hint.getParams() != null && 0 < hint.getParams().length) { try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, hint.getParams()[0].toString())) { request.setCollapse(CollapseBuilder.fromXContent(parser)); } catch (IOException e) { throw new SqlParseException("could not parse collapse hint: " + e.getMessage()); } } } } protected void updateRequestWithPostFilter(Select select, SearchRequestBuilder request) { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.POST_FILTER && hint.getParams() != null && 0 < hint.getParams().length) { request.setPostFilter(QueryBuilders.wrapperQuery(hint.getParams()[0].toString())); } } } protected void updateRequestWithIndexAndRoutingOptions(Select select, SearchRequestBuilder request) { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.IGNORE_UNAVAILABLE) { //saving the defaults from TransportClient search request.setIndicesOptions(IndicesOptions.fromOptions(true, false, true, false, IndicesOptions.strictExpandOpenAndForbidClosed())); } if (hint.getType() == HintType.ROUTINGS) { Object[] routings = hint.getParams(); String[] routingsAsStringArray = new String[routings.length]; for (int i = 0; i < routings.length; i++) { routingsAsStringArray[i] = routings[i].toString(); } request.setRouting(routingsAsStringArray); } } } protected void updateRequestWithPreference(Select select, SearchRequestBuilder request) { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.PREFERENCE && hint.getParams() != null && 0 < hint.getParams().length) { request.setPreference(hint.getParams()[0].toString()); } } } protected void updateRequestWithTrackTotalHits(Select select, SearchRequestBuilder request) { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.TRACK_TOTAL_HITS && hint.getParams() != null && 0 < hint.getParams().length) { String param = hint.getParams()[0].toString(); try { request.setTrackTotalHitsUpTo(Integer.parseInt(param)); } catch (NumberFormatException ex) { request.setTrackTotalHits(Boolean.parseBoolean(param)); } } } } protected void updateRequestWithTimeout(Select select, SearchRequestBuilder request) { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.TIMEOUT && hint.getParams() != null && 0 < hint.getParams().length) { String param = hint.getParams()[0].toString(); request.setTimeout(TimeValue.parseTimeValue(param, SearchSourceBuilder.TIMEOUT_FIELD.getPreferredName())); } } } protected void updateRequestWithIndicesOptions(Select select, SearchRequestBuilder request) throws SqlParseException { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.INDICES_OPTIONS && hint.getParams() != null && 0 < hint.getParams().length) { String param = hint.getParams()[0].toString(); try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, param)) { request.setIndicesOptions(IndicesOptions.fromMap(parser.map(), SearchRequest.DEFAULT_INDICES_OPTIONS)); } catch (IOException e) { throw new SqlParseException("could not parse indices_options hint: " + e.getMessage()); } } } } protected void updateRequestWithMinScore(Select select, SearchRequestBuilder request) { for (Hint hint : select.getHints()) { if (hint.getType() == HintType.MIN_SCORE && hint.getParams() != null && 0 < hint.getParams().length) { String param = hint.getParams()[0].toString(); request.setMinScore(Float.parseFloat(param)); } } } protected void updateRequestWithHighlight(Select select, SearchRequestBuilder request) { boolean foundAnyHighlights = false; HighlightBuilder highlightBuilder = new HighlightBuilder(); for (Hint hint : select.getHints()) { if (hint.getType() == HintType.HIGHLIGHT) { HighlightBuilder.Field highlightField = parseHighlightField(hint.getParams()); if (highlightField != null) { foundAnyHighlights = true; highlightBuilder.field(highlightField); } } } if (foundAnyHighlights) { request.highlighter(highlightBuilder); } } protected HighlightBuilder.Field parseHighlightField(Object[] params) { if (params == null || params.length == 0 || params.length > 2) { //todo: exception. } HighlightBuilder.Field field = new HighlightBuilder.Field(params[0].toString()); if (params.length == 1) { return field; } Map<String, Object> highlightParams = (Map<String, Object>) params[1]; for (Map.Entry<String, Object> param : highlightParams.entrySet()) { switch (param.getKey()) { case "type": field.highlighterType((String) param.getValue()); break; case "boundary_chars": field.boundaryChars(fromArrayListToCharArray((ArrayList) param.getValue())); break; case "boundary_max_scan": field.boundaryMaxScan((Integer) param.getValue()); break; case "force_source": field.forceSource((Boolean) param.getValue()); break; case "fragmenter": field.fragmenter((String) param.getValue()); break; case "fragment_offset": field.fragmentOffset((Integer) param.getValue()); break; case "fragment_size": field.fragmentSize((Integer) param.getValue()); break; case "highlight_filter": field.highlightFilter((Boolean) param.getValue()); break; case "matched_fields": field.matchedFields((String[]) ((ArrayList) param.getValue()).toArray(new String[((ArrayList) param.getValue()).size()])); break; case "no_match_size": field.noMatchSize((Integer) param.getValue()); break; case "num_of_fragments": field.numOfFragments((Integer) param.getValue()); break; case "order": field.order((String) param.getValue()); break; case "phrase_limit": field.phraseLimit((Integer) param.getValue()); break; case "post_tags": field.postTags((String[]) ((ArrayList) param.getValue()).toArray(new String[((ArrayList) param.getValue()).size()])); break; case "pre_tags": field.preTags((String[]) ((ArrayList) param.getValue()).toArray(new String[((ArrayList) param.getValue()).size()])); break; case "require_field_match": field.requireFieldMatch((Boolean) param.getValue()); break; } } return field; } private char[] fromArrayListToCharArray(ArrayList arrayList) { char[] chars = new char[arrayList.size()]; int i = 0; for (Object item : arrayList) { chars[i] = item.toString().charAt(0); i++; } return chars; } /** * Prepare the request, and return ES request. * zhongshu-comment 将sql字符串解析后的java对象,转换为es的查询请求对象 * * @return ActionRequestBuilder (ES request) * @throws SqlParseException */ public abstract SqlElasticRequestBuilder explain() throws SqlParseException; }
Java
public class EntityIndexer implements Runnable { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); private static final boolean DEBUG = UtilProperties.getPropertyAsBoolean("entityindexing", "entity.indexer.debug", false); private static final int LOG_LEVEL = Debug.getLevelFromString(UtilProperties.getPropertyValue("entityindexing", "entity.indexer.log.level", "info")); private static final int STATS_INTERVAL = UtilProperties.getPropertyAsInteger("entityindexing", "entity.indexer.log.stats.interval", -1); /** * Maps a data source name (by convention the entity name) and data element ID (primary key) to an indexer. The * The indexer refreshes the data with hooks using {@link IndexingHookHandler}. */ private static final Map<String, EntityIndexer.Factory> factoryMap = new ConcurrentHashMap<>(); private static final Object factoryMapLock = new Object(); /** * Maps a data source name (by convention the entity name) and data element ID (primary key) to an indexer. The * The indexer refreshes the data with hooks using {@link IndexingHookHandler}. */ private static final Map<String, EntityIndexer> indexerMap = new ConcurrentHashMap<>(); private static final Object indexerMapLock = new Object(); private static final Map<String, ?> defaultProperties = Collections.unmodifiableMap(UtilProperties.getPropertiesWithPrefix( UtilProperties.getMergedPropertiesFromAllComponents("entityindexing"), "entity.indexer.default.")); private static final Factory defaultFactory = loadFactory("default", defaultProperties, new Factory()); protected final String name; // entity name by default protected final String entityName; protected final Queue<Entry> queue; protected ModelEntity modelEntity; protected final Semaphore runSemaphore; protected Map<String, ?> properties; protected List<Consumer> consumers; protected Long runServicePriority; protected int flushTime; protected int maxRunTime; protected int bufSize; protected int sleepTime; protected long lastRunStatsTime = 0; protected EntityIndexer(String name, Map<String, ?> properties, Queue<Entry> queue) { if (properties == null) { properties = Collections.emptyMap(); } this.name = name; this.queue = queue; String entityName = (String) properties.get("entityName"); if (UtilValidate.isEmpty(entityName)) { entityName = name; } this.entityName = entityName; this.properties = Collections.unmodifiableMap(new HashMap<>(properties)); this.flushTime = UtilMisc.toInteger(properties.get("flushTime"), 3000); this.maxRunTime = UtilMisc.toInteger(properties.get("maxRunTime"), 60000); this.bufSize = UtilMisc.toInteger(properties.get("bufSize"), 1000); this.sleepTime = UtilMisc.toInteger(properties.get("sleepTime"), 500); this.runSemaphore = new Semaphore(1); this.lastRunStatsTime = 0; } public static class Factory { public EntityIndexer makeIndexer(String name, Map<String, ?> properties) { return new EntityIndexer(name, properties, makeQueue(properties)); } public Queue<Entry> makeQueue(Map<String, ?> properties) { return new PriorityBlockingQueue<>(1000); } } /** * Gets a data indexer for the given data source name (entity name) and data element ID (primary key). * NOTE: The data source name must not contain the string "::". */ public static <I extends EntityIndexer> I getIndexer(String name) { EntityIndexer indexer = indexerMap.get(name); if (indexer == null) { synchronized(indexerMapLock) { indexer = indexerMap.get(name); if (indexer == null) { indexer = makeIndexer(name); indexerMap.put(name, indexer); } } } return UtilGenerics.cast(indexer); } protected static <I extends EntityIndexer> I makeIndexer(String name) { Factory factory = factoryMap.get(name); if (factory == null) { factory = getFactory(name); if (factory == null) { return null; } } return UtilGenerics.cast(factory.makeIndexer(name, loadProperties(name))); } /** * Gets a data indexer factory for the given data source name (entity name). * NOTE: The data source name must not contain the string "::". */ public static <F extends Factory> F getFactory(String name) { Factory factory = factoryMap.get(name); if (factory == null) { synchronized(factoryMapLock) { factory = factoryMap.get(name); if (factory == null) { factory = loadFactory(name, loadProperties(name), defaultFactory); factoryMap.put(name, factory); } } } return UtilGenerics.cast(factory); } protected static Map<String, ?> getDefaultProperties() { return defaultProperties; } protected static Map<String, ?> loadProperties(String name) { Map<String, ?> properties = new HashMap<>(getDefaultProperties()); return UtilProperties.putPropertiesWithPrefix(UtilGenerics.cast(properties), UtilProperties.getMergedPropertiesFromAllComponents("entityindexing"), "entity.indexer." + name + "."); } /** * Returns the default indexer factory. */ private static Factory getDefaultFactory(String name, Map<String, ?> properties) { return defaultFactory; } protected static Factory loadFactory(String name, Map<String, ?> properties, Factory defaultFactory) { String factoryClass = (String) properties.get("factoryClass"); if (UtilValidate.isEmpty(factoryClass)) { return defaultFactory; } try { return UtilGenerics.cast(Thread.currentThread().getContextClassLoader().loadClass(factoryClass) .getConstructor().newInstance()); } catch(Exception e) { Debug.logError(e, "Could not load entity indexer factoryClass [" + factoryClass + "] from properties", module); return defaultFactory; } } /** * Registers a new factory in the factoryMap registry if none exists but does not replace an existing factory in * which case it returns the existing factory. */ public static <F extends Factory> F register(String name, Factory factory) { Factory prevFactory = factoryMap.putIfAbsent(name, factory); return UtilGenerics.cast((prevFactory != null) ? prevFactory : factory); } /** * Registers a new factory in the factoryMap registry. * Replaces any existing factory with the one passed and returns the new factory. */ public static <F extends Factory> F forceRegister(String name, Factory factory) { factoryMap.put(name, factory); return UtilGenerics.cast(factory); } public String getName() { return name; } /** * Returns the entity name for the indexer (for lookups), by default the indexer name. */ public String getEntityName() { return entityName; } public Queue<Entry> getQueue() { return queue; } public Map<String, ?> getProperties() { return properties; } public long getRunServicePriority() { Long runServicePriority = this.runServicePriority; if (runServicePriority == null) { Object runServicePriorityObj = getProperties().get("runServicePriority"); if (runServicePriorityObj instanceof Long) { runServicePriority = (Long) runServicePriorityObj; } else if (runServicePriorityObj instanceof Number) { runServicePriority = ((Number) runServicePriorityObj).longValue(); } else if (runServicePriorityObj instanceof String) { try { runServicePriority = Long.parseLong((String) runServicePriorityObj); } catch(Exception e) { Debug.logError(e, "Cannot parse runServicePriority value [" + runServicePriorityObj + "]", module); } } if (runServicePriority == null) { runServicePriority = 100L; } this.runServicePriority = runServicePriority; } return runServicePriority; } @Override public String toString() { return getName(); } public Entry add(Entry entry) { getQueue().add(entry); return entry; } public int poll(List<Entry> entries, int max) { int count; if (getQueue() instanceof PriorityBlockingQueue) { count = ((PriorityBlockingQueue<Entry>) getQueue()).drainTo(entries, max); } else { for(int i = 0; i < max; i++) { Entry entry = getQueue().poll(); if (entry == null) { return i; } entries.add(entry); } count = max; } // TODO: optimization: the entries are grouped by PK, so the last ones can get cut off, for now this will complicate // because have to read the queue twice and in between another element can be added /* // Consume as many sequential duplicate PKs as possible because the last batch of same-id-ordered entries may get cut in half. Set<Entry> pks = null; while(true) { Entry entry = getQueue().peek(); if (entry == null) { break; } if (pks == null) { // NOTE: this uses the implicit pk equals/hashcode for duplicates, not perfect pks = new HashSet<>(entries); } if (!pks.contains(entry)) { } } */ return count; } public int getBufSize() { return bufSize; } public long getFlushTime() { return flushTime; } public long getMaxRunTime() { return maxRunTime; } public int getSleepTime() { return sleepTime; } @Override public void run() { try { run(getDefaultDctx(), Collections.emptyMap()); } catch(Exception e) { Debug.logError(e, "Error during entity indexing: " + e.getMessage(), module); } } public void run(DispatchContext dctx, Map<String, Object> context) throws GeneralException, InterruptedException, IOException { long startTime = System.currentTimeMillis(); long lastReadTime = 0; int numRead; List<Entry> entries = new ArrayList<>(getBufSize()); List<DocEntry> docs = new ArrayList<>(getBufSize()); Set<Entry> docsToRemove = new LinkedHashSet<>(getBufSize()); int processedEntries = 0; int totalProcessedEntries = 0; //int oldQueueSize = getQueue().size(); int docsCommitted = 0; int docsRemoved = 0; int pollCount = 0; // Read entries up to maxRunTime until there are no more or as long as elements were read but the buffer is still waiting for more while (((System.currentTimeMillis()) - startTime) < getMaxRunTime()) { // Gather the queue as long as new elements become available or wait briefly if flush time not reached // TODO: REVIEW: At the very end unless maxRunTime reached we always do an extra poll() back here to minimize the number of // times this thread gets reactivated, and combined with flush time this helps buffer JobManager overhead, however, but // a few minor thread synchronization issues exist with the semaphore boolean flush = false; while (!flush && (((System.currentTimeMillis()) - startTime) < getMaxRunTime()) && ((numRead = poll(entries, getBufSize())) > 0 || ((docs.size() > 0 || docsToRemove.size() > 0) && (System.currentTimeMillis() - lastReadTime) < getFlushTime()))) { pollCount += 1; // commit if buffer full if (entries.size() > 0) { lastReadTime = entries.get(0).getEntryTime(); processedEntries += entries.size(); totalProcessedEntries += entries.size(); for(Entry entry : entries) { if ("all".equals(entry.getFlush())) { flush = true; break; } } if (Debug.infoOn()) { StringBuilder pkList = new StringBuilder(); int pkCount = 0; for(Entry entry : entries) { if (pkCount > 0) { pkList.append(", "); } pkList.append(entry.getShortPk()); pkCount++; if (pkCount >= SolrProductSearch.getMaxLogIds()) { break; } } if (entries.size() > SolrProductSearch.getMaxLogIds()) { pkList.append("..."); } String extraInfo = ""; if (Debug.VERBOSE == LOG_LEVEL) { extraInfo = ", flush=" + flush + ", bufSize=" + getBufSize() + ", flushTime=" + getFlushTime() + ", numRead=" + numRead + ", docsSize=" + docs.size() + ", docsToRemoveSize=" + docsToRemove.size() + ", startTime=" + UtilDateTime.getTimestamp(startTime) + ", currentTime=" + UtilDateTime.getTimestamp(System.currentTimeMillis()) + ", maxRunTime=" + UtilDateTime.formatDurationHMS(getMaxRunTime()) + ", pollCount=" + pollCount + ", lastReadTime=" + UtilDateTime.getTimestamp(lastReadTime) + ", processedEntries=" + processedEntries + ", totalProcessedEntries=" + totalProcessedEntries; } Debug.logInfo("Reading docs " + (processedEntries + 1) + "-" + (processedEntries + entries.size()) + " [" + getName() + "]: " + pkList + " (runTime: " + UtilDateTime.formatDurationHMS((System.currentTimeMillis()) - startTime) + extraInfo + ")", module); } readDocs(dctx, context, entries, docs, docsToRemove); entries.clear(); } else if (!flush) { Thread.sleep(getSleepTime()); } } if (!docs.isEmpty() || !docsToRemove.isEmpty()) { commit(dctx, context, docs, docsToRemove); docsCommitted += docs.size(); docsRemoved += docsToRemove.size(); docs.clear(); docsToRemove.clear(); processedEntries = 0; } } if (getStatsInterval() >= 0) { long nowTime = System.currentTimeMillis(); if ((nowTime - lastRunStatsTime) > getStatsInterval()) { lastRunStatsTime = nowTime; Debug.logInfo("Entity indexer [" + getName() + "] run doc stats: [committed=" + docsCommitted + ", removed=" + docsRemoved + ", entries=" + totalProcessedEntries + ", runTime=" + UtilDateTime.formatDurationHMS(nowTime - startTime) + "ms]", module); } } } public void tryRun(DispatchContext dctx, Map<String, Object> context) throws GeneralException, InterruptedException, IOException { if (runSemaphore.tryAcquire()) { Debug.logInfo("Entity indexer [" + getName() + "]: beginning run (queued: " + getQueue().size() + ")", module); try { run(dctx, context); } finally { runSemaphore.release(); if (isDebug()) { Debug.logInfo("Entity indexer [" + getName() + "]: finished run", module); } } } } public boolean isRunning() { return (runSemaphore.availablePermits() == 0); } /** * Main processing method, may be overridden; default implementation dispatches documents to consumers. */ public Object readDocs(DispatchContext dctx, Map<String, Object> context, Iterable<Entry> entries, List<DocEntry> docs, Set<Entry> docsToRemove) throws GeneralException, InterruptedException, IOException { for(Entry entry : entries) { if (entry.isExplicitRemove()) { docsToRemove.add(entry); } else { // FIXME: missing auto-detect for non-explicit removal here docs.add(makeDocEntry(entry, null, null)); } } return null; } public Object readDocsAndCommit(DispatchContext dctx, Map<String, Object> context, Iterable<Entry> entries) throws GeneralException, InterruptedException, IOException { // special cases/reuse List<DocEntry> docs = new ArrayList<>(getBufSize()); Set<Entry> docsToRemove = new LinkedHashSet<>(getBufSize()); Object result = readDocs(dctx, context, entries, docs, docsToRemove); if (docs.size() > 0 || docsToRemove.size() > 0) { commit(dctx, context, docs, docsToRemove); } return result; } public Object extractEntriesToDocs(DispatchContext dctx, Map<String, Object> context, long entryTime, Object properties, List<DocEntry> docs, Set<Entry> docsToRemove) throws GeneralException, InterruptedException, IOException { Collection<EntityIndexer.Entry> entries = extractEntries(dctx.getDelegator(), context, entryTime, properties); if (UtilValidate.isEmpty(entries)) { return null; } return readDocs(dctx, context, entries, docs, docsToRemove); } public Object extractEntriesToDocs(DispatchContext dctx, Map<String, Object> context, List<DocEntry> docs, Set<Entry> docsToRemove) throws GeneralException, InterruptedException, IOException { return extractEntriesToDocs(dctx, context, System.currentTimeMillis(), null, docs, docsToRemove); } /** * Returns the delegator, by default the default system delegator (not the "current"). */ protected Delegator getDefaultDelegator() { return DelegatorFactory.getDefaultDelegator(); } /** * Returns the dispatcher, by default the default system dispatcher (not the "current"). */ protected LocalDispatcher getDefaultDispatcher() { return ServiceContainer.getLocalDispatcher(getDefaultDelegator().getDelegatorName(), getDefaultDelegator()); } /** * Returns the dispatch context, by default default system dispatch context (not the "current"). */ protected DispatchContext getDefaultDctx() { return getDefaultDispatcher().getDispatchContext(); } protected ModelEntity getModelEntity(String entityName) { ModelEntity modelEntity = getDefaultDelegator().getModelEntity(entityName); if (modelEntity == null) { throw new IllegalArgumentException("Could not find model for entity [" + entityName + "]"); } return modelEntity; } public ModelEntity getModelEntity() { ModelEntity modelEntity = this.modelEntity; if (modelEntity == null) { modelEntity = getModelEntity(getEntityName()); this.modelEntity = modelEntity; } return modelEntity; } /** * Creates indexer entity entries, one per entity/product, from the given maps compatible with the * scheduleEntityIndexing (scheduleProductIndexing) service interface. */ public Collection<Entry> extractEntries(Delegator delegator, Map<String, Object> context, long entryTime, Object properties) { Object entityRef = extractEntryRef(delegator, context); if (entityRef == null) { return null; } Action action = extractEntryAction(delegator, context); Collection<GenericPK> pks = extractEntryPKs(delegator, context); if (UtilValidate.isEmpty(pks)) { return null; } Collection<Entry> entries = new ArrayList<>(pks.size()); Collection<String> topics = UtilGenerics.cast(context.get("topics")); String flush = UtilGenerics.cast(context.get("flush")); for(GenericPK pk : pks) { Entry entry = makeEntry(pk, entityRef, action, entryTime, topics, flush, context, properties); if (entry != null) { entries.add(entry); } } return entries; } public Object extractEntryRef(Delegator delegator, Map<String, Object> context) { Object entityRef = context.get("instance"); if (entityRef != null) { return entityRef; } entityRef = context.get("id"); if (entityRef != null) { return entityRef; } Object idField = context.get("idField"); if (idField != null) { entityRef = extractFirstIdField(idField, context); if (entityRef != null) { return entityRef; } } return null; } /** * Default algorithm for extracting target PKs from passed entity values and pks, best-effort. * Usually 1 is returned but more may be needed in some cases. */ public Collection<GenericPK> extractEntryPKs(Delegator delegator, Map<String, Object> context) { Object entityRef = context.get("instance"); if (entityRef instanceof GenericEntity) { GenericEntity entity = (GenericEntity) entityRef; if (getEntityName().equals(entity.getEntityName())) { return UtilMisc.toList((entity instanceof GenericPK) ? (GenericPK) entity : entity.getPrimaryKey()); } String relationName = (String) context.get("relationName"); if (relationName != null) { return UtilMisc.toList(entity.getRelatedOnePk(relationName)); } List<GenericPK> pkMaps = entity.getRelatedOnePksForEntity(new ArrayList<>(), getEntityName()); if (UtilValidate.isNotEmpty(pkMaps)) { return pkMaps; } } Object idRef = context.get("id"); if (idRef == null) { if (entityRef instanceof Map) { // may also be GenericEntity (some entities may use idField when no relation defined) Map<String, Object> mapEntityRef = UtilGenerics.cast(entityRef); Object idField = context.get("idField"); if (idField != null) { idRef = extractFirstIdField(idField, mapEntityRef); // FIXME: support PKs greater than size 1 for idField } } if (idRef == null) { Object idField = context.get("idField"); if (idField != null) { idRef = extractFirstIdField(idField, context); // FIXME: support PKs greater than size 1 for idField } if (idRef == null) { return null; } } } if (getModelEntity().getPksSize() == 1) { return UtilMisc.toList(GenericPK.create(delegator, getModelEntity(), idRef)); } else if (idRef instanceof String) { GenericPK pk = GenericPK.create(delegator, getModelEntity(), modelEntity.getPkMapFromId((String) idRef, delegator)); // TODO: optimize if (pk.size() == getModelEntity().getPksSize()) { return UtilMisc.toList(pk); } } return null; } protected static Object extractIdField(Object idField, Map<String, ?> map) { if (idField == null) { return null; } else if (idField instanceof String) { return map.get(idField); } else if (idField instanceof Collection) { Map<String, Object> fields = new LinkedHashMap<>(); for(String id : UtilGenerics.<Collection<String>>cast(idField)) { fields.put(id, map.get(id)); } return fields; } else { throw new IllegalArgumentException("Invalid idField: " + idField); } } protected static Object extractFirstIdField(Object idField, Map<String, ?> map) { // TODO: remove in future return UtilMisc.firstOrSelfSafe(extractIdField(idField, map)); } public Action extractEntryAction(Delegator delegator, Map<String, Object> context) { Object action = context.get("action"); if (action instanceof Action) { return (Action) action; } else if (action instanceof Boolean) { return Boolean.FALSE.equals(action) ? Action.REMOVE : Action.ADD; } else if (action instanceof String) { if ("add".equals(action)) { return Action.ADD; } else if ("remove".equals(action)) { return Action.REMOVE; } else if (!((String) action).isEmpty()) { throw new IllegalArgumentException("Invalid action string value: " + action); } } else if (action != null) { throw new IllegalArgumentException("Invalid action value type: " + action.getClass()); } return null; } public enum Action { ADD, REMOVE; } public GenericPK toPk(Object value) { if (value instanceof GenericPK) { return (GenericPK) value; } else if (value instanceof GenericEntity) { return ((GenericEntity) value).getPrimaryKey(); } else if (value instanceof Map) { return GenericPK.create(getDefaultDelegator(), getModelEntity(), UtilGenerics.<Map<String, Object>>cast(value), getModelEntity().getPkFieldsUnmodifiable()); } else { return GenericPK.create(getDefaultDelegator(), getModelEntity(), value); } } public Entry makeEntry(GenericPK pk, Object entityRef, Action action, long entryTime, Collection<String> topics, String flush, Map<String, Object> context, Object properties) { return new Entry(pk, entityRef, action, entryTime, topics, flush, context); } public Entry makeEntry(Object pk, Action action, Collection<String> topics) { return makeEntry(toPk(pk), null, action, System.currentTimeMillis(), topics, null, null, properties); } public Entry makeEntry(Entry other, Object pk, Long entryTime) { return makeEntry(other, toPk(pk), entryTime); } public static class Entry implements Comparable<Entry>, Serializable { protected final GenericPK pk; protected transient String shortPk; protected final Object entityRef; protected final Action action; protected long entryTime; protected final Collection<String> topics; protected String flush; protected Entry(GenericPK pk, Object entityRef, Action action, long entryTime, Collection<String> topics, String flush, Map<String, Object> context) { this.pk = pk; this.entityRef = entityRef; this.action = action; this.entryTime = entryTime; this.topics = (topics != null) ? topics : Collections.emptySet(); this.flush = flush; } public Entry(GenericPK pk, Object entityRef, Action action, long entryTime, Collection<String> topics, String flush) { this.pk = pk; this.entityRef = entityRef; this.action = action; this.entryTime = entryTime; this.topics = (topics != null) ? topics : Collections.emptySet(); this.flush = flush; } protected Entry(Entry other, GenericPK pk, Long entryTime) { this.pk = (pk != null) ? pk : other.getPk(); this.entityRef = other.entityRef; this.action = other.action; this.entryTime = (entryTime != null) ? entryTime : other.getEntryTime(); this.topics = other.topics; } public GenericPK getPk() { return pk; } public String getShortPk() { String shortPk = this.shortPk; if (shortPk == null) { shortPk = pk.getPkShortValueString(); this.shortPk = shortPk; } return shortPk; } public Object getEntityRef() { return entityRef; } public Action getAction() { return action; } public boolean isExplicitAdd() { return getAction() == Action.ADD; } public boolean isExplicitRemove() { return getAction() == Action.REMOVE; } public long getEntryTime() { return entryTime; } public Collection<String> getTopics() { return topics; } public boolean hasTopic() { return !topics.isEmpty(); } public String getFlush() { return flush; } @Override public int compareTo(Entry o) { if (pk.equals(o.pk)) { return 0; // same ID = same value = same priority, time doesn't matter } return Long.compare(entryTime, o.entryTime); // oldest entries should get picked first } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; return getPk().equals(entry.getPk()); } @Override public int hashCode() { return Objects.hash(getPk()); } } public DocEntry makeDocEntry(Entry entry, Map<String, Object> doc, Object docBuilder) { return new DocEntry(entry, doc, docBuilder); } public DocEntry makeDocEntry(GenericPK pk, Map<String, Object> doc, Object docBuilder) { return new DocEntry(pk, doc, docBuilder); } /** * Processed document entry (commit). */ public class DocEntry implements Serializable { private final GenericPK pk; private transient String shortPk; private final Entry entry; private final Map<String, Object> doc; private final Object data; protected DocEntry(Entry entry, Map<String, Object> doc, Object data) { this.entry = entry; this.pk = entry.getPk(); this.doc = doc; this.data = data; } protected DocEntry(GenericPK pk, Map<String, Object> doc, Object data) { this.entry = null; this.pk = pk; this.doc = doc; this.data = data; } /** The entry used to request this indexing, or null if generic event or callback. */ public Entry getEntry() { return entry; } /** Makes a new Entry reflecting this DocEntry. */ public Entry makeEntry(Action action, long entryTime, Collection<String> topics, String flush, Map<String, Object> context, Object properties) { return EntityIndexer.this.makeEntry(getPk(), (getEntry() != null) ? getEntry().getEntityRef() : null, action, entryTime, topics, flush, context, properties); } public Map<String, Object> getDoc() { return doc; } public Object getData() { return data; } public GenericPK getPk() { return pk; } public String getShortPk() { String shortPk = this.shortPk; if (shortPk == null) { shortPk = pk.getPkShortValueString(); this.shortPk = shortPk; } return shortPk; } public Collection<String> getTopics() { return (entry != null) ? entry.getTopics() : Collections.emptySet(); } public boolean hasTopic() { return (entry != null) ? entry.hasTopic() : false; } } public Object commit(DispatchContext dctx, Map<String, Object> context, Collection<? extends DocEntry> docs, Collection<? extends Entry> docsToRemove) { for(Consumer consumer : getConsumers()) { Collection<? extends DocEntry> consumerDocs = docs.stream().filter(consumer::acceptsDoc).collect(Collectors.toList()); Collection<? extends Entry> consumerDocsToRemove = docsToRemove.stream().filter(consumer::acceptsDoc).collect(Collectors.toList()); try { Map<String, Object> servCtx = UtilMisc.toMap( "userLogin", dctx.getDelegator().from("UserLogin").where("userLoginId", "system").cache().queryOneSafe(), "docs", consumerDocs, "docsToRemove", consumerDocsToRemove, "onError", consumer.getOnError()); if (consumer.isAsync()) { dctx.getDispatcher().runAsync(consumer.getServiceName(), servCtx, ServiceOptions.async(consumer.isPersist()).priority(consumer.getPriority())); //Debug.logInfo("Jobs after starting " + consumer.getServiceName() + ": " + JobPoller.getInstance().getPoolState(false, true, 16), module); } else { Map<String, Object> servResult = dctx.getDispatcher().runSync(consumer.getServiceName(), servCtx); if (ServiceUtil.isError(servResult)) { Debug.logError("Error dispatching " + docs.size() + " documents to entity indexing consumer " + consumer + ": " + ServiceUtil.getErrorMessage(servResult), module); } } } catch(GeneralException e) { Debug.logError(e, "Could not dispatch " + docs.size() + " documents to entity indexing consumer " + consumer, module); } } return null; } public List<Consumer> getConsumers() { List<Consumer> consumers = this.consumers; if (consumers == null) { Map<String, Map<String, Object>> consumerProps = UtilProperties.extractPropertiesWithPrefixAndId(new LinkedHashMap<>(), getProperties(),"consumer."); consumers = new ArrayList<>(consumerProps.size()); for(Map.Entry<String, Map<String, Object>> entry : consumerProps.entrySet()) { Consumer consumer = makeConsumer(entry.getKey(), entry.getValue()); if (consumer != null) { consumers.add(consumer); } } Collections.sort(consumers, (o1, o2) -> Integer.compare(o1.getSequenceNum(), o2.getSequenceNum())); Debug.logInfo("Consumers for entity indexer [" + getName() + "]: " + consumers, module); consumers = Collections.unmodifiableList(consumers); this.consumers = consumers; } return consumers; } protected Consumer makeConsumer(String name, Map<String, ?> props) { name = (name != null) ? name : (String) props.get("name"); String serviceName = (String) props.get("service"); Object topicsObj = props.get("topics"); String mode = (String) props.get("mode"); boolean persist = UtilMisc.booleanValue(props.get("persist"), false); Set<String> topics = null; if (topicsObj instanceof Collection) { topics = UtilGenerics.cast(topicsObj); } else if (topicsObj instanceof String) { topics = StringUtil.splitRegex(new LinkedHashSet<>(), (String) props.get("topics"), ",", null, true, false); } else if (topicsObj != null) { Debug.logError("Invalid entity indexing consumer topics configuration: " + topicsObj + ": " + props, module); return null; } if (UtilValidate.isEmpty(name) || UtilValidate.isEmpty(serviceName) || UtilValidate.isEmpty(topicsObj)) { Debug.logError("Invalid entity indexing consumer configuration: " + props, module); return null; } long priority = UtilMisc.toLong(props.get("priority"), 99L); String onError = (String) props.get("onError"); return makeConsumer(name, UtilMisc.toInteger(props.get("sequenceNum"), 100), serviceName, topics, mode, persist, priority, onError); } protected Consumer makeConsumer(String name, int sequenceNum, String serviceName, Set<String> topics, String mode, boolean persist, long priority, String onError) { return new Consumer(name, sequenceNum, serviceName, topics, mode, persist, priority, onError); } public static class Consumer { private final String name; private final int sequenceNum; private final String serviceName; private final Set<String> topics; private final String mode; private final boolean persist; private final long priority; private final String onError; protected Consumer(String name, int sequenceNum, String serviceName, Set<String> topics, String mode, boolean persist, long priority, String onError) { this.name = name; this.sequenceNum = sequenceNum; this.serviceName = serviceName; this.topics = (topics != null) ? Collections.unmodifiableSet(new LinkedHashSet<>(topics)) : Collections.emptySet(); this.mode = mode; this.persist = persist; this.priority = priority; this.onError = onError; } public String getName() { return name; } public int getSequenceNum() { return sequenceNum; } public String getServiceName() { return serviceName; } public Set<String> getTopics() { return topics; } public boolean hasTopic(Collection<String> topics) { for(String topic : topics) { if (this.topics.contains(topic)) { return true; } } return false; } public boolean acceptsDoc(DocEntry docEntry) { return !docEntry.hasTopic() || hasTopic(docEntry.getTopics()); } public boolean acceptsDoc(Entry entry) { return !entry.hasTopic() || hasTopic(entry.getTopics()); } public boolean isAsync() { return true; } public boolean isPersist() { return false; } public long getPriority() { return priority; } public String getOnError() { return onError; } @Override public String toString() { return "{" + "name='" + name + '\'' + ", sequenceNum=" + sequenceNum + ", serviceName='" + serviceName + '\'' + ", topics=" + topics + ", mode='" + mode + '\'' + ", persist=" + persist + ", priority=" + priority + ", onError='" + onError + '\'' + '}'; } } /** * Service that registers the given entity PK to the current thread's transactions for queueing with * queueEntityIndex, otherwise performs queueEntityIndex immediately. queueEntityIndex then appends to the queue * for the EntityIndexer. */ public static Map<String, Object> scheduleEntityIndexing(ServiceContext ctx) { if (!SystemState.getInstance().isServerExecution()) { if (Debug.verboseOn()) { Debug.logInfo("Not scheduling entity indexing; not a regular server execution", module); } return ServiceUtil.returnSuccess("Not scheduling entity indexing; not a regular server execution"); } if ("trans-commit".equals(ctx.attr("event")) && TransactionUtil.isTransactionInPlaceSafe()) { if (TransactionUtil.getStatusSafe() == TransactionUtil.STATUS_MARKED_ROLLBACK) { return ServiceUtil.returnFailure("Current transaction is marked for rollback; aborting scheduleEntityIndexing"); } return scheduleTransCommitEntityIndexing(ctx); } else { return queueEntityIndexing(ctx); } } /** * Extracts an entity PK from context and adds it to entitiesToIndex map to the transaction commit registration service entry for scheduleEntityIndexing. */ public static Map<String, Object> scheduleTransCommitEntityIndexing(ServiceContext ctx) { try { LocalDispatcher dispatcher = ctx.dispatcher(); ServiceSyncRegistrations regs = dispatcher.getServiceSyncRegistrations(); EntityIndexer indexer = EntityIndexer.getIndexer(ctx.attr("entityName")); if (indexer == null) { throw new IllegalArgumentException("Could not get indexer for entity [" + ctx.attr("entityName") + "]"); } Collection<Entry> entries = indexer.extractEntries(ctx.delegator(), ctx.context(), System.currentTimeMillis(), null); if (UtilValidate.isEmpty(entries)) { Debug.logWarning("No entity values identified for scheduling for context: " + ctx.context(), module); return ServiceUtil.returnFailure("No entity values identified for scheduling"); } Collection<ServiceSyncRegistrations.ServiceSyncRegistration> commitRegs = regs.getCommitRegistrationsForService("scheduleEntityIndexing"); if (commitRegs.size() >= 1) { if (commitRegs.size() >= 2) { Debug.logError("scheduleTransCommitEntityIndexing: Found more than one transaction commit registration" + " for scheduleEntityIndexing; should not happen! (coding or ECA config error)", module); } ServiceSyncRegistrations.ServiceSyncRegistration reg = commitRegs.iterator().next(); // WARN: editing existing registration's service context in-place Map<String, Map<GenericPK, Entry>> entitiesToIndex = UtilGenerics.cast(reg.getContext().get("entitiesToIndex")); Map<GenericPK, Entry> entryMap = UtilGenerics.cast(entitiesToIndex.get(indexer.getName())); if (entryMap == null) { entryMap = new LinkedHashMap<>(); entitiesToIndex.put(indexer.getName(), entryMap); } for(Entry entry : entries) { entryMap.remove(entry.getPk()); // this is a LinkedHashMap, so remove existing first so we keep the "real" order entryMap.put(entry.getPk(), entry); } String msg = "Scheduled transaction commit entity indexing for " + entries.size() + " entity " + indexer.getEntityName(); Debug.logInfo("scheduleEntityIndexing: " + msg, module); return ServiceUtil.returnSuccess(msg); } else { // register the service Map<String, Object> servCtx = UtilMisc.toMap("locale", ctx.locale(), "userLogin", ctx.userLogin(), "timeZone", ctx.timeZone(), "event", "global-queue"); Map<String, Map<GenericPK, Entry>> entitiesToIndex = new LinkedHashMap<>(); // IMPORTANT: LinkedHashMap keeps order of changes across transaction Map<GenericPK, Entry> entryMap = new LinkedHashMap<>(); for(Entry entry : entries) { entryMap.put(entry.getPk(), entry); } entitiesToIndex.put(indexer.getName(), entryMap); servCtx.put("entitiesToIndex", entitiesToIndex); regs.addCommitService(ctx.dctx(), "scheduleEntityIndexing", null, servCtx, false, false); } //StringBuilder pkList = new StringBuilder(); //int pkCount = 0; //for(Entry entry : entries) { // if (pkList.length() > 0) { // pkList.append(", "); // } // pkList.append(entry.getShortPk()); // pkCount++; // if (pkCount >= SolrProductSearch.maxLogIds) { // break; // } //} //if (entries.size() > SolrProductSearch.maxLogIds) { // pkList.append("..."); //} // This looks redundant because the queue below already does it and accumulates them //String msg = "Scheduled transaction commit entity indexing for " + entries.size() + " entries of entity " + indexer.getEntityName() // + ": " + pkList; //Debug.logInfo("scheduleEntityIndexing: " + msg, module); return ServiceUtil.returnSuccess("Scheduled transaction commit entity indexing for " + entries.size() + " entries of entity " + indexer.getEntityName()); } catch (Exception e) { final String errMsg = "Could not schedule transaction global-commit entity indexing"; Debug.logError(e, "scheduleEntityIndexing: " + errMsg, module); return ServiceUtil.returnError(errMsg + ": " + e.toString()); } } /** * Queues the given entity PKs for indexing in the appropriate {@link EntityIndexer}. */ public static Map<String, Object> queueEntityIndexing(ServiceContext ctx) { try { Map<String, Map<GenericPK, Entry>> entitiesToIndex = ctx.attr("entitiesToIndex"); String entityName = ctx.attr("entityName"); if (UtilValidate.isNotEmpty(entityName)) { // Only needed for "inline" queues (inline here is a convenience) EntityIndexer indexer = EntityIndexer.getIndexer(entityName); Collection<Entry> entries = indexer.extractEntries(ctx.delegator(), ctx.context(), System.currentTimeMillis(), null); if (UtilValidate.isNotEmpty(entries)) { if (entitiesToIndex == null) { entitiesToIndex = new LinkedHashMap<>(); } Map<GenericPK, Entry> entryMap = entitiesToIndex.get(indexer.getName()); if (entryMap == null) { entryMap = new LinkedHashMap<>(); entitiesToIndex.put(indexer.getName(), entryMap); } for (Entry entry : entries) { entryMap.remove(entry.getPk()); // this is a LinkedHashMap, so remove existing first so we keep the "real" order entryMap.put(entry.getPk(), entry); } } } Map<String, Object> newEntitiesToIndex = ctx.attr("newEntitiesToIndex"); Set<String> entityNames = UtilMisc.keySet(entitiesToIndex, newEntitiesToIndex); int scheduled = 0; StringBuilder pkList = new StringBuilder(); int pkCount = 0; for(String targetEntityName : entityNames) { EntityIndexer targetIndexer = getIndexer(targetEntityName); if (pkList.length() > 0) { pkList.append("; "); } pkList.append(targetIndexer.getEntityName()); pkList.append(": "); boolean firstPk = true; Map<GenericPK, Entry> targetEntry = (entitiesToIndex != null) ? entitiesToIndex.get(targetEntityName) : null; if (targetEntry != null) { for (Entry entry : targetEntry.values()) { targetIndexer.add(entry); if (pkCount < SolrProductSearch.getMaxLogIds()) { if (!firstPk) { pkList.append(", "); } pkList.append(entry.getShortPk()); pkCount++; } else if (pkCount == SolrProductSearch.getMaxLogIds()) { pkList.append("..."); pkCount++; } scheduled++; firstPk = false; } } Object rawEntities = (newEntitiesToIndex != null) ? newEntitiesToIndex.get(targetEntityName) : null; if (rawEntities != null) { Map<String, Object> extractCtx = new HashMap<>(ctx.context()); extractCtx.remove("entityName"); extractCtx.remove("idField"); Iterator<?> it; if (rawEntities instanceof Iterable || rawEntities instanceof Iterator) { it = UtilMisc.asIterator(rawEntities); } else { it = UtilMisc.toList(rawEntities).iterator(); } if (rawEntities instanceof EntityListIterator) { // in this case trigger running early due to high number if (!targetIndexer.isRunning()) { // Start the async service to create a new thread and prioritize in system at same time ctx.dispatcher().runAsync("runEntityIndexing", UtilMisc.toMap("userLogin", ctx.attr("userLogin"), "entityName", targetIndexer.getName()), ServiceOptions.asyncMemory().priority(targetIndexer.getRunServicePriority())); } } Object value; while((value = UtilMisc.next(it)) != null) { if (value instanceof GenericEntity) { extractCtx.put("instance", value); extractCtx.remove("id"); } else if (value instanceof String) { extractCtx.remove("instance"); extractCtx.put("id", value); } else { throw new IllegalArgumentException("invalid entityInstances for entity [" + targetEntityName + "]: " + value.getClass().getName()); } Collection<Entry> entries = targetIndexer.extractEntries(ctx.delegator(), extractCtx, System.currentTimeMillis(), null); if (UtilValidate.isNotEmpty(entries)) { for(Entry entry : entries) { targetIndexer.add(entry); if (pkCount < SolrProductSearch.getMaxLogIds()) { if (!firstPk) { pkList.append(", "); } pkList.append(entry.getShortPk()); pkCount++; } else if (pkCount == SolrProductSearch.getMaxLogIds()) { pkList.append("..."); pkCount++; } scheduled++; firstPk = false; } } } } if (!targetIndexer.isRunning()) { // Start the async service to create a new thread and prioritize in system at same time ctx.dispatcher().runAsync("runEntityIndexing", UtilMisc.toMap("userLogin", ctx.attr("userLogin"), "entityName", targetIndexer.getName()), ServiceOptions.asyncMemory().priority(targetIndexer.getRunServicePriority())); } } String msg = "Queued entity indexing for " + scheduled + " entries: " + pkList; Debug.logInfo("scheduleEntityIndexing: " + msg, module); return ServiceUtil.returnSuccess(msg); } catch (Exception e) { final String errMsg = "Could not queue entity indexing"; Debug.logError(e, "scheduleEntityIndexing: " + errMsg, module); return ServiceUtil.returnError(errMsg + ": " + e.toString()); } } public static Map<String, Object> scheduleAllEntityIndexing(ServiceContext ctx) { Delegator delegator = ctx.delegator(); ProcessSignals processSignals = null; String entityName = ctx.attr("entityName"); Integer maxRows = ctx.attr("maxRows"); EntityListIterator prodIt = null; try { if (processSignals != null && processSignals.isSet("stop")) { return ServiceUtil.returnFailure(processSignals.getProcess() + " aborted"); } EntityFindOptions findOptions = new EntityFindOptions(); if (maxRows != null) { findOptions.setMaxRows(maxRows); } prodIt = delegator.find(entityName, null, null, null, null, findOptions); if (processSignals != null && processSignals.isSet("stop")) { return ServiceUtil.returnFailure(processSignals.getProcess() + " aborted"); } /* TODO: filters Collection<String> includeMainStoreIds = UtilMisc.nullIfEmpty(ctx.<Collection<String>>attr("includeMainStoreIds")); Collection<String> includeAnyStoreIds = UtilMisc.nullIfEmpty(ctx.<Collection<String>>attr("includeAnyStoreIds")); List<SolrDocBuilder.ProductFilter> productFilters = null; SolrDocBuilder.ProductFilter storeProductFilter = docBuilder.makeStoreProductFilter(includeMainStoreIds, includeAnyStoreIds); if (storeProductFilter != null) { productFilters = (productFilters != null) ? new ArrayList<>(productFilters) : new ArrayList<>(); productFilters.add(storeProductFilter); } */ Map<String, Object> queueCtx = new HashMap<>(ctx.context()); queueCtx.put("newEntitiesToIndex", UtilMisc.toMap(entityName, prodIt)); Map<String, Object> queueResult = queueEntityIndexing(ctx.from(queueCtx)); if (ServiceUtil.isError(queueResult)) { return ServiceUtil.returnResultSysFields(queueResult); } return ServiceUtil.returnResultSysFields(queueResult); } catch (Exception e) { return ServiceUtil.returnError(e.toString()); } finally { if (prodIt != null) { try { prodIt.close(); } catch(Exception e) { } } } } /** * Re-queues the given entity PKs for indexing in the appropriate {@link EntityIndexer} after failure. * May be called directly by entityIndexingConsumer implementations. * NOTE: Currently no service interface to avoid transaction handling. */ public static Map<String, Object> requeueEntityIndexing(DispatchContext dctx, Map<String, Object> context) { try { Collection<? extends EntityIndexer.DocEntry> allDocs = UtilGenerics.cast(context.get("docs")); Collection<String> topics = UtilGenerics.cast(context.get("topics")); if (topics == null && !context.containsKey("topics")) { String onError = UtilGenerics.cast(context.get("onError")); Collection<String> srcTopics = UtilGenerics.cast(context.get("srcTopics")); if ("ignore".equals(onError)) { return ServiceUtil.returnSuccess(); } else if ("requeue-topic".equals(onError)) { topics = srcTopics; } else if ("requeue-all".equals(onError)) { topics = null; } } if (UtilValidate.isEmpty(topics)) { topics = null; } String entityName = (String) context.get("entityName"); int scheduled = 0; StringBuilder pkList = new StringBuilder(); int pkCount = 0; EntityIndexer targetIndexer = getIndexer(entityName); if (targetIndexer == null) { throw new IllegalArgumentException("Invalid entity indexer name: " + entityName); } if (pkList.length() > 0) { pkList.append("; "); } pkList.append(targetIndexer.getEntityName()); pkList.append(": "); boolean firstPk = true; long entryTime = System.currentTimeMillis(); for(DocEntry docEntry : allDocs) { Entry entry = docEntry.makeEntry(Action.ADD, entryTime, topics, null, null, null); targetIndexer.add(entry); if (pkCount < SolrProductSearch.getMaxLogIds()) { if (!firstPk) { pkList.append(", "); } pkList.append(entry.getShortPk()); pkCount++; } else if (pkCount == SolrProductSearch.getMaxLogIds()) { pkList.append("..."); pkCount++; } scheduled++; firstPk = false; } if (!targetIndexer.isRunning()) { // Start the async service to create a new thread and prioritize in system at same time dctx.getDispatcher().runAsync("runEntityIndexing", UtilMisc.toMap("userLogin", context.get("userLogin"), "entityName", targetIndexer.getName()), ServiceOptions.asyncMemory().priority(targetIndexer.getRunServicePriority())); } String msg = "Requeued entity indexing for " + scheduled + " entries: " + pkList; Debug.logInfo("requeueEntityIndexing: " + msg, module); return ServiceUtil.returnSuccess(msg); } catch (Exception e) { final String errMsg = "Could not requeue entity indexing"; Debug.logError(e, "requeueEntityIndexing: " + errMsg, module); return ServiceUtil.returnError(errMsg + ": " + e.toString()); } } /** * Runs entity indexing for an entity/indexer IF not already started; if started does nothing for that indexer. * Must be run as an async service to let the job manager determine best time to run processing. * NOTE: This must strictly be an async service without transaction because the thread may get recycled up to * a maximum. * WARN: If multiple entityNames are passed they try-run sequentially - avoiding this for now, instead doing multiple * runAsync with single entityName. */ public static Map<String, Object> runEntityIndexing(ServiceContext ctx) { Collection<String> entityNames = ctx.attr("entityNames"); if (UtilValidate.isEmpty(entityNames)) { String entityName = ctx.attr("entityName"); if (UtilValidate.isEmpty(entityName)) { return ServiceUtil.returnError("No entity names (indexer names) specified"); } entityNames = UtilMisc.toList(entityName); } for(String entityName : entityNames) { EntityIndexer targetIndexer = getIndexer(entityName); if (targetIndexer != null) { try { // Run with default dispatch context so everyone is equal //targetIndexer.tryRun(dctx, context); targetIndexer.tryRun(targetIndexer.getDefaultDctx(), ctx.context()); } catch(Exception e) { Debug.logError(e, module); return ServiceUtil.returnError(e.toString()); } // If there are elements in the queue, queue another invocation using a separate service call. // NOTE: On a live system with a constant flux of ECAs this is not needed, but for development this can be needed. if (!targetIndexer.isRunning() && targetIndexer.getQueue().size() > 0) { // Start the async service to create a new thread and prioritize in system at same time try { ctx.dispatcher().runAsync("runEntityIndexing", UtilMisc.toMap("userLogin", ctx.attr("userLogin"), "entityName", targetIndexer.getName()), ServiceOptions.asyncMemory().priority(targetIndexer.getRunServicePriority())); } catch (GenericServiceException e) { String msg = "Could not reschedule runEntityIndexing: " + e.toString(); Debug.logError(e, "runEntityIndexing: " + msg, module); return ServiceUtil.returnFailure(msg); } } } } return ServiceUtil.returnSuccess(); } public static boolean isDebug() { return DEBUG; } public static int getStatsInterval() { return STATS_INTERVAL; } }
Java
public class DocEntry implements Serializable { private final GenericPK pk; private transient String shortPk; private final Entry entry; private final Map<String, Object> doc; private final Object data; protected DocEntry(Entry entry, Map<String, Object> doc, Object data) { this.entry = entry; this.pk = entry.getPk(); this.doc = doc; this.data = data; } protected DocEntry(GenericPK pk, Map<String, Object> doc, Object data) { this.entry = null; this.pk = pk; this.doc = doc; this.data = data; } /** The entry used to request this indexing, or null if generic event or callback. */ public Entry getEntry() { return entry; } /** Makes a new Entry reflecting this DocEntry. */ public Entry makeEntry(Action action, long entryTime, Collection<String> topics, String flush, Map<String, Object> context, Object properties) { return EntityIndexer.this.makeEntry(getPk(), (getEntry() != null) ? getEntry().getEntityRef() : null, action, entryTime, topics, flush, context, properties); } public Map<String, Object> getDoc() { return doc; } public Object getData() { return data; } public GenericPK getPk() { return pk; } public String getShortPk() { String shortPk = this.shortPk; if (shortPk == null) { shortPk = pk.getPkShortValueString(); this.shortPk = shortPk; } return shortPk; } public Collection<String> getTopics() { return (entry != null) ? entry.getTopics() : Collections.emptySet(); } public boolean hasTopic() { return (entry != null) ? entry.hasTopic() : false; } }
Java
public abstract class SGridUtils { public static final SGridCellRendererNumber CellRendererInteger = new SGridCellRendererNumber(SLibUtils.DecimalFormatInteger); public static final SGridCellRendererNumber CellRendererIntegerRaw = new SGridCellRendererNumber(SLibUtils.DecimalFormatIntegerRaw); public static final SGridCellRendererNumber CellRendererCalendarYear = new SGridCellRendererNumber(SLibUtils.DecimalFormatCalendarYear); public static final SGridCellRendererNumber CellRendererCalendarMonth = new SGridCellRendererNumber(SLibUtils.DecimalFormatCalendarMonth); public static final SGridCellRendererNumber CellRendererValue0D = new SGridCellRendererNumber(SLibUtils.DecimalFormatValue0D); public static final SGridCellRendererNumber CellRendererValue2D = new SGridCellRendererNumber(SLibUtils.DecimalFormatValue2D); public static final SGridCellRendererNumber CellRendererValue4D = new SGridCellRendererNumber(SLibUtils.DecimalFormatValue4D); public static final SGridCellRendererNumber CellRendererValue8D = new SGridCellRendererNumber(SLibUtils.DecimalFormatValue8D); public static final SGridCellRendererNumber CellRendererPercentage0D = new SGridCellRendererNumber(SLibUtils.DecimalFormatPercentage0D); public static final SGridCellRendererNumber CellRendererPercentage2D = new SGridCellRendererNumber(SLibUtils.DecimalFormatPercentage2D); public static final SGridCellRendererNumber CellRendererPercentage4D = new SGridCellRendererNumber(SLibUtils.DecimalFormatPercentage4D); public static final SGridCellRendererNumber CellRendererPercentage8D = new SGridCellRendererNumber(SLibUtils.DecimalFormatPercentage8D); public static final SGridCellRendererDefault CellRendererString = new SGridCellRendererDefault(); public static final SGridCellRendererBoolean CellRendererBoolean = new SGridCellRendererBoolean(); public static final SGridCellRendererDate CellRendererDate = new SGridCellRendererDate(SLibUtils.DateFormatDate); public static final SGridCellRendererDate CellRendererDatetime = new SGridCellRendererDate(SLibUtils.DateFormatDatetime); public static final SGridCellRendererDate CellRendererTime = new SGridCellRendererDate(SLibUtils.DateFormatTime); public static final SGridCellRendererIcon CellRendererIcon = new SGridCellRendererIcon(); public static SGridCellRendererNumber getCellRendererNumber() { return CellRendererValue8D; } public static SGridCellRendererNumber getCellRendererNumberAmount() { return CellRendererValue2D; } public static SGridCellRendererNumber getCellRendererNumberAmountUnitary() { return CellRendererValue8D; } public static SGridCellRendererNumber getCellRendererNumberExchangeRate() { return CellRendererValue4D; } public static SGridCellRendererNumber getCellRendererNumberQuantity() { return CellRendererValue4D; } public static SGridCellRendererNumber getCellRendererNumberPercentage() { return CellRendererPercentage8D; } public static SGridCellRendererNumber getCellRendererNumberPercentageTax() { return CellRendererPercentage4D; } public static SGridCellRendererNumber getCellRendererNumberPercentageDiscount() { return CellRendererPercentage4D; } public static int getColumnWidth(final int columnType) { int width = 0; switch (columnType) { case SGridConsts.COL_TYPE_INT_1B: width = 25; break; case SGridConsts.COL_TYPE_INT_2B: width = 50; break; case SGridConsts.COL_TYPE_INT_4B: width = 75; break; case SGridConsts.COL_TYPE_INT_8B: width = 100; break; case SGridConsts.COL_TYPE_INT_RAW: width = 75; break; case SGridConsts.COL_TYPE_INT_CAL_MONTH: width = 30; break; case SGridConsts.COL_TYPE_INT_CAL_YEAR: width = 40; break; case SGridConsts.COL_TYPE_INT_ICON: width = 16; break; case SGridConsts.COL_TYPE_DEC_0D: width = 60; break; case SGridConsts.COL_TYPE_DEC_2D: width = 80; break; case SGridConsts.COL_TYPE_DEC_4D: width = 100; break; case SGridConsts.COL_TYPE_DEC_8D: width = 120; break; case SGridConsts.COL_TYPE_DEC_AMT: width = 100; break; case SGridConsts.COL_TYPE_DEC_AMT_UNIT: width = 120; break; case SGridConsts.COL_TYPE_DEC_EXC_RATE: width = 80; break; case SGridConsts.COL_TYPE_DEC_QTY: width = 100; break; case SGridConsts.COL_TYPE_DEC_PER_0D: width = 60; break; case SGridConsts.COL_TYPE_DEC_PER_2D: width = 80; break; case SGridConsts.COL_TYPE_DEC_PER_4D: width = 100; break; case SGridConsts.COL_TYPE_DEC_PER_8D: width = 120; break; case SGridConsts.COL_TYPE_DEC_PER_TAX: width = 80; break; case SGridConsts.COL_TYPE_DEC_PER_DISC: width = 80; break; case SGridConsts.COL_TYPE_BOOL_S: width = 50; break; case SGridConsts.COL_TYPE_BOOL_M: width = 75; break; case SGridConsts.COL_TYPE_BOOL_L: width = 100; break; case SGridConsts.COL_TYPE_TEXT: width = 100; break; case SGridConsts.COL_TYPE_TEXT_CODE_CO: width = 35; break; case SGridConsts.COL_TYPE_TEXT_CODE_BPR: width = 50; break; case SGridConsts.COL_TYPE_TEXT_CODE_CAT: width = 50; break; case SGridConsts.COL_TYPE_TEXT_CODE_ITM: width = 100; break; case SGridConsts.COL_TYPE_TEXT_CODE_UNT: width = 35; break; case SGridConsts.COL_TYPE_TEXT_CODE_CUR: width = 35; break; case SGridConsts.COL_TYPE_TEXT_CODE_ACC: width = 100; break; case SGridConsts.COL_TYPE_TEXT_NAME_CAT_S: width = 100; break; case SGridConsts.COL_TYPE_TEXT_NAME_CAT_M: width = 200; break; case SGridConsts.COL_TYPE_TEXT_NAME_CAT_L: width = 300; break; case SGridConsts.COL_TYPE_TEXT_NAME_BPR_S: width = 150; break; case SGridConsts.COL_TYPE_TEXT_NAME_BPR_L: width = 300; break; case SGridConsts.COL_TYPE_TEXT_NAME_ITM_S: width = 150; break; case SGridConsts.COL_TYPE_TEXT_NAME_ITM_L: width = 300; break; case SGridConsts.COL_TYPE_TEXT_NAME_USR: width = 100; break; case SGridConsts.COL_TYPE_TEXT_NAME_ACC: width = 200; break; case SGridConsts.COL_TYPE_TEXT_REG_PER: width = 50; break; case SGridConsts.COL_TYPE_TEXT_REG_NUM: width = 85; break; case SGridConsts.COL_TYPE_DATE: width = 65; break; case SGridConsts.COL_TYPE_DATE_DATETIME: width = 110; break; case SGridConsts.COL_TYPE_DATE_TIME: width = 45; break; default: SLibUtils.showException(SGridUtils.class.getName(), new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN)); } return width; } public static DefaultTableCellRenderer getCellRenderer(final int columnType) { DefaultTableCellRenderer renderer = null; switch (columnType) { case SGridConsts.COL_TYPE_INT_1B: case SGridConsts.COL_TYPE_INT_2B: case SGridConsts.COL_TYPE_INT_4B: case SGridConsts.COL_TYPE_INT_8B: renderer = CellRendererInteger; break; case SGridConsts.COL_TYPE_INT_RAW: renderer = CellRendererIntegerRaw; break; case SGridConsts.COL_TYPE_INT_CAL_MONTH: renderer = CellRendererCalendarMonth; break; case SGridConsts.COL_TYPE_INT_CAL_YEAR: renderer = CellRendererCalendarYear; break; case SGridConsts.COL_TYPE_INT_ICON: renderer = CellRendererIcon; break; case SGridConsts.COL_TYPE_DEC_0D: renderer = CellRendererValue0D; break; case SGridConsts.COL_TYPE_DEC_2D: renderer = CellRendererValue2D; break; case SGridConsts.COL_TYPE_DEC_4D: renderer = CellRendererValue4D; break; case SGridConsts.COL_TYPE_DEC_8D: renderer = CellRendererValue8D; break; case SGridConsts.COL_TYPE_DEC_AMT: renderer = CellRendererValue2D; break; case SGridConsts.COL_TYPE_DEC_AMT_UNIT: renderer = CellRendererValue8D; break; case SGridConsts.COL_TYPE_DEC_EXC_RATE: renderer = CellRendererValue4D; break; case SGridConsts.COL_TYPE_DEC_QTY: renderer = CellRendererValue4D; break; case SGridConsts.COL_TYPE_DEC_PER_0D: renderer = CellRendererPercentage0D; break; case SGridConsts.COL_TYPE_DEC_PER_2D: renderer = CellRendererPercentage2D; break; case SGridConsts.COL_TYPE_DEC_PER_4D: renderer = CellRendererPercentage4D; break; case SGridConsts.COL_TYPE_DEC_PER_8D: renderer = CellRendererPercentage8D; break; case SGridConsts.COL_TYPE_DEC_PER_TAX: renderer = CellRendererPercentage4D; break; case SGridConsts.COL_TYPE_DEC_PER_DISC: renderer = CellRendererPercentage4D; break; case SGridConsts.COL_TYPE_BOOL_S: case SGridConsts.COL_TYPE_BOOL_M: case SGridConsts.COL_TYPE_BOOL_L: renderer = CellRendererBoolean; break; case SGridConsts.COL_TYPE_TEXT: case SGridConsts.COL_TYPE_TEXT_CODE_CO: case SGridConsts.COL_TYPE_TEXT_CODE_BPR: case SGridConsts.COL_TYPE_TEXT_CODE_CAT: case SGridConsts.COL_TYPE_TEXT_CODE_ITM: case SGridConsts.COL_TYPE_TEXT_CODE_UNT: case SGridConsts.COL_TYPE_TEXT_CODE_CUR: case SGridConsts.COL_TYPE_TEXT_CODE_ACC: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_S: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_M: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_L: case SGridConsts.COL_TYPE_TEXT_NAME_BPR_S: case SGridConsts.COL_TYPE_TEXT_NAME_BPR_L: case SGridConsts.COL_TYPE_TEXT_NAME_ITM_S: case SGridConsts.COL_TYPE_TEXT_NAME_ITM_L: case SGridConsts.COL_TYPE_TEXT_NAME_USR: case SGridConsts.COL_TYPE_TEXT_NAME_ACC: case SGridConsts.COL_TYPE_TEXT_REG_PER: case SGridConsts.COL_TYPE_TEXT_REG_NUM: renderer = CellRendererString; break; case SGridConsts.COL_TYPE_DATE: renderer = CellRendererDate; break; case SGridConsts.COL_TYPE_DATE_DATETIME: renderer = CellRendererDatetime; break; case SGridConsts.COL_TYPE_DATE_TIME: renderer = CellRendererTime; break; default: SLibUtils.showException(SGridUtils.class.getName(), new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN)); } return renderer; } public static int getDataType(final int columnType) { int type = SLibConsts.UNDEFINED; switch (columnType) { case SGridConsts.COL_TYPE_INT_1B: case SGridConsts.COL_TYPE_INT_2B: case SGridConsts.COL_TYPE_INT_4B: case SGridConsts.COL_TYPE_INT_8B: case SGridConsts.COL_TYPE_INT_RAW: case SGridConsts.COL_TYPE_INT_CAL_MONTH: case SGridConsts.COL_TYPE_INT_CAL_YEAR: case SGridConsts.COL_TYPE_INT_ICON: type = SLibConsts.DATA_TYPE_INT; break; case SGridConsts.COL_TYPE_DEC_0D: case SGridConsts.COL_TYPE_DEC_2D: case SGridConsts.COL_TYPE_DEC_4D: case SGridConsts.COL_TYPE_DEC_8D: case SGridConsts.COL_TYPE_DEC_AMT: case SGridConsts.COL_TYPE_DEC_AMT_UNIT: case SGridConsts.COL_TYPE_DEC_EXC_RATE: case SGridConsts.COL_TYPE_DEC_QTY: case SGridConsts.COL_TYPE_DEC_PER_0D: case SGridConsts.COL_TYPE_DEC_PER_2D: case SGridConsts.COL_TYPE_DEC_PER_4D: case SGridConsts.COL_TYPE_DEC_PER_8D: case SGridConsts.COL_TYPE_DEC_PER_TAX: case SGridConsts.COL_TYPE_DEC_PER_DISC: type = SLibConsts.DATA_TYPE_DEC; break; case SGridConsts.COL_TYPE_BOOL_S: case SGridConsts.COL_TYPE_BOOL_M: case SGridConsts.COL_TYPE_BOOL_L: type = SLibConsts.DATA_TYPE_BOOL; break; case SGridConsts.COL_TYPE_TEXT: case SGridConsts.COL_TYPE_TEXT_CODE_CO: case SGridConsts.COL_TYPE_TEXT_CODE_BPR: case SGridConsts.COL_TYPE_TEXT_CODE_CAT: case SGridConsts.COL_TYPE_TEXT_CODE_ITM: case SGridConsts.COL_TYPE_TEXT_CODE_UNT: case SGridConsts.COL_TYPE_TEXT_CODE_CUR: case SGridConsts.COL_TYPE_TEXT_CODE_ACC: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_S: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_M: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_L: case SGridConsts.COL_TYPE_TEXT_NAME_BPR_S: case SGridConsts.COL_TYPE_TEXT_NAME_BPR_L: case SGridConsts.COL_TYPE_TEXT_NAME_ITM_S: case SGridConsts.COL_TYPE_TEXT_NAME_ITM_L: case SGridConsts.COL_TYPE_TEXT_NAME_USR: case SGridConsts.COL_TYPE_TEXT_NAME_ACC: case SGridConsts.COL_TYPE_TEXT_REG_PER: case SGridConsts.COL_TYPE_TEXT_REG_NUM: type = SLibConsts.DATA_TYPE_TEXT; break; case SGridConsts.COL_TYPE_DATE: case SGridConsts.COL_TYPE_DATE_DATETIME: case SGridConsts.COL_TYPE_DATE_TIME: type = SLibConsts.DATA_TYPE_DATE; break; default: SLibUtils.showException(SGridUtils.class.getName(), new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN)); } return type; } public static int getGuiType(final int columnType) { int type = SLibConsts.UNDEFINED; switch (columnType) { case SGridConsts.COL_TYPE_INT_1B: case SGridConsts.COL_TYPE_INT_2B: case SGridConsts.COL_TYPE_INT_4B: case SGridConsts.COL_TYPE_INT_8B: type = SGuiConsts.GUI_TYPE_INT; break; case SGridConsts.COL_TYPE_INT_RAW: type = SGuiConsts.GUI_TYPE_INT_RAW; break; case SGridConsts.COL_TYPE_INT_CAL_MONTH: type = SGuiConsts.GUI_TYPE_INT_CAL_MONTH; break; case SGridConsts.COL_TYPE_INT_CAL_YEAR: type = SGuiConsts.GUI_TYPE_INT_CAL_YEAR; break; case SGridConsts.COL_TYPE_INT_ICON: type = SGuiConsts.GUI_TYPE_INT; break; case SGridConsts.COL_TYPE_DEC_0D: case SGridConsts.COL_TYPE_DEC_2D: case SGridConsts.COL_TYPE_DEC_4D: case SGridConsts.COL_TYPE_DEC_8D: type = SGuiConsts.GUI_TYPE_DEC; break; case SGridConsts.COL_TYPE_DEC_AMT: type = SGuiConsts.GUI_TYPE_DEC_AMT; break; case SGridConsts.COL_TYPE_DEC_AMT_UNIT: type = SGuiConsts.GUI_TYPE_DEC_AMT_UNIT; break; case SGridConsts.COL_TYPE_DEC_EXC_RATE: type = SGuiConsts.GUI_TYPE_DEC_EXC_RATE; break; case SGridConsts.COL_TYPE_DEC_QTY: type = SGuiConsts.GUI_TYPE_DEC_QTY; break; case SGridConsts.COL_TYPE_DEC_PER_0D: case SGridConsts.COL_TYPE_DEC_PER_2D: case SGridConsts.COL_TYPE_DEC_PER_4D: case SGridConsts.COL_TYPE_DEC_PER_8D: type = SGuiConsts.GUI_TYPE_DEC_PER; break; case SGridConsts.COL_TYPE_DEC_PER_TAX: type = SGuiConsts.GUI_TYPE_DEC_PER_TAX; break; case SGridConsts.COL_TYPE_DEC_PER_DISC: type = SGuiConsts.GUI_TYPE_DEC_PER_DISC; break; case SGridConsts.COL_TYPE_BOOL_S: case SGridConsts.COL_TYPE_BOOL_M: case SGridConsts.COL_TYPE_BOOL_L: type = SGuiConsts.GUI_TYPE_BOOL; break; case SGridConsts.COL_TYPE_TEXT: case SGridConsts.COL_TYPE_TEXT_CODE_CO: case SGridConsts.COL_TYPE_TEXT_CODE_BPR: case SGridConsts.COL_TYPE_TEXT_CODE_CAT: case SGridConsts.COL_TYPE_TEXT_CODE_ITM: case SGridConsts.COL_TYPE_TEXT_CODE_UNT: case SGridConsts.COL_TYPE_TEXT_CODE_CUR: case SGridConsts.COL_TYPE_TEXT_CODE_ACC: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_S: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_M: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_L: case SGridConsts.COL_TYPE_TEXT_NAME_BPR_S: case SGridConsts.COL_TYPE_TEXT_NAME_BPR_L: case SGridConsts.COL_TYPE_TEXT_NAME_ITM_S: case SGridConsts.COL_TYPE_TEXT_NAME_ITM_L: case SGridConsts.COL_TYPE_TEXT_NAME_USR: case SGridConsts.COL_TYPE_TEXT_NAME_ACC: case SGridConsts.COL_TYPE_TEXT_REG_PER: case SGridConsts.COL_TYPE_TEXT_REG_NUM: type = SGuiConsts.GUI_TYPE_TEXT; break; case SGridConsts.COL_TYPE_DATE: type = SGuiConsts.GUI_TYPE_DATE; break; case SGridConsts.COL_TYPE_DATE_DATETIME: type = SGuiConsts.GUI_TYPE_DATE_DATETIME; break; case SGridConsts.COL_TYPE_DATE_TIME: type = SGuiConsts.GUI_TYPE_DATE_TIME; break; default: SLibUtils.showException(SGridUtils.class.getName(), new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN)); } return type; } public static Class<?> getDataTypeClass(final int columnType) { Class<?> typeClass = null; switch (columnType) { case SGridConsts.COL_TYPE_INT_1B: case SGridConsts.COL_TYPE_INT_2B: case SGridConsts.COL_TYPE_INT_4B: typeClass = Integer.class; break; case SGridConsts.COL_TYPE_INT_8B: typeClass = Long.class; break; case SGridConsts.COL_TYPE_INT_RAW: case SGridConsts.COL_TYPE_INT_CAL_MONTH: case SGridConsts.COL_TYPE_INT_CAL_YEAR: case SGridConsts.COL_TYPE_INT_ICON: typeClass = Integer.class; break; case SGridConsts.COL_TYPE_DEC_0D: case SGridConsts.COL_TYPE_DEC_2D: case SGridConsts.COL_TYPE_DEC_4D: case SGridConsts.COL_TYPE_DEC_8D: case SGridConsts.COL_TYPE_DEC_AMT: case SGridConsts.COL_TYPE_DEC_AMT_UNIT: case SGridConsts.COL_TYPE_DEC_EXC_RATE: case SGridConsts.COL_TYPE_DEC_QTY: case SGridConsts.COL_TYPE_DEC_PER_0D: case SGridConsts.COL_TYPE_DEC_PER_2D: case SGridConsts.COL_TYPE_DEC_PER_4D: case SGridConsts.COL_TYPE_DEC_PER_8D: case SGridConsts.COL_TYPE_DEC_PER_TAX: case SGridConsts.COL_TYPE_DEC_PER_DISC: typeClass = Double.class; break; case SGridConsts.COL_TYPE_BOOL_S: case SGridConsts.COL_TYPE_BOOL_M: case SGridConsts.COL_TYPE_BOOL_L: typeClass = Boolean.class; break; case SGridConsts.COL_TYPE_TEXT: case SGridConsts.COL_TYPE_TEXT_CODE_CO: case SGridConsts.COL_TYPE_TEXT_CODE_BPR: case SGridConsts.COL_TYPE_TEXT_CODE_CAT: case SGridConsts.COL_TYPE_TEXT_CODE_ITM: case SGridConsts.COL_TYPE_TEXT_CODE_UNT: case SGridConsts.COL_TYPE_TEXT_CODE_CUR: case SGridConsts.COL_TYPE_TEXT_CODE_ACC: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_S: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_M: case SGridConsts.COL_TYPE_TEXT_NAME_CAT_L: case SGridConsts.COL_TYPE_TEXT_NAME_BPR_S: case SGridConsts.COL_TYPE_TEXT_NAME_BPR_L: case SGridConsts.COL_TYPE_TEXT_NAME_ITM_S: case SGridConsts.COL_TYPE_TEXT_NAME_ITM_L: case SGridConsts.COL_TYPE_TEXT_NAME_USR: case SGridConsts.COL_TYPE_TEXT_NAME_ACC: case SGridConsts.COL_TYPE_TEXT_REG_PER: case SGridConsts.COL_TYPE_TEXT_REG_NUM: typeClass = String.class; break; case SGridConsts.COL_TYPE_DATE: case SGridConsts.COL_TYPE_DATE_DATETIME: case SGridConsts.COL_TYPE_DATE_TIME: typeClass = Date.class; break; default: SLibUtils.showException(SGridUtils.class.getName(), new Exception(SLibConsts.ERR_MSG_OPTION_UNKNOWN)); } return typeClass; } private static int seek(final SGridPane gridPane, final int col, final SortOrder sortOrder, final int rowFirst, final int rowLast, final double value) { int rowMiddle; double valueComparison; rowMiddle = rowFirst + ((rowLast - rowFirst) / 2); valueComparison = value - ((Number) gridPane.getTable().getValueAt(rowMiddle, col)).doubleValue(); if (valueComparison == 0) { return rowMiddle; } switch (sortOrder) { case ASCENDING: if (valueComparison < 0) { if ((rowMiddle - 1) >= rowFirst) { return seek(gridPane, col, sortOrder, rowFirst, rowMiddle - 1, value); } } else { if (rowLast >= (rowMiddle + 1)) { return seek(gridPane, col, sortOrder, rowMiddle + 1, rowLast, value); } } break; case DESCENDING: if (valueComparison < 0) { if (rowLast >= (rowMiddle + 1)) { return seek(gridPane, col, sortOrder, rowMiddle + 1, rowLast, value); } } else { if ((rowMiddle - 1) >= rowFirst) { return seek(gridPane, col, sortOrder, rowFirst, rowMiddle - 1, value); } } break; default: } return -1; } private static int seek(final SGridPane gridPane, final int col, final SortOrder sortOrder, final int rowFirst, final int rowLast, final String value) { int rowMiddle; int valueComparison; rowMiddle = rowFirst + ((rowLast - rowFirst) / 2); valueComparison = value.compareToIgnoreCase( (((java.lang.String) gridPane.getTable().getValueAt(rowMiddle, col)).length() > value.length() ? ((java.lang.String) gridPane.getTable().getValueAt(rowMiddle, col)).substring(0, value.length()) : (java.lang.String) gridPane.getTable().getValueAt(rowMiddle, col))); if (valueComparison == 0) { return rowMiddle; } switch (sortOrder) { case ASCENDING: if (valueComparison < 0) { if ((rowMiddle - 1) >= rowFirst) { return seek(gridPane, col, sortOrder, rowFirst, rowMiddle - 1, value); } } else { if (rowLast >= (rowMiddle + 1)) { return seek(gridPane, col, sortOrder, rowMiddle + 1, rowLast, value); } } break; case DESCENDING: if (valueComparison < 0) { if (rowLast >= (rowMiddle + 1)) { return seek(gridPane, col, sortOrder, rowMiddle + 1, rowLast, value); } } else { if ((rowMiddle - 1) >= rowFirst) { return seek(gridPane, col, sortOrder, rowFirst, rowMiddle - 1, value); } } break; default: } return -1; } private static int seek(final SGridPane gridPane, final int col, final SortOrder sortOrder, final int rowFirst, final int rowLast, final Date value) { int rowMiddle; int valueComparison; rowMiddle = rowFirst + ((rowLast - rowFirst) / 2); valueComparison = value.compareTo((java.util.Date) gridPane.getTable().getValueAt(rowMiddle, col)); if (valueComparison == 0) { return rowMiddle; } switch (sortOrder) { case ASCENDING: if (valueComparison < 0) { if ((rowMiddle - 1) >= rowFirst) { return seek(gridPane, col, sortOrder, rowFirst, rowMiddle - 1, value); } } else { if (rowLast >= (rowMiddle + 1)) { return seek(gridPane, col, sortOrder, rowMiddle + 1, rowLast, value); } } break; case DESCENDING: if (valueComparison < 0) { if (rowLast >= (rowMiddle + 1)) { return seek(gridPane, col, sortOrder, rowMiddle + 1, rowLast, value); } } else { if ((rowMiddle - 1) >= rowFirst) { return seek(gridPane, col, sortOrder, rowFirst, rowMiddle - 1, value); } } break; default: } return -1; } public static void seekValue(SGridPane gridPane, String valueToSeek) { int col = 0; int colType = SLibConsts.UNDEFINED; int row = -1; int rows = rows = gridPane.getTable().getRowCount(); double valueAsDouble = 0d; Date valueAsDate = null; SortOrder sortOrder = null; if (gridPane.getTable().getRowSorter().getSortKeys().isEmpty()) { col = gridPane.getTable().convertColumnIndexToView(0); sortOrder = SortOrder.ASCENDING; } else { col = gridPane.getTable().convertColumnIndexToView(((RowSorter.SortKey) gridPane.getTable().getRowSorter().getSortKeys().get(0)).getColumn()); sortOrder = ((RowSorter.SortKey) gridPane.getTable().getRowSorter().getSortKeys().get(0)).getSortOrder(); } if (rows > 0) { if (col >= 0 && col < gridPane.getTable().getColumnCount()) { colType = gridPane.getModel().getGridColumns().get(gridPane.getTable().convertColumnIndexToModel(col)).getColumnType(); switch (SGridUtils.getDataType(colType)) { case SLibConsts.DATA_TYPE_BOOL: case SLibConsts.DATA_TYPE_INT: case SLibConsts.DATA_TYPE_DEC: valueAsDouble = SLibUtils.parseDouble(valueToSeek); row = seek(gridPane, col, sortOrder, 0, rows - 1, valueAsDouble); break; case SLibConsts.DATA_TYPE_TEXT: row = seek(gridPane, col, sortOrder, 0, rows - 1, SLibUtils.textTrim(valueToSeek)); break; case SLibConsts.DATA_TYPE_DATE: SimpleDateFormat dateFormat = null; switch (colType) { case SGridConsts.COL_TYPE_DATE: dateFormat = SLibUtils.DateFormatDate; break; case SGridConsts.COL_TYPE_DATE_DATETIME: dateFormat = SLibUtils.DateFormatDatetime; break; case SGridConsts.COL_TYPE_DATE_TIME: dateFormat = SLibUtils.DateFormatTime; break; default: } try { valueAsDate = dateFormat.parse(valueToSeek); row = seek(gridPane, col, sortOrder, 0, rows - 1, valueAsDate); } catch (java.text.ParseException e) { SLibUtils.showException(SGridUtils.class.getName(), e); } break; default: break; } if (row == -1) { gridPane.getClient().showMsgBoxWarning(SGridConsts.ERR_MSG_VAL_NOT_FOUND + "\n(" + valueToSeek + ")"); } else { // Go back to first occurrence of value: switch (SGridUtils.getDataType(colType)) { case SLibConsts.DATA_TYPE_BOOL: case SLibConsts.DATA_TYPE_INT: case SLibConsts.DATA_TYPE_DEC: while (row > 0 && valueAsDouble == ((Number) gridPane.getTable().getValueAt(row - 1, col)).doubleValue()) { row--; } break; case SLibConsts.DATA_TYPE_TEXT: while (row > 0 && valueToSeek.compareToIgnoreCase( (((String) gridPane.getTable().getValueAt(row - 1, col)).length() > valueToSeek.length() ? ((String) gridPane.getTable().getValueAt(row - 1, col)).substring(0, valueToSeek.length()) : (String) gridPane.getTable().getValueAt(row - 1, col))) == 0) { row--; } break; case SLibConsts.DATA_TYPE_DATE: while (row > 0 && valueAsDate.compareTo((Date) gridPane.getTable().getValueAt(row - 1, col)) == 0) { row--; } break; default: } // Scroll to value: gridPane.setSelectedGridRow(row); gridPane.getTable().requestFocus(); } } } } public static void searchValue(SGridPane gridPane, String valueToSearch, boolean fromTop) { int row = 0; int col = 0; int rows = gridPane.getTable().getRowCount(); int cols = gridPane.getTable().getColumnCount(); String valueToSearchUpper = valueToSearch.toUpperCase(); if (!valueToSearchUpper.isEmpty()) { if (rows > 0) { row: for (row = fromTop ? 0 : (gridPane.getTable().getSelectedRow() + 1); row < rows; row++) { col: for (col = 0; col < cols; col++) { if (gridPane.getTable().getValueAt(row, col) != null) { if (gridPane.getTable().getValueAt(row, col).toString().toUpperCase().contains(valueToSearchUpper)) { gridPane.setSelectedGridRow(row); break row; } } } } } } } public static void saveCsv(SGridPane gridPane, java.lang.String title) { int col = 0; int colType = 0; int colModel = 0; int rowModel = 0; int row = 0; String buffer = ""; gridPane.getClient().getFileChooser().setSelectedFile(new File(title + " " + SLibUtils.FileDateFormatDatetime.format(new Date()) + ".csv")); if (gridPane.getClient().getFileChooser().showSaveDialog(gridPane.getClient().getFrame()) == JFileChooser.APPROVE_OPTION) { File file = new File(gridPane.getClient().getFileChooser().getSelectedFile().getAbsolutePath()); try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); for (col = 0; col < gridPane.getTable().getColumnCount(); col++) { colModel = gridPane.getTable().convertColumnIndexToModel(col); buffer += (buffer.length() == 0 ? "" : ",") + "\"" + SLibUtils.textToAscii(gridPane.getModel().getGridColumns().get(colModel).getColumnTitle()) + "\""; } bw.write(buffer); for (row = 0; row < gridPane.getTable().getRowCount(); row++) { buffer = ""; for (col = 0; col < gridPane.getTable().getColumnCount(); col++) { buffer += (col == 0 ? "" : ","); rowModel = gridPane.getTable().convertRowIndexToModel(row); colModel = gridPane.getTable().convertColumnIndexToModel(col); if (gridPane.getModel().getValueAt(rowModel, colModel) != null) { colType = gridPane.getModel().getGridColumns().get(colModel).getColumnType(); switch (SGridUtils.getDataType(colType)) { case SLibConsts.DATA_TYPE_BOOL: buffer += (((Boolean) gridPane.getModel().getValueAt(rowModel, colModel)).booleanValue() ? "1" : "0"); break; case SLibConsts.DATA_TYPE_INT: buffer += ((Number) gridPane.getModel().getValueAt(rowModel, colModel)).longValue(); break; case SLibConsts.DATA_TYPE_DEC: buffer += ((Number) gridPane.getModel().getValueAt(rowModel, colModel)).doubleValue(); break; case SLibConsts.DATA_TYPE_TEXT: buffer += "\"" + (!gridPane.getModel().getGridColumns().get(colModel).isApostropheOnCsvRequired() ? "" : "'") + SLibUtils.textToAscii(((String) gridPane.getModel().getValueAt(rowModel, colModel)).replaceAll("\"", "\"\"")) + "\""; break; case SLibConsts.DATA_TYPE_DATE: switch (colType) { case SGridConsts.COL_TYPE_DATE: buffer += SLibUtils.CsvFormatDate.format((Date) gridPane.getModel().getValueAt(rowModel, colModel)); break; case SGridConsts.COL_TYPE_DATE_DATETIME: buffer += SLibUtils.CsvFormatDatetime.format((Date) gridPane.getModel().getValueAt(rowModel, colModel)); break; case SGridConsts.COL_TYPE_DATE_TIME: buffer += SLibUtils.CsvFormatTime.format((Date) gridPane.getModel().getValueAt(rowModel, colModel)); break; default: } break; default: buffer += "\"?\""; } } } bw.write("\n"); bw.write(SLibUtils.textToAscii(buffer)); } bw.flush(); bw.close(); if (gridPane.getClient().showMsgBoxConfirm(SGuiConsts.MSG_FILE_SAVED + file.getPath() + "\n" + SGuiConsts.MSG_CNF_FILE_OPEN) == JOptionPane.YES_OPTION) { SLibUtils.launchFile(file.getPath()); } } catch (Exception e) { SLibUtils.showException(SGridUtils.class.getName(), e); } } } public static void computeRpn(SGridModel gridModel) { int col = 0; int row = 0; double a = 0; double b = 0; double value = 0; Deque<Object> stack = new ArrayDeque<Object>(); Vector<SLibRpnArgument> arguments = null; SLibRpnOperator operator = null; try { for (col = 0; col < gridModel.getColumnCount(); col++) { arguments = gridModel.getGridColumns().get(col).getRpnArguments(); if (arguments.size() > 0) { for (row = 0; row < gridModel.getRowCount(); row++) { for (SLibRpnArgument argument : arguments) { if (argument.getArgumentType() == SLibRpnArgumentType.OPERAND) { stack.addFirst(gridModel.getValueAtFieldName(row, (String) argument.getArgument())); } else if (argument.getArgumentType() == SLibRpnArgumentType.OPERATOR) { if (stack.size() < 2) { throw new Exception(SLibConsts.ERR_MSG_RPN_ARGS_FEW); } else { b = stack.getFirst() instanceof Boolean ? (((Boolean) stack.pollFirst()) ? 1d : 0d) : ((Number) stack.pollFirst()).doubleValue(); a = stack.getFirst() instanceof Boolean ? (((Boolean) stack.pollFirst()) ? 1d : 0d) : ((Number) stack.pollFirst()).doubleValue(); operator = (SLibRpnOperator) argument.getArgument(); switch (operator) { case ADDITION: stack.addFirst(a + b); break; case SUBTRACTION: stack.addFirst(a - b); break; case MULTIPLICATION: stack.addFirst(a * b); break; case DIVISION: stack.addFirst(b == 0d ? 0d : a / b); break; default: } } } } if (stack.size() == 1) { value = ((Number) stack.pollFirst()).doubleValue(); } else if (stack.size() < 1) { throw new Exception(SLibConsts.ERR_MSG_RPN_ARGS_FEW); } else if (stack.size() > 1) { throw new Exception(SLibConsts.ERR_MSG_RPN_ARGS_MANY); } gridModel.setValueAt(value, row, col); } } } } catch (Exception e) { SLibUtils.showException(SGridUtils.class.getName(), e); } } public static String getSqlFilterDate(final String fieldName, final SGuiDate guiDate) { String sql = ""; int[] date = null; switch (guiDate.getGuiType()) { case SGuiConsts.GUI_DATE_DATE: sql = fieldName + " = '" + SLibUtils.DbmsDateFormatDate.format(guiDate) + "' "; break; case SGuiConsts.GUI_DATE_MONTH: date = SLibTimeUtils.digestMonth(guiDate); sql = "(YEAR(" + fieldName + ") = " + date[0] + " AND MONTH(" + fieldName + ") = " + date[1] + ") "; break; case SGuiConsts.GUI_DATE_YEAR: date = SLibTimeUtils.digestYear(guiDate); sql = "YEAR(" + fieldName + ") = " + date[0] + " "; break; default: } return sql; } public static String getSqlFilterDateRange(final String fieldName, final Date[] range) { return fieldName + " BETWEEN '" + SLibUtils.DbmsDateFormatDate.format(range[0]) + "' AND '" + SLibUtils.DbmsDateFormatDate.format(range[1]) + "' "; } public static String getSqlFilterKey(final String[] fieldNames, final int[] key) { String sql = ""; if (fieldNames.length == key.length) { for (int i = 0; i < fieldNames.length; i++) { if (key[i] != SLibConsts.UNDEFINED) { sql += (sql.length() == 0 ? "" : "AND ") + fieldNames[i] + " = " + key[i] + " "; } } } return sql; } public static JButton createButton(final ImageIcon icon, final String toolTip, final ActionListener listener) { JButton button = new JButton(icon); button.setPreferredSize(new Dimension(23, 23)); button.setToolTipText(toolTip); button.addActionListener(listener); return button; } public static JTextField createTextField(final String toolTip) { return createTextField(toolTip, new Dimension(100, 23)); } public static JTextField createTextField(final String toolTip, final Dimension dimension) { JTextField textField = new JTextField(); textField.setEditable(false); textField.setFocusable(false); textField.setPreferredSize(dimension); textField.setToolTipText(toolTip); return textField; } }
Java
public class KpeInspector { private String baseFolder, outFolder; private KpeDocument doc; private IRealVector docVector; private boolean folderInitialized = false; private List<List<Phrase>> subsets; private List<Phrase> subset; public KpeInspector(KpeDocument d) { doc = d; baseFolder = KpeConfig.getProperty("inspect.output"); } private void initFolder() throws IOException { if (folderInitialized) return; outFolder = baseFolder + doc.getId()+"/"; File folder = new File(outFolder); if (!folder.exists()) { // delete files folder.mkdir(); } else { // create folder //for (File f : folder.listFiles()) f.delete(); } folderInitialized = true; } // output all candidate phrases, sorted by similarity in descending order public void phrasesBySimilarity(GreedyExtractorConfig config) throws Exception { initFolder(); GreedyExtractor extr = new GreedyExtractor(5, config); extr.prepareForExtraction(doc.getText()); PrintStream out = new PrintStream(outFolder+"phrasesBySim.txt"); out.println("solution phrases: "); PhraseHelper.printPhraseSet(out, doc.getKeyphrases(), 5, true); out.println("phrases by similarity: "); extr.printRankedCandidates(out); out.close(); } public void phrasesByFrequency(IPhraseExtractor extr) throws Exception { initFolder(); List<Phrase> phrases = extr.extractPhrases(doc.getText()); List<Integer> freqs = new ArrayList<Integer>(); for (Phrase ph: phrases) freqs.add(ph.getFrequency()); Utils.sort(phrases, freqs, true); PrintStream out = new PrintStream(outFolder+"phrasesByFreq.txt"); for (Phrase ph: phrases) { out.println(ph.getFrequency() + " | " + ph.canonicForm() + " | " + ph.toString()); } out.close(); } public void extractedPhrases(IKpextractor extr) throws Exception { initFolder(); List<Phrase> kphrases = extr.extract(doc.getText()); PrintStream out = new PrintStream(outFolder+"keyphrases_"+extr.getId()+".txt"); out.println("correct phrases:"); PhraseHelper.printPhraseSet(out, doc.getKeyphrases(), 5, true); out.println(); out.println("solution phrases:"); PhraseHelper.printPhraseSet(out, kphrases, 5, true); out.println(); // construct found and not found phrases List<Phrase> found = new ArrayList<Phrase>(); List<Phrase> notFound = new ArrayList<Phrase>(); List<Phrase> incorrect = new ArrayList<Phrase>(); for(Phrase ph : doc.getKeyphrases()) { if (kphrases.contains(ph)) found.add(ph); else notFound.add(ph); } for (Phrase ph : kphrases) { if (!doc.getKeyphrases().contains(ph)) incorrect.add(ph); } // print found and not found phrases out.println("correctly found :"); PhraseHelper.printPhraseSet(out, found, 5, true); out.println(); out.println("incorrectly found :"); PhraseHelper.printPhraseSet(out, incorrect, 5, true); out.println(); out.println("not found :"); PhraseHelper.printPhraseSet(out, notFound, 5, true); out.println(); F1Evaluator eval = new F1Evaluator(extr, IPhraseEquality.PhEquality.SEMEVAL); F1Metric result = eval.evaluateResult(kphrases, doc.getKeyphrases()); out.println(result); out.close(); } // analyze coverage of the document by phrase subsets public void coverage(List<Phrase> phrases, GreedyExtractorConfig c, int setSize) throws Exception { initFolder(); c.adaptToDocument(doc.getText()); IRealVector documentVector = c.docVectorizer.vectorize(doc.getText()); int n = phrases.size(); generateSubsets(phrases, setSize, 0, -1); List<Double> score = new ArrayList<Double>(); for (List<Phrase> ss : subsets) { c.phVectorizer.clear(); for (Phrase ph : ss) c.phVectorizer.addPhrase(ph); IRealVector vec = c.phVectorizer.vector(); double sc = c.phraseSetQuality.compare(vec, documentVector); score.add(sc); } Utils.sort(subsets, score, true); PrintStream out = new PrintStream(outFolder+"coverage"+setSize+".txt"); for (int i = 0; i < subsets.size(); ++i) { List<Phrase> ss = subsets.get(i); out.print("score: " + Utils.doubleStr(score.get(i),3) + " "); PhraseHelper.printPhraseSet(out, ss, 10, true); } out.close(); } private void generateSubsets(List<Phrase> ph, int size, int d, int i) { if (d == 0) { subsets = new ArrayList<List<Phrase>>(); subset = new ArrayList<Phrase>(); generateSubsets(ph, size, 1, 0); } else if (d <= size) { for (int j = i; j < ph.size(); ++j) { subset.add(ph.get(j)); generateSubsets(ph, size, d+1, j+1); subset.remove(subset.size()-1); } } else { subsets.add(new ArrayList<Phrase>(subset)); } } }
Java
public class CallDeleteBook { public void process(final HashMap<String, Object> params) throws JSONException{ String urlString = Constants.AWS_URL + Constants.CALL_DELETE_BOOK_URL; LogHelper.logMessage("URL", urlString); //Extracting ONLY REQUIRED params JSONObject requestJSON = null; final Context context; final String action; final View view; final UpdateDeleteFragment fragment; final Activity activity; requestJSON = (JSONObject) params.get(Constants.REQUEST_JSON); context = (Context) params.get(Constants.CONTEXT); action = (String) params.get(Constants.ACTION); view = (View) params.get(Constants.VIEW); fragment = (UpdateDeleteFragment) params.get(Constants.FRAGMENT); activity = (Activity) params.get(Constants.ACTIVITY); //Now making the request JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.POST, urlString, requestJSON, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { try { HashMap returnHashMap = new HashMap<String, String>(); Boolean isSuccess = jsonObject.getBoolean("success"); if(isSuccess){ String message = jsonObject.getString("message"); LogHelper.logMessage("Siddharth","\n message: " + message); updateUI(fragment, context, action, activity, returnHashMap, params); }else{ UpdateDeleteFragment.showProgress(false); HashMap<String, Object> extraParams = new HashMap<String, Object>(); extraParams.put("activity", activity); ExceptionMessageHandler.handleError(context, jsonObject.getString("message"), null, extraParams); } }catch (JSONException e){ UpdateDeleteFragment.showProgress(false); HashMap<String, Object> extraParams = new HashMap<String, Object>(); extraParams.put("activity", activity); ExceptionMessageHandler.handleError(context, e.getMessage(), e, extraParams); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { String errorMessage = error.getMessage(); NetworkResponse networkResponse = error.networkResponse; if (networkResponse != null && networkResponse.data != null) { try { JSONObject jsonError = new JSONObject(new String(networkResponse.data)); errorMessage = jsonError.getString("message"); } catch (JSONException e) { UpdateDeleteFragment.showProgress(false); ExceptionMessageHandler.handleError(context, Constants.GENERIC_ERROR_MSG, null, null); } } UpdateDeleteFragment.showProgress(false); error.printStackTrace(); HashMap<String, Object> hs = new HashMap<String, Object>(); hs.put("activity", activity); ExceptionMessageHandler.handleError(context, errorMessage, error, hs); } }); RequestClass.getRequestQueue().add(jsObjRequest); } public void updateUI(Fragment fragment, Context context, String action, Activity activity, HashMap<String, String> returnHashMap, HashMap<String,Object> extraparams){ switch (action) { case Constants.ACTION_DELETE_BOOK: UpdateDeleteFragment.showProgress(false); Toast.makeText(activity, "Book deleted.", Toast.LENGTH_SHORT).show(); fragment.getFragmentManager().beginTransaction().replace(R.id.place_holder,new ListFragment()).addToBackStack(null).commit(); // Intent intent=new Intent(fragment.getActivity(),CatalogActivity.class); // fragment.startActivity(intent); } } }
Java
public class ReservedStringExpression extends SimpleStringExpression { public ReservedStringExpression(String token) throws URITemplateException { super(token); } @Override protected boolean isReserved(char ch) { return false; } @Override protected String encodeValue(String value) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (super.isReserved(ch)) { builder.append(ch); } else { builder.append(super.encodeValue(String.valueOf(ch))); } } return builder.toString(); } @Override protected boolean setVariables(String expressionValue, Map<String, String> variables) { if (variableList.size() == 1) { Variable var = variableList.get(0); String name = var.getName(); String finalValue = decodeValue(expressionValue); if (variables.containsKey(name) && !finalValue.equals(variables.get(name))) { return false; } if (var.checkModifier(finalValue)) { variables.put(name, finalValue); return true; } else { return false; } } return super.setVariables(expressionValue, variables); } }
Java
public class runSerializerComplex extends CommandBase { private final Serializer subsystem; private double serializerSpeed; public double resetti; public boolean bottomSensorValue; public boolean topSensorValue; /** * Runs the serializer forever in a single command * * @author Nicholas Stokes * @param serializer The subsystem used by this command. (Serializer) * @param speed A double number that sets what speed the motors move at */ public runSerializerComplex(Serializer serializer, double speed) { subsystem = serializer; serializerSpeed = speed; // Use addRequirements() here to declare subsystem dependencies. addRequirements(subsystem); } // Called when the command is initially scheduled. @Override public void initialize() { // Sets up the reset value and the sensorValue boolean needed for the execute command bottomSensorValue = false; topSensorValue = false; resetti = 0; } @Override public void execute() { /* * This command is pretty simple but also complex. If the sensor value is true, * the serializer runs until it turns false which then flips a boolean to true, * which then locks the command inside a wait, After 0.01 second, the boolean * turns false and then the cycle continues. */ if ((bottomSensorValue == true) && (topSensorValue == true)) { subsystem.stopSerializer(); } else { if (subsystem.bottomSerializerSensor.get() == true) { subsystem.setSerializerSpeed(serializerSpeed); bottomSensorValue = true; } else if (subsystem.bottomSerializerSensor.get() == false) { subsystem.stopSerializer(); } else if (subsystem.topSerializerSensor.get() == false) { subsystem.stopSerializer(); } else if (subsystem.bottomSerializerSensor.get() == true) { topSensorValue = true; } } } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) { subsystem.stopSerializer(); } @Override public boolean isFinished() { return false; } }
Java
@SuppressWarnings("serial") public class CPMXYStepRenderer extends XYStepRenderer { private final CPMLogHandler perfLog; private final CPMPreferencesHandler plotPrefs; // Flag that indicates a data gap exists between two data points private boolean gapFlag; // Start and end of the data gap private double x0gap; private double x1gap; // Storage for the second x-coordinate from the previous set of coordinates private int prevX1; /************************************************************************** * Modified JFreeChart XYStepRenderer constructor *************************************************************************/ public CPMXYStepRenderer(CPMLogHandler perfLog, CPMPreferencesHandler plotPrefs) { super(); this.perfLog = perfLog; this.plotPrefs = plotPrefs; } // //////////////////////////////////////////////////////////////////////// // Begin modification to JFreeChart stock code /************************************************************************** * Shade the area under a step (enter to exit event sequence) * * @param g2 * the graphics target * * @param plot * the plot (can be used to obtain standard color information * etc.) * * @param series * the series index (zero-based) * @param x0 * * the x-coordinate for the starting point of the line * * @param y0 * the y-coordinate for the starting point of the line * * @param x1 * the x-coordinate for the ending point of the line * * @param y1 * the y-coordinate for the ending point of the line *************************************************************************/ private void shadeUnderStep(Graphics2D g2, XYPlot plot, int series, double x0, double y0, double x1, double y1) { Polygon pArea = new Polygon(); // Set the color to the outline (fill) color g2.setPaint(plot.getRenderer().getSeriesOutlinePaint(series)); // Check if the two data points encompass a gap in the log data (due // to multiple log files); don't fill the gap area if (gapFlag) { // Check if there is any space between the starting point and the // start of the gap if (x0 < x0gap) { // Set the four corners of the shaded rectangle starting with // the first point and stopping at the beginning of the gap pArea.addPoint((int) x0, (int) y0); pArea.addPoint((int) x0, (int) y1); pArea.addPoint((int) x0gap, (int) y1); pArea.addPoint((int) x0gap, (int) y0); // Fill the polygon g2.fill(pArea); } // Check is there is any space between the end of the gap and the // ending point if (x1 > x1gap) { // Set the four corners of the shaded rectangle starting with // the end of the gap and stopping at the second point pArea.addPoint((int) x1gap, (int) y0); pArea.addPoint((int) x1gap, (int) y1); pArea.addPoint((int) x1, (int) y1); pArea.addPoint((int) x1, (int) y0); // Fill the polygon g2.fill(pArea); } } // No data gap; fill the entire area else { // Set the four corners of the shaded rectangle starting at the // first point and stopping at the second pArea.addPoint((int) x0, (int) y0); pArea.addPoint((int) x0, (int) y1); pArea.addPoint((int) x1, (int) y1); pArea.addPoint((int) x1, (int) y0); // Fill the polygon g2.fill(pArea); } // Restore the color to the line color g2.setPaint(plot.getRenderer().getSeriesPaint(0)); } // End modification to stock code // //////////////////////////////////////////////////////////////////////// /** * A utility method that draws a line but only if none of the coordinates * are NaN values. * * @param g2 * the graphics target. * @param line * the line object. * @param x0 * the x-coordinate for the starting point of the line. * @param y0 * the y-coordinate for the starting point of the line. * @param x1 * the x-coordinate for the ending point of the line. * @param y1 * the y-coordinate for the ending point of the line. */ private void drawLine(Graphics2D g2, Line2D line, double x0, double y0, double x1, double y1) { if (Double.isNaN(x0) || Double.isNaN(x1) || Double.isNaN(y0) || Double.isNaN(y1)) { return; } line.setLine(x0, y0, x1, y1); g2.draw(line); } /** * Draws the visual representation of a single data item. * * @param g2 * the graphics device. * @param state * the renderer state. * @param dataArea * the area within which the data is being drawn. * @param info * collects information about the drawing. * @param plot * the plot (can be used to obtain standard color information * etc). * @param domainAxis * the domain axis. * @param rangeAxis * the vertical axis. * @param dataset * the dataset. * @param series * the series index (zero-based). * @param item * the item index (zero-based). * @param crosshairState * crosshair information for the plot (<code>null</code> * permitted). * @param pass * the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // do nothing if item is not visible if (!getItemVisible(series, item)) { return; } PlotOrientation orientation = plot.getOrientation(); Paint seriesPaint = getItemPaint(series, item); Stroke seriesStroke = getItemStroke(series, item); g2.setPaint(seriesPaint); g2.setStroke(seriesStroke); // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = (Double.isNaN(y1) ? Double.NaN : rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation)); // //////////////////////////////////////////////////////////////////// // Begin modification to JFreeChart stock code // Check if this is the first point to be plotted if (item == 0) { // Reset the x-coordinate comparison value prevX1 = -1; } // End modification to stock code // //////////////////////////////////////////////////////////////////// if (pass == 0 && item > 0) { // get the previous data point... double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = (Double.isNaN(y0) ? Double.NaN : rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation)); // //////////////////////////////////////////////////////////////// // Begin modification to JFreeChart stock code // Check that the points aren't redrawing the same vertical line // on the screen as the previous points. Skipping these saves time // when redrawing if ((int) transX1 != prevX1) { /** * Note: The code below allows plotting of the step lines * either horizontally or vertically. CPM only plots * horizontally so this code is commented out */ // if (orientation == PlotOrientation.HORIZONTAL) // { // if (transY0 == transY1) // { // // this represents the situation // // for drawing a horizontal bar. // drawLine(g2, state.workingLine, transY0, transX0, transY1, // transX1); // } // else // { // this handles the need to perform a 'step'. // // // calculate the step point // double transXs = transX0 + (getStepPoint() // * (transX1 - transX0)); // drawLine(g2, state.workingLine, transY0, transX0, transY0, // transXs); // drawLine(g2, state.workingLine, transY0, transXs, transY1, // transXs); // drawLine(g2, state.workingLine, transY1, transXs, transY1, // transX1); // } // } // else if (orientation == PlotOrientation.VERTICAL) // { // Initialize the flag to assume no gap between the two points gapFlag = false; // Step through the array of gaps for (int index = 0; index < perfLog.getDataGapIndex().size(); index++) { // Check if the two points encompass this gap if (x0 <= perfLog.getPerfLogData().get(perfLog.getDataGapIndex().get(index) - 1).getTimeStamp() && x1 >= perfLog.getPerfLogData().get(perfLog.getDataGapIndex().get(index)).getTimeStamp()) { // Store the x-coordinates of the beginning and ending // of the gap; the values are adjusted by 1 to prevent // shading over a plot line x0gap = domainAxis.valueToJava2D(perfLog.getPerfLogData().get(perfLog.getDataGapIndex().get(index) - 1).getTimeStamp(), dataArea, xAxisLocation) - 1; x1gap = domainAxis.valueToJava2D(perfLog.getPerfLogData().get(perfLog.getDataGapIndex().get(index)).getTimeStamp(), dataArea, xAxisLocation) + 1; // Set the flag to indicate that a gap exists gapFlag = true; } } // End modification to stock code // //////////////////////////////////////////////////////// if (transY0 == transY1) { // //////////////////////////////////////////////////// // Begin modification to JFreeChart stock code // Check if this horizontal line is not at the exit // event level (i.e., between an exit and enter event). // If it is, check if showing these lines is enabled if (y0 != EXIT || plotPrefs.isStepPlotShowExit(false)) { // End modification to stock code // //////////////////////////////////////////////// // this represents the situation // for drawing a horizontal bar. drawLine(g2, state.workingLine, transX0, transY0, transX1, transY1); // //////////////////////////////////////////////////// // Begin modification to JFreeChart stock code } // Check if the user has shading enabled and that both of // the y-values are entry events (= 1). This accounts // for two entry events occurring without an // intervening exit event, and also if the last y-value // is an exit event if (y0 != EXIT && plotPrefs.isStepPlotShowShading(false)) { double transYx = rangeAxis.valueToJava2D(EXIT, dataArea, yAxisLocation); // Shade within the four corners of the rectangle shadeUnderStep(g2, plot, series, transX0 + 1, transYx + 1, transX1 + 1, transY1 + 1); } // End modification to stock code // //////////////////////////////////////////////////////// } else { // this handles the need to perform a 'step'. // calculate the step point double transXs = transX0 + (getStepPoint() * (transX1 - transX0)); // //////////////////////////////////////////////////////// // Begin modification to JFreeChart stock code // Check if user has shading enabled if (plotPrefs.isStepPlotShowShading(false)) { // Only shade when stepping "down" if ((int) transY0 < (int) transY1) { // Shade within the four corners of the // rectangle shadeUnderStep(g2, plot, series, transX0 + 1, transY0, transXs, transY1 + 1); } } // Check if this horizontal line is not at the exit // event level (i.e., between an exit and enter event). // If it is, check if showing these lines is enabled if (y0 != EXIT || plotPrefs.isStepPlotShowExit(false)) { // End modification to stock code // //////////////////////////////////////////////////// drawLine(g2, state.workingLine, transX0, transY0, transXs, transY0); // //////////////////////////////////////////////////// // Begin modification to JFreeChart stock code } // End modification to stock code // //////////////////////////////////////////////////////// drawLine(g2, state.workingLine, transXs, transY0, transXs, transY1); // //////////////////////////////////////////////////////// // Begin modification to JFreeChart stock code // Check if this horizontal line is not at the exit // event level (i.e., between an exit and enter event). // If it is, check if showing these lines is enabled if (y1 != EXIT || plotPrefs.isStepPlotShowExit(false)) { // End modification to stock code // //////////////////////////////////////////////////// drawLine(g2, state.workingLine, transXs, transY1, transX1, transY1); // //////////////////////////////////////////////////// // Begin modification to JFreeChart stock code } // End modification to stock code // //////////////////////////////////////////////////////// } // //////////////////////////////////////////////////////////// // Begin modification to JFreeChart stock code // } // Note: Closing brace for code commented out above } // Store the second x-coordinate of this point pair for comparison // on the next pass prevX1 = (int) transX1; // End modification to stock code // //////////////////////////////////////////////////////////////// // submit this data item as a candidate for the crosshair point int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, orientation); // collect entity and tool tip information... EntityCollection entities = state.getEntityCollection(); if (entities != null) { addEntity(entities, null, dataset, series, item, transX1, transY1); } } if (pass == 1) { // draw the item label if there is one... if (isItemLabelVisible(series, item)) { double xx = transX1; double yy = transY1; if (orientation == PlotOrientation.HORIZONTAL) { xx = transY1; yy = transX1; } drawItemLabel(g2, orientation, dataset, series, item, xx, yy, (y1 < 0.0)); } } } }
Java
@JsonIgnoreProperties(ignoreUnknown=true) public class Expense implements Serializable { String name,category,user,date,amount,id; public String getId() { return id; } public void setId(String id) { this.id = id; } public Expense() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } }
Java
public class ClassAspectTest extends Base{ // @Autowired // private FlyMockProperties flyMockProperties; @Autowired private ClassAspect classAspect; @Test public void test() { Integer hello = classAspect.hello(); } }
Java
public class BaseMethods { public static String CACHE_LOG = "cache_log"; public static final int DEFAULT_TIMEOUT = 5; private OkHttpClient.Builder builder; //设置缓存路径 private File httpCacheDirectory = new File(Application.getContext().getCacheDir(), "responses"); //设置缓存 10M private Cache cache = new Cache(httpCacheDirectory, 20 * 1024 * 1024); private Interceptor interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (!NetworkState.networkConnected(Application.getContext())) { request = request.newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .build(); } Response response = chain.proceed(request); if (NetworkState.networkConnected(Application.getContext())) { String cacheControl = request.cacheControl().toString(); response = response.newBuilder() .removeHeader("Pragma") .removeHeader("Cache-Control") .header("Cache-Control", cacheControl) .build(); } else { int maxStale = 60 * 60 * 24 * 7; // 没网一周后失效 response = response.newBuilder() .removeHeader("Pragma") .removeHeader("Cache-Control") .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) .build(); } return response; } }; public OkHttpClient getOkHttpClientBuilder() { if (builder == null) { builder = new OkHttpClient.Builder() .addNetworkInterceptor(interceptor) .addInterceptor(interceptor) .cache(cache); builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); } return builder.build(); } }
Java
public class SQLIdFilter<T extends DataObject> implements SQLFilter<T>, PatternFilter<T>{ public SQLIdFilter(Class<T> target,Repository res, int id) { this( target,res,id,false); } public SQLIdFilter(Class<T> target,Repository res, int id,boolean exclude) { super(); this.target=target; this.res = res; this.id=id; this.exclude=exclude; } private final Class<T> target; private final Repository res; private final int id; private final boolean exclude; @Override public void accept(T o) { } @Override public List<PatternArgument> getParameters(List<PatternArgument> list) { list.add(new ConstPatternArgument<>(Integer.class, id)); return list; } @Override public StringBuilder addPattern(Set<Repository> tables,StringBuilder sb, boolean qualify) { res.addUniqueName(sb, qualify, true); if( exclude) { sb.append("!=?"); }else { sb.append("=?"); } return sb; } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.BaseFilter#accept(uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor) */ @Override public <X> X acceptVisitor(FilterVisitor<X,T> vis) throws Exception { return vis.visitPatternFilter(this); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.Targetted#getTarget() */ @Override public Class<T> getTarget() { return target; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SQLIdFilter(id="); sb.append(Integer.toString(id)); sb.append(")"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (exclude ? 1231 : 1237); result = prime * result + id; result = prime * result + ((res == null) ? 0 : res.hashCode()); result = prime * result + ((target == null) ? 0 : target.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SQLIdFilter other = (SQLIdFilter) obj; if (exclude != other.exclude) return false; if (id != other.id) return false; if (res == null) { if (other.res != null) return false; } else if (!res.equals(other.res)) return false; if (target == null) { if (other.target != null) return false; } else if (!target.equals(other.target)) return false; return true; } }
Java
public class MountDelegate { private final LongSparseArray<Integer> mReferenceCountMap = new LongSparseArray<>(); private final List<MountExtension> mMountExtensions = new ArrayList<>(); private final MountDelegateTarget mMountDelegateTarget; private final Map<MountExtension, ExtensionState> mExtensionStates = new HashMap<>(); private @Nullable ExtensionState mUnmountDelegateExtensionState; private boolean mReferenceCountingEnabled = false; public MountDelegate(MountDelegateTarget mountDelegateTarget) { mMountDelegateTarget = mountDelegateTarget; } public void addExtension(MountExtension mountExtension) { final ExtensionState extensionState = mountExtension.createExtensionState(this); if (mountExtension instanceof UnmountDelegateExtension) { mMountDelegateTarget.setUnmountDelegateExtension((UnmountDelegateExtension) mountExtension); mUnmountDelegateExtensionState = extensionState; } mReferenceCountingEnabled = mReferenceCountingEnabled || mountExtension.canPreventMount(); mExtensionStates.put(mountExtension, extensionState); mMountExtensions.add(mountExtension); } public void removeExtension(MountExtension mountExtension) { mMountExtensions.remove(mountExtension); mExtensionStates.remove(mountExtension); if (mountExtension instanceof UnmountDelegateExtension) { mMountDelegateTarget.removeUnmountDelegateExtension(); mUnmountDelegateExtensionState = null; } updateRefCountEnabled(); } void unregisterAllExtensions() { mMountExtensions.clear(); mExtensionStates.clear(); mReferenceCountingEnabled = false; } private void updateRefCountEnabled() { mReferenceCountingEnabled = false; for (int i = 0, size = mMountExtensions.size(); i < size; i++) { mReferenceCountingEnabled = mReferenceCountingEnabled || mMountExtensions.get(i).canPreventMount(); } } void unBind() { for (int i = 0, size = mMountExtensions.size(); i < size; i++) { final MountExtension mountExtension = mMountExtensions.get(i); mountExtension.onUnbind(getExtensionState(mountExtension)); } } void unMount() { for (int i = 0, size = mMountExtensions.size(); i < size; i++) { final MountExtension mountExtension = mMountExtensions.get(i); mountExtension.onUnmount(getExtensionState(mountExtension)); } } void onBindItem(final RenderUnit renderUnit, final Object content, final Object layoutData) { for (int i = 0, size = mMountExtensions.size(); i < size; i++) { final MountExtension extension = mMountExtensions.get(i); extension.onBindItem(getExtensionState(extension), renderUnit, content, layoutData); } } void onUnbindItem(final RenderUnit renderUnit, final Object content, final Object layoutData) { for (int i = 0, size = mMountExtensions.size(); i < size; i++) { final MountExtension extension = mMountExtensions.get(i); extension.onUnbindItem(getExtensionState(extension), renderUnit, content, layoutData); } } void onUpdateItemsIfNeeded( final @Nullable RenderUnit<?> previousRenderUnit, final @Nullable Object previousLayoutData, final @Nullable RenderUnit<?> nextRenderUnit, final @Nullable Object nextLayoutData, final Object content) { for (int i = 0, size = mMountExtensions.size(); i < size; i++) { final MountExtension extension = mMountExtensions.get(i); final ExtensionState state = getExtensionState(extension); if (extension.shouldUpdateItem( previousRenderUnit, previousLayoutData, nextRenderUnit, nextLayoutData)) { extension.onUnbindItem(state, previousRenderUnit, content, previousLayoutData); extension.onBindItem(state, nextRenderUnit, content, nextLayoutData); } } } public void onMountItem( final RenderUnit renderUnit, final Object content, final Object layoutData) { for (int i = 0, size = mMountExtensions.size(); i < size; i++) { final MountExtension extension = mMountExtensions.get(i); extension.onMountItem(getExtensionState(extension), renderUnit, content, layoutData); } } public void onUnmountItem( final RenderUnit renderUnit, final Object content, final @Nullable Object layoutData) { for (int i = 0, size = mMountExtensions.size(); i < size; i++) { final MountExtension extension = mMountExtensions.get(i); extension.onUnmountItem(getExtensionState(extension), renderUnit, content, layoutData); } } public ExtensionState getExtensionState(MountExtension mountExtension) { return mExtensionStates.get(mountExtension); } @Nullable public ExtensionState getUnmountDelegateExtensionState() { return mUnmountDelegateExtensionState; } public Object getContentAt(int position) { return mMountDelegateTarget.getContentAt(position); } public @Nullable Object getContentById(long id) { return mMountDelegateTarget.getContentById(id); } public boolean isRootItem(int position) { return mMountDelegateTarget.isRootItem(position); } /** @return true if this item needs to be mounted. */ public boolean maybeLockForMount(RenderTreeNode renderTreeNode, int index) { if (!mReferenceCountingEnabled) { return true; } for (int i = 0, size = mMountExtensions.size(); i < size; i++) { final MountExtension mountExtension = mMountExtensions.get(i); mountExtension.beforeMountItem(getExtensionState(mountExtension), renderTreeNode, index); } return hasAcquiredRef(renderTreeNode.getRenderUnit().getId()); } public boolean isLockedForMount(RenderTreeNode renderTreeNode) { return isLockedForMount(renderTreeNode.getRenderUnit().getId()); } public boolean isLockedForMount(long id) { if (!mReferenceCountingEnabled) { return true; } return hasAcquiredRef(id); } private boolean hasAcquiredRef(long renderUnitId) { final Integer refCount = mReferenceCountMap.get(renderUnitId); return refCount != null && refCount > 0; } @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) public void acquireMountRef(final RenderTreeNode node) { acquireMountRef(node.getRenderUnit().getId()); } public void acquireMountRef(final long id) { incrementExtensionRefCount(id); } public void acquireAndMountRef(final RenderTreeNode node) { acquireAndMountRef(node.getRenderUnit().getId()); } public void acquireAndMountRef(final long id) { acquireMountRef(id); // Only mount if we're during a mounting phase, otherwise the mounting phase will take care of // that. mMountDelegateTarget.notifyMount(id); } @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) public void releaseMountRef(final RenderTreeNode renderTreeNode) { releaseMountRef(renderTreeNode.getRenderUnit().getId()); } public void releaseMountRef(final long id) { decrementExtensionRefCount(id); } public void releaseAndUnmountRef(final RenderTreeNode renderTreeNode) { releaseAndUnmountRef(renderTreeNode.getRenderUnit().getId()); } public void releaseAndUnmountRef(final long id) { final boolean wasLockedForMount = isLockedForMount(id); releaseMountRef(id); if (wasLockedForMount && !isLockedForMount(id)) { mMountDelegateTarget.notifyUnmount(id); } } public void releaseAllAcquiredReferences() { if (!mReferenceCountingEnabled) { return; } for (MountExtension<?, ?> extension : mMountExtensions) { final ExtensionState state = getExtensionState(extension); state.releaseAllAcquiredReferences(); } mReferenceCountMap.clear(); } private void incrementExtensionRefCount(long renderUnitId) { if (!mReferenceCountingEnabled) { return; } Integer refCount = mReferenceCountMap.get(renderUnitId); if (refCount == null) { refCount = 0; } mReferenceCountMap.put(renderUnitId, refCount + 1); } private void decrementExtensionRefCount(final long renderUnitId) { if (!mReferenceCountingEnabled) { return; } Integer refCount = mReferenceCountMap.get(renderUnitId); if (refCount == null || refCount == 0) { throw new IllegalStateException( "Trying to decrement reference count for an item you don't own."); } mReferenceCountMap.put(renderUnitId, refCount - 1); } public MountDelegateTarget getMountDelegateTarget() { return mMountDelegateTarget; } @VisibleForTesting public int getRefCount(long id) { return mReferenceCountMap.get(id); } }
Java
public class EdDsaKeyGenerator implements KeyGenerator { private final EdKeyAnalyzer analyzer; private final SchemeProvider schemeProvider; public EdDsaKeyGenerator(SchemeProvider schemeProvider) { if (schemeProvider == null) { throw new IllegalArgumentException("SchemeProvider must not be null."); } this.schemeProvider = schemeProvider; Curve curve = schemeProvider.getCurve(); this.analyzer = new EdKeyAnalyzer(curve); } @Override public EdKeyAnalyzer getKeyAnalyzer() { return analyzer; } @Override public KeyPair generateKeyPair() { PrivateKey privateKey = schemeProvider.generatePrivateKey(); return generateKeyPair(privateKey); } @Override public KeyPair generateKeyPair(PrivateKey privateKey) { PublicKey publicKey = derivePublicKey(privateKey); return new KeyPair(privateKey, publicKey, analyzer); } @Override public PublicKey derivePublicKey(PrivateKey privateKey) { if (privateKey == null) { throw new IllegalArgumentException("PrivateKey must not be null."); } PublicKeyDelegate delegate = schemeProvider.getPublicKeyDelegate(); byte[] publicKeySeed = delegate.generatePublicKeySeed(privateKey); return new PublicKey(publicKeySeed); } }
Java
@API(status = INTERNAL, since = "1.0") final class Expressions { /** * @param expression Possibly named with a non-empty symbolic name. * @param <T> The type being returned * @return The name of the expression if the expression is named or the expression itself. */ static <T> T nameOrExpression(T expression) { if (expression instanceof Named) { return ((Named) expression).getSymbolicName().map(v -> (T) v).orElse(expression); } else { return expression; } } static Expression[] createSymbolicNames(String[] variables) { return Arrays.stream(variables).map(SymbolicName::create).toArray(Expression[]::new); } static Expression[] createSymbolicNames(Named[] variables) { return Arrays.stream(variables).map(Named::getRequiredSymbolicName) .toArray(Expression[]::new); } private Expressions() { } }
Java
public final class DefaultArraySpectrum implements ArraySpectrum { // The spectral data. _data = new double[2][num_data_points] // data[0][i] = x values // data[1][i] = y values private final double[][] _data; public static DefaultArraySpectrum fromUserSpectrum(String spectrum) { final double[][] data = DatFile.fromUserSpectrum(spectrum); return new DefaultArraySpectrum(data); } /** * Construct a DefaultSpectrum. Lists represent data point pairs * so they must have the same length. */ public DefaultArraySpectrum(final List<Double> xs, final List<Double> ys) { assert xs.size() == ys.size(); _data = new double[2][xs.size()]; for (int i = 0; i < xs.size(); ++i) { _data[0][i] = xs.get(i); _data[1][i] = ys.get(i); } } /** * Construct a DefaultSpectrum. Data array must be of this form: * double data[][] = new double[2][length]; * data[0][i] = x values * data[1][i] = y values */ public DefaultArraySpectrum(final double[][] data) { assert data.length == 2; assert data[0].length == data[1].length; _data = new double[2][]; _data[0] = data[0].clone(); _data[1] = data[1].clone(); } /** * Constructs a DefaultArraySpectrum from the specified file. * * @param fileName This method uses class.getResource() to search * for this resource. So fileName should be relative to some * location on the classpath. * <p/> * Each line of a ArraySpectrum data file consists of two doubles * separated by whitespace or comma. */ public DefaultArraySpectrum(String fileName) { final double[][] data = DatFile.arrays().apply(fileName); // for now make a copy of cached values, just to be on the safe side _data = new double[2][]; _data[0] = data[0].clone(); _data[1] = data[1].clone(); } /** * Implements Cloneable interface */ @Override public Object clone() { // constructor will clone the data array return new DefaultArraySpectrum(_data); } /** * @return starting x value */ @Override public double getStart() { return _data[0][0]; } /** * @return ending x value */ @Override public double getEnd() { return _data[0][_data[0].length - 1]; } /** * Returns x value of specified data point. */ @Override public double getX(int index) { return _data[0][index]; } /** * Returns y value of specified data point. */ @Override public double getY(int index) { return _data[1][index]; } /** * @return y value at specified x using linear interpolation. * Silently returns zero if x is out of spectrum range. */ @Override public double getY(double x) { if (x < getStart() || x > getEnd()) return 0; int low_index = getLowerIndex(x); int high_index = low_index + 1; double y1 = getY(low_index); double y2 = getY(high_index); double x1 = getX(low_index); double x2 = getX(high_index); double slope = (y2 - y1) / (x2 - x1); return (slope * (x - x1) + y1); } /** * @return number of bins in the histogram (number of data points) */ @Override public int getLength() { return _data[0].length; } /** * Returns the index of the data point with largest x value less than x */ @Override public int getLowerIndex(double x) { // In a general spectrum we don't have an idea which bin a particular // x value is in. The only solution is to search for it. // Could just walk through, but do a binary search for it. int low_index = 0; int high_index = _data[0].length; if (high_index - low_index <= 1) return low_index; while (high_index - low_index > 1) { int index = (high_index + low_index) / 2; if (getX(index) < x) low_index = index; else high_index = index; } return low_index; } @Override public void applyWavelengthCorrection() { for (int i = 0; i < getLength(); ++i) { _data[1][i] = _data[1][i] * _data[0][i]; } } /** * Sets y value in specified x bin. * If specified bin is out of range, this is a no-op. */ @Override public void setY(int index, double y) { if (index < 0 || index >= getLength()) return; // no-op _data[1][index] = y; } /** * Rescales X axis by specified factor. */ @Override public void rescaleX(double factor) { if (factor == 1.0) return; for (int i = 0; i < getLength(); ++i) { _data[0][i] *= factor; } } /** * Rescales Y axis by specified factor. */ @Override public void rescaleY(double factor) { if (factor == 1.0) return; for (int i = 0; i < getLength(); ++i) { _data[1][i] *= factor; } } @Override public void smoothY(int smoothing_element) { if (smoothing_element == 1.0) return; for (int i = 0; i < getLength(); ++i) { try { if (i + smoothing_element > getLength()) _data[1][i] = getAverage(i, getLength()); else _data[1][i] = getAverage(i, i + smoothing_element); } catch (Exception e) { System.out.println(e.toString()); } } } /** * Returns the integral of entire spectrum. */ @Override public double getIntegral() { return getIntegral(getStart(), getEnd()); } /** * Returns the integral of y values in the spectrum in * the specified range. */ public double getIntegral(double x_start, double x_end) { assert x_start <= x_end; assert x_start >= getStart() && x_start <= getEnd(); assert x_end >= getStart() && x_end <= getEnd(); // Add up trapezoid areas. // x1 and x2 may not be exactly on sampling points so do // first and last trapezoid separately. double area = 0.0; int start_index, end_index; double delta_x, y1, y2, x1, x2; x1 = x_start; start_index = getLowerIndex(x1); start_index++; // right side of first trapezoid x2 = getX(start_index); y1 = getY(x1); y2 = getY(start_index); delta_x = x2 - x1; area += delta_x * (y1 + y2) / 2.0; x2 = x_end; end_index = getLowerIndex(x2); x1 = getX(end_index); y2 = getY(x2); y1 = getY(end_index); delta_x = x2 - x1; area += delta_x * (y1 + y2) / 2.0; area += getIntegral(start_index, end_index); return area; } /** * Returns the integral of values in the ArraySpectrum in the * specified range between specified indices. */ public double getIntegral(int start_index, int end_index) { assert start_index <= end_index; assert start_index >= 0 && start_index < getLength(); assert end_index >= 0 && end_index < getLength(); double area = 0.0; double delta_x,y1, y2, x1, x2; // Add up trapezoid areas. for (int index = start_index; index < end_index; ++index) { x1 = getX(index); x2 = getX(index + 1); y1 = getY(index); y2 = getY(index + 1); delta_x = x2 - x1; area += delta_x * (y2 + y1) / 2.0; } return area; } /** * Returns the average of values in the SampledSpectrum in * the specified range. */ @Override public double getAverage(double x_start, double x_end) { return getIntegral(x_start, x_end) / (x_end - x_start); } /** * Returns the average of values in the SampledSpectrum in * the specified range. */ private double getAverage(int indexStart, int indexEnd) { return getIntegral(indexStart, indexEnd) / (getX(indexEnd) - getX(indexStart)); } /** * This returns a 2d array of the SED data used to chart the SED * using JClass Chart. The array has the following dimensions * double data[][] = new double[2][getLength()]; * data[0][i] = x values * data[1][i] = y values * May return reference to member data, so client should not * alter the return value. */ @Override public double[][] getData() { return _data; } /** * This returns a 2d array of the SED data used to chart the SED * using JClass Chart. The array has the following dimensions * double data[][] = new double[2][getLength()]; * data[0][i] = x values * data[1][i] = y values * * @param maxIndex data returned up to maximum specified * x bin. If maxIndex >= number of data points, maxIndex * will be truncated. */ @Override public double[][] getData(int maxIndex) { return getData(0, maxIndex); } /** * This returns a 2d array of the SED data used to chart the SED * using JClass Chart. The array has the following dimensions * double data[][] = new double[2][getLength()]; * data[0][i] = x values * data[1][i] = y values * * @param minIndex data returned from minimum specified * @param maxIndex data returned up to maximum specified * x bin. If maxIndex >= number of data points, maxIndex * will be truncated. */ @Override public double[][] getData(int minIndex, int maxIndex) { if (minIndex < 0) minIndex = 0; if (maxIndex >= _data[0].length) maxIndex = _data[0].length - 1; double[][] data = new double[2][maxIndex - minIndex + 1]; for (int i = minIndex; i <= maxIndex; i++) { data[0][i - minIndex] = _data[0][i]; data[1][i - minIndex] = _data[1][i]; } return data; } }
Java
public class AccessLogFormatter extends Formatter { @Override public String format(LogRecord logRecord) { return logRecord.getMessage() + '\n'; } }
Java
public class SweDataRecord extends SweAbstractDataRecord { @Override public SweDataComponentType getDataComponentType() { return SweDataComponentType.DataRecord; } @Override public SweDataRecord addField(final SweField field) { return (SweDataRecord) super.addField(field); } @Override public int hashCode() { return Objects.hash(42, super.hashCode(), 7, getDataComponentType()); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return super.equals(obj); } @Override public String toString() { return String.format("SweDataRecord [fields=%s, definition=%s, label=%s, identifier=%s, xml=%s]", getFields(), getDefinition(), getLabel(), getIdentifier(), getXml()); } @Override public <T, X extends Throwable> T accept(SweDataComponentVisitor<T, X> visitor) throws X { return visitor.visit(this); } @Override public <X extends Throwable> void accept(VoidSweDataComponentVisitor<X> visitor) throws X { visitor.visit(this); } @Override public SweDataRecord copy() { SweDataRecord copy = new SweDataRecord(); copyValueTo(copy); getFields().stream().map(SweField::copy).forEach(copy::addField); return copy; } }
Java
public class MockObdGatewayService extends AbstractGatewayService { private static final String TAG = MockObdGatewayService.class.getName(); public void startService() { Log.d(TAG, "Starting " + this.getClass().getName() + " service.."); // Let's configure the connection. Log.d(TAG, "Queing jobs for connection configuration.."); queueJob(new ObdCommandJob(new ObdResetCommand())); queueJob(new ObdCommandJob(new EchoOffCommand())); /* * Will send second-time based on tests. * * TODO this can be done w/o having to queue jobs by just issuing * command.run(), command.getResult() and validate the result. */ queueJob(new ObdCommandJob(new EchoOffCommand())); queueJob(new ObdCommandJob(new LineFeedOffCommand())); queueJob(new ObdCommandJob(new TimeoutCommand(62))); // For now set protocol to AUTO queueJob(new ObdCommandJob(new SelectProtocolCommand(ObdProtocols.AUTO))); // Job for returning dummy data queueJob(new ObdCommandJob(new AmbientAirTemperatureCommand())); queueCounter = 0L; Log.d(TAG, "Initialization jobs queued."); isRunning = true; } /** * Runs the queue until the service is stopped */ protected void executeQueue() { Log.d(TAG, "Executing queue.."); while (!Thread.currentThread().isInterrupted()) { ObdCommandJob job = null; try { job = jobsQueue.take(); Log.d(TAG, "Taking job[" + job.getId() + "] from queue.."); if (job.getState().equals(ObdCommandJobState.NEW)) { Log.d(TAG, "Job state is NEW. Run it.."); job.setState(ObdCommandJobState.RUNNING); Log.d(TAG, job.getCommand().getName()); job.getCommand().run(new ByteArrayInputStream("41 00 00 00>41 00 00 00>41 00 00 00>".getBytes()), new ByteArrayOutputStream()); } else { Log.e(TAG, "Job state was not new, so it shouldn't be in queue. BUG ALERT!"); } } catch (InterruptedException i) { Thread.currentThread().interrupt(); } catch (Exception e) { e.printStackTrace(); if (job != null) { job.setState(ObdCommandJobState.EXECUTION_ERROR); } Log.e(TAG, "Failed to run command. -> " + e.getMessage()); } if (job != null) { Log.d(TAG, "Job is finished."); job.setState(ObdCommandJobState.FINISHED); final ObdCommandJob job2 = job; ((MainActivity) ctx).runOnUiThread(new Runnable() { @Override public void run() { ((MainActivity) ctx).stateUpdate(job2); } }); } } } /** * Stop OBD connection and queue processing. */ public void stopService() { Log.d(TAG, "Stopping service.."); notificationManager.cancel(NOTIFICATION_ID); jobsQueue.clear(); isRunning = false; // kill service stopSelf(); } }
Java
public class EditProductPresenter extends Presenter<EditProductPresenter.IView> { @Inject public EditProductPresenter( IView view, PlaceController placeController ) { super( view, placeController ); } @Override public void bind() { bus().addHandler( RemovePictureEvent.TYPE, event -> { EditProduct where = ( EditProduct ) controller().getWhere(); if ( where.getId() != null ) { ProductPicture picture = event.getPicture(); bus().billing().deleteProductPicture( where.getId(), picture.getOrder(), this::deletePictureDone ); } } ); bus().addHandler( ProductListEvent.TYPE, event -> controller().goTo( new Products( event.getScrollspy() ) ) ); bus().addHandler( SaveProductEvent.TYPE, event -> { Product product = event.getProduct(); if ( product.getId() == null ) { bus().billing().createProduct( false, product, ( SuccessCallback<Product> ) response -> { success( messages.msgRecordCreated() ); controller().goTo( new EditProduct( response.getId(), "tabDetail" ) ); } ); } else { bus().billing().updateProduct( product.getId(), false, product, ( SuccessCallback<Product> ) this::onProductSuccess ); } } ); bus().addHandler( RecalculatedPricingEvent.TYPE, event -> view().update( event.getPricing() ) ); } @Override public void onBackingObject() { view().setModel( newProduct() ); EditProduct where = ( EditProduct ) controller().getWhere(); if ( where.getId() != null ) { bus().billing().findProductById( where.getId(), true, ( SuccessCallback<Product> ) response -> view().setModel( response ) ); } onAfterBackingObject(); } private Product newProduct() { return new Product(); } private void deletePictureDone( Void response, FacadeCallback.Failure failure ) { if ( failure.isSuccess() ) { success( messages.msgPictureDeleted() ); } // silently ignore 404 - not an error, it means that we want to delete picture // which is not assigned to product yet else if ( !failure.isNotFound() ) { error( messages.msgErrorRemoteServiceCall() ); } } private void onProductSuccess( Product response ) { ProductPricing pricing = response.getPricing(); view().updatePriceExclVat( pricing == null ? 0.0 : pricing.getPriceExclVat() ); success( messages.msgRecordUpdated() ); } public interface IView extends org.ctoolkit.gwt.client.view.IView<Product> { /** * Updates the product pricing items UI by recalculated pricing. * * @param pricing the recalculated pricing */ void update( Pricing pricing ); /** * Updates the product's price (excl. VAT) at pricing panel. * * @param price the price to be shown to user */ void updatePriceExclVat( @Nullable Double price ); } }
Java
public class MyDataBase extends SQLiteOpenHelper { public static final String DATABASE_NAME="hyc.db"; public static final int LEVEL_1=1; public static final int DB_LEVEL=LEVEL_1; private final Context context; public interface Tables{ String CONTACTS="contacts"; } public MyDataBase(Context context) { super(context, DATABASE_NAME, null, DB_LEVEL); this.context = context; } @Override public void onCreate(SQLiteDatabase db) { String sql="CREATE TABLE "+Tables.CONTACTS+"(" + BaseColumns._ID+" INTEGER PRIMARY KEY AUTOINCREMENT ," + "contact_name "+ " TEXT ," + "contact_number "+" TEXT " + " )"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
Java
class DefaultConfiguringBeanFactoryPostProcessor implements BeanFactoryPostProcessor, BeanClassLoaderAware, SmartInitializingSingleton { private static final Log LOGGER = LogFactory.getLog(DefaultConfiguringBeanFactoryPostProcessor.class); private static final IntegrationConverterInitializer INTEGRATION_CONVERTER_INITIALIZER = new IntegrationConverterInitializer(); private static final Set<Integer> REGISTRIES_PROCESSED = new HashSet<>(); private ClassLoader classLoader; private ConfigurableListableBeanFactory beanFactory; private BeanDefinitionRegistry registry; @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (beanFactory instanceof BeanDefinitionRegistry) { this.beanFactory = beanFactory; this.registry = (BeanDefinitionRegistry) beanFactory; registerBeanFactoryChannelResolver(); registerMessagePublishingErrorHandler(); registerNullChannel(); registerErrorChannel(); registerIntegrationEvaluationContext(); registerTaskScheduler(); registerIdGeneratorConfigurer(); registerIntegrationProperties(); registerBuiltInBeans(); registerRoleController(); registerMessageBuilderFactory(); registerHeaderChannelRegistry(); registerGlobalChannelInterceptorProcessor(); registerDefaultDatatypeChannelMessageConverter(); registerArgumentResolverMessageConverter(); registerMessageHandlerMethodFactory(); registerListMessageHandlerMethodFactory(); } else if (LOGGER.isWarnEnabled()) { LOGGER.warn("BeanFactory is not a BeanDefinitionRegistry. " + "The default Spring Integration infrastructure beans are not going to be registered"); } } @Override public void afterSingletonsInstantiated() { if (LOGGER.isDebugEnabled()) { Properties integrationProperties = IntegrationContextUtils.getIntegrationProperties(this.beanFactory); StringWriter writer = new StringWriter(); integrationProperties.list(new PrintWriter(writer)); StringBuffer propertiesBuffer = writer.getBuffer() .delete(0, "-- listing properties --".length()); LOGGER.debug("\nSpring Integration global properties:\n" + propertiesBuffer); } } private void registerBeanFactoryChannelResolver() { if (!this.beanFactory.containsBeanDefinition(ChannelResolverUtils.CHANNEL_RESOLVER_BEAN_NAME)) { this.registry.registerBeanDefinition(ChannelResolverUtils.CHANNEL_RESOLVER_BEAN_NAME, new RootBeanDefinition(BeanFactoryChannelResolver.class)); } } private void registerMessagePublishingErrorHandler() { if (!this.beanFactory.containsBeanDefinition( ChannelUtils.MESSAGE_PUBLISHING_ERROR_HANDLER_BEAN_NAME)) { this.registry.registerBeanDefinition(ChannelUtils.MESSAGE_PUBLISHING_ERROR_HANDLER_BEAN_NAME, new RootBeanDefinition(MessagePublishingErrorHandler.class)); } } /** * Register a null channel in the application context. * The bean name is defined by the constant {@link IntegrationContextUtils#NULL_CHANNEL_BEAN_NAME}. */ private void registerNullChannel() { if (this.beanFactory.containsBean(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME)) { BeanDefinition nullChannelDefinition = null; BeanFactory beanFactoryToUse = this.beanFactory; do { if (beanFactoryToUse instanceof ConfigurableListableBeanFactory) { ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) beanFactoryToUse; if (listable.containsBeanDefinition(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME)) { nullChannelDefinition = listable .getBeanDefinition(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME); } } if (beanFactoryToUse instanceof HierarchicalBeanFactory) { beanFactoryToUse = ((HierarchicalBeanFactory) beanFactoryToUse).getParentBeanFactory(); } } while (nullChannelDefinition == null); if (!NullChannel.class.getName().equals(nullChannelDefinition.getBeanClassName())) { throw new IllegalStateException("The bean name '" + IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME + "' is reserved."); } } else { this.registry.registerBeanDefinition(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME, new RootBeanDefinition(NullChannel.class)); } } /** * Register an error channel in the application context. * The bean name is defined by the constant {@link IntegrationContextUtils#ERROR_CHANNEL_BEAN_NAME}. * Also a {@link IntegrationContextUtils#ERROR_LOGGER_BEAN_NAME} is registered as a subscriber for this * error channel. */ private void registerErrorChannel() { if (!this.beanFactory.containsBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)) { if (LOGGER.isInfoEnabled()) { LOGGER.info("No bean named '" + IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME + "' has been explicitly defined. " + "Therefore, a default PublishSubscribeChannel will be created."); } this.registry.registerBeanDefinition(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME, new RootBeanDefinition(PublishSubscribeChannel.class)); BeanDefinition loggingHandler = BeanDefinitionBuilder.genericBeanDefinition(LoggingHandler.class) .addConstructorArgValue("ERROR") .getBeanDefinition(); String errorLoggerBeanName = IntegrationContextUtils.ERROR_LOGGER_BEAN_NAME + IntegrationConfigUtils.HANDLER_ALIAS_SUFFIX; this.registry.registerBeanDefinition(errorLoggerBeanName, loggingHandler); BeanDefinitionBuilder loggingEndpointBuilder = BeanDefinitionBuilder.genericBeanDefinition(ConsumerEndpointFactoryBean.class) .addPropertyReference("handler", errorLoggerBeanName) .addPropertyValue("inputChannelName", IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME); BeanComponentDefinition componentDefinition = new BeanComponentDefinition(loggingEndpointBuilder.getBeanDefinition(), IntegrationContextUtils.ERROR_LOGGER_BEAN_NAME); BeanDefinitionReaderUtils.registerBeanDefinition(componentDefinition, this.registry); } } /** * Register {@link IntegrationEvaluationContextFactoryBean} * and {@link IntegrationSimpleEvaluationContextFactoryBean} beans, if necessary. */ private void registerIntegrationEvaluationContext() { if (!this.registry.containsBeanDefinition(IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME)) { BeanDefinitionBuilder integrationEvaluationContextBuilder = BeanDefinitionBuilder .genericBeanDefinition(IntegrationEvaluationContextFactoryBean.class); integrationEvaluationContextBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); BeanDefinitionHolder integrationEvaluationContextHolder = new BeanDefinitionHolder(integrationEvaluationContextBuilder.getBeanDefinition(), IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME); BeanDefinitionReaderUtils.registerBeanDefinition(integrationEvaluationContextHolder, this.registry); } if (!this.registry.containsBeanDefinition( IntegrationContextUtils.INTEGRATION_SIMPLE_EVALUATION_CONTEXT_BEAN_NAME)) { BeanDefinitionBuilder integrationEvaluationContextBuilder = BeanDefinitionBuilder .genericBeanDefinition(IntegrationSimpleEvaluationContextFactoryBean.class); integrationEvaluationContextBuilder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); BeanDefinitionHolder integrationEvaluationContextHolder = new BeanDefinitionHolder(integrationEvaluationContextBuilder.getBeanDefinition(), IntegrationContextUtils.INTEGRATION_SIMPLE_EVALUATION_CONTEXT_BEAN_NAME); BeanDefinitionReaderUtils.registerBeanDefinition(integrationEvaluationContextHolder, this.registry); } } /** * Register an {@link IdGeneratorConfigurer} in the application context. */ private void registerIdGeneratorConfigurer() { Class<?> clazz = IdGeneratorConfigurer.class; String className = clazz.getName(); String[] definitionNames = this.registry.getBeanDefinitionNames(); for (String definitionName : definitionNames) { BeanDefinition definition = this.registry.getBeanDefinition(definitionName); if (className.equals(definition.getBeanClassName())) { if (LOGGER.isInfoEnabled()) { LOGGER.info(className + " is already registered and will be used"); } return; } } RootBeanDefinition beanDefinition = new RootBeanDefinition(clazz); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, this.registry); } /** * Register a {@link ThreadPoolTaskScheduler} bean in the application context. */ private void registerTaskScheduler() { if (!this.beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)) { if (LOGGER.isInfoEnabled()) { LOGGER.info("No bean named '" + IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME + "' has been explicitly defined. " + "Therefore, a default ThreadPoolTaskScheduler will be created."); } BeanDefinition scheduler = BeanDefinitionBuilder.genericBeanDefinition(ThreadPoolTaskScheduler.class) .addPropertyValue("poolSize", IntegrationProperties .getExpressionFor(IntegrationProperties.TASK_SCHEDULER_POOL_SIZE)) .addPropertyValue("threadNamePrefix", "task-scheduler-") .addPropertyValue("rejectedExecutionHandler", new CallerRunsPolicy()) .addPropertyReference("errorHandler", ChannelUtils.MESSAGE_PUBLISHING_ERROR_HANDLER_BEAN_NAME) .getBeanDefinition(); this.registry.registerBeanDefinition(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, scheduler); } } /** * Register an {@code integrationGlobalProperties} bean if necessary. */ private void registerIntegrationProperties() { if (!this.beanFactory.containsBean(IntegrationContextUtils.INTEGRATION_GLOBAL_PROPERTIES_BEAN_NAME)) { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(this.classLoader); try { Resource[] defaultResources = resourceResolver.getResources("classpath*:META-INF/spring.integration.default.properties"); Resource[] userResources = resourceResolver.getResources("classpath*:META-INF/spring.integration.properties"); List<Resource> resources = new LinkedList<>(Arrays.asList(defaultResources)); resources.addAll(Arrays.asList(userResources)); BeanDefinitionBuilder integrationPropertiesBuilder = BeanDefinitionBuilder .genericBeanDefinition(PropertiesFactoryBean.class) .addPropertyValue("locations", resources); this.registry.registerBeanDefinition(IntegrationContextUtils.INTEGRATION_GLOBAL_PROPERTIES_BEAN_NAME, integrationPropertiesBuilder.getBeanDefinition()); } catch (IOException e) { LOGGER.warn("Cannot load 'spring.integration.properties' Resources.", e); } } } /** * Register {@code jsonPath} and {@code xpath} SpEL-function beans, if necessary. */ private void registerBuiltInBeans() { int registryId = System.identityHashCode(this.registry); jsonPath(registryId); xpath(registryId); jsonNodeToString(registryId); REGISTRIES_PROCESSED.add(registryId); } private void jsonPath(int registryId) throws LinkageError { String jsonPathBeanName = "jsonPath"; if (!this.beanFactory.containsBean(jsonPathBeanName) && !REGISTRIES_PROCESSED.contains(registryId)) { Class<?> jsonPathClass = null; try { jsonPathClass = ClassUtils.forName("com.jayway.jsonpath.JsonPath", this.classLoader); } catch (@SuppressWarnings("unused") ClassNotFoundException e) { LOGGER.debug("The '#jsonPath' SpEL function cannot be registered: " + "there is no jayway json-path.jar on the classpath."); } if (jsonPathClass != null) { try { ClassUtils.forName("com.jayway.jsonpath.Predicate", this.classLoader); } catch (ClassNotFoundException e) { jsonPathClass = null; LOGGER.warn("The '#jsonPath' SpEL function cannot be registered. " + "An old json-path.jar version is detected in the classpath." + "At least 2.4.0 is required; see version information at: " + "https://github.com/jayway/JsonPath/releases", e); } } if (jsonPathClass != null) { IntegrationConfigUtils.registerSpelFunctionBean(this.registry, jsonPathBeanName, IntegrationConfigUtils.BASE_PACKAGE + ".json.JsonPathUtils", "evaluate"); } } } private void xpath(int registryId) throws LinkageError { String xpathBeanName = "xpath"; if (!this.beanFactory.containsBean(xpathBeanName) && !REGISTRIES_PROCESSED.contains(registryId)) { Class<?> xpathClass = null; try { xpathClass = ClassUtils.forName(IntegrationConfigUtils.BASE_PACKAGE + ".xml.xpath.XPathUtils", this.classLoader); } catch (@SuppressWarnings("unused") ClassNotFoundException e) { LOGGER.debug("SpEL function '#xpath' isn't registered: " + "there is no spring-integration-xml.jar on the classpath."); } if (xpathClass != null) { IntegrationConfigUtils.registerSpelFunctionBean(this.registry, xpathBeanName, IntegrationConfigUtils.BASE_PACKAGE + ".xml.xpath.XPathUtils", "evaluate"); } } } private void jsonNodeToString(int registryId) { if (!this.beanFactory.containsBean( IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME) && !REGISTRIES_PROCESSED.contains(registryId) && JacksonPresent.isJackson2Present()) { this.registry.registerBeanDefinition( IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME, BeanDefinitionBuilder.genericBeanDefinition(IntegrationConfigUtils.BASE_PACKAGE + ".json.ToStringFriendlyJsonNodeToStringConverter") .getBeanDefinition()); INTEGRATION_CONVERTER_INITIALIZER.registerConverter(this.registry, new RuntimeBeanReference( IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME)); } } /** * Register a {@link SmartLifecycleRoleController} if necessary. */ private void registerRoleController() { if (!this.beanFactory.containsBean(IntegrationContextUtils.INTEGRATION_LIFECYCLE_ROLE_CONTROLLER)) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(SmartLifecycleRoleController.class); builder.addConstructorArgValue(new ManagedList<String>()); builder.addConstructorArgValue(new ManagedList<Lifecycle>()); this.registry.registerBeanDefinition( IntegrationContextUtils.INTEGRATION_LIFECYCLE_ROLE_CONTROLLER, builder.getBeanDefinition()); } } /** * Register a {@link DefaultMessageBuilderFactory} if necessary. */ private void registerMessageBuilderFactory() { if (!this.beanFactory.containsBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME)) { BeanDefinitionBuilder mbfBuilder = BeanDefinitionBuilder .genericBeanDefinition(DefaultMessageBuilderFactory.class) .addPropertyValue("readOnlyHeaders", IntegrationProperties.getExpressionFor(IntegrationProperties.READ_ONLY_HEADERS)); this.registry.registerBeanDefinition( IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME, mbfBuilder.getBeanDefinition()); } } /** * Register a {@link DefaultHeaderChannelRegistry} if necessary. */ private void registerHeaderChannelRegistry() { if (!this.beanFactory.containsBean(IntegrationContextUtils.INTEGRATION_HEADER_CHANNEL_REGISTRY_BEAN_NAME)) { if (LOGGER.isInfoEnabled()) { LOGGER.info("No bean named '" + IntegrationContextUtils.INTEGRATION_HEADER_CHANNEL_REGISTRY_BEAN_NAME + "' has been explicitly defined. " + "Therefore, a default DefaultHeaderChannelRegistry will be created."); } BeanDefinitionBuilder schedulerBuilder = BeanDefinitionBuilder.genericBeanDefinition(DefaultHeaderChannelRegistry.class); BeanDefinitionHolder replyChannelRegistryComponent = new BeanDefinitionHolder( schedulerBuilder.getBeanDefinition(), IntegrationContextUtils.INTEGRATION_HEADER_CHANNEL_REGISTRY_BEAN_NAME); BeanDefinitionReaderUtils.registerBeanDefinition(replyChannelRegistryComponent, this.registry); } } /** * Register a {@link GlobalChannelInterceptorProcessor} if necessary. */ private void registerGlobalChannelInterceptorProcessor() { if (!this.registry.containsBeanDefinition( IntegrationContextUtils.GLOBAL_CHANNEL_INTERCEPTOR_PROCESSOR_BEAN_NAME)) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(GlobalChannelInterceptorProcessor.class) .setRole(BeanDefinition.ROLE_INFRASTRUCTURE); this.registry.registerBeanDefinition(IntegrationContextUtils.GLOBAL_CHANNEL_INTERCEPTOR_PROCESSOR_BEAN_NAME, builder.getBeanDefinition()); } } /** * Register a {@link DefaultDatatypeChannelMessageConverter} bean if necessary. */ private void registerDefaultDatatypeChannelMessageConverter() { if (!this.beanFactory.containsBean( IntegrationContextUtils.INTEGRATION_DATATYPE_CHANNEL_MESSAGE_CONVERTER_BEAN_NAME)) { BeanDefinitionBuilder converterBuilder = BeanDefinitionBuilder .genericBeanDefinition(DefaultDatatypeChannelMessageConverter.class); this.registry.registerBeanDefinition( IntegrationContextUtils.INTEGRATION_DATATYPE_CHANNEL_MESSAGE_CONVERTER_BEAN_NAME, converterBuilder.getBeanDefinition()); } } /** * Register the default {@link ConfigurableCompositeMessageConverter} for argument * resolvers during handler method invocation. */ private void registerArgumentResolverMessageConverter() { if (!this.beanFactory.containsBean(IntegrationContextUtils.ARGUMENT_RESOLVER_MESSAGE_CONVERTER_BEAN_NAME)) { BeanDefinitionBuilder converterBuilder = BeanDefinitionBuilder .genericBeanDefinition(ConfigurableCompositeMessageConverter.class); this.registry.registerBeanDefinition(IntegrationContextUtils.ARGUMENT_RESOLVER_MESSAGE_CONVERTER_BEAN_NAME, converterBuilder.getBeanDefinition()); } } private void registerMessageHandlerMethodFactory() { if (!this.beanFactory.containsBean(IntegrationContextUtils.MESSAGE_HANDLER_FACTORY_BEAN_NAME)) { BeanDefinitionBuilder messageHandlerMethodFactoryBuilder = createMessageHandlerMethodFactoryBeanDefinition(false); this.registry.registerBeanDefinition(IntegrationContextUtils.MESSAGE_HANDLER_FACTORY_BEAN_NAME, messageHandlerMethodFactoryBuilder.getBeanDefinition()); } } private void registerListMessageHandlerMethodFactory() { if (!this.beanFactory.containsBean(IntegrationContextUtils.LIST_MESSAGE_HANDLER_FACTORY_BEAN_NAME)) { BeanDefinitionBuilder messageHandlerMethodFactoryBuilder = createMessageHandlerMethodFactoryBeanDefinition(true); this.registry.registerBeanDefinition(IntegrationContextUtils.LIST_MESSAGE_HANDLER_FACTORY_BEAN_NAME, messageHandlerMethodFactoryBuilder.getBeanDefinition()); } } private BeanDefinitionBuilder createMessageHandlerMethodFactoryBeanDefinition(boolean listCapable) { return BeanDefinitionBuilder.genericBeanDefinition(DefaultMessageHandlerMethodFactory.class) .addPropertyReference("messageConverter", IntegrationContextUtils.ARGUMENT_RESOLVER_MESSAGE_CONVERTER_BEAN_NAME) .addPropertyValue("customArgumentResolvers", buildArgumentResolvers(listCapable)); } private ManagedList<BeanDefinition> buildArgumentResolvers(boolean listCapable) { ManagedList<BeanDefinition> resolvers = new ManagedList<>(); resolvers.add(new RootBeanDefinition(PayloadExpressionArgumentResolver.class)); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(NullAwarePayloadArgumentResolver.class); builder.addConstructorArgReference(IntegrationContextUtils.ARGUMENT_RESOLVER_MESSAGE_CONVERTER_BEAN_NAME); // TODO Validator ? resolvers.add(builder.getBeanDefinition()); resolvers.add(new RootBeanDefinition(PayloadsArgumentResolver.class)); if (listCapable) { resolvers.add( BeanDefinitionBuilder.genericBeanDefinition(CollectionArgumentResolver.class) .addConstructorArgValue(true) .getBeanDefinition()); } resolvers.add(new RootBeanDefinition(MapArgumentResolver.class)); return resolvers; } }