repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
lucaseverini/C-compiler-for-IBM-1401
assignment4/wci/frontend/pascal/parsers/SubrangeTypeParser.java
4558
package wci.frontend.pascal.parsers; import wci.frontend.*; import wci.frontend.pascal.*; import wci.intermediate.*; import wci.intermediate.symtabimpl.*; import wci.intermediate.typeimpl.*; import static wci.frontend.pascal.PascalTokenType.*; import static wci.frontend.pascal.PascalErrorCode.*; import static wci.intermediate.symtabimpl.SymTabKeyImpl.*; import static wci.intermediate.typeimpl.TypeFormImpl.*; import static wci.intermediate.typeimpl.TypeKeyImpl.*; public class SubrangeTypeParser extends TypeSpecificationParser { /** * Constructor. * @param parent the parent parser. */ protected SubrangeTypeParser(PascalParserTD parent) { super(parent); } /** * Parse a Pascal subrange type specification. * @param token the current token. * @return the subrange type specification. * @throws Exception if an error occurred. */ public TypeSpec parse(Token token) throws Exception { TypeSpec subrangeType = TypeFactory.createType(SUBRANGE); Object minValue = null; Object maxValue = null; // Parse the minimum constant. Token constantToken = token; ConstantDefinitionsParser constantParser = new ConstantDefinitionsParser(this); minValue = constantParser.parseConstant(token); // Set the minimum constant's type. TypeSpec minType = constantToken.getType() == IDENTIFIER ? constantParser.getConstantType(constantToken) : constantParser.getConstantType(minValue); minValue = checkValueType(constantToken, minValue, minType); token = currentToken(); Boolean sawDotDot = false; // Look for the .. token. if (token.getType() == DOT_DOT) { token = nextToken(); // consume the .. token sawDotDot = true; } TokenType tokenType = token.getType(); // At the start of the maximum constant? if (ConstantDefinitionsParser.CONSTANT_START_SET.contains(tokenType)) { if (!sawDotDot) { errorHandler.flag(token, MISSING_DOT_DOT, this); } // Parse the maximum constant. token = synchronize(ConstantDefinitionsParser.CONSTANT_START_SET); constantToken = token; maxValue = constantParser.parseConstant(token); // Set the maximum constant's type. TypeSpec maxType = constantToken.getType() == IDENTIFIER ? constantParser.getConstantType(constantToken) : constantParser.getConstantType(maxValue); maxValue = checkValueType(constantToken, maxValue, maxType); // Are the min and max value types valid? if ((minValue == null) || (maxValue == null)) { errorHandler.flag(constantToken, INCOMPATIBLE_TYPES, this); } // Are the min and max value types the same? else if (minType != maxType) { errorHandler.flag(constantToken, INVALID_SUBRANGE_TYPE, this); } // Min value > max value? else if ((minValue != null) && (maxValue != null) && ((Integer) minValue >= (Integer) maxValue)) { errorHandler.flag(constantToken, MIN_GT_MAX, this); } } else { errorHandler.flag(constantToken, INVALID_SUBRANGE_TYPE, this); } subrangeType.setAttribute(SUBRANGE_BASE_TYPE, minType); subrangeType.setAttribute(SUBRANGE_MIN_VALUE, minValue); subrangeType.setAttribute(SUBRANGE_MAX_VALUE, maxValue); return subrangeType; } /** * Check a value of a type specification. * @param token the current token. * @param value the value. * @param type the type specifiction. * @return the value. */ private Object checkValueType(Token token, Object value, TypeSpec type) { if (type == null) { return value; } if (type == Predefined.integerType) { return value; } else if (type == Predefined.charType) { char ch = ((String) value).charAt(0); return Character.getNumericValue(ch); } else if (type.getForm() == ENUMERATION) { return value; } else { errorHandler.flag(token, INVALID_SUBRANGE_TYPE, this); return value; } } }
gpl-2.0
veithen/rhq-websphere-plugin
rhq-websphere-agent-plugin/src/main/java/be/fgov/kszbcss/rhq/websphere/component/sib/SIBGatewayLinkInfo.java
1649
/* * RHQ WebSphere Plug-in * Copyright (C) 2012 Crossroads Bank for Social Security * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation, and/or the GNU Lesser * General Public License, version 2.1, also as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License and the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU General Public License * and the GNU Lesser General Public License along with this program; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package be.fgov.kszbcss.rhq.websphere.component.sib; import java.io.Serializable; public class SIBGatewayLinkInfo implements Serializable { private static final long serialVersionUID = -6879948489456904577L; private final String id; private final String name; private final String targetUuid; public SIBGatewayLinkInfo(String id, String name, String targetUuid) { this.id = id; this.name = name; this.targetUuid = targetUuid; } public String getId() { return id; } public String getName() { return name; } public String getTargetUuid() { return targetUuid; } }
gpl-2.0
LUISURBM/GA
GA/src/java/siga/ga/beans/GaDcmFacade.java
581
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package siga.ga.beans; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import siga.ga.entytis.GaDcm; /** * * @author Otros */ @Stateless public class GaDcmFacade extends AbstractFacade<GaDcm> { @PersistenceContext(unitName = "GAPU") private EntityManager em; protected EntityManager getEntityManager() { return em; } public GaDcmFacade() { super(GaDcm.class); } }
gpl-2.0
xaled/print-feed
src/org/horrabin/horrorss/util/DateParser.java
1033
/** * DateParser.java * * HORRORss Package, Version 2.2.0 * Simple RSS parser * * October 16, 2012 * * Copyright (C) 2012 Fernando Fornieles * e-mail: nandofm@gmail.com * * This file is part of HORRORss * * HORRORss is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HORRORss is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.horrabin.horrorss.util; import java.util.Date; public interface DateParser { public Date getDate(String date, int rssType) throws Exception; }
gpl-2.0
renatoathaydes/checker-framework
checker/src/org/checkerframework/checker/regex/qual/Regex.java
1410
package org.checkerframework.checker.regex.qual; import org.checkerframework.checker.regex.classic.qual.UnknownRegex; import org.checkerframework.checker.tainting.qual.Tainted; import org.checkerframework.framework.qual.SubtypeOf; import org.checkerframework.framework.qual.TypeQualifier; import org.checkerframework.qualframework.poly.SimpleQualifierParameterAnnotationConverter; import org.checkerframework.qualframework.poly.qual.Wildcard; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Regex is the annotation to specify the regex qualifier. * * @see Tainted */ //@ImplicitFor(trees = { Tree.Kind.NULL_LITERAL }) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @Repeatable(MultiRegex.class) // Needed for classic checker @TypeQualifier @SubtypeOf(UnknownRegex.class) public @interface Regex { /** * The number of groups in the regular expression. * Defaults to 0. */ int value() default 0; /** * The name of the qualifier parameter to set. */ String param() default SimpleQualifierParameterAnnotationConverter.PRIMARY_TARGET; /** * Specify that this use is a wildcard with a bound. */ Wildcard wildcard() default Wildcard.NONE; }
gpl-2.0
pbsf/checker-framework
checker/tests/fenum/CatchFenumUnqualified.java
413
import org.checkerframework.checker.fenum.qual.Fenum; class CatchFenumUnqualfied { void method() { try { //:: error: (exception.parameter.invalid) } catch (@Fenum("A") RuntimeException e) { } try { //:: error: (exception.parameter.invalid) } catch (@Fenum("A") NullPointerException | @Fenum("A") ArrayIndexOutOfBoundsException e) { } } }
gpl-2.0
vargax/ejemplos
java/apo/n13_cupiHotel/source/interfaz/InterfazCupiHotel.java
15548
package interfaz; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import mundo.CupiHotel; import mundo.ICupiHotel; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Date; import javax.swing.JTable; import java.awt.GridLayout; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import javax.swing.JSplitPane; import javax.swing.border.LineBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import java.awt.Color; import java.awt.Insets; import javax.swing.ListSelectionModel; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class InterfazCupiHotel extends JFrame implements ActionListener { /** * Constante Serialización */ private static final long serialVersionUID = -3149543507462038988L; //----------------------------------------------------------------- // Constantes //----------------------------------------------------------------- /** * Ruta del archivo de serialización */ private final static String RUTA = "./data/CupiHotel.data"; /** * Corresponde a la ruta del reporte */ private final static String RUTA_REPORTE = "./data/reporte.txt"; /** * Columnas de la tabla que despliega la información de las habitaciones */ private final static String[] columnasHabitacion = {"id", "Número", "Tipo","Precio", "Huespedes", "Consumos","Reservas"}; /** * Columnas de la tabla que despliega la información de los huespedes */ private final static String[] columnasHuesped = {"Nombre", "Edad", "Id", "Dirección", "Teléfono", "Noches"}; /** * Columnas de la tabla que despliega la información de los consumos */ private final static String[] columnasConsumo = {"Descripción","Valor"}; /** * Columnas de la tabla que despliega la información de las reservas */ private final static String[] columnasReserva = {"Nombre", "Días Reservados", "Fecha Inicio"}; //----------------------------------------------------------------- // Atributos //----------------------------------------------------------------- /** * El panel principal de la aplicación */ private JPanel panelPrincipal; /** * La relacion con el mundo del problema */ private ICupiHotel hotel; /** * Las tablas para desplegar la información del hotel */ private DefaultTableModel modeloTablaHabitaciones; private JTable tablaHabitaciones; private String[][] infoHabitaciones; private DefaultTableModel modeloTablaHuespedes; private JTable tablaHuespedes; private String[][] infoHuespedes; private DefaultTableModel modeloTablaConsumos; private JTable tablaConsumos; private String[][] infoConsumos; private DefaultTableModel modeloTablaReservas; private JTable tablaReservas; private String[][] infoReservas; /** * El id de la habitación actual */ int habitacionActual; //----------------------------------------------------------------- // Método MAIN //----------------------------------------------------------------- /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { InterfazCupiHotel frame = new InterfazCupiHotel(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } //----------------------------------------------------------------- // Constructor //----------------------------------------------------------------- /** * Create the frame. */ public InterfazCupiHotel() { setTitle("CupiHotel"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 850, 600); cargarHotel(); modeloTablaHabitaciones = new DefaultTableModel(); modeloTablaHuespedes = new DefaultTableModel(); modeloTablaConsumos = new DefaultTableModel(); modeloTablaReservas = new DefaultTableModel(); BarraMenu barraMenu = new BarraMenu(this); setJMenuBar(barraMenu); panelPrincipal = new JPanel(); panelPrincipal.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(panelPrincipal); panelPrincipal.setLayout(new BorderLayout(0, 0)); JSplitPane splitPane = new JSplitPane(); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); panelPrincipal.add(splitPane); JPanel panelInfohabitaciones = new JPanel(); panelInfohabitaciones.setBorder(new TitledBorder(new LineBorder(new Color(184, 207, 229)), "Informaci\u00F3n Habitaciones", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(51, 51, 51))); splitPane.setLeftComponent(panelInfohabitaciones); tablaHabitaciones = new JTable(modeloTablaHabitaciones); JScrollPane scrollPane = new JScrollPane(tablaHabitaciones); tablaHabitaciones.setFillsViewportHeight(true); tablaHabitaciones.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tablaHabitaciones.getSelectionModel().addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { habitacionActual = Integer.parseInt((String) modeloTablaHabitaciones.getValueAt(tablaHabitaciones.getSelectedRow(), 0)); cargarInfoHabitacion(habitacionActual); //System.out.println(habitacionActual); } } ); panelInfohabitaciones.setLayout(new GridLayout(0, 1, 0, 0)); panelInfohabitaciones.add(scrollPane); JPanel panel_1 = new JPanel(); panel_1.setBorder(new TitledBorder(new LineBorder(new Color(184, 207, 229)), "Habitaci\u00F3n Actual", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(51, 51, 51))); splitPane.setRightComponent(panel_1); GridBagLayout gbl_panel_1 = new GridBagLayout(); gbl_panel_1.columnWidths = new int[]{0, 0, 0}; gbl_panel_1.rowHeights = new int[]{0, 0, 0, 0}; gbl_panel_1.columnWeights = new double[]{1.0, 1.0, Double.MIN_VALUE}; gbl_panel_1.rowWeights = new double[]{1.0, 1.0, 0.0, Double.MIN_VALUE}; panel_1.setLayout(gbl_panel_1); JPanel panelInfoHuespedes = new JPanel(); panelInfoHuespedes.setBorder(new TitledBorder(null, "Huespedes", TitledBorder.LEADING, TitledBorder.TOP, null, null)); GridBagConstraints gbc_panelInfoHuespedes = new GridBagConstraints(); gbc_panelInfoHuespedes.gridwidth = 2; gbc_panelInfoHuespedes.insets = new Insets(0, 0, 5, 0); gbc_panelInfoHuespedes.fill = GridBagConstraints.BOTH; gbc_panelInfoHuespedes.gridx = 0; gbc_panelInfoHuespedes.gridy = 0; panel_1.add(panelInfoHuespedes, gbc_panelInfoHuespedes); panelInfoHuespedes.setLayout(new GridLayout(1, 0, 0, 0)); tablaHuespedes = new JTable(modeloTablaHuespedes); tablaHuespedes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollPane_1 = new JScrollPane(tablaHuespedes); panelInfoHuespedes.add(scrollPane_1); JPanel panelInfoConsumos = new JPanel(); panelInfoConsumos.setBorder(new TitledBorder(null, "Consumos", TitledBorder.LEADING, TitledBorder.TOP, null, null)); GridBagConstraints gbc_panelInfoConsumos = new GridBagConstraints(); gbc_panelInfoConsumos.insets = new Insets(0, 0, 5, 5); gbc_panelInfoConsumos.fill = GridBagConstraints.BOTH; gbc_panelInfoConsumos.gridx = 0; gbc_panelInfoConsumos.gridy = 1; panel_1.add(panelInfoConsumos, gbc_panelInfoConsumos); panelInfoConsumos.setLayout(new GridLayout(0, 1, 0, 0)); tablaConsumos = new JTable(modeloTablaConsumos); tablaConsumos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollPane_2 = new JScrollPane(tablaConsumos); panelInfoConsumos.add(scrollPane_2); JPanel panelInfoReservas = new JPanel(); panelInfoReservas.setBorder(new TitledBorder(null, "Reservas", TitledBorder.LEADING, TitledBorder.TOP, null, null)); GridBagConstraints gbc_panelInfoReservas = new GridBagConstraints(); gbc_panelInfoReservas.insets = new Insets(0, 0, 5, 0); gbc_panelInfoReservas.fill = GridBagConstraints.BOTH; gbc_panelInfoReservas.gridx = 1; gbc_panelInfoReservas.gridy = 1; panel_1.add(panelInfoReservas, gbc_panelInfoReservas); panelInfoReservas.setLayout(new GridLayout(0, 1, 0, 0)); tablaReservas = new JTable(modeloTablaReservas); tablaReservas.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollPane_3 = new JScrollPane(tablaReservas); panelInfoReservas.add(scrollPane_3); JPanel panel = new JPanel(); panel.setMaximumSize(new Dimension(50, 50)); GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.fill = GridBagConstraints.HORIZONTAL; gbc_panel.gridwidth = 2; gbc_panel.insets = new Insets(0, 0, 0, 5); gbc_panel.gridx = 0; gbc_panel.gridy = 2; panel_1.add(panel, gbc_panel); panel.setLayout(new GridLayout(1, 5, 5, 5)); JButton btnAgregarReserva = new JButton("Agregar Reserva"); btnAgregarReserva.setActionCommand("agregarReserva"); btnAgregarReserva.addActionListener(this); panel.add(btnAgregarReserva); JButton btnEliminarReserva = new JButton("Eliminar Reserva"); btnEliminarReserva.setActionCommand("eliminarReserva"); btnEliminarReserva.addActionListener(this); panel.add(btnEliminarReserva); JButton btnRegistrarHuesped = new JButton("Registrar Huesped"); btnRegistrarHuesped.setActionCommand("registrarHuesped"); btnRegistrarHuesped.addActionListener(this); panel.add(btnRegistrarHuesped); JButton btnRegistrarConsumo = new JButton("Registrar Consumo"); btnRegistrarConsumo.setActionCommand("registrarConsumo"); btnRegistrarConsumo.addActionListener(this); panel.add(btnRegistrarConsumo); JButton btnRealizarCheckout = new JButton("Realizar Check-Out"); btnRealizarCheckout.setActionCommand("realizarCheckout"); btnRealizarCheckout.addActionListener(this); panel.add(btnRealizarCheckout); cargarInfoHabitaciones(); } //----------------------------------------------------------------- // Métodos //----------------------------------------------------------------- /** * Restaura el mundo del problema */ public void cargarHotel() { File datos = new File(RUTA); if(datos.exists()) { ObjectInputStream ois; try { ois = new ObjectInputStream(new FileInputStream(datos)); hotel = (ICupiHotel) ois.readObject(); ois.close(); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Imposible restaurar el mundo "+e.getMessage()); e.printStackTrace(); } } else cargarDesdeArchivoConf(); } /** * Restaura el hotel desde el archivo de configuración */ public void cargarDesdeArchivoConf() { JFileChooser fc = new JFileChooser("./data"); fc.setDialogTitle("Cargar Hotel"); File archivo = null; int respuesta = fc.showOpenDialog(this); if(respuesta == JFileChooser.APPROVE_OPTION) { archivo = fc.getSelectedFile(); if(archivo !=null) { hotel = new CupiHotel(); try { hotel.inicializarHotel(archivo); cargarInfoHabitaciones(); } catch(Exception e) { JOptionPane.showMessageDialog(this, "Imposible cargar desde archivo "+ e.getMessage()); } } else JOptionPane.showMessageDialog(this,"Imposible restaurar mundo"); } } /** * Carga la información de la habitación seleccionada actualmente */ public void cargarInfoHabitacion(int idHabitacion) { cargarInfoHuespedes(idHabitacion); cargarInfoConsumos(idHabitacion); cargarInfoReservas(idHabitacion); } /** * Carga la información de las habitaciones */ public void cargarInfoHabitaciones() { infoHabitaciones = hotel.darListaHabitaciones(); modeloTablaHabitaciones.setDataVector(infoHabitaciones, columnasHabitacion); modeloTablaHabitaciones.fireTableDataChanged(); } /** * Carga la información de los huespedes */ public void cargarInfoHuespedes(int idHabitacion) { infoHuespedes = hotel.darListaHuespedes(idHabitacion); modeloTablaHuespedes.setDataVector(infoHuespedes, columnasHuesped); modeloTablaHuespedes.fireTableDataChanged(); } /** * Carga la información de los consumos */ public void cargarInfoConsumos(int idHabitacion) { infoConsumos = hotel.darListaConsumos(idHabitacion); modeloTablaConsumos.setDataVector(infoConsumos, columnasConsumo); modeloTablaConsumos.fireTableDataChanged(); } /** * Carga la información de las reservas */ public void cargarInfoReservas(int idHabitacion) { infoReservas = hotel.darListaReservas(idHabitacion); modeloTablaReservas.setDataVector(infoReservas, columnasReserva); modeloTablaReservas.fireTableDataChanged(); } /** * Registra una nueva reserva */ public void registrarReserva(String nombreP, String fechaInicioP, String diasReservadosP) { Date fechaInicio = new Date(Date.parse(fechaInicioP)); int diasReservados = Integer.parseInt(diasReservadosP); hotel.registrarReserva(habitacionActual, nombreP, fechaInicio, diasReservados); cargarInfoReservas(habitacionActual); } /** * Registra un nuevo huesped */ public void registrarHuesped(String nombreP, String edadP, String identificacionP, String direccionP, String telefonoP, String nochesP) { int edad = Integer.parseInt(edadP); int identificacion = Integer.parseInt(identificacionP); int telefono = Integer.parseInt(telefonoP); int noches = Integer.parseInt(nochesP); hotel.registrarHuesped(habitacionActual, nombreP, edad, identificacion, direccionP, telefono, noches); cargarInfoHuespedes(habitacionActual); } /** * Registra un nuevo consumo */ public void registrarConsumo(String nombreP, String valorP) { float valor = Float.parseFloat(valorP); hotel.registrarConsumo(habitacionActual, nombreP, valor); cargarInfoConsumos(habitacionActual); } /** * Finaliza la aplicación */ public void dispose() { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(RUTA)); oos.writeObject(hotel); oos.close(); super.dispose(); } catch(Exception e) { int a =JOptionPane.showConfirmDialog(this, "Error al guardar el estado del hotel: /n "+e.getMessage()+"/n ¿Desea cerrar el programa?","CupiHotel", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); if(a == JOptionPane.YES_OPTION) super.dispose(); } } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("agregarReserva")) { DialogoRegistrarReserva dialogo = new DialogoRegistrarReserva(this); dialogo.setVisible(true); } else if (comando.equals("registrarHuesped")) { DialogoRegistrarHuesped dialogo = new DialogoRegistrarHuesped(this); dialogo.setVisible(true); } else if (comando.equals("registrarConsumo")) { DialogoRegistrarConsumo dialogo = new DialogoRegistrarConsumo(this); dialogo.setVisible(true); } else if (comando.equals("eliminarReserva")) { System.out.println(tablaHabitaciones.getSelectedRow()); } } public void generarReporte() { try { File archivo = new File(RUTA_REPORTE); hotel.generarReporte(archivo); } catch(Exception e) { JOptionPane.showMessageDialog(this, "Imposible generar reporte "+e.getMessage()); } } }
gpl-2.0
openjdk/jdk7u
jaxp/src/com/sun/org/apache/xalan/internal/res/XSLTErrorResources_zh_CN.java
68509
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: XSLTErrorResources_zh_CN.java /st_wptg_1.7.0.79.0jdk/1 2015/01/23 11:18:41 gmolloy Exp $ */ package com.sun.org.apache.xalan.internal.res; import java.util.ListResourceBundle; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * Set up error messages. * We build a two dimensional array of message keys and * message strings. In order to add a new message here, * you need to first add a String constant. And * you need to enter key , value pair as part of contents * Array. You also need to update MAX_CODE for error strings * and MAX_WARNING for warnings ( Needed for only information * purpose ) */ public class XSLTErrorResources_zh_CN extends ListResourceBundle { /* * This file contains error and warning messages related to Xalan Error * Handling. * * General notes to translators: * * 1) Xalan (or more properly, Xalan-interpretive) and XSLTC are names of * components. * XSLT is an acronym for "XML Stylesheet Language: Transformations". * XSLTC is an acronym for XSLT Compiler. * * 2) A stylesheet is a description of how to transform an input XML document * into a resultant XML document (or HTML document or text). The * stylesheet itself is described in the form of an XML document. * * 3) A template is a component of a stylesheet that is used to match a * particular portion of an input document and specifies the form of the * corresponding portion of the output document. * * 4) An element is a mark-up tag in an XML document; an attribute is a * modifier on the tag. For example, in <elem attr='val' attr2='val2'> * "elem" is an element name, "attr" and "attr2" are attribute names with * the values "val" and "val2", respectively. * * 5) A namespace declaration is a special attribute that is used to associate * a prefix with a URI (the namespace). The meanings of element names and * attribute names that use that prefix are defined with respect to that * namespace. * * 6) "Translet" is an invented term that describes the class file that * results from compiling an XML stylesheet into a Java class. * * 7) XPath is a specification that describes a notation for identifying * nodes in a tree-structured representation of an XML document. An * instance of that notation is referred to as an XPath expression. * */ /* * Static variables */ public static final String ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX = "ER_INVALID_SET_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX"; public static final String ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT = "ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT"; public static final String ER_NO_CURLYBRACE = "ER_NO_CURLYBRACE"; public static final String ER_FUNCTION_NOT_SUPPORTED = "ER_FUNCTION_NOT_SUPPORTED"; public static final String ER_ILLEGAL_ATTRIBUTE = "ER_ILLEGAL_ATTRIBUTE"; public static final String ER_NULL_SOURCENODE_APPLYIMPORTS = "ER_NULL_SOURCENODE_APPLYIMPORTS"; public static final String ER_CANNOT_ADD = "ER_CANNOT_ADD"; public static final String ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES="ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES"; public static final String ER_NO_NAME_ATTRIB = "ER_NO_NAME_ATTRIB"; public static final String ER_TEMPLATE_NOT_FOUND = "ER_TEMPLATE_NOT_FOUND"; public static final String ER_CANT_RESOLVE_NAME_AVT = "ER_CANT_RESOLVE_NAME_AVT"; public static final String ER_REQUIRES_ATTRIB = "ER_REQUIRES_ATTRIB"; public static final String ER_MUST_HAVE_TEST_ATTRIB = "ER_MUST_HAVE_TEST_ATTRIB"; public static final String ER_BAD_VAL_ON_LEVEL_ATTRIB = "ER_BAD_VAL_ON_LEVEL_ATTRIB"; public static final String ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML = "ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML"; public static final String ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME = "ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME"; public static final String ER_NEED_MATCH_ATTRIB = "ER_NEED_MATCH_ATTRIB"; public static final String ER_NEED_NAME_OR_MATCH_ATTRIB = "ER_NEED_NAME_OR_MATCH_ATTRIB"; public static final String ER_CANT_RESOLVE_NSPREFIX = "ER_CANT_RESOLVE_NSPREFIX"; public static final String ER_ILLEGAL_VALUE = "ER_ILLEGAL_VALUE"; public static final String ER_NO_OWNERDOC = "ER_NO_OWNERDOC"; public static final String ER_ELEMTEMPLATEELEM_ERR ="ER_ELEMTEMPLATEELEM_ERR"; public static final String ER_NULL_CHILD = "ER_NULL_CHILD"; public static final String ER_NEED_SELECT_ATTRIB = "ER_NEED_SELECT_ATTRIB"; public static final String ER_NEED_TEST_ATTRIB = "ER_NEED_TEST_ATTRIB"; public static final String ER_NEED_NAME_ATTRIB = "ER_NEED_NAME_ATTRIB"; public static final String ER_NO_CONTEXT_OWNERDOC = "ER_NO_CONTEXT_OWNERDOC"; public static final String ER_COULD_NOT_CREATE_XML_PROC_LIAISON = "ER_COULD_NOT_CREATE_XML_PROC_LIAISON"; public static final String ER_PROCESS_NOT_SUCCESSFUL = "ER_PROCESS_NOT_SUCCESSFUL"; public static final String ER_NOT_SUCCESSFUL = "ER_NOT_SUCCESSFUL"; public static final String ER_ENCODING_NOT_SUPPORTED = "ER_ENCODING_NOT_SUPPORTED"; public static final String ER_COULD_NOT_CREATE_TRACELISTENER = "ER_COULD_NOT_CREATE_TRACELISTENER"; public static final String ER_KEY_REQUIRES_NAME_ATTRIB = "ER_KEY_REQUIRES_NAME_ATTRIB"; public static final String ER_KEY_REQUIRES_MATCH_ATTRIB = "ER_KEY_REQUIRES_MATCH_ATTRIB"; public static final String ER_KEY_REQUIRES_USE_ATTRIB = "ER_KEY_REQUIRES_USE_ATTRIB"; public static final String ER_REQUIRES_ELEMENTS_ATTRIB = "ER_REQUIRES_ELEMENTS_ATTRIB"; public static final String ER_MISSING_PREFIX_ATTRIB = "ER_MISSING_PREFIX_ATTRIB"; public static final String ER_BAD_STYLESHEET_URL = "ER_BAD_STYLESHEET_URL"; public static final String ER_FILE_NOT_FOUND = "ER_FILE_NOT_FOUND"; public static final String ER_IOEXCEPTION = "ER_IOEXCEPTION"; public static final String ER_NO_HREF_ATTRIB = "ER_NO_HREF_ATTRIB"; public static final String ER_STYLESHEET_INCLUDES_ITSELF = "ER_STYLESHEET_INCLUDES_ITSELF"; public static final String ER_PROCESSINCLUDE_ERROR ="ER_PROCESSINCLUDE_ERROR"; public static final String ER_MISSING_LANG_ATTRIB = "ER_MISSING_LANG_ATTRIB"; public static final String ER_MISSING_CONTAINER_ELEMENT_COMPONENT = "ER_MISSING_CONTAINER_ELEMENT_COMPONENT"; public static final String ER_CAN_ONLY_OUTPUT_TO_ELEMENT = "ER_CAN_ONLY_OUTPUT_TO_ELEMENT"; public static final String ER_PROCESS_ERROR = "ER_PROCESS_ERROR"; public static final String ER_UNIMPLNODE_ERROR = "ER_UNIMPLNODE_ERROR"; public static final String ER_NO_SELECT_EXPRESSION ="ER_NO_SELECT_EXPRESSION"; public static final String ER_CANNOT_SERIALIZE_XSLPROCESSOR = "ER_CANNOT_SERIALIZE_XSLPROCESSOR"; public static final String ER_NO_INPUT_STYLESHEET = "ER_NO_INPUT_STYLESHEET"; public static final String ER_FAILED_PROCESS_STYLESHEET = "ER_FAILED_PROCESS_STYLESHEET"; public static final String ER_COULDNT_PARSE_DOC = "ER_COULDNT_PARSE_DOC"; public static final String ER_COULDNT_FIND_FRAGMENT = "ER_COULDNT_FIND_FRAGMENT"; public static final String ER_NODE_NOT_ELEMENT = "ER_NODE_NOT_ELEMENT"; public static final String ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB = "ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB"; public static final String ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB = "ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB"; public static final String ER_NO_CLONE_OF_DOCUMENT_FRAG = "ER_NO_CLONE_OF_DOCUMENT_FRAG"; public static final String ER_CANT_CREATE_ITEM = "ER_CANT_CREATE_ITEM"; public static final String ER_XMLSPACE_ILLEGAL_VALUE = "ER_XMLSPACE_ILLEGAL_VALUE"; public static final String ER_NO_XSLKEY_DECLARATION = "ER_NO_XSLKEY_DECLARATION"; public static final String ER_CANT_CREATE_URL = "ER_CANT_CREATE_URL"; public static final String ER_XSLFUNCTIONS_UNSUPPORTED = "ER_XSLFUNCTIONS_UNSUPPORTED"; public static final String ER_PROCESSOR_ERROR = "ER_PROCESSOR_ERROR"; public static final String ER_NOT_ALLOWED_INSIDE_STYLESHEET = "ER_NOT_ALLOWED_INSIDE_STYLESHEET"; public static final String ER_RESULTNS_NOT_SUPPORTED = "ER_RESULTNS_NOT_SUPPORTED"; public static final String ER_DEFAULTSPACE_NOT_SUPPORTED = "ER_DEFAULTSPACE_NOT_SUPPORTED"; public static final String ER_INDENTRESULT_NOT_SUPPORTED = "ER_INDENTRESULT_NOT_SUPPORTED"; public static final String ER_ILLEGAL_ATTRIB = "ER_ILLEGAL_ATTRIB"; public static final String ER_UNKNOWN_XSL_ELEM = "ER_UNKNOWN_XSL_ELEM"; public static final String ER_BAD_XSLSORT_USE = "ER_BAD_XSLSORT_USE"; public static final String ER_MISPLACED_XSLWHEN = "ER_MISPLACED_XSLWHEN"; public static final String ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE = "ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE"; public static final String ER_MISPLACED_XSLOTHERWISE = "ER_MISPLACED_XSLOTHERWISE"; public static final String ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE = "ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE"; public static final String ER_NOT_ALLOWED_INSIDE_TEMPLATE = "ER_NOT_ALLOWED_INSIDE_TEMPLATE"; public static final String ER_UNKNOWN_EXT_NS_PREFIX = "ER_UNKNOWN_EXT_NS_PREFIX"; public static final String ER_IMPORTS_AS_FIRST_ELEM = "ER_IMPORTS_AS_FIRST_ELEM"; public static final String ER_IMPORTING_ITSELF = "ER_IMPORTING_ITSELF"; public static final String ER_XMLSPACE_ILLEGAL_VAL ="ER_XMLSPACE_ILLEGAL_VAL"; public static final String ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL = "ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL"; public static final String ER_SAX_EXCEPTION = "ER_SAX_EXCEPTION"; public static final String ER_XSLT_ERROR = "ER_XSLT_ERROR"; public static final String ER_CURRENCY_SIGN_ILLEGAL= "ER_CURRENCY_SIGN_ILLEGAL"; public static final String ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM = "ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM"; public static final String ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER = "ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER"; public static final String ER_REDIRECT_COULDNT_GET_FILENAME = "ER_REDIRECT_COULDNT_GET_FILENAME"; public static final String ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT = "ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT"; public static final String ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX = "ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX"; public static final String ER_MISSING_NS_URI = "ER_MISSING_NS_URI"; public static final String ER_MISSING_ARG_FOR_OPTION = "ER_MISSING_ARG_FOR_OPTION"; public static final String ER_INVALID_OPTION = "ER_INVALID_OPTION"; public static final String ER_MALFORMED_FORMAT_STRING = "ER_MALFORMED_FORMAT_STRING"; public static final String ER_STYLESHEET_REQUIRES_VERSION_ATTRIB = "ER_STYLESHEET_REQUIRES_VERSION_ATTRIB"; public static final String ER_ILLEGAL_ATTRIBUTE_VALUE = "ER_ILLEGAL_ATTRIBUTE_VALUE"; public static final String ER_CHOOSE_REQUIRES_WHEN ="ER_CHOOSE_REQUIRES_WHEN"; public static final String ER_NO_APPLY_IMPORT_IN_FOR_EACH = "ER_NO_APPLY_IMPORT_IN_FOR_EACH"; public static final String ER_CANT_USE_DTM_FOR_OUTPUT = "ER_CANT_USE_DTM_FOR_OUTPUT"; public static final String ER_CANT_USE_DTM_FOR_INPUT = "ER_CANT_USE_DTM_FOR_INPUT"; public static final String ER_CALL_TO_EXT_FAILED = "ER_CALL_TO_EXT_FAILED"; public static final String ER_PREFIX_MUST_RESOLVE = "ER_PREFIX_MUST_RESOLVE"; public static final String ER_INVALID_UTF16_SURROGATE = "ER_INVALID_UTF16_SURROGATE"; public static final String ER_XSLATTRSET_USED_ITSELF = "ER_XSLATTRSET_USED_ITSELF"; public static final String ER_CANNOT_MIX_XERCESDOM ="ER_CANNOT_MIX_XERCESDOM"; public static final String ER_TOO_MANY_LISTENERS = "ER_TOO_MANY_LISTENERS"; public static final String ER_IN_ELEMTEMPLATEELEM_READOBJECT = "ER_IN_ELEMTEMPLATEELEM_READOBJECT"; public static final String ER_DUPLICATE_NAMED_TEMPLATE = "ER_DUPLICATE_NAMED_TEMPLATE"; public static final String ER_INVALID_KEY_CALL = "ER_INVALID_KEY_CALL"; public static final String ER_REFERENCING_ITSELF = "ER_REFERENCING_ITSELF"; public static final String ER_ILLEGAL_DOMSOURCE_INPUT = "ER_ILLEGAL_DOMSOURCE_INPUT"; public static final String ER_CLASS_NOT_FOUND_FOR_OPTION = "ER_CLASS_NOT_FOUND_FOR_OPTION"; public static final String ER_REQUIRED_ELEM_NOT_FOUND = "ER_REQUIRED_ELEM_NOT_FOUND"; public static final String ER_INPUT_CANNOT_BE_NULL ="ER_INPUT_CANNOT_BE_NULL"; public static final String ER_URI_CANNOT_BE_NULL = "ER_URI_CANNOT_BE_NULL"; public static final String ER_FILE_CANNOT_BE_NULL = "ER_FILE_CANNOT_BE_NULL"; public static final String ER_SOURCE_CANNOT_BE_NULL = "ER_SOURCE_CANNOT_BE_NULL"; public static final String ER_CANNOT_INIT_BSFMGR = "ER_CANNOT_INIT_BSFMGR"; public static final String ER_CANNOT_CMPL_EXTENSN = "ER_CANNOT_CMPL_EXTENSN"; public static final String ER_CANNOT_CREATE_EXTENSN = "ER_CANNOT_CREATE_EXTENSN"; public static final String ER_INSTANCE_MTHD_CALL_REQUIRES = "ER_INSTANCE_MTHD_CALL_REQUIRES"; public static final String ER_INVALID_ELEMENT_NAME ="ER_INVALID_ELEMENT_NAME"; public static final String ER_ELEMENT_NAME_METHOD_STATIC = "ER_ELEMENT_NAME_METHOD_STATIC"; public static final String ER_EXTENSION_FUNC_UNKNOWN = "ER_EXTENSION_FUNC_UNKNOWN"; public static final String ER_MORE_MATCH_CONSTRUCTOR = "ER_MORE_MATCH_CONSTRUCTOR"; public static final String ER_MORE_MATCH_METHOD = "ER_MORE_MATCH_METHOD"; public static final String ER_MORE_MATCH_ELEMENT = "ER_MORE_MATCH_ELEMENT"; public static final String ER_INVALID_CONTEXT_PASSED = "ER_INVALID_CONTEXT_PASSED"; public static final String ER_POOL_EXISTS = "ER_POOL_EXISTS"; public static final String ER_NO_DRIVER_NAME = "ER_NO_DRIVER_NAME"; public static final String ER_NO_URL = "ER_NO_URL"; public static final String ER_POOL_SIZE_LESSTHAN_ONE = "ER_POOL_SIZE_LESSTHAN_ONE"; public static final String ER_INVALID_DRIVER = "ER_INVALID_DRIVER"; public static final String ER_NO_STYLESHEETROOT = "ER_NO_STYLESHEETROOT"; public static final String ER_ILLEGAL_XMLSPACE_VALUE = "ER_ILLEGAL_XMLSPACE_VALUE"; public static final String ER_PROCESSFROMNODE_FAILED = "ER_PROCESSFROMNODE_FAILED"; public static final String ER_RESOURCE_COULD_NOT_LOAD = "ER_RESOURCE_COULD_NOT_LOAD"; public static final String ER_BUFFER_SIZE_LESSTHAN_ZERO = "ER_BUFFER_SIZE_LESSTHAN_ZERO"; public static final String ER_UNKNOWN_ERROR_CALLING_EXTENSION = "ER_UNKNOWN_ERROR_CALLING_EXTENSION"; public static final String ER_NO_NAMESPACE_DECL = "ER_NO_NAMESPACE_DECL"; public static final String ER_ELEM_CONTENT_NOT_ALLOWED = "ER_ELEM_CONTENT_NOT_ALLOWED"; public static final String ER_STYLESHEET_DIRECTED_TERMINATION = "ER_STYLESHEET_DIRECTED_TERMINATION"; public static final String ER_ONE_OR_TWO = "ER_ONE_OR_TWO"; public static final String ER_TWO_OR_THREE = "ER_TWO_OR_THREE"; public static final String ER_COULD_NOT_LOAD_RESOURCE = "ER_COULD_NOT_LOAD_RESOURCE"; public static final String ER_CANNOT_INIT_DEFAULT_TEMPLATES = "ER_CANNOT_INIT_DEFAULT_TEMPLATES"; public static final String ER_RESULT_NULL = "ER_RESULT_NULL"; public static final String ER_RESULT_COULD_NOT_BE_SET = "ER_RESULT_COULD_NOT_BE_SET"; public static final String ER_NO_OUTPUT_SPECIFIED = "ER_NO_OUTPUT_SPECIFIED"; public static final String ER_CANNOT_TRANSFORM_TO_RESULT_TYPE = "ER_CANNOT_TRANSFORM_TO_RESULT_TYPE"; public static final String ER_CANNOT_TRANSFORM_SOURCE_TYPE = "ER_CANNOT_TRANSFORM_SOURCE_TYPE"; public static final String ER_NULL_CONTENT_HANDLER ="ER_NULL_CONTENT_HANDLER"; public static final String ER_NULL_ERROR_HANDLER = "ER_NULL_ERROR_HANDLER"; public static final String ER_CANNOT_CALL_PARSE = "ER_CANNOT_CALL_PARSE"; public static final String ER_NO_PARENT_FOR_FILTER ="ER_NO_PARENT_FOR_FILTER"; public static final String ER_NO_STYLESHEET_IN_MEDIA = "ER_NO_STYLESHEET_IN_MEDIA"; public static final String ER_NO_STYLESHEET_PI = "ER_NO_STYLESHEET_PI"; public static final String ER_NOT_SUPPORTED = "ER_NOT_SUPPORTED"; public static final String ER_PROPERTY_VALUE_BOOLEAN = "ER_PROPERTY_VALUE_BOOLEAN"; public static final String ER_COULD_NOT_FIND_EXTERN_SCRIPT = "ER_COULD_NOT_FIND_EXTERN_SCRIPT"; public static final String ER_RESOURCE_COULD_NOT_FIND = "ER_RESOURCE_COULD_NOT_FIND"; public static final String ER_OUTPUT_PROPERTY_NOT_RECOGNIZED = "ER_OUTPUT_PROPERTY_NOT_RECOGNIZED"; public static final String ER_FAILED_CREATING_ELEMLITRSLT = "ER_FAILED_CREATING_ELEMLITRSLT"; public static final String ER_VALUE_SHOULD_BE_NUMBER = "ER_VALUE_SHOULD_BE_NUMBER"; public static final String ER_VALUE_SHOULD_EQUAL = "ER_VALUE_SHOULD_EQUAL"; public static final String ER_FAILED_CALLING_METHOD = "ER_FAILED_CALLING_METHOD"; public static final String ER_FAILED_CREATING_ELEMTMPL = "ER_FAILED_CREATING_ELEMTMPL"; public static final String ER_CHARS_NOT_ALLOWED = "ER_CHARS_NOT_ALLOWED"; public static final String ER_ATTR_NOT_ALLOWED = "ER_ATTR_NOT_ALLOWED"; public static final String ER_BAD_VALUE = "ER_BAD_VALUE"; public static final String ER_ATTRIB_VALUE_NOT_FOUND = "ER_ATTRIB_VALUE_NOT_FOUND"; public static final String ER_ATTRIB_VALUE_NOT_RECOGNIZED = "ER_ATTRIB_VALUE_NOT_RECOGNIZED"; public static final String ER_NULL_URI_NAMESPACE = "ER_NULL_URI_NAMESPACE"; public static final String ER_NUMBER_TOO_BIG = "ER_NUMBER_TOO_BIG"; public static final String ER_CANNOT_FIND_SAX1_DRIVER = "ER_CANNOT_FIND_SAX1_DRIVER"; public static final String ER_SAX1_DRIVER_NOT_LOADED = "ER_SAX1_DRIVER_NOT_LOADED"; public static final String ER_SAX1_DRIVER_NOT_INSTANTIATED = "ER_SAX1_DRIVER_NOT_INSTANTIATED" ; public static final String ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER = "ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER"; public static final String ER_PARSER_PROPERTY_NOT_SPECIFIED = "ER_PARSER_PROPERTY_NOT_SPECIFIED"; public static final String ER_PARSER_ARG_CANNOT_BE_NULL = "ER_PARSER_ARG_CANNOT_BE_NULL" ; public static final String ER_FEATURE = "ER_FEATURE"; public static final String ER_PROPERTY = "ER_PROPERTY" ; public static final String ER_NULL_ENTITY_RESOLVER ="ER_NULL_ENTITY_RESOLVER"; public static final String ER_NULL_DTD_HANDLER = "ER_NULL_DTD_HANDLER" ; public static final String ER_NO_DRIVER_NAME_SPECIFIED = "ER_NO_DRIVER_NAME_SPECIFIED"; public static final String ER_NO_URL_SPECIFIED = "ER_NO_URL_SPECIFIED"; public static final String ER_POOLSIZE_LESS_THAN_ONE = "ER_POOLSIZE_LESS_THAN_ONE"; public static final String ER_INVALID_DRIVER_NAME = "ER_INVALID_DRIVER_NAME"; public static final String ER_ERRORLISTENER = "ER_ERRORLISTENER"; public static final String ER_ASSERT_NO_TEMPLATE_PARENT = "ER_ASSERT_NO_TEMPLATE_PARENT"; public static final String ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR = "ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR"; public static final String ER_NOT_ALLOWED_IN_POSITION = "ER_NOT_ALLOWED_IN_POSITION"; public static final String ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION = "ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION"; public static final String ER_NAMESPACE_CONTEXT_NULL_NAMESPACE = "ER_NAMESPACE_CONTEXT_NULL_NAMESPACE"; public static final String ER_NAMESPACE_CONTEXT_NULL_PREFIX = "ER_NAMESPACE_CONTEXT_NULL_PREFIX"; public static final String ER_XPATH_RESOLVER_NULL_QNAME = "ER_XPATH_RESOLVER_NULL_QNAME"; public static final String ER_XPATH_RESOLVER_NEGATIVE_ARITY = "ER_XPATH_RESOLVER_NEGATIVE_ARITY"; public static final String INVALID_TCHAR = "INVALID_TCHAR"; public static final String INVALID_QNAME = "INVALID_QNAME"; public static final String INVALID_ENUM = "INVALID_ENUM"; public static final String INVALID_NMTOKEN = "INVALID_NMTOKEN"; public static final String INVALID_NCNAME = "INVALID_NCNAME"; public static final String INVALID_BOOLEAN = "INVALID_BOOLEAN"; public static final String INVALID_NUMBER = "INVALID_NUMBER"; public static final String ER_ARG_LITERAL = "ER_ARG_LITERAL"; public static final String ER_DUPLICATE_GLOBAL_VAR ="ER_DUPLICATE_GLOBAL_VAR"; public static final String ER_DUPLICATE_VAR = "ER_DUPLICATE_VAR"; public static final String ER_TEMPLATE_NAME_MATCH = "ER_TEMPLATE_NAME_MATCH"; public static final String ER_INVALID_PREFIX = "ER_INVALID_PREFIX"; public static final String ER_NO_ATTRIB_SET = "ER_NO_ATTRIB_SET"; public static final String ER_FUNCTION_NOT_FOUND = "ER_FUNCTION_NOT_FOUND"; public static final String ER_CANT_HAVE_CONTENT_AND_SELECT = "ER_CANT_HAVE_CONTENT_AND_SELECT"; public static final String ER_INVALID_SET_PARAM_VALUE = "ER_INVALID_SET_PARAM_VALUE"; public static final String ER_SET_FEATURE_NULL_NAME = "ER_SET_FEATURE_NULL_NAME"; public static final String ER_GET_FEATURE_NULL_NAME = "ER_GET_FEATURE_NULL_NAME"; public static final String ER_UNSUPPORTED_FEATURE = "ER_UNSUPPORTED_FEATURE"; public static final String ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING = "ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING"; public static final String WG_FOUND_CURLYBRACE = "WG_FOUND_CURLYBRACE"; public static final String WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR = "WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR"; public static final String WG_EXPR_ATTRIB_CHANGED_TO_SELECT = "WG_EXPR_ATTRIB_CHANGED_TO_SELECT"; public static final String WG_NO_LOCALE_IN_FORMATNUMBER = "WG_NO_LOCALE_IN_FORMATNUMBER"; public static final String WG_LOCALE_NOT_FOUND = "WG_LOCALE_NOT_FOUND"; public static final String WG_CANNOT_MAKE_URL_FROM ="WG_CANNOT_MAKE_URL_FROM"; public static final String WG_CANNOT_LOAD_REQUESTED_DOC = "WG_CANNOT_LOAD_REQUESTED_DOC"; public static final String WG_CANNOT_FIND_COLLATOR ="WG_CANNOT_FIND_COLLATOR"; public static final String WG_FUNCTIONS_SHOULD_USE_URL = "WG_FUNCTIONS_SHOULD_USE_URL"; public static final String WG_ENCODING_NOT_SUPPORTED_USING_UTF8 = "WG_ENCODING_NOT_SUPPORTED_USING_UTF8"; public static final String WG_ENCODING_NOT_SUPPORTED_USING_JAVA = "WG_ENCODING_NOT_SUPPORTED_USING_JAVA"; public static final String WG_SPECIFICITY_CONFLICTS = "WG_SPECIFICITY_CONFLICTS"; public static final String WG_PARSING_AND_PREPARING = "WG_PARSING_AND_PREPARING"; public static final String WG_ATTR_TEMPLATE = "WG_ATTR_TEMPLATE"; public static final String WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESPACE = "WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESP"; public static final String WG_ATTRIB_NOT_HANDLED = "WG_ATTRIB_NOT_HANDLED"; public static final String WG_NO_DECIMALFORMAT_DECLARATION = "WG_NO_DECIMALFORMAT_DECLARATION"; public static final String WG_OLD_XSLT_NS = "WG_OLD_XSLT_NS"; public static final String WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED = "WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED"; public static final String WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE = "WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE"; public static final String WG_ILLEGAL_ATTRIBUTE = "WG_ILLEGAL_ATTRIBUTE"; public static final String WG_COULD_NOT_RESOLVE_PREFIX = "WG_COULD_NOT_RESOLVE_PREFIX"; public static final String WG_STYLESHEET_REQUIRES_VERSION_ATTRIB = "WG_STYLESHEET_REQUIRES_VERSION_ATTRIB"; public static final String WG_ILLEGAL_ATTRIBUTE_NAME = "WG_ILLEGAL_ATTRIBUTE_NAME"; public static final String WG_ILLEGAL_ATTRIBUTE_VALUE = "WG_ILLEGAL_ATTRIBUTE_VALUE"; public static final String WG_EMPTY_SECOND_ARG = "WG_EMPTY_SECOND_ARG"; public static final String WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML = "WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML"; public static final String WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME = "WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME"; public static final String WG_ILLEGAL_ATTRIBUTE_POSITION = "WG_ILLEGAL_ATTRIBUTE_POSITION"; public static final String NO_MODIFICATION_ALLOWED_ERR = "NO_MODIFICATION_ALLOWED_ERR"; /* * Now fill in the message text. * Then fill in the message text for that message code in the * array. Use the new error code as the index into the array. */ // Error messages... /** Get the lookup table for error messages. * * @return The message lookup table. */ public Object[][] getContents() { return new Object[][] { /** Error message ID that has a null message, but takes in a single object. */ {"ER0000" , "{0}" }, { ER_NO_CURLYBRACE, "\u9519\u8BEF: \u8868\u8FBE\u5F0F\u4E2D\u4E0D\u80FD\u5305\u542B '{'"}, { ER_ILLEGAL_ATTRIBUTE , "{0}\u5177\u6709\u975E\u6CD5\u5C5E\u6027: {1}"}, {ER_NULL_SOURCENODE_APPLYIMPORTS , "sourceNode \u5728 xsl:apply-imports \u4E2D\u4E3A\u7A7A\u503C!"}, {ER_CANNOT_ADD, "\u65E0\u6CD5\u5411{1}\u6DFB\u52A0{0}"}, { ER_NULL_SOURCENODE_HANDLEAPPLYTEMPLATES, "sourceNode \u5728 handleApplyTemplatesInstruction \u4E2D\u4E3A\u7A7A\u503C!"}, { ER_NO_NAME_ATTRIB, "{0}\u5FC5\u987B\u5177\u6709 name \u5C5E\u6027\u3002"}, {ER_TEMPLATE_NOT_FOUND, "\u627E\u4E0D\u5230\u540D\u4E3A{0}\u7684\u6A21\u677F"}, {ER_CANT_RESOLVE_NAME_AVT, "\u65E0\u6CD5\u89E3\u6790 xsl:call-template \u4E2D\u7684\u540D\u79F0 AVT\u3002"}, {ER_REQUIRES_ATTRIB, "{0}\u9700\u8981\u5C5E\u6027: {1}"}, { ER_MUST_HAVE_TEST_ATTRIB, "{0}\u5FC5\u987B\u5177\u6709 ''test'' \u5C5E\u6027\u3002"}, {ER_BAD_VAL_ON_LEVEL_ATTRIB, "level \u5C5E\u6027\u7684\u503C\u9519\u8BEF: {0}"}, {ER_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML, "processing-instruction \u540D\u79F0\u4E0D\u80FD\u4E3A 'xml'"}, { ER_PROCESSINGINSTRUCTION_NOTVALID_NCNAME, "processing-instruction \u540D\u79F0\u5FC5\u987B\u662F\u6709\u6548\u7684 NCName: {0}"}, { ER_NEED_MATCH_ATTRIB, "\u5982\u679C{0}\u5177\u6709\u67D0\u79CD\u6A21\u5F0F, \u5219\u5FC5\u987B\u5177\u6709 match \u5C5E\u6027\u3002"}, { ER_NEED_NAME_OR_MATCH_ATTRIB, "{0}\u9700\u8981 name \u6216 match \u5C5E\u6027\u3002"}, {ER_CANT_RESOLVE_NSPREFIX, "\u65E0\u6CD5\u89E3\u6790\u540D\u79F0\u7A7A\u95F4\u524D\u7F00: {0}"}, { ER_ILLEGAL_VALUE, "xml:space \u5177\u6709\u975E\u6CD5\u503C: {0}"}, { ER_NO_OWNERDOC, "\u5B50\u8282\u70B9\u6CA1\u6709\u6240\u6709\u8005\u6587\u6863!"}, { ER_ELEMTEMPLATEELEM_ERR, "ElemTemplateElement \u9519\u8BEF: {0}"}, { ER_NULL_CHILD, "\u6B63\u5728\u5C1D\u8BD5\u6DFB\u52A0\u7A7A\u5B50\u7EA7!"}, { ER_NEED_SELECT_ATTRIB, "{0}\u9700\u8981 select \u5C5E\u6027\u3002"}, { ER_NEED_TEST_ATTRIB , "xsl:when \u5FC5\u987B\u5177\u6709 'test' \u5C5E\u6027\u3002"}, { ER_NEED_NAME_ATTRIB, "xsl:with-param \u5FC5\u987B\u5177\u6709 'name' \u5C5E\u6027\u3002"}, { ER_NO_CONTEXT_OWNERDOC, "\u4E0A\u4E0B\u6587\u6CA1\u6709\u6240\u6709\u8005\u6587\u6863!"}, {ER_COULD_NOT_CREATE_XML_PROC_LIAISON, "\u65E0\u6CD5\u521B\u5EFA XML TransformerFactory Liaison: {0}"}, {ER_PROCESS_NOT_SUCCESSFUL, "Xalan: \u8FDB\u7A0B\u672A\u6210\u529F\u3002"}, { ER_NOT_SUCCESSFUL, "Xalan: \u672A\u6210\u529F\u3002"}, { ER_ENCODING_NOT_SUPPORTED, "\u4E0D\u652F\u6301\u7F16\u7801: {0}"}, {ER_COULD_NOT_CREATE_TRACELISTENER, "\u65E0\u6CD5\u521B\u5EFA TraceListener: {0}"}, {ER_KEY_REQUIRES_NAME_ATTRIB, "xsl:key \u9700\u8981 'name' \u5C5E\u6027!"}, { ER_KEY_REQUIRES_MATCH_ATTRIB, "xsl:key \u9700\u8981 'match' \u5C5E\u6027!"}, { ER_KEY_REQUIRES_USE_ATTRIB, "xsl:key \u9700\u8981 'use' \u5C5E\u6027!"}, { ER_REQUIRES_ELEMENTS_ATTRIB, "(StylesheetHandler) {0}\u9700\u8981 ''elements'' \u5C5E\u6027!"}, { ER_MISSING_PREFIX_ATTRIB, "(StylesheetHandler) \u7F3A\u5C11{0}\u5C5E\u6027 ''prefix''"}, { ER_BAD_STYLESHEET_URL, "\u6837\u5F0F\u8868 URL \u9519\u8BEF: {0}"}, { ER_FILE_NOT_FOUND, "\u627E\u4E0D\u5230\u6837\u5F0F\u8868\u6587\u4EF6: {0}"}, { ER_IOEXCEPTION, "\u6837\u5F0F\u8868\u6587\u4EF6\u51FA\u73B0 IO \u5F02\u5E38\u9519\u8BEF: {0}"}, { ER_NO_HREF_ATTRIB, "(StylesheetHandler) \u627E\u4E0D\u5230{0}\u7684 href \u5C5E\u6027"}, { ER_STYLESHEET_INCLUDES_ITSELF, "(StylesheetHandler) {0}\u76F4\u63A5\u6216\u95F4\u63A5\u5305\u542B\u5176\u81EA\u8EAB!"}, { ER_PROCESSINCLUDE_ERROR, "StylesheetHandler.processInclude \u9519\u8BEF, {0}"}, { ER_MISSING_LANG_ATTRIB, "(StylesheetHandler) \u7F3A\u5C11{0}\u5C5E\u6027 ''lang''"}, { ER_MISSING_CONTAINER_ELEMENT_COMPONENT, "(StylesheetHandler) {0}\u5143\u7D20\u7684\u653E\u7F6E\u4F4D\u7F6E\u662F\u5426\u9519\u8BEF?? \u7F3A\u5C11\u5BB9\u5668\u5143\u7D20 ''component''"}, { ER_CAN_ONLY_OUTPUT_TO_ELEMENT, "\u53EA\u80FD\u8F93\u51FA\u5230 Element, DocumentFragment, Document \u6216 PrintWriter\u3002"}, { ER_PROCESS_ERROR, "StylesheetRoot.process \u9519\u8BEF"}, { ER_UNIMPLNODE_ERROR, "UnImplNode \u9519\u8BEF: {0}"}, { ER_NO_SELECT_EXPRESSION, "\u9519\u8BEF! \u627E\u4E0D\u5230 xpath \u9009\u62E9\u8868\u8FBE\u5F0F (-select)\u3002"}, { ER_CANNOT_SERIALIZE_XSLPROCESSOR, "\u65E0\u6CD5\u5E8F\u5217\u5316 XSLProcessor!"}, { ER_NO_INPUT_STYLESHEET, "\u672A\u6307\u5B9A\u6837\u5F0F\u8868\u8F93\u5165!"}, { ER_FAILED_PROCESS_STYLESHEET, "\u65E0\u6CD5\u5904\u7406\u6837\u5F0F\u8868!"}, { ER_COULDNT_PARSE_DOC, "\u65E0\u6CD5\u89E3\u6790{0}\u6587\u6863!"}, { ER_COULDNT_FIND_FRAGMENT, "\u627E\u4E0D\u5230\u7247\u6BB5: {0}"}, { ER_NODE_NOT_ELEMENT, "\u7247\u6BB5\u6807\u8BC6\u7B26\u6307\u5411\u7684\u8282\u70B9\u4E0D\u662F\u5143\u7D20: {0}"}, { ER_FOREACH_NEED_MATCH_OR_NAME_ATTRIB, "for-each \u5FC5\u987B\u5177\u6709 match \u6216 name \u5C5E\u6027"}, { ER_TEMPLATES_NEED_MATCH_OR_NAME_ATTRIB, "templates \u5FC5\u987B\u5177\u6709 match \u6216 name \u5C5E\u6027"}, { ER_NO_CLONE_OF_DOCUMENT_FRAG, "\u4E0D\u80FD\u514B\u9686\u6587\u6863\u7247\u6BB5!"}, { ER_CANT_CREATE_ITEM, "\u65E0\u6CD5\u5728\u7ED3\u679C\u6811\u4E2D\u521B\u5EFA\u9879: {0}"}, { ER_XMLSPACE_ILLEGAL_VALUE, "\u6E90 XML \u4E2D\u7684 xml:space \u5177\u6709\u975E\u6CD5\u503C: {0}"}, { ER_NO_XSLKEY_DECLARATION, "{0}\u6CA1\u6709 xsl:key \u58F0\u660E!"}, { ER_CANT_CREATE_URL, "\u9519\u8BEF! \u65E0\u6CD5\u4E3A{0}\u521B\u5EFA url"}, { ER_XSLFUNCTIONS_UNSUPPORTED, "\u4E0D\u652F\u6301 xsl:functions"}, { ER_PROCESSOR_ERROR, "XSLT TransformerFactory \u9519\u8BEF"}, { ER_NOT_ALLOWED_INSIDE_STYLESHEET, "(StylesheetHandler) \u6837\u5F0F\u8868\u4E2D\u4E0D\u5141\u8BB8\u4F7F\u7528{0}!"}, { ER_RESULTNS_NOT_SUPPORTED, "\u4E0D\u518D\u652F\u6301 result-ns! \u8BF7\u6539\u7528 xsl:output\u3002"}, { ER_DEFAULTSPACE_NOT_SUPPORTED, "\u4E0D\u518D\u652F\u6301 default-space! \u8BF7\u6539\u7528 xsl:strip-space \u6216 xsl:preserve-space\u3002"}, { ER_INDENTRESULT_NOT_SUPPORTED, "\u4E0D\u518D\u652F\u6301 indent-result! \u8BF7\u6539\u7528 xsl:output\u3002"}, { ER_ILLEGAL_ATTRIB, "(StylesheetHandler) {0}\u5177\u6709\u975E\u6CD5\u5C5E\u6027: {1}"}, { ER_UNKNOWN_XSL_ELEM, "\u672A\u77E5 XSL \u5143\u7D20: {0}"}, { ER_BAD_XSLSORT_USE, "(StylesheetHandler) xsl:sort \u53EA\u80FD\u4E0E xsl:apply-templates \u6216 xsl:for-each \u4E00\u8D77\u4F7F\u7528\u3002"}, { ER_MISPLACED_XSLWHEN, "(StylesheetHandler) xsl:when \u7684\u653E\u7F6E\u4F4D\u7F6E\u9519\u8BEF!"}, { ER_XSLWHEN_NOT_PARENTED_BY_XSLCHOOSE, "(StylesheetHandler) xsl:when \u7684\u7236\u7EA7\u4E0D\u662F xsl:choose!"}, { ER_MISPLACED_XSLOTHERWISE, "(StylesheetHandler) xsl:otherwise \u7684\u653E\u7F6E\u4F4D\u7F6E\u9519\u8BEF!"}, { ER_XSLOTHERWISE_NOT_PARENTED_BY_XSLCHOOSE, "(StylesheetHandler) xsl:otherwise \u7684\u7236\u7EA7\u4E0D\u662F xsl:choose!"}, { ER_NOT_ALLOWED_INSIDE_TEMPLATE, "(StylesheetHandler) \u6A21\u677F\u4E2D\u4E0D\u5141\u8BB8\u4F7F\u7528{0}!"}, { ER_UNKNOWN_EXT_NS_PREFIX, "(StylesheetHandler) {0}\u6269\u5C55\u540D\u79F0\u7A7A\u95F4\u524D\u7F00 {1} \u672A\u77E5"}, { ER_IMPORTS_AS_FIRST_ELEM, "(StylesheetHandler) \u53EA\u80FD\u4F5C\u4E3A\u6837\u5F0F\u8868\u4E2D\u7684\u7B2C\u4E00\u4E2A\u5143\u7D20\u5BFC\u5165!"}, { ER_IMPORTING_ITSELF, "(StylesheetHandler) {0}\u76F4\u63A5\u6216\u95F4\u63A5\u5BFC\u5165\u5176\u81EA\u8EAB!"}, { ER_XMLSPACE_ILLEGAL_VAL, "(StylesheetHandler) xml:space \u5177\u6709\u975E\u6CD5\u503C: {0}"}, { ER_PROCESSSTYLESHEET_NOT_SUCCESSFUL, "processStylesheet \u5931\u8D25!"}, { ER_SAX_EXCEPTION, "SAX \u5F02\u5E38\u9519\u8BEF"}, // add this message to fix bug 21478 { ER_FUNCTION_NOT_SUPPORTED, "\u4E0D\u652F\u6301\u8BE5\u51FD\u6570!"}, { ER_XSLT_ERROR, "XSLT \u9519\u8BEF"}, { ER_CURRENCY_SIGN_ILLEGAL, "\u683C\u5F0F\u6A21\u5F0F\u5B57\u7B26\u4E32\u4E2D\u4E0D\u5141\u8BB8\u4F7F\u7528\u8D27\u5E01\u7B26\u53F7"}, { ER_DOCUMENT_FUNCTION_INVALID_IN_STYLESHEET_DOM, "\u6837\u5F0F\u8868 DOM \u4E2D\u4E0D\u652F\u6301 Document \u51FD\u6570!"}, { ER_CANT_RESOLVE_PREFIX_OF_NON_PREFIX_RESOLVER, "\u65E0\u6CD5\u89E3\u6790\u975E\u524D\u7F00\u89E3\u6790\u5668\u7684\u524D\u7F00!"}, { ER_REDIRECT_COULDNT_GET_FILENAME, "\u91CD\u5B9A\u5411\u6269\u5C55: \u65E0\u6CD5\u83B7\u53D6\u6587\u4EF6\u540D - file \u6216 select \u5C5E\u6027\u5FC5\u987B\u8FD4\u56DE\u6709\u6548\u5B57\u7B26\u4E32\u3002"}, { ER_CANNOT_BUILD_FORMATTERLISTENER_IN_REDIRECT, "\u65E0\u6CD5\u5728\u91CD\u5B9A\u5411\u6269\u5C55\u4E2D\u6784\u5EFA FormatterListener!"}, { ER_INVALID_PREFIX_IN_EXCLUDERESULTPREFIX, "exclude-result-prefixes \u4E2D\u7684\u524D\u7F00\u65E0\u6548: {0}"}, { ER_MISSING_NS_URI, "\u6307\u5B9A\u524D\u7F00\u7F3A\u5C11\u540D\u79F0\u7A7A\u95F4 URI"}, { ER_MISSING_ARG_FOR_OPTION, "\u9009\u9879\u7F3A\u5C11\u53C2\u6570: {0}"}, { ER_INVALID_OPTION, "\u9009\u9879\u65E0\u6548: {0}"}, { ER_MALFORMED_FORMAT_STRING, "\u683C\u5F0F\u5B57\u7B26\u4E32\u7684\u683C\u5F0F\u9519\u8BEF: {0}"}, { ER_STYLESHEET_REQUIRES_VERSION_ATTRIB, "xsl:stylesheet \u9700\u8981 'version' \u5C5E\u6027!"}, { ER_ILLEGAL_ATTRIBUTE_VALUE, "\u5C5E\u6027{0}\u5177\u6709\u975E\u6CD5\u503C: {1}"}, { ER_CHOOSE_REQUIRES_WHEN, "xsl:choose \u9700\u8981 xsl:when"}, { ER_NO_APPLY_IMPORT_IN_FOR_EACH, "xsl:for-each \u4E2D\u4E0D\u5141\u8BB8\u4F7F\u7528 xsl:apply-imports"}, { ER_CANT_USE_DTM_FOR_OUTPUT, "\u65E0\u6CD5\u5C06 DTMLiaison \u7528\u4E8E\u8F93\u51FA DOM \u8282\u70B9... \u8BF7\u6539\u4E3A\u4F20\u9012 com.sun.org.apache.xpath.internal.DOM2Helper!"}, { ER_CANT_USE_DTM_FOR_INPUT, "\u65E0\u6CD5\u5C06 DTMLiaison \u7528\u4E8E\u8F93\u5165 DOM \u8282\u70B9... \u8BF7\u6539\u4E3A\u4F20\u9012 com.sun.org.apache.xpath.internal.DOM2Helper!"}, { ER_CALL_TO_EXT_FAILED, "\u672A\u80FD\u8C03\u7528\u6269\u5C55\u5143\u7D20: {0}"}, { ER_PREFIX_MUST_RESOLVE, "\u524D\u7F00\u5FC5\u987B\u89E3\u6790\u4E3A\u540D\u79F0\u7A7A\u95F4: {0}"}, { ER_INVALID_UTF16_SURROGATE, "\u68C0\u6D4B\u5230\u65E0\u6548\u7684 UTF-16 \u4EE3\u7406: {0}?"}, { ER_XSLATTRSET_USED_ITSELF, "xsl:attribute-set {0} \u4F7F\u7528\u5176\u81EA\u8EAB, \u8FD9\u5C06\u5BFC\u81F4\u65E0\u9650\u5FAA\u73AF\u3002"}, { ER_CANNOT_MIX_XERCESDOM, "\u65E0\u6CD5\u6DF7\u5408\u975E Xerces-DOM \u8F93\u5165\u548C Xerces-DOM \u8F93\u51FA!"}, { ER_TOO_MANY_LISTENERS, "addTraceListenersToStylesheet - TooManyListenersException"}, { ER_IN_ELEMTEMPLATEELEM_READOBJECT, "\u5728 ElemTemplateElement.readObject \u4E2D: {0}"}, { ER_DUPLICATE_NAMED_TEMPLATE, "\u627E\u5230\u591A\u4E2A\u540D\u4E3A{0}\u7684\u6A21\u677F"}, { ER_INVALID_KEY_CALL, "\u51FD\u6570\u8C03\u7528\u65E0\u6548: \u4E0D\u5141\u8BB8\u9012\u5F52 key() \u8C03\u7528"}, { ER_REFERENCING_ITSELF, "\u53D8\u91CF {0} \u76F4\u63A5\u6216\u95F4\u63A5\u5F15\u7528\u5176\u81EA\u8EAB!"}, { ER_ILLEGAL_DOMSOURCE_INPUT, "\u5BF9\u4E8E newTemplates \u7684 DOMSource, \u8F93\u5165\u8282\u70B9\u4E0D\u80FD\u4E3A\u7A7A\u503C!"}, { ER_CLASS_NOT_FOUND_FOR_OPTION, "\u627E\u4E0D\u5230\u9009\u9879{0}\u7684\u7C7B\u6587\u4EF6"}, { ER_REQUIRED_ELEM_NOT_FOUND, "\u627E\u4E0D\u5230\u6240\u9700\u5143\u7D20: {0}"}, { ER_INPUT_CANNOT_BE_NULL, "InputStream \u4E0D\u80FD\u4E3A\u7A7A\u503C"}, { ER_URI_CANNOT_BE_NULL, "URI \u4E0D\u80FD\u4E3A\u7A7A\u503C"}, { ER_FILE_CANNOT_BE_NULL, "File \u4E0D\u80FD\u4E3A\u7A7A\u503C"}, { ER_SOURCE_CANNOT_BE_NULL, "InputSource \u4E0D\u80FD\u4E3A\u7A7A\u503C"}, { ER_CANNOT_INIT_BSFMGR, "\u65E0\u6CD5\u521D\u59CB\u5316 BSF \u7BA1\u7406\u5668"}, { ER_CANNOT_CMPL_EXTENSN, "\u65E0\u6CD5\u7F16\u8BD1\u6269\u5C55"}, { ER_CANNOT_CREATE_EXTENSN, "\u65E0\u6CD5\u521B\u5EFA\u6269\u5C55: {0}, \u539F\u56E0: {1}"}, { ER_INSTANCE_MTHD_CALL_REQUIRES, "\u5BF9\u65B9\u6CD5{0}\u7684\u5B9E\u4F8B\u65B9\u6CD5\u8C03\u7528\u9700\u8981\u5C06 Object \u5B9E\u4F8B\u4F5C\u4E3A\u7B2C\u4E00\u4E2A\u53C2\u6570"}, { ER_INVALID_ELEMENT_NAME, "\u6307\u5B9A\u7684\u5143\u7D20\u540D\u79F0{0}\u65E0\u6548"}, { ER_ELEMENT_NAME_METHOD_STATIC, "\u5143\u7D20\u540D\u79F0\u65B9\u6CD5\u5FC5\u987B\u662F static {0}"}, { ER_EXTENSION_FUNC_UNKNOWN, "\u6269\u5C55\u51FD\u6570 {0}: {1} \u672A\u77E5"}, { ER_MORE_MATCH_CONSTRUCTOR, "{0}\u7684\u6784\u9020\u5668\u5177\u6709\u591A\u4E2A\u6700\u4F73\u5339\u914D"}, { ER_MORE_MATCH_METHOD, "\u65B9\u6CD5{0}\u5177\u6709\u591A\u4E2A\u6700\u4F73\u5339\u914D"}, { ER_MORE_MATCH_ELEMENT, "\u5143\u7D20\u65B9\u6CD5{0}\u5177\u6709\u591A\u4E2A\u6700\u4F73\u5339\u914D"}, { ER_INVALID_CONTEXT_PASSED, "\u4F20\u9012\u7684\u7528\u4E8E\u5BF9{0}\u6C42\u503C\u7684\u4E0A\u4E0B\u6587\u65E0\u6548"}, { ER_POOL_EXISTS, "\u6C60\u5DF2\u5B58\u5728"}, { ER_NO_DRIVER_NAME, "\u672A\u6307\u5B9A\u9A71\u52A8\u7A0B\u5E8F\u540D\u79F0"}, { ER_NO_URL, "\u672A\u6307\u5B9A URL"}, { ER_POOL_SIZE_LESSTHAN_ONE, "\u6C60\u5927\u5C0F\u5C0F\u4E8E 1!"}, { ER_INVALID_DRIVER, "\u6307\u5B9A\u7684\u9A71\u52A8\u7A0B\u5E8F\u540D\u79F0\u65E0\u6548!"}, { ER_NO_STYLESHEETROOT, "\u627E\u4E0D\u5230\u6837\u5F0F\u8868\u6839!"}, { ER_ILLEGAL_XMLSPACE_VALUE, "xml:space \u7684\u503C\u975E\u6CD5"}, { ER_PROCESSFROMNODE_FAILED, "processFromNode \u5931\u8D25"}, { ER_RESOURCE_COULD_NOT_LOAD, "\u8D44\u6E90 [ {0} ] \u65E0\u6CD5\u52A0\u8F7D: {1} \n {2} \t {3}"}, { ER_BUFFER_SIZE_LESSTHAN_ZERO, "\u7F13\u51B2\u533A\u5927\u5C0F <=0"}, { ER_UNKNOWN_ERROR_CALLING_EXTENSION, "\u8C03\u7528\u6269\u5C55\u65F6\u51FA\u73B0\u672A\u77E5\u9519\u8BEF"}, { ER_NO_NAMESPACE_DECL, "\u524D\u7F00 {0} \u6CA1\u6709\u5BF9\u5E94\u7684\u540D\u79F0\u7A7A\u95F4\u58F0\u660E"}, { ER_ELEM_CONTENT_NOT_ALLOWED, "lang=javaclass {0}\u4E0D\u5141\u8BB8\u4F7F\u7528\u5143\u7D20\u5185\u5BB9"}, { ER_STYLESHEET_DIRECTED_TERMINATION, "\u6837\u5F0F\u8868\u6307\u5411\u7EC8\u6B62"}, { ER_ONE_OR_TWO, "1 \u6216 2"}, { ER_TWO_OR_THREE, "2 \u6216 3"}, { ER_COULD_NOT_LOAD_RESOURCE, "\u65E0\u6CD5\u52A0\u8F7D{0} (\u68C0\u67E5 CLASSPATH), \u73B0\u5728\u53EA\u4F7F\u7528\u9ED8\u8BA4\u503C"}, { ER_CANNOT_INIT_DEFAULT_TEMPLATES, "\u65E0\u6CD5\u521D\u59CB\u5316\u9ED8\u8BA4\u6A21\u677F"}, { ER_RESULT_NULL, "Result \u4E0D\u80FD\u4E3A\u7A7A\u503C"}, { ER_RESULT_COULD_NOT_BE_SET, "\u65E0\u6CD5\u8BBE\u7F6E Result"}, { ER_NO_OUTPUT_SPECIFIED, "\u672A\u6307\u5B9A\u8F93\u51FA"}, { ER_CANNOT_TRANSFORM_TO_RESULT_TYPE, "\u65E0\u6CD5\u8F6C\u6362\u4E3A\u7C7B\u578B\u4E3A{0}\u7684 Result"}, { ER_CANNOT_TRANSFORM_SOURCE_TYPE, "\u65E0\u6CD5\u8F6C\u6362\u7C7B\u578B\u4E3A{0}\u7684\u6E90"}, { ER_NULL_CONTENT_HANDLER, "\u7A7A\u5185\u5BB9\u5904\u7406\u7A0B\u5E8F"}, { ER_NULL_ERROR_HANDLER, "\u7A7A\u9519\u8BEF\u5904\u7406\u7A0B\u5E8F"}, { ER_CANNOT_CALL_PARSE, "\u5982\u679C\u5C1A\u672A\u8BBE\u7F6E ContentHandler, \u5219\u65E0\u6CD5\u8C03\u7528 parse"}, { ER_NO_PARENT_FOR_FILTER, "\u7B5B\u9009\u5668\u6CA1\u6709\u7236\u7EA7"}, { ER_NO_STYLESHEET_IN_MEDIA, "\u5728{0}\u4E2D\u627E\u4E0D\u5230\u6837\u5F0F\u8868, \u4ECB\u8D28= {1}"}, { ER_NO_STYLESHEET_PI, "\u5728{0}\u4E2D\u627E\u4E0D\u5230 xml-stylesheet PI"}, { ER_NOT_SUPPORTED, "\u4E0D\u652F\u6301: {0}"}, { ER_PROPERTY_VALUE_BOOLEAN, "\u5C5E\u6027{0}\u7684\u503C\u5E94\u4E3A Boolean \u5B9E\u4F8B"}, { ER_COULD_NOT_FIND_EXTERN_SCRIPT, "\u65E0\u6CD5\u5728{0}\u4E2D\u83B7\u53D6\u5916\u90E8\u811A\u672C"}, { ER_RESOURCE_COULD_NOT_FIND, "\u627E\u4E0D\u5230\u8D44\u6E90 [ {0} ]\u3002\n {1}"}, { ER_OUTPUT_PROPERTY_NOT_RECOGNIZED, "\u65E0\u6CD5\u8BC6\u522B\u8F93\u51FA\u5C5E\u6027: {0}"}, { ER_FAILED_CREATING_ELEMLITRSLT, "\u672A\u80FD\u521B\u5EFA ElemLiteralResult \u5B9E\u4F8B"}, //Earlier (JDK 1.4 XALAN 2.2-D11) at key code '204' the key name was ER_PRIORITY_NOT_PARSABLE // In latest Xalan code base key name is ER_VALUE_SHOULD_BE_NUMBER. This should also be taken care //in locale specific files like XSLTErrorResources_de.java, XSLTErrorResources_fr.java etc. //NOTE: Not only the key name but message has also been changed. { ER_VALUE_SHOULD_BE_NUMBER, "{0}\u7684\u503C\u5E94\u5305\u542B\u53EF\u89E3\u6790\u7684\u6570\u5B57"}, { ER_VALUE_SHOULD_EQUAL, "{0}\u7684\u503C\u5E94\u7B49\u4E8E\u201C\u662F\u201D\u6216\u201C\u5426\u201D"}, { ER_FAILED_CALLING_METHOD, "\u672A\u80FD\u8C03\u7528{0}\u65B9\u6CD5"}, { ER_FAILED_CREATING_ELEMTMPL, "\u672A\u80FD\u521B\u5EFA ElemTemplateElement \u5B9E\u4F8B"}, { ER_CHARS_NOT_ALLOWED, "\u4E0D\u5141\u8BB8\u5728\u6587\u6863\u4E2D\u7684\u6B64\u4F4D\u7F6E\u5904\u4F7F\u7528\u5B57\u7B26"}, { ER_ATTR_NOT_ALLOWED, "{1}\u5143\u7D20\u4E2D\u4E0D\u5141\u8BB8\u4F7F\u7528 \"{0}\" \u5C5E\u6027!"}, { ER_BAD_VALUE, "{0}\u9519\u8BEF\u503C{1} "}, { ER_ATTRIB_VALUE_NOT_FOUND, "\u627E\u4E0D\u5230{0}\u5C5E\u6027\u503C "}, { ER_ATTRIB_VALUE_NOT_RECOGNIZED, "\u65E0\u6CD5\u8BC6\u522B{0}\u5C5E\u6027\u503C "}, { ER_NULL_URI_NAMESPACE, "\u5C1D\u8BD5\u4F7F\u7528\u7A7A URI \u751F\u6210\u540D\u79F0\u7A7A\u95F4\u524D\u7F00"}, { ER_NUMBER_TOO_BIG, "\u5C1D\u8BD5\u8BBE\u7F6E\u8D85\u8FC7\u6700\u5927\u957F\u6574\u578B\u7684\u6570\u5B57\u7684\u683C\u5F0F"}, { ER_CANNOT_FIND_SAX1_DRIVER, "\u627E\u4E0D\u5230 SAX1 \u9A71\u52A8\u7A0B\u5E8F\u7C7B{0}"}, { ER_SAX1_DRIVER_NOT_LOADED, "\u5DF2\u627E\u5230 SAX1 \u9A71\u52A8\u7A0B\u5E8F\u7C7B{0}, \u4F46\u65E0\u6CD5\u8FDB\u884C\u52A0\u8F7D"}, { ER_SAX1_DRIVER_NOT_INSTANTIATED, "\u5DF2\u52A0\u8F7D SAX1 \u9A71\u52A8\u7A0B\u5E8F\u7C7B{0}, \u4F46\u65E0\u6CD5\u8FDB\u884C\u5B9E\u4F8B\u5316"}, { ER_SAX1_DRIVER_NOT_IMPLEMENT_PARSER, "SAX1 \u9A71\u52A8\u7A0B\u5E8F\u7C7B {0} \u672A\u5B9E\u73B0 org.xml.sax.Parser"}, { ER_PARSER_PROPERTY_NOT_SPECIFIED, "\u672A\u6307\u5B9A\u7CFB\u7EDF\u5C5E\u6027 org.xml.sax.parser"}, { ER_PARSER_ARG_CANNOT_BE_NULL, "\u89E3\u6790\u5668\u53C2\u6570\u4E0D\u80FD\u4E3A\u7A7A\u503C"}, { ER_FEATURE, "\u529F\u80FD: {0}"}, { ER_PROPERTY, "\u5C5E\u6027: {0}"}, { ER_NULL_ENTITY_RESOLVER, "\u7A7A\u5B9E\u4F53\u89E3\u6790\u5668"}, { ER_NULL_DTD_HANDLER, "\u7A7A DTD \u5904\u7406\u7A0B\u5E8F"}, { ER_NO_DRIVER_NAME_SPECIFIED, "\u672A\u6307\u5B9A\u9A71\u52A8\u7A0B\u5E8F\u540D\u79F0!"}, { ER_NO_URL_SPECIFIED, "\u672A\u6307\u5B9A URL!"}, { ER_POOLSIZE_LESS_THAN_ONE, "\u6C60\u5927\u5C0F\u5C0F\u4E8E 1!"}, { ER_INVALID_DRIVER_NAME, "\u6307\u5B9A\u7684\u9A71\u52A8\u7A0B\u5E8F\u540D\u79F0\u65E0\u6548!"}, { ER_ERRORLISTENER, "ErrorListener"}, // Note to translators: The following message should not normally be displayed // to users. It describes a situation in which the processor has detected // an internal consistency problem in itself, and it provides this message // for the developer to help diagnose the problem. The name // 'ElemTemplateElement' is the name of a class, and should not be // translated. { ER_ASSERT_NO_TEMPLATE_PARENT, "\u7A0B\u5E8F\u5458\u9519\u8BEF! \u8868\u8FBE\u5F0F\u6CA1\u6709 ElemTemplateElement \u7236\u7EA7!"}, // Note to translators: The following message should not normally be displayed // to users. It describes a situation in which the processor has detected // an internal consistency problem in itself, and it provides this message // for the developer to help diagnose the problem. The substitution text // provides further information in order to diagnose the problem. The name // 'RedundentExprEliminator' is the name of a class, and should not be // translated. { ER_ASSERT_REDUNDENT_EXPR_ELIMINATOR, "RedundentExprEliminator \u4E2D\u7684\u7A0B\u5E8F\u5458\u65AD\u8A00: {0}"}, { ER_NOT_ALLOWED_IN_POSITION, "\u4E0D\u5141\u8BB8\u5728\u6837\u5F0F\u8868\u4E2D\u7684\u6B64\u4F4D\u7F6E\u4F7F\u7528{0}!"}, { ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION, "\u4E0D\u5141\u8BB8\u5728\u6837\u5F0F\u8868\u4E2D\u7684\u6B64\u4F4D\u7F6E\u4F7F\u7528\u975E\u7A7A\u767D\u6587\u672C!"}, // This code is shared with warning codes. // SystemId Unknown { INVALID_TCHAR, "CHAR \u5C5E\u6027{0}\u4F7F\u7528\u4E86\u975E\u6CD5\u503C{1}\u3002CHAR \u7C7B\u578B\u7684\u5C5E\u6027\u53EA\u80FD\u4E3A 1 \u4E2A\u5B57\u7B26!"}, // Note to translators: The following message is used if the value of // an attribute in a stylesheet is invalid. "QNAME" is the XML data-type of // the attribute, and should not be translated. The substitution text {1} is // the attribute value and {0} is the attribute name. //The following codes are shared with the warning codes... { INVALID_QNAME, "QNAME \u5C5E\u6027{0}\u4F7F\u7528\u4E86\u975E\u6CD5\u503C{1}"}, // Note to translators: The following message is used if the value of // an attribute in a stylesheet is invalid. "ENUM" is the XML data-type of // the attribute, and should not be translated. The substitution text {1} is // the attribute value, {0} is the attribute name, and {2} is a list of valid // values. { INVALID_ENUM, "ENUM \u5C5E\u6027{0}\u4F7F\u7528\u4E86\u975E\u6CD5\u503C{1}\u3002\u6709\u6548\u503C\u4E3A: {2}\u3002"}, // Note to translators: The following message is used if the value of // an attribute in a stylesheet is invalid. "NMTOKEN" is the XML data-type // of the attribute, and should not be translated. The substitution text {1} is // the attribute value and {0} is the attribute name. { INVALID_NMTOKEN, "NMTOKEN \u5C5E\u6027{0}\u4F7F\u7528\u4E86\u975E\u6CD5\u503C{1} "}, // Note to translators: The following message is used if the value of // an attribute in a stylesheet is invalid. "NCNAME" is the XML data-type // of the attribute, and should not be translated. The substitution text {1} is // the attribute value and {0} is the attribute name. { INVALID_NCNAME, "NCNAME \u5C5E\u6027{0}\u4F7F\u7528\u4E86\u975E\u6CD5\u503C{1} "}, // Note to translators: The following message is used if the value of // an attribute in a stylesheet is invalid. "boolean" is the XSLT data-type // of the attribute, and should not be translated. The substitution text {1} is // the attribute value and {0} is the attribute name. { INVALID_BOOLEAN, "Boolean \u5C5E\u6027{0}\u4F7F\u7528\u4E86\u975E\u6CD5\u503C{1} "}, // Note to translators: The following message is used if the value of // an attribute in a stylesheet is invalid. "number" is the XSLT data-type // of the attribute, and should not be translated. The substitution text {1} is // the attribute value and {0} is the attribute name. { INVALID_NUMBER, "Number \u5C5E\u6027{0}\u4F7F\u7528\u4E86\u975E\u6CD5\u503C{1} "}, // End of shared codes... // Note to translators: A "match pattern" is a special form of XPath expression // that is used for matching patterns. The substitution text is the name of // a function. The message indicates that when this function is referenced in // a match pattern, its argument must be a string literal (or constant.) // ER_ARG_LITERAL - new error message for bugzilla //5202 { ER_ARG_LITERAL, "\u5339\u914D\u6A21\u5F0F\u4E2D\u7684{0}\u7684\u53C2\u6570\u5FC5\u987B\u4E3A\u6587\u5B57\u3002"}, // Note to translators: The following message indicates that two definitions of // a variable. A "global variable" is a variable that is accessible everywher // in the stylesheet. // ER_DUPLICATE_GLOBAL_VAR - new error message for bugzilla #790 { ER_DUPLICATE_GLOBAL_VAR, "\u5168\u5C40\u53D8\u91CF\u58F0\u660E\u91CD\u590D\u3002"}, // Note to translators: The following message indicates that two definitions of // a variable were encountered. // ER_DUPLICATE_VAR - new error message for bugzilla #790 { ER_DUPLICATE_VAR, "\u53D8\u91CF\u58F0\u660E\u91CD\u590D\u3002"}, // Note to translators: "xsl:template, "name" and "match" are XSLT keywords // which must not be translated. // ER_TEMPLATE_NAME_MATCH - new error message for bugzilla #789 { ER_TEMPLATE_NAME_MATCH, "xsl:template \u5FC5\u987B\u5177\u6709 name \u548C/\u6216 match \u5C5E\u6027"}, // Note to translators: "exclude-result-prefixes" is an XSLT keyword which // should not be translated. The message indicates that a namespace prefix // encountered as part of the value of the exclude-result-prefixes attribute // was in error. // ER_INVALID_PREFIX - new error message for bugzilla #788 { ER_INVALID_PREFIX, "exclude-result-prefixes \u4E2D\u7684\u524D\u7F00\u65E0\u6548: {0}"}, // Note to translators: An "attribute set" is a set of attributes that can // be added to an element in the output document as a group. The message // indicates that there was a reference to an attribute set named {0} that // was never defined. // ER_NO_ATTRIB_SET - new error message for bugzilla #782 { ER_NO_ATTRIB_SET, "\u540D\u4E3A{0}\u7684\u5C5E\u6027\u96C6\u4E0D\u5B58\u5728"}, // Note to translators: This message indicates that there was a reference // to a function named {0} for which no function definition could be found. { ER_FUNCTION_NOT_FOUND, "\u540D\u4E3A{0}\u7684\u51FD\u6570\u4E0D\u5B58\u5728"}, // Note to translators: This message indicates that the XSLT instruction // that is named by the substitution text {0} must not contain other XSLT // instructions (content) or a "select" attribute. The word "select" is // an XSLT keyword in this case and must not be translated. { ER_CANT_HAVE_CONTENT_AND_SELECT, "{0}\u5143\u7D20\u4E0D\u80FD\u540C\u65F6\u5177\u6709\u5185\u5BB9\u548C select \u5C5E\u6027\u3002"}, // Note to translators: This message indicates that the value argument // of setParameter must be a valid Java Object. { ER_INVALID_SET_PARAM_VALUE, "\u53C2\u6570 {0} \u7684\u503C\u5FC5\u987B\u662F\u6709\u6548 Java \u5BF9\u8C61"}, { ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX_FOR_DEFAULT, "xsl:namespace-alias \u5143\u7D20\u7684 result-prefix \u5C5E\u6027\u5177\u6709\u503C '#default', \u4F46\u8BE5\u5143\u7D20\u7684\u4F5C\u7528\u57DF\u4E2D\u6CA1\u6709\u9ED8\u8BA4\u540D\u79F0\u7A7A\u95F4\u7684\u58F0\u660E"}, { ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX, "xsl:namespace-alias \u5143\u7D20\u7684 result-prefix \u5C5E\u6027\u5177\u6709\u503C ''{0}'', \u4F46\u8BE5\u5143\u7D20\u7684\u4F5C\u7528\u57DF\u4E2D\u6CA1\u6709\u524D\u7F00 ''{0}'' \u7684\u540D\u79F0\u7A7A\u95F4\u58F0\u660E\u3002"}, { ER_SET_FEATURE_NULL_NAME, "TransformerFactory.setFeature(String name, boolean value) \u4E2D\u7684\u529F\u80FD\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u503C\u3002"}, { ER_GET_FEATURE_NULL_NAME, "TransformerFactory.getFeature(String name) \u4E2D\u7684\u529F\u80FD\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u503C\u3002"}, { ER_UNSUPPORTED_FEATURE, "\u65E0\u6CD5\u5BF9\u6B64 TransformerFactory \u8BBE\u7F6E\u529F\u80FD ''{0}''\u3002"}, { ER_EXTENSION_ELEMENT_NOT_ALLOWED_IN_SECURE_PROCESSING, "\u5F53\u5B89\u5168\u5904\u7406\u529F\u80FD\u8BBE\u7F6E\u4E3A\u201C\u771F\u201D\u65F6, \u4E0D\u5141\u8BB8\u4F7F\u7528\u6269\u5C55\u5143\u7D20 ''{0}''\u3002"}, { ER_NAMESPACE_CONTEXT_NULL_NAMESPACE, "\u65E0\u6CD5\u83B7\u53D6\u7A7A\u540D\u79F0\u7A7A\u95F4 uri \u7684\u524D\u7F00\u3002"}, { ER_NAMESPACE_CONTEXT_NULL_PREFIX, "\u65E0\u6CD5\u83B7\u53D6\u7A7A\u524D\u7F00\u7684\u540D\u79F0\u7A7A\u95F4 uri\u3002"}, { ER_XPATH_RESOLVER_NULL_QNAME, "\u51FD\u6570\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u503C\u3002"}, { ER_XPATH_RESOLVER_NEGATIVE_ARITY, "\u5143\u6570\u4E0D\u80FD\u4E3A\u8D1F\u6570\u3002"}, // Warnings... { WG_FOUND_CURLYBRACE, "\u5DF2\u627E\u5230 '}', \u4F46\u672A\u6253\u5F00\u5C5E\u6027\u6A21\u677F!"}, { WG_COUNT_ATTRIB_MATCHES_NO_ANCESTOR, "\u8B66\u544A: count \u5C5E\u6027\u4E0E xsl:number \u4E2D\u7684 ancestor \u4E0D\u5339\u914D! \u76EE\u6807 = {0}"}, { WG_EXPR_ATTRIB_CHANGED_TO_SELECT, "\u65E7\u8BED\u6CD5: 'expr' \u5C5E\u6027\u7684\u540D\u79F0\u5DF2\u66F4\u6539\u4E3A 'select'\u3002"}, { WG_NO_LOCALE_IN_FORMATNUMBER, "Xalan \u5C1A\u672A\u5904\u7406 format-number \u51FD\u6570\u4E2D\u7684\u533A\u57DF\u8BBE\u7F6E\u540D\u79F0\u3002"}, { WG_LOCALE_NOT_FOUND, "\u8B66\u544A: \u627E\u4E0D\u5230 xml:lang={0} \u7684\u533A\u57DF\u8BBE\u7F6E"}, { WG_CANNOT_MAKE_URL_FROM, "\u65E0\u6CD5\u6839\u636E{0}\u751F\u6210 URL"}, { WG_CANNOT_LOAD_REQUESTED_DOC, "\u65E0\u6CD5\u52A0\u8F7D\u8BF7\u6C42\u7684\u6587\u6863: {0}"}, { WG_CANNOT_FIND_COLLATOR, "\u627E\u4E0D\u5230 <sort xml:lang={0} \u7684 Collator"}, { WG_FUNCTIONS_SHOULD_USE_URL, "\u65E7\u8BED\u6CD5: \u51FD\u6570\u6307\u4EE4\u5E94\u4F7F\u7528{0}\u7684 url"}, { WG_ENCODING_NOT_SUPPORTED_USING_UTF8, "\u4E0D\u652F\u6301\u7F16\u7801: {0}, \u4F7F\u7528 UTF-8"}, { WG_ENCODING_NOT_SUPPORTED_USING_JAVA, "\u4E0D\u652F\u6301\u7F16\u7801: {0}, \u4F7F\u7528 Java {1}"}, { WG_SPECIFICITY_CONFLICTS, "\u53D1\u73B0\u7279\u5F81\u51B2\u7A81: \u5C06\u4F7F\u7528\u4E0A\u6B21\u5728\u6837\u5F0F\u8868\u4E2D\u627E\u5230\u7684{0}\u3002"}, { WG_PARSING_AND_PREPARING, "========= \u89E3\u6790\u548C\u51C6\u5907{0} =========="}, { WG_ATTR_TEMPLATE, "\u5C5E\u6027\u6A21\u677F{0}"}, { WG_CONFLICT_BETWEEN_XSLSTRIPSPACE_AND_XSLPRESERVESPACE, "xsl:strip-space \u548C xsl:preserve-space \u4E4B\u95F4\u5B58\u5728\u5339\u914D\u51B2\u7A81"}, { WG_ATTRIB_NOT_HANDLED, "Xalan \u5C1A\u672A\u5904\u7406{0}\u5C5E\u6027!"}, { WG_NO_DECIMALFORMAT_DECLARATION, "\u627E\u4E0D\u5230\u5341\u8FDB\u5236\u683C\u5F0F\u7684\u58F0\u660E: {0}"}, { WG_OLD_XSLT_NS, "\u7F3A\u5C11 XSLT \u540D\u79F0\u7A7A\u95F4\u6216 XSLT \u540D\u79F0\u7A7A\u95F4\u9519\u8BEF\u3002"}, { WG_ONE_DEFAULT_XSLDECIMALFORMAT_ALLOWED, "\u4EC5\u5141\u8BB8\u4F7F\u7528\u4E00\u4E2A\u9ED8\u8BA4\u7684 xsl:decimal-format \u58F0\u660E\u3002"}, { WG_XSLDECIMALFORMAT_NAMES_MUST_BE_UNIQUE, "xsl:decimal-format \u540D\u79F0\u5FC5\u987B\u552F\u4E00\u3002\u540D\u79F0 \"{0}\" \u91CD\u590D\u3002"}, { WG_ILLEGAL_ATTRIBUTE, "{0}\u5177\u6709\u975E\u6CD5\u5C5E\u6027: {1}"}, { WG_COULD_NOT_RESOLVE_PREFIX, "\u65E0\u6CD5\u89E3\u6790\u540D\u79F0\u7A7A\u95F4\u524D\u7F00: {0}\u3002\u5C06\u5FFD\u7565\u8282\u70B9\u3002"}, { WG_STYLESHEET_REQUIRES_VERSION_ATTRIB, "xsl:stylesheet \u9700\u8981 'version' \u5C5E\u6027!"}, { WG_ILLEGAL_ATTRIBUTE_NAME, "\u975E\u6CD5\u5C5E\u6027\u540D\u79F0: {0}"}, { WG_ILLEGAL_ATTRIBUTE_VALUE, "\u5C5E\u6027{0}\u4F7F\u7528\u4E86\u975E\u6CD5\u503C{1}"}, { WG_EMPTY_SECOND_ARG, "\u6839\u636E document \u51FD\u6570\u7684\u7B2C\u4E8C\u4E2A\u53C2\u6570\u5F97\u5230\u7684\u8282\u70B9\u96C6\u4E3A\u7A7A\u3002\u8FD4\u56DE\u7A7A node-set\u3002"}, //Following are the new WARNING keys added in XALAN code base after Jdk 1.4 (Xalan 2.2-D11) // Note to translators: "name" and "xsl:processing-instruction" are keywords // and must not be translated. { WG_PROCESSINGINSTRUCTION_NAME_CANT_BE_XML, "xsl:processing-instruction \u540D\u79F0\u7684 'name' \u5C5E\u6027\u7684\u503C\u4E0D\u80FD\u4E3A 'xml'"}, // Note to translators: "name" and "xsl:processing-instruction" are keywords // and must not be translated. "NCName" is an XML data-type and must not be // translated. { WG_PROCESSINGINSTRUCTION_NOTVALID_NCNAME, "xsl:processing-instruction \u7684 ''name'' \u5C5E\u6027\u7684\u503C\u5FC5\u987B\u662F\u6709\u6548\u7684 NCName: {0}"}, // Note to translators: This message is reported if the stylesheet that is // being processed attempted to construct an XML document with an attribute in a // place other than on an element. The substitution text specifies the name of // the attribute. { WG_ILLEGAL_ATTRIBUTE_POSITION, "\u5728\u751F\u6210\u5B50\u8282\u70B9\u4E4B\u540E\u6216\u5728\u751F\u6210\u5143\u7D20\u4E4B\u524D\u65E0\u6CD5\u6DFB\u52A0\u5C5E\u6027 {0}\u3002\u5C06\u5FFD\u7565\u5C5E\u6027\u3002"}, { NO_MODIFICATION_ALLOWED_ERR, "\u5C1D\u8BD5\u4FEE\u6539\u4E0D\u5141\u8BB8\u4FEE\u6539\u7684\u5BF9\u8C61\u3002" }, //Check: WHY THERE IS A GAP B/W NUMBERS in the XSLTErrorResources properties file? // Other miscellaneous text used inside the code... { "ui_language", "en"}, { "help_language", "en" }, { "language", "en" }, { "BAD_CODE", "createMessage \u7684\u53C2\u6570\u8D85\u51FA\u8303\u56F4"}, { "FORMAT_FAILED", "\u8C03\u7528 messageFormat \u65F6\u629B\u51FA\u5F02\u5E38\u9519\u8BEF"}, { "version", ">>>>>>> Xalan \u7248\u672C "}, { "version2", "<<<<<<<"}, { "yes", "\u662F"}, { "line", "\u884C\u53F7"}, { "column","\u5217\u53F7"}, { "xsldone", "XSLProcessor: \u5B8C\u6210"}, // Note to translators: The following messages provide usage information // for the Xalan Process command line. "Process" is the name of a Java class, // and should not be translated. { "xslProc_option", "Xalan-J \u547D\u4EE4\u884C Process \u7C7B\u9009\u9879:"}, { "xslProc_option", "Xalan-J \u547D\u4EE4\u884C Process \u7C7B\u9009\u9879:"}, { "xslProc_invalid_xsltc_option", "XSLTC \u6A21\u5F0F\u4E0B\u4E0D\u652F\u6301\u9009\u9879{0}\u3002"}, { "xslProc_invalid_xalan_option", "\u9009\u9879{0}\u53EA\u80FD\u4E0E -XSLTC \u4E00\u8D77\u4F7F\u7528\u3002"}, { "xslProc_no_input", "\u9519\u8BEF: \u672A\u6307\u5B9A\u6837\u5F0F\u8868\u6216\u8F93\u5165 xml\u3002\u8FD0\u884C\u6B64\u547D\u4EE4\u65F6, \u7528\u6CD5\u6307\u4EE4\u4E0D\u5E26\u4EFB\u4F55\u9009\u9879\u3002"}, { "xslProc_common_options", "-\u516C\u7528\u9009\u9879-"}, { "xslProc_xalan_options", "-Xalan \u7684\u9009\u9879-"}, { "xslProc_xsltc_options", "-XSLTC \u7684\u9009\u9879-"}, { "xslProc_return_to_continue", "(\u6309 <return> \u4EE5\u7EE7\u7EED)"}, // Note to translators: The option name and the parameter name do not need to // be translated. Only translate the messages in parentheses. Note also that // leading whitespace in the messages is used to indent the usage information // for each option in the English messages. // Do not translate the keywords: XSLTC, SAX, DOM and DTM. { "optionXSLTC", " [-XSLTC (\u4F7F\u7528 XSLTC \u8FDB\u884C\u8F6C\u6362)]"}, { "optionIN", " [-IN inputXMLURL]"}, { "optionXSL", " [-XSL XSLTransformationURL]"}, { "optionOUT", " [-OUT outputFileName]"}, { "optionLXCIN", " [-LXCIN compiledStylesheetFileNameIn]"}, { "optionLXCOUT", " [-LXCOUT compiledStylesheetFileNameOutOut]"}, { "optionPARSER", " [-PARSER fully qualified class name of parser liaison]"}, { "optionE", " [-E (\u4E0D\u5C55\u5F00\u5B9E\u4F53\u5F15\u7528)]"}, { "optionV", " [-E (\u4E0D\u5C55\u5F00\u5B9E\u4F53\u5F15\u7528)]"}, { "optionQC", " [-QC (\u65E0\u63D0\u793A\u6A21\u5F0F\u51B2\u7A81\u8B66\u544A)]"}, { "optionQ", " [-Q (\u65E0\u63D0\u793A\u6A21\u5F0F)]"}, { "optionLF", " [-LF (\u4EC5\u5728\u8F93\u51FA\u65F6\u4F7F\u7528\u6362\u884C\u7B26 {\u9ED8\u8BA4\u503C\u4E3A CR/LF})]"}, { "optionCR", " [-CR (\u4EC5\u5728\u8F93\u51FA\u65F6\u4F7F\u7528\u56DE\u8F66 {\u9ED8\u8BA4\u503C\u4E3A CR/LF})]"}, { "optionESCAPE", " [-ESCAPE (\u8981\u8F6C\u79FB\u7684\u5B57\u7B26 {\u9ED8\u8BA4\u503C\u4E3A <>&\"'\\r\\n}]"}, { "optionINDENT", " [-INDENT (\u63A7\u5236\u8981\u7F29\u8FDB\u7684\u7A7A\u683C\u6570 {\u9ED8\u8BA4\u503C\u4E3A 0})]"}, { "optionTT", " [-TT (\u5728\u8C03\u7528\u6A21\u677F\u65F6\u8DDF\u8E2A\u6A21\u677F\u3002)]"}, { "optionTG", " [-TG (\u8DDF\u8E2A\u6BCF\u4E2A\u751F\u6210\u4E8B\u4EF6\u3002)]"}, { "optionTS", " [-TS (\u8DDF\u8E2A\u6BCF\u4E2A\u9009\u62E9\u4E8B\u4EF6\u3002)]"}, { "optionTTC", " [-TTC (\u5728\u5904\u7406\u6A21\u677F\u5B50\u7EA7\u65F6\u8DDF\u8E2A\u6A21\u677F\u5B50\u7EA7\u3002)]"}, { "optionTCLASS", " [-TCLASS (\u7528\u4E8E\u8DDF\u8E2A\u6269\u5C55\u7684 TraceListener \u7C7B\u3002)]"}, { "optionVALIDATE", " [-VALIDATE (\u8BBE\u7F6E\u662F\u5426\u8FDB\u884C\u9A8C\u8BC1\u3002\u9ED8\u8BA4\u60C5\u51B5\u4E0B, \u5C06\u7981\u6B62\u9A8C\u8BC1\u3002)]"}, { "optionEDUMP", " [-EDUMP {optional filename} (\u5728\u51FA\u9519\u65F6\u6267\u884C\u5806\u6808\u8F6C\u50A8\u3002)]"}, { "optionXML", " [-XML (\u4F7F\u7528 XML \u683C\u5F0F\u8BBE\u7F6E\u5DE5\u5177\u5E76\u6DFB\u52A0 XML \u6807\u5934\u3002)]"}, { "optionTEXT", " [-TEXT (\u4F7F\u7528\u7B80\u5355\u6587\u672C\u683C\u5F0F\u8BBE\u7F6E\u5DE5\u5177\u3002)]"}, { "optionHTML", " [-HTML (\u4F7F\u7528 HTML \u683C\u5F0F\u8BBE\u7F6E\u5DE5\u5177\u3002)]"}, { "optionPARAM", " [-PARAM \u540D\u79F0\u8868\u8FBE\u5F0F (\u8BBE\u7F6E\u6837\u5F0F\u8868\u53C2\u6570)]"}, { "noParsermsg1", "XSL \u8FDB\u7A0B\u672A\u6210\u529F\u3002"}, { "noParsermsg2", "** \u627E\u4E0D\u5230\u89E3\u6790\u5668 **"}, { "noParsermsg3", "\u8BF7\u68C0\u67E5\u60A8\u7684\u7C7B\u8DEF\u5F84\u3002"}, { "noParsermsg4", "\u5982\u679C\u6CA1\u6709 IBM \u63D0\u4F9B\u7684 XML Parser for Java, \u5219\u53EF\u4EE5\u4ECE"}, { "noParsermsg5", "IBM AlphaWorks \u8FDB\u884C\u4E0B\u8F7D, \u7F51\u5740\u4E3A: http://www.alphaworks.ibm.com/formula/xml"}, { "optionURIRESOLVER", " [-URIRESOLVER \u5B8C\u6574\u7C7B\u540D (\u4F7F\u7528 URIResolver \u89E3\u6790 URI)]"}, { "optionENTITYRESOLVER", " [-ENTITYRESOLVER \u5B8C\u6574\u7C7B\u540D (\u4F7F\u7528 EntityResolver \u89E3\u6790\u5B9E\u4F53)]"}, { "optionCONTENTHANDLER", " [-CONTENTHANDLER \u5B8C\u6574\u7C7B\u540D (\u4F7F\u7528 ContentHandler \u5E8F\u5217\u5316\u8F93\u51FA)]"}, { "optionLINENUMBERS", " [-L \u4F7F\u7528\u6E90\u6587\u6863\u7684\u884C\u53F7]"}, { "optionSECUREPROCESSING", " [-SECURE (\u5C06\u5B89\u5168\u5904\u7406\u529F\u80FD\u8BBE\u7F6E\u4E3A\u201C\u771F\u201D\u3002)]"}, // Following are the new options added in XSLTErrorResources.properties files after Jdk 1.4 (Xalan 2.2-D11) { "optionMEDIA", " [-MEDIA mediaType (\u4F7F\u7528 media \u5C5E\u6027\u67E5\u627E\u4E0E\u6587\u6863\u5173\u8054\u7684\u6837\u5F0F\u8868\u3002)]"}, { "optionFLAVOR", " [-FLAVOR flavorName (\u660E\u786E\u4F7F\u7528 s2s=SAX \u6216 d2d=DOM \u6267\u884C\u8F6C\u6362\u3002)] "}, // Added by sboag/scurcuru; experimental { "optionDIAG", " [-DIAG (\u8F93\u51FA\u5168\u90E8\u8F6C\u6362\u65F6\u95F4 (\u6BEB\u79D2)\u3002)]"}, { "optionINCREMENTAL", " [-INCREMENTAL (\u901A\u8FC7\u5C06 http://xml.apache.org/xalan/features/incremental \u8BBE\u7F6E\u4E3A\u201C\u771F\u201D\u6765\u8BF7\u6C42\u589E\u91CF DTM \u6784\u5EFA\u3002)]"}, { "optionNOOPTIMIMIZE", " [-NOOPTIMIMIZE (\u901A\u8FC7\u5C06 http://xml.apache.org/xalan/features/optimize \u8BBE\u7F6E\u4E3A\u201C\u5047\u201D\u6765\u8BF7\u6C42\u4E0D\u6267\u884C\u6837\u5F0F\u8868\u4F18\u5316\u5904\u7406\u3002)]"}, { "optionRL", " [-RL recursionlimit (\u58F0\u660E\u6837\u5F0F\u8868\u9012\u5F52\u6DF1\u5EA6\u7684\u6570\u5B57\u9650\u5236\u3002)]"}, { "optionXO", " [-XO [transletName] (\u4E3A\u751F\u6210\u7684 translet \u5206\u914D\u540D\u79F0)]"}, { "optionXD", " [-XD destinationDirectory (\u6307\u5B9A translet \u7684\u76EE\u6807\u76EE\u5F55)]"}, { "optionXJ", " [-XJ jarfile (\u5C06 translet \u7C7B\u6253\u5305\u5230\u540D\u4E3A <jarfile> \u7684 jar \u6587\u4EF6\u4E2D)]"}, { "optionXP", " [-XP package (\u4E3A\u751F\u6210\u7684\u6240\u6709 translet \u7C7B\u6307\u5B9A\u7A0B\u5E8F\u5305\u540D\u79F0\u524D\u7F00)]"}, //AddITIONAL STRINGS that need L10n // Note to translators: The following message describes usage of a particular // command-line option that is used to enable the "template inlining" // optimization. The optimization involves making a copy of the code // generated for a template in another template that refers to it. { "optionXN", " [-XN (\u542F\u7528\u6A21\u677F\u5185\u5D4C)]" }, { "optionXX", " [-XX (\u542F\u7528\u9644\u52A0\u8C03\u8BD5\u6D88\u606F\u8F93\u51FA)]"}, { "optionXT" , " [-XT (\u5982\u679C\u53EF\u80FD, \u4F7F\u7528 translet \u8FDB\u884C\u8F6C\u6362)]"}, { "diagTiming"," --------- \u901A\u8FC7{1}\u8F6C\u6362{0}\u82B1\u8D39\u4E86 {2} \u6BEB\u79D2\u7684\u65F6\u95F4" }, { "recursionTooDeep","\u6A21\u677F\u5D4C\u5957\u592A\u6DF1\u3002\u5D4C\u5957 = {0}, \u6A21\u677F{1} {2}" }, { "nameIs", "\u540D\u79F0\u4E3A" }, { "matchPatternIs", "\u5339\u914D\u6A21\u5F0F\u4E3A" } }; } // ================= INFRASTRUCTURE ====================== /** String for use when a bad error code was encountered. */ public static final String BAD_CODE = "BAD_CODE"; /** String for use when formatting of the error string failed. */ public static final String FORMAT_FAILED = "FORMAT_FAILED"; /** General error string. */ public static final String ERROR_STRING = "#error"; /** String to prepend to error messages. */ public static final String ERROR_HEADER = "Error: "; /** String to prepend to warning messages. */ public static final String WARNING_HEADER = "Warning: "; /** String to specify the XSLT module. */ public static final String XSL_HEADER = "XSLT "; /** String to specify the XML parser module. */ public static final String XML_HEADER = "XML "; /** I don't think this is used any more. * @deprecated */ public static final String QUERY_HEADER = "PATTERN "; }
gpl-2.0
zapster/graal-core
graal/com.oracle.graal.microbenchmarks/src/com/oracle/graal/microbenchmarks/graal/NodeBenchmark.java
6186
/* * Copyright (c) 2015, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.microbenchmarks.graal; import java.util.HashMap; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; import com.oracle.graal.graph.Node; import com.oracle.graal.graph.NodeBitMap; import com.oracle.graal.microbenchmarks.graal.util.GraalState; import com.oracle.graal.microbenchmarks.graal.util.MethodSpec; import com.oracle.graal.microbenchmarks.graal.util.NodesState; import com.oracle.graal.microbenchmarks.graal.util.NodesState.NodePair; import com.oracle.graal.nodes.ConstantNode; import com.oracle.graal.nodes.calc.AddNode; import com.oracle.graal.nodes.util.GraphUtil; public class NodeBenchmark extends GraalBenchmark { @MethodSpec(declaringClass = String.class, name = "equals") public static class StringEquals extends NodesState { } @Benchmark @Warmup(iterations = 20) public int getNodeClass(StringEquals s) { int sum = 0; for (Node n : s.nodes) { sum += n.getNodeClass().iterableId(); } return sum; } @Benchmark public void dataEquals(StringEquals s, Blackhole bh) { for (Node n : s.nodes) { bh.consume(n.getNodeClass().dataEquals(n, n)); } } @Benchmark public void replaceFirstInput(StringEquals s, Blackhole bh) { for (Node n : s.nodes) { bh.consume(n.getNodeClass().replaceFirstInput(n, n, n)); } } @Benchmark public void inputsEquals(StringEquals s, Blackhole bh) { for (Node n : s.nodes) { bh.consume(n.getNodeClass().equalInputs(n, n)); } } @Benchmark public void inputs(StringEquals s, Blackhole bh) { for (Node n : s.nodes) { for (Node input : n.inputs()) { bh.consume(input); } } } @Benchmark public void acceptInputs(StringEquals s, Blackhole bh) { Node.EdgeVisitor consumer = new Node.EdgeVisitor() { @Override public Node apply(Node t, Node u) { bh.consume(u); return u; } }; for (Node n : s.nodes) { n.applyInputs(consumer); } } @Benchmark public void createAndDeleteAdd(StringEquals s, Blackhole bh) { AddNode addNode = new AddNode(ConstantNode.forInt(40), ConstantNode.forInt(2)); s.graph.addOrUniqueWithInputs(addNode); GraphUtil.killWithUnusedFloatingInputs(addNode); bh.consume(addNode); } @Benchmark public void createAndDeleteConstant(StringEquals s, Blackhole bh) { ConstantNode constantNode = ConstantNode.forInt(42); s.graph.addOrUnique(constantNode); GraphUtil.killWithUnusedFloatingInputs(constantNode); bh.consume(constantNode); } @Benchmark public void usages(StringEquals s, Blackhole bh) { for (Node n : s.nodes) { for (Node input : n.usages()) { bh.consume(input); } } } @Benchmark @Warmup(iterations = 20) public void nodeBitmap(StringEquals s, @SuppressWarnings("unused") GraalState g) { NodeBitMap bitMap = s.graph.createNodeBitMap(); for (Node node : s.graph.getNodes()) { if (!bitMap.isMarked(node)) { bitMap.mark(node); } } for (Node node : s.graph.getNodes()) { if (bitMap.isMarked(node)) { bitMap.clear(node); } } } @MethodSpec(declaringClass = HashMap.class, name = "computeIfAbsent") public static class HashMapComputeIfAbsent extends NodesState { } // Checkstyle: stop method name check @Benchmark @Warmup(iterations = 20) public int valueEquals_STRING_EQUALS(StringEquals s) { int result = 0; for (NodePair np : s.valueEqualsNodePairs) { if (np.n1.valueEquals(np.n2)) { result += 27; } else { result += 31; } } return result; } @Benchmark @Warmup(iterations = 20) public int valueEquals_HASHMAP_COMPUTE_IF_ABSENT(HashMapComputeIfAbsent s) { int result = 0; for (NodePair np : s.valueEqualsNodePairs) { if (np.n1.valueEquals(np.n2)) { result += 27; } else { result += 31; } } return result; } @Benchmark @Warmup(iterations = 20) public int valueNumberLeaf_HASHMAP_COMPUTE_IF_ABSENT(HashMapComputeIfAbsent s) { int result = 0; for (Node n : s.valueNumberableLeafNodes) { result += (n.getNodeClass().isLeafNode() ? 1 : 0); } return result; } @Benchmark @Warmup(iterations = 20) public int valueNumberLeaf_STRING_EQUALS(StringEquals s) { int result = 0; for (Node n : s.valueNumberableLeafNodes) { result += (n.getNodeClass().isLeafNode() ? 1 : 0); } return result; } // Checkstyle: resume method name check }
gpl-2.0
blazegraph/database
bigdata-core/bigdata/src/java/com/bigdata/btree/keys/ASCIIDecoderUtility.java
2697
/* Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved. Contact: SYSTAP, LLC DBA Blazegraph 2501 Calvert ST NW #106 Washington, DC 20008 licenses@blazegraph.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Created on Apr 22, 2009 */ package com.bigdata.btree.keys; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Utility reads unsigned byte[] keys from stdin and writes their decoded ASCII * values on stdout. This may be used to decode the keys for an index whose keys * are encoded ASCII strings. It CAN NOT be used to decode Unicode sort keys. * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id$ */ public class ASCIIDecoderUtility { /** * */ public ASCIIDecoderUtility() { } /** * Reads decimal representations of unsigned bytes representing ASCII * characters from stdin, writing their ASCII values on stdout. The * following characters are stripped from the input: <code>[]</code>. The * values may be delimited by commas or whitespace or both. * * @param args * ignored. * * @throws IOException */ public static void main(String[] args) throws IOException { final BufferedReader r = new BufferedReader(new InputStreamReader( System.in)); String s; while ((s = r.readLine()) != null) { final String[] a = s.split("[\\s,\\[\\]]+"); final byte[] b = new byte[a.length]; int len = 0; for (String t : a) { if (t.length() == 0) continue; final int i = Integer.parseInt(t); b[len++] = (byte) i; } final String ascii = KeyBuilder .decodeASCII(b, 0/*off*/, len/*len*/); System.out.println(ascii); } } }
gpl-2.0
vvdeng/vportal
src/com/paipai/verticalframework/ui/component/printer/CalendarPrinter.java
2858
/** * Copyright (C) 1998-2008 TENCENT Inc.All Rights Reserved. * * FileName??CalendarPrinter.java * * Description?? * History?? * ?汾?? ???? ???? ????????????? * 1.0 bevisdeng 2010-10-22 ???? */ package com.paipai.verticalframework.ui.component.printer; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.jsp.JspContext; import javax.servlet.jsp.tagext.JspFragment; import com.paipai.verticalframework.ui.constant.Attr; import com.paipai.verticalframework.ui.constant.Tag; import com.paipai.verticalframework.ui.printer.DefaultXhtmlPrinter; public class CalendarPrinter extends DefaultXhtmlPrinter { public static final String DEFAULT_FORMAT = "%y-%m-%d"; private static SimpleDateFormat sdf = new SimpleDateFormat(); public CalendarPrinter(JspFragment jspFragment, JspContext jspContext) { super(jspFragment, jspContext); } /** * ????????????????????????? * * @param id : * ????????id * @param name * :??????????? ??????????????????????? * @return format java?????? */ public void printCalendar(String id, String name, String format, Object value, boolean readonly) { printHelper.startElement(Tag.INPUT); printHelper.attribute(Attr.ID, id); printHelper.attribute(Attr.TYPE, "text"); printHelper.attribute(Attr.NAME, name); if (value == null) { value = new Date(); } if (value instanceof String) { printHelper.attribute(Attr.VALUE, value.toString()); } else if (value instanceof Date) { if (format == null || format.trim().length() == 0) { format = "yyyy-MM-dd"; } sdf.applyPattern(format); printHelper.attribute(Attr.VALUE, sdf.format(value)); } if (readonly) { printHelper.attribute(Attr.READONLY); } printHelper.endElement(Tag.INPUT); // ????PP.vfui.calendar()???????????????; printHelper .script("var sopt={input: '#" + id + "',action:'#" + id + "',useDeltaYear:true,format:'" + transformFormat(format) + "',time:" + useTime(format) + ",zeroHour:true,deltaYear:1};PP.vfui.component.calendar(sopt);"); flushTag(); } /** * ??java??????????calendar??Js?????? * * @param javaFormat * :java?????? * @return calendar?????????????? */ private static String transformFormat(String javaFormat) { if (javaFormat == null || javaFormat.trim().length() == 0) { return DEFAULT_FORMAT; } return javaFormat.replaceAll("[sSz]", "").replace("yyyy", "%y") .replace("yy", "%y").replace("MM", "%m").replace("dd", "%d") .replace("HH", "%h").replace("mm", "%M"); } private static boolean useTime(String javaFormat) { return (javaFormat != null && (javaFormat.contains("HH") || javaFormat .contains("mm"))); } }
gpl-2.0
elkafoury/dguitar
src/dguitar/adaptors/song/impl/RepeatedSongPhraseImpl.java
1949
/* * Created on Mar 1, 2005 */ package dguitar.adaptors.song.impl; import dguitar.adaptors.song.RepeatedSongPhrase; import dguitar.adaptors.song.SongMeasure; import dguitar.adaptors.song.SongPhrase; /** * Implementation of RepeatedSongPhrase * @author crnash */ public class RepeatedSongPhraseImpl implements RepeatedSongPhrase { SongPhrase phrase; int repeatCount; public RepeatedSongPhraseImpl(SongPhrase phrase,int repeatCount) { this.phrase=phrase; this.repeatCount=repeatCount; } /* (non-Javadoc) * @see Song.SongPhrase#getScoreMeasureCount() */ public int getScoreMeasureCount() { return phrase.getScoreMeasureCount(); } /* (non-Javadoc) * @see Song.SongPhrase#getScoreMeasure(int) */ public SongMeasure getScoreMeasure(int measure) { int sc=phrase.getScoreMeasureCount(); if((measure<0)||(measure>=sc)) throw new ArrayIndexOutOfBoundsException(); return phrase.getScoreMeasure(measure); } /* (non-Javadoc) * @see Song.SongPhrase#getPerformanceMeasureCount() */ public int getPerformanceMeasureCount() { return (repeatCount+1)*phrase.getPerformanceMeasureCount(); } /* (non-Javadoc) * @see Song.SongPhrase#getPerformanceMeasure(int) */ public SongMeasure getPerformanceMeasure(int measure) { int pc=phrase.getPerformanceMeasureCount(); if((measure<0)||(measure>=(repeatCount+1)*pc)) throw new ArrayIndexOutOfBoundsException(); return phrase.getPerformanceMeasure(measure%pc); } /** * @return Returns the phrase. */ public SongPhrase getPhrase() { return phrase; } /** * @return Returns the repeatCount. */ public int getRepeatCount() { return repeatCount; } }
gpl-2.0
sannysanoff/CodenameOne
vm/ByteCodeTranslator/src/com/codename1/tools/translator/bytecodes/MultiArray.java
6630
/* * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Codename One designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Codename One through http://www.codenameone.com/ if you * need additional information or have any questions. */ package com.codename1.tools.translator.bytecodes; import com.codename1.tools.translator.ByteCodeClass; import java.util.List; import org.objectweb.asm.Opcodes; /** * * @author Shai Almog */ public class MultiArray extends Instruction { private String desc; private int dims; private String actualType; public MultiArray(String desc, int dims) { super(Opcodes.MULTIANEWARRAY); this.desc = desc; this.dims = dims; } @Override public void addDependencies(List<String> dependencyList) { String t = desc.replace('.', '_').replace('/', '_').replace('$', '_'); t = unarray(t); actualType = t; if(t != null && !dependencyList.contains(t)) { dependencyList.add(t); } if(actualType == null) { // primitive array switch(desc.charAt(desc.length() - 1)) { case 'I': actualType = "JAVA_INT"; break; case 'J': actualType = "JAVA_LONG"; break; case 'B': actualType = "JAVA_BYTE"; break; case 'S': actualType = "JAVA_SHORT"; break; case 'F': actualType = "JAVA_FLOAT"; break; case 'D': actualType = "JAVA_DOUBLE"; break; case 'Z': actualType = "JAVA_BOOLEAN"; break; case 'C': actualType = "JAVA_CHAR"; break; } } ByteCodeClass.addArrayType(actualType, dims); } @Override public void appendInstruction(StringBuilder b, List<Instruction> l) { int actualDim = dims; /*int offset = 0; offset = desc.indexOf('[', offset); while(offset > -1) { actualDim++; offset = desc.indexOf('[', offset); }*/ switch(actualDim) { case 2: b.append(" PUSH_OBJ(alloc2DArray(threadStateData, (*(--SP)).data.i, "); switch(dims) { case 1: b.append("-1"); break; case 2: b.append("(*(--SP)).data.i"); break; } b.append(", &class_array2__"); b.append(actualType); b.append(", &class_array1__"); b.append(actualType); b.append(", sizeof("); if(actualType.startsWith("JAVA_")) { b.append(actualType); } else { b.append("JAVA_OBJECT"); } b.append("))); /* MULTIANEWARRAY */\n"); break; case 3: b.append(" PUSH_OBJ(alloc3DArray(threadStateData, POP_INT(), "); switch(dims) { case 1: b.append("-1, -1"); break; case 2: b.append("POP_INT(), -1"); break; case 3: b.append("POP_INT(), POP_INT()"); break; } b.append(", &class_array3__"); b.append(actualType); b.append(", &class_array2__"); b.append(actualType); b.append(", &class_array1__"); b.append(actualType); b.append(", sizeof("); if(actualType.startsWith("JAVA_")) { b.append(actualType); } else { b.append("JAVA_OBJECT"); } b.append("))); /* MULTIANEWARRAY */\n"); break; case 4: b.append(" PUSH_OBJ(alloc4DArray(threadStateData, POP_INT(), "); switch(dims) { case 1: b.append("-1, -1, -1"); break; case 2: b.append("POP_INT(), -1, -1"); break; case 3: b.append("POP_INT(), POP_INT(), -1"); break; case 4: b.append("POP_INT(), POP_INT(), POP_INT()"); break; } b.append(", &class_array4__"); b.append(actualType); b.append(", &class_array3__"); b.append(actualType); b.append(", &class_array2__"); b.append(actualType); b.append(", &class_array1__"); b.append(actualType); b.append(", sizeof("); if(actualType.startsWith("JAVA_")) { b.append(actualType); } else { b.append("JAVA_OBJECT"); } b.append("))); /* MULTIANEWARRAY */\n"); break; } } }
gpl-2.0
huangfangyi/FanXin-based-HuanXin
app/src/main/java/com/htmessage/fanxinht/acitivity/main/conversation/ConversationAdapter.java
9906
package com.htmessage.fanxinht.acitivity.main.conversation; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.htmessage.fanxinht.R; import com.htmessage.fanxinht.acitivity.chat.group.GroupNoticeMessageUtils; import com.htmessage.fanxinht.domain.User; import com.htmessage.fanxinht.acitivity.chat.weight.emojicon.SmileUtils; import com.htmessage.fanxinht.manager.ContactsManager; import com.htmessage.fanxinht.utils.DateUtils; import com.htmessage.sdk.ChatType; import com.htmessage.sdk.client.HTClient; import com.htmessage.sdk.model.HTConversation; import com.htmessage.sdk.model.HTGroup; import com.htmessage.sdk.model.HTMessage; import com.htmessage.sdk.model.HTMessageTextBody; import java.util.Date; import java.util.List; public class ConversationAdapter extends BaseAdapter { private List<HTConversation> htConversations; private Context context; public ConversationAdapter(Context context, List<HTConversation> htConversations) { this.context = context; this.htConversations = htConversations; } @Override public int getCount() { return htConversations.size(); } @Override public HTConversation getItem(int position) { return htConversations.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_conversation_single, parent, false); } ViewHolder holder = (ViewHolder) convertView.getTag(); if (holder == null) { holder = new ViewHolder(); holder.tv_name = (TextView) convertView.findViewById(R.id.name); holder.tv_content = (TextView) convertView.findViewById(R.id.message); holder.tv_time = (TextView) convertView.findViewById(R.id.time); holder.tv_unread = (TextView) convertView.findViewById(R.id.unread_msg_number); holder.ivAvatar = (ImageView) convertView.findViewById(R.id.avatar); holder.tv_group_tag=(TextView) convertView.findViewById(R.id.tv_group_tag); holder.re_main=(RelativeLayout) convertView.findViewById(R.id.re_main); convertView.setTag(holder); } HTConversation htConversation = getItem(position); ChatType chatType = htConversation.getChatType(); HTMessage htMessage = null; List<HTMessage> messages = htConversation.getAllMessages(); if (messages.size() > 0) { htMessage = htConversation.getLastMessage(); } String userId = htConversation.getUserId(); if (chatType == ChatType.groupChat) { holder.tv_name.setMaxLines(1); holder.tv_name.setMaxEms(10); holder.tv_name.setEllipsize(TextUtils.TruncateAt.END); HTGroup htGroup = HTClient.getInstance().groupManager().getGroup(userId); if (htGroup != null) { holder.tv_name.setText(htGroup.getGroupName()); Glide.with(context).load(htGroup.getImgUrl()).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.default_group).into(holder.ivAvatar); }else { //如果当前群还未获取到, if(htMessage!=null&&htMessage.getIntAttribute("action",0)==2000){ String groupName=htMessage.getStringAttribute("groupName"); if(!TextUtils.isEmpty(groupName)){ holder.tv_name.setText(groupName); } } } holder.tv_group_tag.setVisibility(View.VISIBLE); } else { User user = ContactsManager.getInstance().getContactList().get(userId); holder.tv_group_tag.setVisibility(View.INVISIBLE); if (user != null) { holder.tv_name.setText(user.getNick()); Glide.with(context).load(user.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.default_avatar).into(holder.ivAvatar); } else { holder.tv_name.setText(userId); Glide.with(context).load(R.drawable.default_avatar).into(holder.ivAvatar); } } if (htConversation.getUnReadCount() > 0) { // show unread message count holder.tv_unread.setText(String.valueOf(htConversation.getUnReadCount())); holder.tv_unread.setVisibility(View.VISIBLE); } else { holder.tv_unread.setVisibility(View.INVISIBLE); } if (htMessage != null) { holder.tv_content.setText(SmileUtils.getSmiledText(context, getContent(htMessage)), TextView.BufferType.SPANNABLE); holder.tv_time.setText(DateUtils.getTimestampString(new Date(htMessage.getTime()))); }else{ holder.tv_content.setText(""); holder.tv_time.setText(DateUtils.getTimestampString(new Date(htConversation.getTime()))); } if(htConversation.getTopTimestamp()!=0){ holder.re_main.setBackgroundResource(R.drawable.list_item_bg_gray); }else{ holder.re_main.setBackgroundResource(R.drawable.list_item_bg_white); } return convertView; } private static class ViewHolder { /** * 和谁的聊天记录 */ TextView tv_name; /** * 消息未读数 */ TextView tv_unread; /** * 最后一条消息的内容 */ TextView tv_content; /** * 最后一条消息的时间 */ TextView tv_time; ImageView ivAvatar; //群组的标识 TextView tv_group_tag; RelativeLayout re_main; } protected final static String[] msgs = {"发来一条消息", "[图片消息]", "[语音消息]", "[位置消息]", "[视频消息]", "[文件消息]", "%1个联系人发来%2条消息" }; private String getContent(HTMessage message) { int action=message.getIntAttribute("action",0); if(action>1999&&action<2005||action==3000){ return GroupNoticeMessageUtils.getGroupNoticeContent(message); } // HTConversation htConversation = ConversationManager.getInstance().getConversation(message.getFrom()); String notifyText = ""; if (message.getType() == null) { return ""; } switch (message.getType()) { case TEXT: HTMessageTextBody textBody = (HTMessageTextBody) message.getBody(); String content = textBody.getContent(); if (content != null) { notifyText += content; } else { notifyText += msgs[0]; } break; case IMAGE: notifyText += msgs[1]; break; case VOICE: notifyText += msgs[2]; break; case LOCATION: notifyText += msgs[3]; break; case VIDEO: notifyText += msgs[4]; break; case FILE: notifyText += msgs[5]; break; } return notifyText; } // /** // * 根据消息内容和消息类型获取消息内容提示 // * // * @param message // * @param context // * @return // */ // private String getMessageDigest(HTMessage message, Context context) { // String digest = ""; // switch (message.getType()) { // case LOCATION: // 位置消息 // if (message.getDirect() == HTMessage.Direct.RECEIVE) { // // digest = getStrng(context, R.string.location_recv); // digest = String.format(digest, message.getFrom()); // return digest; // } else { // // digest = EasyUtils.getAppResourceString(context, // // "location_prefix"); // digest = getStrng(context, R.string.location_prefix); // } // break; // case IMAGE: // 图片消息 // // digest = getStrng(context, R.string.picture); // // break; // case VOICE:// 语音消息 // digest = getStrng(context, R.string.voice); // break; // case VIDEO: // 视频消息 // digest = getStrng(context, R.string.video); // break; // case TXT: // 文本消息 // if (!message.getBooleanAttribute( // Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) { // TextMessageBody txtBody = (TextMessageBody) message.getBody(); // digest = txtBody.getMessage(); // } else { // TextMessageBody txtBody = (TextMessageBody) message.getBody(); // digest = getStrng(context, R.string.voice_call) // + txtBody.getMessage(); // } // break; // case FILE: // 普通文件消息 // digest = getStrng(context, R.string.file); // break; // default: // System.err.println("error, unknow type"); // return ""; // } // // return digest; // } String getStrng(Context context, int resId) { return context.getResources().getString(resId); } }
gpl-2.0
nicolabeghin/hibersap-hybris
src/org/hibersap/execution/jco/JCoContext.java
3392
/* * Copyright (c) 2008-2014 akquinet tech@spree GmbH * * This file is part of Hibersap. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this software except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hibersap.execution.jco; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibersap.HibersapException; import org.hibersap.configuration.xml.Property; import org.hibersap.configuration.xml.SessionManagerConfig; import org.hibersap.execution.Connection; import org.hibersap.session.Context; import java.util.List; import java.util.Properties; /* * Uses the SAP Java Connector to connect to SAP. * * @author Carsten Erker */ public class JCoContext implements Context { private static final Log LOG = LogFactory.getLog( JCoContext.class ); private static final String JCO_PROPERTIES_PREFIX = "jco."; private String destinationName; /* * {@inheritDoc} */ public void configure( final SessionManagerConfig config ) throws HibersapException { LOG.trace( "configure JCo context" ); final Properties jcoProperties = new Properties(); List<Property> properties = config.getProperties(); for ( Property property : properties ) { String name = property.getName(); if ( name.startsWith( JCO_PROPERTIES_PREFIX ) ) { jcoProperties.put( name, property.getValue() ); } } destinationName = config.getName(); if ( StringUtils.isEmpty( destinationName ) ) { throw new HibersapException( "A session manager name must be specified in Hibersap configuration" ); } JCoEnvironment.registerDestination( destinationName, jcoProperties ); } /* * {@inheritDoc} */ public void close() { JCoEnvironment.unregisterDestination( destinationName ); destinationName = null; } /* * {@inheritDoc} */ public Connection getConnection() { return new JCoConnection( destinationName ); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ( ( destinationName == null ) ? 0 : destinationName.hashCode() ); return result; } @Override public boolean equals( final Object obj ) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } JCoContext other = (JCoContext) obj; if ( destinationName == null ) { if ( other.destinationName != null ) { return false; } } else if ( !destinationName.equals( other.destinationName ) ) { return false; } return true; } }
gpl-2.0
mixaceh/openyu-socklet.j
openyu-socklet-core/src/main/java/org/openyu/socklet/message/service/ProtocolService.java
3219
package org.openyu.socklet.message.service; import java.io.Serializable; import java.util.List; import org.openyu.commons.security.SecurityType; import org.openyu.commons.service.BaseService; import org.openyu.commons.util.ChecksumType; import org.openyu.commons.util.CompressType; import org.openyu.socklet.message.vo.CategoryType; import org.openyu.socklet.message.vo.HeadType; import org.openyu.socklet.message.vo.Message; import org.openyu.socklet.message.vo.Packet; /** * 協定服務 * * 組成/反組byte[] */ public interface ProtocolService extends BaseService { /** * 是否檢查碼 * * @return */ boolean isChecksum(); void setChecksum(boolean checksum); /** * 檢查碼類別 * * @return */ ChecksumType getChecksumType(); void setChecksumType(ChecksumType checksumType); /** * 檢查碼key * * @return */ String getChecksumKey(); void setChecksumKey(String checksumKey); /** * 是否加密 * * @return */ boolean isSecurity(); void setSecurity(boolean security); /** * 加密類別 * * @return */ SecurityType getSecurityType(); void setSecurityType(SecurityType securityType); /** * 加密key * * @return */ String getSecurityKey(); void setSecurityKey(String securityKey); /** * 是否壓縮 * * @return */ boolean isCompress(); void setCompress(boolean compress); /** * 壓縮類別 * * @return */ CompressType getCompressType(); void setCompressType(CompressType compressType); // ------------------------------------------ // handshake // ------------------------------------------ /** * 握手協定,組成byte[] * * @param categoryType * @param authKey * @param sender * @return */ byte[] handshake(CategoryType categoryType, byte[] authKey, String sender); /** * 反握手協定,反組byte[] * * @param values * @return */ Message dehandshake(byte[] values); // ------------------------------------------ // assemble // ------------------------------------------ /** * 訊息協定,組成byte[] * * @param message * @return */ byte[] assemble(Message message); /** * 反訊息協定,反組byte[] * * @param values * @param moduleTypeClass * @param messageTypeClass * @return */ <T extends Enum<T>, U extends Enum<U>> List<Message> disassemble( byte[] values, Class<T> moduleTypeClass, Class<U> messageTypeClass); // ------------------------------------------ // 2014/12/15 // ------------------------------------------ byte[] encode(HeadType headType); byte[] encode(HeadType headType, boolean body); byte[] encode(HeadType headType, char body); byte[] encode(HeadType headType, String body); byte[] encode(HeadType headType, String body, String charsetName); byte[] encode(HeadType headType, byte body); byte[] encode(HeadType headType, short body); byte[] encode(HeadType headType, int body); byte[] encode(HeadType headType, long body); byte[] encode(HeadType headType, float body); byte[] encode(HeadType headType, double body); byte[] encode(HeadType headType, byte[] body); byte[] encode(HeadType headType, Serializable body); Packet<byte[]> decode(byte[] values); }
gpl-2.0
akunft/fastr
com.oracle.truffle.r.test/src/com/oracle/truffle/r/test/library/stats/TestExternal_R_get_prim_name.java
1542
/* * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.r.test.library.stats; import org.junit.Test; import com.oracle.truffle.r.test.TestBase; public class TestExternal_R_get_prim_name extends TestBase { @Test public void testGetPrimName() { assertEval(".Call(methods:::C_R_get_primname, any)"); assertEval(".Call(methods:::C_R_get_primname, \"abc\")"); assertEval(".Call(methods:::C_R_get_primname, 1)"); assertEval(".Call(methods:::C_R_get_primname, NULL)"); } }
gpl-2.0
tharindum/opennms_dashboard
integrations/opennms-rws/src/main/java/org/opennms/netmgt/config/RWSConfigManager.java
7864
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.config; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.opennms.core.utils.LogUtils; import org.opennms.core.xml.CastorUtils; import org.opennms.netmgt.config.rws.BaseUrl; import org.opennms.netmgt.config.rws.RwsConfiguration; import org.opennms.netmgt.config.rws.StandbyUrl; import org.opennms.rancid.ConnectionProperties; /** * <p>Abstract RWSConfigManager class.</p> * * @author <a href="mailto:antonio@opennms.it">Antonio Russo</a> * @author <a href="mailto:brozow@openms.org">Mathew Brozowski</a> * @author <a href="mailto:david@opennms.org">David Hustace</a> */ abstract public class RWSConfigManager implements RWSConfig { private final ReadWriteLock m_globalLock = new ReentrantReadWriteLock(); private final Lock m_readLock = m_globalLock.readLock(); private final Lock m_writeLock = m_globalLock.writeLock(); private int m_cursor = 0; private RwsConfiguration m_config; /** * <p>Constructor for RWSConfigManager.</p> */ public RWSConfigManager() { } /** * <p>Constructor for RWSConfigManager.</p> * * @param stream a {@link java.io.InputStream} object. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. * @throws java.io.IOException if any. */ public RWSConfigManager(final InputStream stream) throws MarshalException, ValidationException, IOException { reloadXML(stream); } public Lock getReadLock() { return m_readLock; } public Lock getWriteLock() { return m_writeLock; } /** * <p>getBase</p> * * @return a {@link org.opennms.rancid.ConnectionProperties} object. */ public ConnectionProperties getBase() { getReadLock().lock(); try { LogUtils.debugf(this, "Connections used: %s%s", getBaseUrl().getServer_url(), getBaseUrl().getDirectory()); LogUtils.debugf(this, "RWS timeout(sec): %d", getBaseUrl().getTimeout()); if (getBaseUrl().getUsername() == null) { return new ConnectionProperties(getBaseUrl().getServer_url(),getBaseUrl().getDirectory(),getBaseUrl().getTimeout()); } String password = ""; if (getBaseUrl().getPassword() != null) password = getBaseUrl().getPassword(); return new ConnectionProperties(getBaseUrl().getUsername(),password,getBaseUrl().getServer_url(),getBaseUrl().getDirectory(),getBaseUrl().getTimeout()); } finally { getReadLock().unlock(); } } /** * <p>getNextStandBy</p> * * @return a {@link org.opennms.rancid.ConnectionProperties} object. */ public ConnectionProperties getNextStandBy() { if (! hasStandbyUrl()) return null; getReadLock().lock(); try { final StandbyUrl standByUrl = getNextStandbyUrl(); LogUtils.debugf(this, "Connections used: %s%s", standByUrl.getServer_url(), standByUrl.getDirectory()); LogUtils.debugf(this, "RWS timeout(sec): %d", standByUrl.getTimeout()); if (standByUrl.getUsername() == null) { return new ConnectionProperties(standByUrl.getServer_url(),standByUrl.getDirectory(),standByUrl.getTimeout()); } String password = ""; if (standByUrl.getPassword() != null) { password = standByUrl.getPassword(); } return new ConnectionProperties(standByUrl.getUsername(),password,standByUrl.getServer_url(),standByUrl.getDirectory(),standByUrl.getTimeout()); } finally { getReadLock().unlock(); } } /** * <p>getStandBy</p> * * @return an array of {@link org.opennms.rancid.ConnectionProperties} objects. */ public ConnectionProperties[] getStandBy() { return null; } /** * <p>getBaseUrl</p> * * @return a {@link org.opennms.netmgt.config.rws.BaseUrl} object. */ public BaseUrl getBaseUrl() { getReadLock().lock(); try { return m_config.getBaseUrl(); } finally { getReadLock().unlock(); } } /** * <p>getStanbyUrls</p> * * @return an array of {@link org.opennms.netmgt.config.rws.StandbyUrl} objects. */ public StandbyUrl[] getStanbyUrls() { getReadLock().lock(); try { return m_config.getStandbyUrl(); } finally { getReadLock().unlock(); } } /** * <p>getNextStandbyUrl</p> * * @return a {@link org.opennms.netmgt.config.rws.StandbyUrl} object. */ public StandbyUrl getNextStandbyUrl() { getReadLock().lock(); try { StandbyUrl standbyUrl = null; if (hasStandbyUrl()) { if (m_cursor == m_config.getStandbyUrlCount()) { m_cursor = 0; } standbyUrl = m_config.getStandbyUrl(m_cursor++); } return standbyUrl; } finally { getReadLock().unlock(); } } /** * <p>hasStandbyUrl</p> * * @return a boolean. */ public boolean hasStandbyUrl() { getReadLock().lock(); try { return (m_config.getStandbyUrlCount() > 0); } finally { getReadLock().unlock(); } } /** * <p>reloadXML</p> * * @param stream a {@link java.io.InputStream} object. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. * @throws java.io.IOException if any. */ protected void reloadXML(final InputStream stream) throws MarshalException, ValidationException, IOException { getWriteLock().lock(); try { m_config = CastorUtils.unmarshal(RwsConfiguration.class, stream); } finally { getWriteLock().unlock(); } } /** * Return the poller configuration object. * * @return a {@link org.opennms.netmgt.config.rws.RwsConfiguration} object. */ public RwsConfiguration getConfiguration() { getReadLock().lock(); try { return m_config; } finally { getReadLock().unlock(); } } }
gpl-2.0
LiconFromFramgia/FirebaseAndroid
app/src/main/java/com/framgia/demo/ChatApplication.java
306
package com.framgia.demo; import android.app.Application; import com.firebase.client.Firebase; /** * Created by FRAMGIA\khairul.alam.licon on 4/11/15. */ public class ChatApplication extends Application { @Override public void onCreate() { super.onCreate(); Firebase.setAndroidContext(this); } }
gpl-2.0
dkfellows/stendhal
src/games/stendhal/server/script/MoveAndStrengthenOnlinePlayers.java
6174
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.script; import games.stendhal.common.Direction; import games.stendhal.common.Rand; import games.stendhal.server.core.engine.PlayerList; import games.stendhal.server.core.engine.SingletonRepository; import games.stendhal.server.core.engine.StendhalRPWorld; import games.stendhal.server.core.engine.StendhalRPZone; import games.stendhal.server.core.engine.Task; import games.stendhal.server.core.events.TurnListener; import games.stendhal.server.core.scripting.ScriptImpl; import games.stendhal.server.entity.item.Item; import games.stendhal.server.entity.item.StackableItem; import games.stendhal.server.entity.player.Player; import java.util.ArrayList; import java.util.Collection; import java.util.List; import marauroa.common.game.IRPZone; /** * Script to make all players stronger and immune to poison before randomly distributing them * over all zones of the running server * * @author madmetzger */ public class MoveAndStrengthenOnlinePlayers extends ScriptImpl { private List<StendhalRPZone> zones = new ArrayList<StendhalRPZone>(); /** * Create the script and initialize the list of zones */ public MoveAndStrengthenOnlinePlayers() { StendhalRPWorld rpWorld = SingletonRepository.getRPWorld(); for (IRPZone irpZone : rpWorld) { StendhalRPZone irpZone2 = (StendhalRPZone) irpZone; if (!irpZone2.getName().startsWith("int")) { zones.add(irpZone2); } } } @Override public void execute(final Player admin, List<String> args) { Collection<Player> onlinePlayers = SingletonRepository.getRuleProcessor().getOnlinePlayers().getAllPlayers(); PlayerList pl = new PlayerList(); int packet = 1; for (Player p : onlinePlayers) { String zoneName = p.getZone().getName(); if ((zoneName != null) && (zoneName.equals("int_afterlife") || zoneName.equals("int_semos_guard_house"))) { pl.add(p); if(pl.getAllPlayers().size() == 5) { SingletonRepository.getTurnNotifier().notifyInTurns(packet, new MoveAndStrengthenPlayersTurnListener(pl, admin)); pl = new PlayerList(); packet += 1; } } } } private class MoveAndStrengthenPlayersTurnListener implements TurnListener { private final PlayerList playersToDealWith; private final Player admin; MoveAndStrengthenPlayersTurnListener(PlayerList pl, Player executor) { playersToDealWith = pl; admin = executor; } @Override public void onTurnReached(int currentTurn) { playersToDealWith.forAllPlayersExecute(new Task<Player>() { @Override public void execute(Player player) { equipPlayer(player); fillBag(player); player.setDefXP(999999999); player.addXP(999999999); StendhalRPZone zone = zones.get(Rand.rand(zones.size())); int x = Rand.rand(zone.getWidth() - 4) + 2; int y = Rand.rand(zone.getHeight() - 5) + 2; player.teleport(zone, x, y, Direction.DOWN, admin); } private void fillBag(Player player) { String[] items = {"leek", "porcini", "potion", "antidote", "beer", "minor potion", "home scroll", "ados city scroll", "empty scroll"}; for(String item : items) { StackableItem stackable = (StackableItem) SingletonRepository.getEntityManager().getItem(item); stackable.setQuantity(50); player.equipToInventoryOnly(stackable); } } private void equipPlayer(Player player) { StackableItem money = (StackableItem) SingletonRepository.getEntityManager().getItem("money"); money.setQuantity(5000); player.equipToInventoryOnly(money); StackableItem potions = (StackableItem) SingletonRepository.getEntityManager().getItem("greater potion"); potions.setQuantity(5000); player.equipToInventoryOnly(potions); if(!player.isEquipped("chaos dagger")) { Item first = (Item) player.getSlot("rhand").getFirst(); player.drop(first); Item dagger = SingletonRepository.getEntityManager().getItem("chaos dagger"); player.equip("rhand", dagger); } if(!player.isEquipped("chaos shield")) { Item first = (Item) player.getSlot("lhand").getFirst(); player.drop(first); Item shield = SingletonRepository.getEntityManager().getItem("chaos shield"); player.equip("lhand", shield); } if(!player.isEquipped("black helmet")) { Item first = (Item) player.getSlot("head").getFirst(); player.drop(first); Item helmet = SingletonRepository.getEntityManager().getItem("black helmet"); player.equip("head", helmet); } if(!player.isEquipped("elvish legs")) { Item first = (Item) player.getSlot("legs").getFirst(); player.drop(first); Item legs = SingletonRepository.getEntityManager().getItem("elvish legs"); player.equip("legs", legs); } if(!player.isEquipped("killer boots")) { Item first = (Item) player.getSlot("feet").getFirst(); player.drop(first); Item boots = SingletonRepository.getEntityManager().getItem("killer boots"); player.equip("feet", boots); } if(!player.isEquipped("green dragon cloak")) { Item first = (Item) player.getSlot("cloak").getFirst(); player.drop(first); Item cloak = SingletonRepository.getEntityManager().getItem("green dragon cloak"); player.equip("cloak", cloak); } } }); } } }
gpl-2.0
jbjonesjr/geoproponis
external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/attribute/draw/DrawObjectAttribute.java
2948
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.attribute.draw; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.pkg.OdfAttribute; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; /** * DOM implementation of OpenDocument attribute {@odf.attribute draw:object}. * */ public class DrawObjectAttribute extends OdfAttribute { public static final OdfName ATTRIBUTE_NAME = OdfName.newName(OdfDocumentNamespace.DRAW, "object"); /** * Create the instance of OpenDocument attribute {@odf.attribute draw:object}. * * @param ownerDocument The type is <code>OdfFileDom</code> */ public DrawObjectAttribute(OdfFileDom ownerDocument) { super(ownerDocument, ATTRIBUTE_NAME); } /** * Returns the attribute name. * * @return the <code>OdfName</code> for {@odf.attribute draw:object}. */ @Override public OdfName getOdfName() { return ATTRIBUTE_NAME; } /** * @return Returns the name of this attribute. */ @Override public String getName() { return ATTRIBUTE_NAME.getLocalName(); } /** * Returns the default value of {@odf.attribute draw:object}. * * @return the default value as <code>String</code> dependent of its element name * return <code>null</code> if the default value does not exist */ @Override public String getDefault() { return null; } /** * Default value indicator. As the attribute default value is dependent from its element, the attribute has only a default, when a parent element exists. * * @return <code>true</code> if {@odf.attribute draw:object} has an element parent * otherwise return <code>false</code> as undefined. */ @Override public boolean hasDefault() { return false; } /** * @return Returns whether this attribute is known to be of type ID (i.e. xml:id ?) */ @Override public boolean isId() { return false; } }
gpl-2.0
lamsfoundation/lams
3rdParty_sources/poi/org/apache/poi/poifs/filesystem/Ole10NativeException.java
1299
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.poifs.filesystem; public class Ole10NativeException extends Exception { public Ole10NativeException(String message) { super(message); } public Ole10NativeException(Throwable cause) { super(cause); } public Ole10NativeException(String message, Throwable cause) { super(message, cause); } }
gpl-2.0
ShuttleworthFoundation/tuxlab-Cookbook
libs/Jimi/src/com/sun/jimi/core/raster/imagetype/BytePaletteImage.java
1554
/* * Copyright (c) 1998 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information * of Sun Microsystems, Inc. ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * you entered into with Sun. */ package com.sun.jimi.core.raster.imagetype; import java.awt.image.*; import com.sun.jimi.core.*; import com.sun.jimi.core.raster.*; /** * "Image Type" class for 8bpp palette images. This class is used to check whether an image * is byte-based and uses a palette-based ColorModel (IndexColorModel). * @author Luke Gorrie * @version $Revision: 1.1.1.1 $ $Date: 1998/12/01 12:21:58 $ */ public class BytePaletteImage { public static boolean checkImage(JimiImage image) { return (image instanceof ByteRasterImage) && (((ByteRasterImage)image).getColorModel() instanceof IndexColorModel); } public static ByteRasterImage convertImage(JimiImage image, boolean dither) throws JimiException { JimiRasterImage rasterImage = Jimi.createRasterImage(image); if (checkImage(rasterImage)) { return (ByteRasterImage)rasterImage; } else { JimiImageColorReducer reducer = new JimiImageColorReducer(256); if (dither) { rasterImage = reducer.colorReduceFS(rasterImage); } else { rasterImage = reducer.colorReduce(rasterImage); } } } }
gpl-3.0
davidlad123/spine
spine/src/com/zphinx/spine/message/Messages.java
2648
/** * Resources.java * Copyright (C) 2008 Zphinx Software Solutions * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * THERE IS NO WARRANTY FOR THIS SOFTWARE, TO THE EXTENT PERMITTED BY * APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING WITH ZPHINX SOFTWARE SOLUTIONS * AND/OR OTHER PARTIES WHO PROVIDE THIS SOFTWARE "AS IS" WITHOUT WARRANTY * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM * IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF * ALL NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING * WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS * THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY * GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE * USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF * DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD * PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), * EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF * SUCH DAMAGES. * * For further information, please go to http://spine.zphinx.co.uk/ * **/ package com.zphinx.spine.message; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * Messages provides access to on the fly properties used within spine * * @author David Ladapo * @version 1.0 * <p> * * Copyright &copy; Zphinx Software Solutions * </p> */ public class Messages { /** * */ private static final String BUNDLE_NAME = "com.zphinx.spine.resources.UtilMessages";//$NON-NLS-1$ /** * */ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); /** * Public Constructor */ private Messages() { } public static String getString(String key) { // TODO Auto-generated method stub try{ return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e){ return '!' + key + '!'; } } }
gpl-3.0
cs3410/logisim-evolution
src/com/cburch/logisim/gui/generic/ProjectExplorer.java
12717
/******************************************************************************* * This file is part of logisim-evolution. * * logisim-evolution is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * logisim-evolution is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with logisim-evolution. If not, see <http://www.gnu.org/licenses/>. * * Original code by Carl Burch (http://www.cburch.com), 2011. * Subsequent modifications by : * + Haute École Spécialisée Bernoise * http://www.bfh.ch * + Haute École du paysage, d'ingénierie et d'architecture de Genève * http://hepia.hesge.ch/ * + Haute École d'Ingénierie et de Gestion du Canton de Vaud * http://www.heig-vd.ch/ * The project is currently maintained by : * + REDS Institute - HEIG-VD * Yverdon-les-Bains, Switzerland * http://reds.heig-vd.ch *******************************************************************************/ package com.cburch.logisim.gui.generic; /** * Code taken from Cornell's version of Logisim: * http://www.cs.cornell.edu/courses/cs3410/2015sp/ */ import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractAction; import javax.swing.ActionMap; import javax.swing.Icon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ToolTipManager; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeSelectionModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import com.cburch.logisim.circuit.Circuit; import com.cburch.logisim.circuit.SubcircuitFactory; import com.cburch.logisim.comp.ComponentDrawContext; import com.cburch.logisim.comp.ComponentFactory; import com.cburch.logisim.gui.main.Canvas; import com.cburch.logisim.prefs.AppPreferences; import com.cburch.logisim.proj.Project; import com.cburch.logisim.proj.ProjectEvent; import com.cburch.logisim.proj.ProjectListener; import com.cburch.logisim.tools.AddTool; import com.cburch.logisim.tools.Library; import com.cburch.logisim.tools.Tool; import com.cburch.logisim.util.LocaleListener; import com.cburch.logisim.util.LocaleManager; public class ProjectExplorer extends JTree implements LocaleListener { private class DeleteAction extends AbstractAction { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent event) { TreePath path = getSelectionPath(); if (listener != null && path != null && path.getPathCount() == 2) { listener.deleteRequested(new ProjectExplorerEvent(path)); } ProjectExplorer.this.requestFocus(); } } private class MyCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; @Override public java.awt.Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { java.awt.Component ret; ret = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); if (ret instanceof JComponent) { JComponent comp = (JComponent) ret; comp.setToolTipText(null); } if (value instanceof ProjectExplorerToolNode) { ProjectExplorerToolNode toolNode = (ProjectExplorerToolNode) value; Tool tool = toolNode.getValue(); if (ret instanceof JLabel) { ((JLabel) ret).setText(tool.getDisplayName()); ((JLabel) ret).setIcon(new ToolIcon(tool)); ((JLabel) ret).setToolTipText(tool.getDescription()); } } else if (value instanceof ProjectExplorerLibraryNode) { ProjectExplorerLibraryNode libNode = (ProjectExplorerLibraryNode) value; Library lib = libNode.getValue(); if (ret instanceof JLabel) { String text = lib.getDisplayName(); if (lib.isDirty()) text += DIRTY_MARKER; ((JLabel) ret).setText(text); } } return ret; } } private class MyListener implements MouseListener, TreeSelectionListener, ProjectListener, PropertyChangeListener { private void checkForPopup(MouseEvent e) { if (e.isPopupTrigger()) { TreePath path = getPathForLocation(e.getX(), e.getY()); if (path != null && listener != null) { JPopupMenu menu = listener .menuRequested(new ProjectExplorerEvent(path)); if (menu != null) { menu.show(ProjectExplorer.this, e.getX(), e.getY()); } } } } public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { TreePath path = getPathForLocation(e.getX(), e.getY()); if (path != null && listener != null) { listener.doubleClicked(new ProjectExplorerEvent(path)); } } } // // MouseListener methods // public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { ProjectExplorer.this.requestFocus(); checkForPopup(e); } public void mouseReleased(MouseEvent e) { checkForPopup(e); } // // project/library file/circuit listener methods // public void projectChanged(ProjectEvent event) { int act = event.getAction(); if (act == ProjectEvent.ACTION_SET_TOOL) { TreePath path = getSelectionPath(); if (path != null && path.getLastPathComponent() != event.getTool()) { clearSelection(); } } else if (act == ProjectEvent.ACTION_SET_CURRENT) { ProjectExplorer.this.repaint(); } } // // PropertyChangeListener methods // public void propertyChange(PropertyChangeEvent event) { if (AppPreferences.GATE_SHAPE.isSource(event)) { repaint(); } } // // TreeSelectionListener methods // public void valueChanged(TreeSelectionEvent e) { TreePath path = e.getNewLeadSelectionPath(); if (listener != null) { listener.selectionChanged(new ProjectExplorerEvent(path)); } } } private class MySelectionModel extends DefaultTreeSelectionModel { private static final long serialVersionUID = 1L; @Override public void addSelectionPath(TreePath path) { if (isPathValid(path)) super.addSelectionPath(path); } @Override public void addSelectionPaths(TreePath[] paths) { paths = getValidPaths(paths); if (paths != null) super.addSelectionPaths(paths); } private TreePath[] getValidPaths(TreePath[] paths) { int count = 0; for (int i = 0; i < paths.length; i++) { if (isPathValid(paths[i])) ++count; } if (count == 0) { return null; } else if (count == paths.length) { return paths; } else { TreePath[] ret = new TreePath[count]; int j = 0; for (int i = 0; i < paths.length; i++) { if (isPathValid(paths[i])) ret[j++] = paths[i]; } return ret; } } private boolean isPathValid(TreePath path) { if (path == null || path.getPathCount() > 3) return false; Object last = path.getLastPathComponent(); return last instanceof ProjectExplorerToolNode; } @Override public void setSelectionPath(TreePath path) { if (isPathValid(path)) super.setSelectionPath(path); } @Override public void setSelectionPaths(TreePath[] paths) { paths = getValidPaths(paths); if (paths != null) super.setSelectionPaths(paths); } } private class ToolIcon implements Icon { Tool tool; Circuit circ = null; ToolIcon(Tool tool) { this.tool = tool; if (tool instanceof AddTool) { ComponentFactory fact = ((AddTool) tool).getFactory(false); if (fact instanceof SubcircuitFactory) { circ = ((SubcircuitFactory) fact).getSubcircuit(); } } } public int getIconHeight() { return AppPreferences.getScaled(AppPreferences.BoxSize); } public int getIconWidth() { return AppPreferences.getScaled(AppPreferences.BoxSize); } public void paintIcon(java.awt.Component c, Graphics g, int x, int y) { // draw halo if appropriate if (tool == haloedTool && AppPreferences.ATTRIBUTE_HALO.getBoolean()) { g.setColor(Canvas.HALO_COLOR); g.fillRoundRect(x, y, AppPreferences.getScaled(AppPreferences.BoxSize), AppPreferences.getScaled(AppPreferences.BoxSize), AppPreferences.getScaled(AppPreferences.BoxSize>>1), AppPreferences.getScaled(AppPreferences.BoxSize>>1)); g.setColor(Color.BLACK); } // draw tool icon Graphics gIcon = g.create(); ComponentDrawContext context = new ComponentDrawContext( ProjectExplorer.this, null, null, g, gIcon); tool.paintIcon(context, x+AppPreferences.getScaled(AppPreferences.IconBorder), y+AppPreferences.getScaled(AppPreferences.IconBorder)); gIcon.dispose(); // draw magnifying glass if appropriate if (circ == proj.getCurrentCircuit()) { int tx = x + AppPreferences.getScaled(AppPreferences.BoxSize-7); int ty = y + AppPreferences.getScaled(AppPreferences.BoxSize-7); int[] xp = { tx - 1, x + AppPreferences.getScaled(AppPreferences.BoxSize-2), x + AppPreferences.getScaled(AppPreferences.BoxSize), tx + 1 }; int[] yp = { ty + 1, y + AppPreferences.getScaled(AppPreferences.BoxSize), y + AppPreferences.getScaled(AppPreferences.BoxSize-2), ty - 1 }; g.setColor(MAGNIFYING_INTERIOR); g.fillOval(x + AppPreferences.getScaled(AppPreferences.BoxSize>>2), y + AppPreferences.getScaled(AppPreferences.BoxSize>>2), AppPreferences.getScaled(AppPreferences.BoxSize>>1), AppPreferences.getScaled(AppPreferences.BoxSize>>1)); g.setColor(Color.BLACK); g.drawOval(x + AppPreferences.getScaled(AppPreferences.BoxSize>>2), y + AppPreferences.getScaled(AppPreferences.BoxSize>>2), AppPreferences.getScaled(AppPreferences.BoxSize>>1), AppPreferences.getScaled(AppPreferences.BoxSize>>1)); g.fillPolygon(xp, yp, xp.length); } } } private static final long serialVersionUID = 1L; private static final String DIRTY_MARKER = "*"; public static final Color MAGNIFYING_INTERIOR = new Color(200, 200, 255, 64); private Project proj; private MyListener myListener = new MyListener(); private MyCellRenderer renderer = new MyCellRenderer(); private DeleteAction deleteAction = new DeleteAction(); private ProjectExplorerListener listener = null; private Tool haloedTool = null; public ProjectExplorer(Project proj) { super(); this.proj = proj; setModel(new ProjectExplorerModel(proj)); setRootVisible(true); addMouseListener(myListener); ToolTipManager.sharedInstance().registerComponent(this); MySelectionModel selector = new MySelectionModel(); selector.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); setSelectionModel(selector); setCellRenderer(renderer); addTreeSelectionListener(myListener); InputMap imap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), deleteAction); ActionMap amap = getActionMap(); amap.put(deleteAction, deleteAction); proj.addProjectListener(myListener); AppPreferences.GATE_SHAPE.addPropertyChangeListener(myListener); LocaleManager.addLocaleListener(this); } public Tool getSelectedTool() { TreePath path = getSelectionPath(); if (path == null) return null; Object last = path.getLastPathComponent(); if (last instanceof ProjectExplorerToolNode) { return ((ProjectExplorerToolNode) last).getValue(); } else { return null; } } public void localeChanged() { // repaint() would work, except that names that get longer will be // abbreviated with an ellipsis, even when they fit into the window. ProjectExplorerModel model = (ProjectExplorerModel) getModel(); model.fireStructureChanged(); } public void setHaloedTool(Tool t) { if (haloedTool == t) return; haloedTool = t; repaint(); } public void setListener(ProjectExplorerListener value) { listener = value; } }
gpl-3.0
Tungsten314/cooking
src/food/baketypes/Dryable.java
93
package food.baketypes; import food.Food; public interface Dryable { public Food dry(); }
gpl-3.0
jaypatil/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NNStorage.java
39022
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadLocalRandom; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.hdfs.DFSUtil; import org.apache.hadoop.hdfs.protocol.LayoutVersion; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption; import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException; import org.apache.hadoop.hdfs.server.common.IncorrectVersionException; import org.apache.hadoop.hdfs.server.common.Storage; import org.apache.hadoop.hdfs.server.common.StorageErrorReporter; import org.apache.hadoop.hdfs.server.common.Util; import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo; import org.apache.hadoop.hdfs.util.PersistentLongFile; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.net.DNS; import org.apache.hadoop.util.Time; import org.eclipse.jetty.util.ajax.JSON; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; /** * NNStorage is responsible for management of the StorageDirectories used by * the NameNode. */ @InterfaceAudience.Private public class NNStorage extends Storage implements Closeable, StorageErrorReporter { static final String DEPRECATED_MESSAGE_DIGEST_PROPERTY = "imageMD5Digest"; static final String LOCAL_URI_SCHEME = "file"; /** * The filenames used for storing the images. */ public enum NameNodeFile { IMAGE ("fsimage"), TIME ("fstime"), // from "old" pre-HDFS-1073 format SEEN_TXID ("seen_txid"), EDITS ("edits"), IMAGE_NEW ("fsimage.ckpt"), IMAGE_ROLLBACK("fsimage_rollback"), EDITS_NEW ("edits.new"), // from "old" pre-HDFS-1073 format EDITS_INPROGRESS ("edits_inprogress"), EDITS_TMP ("edits_tmp"), IMAGE_LEGACY_OIV ("fsimage_legacy_oiv"); // For pre-PB format private String fileName = null; NameNodeFile(String name) { this.fileName = name; } @VisibleForTesting public String getName() { return fileName; } } /** * Implementation of StorageDirType specific to namenode storage * A Storage directory could be of type IMAGE which stores only fsimage, * or of type EDITS which stores edits or of type IMAGE_AND_EDITS which * stores both fsimage and edits. */ @VisibleForTesting public enum NameNodeDirType implements StorageDirType { UNDEFINED, IMAGE, EDITS, IMAGE_AND_EDITS; @Override public StorageDirType getStorageDirType() { return this; } @Override public boolean isOfType(StorageDirType type) { return (this == IMAGE_AND_EDITS) && (type == IMAGE || type == EDITS) || this == type; } } protected String blockpoolID = ""; // id of the block pool /** * Flag that controls if we try to restore failed storages. */ private boolean restoreFailedStorage = false; private final Object restorationLock = new Object(); private boolean disablePreUpgradableLayoutCheck = false; /** * TxId of the last transaction that was included in the most * recent fsimage file. This does not include any transactions * that have since been written to the edit log. */ protected volatile long mostRecentCheckpointTxId = HdfsServerConstants.INVALID_TXID; /** * Time of the last checkpoint, in milliseconds since the epoch. */ private long mostRecentCheckpointTime = 0; /** * List of failed (and thus removed) storages. */ final protected List<StorageDirectory> removedStorageDirs = new CopyOnWriteArrayList<>(); /** * Properties from old layout versions that may be needed * during upgrade only. */ private HashMap<String, String> deprecatedProperties; /** * Name directories size for metric. */ private Map<String, Long> nameDirSizeMap = new HashMap<>(); /** * Construct the NNStorage. * @param conf Namenode configuration. * @param imageDirs Directories the image can be stored in. * @param editsDirs Directories the editlog can be stored in. * @throws IOException if any directories are inaccessible. */ public NNStorage(Configuration conf, Collection<URI> imageDirs, Collection<URI> editsDirs) throws IOException { super(NodeType.NAME_NODE); storageDirs = new CopyOnWriteArrayList<>(); // this may modify the editsDirs, so copy before passing in setStorageDirectories(imageDirs, Lists.newArrayList(editsDirs), FSNamesystem.getSharedEditsDirs(conf)); //Update NameDirSize metric value after NN start updateNameDirSize(); } @Override // Storage public boolean isPreUpgradableLayout(StorageDirectory sd) throws IOException { if (disablePreUpgradableLayoutCheck) { return false; } File oldImageDir = new File(sd.getRoot(), "image"); if (!oldImageDir.exists()) { return false; } // check the layout version inside the image file File oldF = new File(oldImageDir, "fsimage"); RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws"); try { oldFile.seek(0); int oldVersion = oldFile.readInt(); oldFile.close(); oldFile = null; if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION) { return false; } } finally { IOUtils.cleanup(LOG, oldFile); } return true; } @Override // Closeable public void close() throws IOException { unlockAll(); storageDirs.clear(); } /** * Set flag whether an attempt should be made to restore failed storage * directories at the next available oppurtuinity. * * @param val Whether restoration attempt should be made. */ void setRestoreFailedStorage(boolean val) { LOG.warn("set restore failed storage to " + val); restoreFailedStorage=val; } /** * @return Whether failed storage directories are to be restored. */ boolean getRestoreFailedStorage() { return restoreFailedStorage; } /** * See if any of removed storages is "writable" again, and can be returned * into service. */ void attemptRestoreRemovedStorage() { // if directory is "alive" - copy the images there... if(!restoreFailedStorage || removedStorageDirs.size() == 0) { return; //nothing to restore } /* We don't want more than one thread trying to restore at a time */ synchronized (this.restorationLock) { LOG.info("NNStorage.attemptRestoreRemovedStorage: check removed(failed) "+ "storage. removedStorages size = " + removedStorageDirs.size()); for (StorageDirectory sd : this.removedStorageDirs) { File root = sd.getRoot(); LOG.info("currently disabled dir " + root.getAbsolutePath() + "; type=" + sd.getStorageDirType() + ";canwrite=" + FileUtil.canWrite(root)); if (root.exists() && FileUtil.canWrite(root)) { LOG.info("restoring dir " + sd.getRoot().getAbsolutePath()); this.addStorageDir(sd); // restore this.removedStorageDirs.remove(sd); } } } } /** * @return A list of storage directories which are in the errored state. */ List<StorageDirectory> getRemovedStorageDirs() { return this.removedStorageDirs; } /** * See {@link NNStorage#setStorageDirectories(Collection, Collection, Collection)}. */ @VisibleForTesting synchronized void setStorageDirectories(Collection<URI> fsNameDirs, Collection<URI> fsEditsDirs) throws IOException { setStorageDirectories(fsNameDirs, fsEditsDirs, new ArrayList<>()); } /** * Set the storage directories which will be used. This should only ever be * called from inside NNStorage. However, it needs to remain package private * for testing, as StorageDirectories need to be reinitialised after using * Mockito.spy() on this class, as Mockito doesn't work well with inner * classes, such as StorageDirectory in this case. * * Synchronized due to initialization of storageDirs and removedStorageDirs. * * @param fsNameDirs Locations to store images. * @param fsEditsDirs Locations to store edit logs. * @throws IOException */ @VisibleForTesting synchronized void setStorageDirectories(Collection<URI> fsNameDirs, Collection<URI> fsEditsDirs, Collection<URI> sharedEditsDirs) throws IOException { this.storageDirs.clear(); this.removedStorageDirs.clear(); // Add all name dirs with appropriate NameNodeDirType for (URI dirName : fsNameDirs) { checkSchemeConsistency(dirName); boolean isAlsoEdits = false; for (URI editsDirName : fsEditsDirs) { if (editsDirName.compareTo(dirName) == 0) { isAlsoEdits = true; fsEditsDirs.remove(editsDirName); break; } } NameNodeDirType dirType = (isAlsoEdits) ? NameNodeDirType.IMAGE_AND_EDITS : NameNodeDirType.IMAGE; // Add to the list of storage directories, only if the // URI is of type file:// if(dirName.getScheme().compareTo("file") == 0) { this.addStorageDir(new StorageDirectory(new File(dirName.getPath()), dirType, sharedEditsDirs.contains(dirName))); // Don't lock the dir if it's shared. } } // Add edits dirs if they are different from name dirs for (URI dirName : fsEditsDirs) { checkSchemeConsistency(dirName); // Add to the list of storage directories, only if the // URI is of type file:// if(dirName.getScheme().compareTo("file") == 0) { this.addStorageDir(new StorageDirectory(new File(dirName.getPath()), NameNodeDirType.EDITS, sharedEditsDirs.contains(dirName))); } } } /** * Return the storage directory corresponding to the passed URI. * @param uri URI of a storage directory * @return The matching storage directory or null if none found */ public StorageDirectory getStorageDirectory(URI uri) { try { uri = Util.fileAsURI(new File(uri)); Iterator<StorageDirectory> it = dirIterator(); while (it.hasNext()) { StorageDirectory sd = it.next(); if (Util.fileAsURI(sd.getRoot()).equals(uri)) { return sd; } } } catch (IOException ioe) { LOG.warn("Error converting file to URI", ioe); } return null; } /** * Checks the consistency of a URI, in particular if the scheme * is specified. * @param u URI whose consistency is being checked. */ private static void checkSchemeConsistency(URI u) throws IOException { String scheme = u.getScheme(); // the URI should have a proper scheme if(scheme == null) { throw new IOException("Undefined scheme for " + u); } } /** * Retrieve current directories of type IMAGE. * @return Collection of URI representing image directories * @throws IOException in case of URI processing error */ Collection<URI> getImageDirectories() throws IOException { return getDirectories(NameNodeDirType.IMAGE); } /** * Retrieve current directories of type EDITS. * @return Collection of URI representing edits directories * @throws IOException in case of URI processing error */ Collection<URI> getEditsDirectories() throws IOException { return getDirectories(NameNodeDirType.EDITS); } /** * Return number of storage directories of the given type. * @param dirType directory type * @return number of storage directories of type dirType */ int getNumStorageDirs(NameNodeDirType dirType) { if(dirType == null) { return getNumStorageDirs(); } Iterator<StorageDirectory> it = dirIterator(dirType); int numDirs = 0; for(; it.hasNext(); it.next()) { numDirs++; } return numDirs; } /** * Return the list of locations being used for a specific purpose. * i.e. Image or edit log storage. * * @param dirType Purpose of locations requested. * @throws IOException */ Collection<URI> getDirectories(NameNodeDirType dirType) throws IOException { ArrayList<URI> list = new ArrayList<>(); Iterator<StorageDirectory> it = (dirType == null) ? dirIterator() : dirIterator(dirType); for ( ; it.hasNext();) { StorageDirectory sd = it.next(); try { list.add(Util.fileAsURI(sd.getRoot())); } catch (IOException e) { throw new IOException("Exception while processing " + "StorageDirectory " + sd.getRoot(), e); } } return list; } /** * Determine the last transaction ID noted in this storage directory. * This txid is stored in a special seen_txid file since it might not * correspond to the latest image or edit log. For example, an image-only * directory will have this txid incremented when edits logs roll, even * though the edits logs are in a different directory. * * @param sd StorageDirectory to check * @return If file exists and can be read, last recorded txid. If not, 0L. * @throws IOException On errors processing file pointed to by sd */ static long readTransactionIdFile(StorageDirectory sd) throws IOException { File txidFile = getStorageFile(sd, NameNodeFile.SEEN_TXID); return PersistentLongFile.readFile(txidFile, 0); } /** * Write last checkpoint time into a separate file. * @param sd storage directory * @throws IOException */ void writeTransactionIdFile(StorageDirectory sd, long txid) throws IOException { Preconditions.checkArgument(txid >= 0, "bad txid: " + txid); File txIdFile = getStorageFile(sd, NameNodeFile.SEEN_TXID); PersistentLongFile.writeFile(txIdFile, txid); } /** * Set the transaction ID and time of the last checkpoint. * * @param txid transaction id of the last checkpoint * @param time time of the last checkpoint, in millis since the epoch */ void setMostRecentCheckpointInfo(long txid, long time) { this.mostRecentCheckpointTxId = txid; this.mostRecentCheckpointTime = time; } /** * @return the transaction ID of the last checkpoint. */ public long getMostRecentCheckpointTxId() { return mostRecentCheckpointTxId; } /** * @return the time of the most recent checkpoint in millis since the epoch. */ long getMostRecentCheckpointTime() { return mostRecentCheckpointTime; } /** * Write a small file in all available storage directories that * indicates that the namespace has reached some given transaction ID. * * This is used when the image is loaded to avoid accidental rollbacks * in the case where an edit log is fully deleted but there is no * checkpoint. See TestNameEditsConfigs.testNameEditsConfigsFailure() * @param txid the txid that has been reached */ public void writeTransactionIdFileToStorage(long txid) { writeTransactionIdFileToStorage(txid, null); } /** * Write a small file in all available storage directories that * indicates that the namespace has reached some given transaction ID. * * This is used when the image is loaded to avoid accidental rollbacks * in the case where an edit log is fully deleted but there is no * checkpoint. See TestNameEditsConfigs.testNameEditsConfigsFailure() * @param txid the txid that has been reached * @param type the type of directory */ public void writeTransactionIdFileToStorage(long txid, NameNodeDirType type) { // Write txid marker in all storage directories for (Iterator<StorageDirectory> it = dirIterator(type); it.hasNext();) { StorageDirectory sd = it.next(); try { writeTransactionIdFile(sd, txid); } catch(IOException e) { // Close any edits stream associated with this dir and remove directory LOG.warn("writeTransactionIdToStorage failed on " + sd, e); reportErrorsOnDirectory(sd); } } } /** * Return the name of the image file that is uploaded by periodic * checkpointing. * * @return List of filenames to save checkpoints to. */ public File[] getFsImageNameCheckpoint(long txid) { ArrayList<File> list = new ArrayList<>(); for (Iterator<StorageDirectory> it = dirIterator(NameNodeDirType.IMAGE); it.hasNext();) { list.add(getStorageFile(it.next(), NameNodeFile.IMAGE_NEW, txid)); } return list.toArray(new File[list.size()]); } /** * @return The first image file with the given txid and image type. */ public File getFsImageName(long txid, NameNodeFile nnf) { for (Iterator<StorageDirectory> it = dirIterator(NameNodeDirType.IMAGE); it.hasNext();) { StorageDirectory sd = it.next(); File fsImage = getStorageFile(sd, nnf, txid); if (FileUtil.canRead(sd.getRoot()) && fsImage.exists()) { return fsImage; } } return null; } /** * @return The first image file whose txid is the same with the given txid and * image type is one of the given types. */ public File getFsImage(long txid, EnumSet<NameNodeFile> nnfs) { for (Iterator<StorageDirectory> it = dirIterator(NameNodeDirType.IMAGE); it.hasNext();) { StorageDirectory sd = it.next(); for (NameNodeFile nnf : nnfs) { File fsImage = getStorageFile(sd, nnf, txid); if (FileUtil.canRead(sd.getRoot()) && fsImage.exists()) { return fsImage; } } } return null; } public File getFsImageName(long txid) { return getFsImageName(txid, NameNodeFile.IMAGE); } public File getHighestFsImageName() { return getFsImageName(getMostRecentCheckpointTxId()); } /** Create new dfs name directory. Caution: this destroys all files * in this filesystem. */ private void format(StorageDirectory sd) throws IOException { sd.clearDirectory(); // create currrent dir writeProperties(sd); writeTransactionIdFile(sd, 0); LOG.info("Storage directory " + sd.getRoot() + " has been successfully formatted."); } /** * Format all available storage directories. */ public void format(NamespaceInfo nsInfo) throws IOException { Preconditions.checkArgument(nsInfo.getLayoutVersion() == 0 || nsInfo.getLayoutVersion() == HdfsServerConstants.NAMENODE_LAYOUT_VERSION, "Bad layout version: %s", nsInfo.getLayoutVersion()); this.setStorageInfo(nsInfo); this.blockpoolID = nsInfo.getBlockPoolID(); for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) { StorageDirectory sd = it.next(); format(sd); } } public static NamespaceInfo newNamespaceInfo() throws UnknownHostException { return new NamespaceInfo(newNamespaceID(), newClusterID(), newBlockPoolID(), Time.now()); } public void format() throws IOException { this.layoutVersion = HdfsServerConstants.NAMENODE_LAYOUT_VERSION; for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) { StorageDirectory sd = it.next(); format(sd); } } /** * Generate new namespaceID. * * namespaceID is a persistent attribute of the namespace. * It is generated when the namenode is formatted and remains the same * during the life cycle of the namenode. * When a datanodes register they receive it as the registrationID, * which is checked every time the datanode is communicating with the * namenode. Datanodes that do not 'know' the namespaceID are rejected. * * @return new namespaceID */ private static int newNamespaceID() { int newID = 0; while(newID == 0) { newID = ThreadLocalRandom.current().nextInt(0x7FFFFFFF); // use 31 bits } return newID; } @Override // Storage protected void setFieldsFromProperties( Properties props, StorageDirectory sd) throws IOException { super.setFieldsFromProperties(props, sd); if (layoutVersion == 0) { throw new IOException("NameNode directory " + sd.getRoot() + " is not formatted."); } // Set Block pool ID in version with federation support if (NameNodeLayoutVersion.supports( LayoutVersion.Feature.FEDERATION, getLayoutVersion())) { String sbpid = props.getProperty("blockpoolID"); setBlockPoolID(sd.getRoot(), sbpid); } setDeprecatedPropertiesForUpgrade(props); } void readProperties(StorageDirectory sd, StartupOption startupOption) throws IOException { Properties props = readPropertiesFile(sd.getVersionFile()); if (HdfsServerConstants.RollingUpgradeStartupOption.ROLLBACK .matches(startupOption)) { int lv = Integer.parseInt(getProperty(props, sd, "layoutVersion")); if (lv > getServiceLayoutVersion()) { // we should not use a newer version for rollingUpgrade rollback throw new IncorrectVersionException(getServiceLayoutVersion(), lv, "storage directory " + sd.getRoot().getAbsolutePath()); } props.setProperty("layoutVersion", Integer.toString(HdfsServerConstants.NAMENODE_LAYOUT_VERSION)); } setFieldsFromProperties(props, sd); } /** * Pull any properties out of the VERSION file that are from older * versions of HDFS and only necessary during upgrade. */ private void setDeprecatedPropertiesForUpgrade(Properties props) { deprecatedProperties = new HashMap<>(); String md5 = props.getProperty(DEPRECATED_MESSAGE_DIGEST_PROPERTY); if (md5 != null) { deprecatedProperties.put(DEPRECATED_MESSAGE_DIGEST_PROPERTY, md5); } } /** * Return a property that was stored in an earlier version of HDFS. * * This should only be used during upgrades. */ String getDeprecatedProperty(String prop) { assert getLayoutVersion() > HdfsServerConstants.NAMENODE_LAYOUT_VERSION : "getDeprecatedProperty should only be done when loading " + "storage from past versions during upgrade."; return deprecatedProperties.get(prop); } /** * Write version file into the storage directory. * * The version file should always be written last. * Missing or corrupted version file indicates that * the checkpoint is not valid. * * @param sd storage directory * @throws IOException */ @Override // Storage protected void setPropertiesFromFields(Properties props, StorageDirectory sd) throws IOException { super.setPropertiesFromFields(props, sd); // Set blockpoolID in version with federation support if (NameNodeLayoutVersion.supports( LayoutVersion.Feature.FEDERATION, getLayoutVersion())) { props.setProperty("blockpoolID", blockpoolID); } } static File getStorageFile(StorageDirectory sd, NameNodeFile type, long imageTxId) { return new File(sd.getCurrentDir(), String.format("%s_%019d", type.getName(), imageTxId)); } /** * Get a storage file for one of the files that doesn't need a txid associated * (e.g version, seen_txid). */ static File getStorageFile(StorageDirectory sd, NameNodeFile type) { return new File(sd.getCurrentDir(), type.getName()); } @VisibleForTesting public static String getCheckpointImageFileName(long txid) { return getNameNodeFileName(NameNodeFile.IMAGE_NEW, txid); } @VisibleForTesting public static String getImageFileName(long txid) { return getNameNodeFileName(NameNodeFile.IMAGE, txid); } @VisibleForTesting public static String getRollbackImageFileName(long txid) { return getNameNodeFileName(NameNodeFile.IMAGE_ROLLBACK, txid); } public static String getLegacyOIVImageFileName(long txid) { return getNameNodeFileName(NameNodeFile.IMAGE_LEGACY_OIV, txid); } private static String getNameNodeFileName(NameNodeFile nnf, long txid) { return String.format("%s_%019d", nnf.getName(), txid); } @VisibleForTesting public static String getInProgressEditsFileName(long startTxId) { return getNameNodeFileName(NameNodeFile.EDITS_INPROGRESS, startTxId); } static File getInProgressEditsFile(StorageDirectory sd, long startTxId) { return new File(sd.getCurrentDir(), getInProgressEditsFileName(startTxId)); } static File getFinalizedEditsFile(StorageDirectory sd, long startTxId, long endTxId) { return new File(sd.getCurrentDir(), getFinalizedEditsFileName(startTxId, endTxId)); } static File getTemporaryEditsFile(StorageDirectory sd, long startTxId, long endTxId, long timestamp) { return new File(sd.getCurrentDir(), getTemporaryEditsFileName(startTxId, endTxId, timestamp)); } static File getImageFile(StorageDirectory sd, NameNodeFile nnf, long txid) { return new File(sd.getCurrentDir(), getNameNodeFileName(nnf, txid)); } @VisibleForTesting public static String getFinalizedEditsFileName(long startTxId, long endTxId) { return String.format("%s_%019d-%019d", NameNodeFile.EDITS.getName(), startTxId, endTxId); } public static String getTemporaryEditsFileName(long startTxId, long endTxId, long timestamp) { return String.format("%s_%019d-%019d_%019d", NameNodeFile.EDITS_TMP.getName(), startTxId, endTxId, timestamp); } /** * Return the first readable finalized edits file for the given txid. */ File findFinalizedEditsFile(long startTxId, long endTxId) throws IOException { File ret = findFile(NameNodeDirType.EDITS, getFinalizedEditsFileName(startTxId, endTxId)); if (ret == null) { throw new IOException( "No edits file for txid " + startTxId + "-" + endTxId + " exists!"); } return ret; } /** * Return the first readable image file for the given txid and image type, or * null if no such image can be found. */ File findImageFile(NameNodeFile nnf, long txid) { return findFile(NameNodeDirType.IMAGE, getNameNodeFileName(nnf, txid)); } /** * Return the first readable storage file of the given name * across any of the 'current' directories in SDs of the * given type, or null if no such file exists. */ private File findFile(NameNodeDirType dirType, String name) { for (StorageDirectory sd : dirIterable(dirType)) { File candidate = new File(sd.getCurrentDir(), name); if (FileUtil.canRead(sd.getCurrentDir()) && candidate.exists()) { return candidate; } } return null; } /** * Disable the check for pre-upgradable layouts. Needed for BackupImage. * @param val Whether to disable the preupgradeable layout check. */ void setDisablePreUpgradableLayoutCheck(boolean val) { disablePreUpgradableLayoutCheck = val; } /** * Marks a list of directories as having experienced an error. * * @param sds A list of storage directories to mark as errored. */ void reportErrorsOnDirectories(List<StorageDirectory> sds) { for (StorageDirectory sd : sds) { reportErrorsOnDirectory(sd); } } /** * Reports that a directory has experienced an error. * Notifies listeners that the directory is no longer * available. * * @param sd A storage directory to mark as errored. */ private void reportErrorsOnDirectory(StorageDirectory sd) { LOG.error("Error reported on storage directory " + sd); String lsd = listStorageDirectories(); LOG.debug("current list of storage dirs:" + lsd); LOG.warn("About to remove corresponding storage: " + sd.getRoot().getAbsolutePath()); try { sd.unlock(); } catch (Exception e) { LOG.warn("Unable to unlock bad storage directory: " + sd.getRoot().getPath(), e); } if (this.storageDirs.remove(sd)) { this.removedStorageDirs.add(sd); } lsd = listStorageDirectories(); LOG.debug("at the end current list of storage dirs:" + lsd); } /** * Processes the startup options for the clusterid and blockpoolid * for the upgrade. * @param startOpt Startup options * @param layoutVersion Layout version for the upgrade * @throws IOException */ void processStartupOptionsForUpgrade(StartupOption startOpt, int layoutVersion) throws IOException { if (startOpt == StartupOption.UPGRADE || startOpt == StartupOption.UPGRADEONLY) { // If upgrade from a release that does not support federation, // if clusterId is provided in the startupOptions use it. // Else generate a new cluster ID if (!NameNodeLayoutVersion.supports( LayoutVersion.Feature.FEDERATION, layoutVersion)) { if (startOpt.getClusterId() == null) { startOpt.setClusterId(newClusterID()); } setClusterID(startOpt.getClusterId()); setBlockPoolID(newBlockPoolID()); } else { // Upgrade from one version of federation to another supported // version of federation doesn't require clusterID. // Warn the user if the current clusterid didn't match with the input // clusterid. if (startOpt.getClusterId() != null && !startOpt.getClusterId().equals(getClusterID())) { LOG.warn("Clusterid mismatch - current clusterid: " + getClusterID() + ", Ignoring given clusterid: " + startOpt.getClusterId()); } } LOG.info("Using clusterid: " + getClusterID()); } } /** * Report that an IOE has occurred on some file which may * or may not be within one of the NN image storage directories. */ @Override public void reportErrorOnFile(File f) { // We use getAbsolutePath here instead of getCanonicalPath since we know // that there is some IO problem on that drive. // getCanonicalPath may need to call stat() or readlink() and it's likely // those calls would fail due to the same underlying IO problem. String absPath = f.getAbsolutePath(); for (StorageDirectory sd : storageDirs) { String dirPath = sd.getRoot().getAbsolutePath(); if (!dirPath.endsWith(File.separator)) { dirPath += File.separator; } if (absPath.startsWith(dirPath)) { reportErrorsOnDirectory(sd); return; } } } /** * Generate new clusterID. * * clusterID is a persistent attribute of the cluster. * It is generated when the cluster is created and remains the same * during the life cycle of the cluster. When a new name node is formated, * if this is a new cluster, a new clusterID is geneated and stored. * Subsequent name node must be given the same ClusterID during its format to * be in the same cluster. * When a datanode register it receive the clusterID and stick with it. * If at any point, name node or data node tries to join another cluster, it * will be rejected. * * @return new clusterID */ public static String newClusterID() { return "CID-" + UUID.randomUUID().toString(); } void setClusterID(String cid) { clusterID = cid; } /** * Try to find current cluster id in the VERSION files. * returns first cluster id found in any VERSION file * null in case none found * @return clusterId or null in case no cluster id found */ public String determineClusterId() { String cid; Iterator<StorageDirectory> sdit = dirIterator(NameNodeDirType.IMAGE); while(sdit.hasNext()) { StorageDirectory sd = sdit.next(); try { Properties props = readPropertiesFile(sd.getVersionFile()); cid = props.getProperty("clusterID"); LOG.info("current cluster id for sd="+sd.getCurrentDir() + ";lv=" + layoutVersion + ";cid=" + cid); if(cid != null && !cid.equals("")) { return cid; } } catch (Exception e) { LOG.warn("this sd not available: " + e.getLocalizedMessage()); } //ignore } LOG.warn("couldn't find any VERSION file containing valid ClusterId"); return null; } /** * Generate new blockpoolID. * * @return new blockpoolID */ static String newBlockPoolID() throws UnknownHostException{ String ip; try { ip = DNS.getDefaultIP("default"); } catch (UnknownHostException e) { LOG.warn("Could not find ip address of \"default\" inteface."); throw e; } int rand = DFSUtil.getSecureRandom().nextInt(Integer.MAX_VALUE); return "BP-" + rand + "-"+ ip + "-" + Time.now(); } /** Validate and set block pool ID. */ public void setBlockPoolID(String bpid) { blockpoolID = bpid; } /** Validate and set block pool ID. */ private void setBlockPoolID(File storage, String bpid) throws InconsistentFSStateException { if (bpid == null || bpid.equals("")) { throw new InconsistentFSStateException(storage, "file " + Storage.STORAGE_FILE_VERSION + " has no block pool Id."); } if (!blockpoolID.equals("") && !blockpoolID.equals(bpid)) { throw new InconsistentFSStateException(storage, "Unexepcted blockpoolID " + bpid + " . Expected " + blockpoolID); } setBlockPoolID(bpid); } public String getBlockPoolID() { return blockpoolID; } /** * Iterate over all current storage directories, inspecting them * with the given inspector. */ void inspectStorageDirs(FSImageStorageInspector inspector) throws IOException { // Process each of the storage directories to find the pair of // newest image file and edit file for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) { StorageDirectory sd = it.next(); inspector.inspectDirectory(sd); } } /** * Iterate over all of the storage dirs, reading their contents to determine * their layout versions. Returns an FSImageStorageInspector which has * inspected each directory. * * <b>Note:</b> this can mutate the storage info fields (ctime, version, etc). * @throws IOException if no valid storage dirs are found or no valid layout * version */ FSImageStorageInspector readAndInspectDirs(EnumSet<NameNodeFile> fileTypes, StartupOption startupOption) throws IOException { Integer layoutVersion = null; boolean multipleLV = false; StringBuilder layoutVersions = new StringBuilder(); // First determine what range of layout versions we're going to inspect for (Iterator<StorageDirectory> it = dirIterator(false); it.hasNext();) { StorageDirectory sd = it.next(); if (!sd.getVersionFile().exists()) { FSImage.LOG.warn("Storage directory " + sd + " contains no VERSION file. Skipping..."); continue; } readProperties(sd, startupOption); // sets layoutVersion int lv = getLayoutVersion(); if (layoutVersion == null) { layoutVersion = lv; } else if (!layoutVersion.equals(lv)) { multipleLV = true; } layoutVersions.append("(").append(sd.getRoot()).append(", ").append(lv) .append(") "); } if (layoutVersion == null) { throw new IOException("No storage directories contained VERSION" + " information"); } if (multipleLV) { throw new IOException( "Storage directories contain multiple layout versions: " + layoutVersions); } // If the storage directories are with the new layout version // (ie edits_<txnid>) then use the new inspector, which will ignore // the old format dirs. FSImageStorageInspector inspector; if (NameNodeLayoutVersion.supports( LayoutVersion.Feature.TXID_BASED_LAYOUT, getLayoutVersion())) { inspector = new FSImageTransactionalStorageInspector(fileTypes); } else { inspector = new FSImagePreTransactionalStorageInspector(); } inspectStorageDirs(inspector); return inspector; } public NamespaceInfo getNamespaceInfo() { return new NamespaceInfo( getNamespaceID(), getClusterID(), getBlockPoolID(), getCTime()); } public String getNNDirectorySize() { return JSON.toString(nameDirSizeMap); } public void updateNameDirSize() { Map<String, Long> nnDirSizeMap = new HashMap<>(); for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) { StorageDirectory sd = it.next(); if (!sd.isShared()) { nnDirSizeMap.put(sd.getRoot().getAbsolutePath(), sd.getDirecorySize()); } } nameDirSizeMap.clear(); nameDirSizeMap.putAll(nnDirSizeMap); } /** * Write all data storage files. * @throws IOException When all the storage directory fails to write * VERSION file */ @Override public void writeAll() throws IOException { this.layoutVersion = getServiceLayoutVersion(); for (StorageDirectory sd : storageDirs) { try { writeProperties(sd); } catch (Exception e) { LOG.warn("Error during write properties to the VERSION file to " + sd.toString(), e); reportErrorsOnDirectory(sd); if (storageDirs.isEmpty()) { throw new IOException("All the storage failed while writing " + "properties to VERSION file"); } } } } }
gpl-3.0
Dana-Kath/thinklab
plugins/org.integratedmodelling.thinklab.modelling/src/org/integratedmodelling/modelling/ploaders/ModelLoader.java
1635
/** * Copyright 2011 The ARIES Consortium (http://www.ariesonline.org) and * www.integratedmodelling.org. This file is part of Thinklab. Thinklab is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Thinklab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Thinklab. If not, see <http://www.gnu.org/licenses/>. */ package org.integratedmodelling.modelling.ploaders; import java.io.File; import java.util.Collection; import org.integratedmodelling.modelling.model.ModelFactory; import org.integratedmodelling.thinklab.exception.ThinklabException; import org.integratedmodelling.thinklab.interfaces.annotations.ProjectLoader; import org.integratedmodelling.thinklab.project.interfaces.IProjectLoader; @ProjectLoader(folder="models") public class ModelLoader implements IProjectLoader { Collection<String> _namespaces; @Override public void load(File directory) throws ThinklabException { _namespaces = ModelFactory.get().loadModelFiles(directory); } @Override public void unload(File directory) throws ThinklabException { for (String ns : _namespaces) { ModelFactory.get().releaseNamespace(ns); } } }
gpl-3.0
0359xiaodong/twidere
src/org/mariotaku/twidere/util/net/ssl/AbstractCheckSignatureVerifier.java
11633
package org.mariotaku.twidere.util.net.ssl; import android.util.Log; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.conn.util.InetAddressUtilsHC4; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.cert.Certificate; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; public abstract class AbstractCheckSignatureVerifier implements X509HostnameVerifier { /** * This contains a list of 2nd-level domains that aren't allowed to have * wildcards when combined with country-codes. For example: [*.co.uk]. * <p/> * The [*.co.uk] problem is an interesting one. Should we just hope that * CA's would never foolishly allow such a certificate to happen? Looks like * we're the only implementation guarding against this. Firefox, Curl, Sun * Java 1.4, 5, 6 don't bother with this check. */ private final static String[] BAD_COUNTRY_2LDS = { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", "lg", "ne", "net", "or", "org" }; static { // Just in case developer forgot to manually sort the array. :-) Arrays.sort(BAD_COUNTRY_2LDS); } private final static String TAG = "HttpClient"; @Override public final boolean verify(final String host, final SSLSession session) { try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); return true; } catch (final SSLException e) { return false; } } @Override public final void verify(final String host, final SSLSocket ssl) throws IOException { if (host == null) throw new NullPointerException("host to verify is null"); SSLSession session = ssl.getSession(); if (session == null) { // In our experience this only happens under IBM 1.4.x when // spurious (unrelated) certificates show up in the server' // chain. Hopefully this will unearth the real problem: final InputStream in = ssl.getInputStream(); in.available(); /* * If you're looking at the 2 lines of code above because you're * running into a problem, you probably have two options: * * #1. Clean up the certificate chain that your server is presenting * (e.g. edit "/etc/apache2/server.crt" or wherever it is your * server's certificate chain is defined). * * OR * * #2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a * non-IBM JVM. */ // If ssl.getInputStream().available() didn't cause an // exception, maybe at least now the session is available? session = ssl.getSession(); if (session == null) { // If it's still null, probably a startHandshake() will // unearth the real problem. ssl.startHandshake(); // Okay, if we still haven't managed to cause an exception, // might as well go for the NPE. Or maybe we're okay now? session = ssl.getSession(); } } final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); } @Override public final void verify(final String host, final String[] cns, final String[] subjectAlts) throws SSLException { verify(host, cns, subjectAlts, null); } public abstract void verify(final String host, final String[] cns, final String[] subjectAlts, final X509Certificate cert) throws SSLException; @Override public final void verify(final String host, final X509Certificate cert) throws SSLException { final String[] cns = getCNs(cert); final String[] subjectAlts = getSubjectAlts(cert, host); verify(host, cns, subjectAlts, cert); } /** * @deprecated (4.3.1) should not be a part of public APIs. */ @Deprecated public static boolean acceptableCountryWildcard(final String cn) { final String parts[] = cn.split("\\.");// it's // not an attempt to wildcard a 2TLD within a country code if (parts.length != 3 || parts[2].length() != 2) return true; return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0; } /** * Counts the number of dots "." in a string. * * @param s string to count dots from * @return number of dots */ public static int countDots(final String s) { int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '.') { count++; } } return count; } public static String[] getCNs(final X509Certificate cert) { final LinkedList<String> cnList = new LinkedList<String>(); /* * Sebastian Hauer's original StrictSSLProtocolSocketFactory used * getName() and had the following comment: * * Parses a X.500 distinguished name for the value of the "Common Name" * field. This is done a bit sloppy right now and should probably be * done a bit more according to <code>RFC 2253</code>. * * I've noticed that toString() seems to do a better job than getName() * on these X500Principal objects, so I'm hoping that addresses * Sebastian's concern. * * For example, getName() gives me this: * 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d * * whereas toString() gives me this: EMAILADDRESS=juliusdavies@cucbc.com * * Looks like toString() even works with non-ascii domain names! I * tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine. */ final String subjectPrincipal = cert.getSubjectX500Principal().toString(); final StringTokenizer st = new StringTokenizer(subjectPrincipal, ",+"); while (st.hasMoreTokens()) { final String tok = st.nextToken().trim(); if (tok.length() > 3) { if (tok.substring(0, 3).equalsIgnoreCase("CN=")) { cnList.add(tok.substring(3)); } } } if (!cnList.isEmpty()) { final String[] cns = new String[cnList.size()]; cnList.toArray(cns); return cns; } else return null; } /** * Extracts the array of SubjectAlt DNS names from an X509Certificate. * Returns null if there aren't any. * <p/> * Note: Java doesn't appear able to extract international characters from * the SubjectAlts. It can only extract international characters from the CN * field. * <p/> * (Or maybe the version of OpenSSL I'm using to test isn't storing the * international characters correctly in the SubjectAlts?). * * @param cert X509Certificate * @return Array of SubjectALT DNS names stored in the certificate. */ public static String[] getDNSSubjectAlts(final X509Certificate cert) { return getSubjectAlts(cert, null); } public static final boolean verify(final String host, final String[] cns, final String[] subjectAlts, final boolean strictWithSubDomains) { // Build the list of names we're going to check. Our DEFAULT and // STRICT implementations of the HostnameVerifier only use the // first CN provided. All other CNs are ignored. // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way). final LinkedList<String> names = new LinkedList<String>(); if (cns != null && cns.length > 0 && cns[0] != null) { names.add(cns[0]); } if (subjectAlts != null) { for (final String subjectAlt : subjectAlts) { if (subjectAlt != null) { names.add(subjectAlt); } } } if (names.isEmpty()) return false; // StringBuilder for building the error message. final StringBuilder buf = new StringBuilder(); // We're can be case-insensitive when comparing the host we used to // establish the socket to the hostname in the certificate. final String hostName = normaliseIPv6Address(host.trim().toLowerCase(Locale.US)); boolean match = false; for (final Iterator<String> it = names.iterator(); it.hasNext();) { // Don't trim the CN, though! String cn = it.next(); cn = cn.toLowerCase(Locale.US); // Store CN in StringBuilder in case we need to report an error. buf.append(" <"); buf.append(cn); buf.append('>'); if (it.hasNext()) { buf.append(" OR"); } // The CN better have at least two dots if it wants wildcard // action. It also can't be [*.co.uk] or [*.co.jp] or // [*.org.uk], etc... final String parts[] = cn.split("\\."); final boolean doWildcard = parts.length >= 3 && parts[0].endsWith("*") && validCountryWildcard(cn) && !isIPAddress(host); if (doWildcard) { final String firstpart = parts[0]; if (firstpart.length() > 1) { // e.g. server* // e.g. server final String prefix = firstpart.substring(0, firstpart.length() - 1); // skip wildcard part from cn final String suffix = cn.substring(firstpart.length());// skip // wildcard part from host final String hostSuffix = hostName.substring(prefix.length()); match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix); } else { match = hostName.endsWith(cn.substring(1)); } if (match && strictWithSubDomains) { // If we're in strict mode, then [*.foo.com] is not // allowed to match [a.b.foo.com] match = countDots(hostName) == countDots(cn); } } else { match = hostName.equals(normaliseIPv6Address(cn)); } if (match) { break; } } return match; } /** * Extracts the array of SubjectAlt DNS or IP names from an X509Certificate. * Returns null if there aren't any. * * @param cert X509Certificate * @param hostname * @return Array of SubjectALT DNS or IP names stored in the certificate. */ private static String[] getSubjectAlts(final X509Certificate cert, final String hostname) { final int subjectType; if (isIPAddress(hostname)) { subjectType = 7; } else { subjectType = 2; } final LinkedList<String> subjectAltList = new LinkedList<String>(); Collection<List<?>> c = null; try { c = cert.getSubjectAlternativeNames(); } catch (final CertificateParsingException cpe) { } if (c != null) { for (final List<?> aC : c) { final List<?> list = aC; final int type = ((Integer) list.get(0)).intValue(); if (type == subjectType) { final String s = (String) list.get(1); subjectAltList.add(s); } } } if (!subjectAltList.isEmpty()) { final String[] subjectAlts = new String[subjectAltList.size()]; subjectAltList.toArray(subjectAlts); return subjectAlts; } else return null; } private static boolean isIPAddress(final String hostname) { return hostname != null && (InetAddressUtilsHC4.isIPv4Address(hostname) || InetAddressUtilsHC4.isIPv6Address(hostname)); } /* * Check if hostname is IPv6, and if so, convert to standard format. */ private static String normaliseIPv6Address(final String hostname) { if (hostname == null || !InetAddressUtilsHC4.isIPv6Address(hostname)) return hostname; try { final InetAddress inetAddress = InetAddress.getByName(hostname); return inetAddress.getHostAddress(); } catch (final UnknownHostException uhe) { // Should not happen, because // we check for IPv6 address // above Log.e(TAG, "Unexpected error converting " + hostname, uhe); return hostname; } } static boolean validCountryWildcard(final String cn) { final String parts[] = cn.split("\\."); // it's not an attempt to wildcard a 2TLD within a country code if (parts.length != 3 || parts[2].length() != 2) return true; return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0; } }
gpl-3.0
ebIX-TT/ebix
org.ebix.umm.uml2text/xtend-gen/org/ebix/umm/uml2text/model/ASCC.java
1413
/** * UMM Schema Generator * Copyright (C) 2014 ebIX, the European forum for energy Business Information eXchange. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.ebix.umm.uml2text.model; import java.util.List; import org.eclipse.uml2.uml.Association; @SuppressWarnings("all") public interface ASCC { public abstract List<String> businessTerm(final Association umlAssociation); public abstract String definition(final Association umlAssociation); public abstract String dictionaryEntryName(final Association umlAssociation); public abstract String uniqueIdentifier(final Association umlAssociation); public abstract String versionIdentifier(final Association umlAssociation); public abstract String sequencingKey(final Association umlAssociation); }
gpl-3.0
Mayomi/PlotSquared-Chinese
src/main/java/com/intellectualcrafters/plot/util/EconHandler.java
617
package com.intellectualcrafters.plot.util; import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer; public abstract class EconHandler { public static EconHandler manager; public abstract double getMoney(PlotPlayer player); public abstract void withdrawMoney(PlotPlayer player, double amount); public abstract void depositMoney(PlotPlayer player, double amount); public abstract void depositMoney(OfflinePlotPlayer player, double amount); public abstract void setPermission(PlotPlayer player, String perm, boolean value); }
gpl-3.0
Substance-Project/GEM
mobile/src/main/java/com/animbus/music/ui/activity/setup/SetupActivity.java
3133
/* * Copyright 2016 Substance Mobile * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.animbus.music.ui.activity.setup; import android.Manifest; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.view.WindowManager; import com.afollestad.appthemeengine.util.ATEUtil; import com.animbus.music.BuildConfig; import com.animbus.music.R; import com.animbus.music.media.Library; import com.github.paolorotolo.appintro.AppIntro2; import com.github.paolorotolo.appintro.AppIntroFragment; /** * Created by Adrian on 8/3/2015. */ public class SetupActivity extends AppIntro2 { @Override public void init(Bundle bundle) { int background = Color.parseColor("#303030"); if (Build.VERSION.SDK_INT >= 21) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().setStatusBarColor(ATEUtil.darkenColor(background)); } else if (Build.VERSION.SDK_INT == 19) getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); addSlide(AppIntroFragment.newInstance( getResources().getString(R.string.app_name_actual), getResources().getString(R.string.setup_intro), R.drawable.ic_gem_simple_white_112dp, background)); addSlide(AppIntroFragment.newInstance( getResources().getString(R.string.permission_storage_explain_title), getResources().getString(R.string.permission_storage_explain_message), R.drawable.ic_folder_white_112dp, background)); if (BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("internal")) addSlide(AppIntroFragment.newInstance( getResources().getString(R.string.internal_tester_warning_title), getResources().getString(R.string.internal_tester_warning), R.drawable.ic_warning_white_112dp, background)); addSlide(AppIntroFragment.newInstance( getResources().getString(R.string.setup_thanks), getResources().getString(R.string.enjoy), R.drawable.ic_smile_white_112dp, background)); askForPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2); setSwipeLock(false); } @Override public void onDonePressed() { finish(); Library.build(); } @Override public void onNextPressed() { } @Override public void onSlideChanged() { } }
gpl-3.0
nishanttotla/predator
cpachecker/src/org/sosy_lab/cpachecker/cpa/policyiteration/tests/package-info.java
93
/** Tests for policy iteration */ package org.sosy_lab.cpachecker.cpa.policyiteration.tests;
gpl-3.0
awilliamson/SimpleDS
src/simpleDS/util/ConfigParser.java
4614
/* @description This class is used to parse the configuration parameters of SimpleDS agents. * * @history 10.Nov.2015 Beta version * * @author <ahref="mailto:h.cuayahuitl@gmail.com">Heriberto Cuayahuitl</a> */ package simpleDS.util; import java.util.HashMap; public class ConfigParser { private HashMap<String,String> configurations; private final String LANGUAGES = "english,german,spanish"; public boolean verbose = false; public int numDialogues = 0; public ConfigParser(String configFile) { configurations = new HashMap<String,String>(); IOUtil.readHashMap(configFile, configurations, "="); StringUtil.expandAbstractKeyValuePairs(configurations); IOUtil.printHashMap(configurations, "CONFIGURATIONS"); checkValidity(); } public void checkValidity() { String param = null; String value = null; try { for (String item : configurations.keySet()) { param = item; value = (String) configurations.get(param); if ((param.equals("Dialogues") && isInteger(value)==false) || (param.equals("SlotsToConfirm") && isInteger(value)==false) || (param.equals("SavingFrequency") && isInteger(value)==false) || (param.equals("LearningSteps") && isInteger(value)==false) || (param.equals("ExperienceSize") && isInteger(value)==false) || (param.equals("BurningSteps") && isInteger(value)==false) || (param.equals("BatchSize") && isInteger(value)==false) || (param.equals("SocketServerPort") && isInteger(value)==false)) { Logger.error(this.getClass().getName(), "checkValidity", "Revise param="+param + " value=("+value + "), it should be a positive integer"); } else if ((param.equals("MinimumProbability") && isReal(value)==false) || (param.equals("DiscountFactor") && isReal(value)==false) || (param.equals("MinimumEpsilon") && isReal(value)==false)) { Logger.error(this.getClass().getName(), "checkValidity", "Revise param="+param + " value=("+value + "), it should be a real number"); } else if ((param.equals("Language") && isLanguage(value)==false)) { Logger.error(this.getClass().getName(), "checkValidity", "Revise param="+param + " value=("+value + "), is not a valid language"); } else if ((param.equals("Verbose") && isBoolean(value)==false) || (param.equals("AndroidSupport") && isBoolean(value)==false)) { Logger.error(this.getClass().getName(), "checkValidity", "Revise param="+param + " value=("+value + "), it should be true or false"); } else if (isOther(value)==false) { Logger.error(this.getClass().getName(), "checkValidity", "Revise param="+param + " value=("+value + "), it should not be empty"); } } } catch (Exception e) { Logger.error(this.getClass().getName(), "checkValidity", "Check param="+param + " value="+value + " in ./config.txt"); System.exit(0); } } private boolean isInteger(String value) { try { Integer.parseInt(value); return true; } catch (Exception e) { return false; } } private boolean isReal(String value) { try { Double.parseDouble(value); return true; } catch (Exception e) { return false; } } private boolean isLanguage(String value) { for (String lang : StringUtil.getArrayListFromString(LANGUAGES, ",")) { if (value.equals(lang)) { return true; } } return false; } private boolean isBoolean(String value) { if (value.equals("true") || value.equals("false")) { return true; } else { return false; } } private boolean isOther(String value) { if (!value.equals("")) { return true; } else { return false; } } public String getParamValue(String param) { return configurations.get(param); } public HashMap<String,String> getParams() { return configurations; } public void setVerboseMode(String _verbose) { if (_verbose != null) { if (_verbose.equals("-v")) { verbose = true; } else if (_verbose.equals("-nv")) { verbose = false; } else { Logger.error(this.getClass().getName(), "checkValidity", "Unknown verbose mode="+_verbose); System.exit(0); } } else { verbose = configurations.get("Verbose").equals("true") ? true : false; } Logger.debug(this.getClass().getName(), "setVerboseMode", "verbose="+verbose); } public void setNumDialogues(String _numDialogues) { if (_numDialogues != null) { numDialogues = Integer.parseInt(_numDialogues); } else { numDialogues = Integer.parseInt(configurations.get("Dialogues")); } Logger.debug(this.getClass().getName(), "setNumDialogues", "numDialogues="+numDialogues); } }
gpl-3.0
obiba/opal
opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/search/entity/SearchEntityUiHandlers.java
980
/* * Copyright (c) 2021 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.opal.web.gwt.app.client.search.entity; import com.gwtplatform.mvp.client.UiHandlers; import org.obiba.opal.web.model.client.magma.ValueSetsDto; import org.obiba.opal.web.model.client.magma.VariableDto; public interface SearchEntityUiHandlers extends UiHandlers { void onSearch(String entityType, String entityId); void onTableChange(String tableReference); void requestValueSequenceView(VariableDto variableDto); void requestBinaryValueView(VariableDto variable); void requestGeoValueView(VariableDto variable, ValueSetsDto.ValueDto value); void requestEntityView(VariableDto variable, ValueSetsDto.ValueDto value); }
gpl-3.0
xiaoligit/hypersocket-framework
hypersocket-core/src/main/java/com/hypersocket/auth/AuthenticationAttemptEvent.java
2518
package com.hypersocket.auth; import org.apache.commons.lang3.ArrayUtils; import com.hypersocket.events.CommonAttributes; import com.hypersocket.events.SystemEvent; import com.hypersocket.i18n.I18NServiceImpl; import com.hypersocket.realm.Realm; public class AuthenticationAttemptEvent extends SystemEvent { private static final long serialVersionUID = -1557924699852329686L; public static final String ATTR_IP_ADDRESS = CommonAttributes.ATTR_IP_ADDRESS; public static final String ATTR_SCHEME = CommonAttributes.ATTR_SCHEME; public static final String ATTR_MODULE = CommonAttributes.ATTR_MODULE; public static final String ATTR_PRINCIPAL_NAME = CommonAttributes.ATTR_PRINCIPAL_NAME; public static final String ATTR_PRINCIPAL_REALM = CommonAttributes.ATTR_PRINCIPAL_REALM; public static final String ATTR_HINT = CommonAttributes.ATTR_HINT; public static final String EVENT_RESOURCE_KEY = "event.auth"; public AuthenticationAttemptEvent(Object source, AuthenticationState state, Authenticator authenticator) { this(source, true, state, authenticator); } public AuthenticationAttemptEvent(Object source, AuthenticationState state, Authenticator authenticator, String resourceKey) { this(source, false, state, authenticator); addAttribute(AuthenticationAttemptEvent.ATTR_HINT, I18NServiceImpl.tagForConversion( AuthenticationService.RESOURCE_BUNDLE, resourceKey)); } private AuthenticationAttemptEvent(Object source, boolean success, AuthenticationState state, Authenticator authenticator) { super(source, EVENT_RESOURCE_KEY, success, state.getRealm()); addAttribute(AuthenticationAttemptEvent.ATTR_IP_ADDRESS, state.getRemoteAddress()); addAttribute(AuthenticationAttemptEvent.ATTR_SCHEME, state.getScheme().getName()); addAttribute(AuthenticationAttemptEvent.ATTR_MODULE, I18NServiceImpl.tagForConversion( authenticator.getResourceBundle(), authenticator.getResourceKey())); addAttribute(AuthenticationAttemptEvent.ATTR_PRINCIPAL_NAME, state.getLastPrincipalName()); addAttribute(AuthenticationAttemptEvent.ATTR_PRINCIPAL_REALM, state.getLastRealmName()); } public AuthenticationAttemptEvent(Object source, String resourceKey, Throwable e, Realm currentRealm) { super(source, resourceKey, e, currentRealm); } public String getResourceBundle() { return AuthenticationService.RESOURCE_BUNDLE; } public String[] getResourceKeys() { return ArrayUtils.add(super.getResourceKeys(), EVENT_RESOURCE_KEY); } }
gpl-3.0
BotBallARDroneAPI/CBCJVM
installer/install/install_data/jvm/cbc/cbccore/display/CBCJVM/src/cbccore/sensors/analog/AnalogBooleanAdapter.java
5301
/* * This file is part of CBCJVM. * CBCJVM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CBCJVM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CBCJVM. If not, see <http://www.gnu.org/licenses/>. */ package cbccore.sensors.analog; import cbccore.sensors.digital.IBooleanSensor; import cbccore.sensors.buttons.BlackButton; /** * Allows you to use an Analog sensor in a boolean (digital) fashion. If a * sensor value goes over or under a specified value, an event will be emitted. */ public class AnalogBooleanAdapter implements IBooleanSensor { private Analog sensor = null; private int pivot = 0; private boolean reverseCondition = false; /** * @param sensor The analog sensor to watch * @param pivot The point where the boolean value "pivot"s around, if the * value goes below this, false is returned otherwise true * is returned<p/> * If you want to do <code>x >= 50</code> then your pivot * value would be 50. You can use boolean algebra to form * pivot values for other equations. * @see cbccore.sensors.analog.Analog */ public AnalogBooleanAdapter(Analog sensor, int pivot) { this.sensor = sensor; this.pivot = pivot; } /** * @param sensor The analog sensor to watch * @param pivot The point where the boolean value "pivot"s around, if the * value goes below this, false is returned otherwise true * is returned<p/> * If you want to do <code>x >= 50</code> then your pivot * value would be 50. You can use boolean algebra to form * pivot values for other equations. * @param reverseCondition if this is set true, than when the sensor input * is greater than the pivot, it will return false, but * when it is less than the pivot, it will return true * @see cbccore.sensors.analog.Analog */ public AnalogBooleanAdapter(Analog sensor,int pivot,boolean reverseCondition) { this.sensor = sensor; this.pivot = pivot; this.reverseCondition = reverseCondition; } public Analog getAnalog() { return sensor; } public boolean getReverseCondition() { return reverseCondition ; } /** * @param reverseCondition if this is set true, than when the sensor input * is greater than the pivot, it will return false, but * when it is less than the pivot, it will return true */ public void setReverseCondition(boolean reverseCondition) { this.reverseCondition = reverseCondition; } /** * The point where the boolean value "pivot"s around, if the value goes * below this, false is returned otherwise true is returned. * * @return The "pivot" value */ public int getPivot() { return pivot; } /** * The point where the boolean value "pivot"s around, if the value goes * below this, false is returned otherwise true is returned. * * @param pivot The point where the boolean value "pivot"s around, if the * value goes below this, false is returned otherwise true is * returned<p/> * If you want to do <code>x >= 50</code> then your pivot * value would be 50. You can use boolean algebra to form * pivot values for other equations. */ public void setPivot(int pivot) { this.pivot = pivot; } @Override public boolean getValue() { if(sensor.getValueHigh() < pivot) return reverseCondition; return !reverseCondition; } /** * Preforms automatic calibration of sensor based on user input. */ public void calibrateSensor() throws Exception { BlackButton bb = new BlackButton(); //setup input from black_button int threshold = 0; System.out.println("Place sensor in true condition and press button"); while(bb.isNotPushed()){java.lang.Thread.yield();} while(bb.isPushed()){java.lang.Thread.yield();} //wait for button to be pressed and released int trueval = sensor.getValueHigh(); System.out.println("Place sensor in false condition and press button"); while(bb.isNotPushed()){java.lang.Thread.yield();} //wait for button to be pressed and released while(bb.isPushed()){java.lang.Thread.yield();} int falseval = sensor.getValueHigh(); reverseCondition=false; threshold=(trueval+falseval)/2 ; //threshold is half way inbetween trueval and falseval reverseCondition=falseval>trueval; //if falseval is greater than true, we reverse condition if(falseval==trueval) //they shouldn't be equal throw new Exception("Bad Calibration! High and low range values are both at "+trueval); pivot=threshold; //set pivot System.out.println("The high value/range is "+trueval); System.out.println("The low value/range is "+falseval); System.out.println("The threshold value is "+threshold); } }
gpl-3.0
mhall119/Phoenicia
app/src/main/java/com/linguaculturalists/phoenicia/components/PlacedBlockSprite.java
4694
package com.linguaculturalists.phoenicia.components; import com.linguaculturalists.phoenicia.PhoeniciaGame; import com.linguaculturalists.phoenicia.ui.SpriteMoveHUD; import com.linguaculturalists.phoenicia.util.GameFonts; import com.linguaculturalists.phoenicia.util.PhoeniciaContext; import org.andengine.entity.IEntity; import org.andengine.entity.modifier.IEntityModifier; import org.andengine.entity.modifier.MoveYModifier; import org.andengine.entity.modifier.ScaleAtModifier; import org.andengine.entity.sprite.AnimatedSprite; import org.andengine.entity.sprite.ButtonSprite; import org.andengine.entity.text.Text; import org.andengine.extension.tmx.TMXTile; import org.andengine.input.touch.TouchEvent; import org.andengine.input.touch.detector.ClickDetector; import org.andengine.input.touch.detector.HoldDetector; import org.andengine.opengl.texture.region.ITiledTextureRegion; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import org.andengine.util.debug.Debug; import org.andengine.util.modifier.IModifier; import org.andengine.util.modifier.ease.EaseBackOut; import org.andengine.util.modifier.ease.EaseLinear; import java.util.Map; /** * An AnimatedSprite that represents a block on the game map. * PlacedBlockSprites maintain their own build progress and images tiles, and will update the set * used in the animation based on their current progress. * * PlacedBlockSprites assume 4 sets of animation tiles, which are used for 0-33%, 34-66%, 67-100% * and 100% onward. */ public class PlacedBlockSprite extends MapBlockSprite { private int mProgress; private int mTime; private boolean complete; /** * Create a new PlacedBlockSprite. * @param pX the X coordinate of the scene to place this PlacedBlockSprite * @param pY the Y coordinate of the scene to place this PlacedBlockSprite * @param pTileId the index of first tile of the first animation set from pTiledTextureRegion * @param pTiledTextureRegion region containing the tile set for this PlacedBlockSprite * @param pVertexBufferObjectManager the game's VertexBufferObjectManager */ public PlacedBlockSprite(final PhoeniciaGame phoeniciaGame, final float pX, final float pY, final int pTime, final int pTileId, final ITiledTextureRegion pTiledTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) { super(phoeniciaGame, pX, pY, pTileId, pTiledTextureRegion, pVertexBufferObjectManager); this.mTime = pTime; this.mProgress = 0; this.complete = false; } /** * Update the current progress of the build for this PlacedBlockSprite. * Updating the progress may change the animation set in use. The current percentage of progress * is determined by pProgress/pTime. * @param pProgress new progress time in seconds * @param pTime the total time the build should take */ public void setProgress(int pProgress, int pTime) { this.mProgress = pProgress; int completed = (pProgress*100) / pTime; int newStartTile = 0; if (completed < 33) { newStartTile = mTileId; } else if (completed < 66) { newStartTile = mTileId+4; } else if (completed < 100) { newStartTile = mTileId+8; } else { newStartTile = mTileId+12; this.complete = true; } if (newStartTile != this.startTile) { this.startTile = newStartTile; this.animate(this.mFrameDurations, startTile, startTile+mFrameDurations.length-1, true); } } /** * Determine if this PlacedBlockSprite's construction is finished. * @return true if the build has finished, otherwise false */ public boolean isComplete() { return this.complete; } /** * Get the current progress time for this PlacedBlockSprite's construction. * @return time (in seconds) that the build has been running */ public int getProgress() { return this.mProgress; } /** * Callback interface for handling Click events on a PlacedBlockSprite. */ public interface OnClickListener { /** * Called when this sprite is clicked * @param pPlacedBlockSprite * @param pTouchAreaLocalX * @param pTouchAreaLocalY */ public void onClick(final PlacedBlockSprite pPlacedBlockSprite, final float pTouchAreaLocalX, final float pTouchAreaLocalY); public void onHold(final PlacedBlockSprite pPlacedBlockSprite, final float pTouchAreaLocalX, final float pTouchAreaLocalY); } }
gpl-3.0
rosenpin/AlwaysOnDisplayAmoled
app/src/main/java/com/tomer/alwayson/activities/DeveloperActivity.java
1794
package com.tomer.alwayson.activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import com.tomer.alwayson.R; import com.tomer.alwayson.helpers.Utils; import java.util.List; import butterknife.BindViews; import butterknife.ButterKnife; public class DeveloperActivity extends AppCompatActivity implements View.OnClickListener { @BindViews({R.id.twitter, R.id.google_plus, R.id.google_play, R.id.linkedin, R.id.github, R.id.patreon}) List<LinearLayout> developerLinks; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_developer); ButterKnife.bind(this); for (LinearLayout developerLink : developerLinks) { developerLink.setOnClickListener(this); } } @Override public void onClick(View v) { String url = ""; switch (v.getId()) { case R.id.twitter: url = "https://twitter.com/Rosenpin"; break; case R.id.google_plus: url = "https://plus.google.com/+TomerRosenfeld"; break; case R.id.google_play: url = "https://play.google.com/store/apps/developer?id=Tomer%27s+apps"; break; case R.id.linkedin: url = "https://www.linkedin.com/in/tomer-rosenfeld-0220366a"; break; case R.id.github: url = "https://github.com/rosenpin"; break; case R.id.patreon: url = "https://www.patreon.com/user?u=2966388"; break; } Utils.openURL(this, url); } }
gpl-3.0
mbshopM/openconcerto
OpenConcerto/src/org/openconcerto/odtemplate/engine/DataModel.java
1835
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. * * The contents of this file are subject to the terms of the GNU General Public License Version 3 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each file. */ package org.openconcerto.odtemplate.engine; import org.openconcerto.odtemplate.TemplateException; import java.util.Map; public abstract class DataModel { public abstract void put(String name, Object value); /** * Copies all of the mappings from the specified map to this. This implementation simply calls * {@link #put(String,Object) put(k, v)} once for each entry in the specified map. * * @param toMerge mappings to be stored. */ public void putAll(Map<? extends String, ?> toMerge) { for (final Map.Entry<? extends String, ?> e : toMerge.entrySet()) { this.put(e.getKey(), e.getValue()); } } protected abstract Object _eval(String expression) throws Exception; public final Object eval(String expression) throws TemplateException { try { return this._eval(expression); } catch (Throwable t) { throw new TemplateException("invalid expression: \"" + expression + "\"", t); } } /** * Copy this engine and especially its bindings. * * @return an independant copy of this. */ public abstract DataModel copy(); }
gpl-3.0
jtracey/Signal-Android
src/org/thoughtcrime/securesms/webrtc/locks/ProximityLock.java
2861
package org.thoughtcrime.securesms.webrtc.locks; import android.os.Build; import android.os.PowerManager; import org.thoughtcrime.securesms.logging.Log; import org.whispersystems.libsignal.util.guava.Optional; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Controls access to the proximity lock. * The proximity lock is not part of the public API. * * @author Stuart O. Anderson */ class ProximityLock { private static final String TAG = ProximityLock.class.getSimpleName(); private final Method wakelockParameterizedRelease = getWakelockParamterizedReleaseMethod(); private final Optional<PowerManager.WakeLock> proximityLock; private static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32; private static final int WAIT_FOR_PROXIMITY_NEGATIVE = 1; ProximityLock(PowerManager pm) { proximityLock = getProximityLock(pm); } private Optional<PowerManager.WakeLock> getProximityLock(PowerManager pm) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (pm.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) { return Optional.fromNullable(pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "signal:proximity")); } else { return Optional.absent(); } } else { try { return Optional.fromNullable(pm.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "signal:incall")); } catch (Throwable t) { Log.e(TAG, "Failed to create proximity lock", t); return Optional.absent(); } } } public void acquire() { if (!proximityLock.isPresent() || proximityLock.get().isHeld()) { return; } proximityLock.get().acquire(); } public void release() { if (!proximityLock.isPresent() || !proximityLock.get().isHeld()) { return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { proximityLock.get().release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY); } else { boolean released = false; if (wakelockParameterizedRelease != null) { try { wakelockParameterizedRelease.invoke(proximityLock.get(), WAIT_FOR_PROXIMITY_NEGATIVE); released = true; } catch (IllegalAccessException e) { Log.w(TAG, e); } catch (InvocationTargetException e) { Log.w(TAG, e); } } if (!released) { proximityLock.get().release(); } } Log.d(TAG, "Released proximity lock:" + proximityLock.get().isHeld()); } private static Method getWakelockParamterizedReleaseMethod() { try { return PowerManager.WakeLock.class.getDeclaredMethod("release", Integer.TYPE); } catch (NoSuchMethodException e) { Log.d(TAG, "Parameterized WakeLock release not available on this device."); } return null; } }
gpl-3.0
RobbiNespu/moloko
src/dev/drsoran/moloko/widgets/TouchableLinkTextView.java
3439
/* * Copyright (c) 2012 Ronny Röhricht * * This file is part of Moloko. * * Moloko is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Moloko is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Moloko. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Ronny Röhricht - implementation */ package dev.drsoran.moloko.widgets; import android.content.Context; import android.text.Layout; import android.text.Selection; import android.text.Spannable; import android.text.style.ClickableSpan; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.TextView; public class TouchableLinkTextView extends TextView { public TouchableLinkTextView( Context context, AttributeSet attrs, int defStyle ) { super( context, attrs, defStyle ); init(); } public TouchableLinkTextView( Context context, AttributeSet attrs ) { super( context, attrs ); init(); } public TouchableLinkTextView( Context context ) { super( context ); init(); } @Override public boolean onTouchEvent( MotionEvent event ) { final int action = event.getAction(); if ( action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN ) { int x = (int) event.getX(); int y = (int) event.getY(); x -= getTotalPaddingLeft(); y -= getTotalPaddingTop(); x += getScrollX(); y += getScrollY(); final Layout layout = getLayout(); int line = layout.getLineForVertical( y ); int off = layout.getOffsetForHorizontal( line, x ); final CharSequence text = getText(); if ( text instanceof Spannable ) { final Spannable buffer = (Spannable) getText(); final ClickableSpan[] link = buffer.getSpans( off, off, ClickableSpan.class ); if ( link.length != 0 ) { if ( action == MotionEvent.ACTION_UP ) { link[ 0 ].onClick( this ); } else if ( action == MotionEvent.ACTION_DOWN ) { Selection.setSelection( buffer, buffer.getSpanStart( link[ 0 ] ), buffer.getSpanEnd( link[ 0 ] ) ); } return true; } else { Selection.removeSelection( buffer ); } } } return super.onTouchEvent( event ); } private void init() { setLinksClickable( false ); } }
gpl-3.0
simon816/ComcraftModLoader
src/net/comcraft/src/LanguageSet.java
452
/* * Copyright (C) 2012 Piotr Wójcik * */ package net.comcraft.src; /** * * @author Piotr Wójcik */ public class LanguageSet { private String languageName; private String patch; public LanguageSet(String name, String patch) { this.languageName = name; this.patch = patch; } public String getLanguageName() { return languageName; } public String getPatch() { return patch; } }
gpl-3.0
bayocr/qdemosapp
qdemos/src/main/java/com/cusl/ull/qdemos/Home.java
6812
package com.cusl.ull.qdemos; import java.util.List; import java.util.Locale; import android.app.ActionBar; import android.app.PendingIntent; import android.content.Intent; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.cusl.ull.qdemos.bbdd.models.UsuarioEleccion; import com.cusl.ull.qdemos.bbdd.utilities.BBDD; import com.cusl.ull.qdemos.fragments.listas.AceptadasFragment; import com.cusl.ull.qdemos.fragments.listas.HistorialFragment; import com.cusl.ull.qdemos.fragments.listas.PendientesFragment; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class Home extends FragmentActivity implements ActionBar.TabListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); // Set up the action bar. final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { com.cusl.ull.qdemos.server.Utilities.sincronizarBBDD(getApplicationContext()); actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this)); } // Muestra un mensajito si hemos sido redirigidos a este Activity a través de la creación, con éxito, de una Qdada if (getIntent().getExtras() != null){ Boolean qdadacreada = getIntent().getExtras().getBoolean("creadaqdada"); if ((qdadacreada != null) && (qdadacreada)){ Crouton.makeText(this, getString(R.string.qdadacreada), Style.CONFIRM).show(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.home, menu); return super.onCreateOptionsMenu(menu); } // Si se ha clickado en la opcion de cerrar sesión del menu, mostraremos el fragment que nos permitirá cerrar la sesión. @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.menu_logout: Intent intent = new Intent(this, Logout.class); startActivity(intent); return true; case R.id.menu_nuevo: Intent intentQ = new Intent(this, Qdada.class); intentQ.putExtra("edicion", true); startActivity(intentQ); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. switch (position) { case 0: return new AceptadasFragment(); case 1: return new PendientesFragment(); case 2: return new HistorialFragment(); } return null; } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section_aceptadas).toUpperCase(l); case 1: return getString(R.string.title_section_pendientes).toUpperCase(l); case 2: return getString(R.string.title_section_historial).toUpperCase(l); } return null; } } }
gpl-3.0
andforce/iBeebo
app/src/main/java/org/zarroboogs/weibo/support/lib/AppFragmentPagerAdapter.java
4516
package org.zarroboogs.weibo.support.lib; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.PagerAdapter; import android.util.Log; import android.view.View; import android.view.ViewGroup; public abstract class AppFragmentPagerAdapter extends PagerAdapter { private static final String TAG = "FragmentPagerAdapter"; private static final boolean DEBUG = false; private final FragmentManager mFragmentManager; private FragmentTransaction mCurTransaction = null; private Fragment mCurrentPrimaryItem = null; public AppFragmentPagerAdapter(FragmentManager fm) { mFragmentManager = fm; } /** * Return the Fragment associated with a specified position. */ public abstract Fragment getItem(int position); @Override public void startUpdate(ViewGroup container) { } @Override public Object instantiateItem(ViewGroup container, int position) { if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } final long itemId = getItemId(position); // Do we already have this fragment? // String name = makeFragmentName(container.getId(), itemId); String name = getTag(position); Fragment fragment = mFragmentManager.findFragmentByTag(name); if (fragment != null) { if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment); mCurTransaction.attach(fragment); } else { fragment = getItem(position); if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment); // mCurTransaction.add(container.getId(), fragment, // makeFragmentName(container.getId(), itemId)); if (!fragment.isAdded()) mCurTransaction.add(container.getId(), fragment, getTag(position)); else mCurTransaction.show(fragment); } if (fragment != mCurrentPrimaryItem) { fragment.setMenuVisibility(false); fragment.setUserVisibleHint(false); } return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } if (DEBUG) Log.v(TAG, "Detaching item #" + getItemId(position) + ": f=" + object + " v=" + ((Fragment) object).getView()); mCurTransaction.detach((Fragment) object); } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { Fragment fragment = (Fragment) object; if (fragment != mCurrentPrimaryItem) { if (mCurrentPrimaryItem != null) { mCurrentPrimaryItem.setMenuVisibility(false); mCurrentPrimaryItem.setUserVisibleHint(false); } if (fragment != null) { fragment.setMenuVisibility(true); fragment.setUserVisibleHint(true); } mCurrentPrimaryItem = fragment; } } @Override public void finishUpdate(ViewGroup container) { if (mCurTransaction != null) { mCurTransaction.commitAllowingStateLoss(); mCurTransaction = null; mFragmentManager.executePendingTransactions(); } } @Override public boolean isViewFromObject(View view, Object object) { return ((Fragment) object).getView() == view; } @Override public Parcelable saveState() { return null; } @Override public void restoreState(Parcelable state, ClassLoader loader) { } /** * Return a unique identifier for the item at the given position. * <p/> * <p> * The default implementation returns the given position. Subclasses should override this method * if the positions of items can change. * </p> * * @param position Position within this adapter * @return Unique identifier for the item at position */ public long getItemId(int position) { return position; } private static String makeFragmentName(int viewId, long id) { return "android:switcher:" + viewId + ":" + id; } protected abstract String getTag(int position); }
gpl-3.0
1ukash/eucalyptus-fork-2.0
clc/modules/storage-controller/src/main/java/com/eucalyptus/storage/BlockStorageChecker.java
10387
/******************************************************************************* *Copyright (c) 2009 Eucalyptus Systems, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, only version 3 of the License. * * * This file is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * * Please contact Eucalyptus Systems, Inc., 130 Castilian * Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/> * if you need additional information or have any questions. * * This file may incorporate work covered under the following copyright and * permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software in source and binary forms, with * or without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. USERS OF * THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE * LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS * SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA * BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN * THE REGENTS’ DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT * OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR * WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH * ANY SUCH LICENSES OR RIGHTS. *******************************************************************************/ /* * * Author: Sunil Soman sunils@cs.ucsb.edu */ package com.eucalyptus.storage; import java.io.File; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.log4j.Logger; import com.eucalyptus.entities.EntityWrapper; import com.eucalyptus.util.EucalyptusCloudException; import com.eucalyptus.util.StorageProperties; import edu.ucsb.eucalyptus.cloud.entities.SnapshotInfo; import edu.ucsb.eucalyptus.cloud.entities.VolumeInfo; import edu.ucsb.eucalyptus.cloud.ws.HttpWriter; import edu.ucsb.eucalyptus.cloud.ws.SnapshotProgressCallback; public class BlockStorageChecker { private static Logger LOG = Logger.getLogger(BlockStorageChecker.class); private LogicalStorageManager blockManager; private static boolean transferredPending = false; public BlockStorageChecker(LogicalStorageManager blockManager) { this.blockManager = blockManager; } public void startupChecks() { new StartupChecker().start(); } private class StartupChecker extends Thread { public StartupChecker() {} public void run() { try { cleanup(); } catch (EucalyptusCloudException e) { LOG.error("Startup cleanup failed", e); } blockManager.startupChecks(); } } public void cleanup() throws EucalyptusCloudException { cleanVolumes(); cleanSnapshots(); } public void cleanVolumes() { cleanStuckVolumes(); cleanFailedVolumes(); } public void cleanSnapshots() { cleanStuckSnapshots(); cleanFailedSnapshots(); } public void cleanStuckVolumes() { EntityWrapper<VolumeInfo> db = StorageProperties.getEntityWrapper(); VolumeInfo volumeInfo = new VolumeInfo(); volumeInfo.setStatus(StorageProperties.Status.creating.toString()); List<VolumeInfo> volumeInfos = db.query(volumeInfo); for(VolumeInfo volInfo : volumeInfos) { String volumeId = volInfo.getVolumeId(); LOG.info("Cleaning failed volume " + volumeId); blockManager.cleanVolume(volumeId); db.delete(volInfo); } db.commit(); } public void cleanFailedVolumes() { EntityWrapper<VolumeInfo> db = StorageProperties.getEntityWrapper(); VolumeInfo volumeInfo = new VolumeInfo(); volumeInfo.setStatus(StorageProperties.Status.failed.toString()); List<VolumeInfo> volumeInfos = db.query(volumeInfo); for(VolumeInfo volInfo : volumeInfos) { String volumeId = volInfo.getVolumeId(); LOG.info("Cleaning failed volume " + volumeId); blockManager.cleanVolume(volumeId); db.delete(volInfo); } db.commit(); } public void cleanFailedVolume(String volumeId) { EntityWrapper<VolumeInfo> db = StorageProperties.getEntityWrapper(); VolumeInfo volumeInfo = new VolumeInfo(volumeId); List<VolumeInfo> volumeInfos = db.query(volumeInfo); if(volumeInfos.size() > 0) { VolumeInfo volInfo = volumeInfos.get(0); LOG.info("Cleaning failed volume " + volumeId); blockManager.cleanVolume(volumeId); db.delete(volInfo); } db.commit(); } public void cleanStuckSnapshots() { EntityWrapper<SnapshotInfo> db = StorageProperties.getEntityWrapper(); SnapshotInfo snapshotInfo = new SnapshotInfo(); snapshotInfo.setStatus(StorageProperties.Status.creating.toString()); List<SnapshotInfo> snapshotInfos = db.query(snapshotInfo); for(SnapshotInfo snapInfo : snapshotInfos) { String snapshotId = snapInfo.getSnapshotId(); LOG.info("Cleaning failed snapshot " + snapshotId); blockManager.cleanSnapshot(snapshotId); db.delete(snapInfo); } db.commit(); } public void cleanFailedSnapshots() { EntityWrapper<SnapshotInfo> db = StorageProperties.getEntityWrapper(); SnapshotInfo snapshotInfo = new SnapshotInfo(); snapshotInfo.setStatus(StorageProperties.Status.failed.toString()); List<SnapshotInfo> snapshotInfos = db.query(snapshotInfo); for(SnapshotInfo snapInfo : snapshotInfos) { String snapshotId = snapInfo.getSnapshotId(); LOG.info("Cleaning failed snapshot " + snapshotId); blockManager.cleanSnapshot(snapshotId); db.delete(snapInfo); } db.commit(); } public void cleanFailedSnapshot(String snapshotId) { EntityWrapper<SnapshotInfo> db = StorageProperties.getEntityWrapper(); SnapshotInfo snapshotInfo = new SnapshotInfo(snapshotId); List<SnapshotInfo> snapshotInfos = db.query(snapshotInfo); if(snapshotInfos.size() > 0) { SnapshotInfo snapInfo = snapshotInfos.get(0); LOG.info("Cleaning failed snapshot " + snapshotId); blockManager.cleanSnapshot(snapshotId); db.delete(snapInfo); } db.commit(); } public void transferPendingSnapshots() throws EucalyptusCloudException { if(!transferredPending) { SnapshotTransfer transferrer = new SnapshotTransfer(this); transferrer.start(); transferredPending = true; } } public static void checkWalrusConnection() { HttpClient httpClient = new HttpClient(); GetMethod getMethod = null; try { java.net.URI addrUri = new URL(StorageProperties.WALRUS_URL).toURI(); String addrPath = addrUri.getPath(); String addr = StorageProperties.WALRUS_URL.replaceAll(addrPath, ""); getMethod = new GetMethod(addr); httpClient.executeMethod(getMethod); StorageProperties.enableSnapshots = true; } catch(Exception ex) { LOG.error("Could not connect to Walrus. Snapshot functionality disabled. Please check the Walrus url."); StorageProperties.enableSnapshots = false; } finally { if(getMethod != null) getMethod.releaseConnection(); } } private class SnapshotTransfer extends Thread { private BlockStorageChecker checker; public SnapshotTransfer(final BlockStorageChecker checker) { this.checker = checker; } public void run() { EntityWrapper<SnapshotInfo> db = StorageProperties.getEntityWrapper(); SnapshotInfo snapshotInfo = new SnapshotInfo(); snapshotInfo.setShouldTransfer(true); List<SnapshotInfo> snapshotInfos = db.query(snapshotInfo); if(snapshotInfos.size() > 0) { SnapshotInfo snapInfo = snapshotInfos.get(0); String snapshotId = snapInfo.getSnapshotId(); List<String> returnValues; try { returnValues = blockManager.prepareForTransfer(snapshotId); } catch (EucalyptusCloudException e) { db.rollback(); LOG.error(e); return; } if(returnValues.size() > 0) { String snapshotFileName = returnValues.get(0); File snapshotFile = new File(snapshotFileName); Map<String, String> httpParamaters = new HashMap<String, String>(); HttpWriter httpWriter; SnapshotProgressCallback callback = new SnapshotProgressCallback(snapshotId, snapshotFile.length(), StorageProperties.TRANSFER_CHUNK_SIZE); httpWriter = new HttpWriter("PUT", snapshotFile, String.valueOf(snapshotFile.length()), callback, "snapset-" + UUID.randomUUID(), snapshotId, "StoreSnapshot", null, httpParamaters); try { httpWriter.run(); } catch(Exception ex) { db.rollback(); LOG.error(ex, ex); checker.cleanFailedSnapshot(snapshotId); } } } db.commit(); } } }
gpl-3.0
tang7526/l1j-client
src/analyzer/src/types/UChar8.java
2984
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * http://www.gnu.org/copyleft/gpl.html */ package types; public class UChar8 { /** * Converts a 32 bit unsigned/signed long array to a 8 bit unsigned char * array. * * @param buff * the array to convert * @return char[] an 8 bit unsigned char array */ public static char[] fromArray(long[] buff) { char[] charBuff = new char[buff.length * 4]; for (int i = 0; i < buff.length; ++i) { charBuff[(i * 4) + 0] = (char) (buff[i] & 0xFF); charBuff[(i * 4) + 1] = (char) ((buff[i] >> 8) & 0xFF); charBuff[(i * 4) + 2] = (char) ((buff[i] >> 16) & 0xFF); charBuff[(i * 4) + 3] = (char) ((buff[i] >> 24) & 0xFF); } return charBuff; } /** * Converts an 8 bit unsigned byte array to an 8 bit unsigned char array. * * @param buff * the array to convert * @return char[] an 8 bit unsigned char array */ public static char[] fromArray(byte[] buff) { char[] charBuff = new char[buff.length]; for (int i = 0; i < buff.length; ++i) { charBuff[i] = (char) (buff[i] & 0xFF); } return charBuff; } /** * Converts an 8 bit unsigned byte array to an 8 bit unsigned char array. * * @param buff * the array to convert length the array size * @return char[] an 8 bit unsigned char array */ public static char[] fromArray(byte[] buff, int length) { char[] charBuff = new char[length]; for (int i = 0; i < length; ++i) { charBuff[i] = (char) (buff[i] & 0xFF); } return charBuff; } /** * Converts an 8 bit unsigned byte to an 8 bit unsigned char. * * @param b * the byte value to convert * @return char an 8 bit unsigned char */ public static char fromUByte8(byte b) { return (char) (b & 0xFF); } /** * Converts a 32 bit unsigned long to an 8 bit unsigned char. * * @param l * the long value to convert * @return char an 8 bit unsigned char */ public static char[] fromULong32(long l) { char[] charBuff = new char[4]; charBuff[0] = (char) (l & 0xFF); charBuff[1] = (char) ((l >> 8) & 0xFF); charBuff[2] = (char) ((l >> 16) & 0xFF); charBuff[3] = (char) ((l >> 24) & 0xFF); return charBuff; } }
gpl-3.0
SmithsModding/Tiny-Storage
src/main/java/com/smithsmodding/tinystorage/common/item/block/ItemBlockClayChestSmall.java
1671
package com.smithsmodding.tinystorage.common.item.block; import java.util.List; import com.smithsmodding.tinystorage.common.block.storage.chests.BlockClayChest; import com.smithsmodding.tinystorage.common.reference.References; import com.smithsmodding.tinystorage.common.reference.Messages; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemBlockClayChestSmall extends ItemBlock { public ItemBlockClayChestSmall(Block block) { super(block); this.setHasSubtypes(true); } @Override public String getUnlocalizedName(ItemStack stack) { int i = MathHelper.clamp_int(stack.getItemDamage(), 0, 15); return super.getUnlocalizedName() + References.dyes[i]; } @Override public int getMetadata(int meta) { return meta; } @SideOnly(Side.CLIENT) public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean flag) { //noinspection unchecked list.add(StatCollector.translateToLocal(Messages.ItemTooltips.BLOCK_SMALL)); if (Block.getBlockFromItem(itemStack.getItem()) != Blocks.air && Block.getBlockFromItem(itemStack.getItem()) instanceof BlockClayChest) { BlockClayChest block = (BlockClayChest) Block.getBlockFromItem(itemStack.getItem()); if (block.getIsLockable()) { //noinspection unchecked list.add(StatCollector.translateToLocal(Messages.ItemTooltips.BLOCK_LOCKED)); } } } }
gpl-3.0
FreekDB/transmartApp
src/java/com/recomdata/util/genego/JobResult.java
7820
/************************************************************************* * tranSMART - translational medicine data mart * * Copyright 2008-2012 Janssen Research & Development, LLC. * * This product includes software developed at Janssen Research & Development, LLC. * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License * as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version, along with the following terms: * 1. You may convey a work based on this program in accordance with section 5, provided that you retain the above notices. * 2. You may convey verbatim copies of this program code as you receive it, in any medium, provided that you retain the above notices. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. * * ******************************************************************/ /** * JobResult.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.recomdata.util.genego; public class JobResult implements java.io.Serializable { private java.lang.String id; private java.lang.String name; private java.lang.String progress; private java.lang.String status; public JobResult() { } public JobResult( java.lang.String id, java.lang.String name, java.lang.String progress, java.lang.String status) { this.id = id; this.name = name; this.progress = progress; this.status = status; } /** * Gets the id value for this JobResult. * * @return id */ public java.lang.String getId() { return id; } /** * Sets the id value for this JobResult. * * @param id */ public void setId(java.lang.String id) { this.id = id; } /** * Gets the name value for this JobResult. * * @return name */ public java.lang.String getName() { return name; } /** * Sets the name value for this JobResult. * * @param name */ public void setName(java.lang.String name) { this.name = name; } /** * Gets the progress value for this JobResult. * * @return progress */ public java.lang.String getProgress() { return progress; } /** * Sets the progress value for this JobResult. * * @param progress */ public void setProgress(java.lang.String progress) { this.progress = progress; } /** * Gets the status value for this JobResult. * * @return status */ public java.lang.String getStatus() { return status; } /** * Sets the status value for this JobResult. * * @param status */ public void setStatus(java.lang.String status) { this.status = status; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof JobResult)) return false; JobResult other = (JobResult) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.id==null && other.getId()==null) || (this.id!=null && this.id.equals(other.getId()))) && ((this.name==null && other.getName()==null) || (this.name!=null && this.name.equals(other.getName()))) && ((this.progress==null && other.getProgress()==null) || (this.progress!=null && this.progress.equals(other.getProgress()))) && ((this.status==null && other.getStatus()==null) || (this.status!=null && this.status.equals(other.getStatus()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getId() != null) { _hashCode += getId().hashCode(); } if (getName() != null) { _hashCode += getName().hashCode(); } if (getProgress() != null) { _hashCode += getProgress().hashCode(); } if (getStatus() != null) { _hashCode += getStatus().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(JobResult.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("SOAP/MetaCore", "JobResult")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("id"); elemField.setXmlName(new javax.xml.namespace.QName("", "id")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("name"); elemField.setXmlName(new javax.xml.namespace.QName("", "name")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("progress"); elemField.setXmlName(new javax.xml.namespace.QName("", "progress")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("status"); elemField.setXmlName(new javax.xml.namespace.QName("", "status")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
gpl-3.0
xitongzou/cardforge
src/forge/gui/input/Input_PayManaCost.java
6294
package forge.gui.input; import forge.*; import forge.card.mana.ManaCost; import forge.card.spellability.SpellAbility; //pays the cost of a card played from the player's hand //the card is removed from the players hand if the cost is paid //CANNOT be used for ABILITIES /** * <p>Input_PayManaCost class.</p> * * @author Forge * @version $Id: $ */ public class Input_PayManaCost extends Input { // anything that uses this should be converted to Ability_Cost /** Constant <code>serialVersionUID=3467312982164195091L</code> */ private static final long serialVersionUID = 3467312982164195091L; private final String originalManaCost; private final Card originalCard; public ManaCost manaCost; private final SpellAbility spell; private boolean skipStack; private int phyLifeToLose = 0; /** * <p>Constructor for Input_PayManaCost.</p> * * @param sa a {@link forge.card.spellability.SpellAbility} object. * @param noStack a boolean. */ public Input_PayManaCost(SpellAbility sa, boolean noStack) { skipStack = noStack; originalManaCost = sa.getManaCost(); // Change originalCard = sa.getSourceCard(); spell = sa; if (Phase.getGameBegins() == 1) { if (sa.getSourceCard().isCopiedSpell() && sa.isSpell()) { if (spell.getAfterPayMana() != null) stopSetNext(spell.getAfterPayMana()); else { manaCost = new ManaCost("0"); AllZone.getStack().add(spell); } } else { manaCost = AllZone.getGameAction().getSpellCostChange(sa, new ManaCost(originalManaCost)); } } else { manaCost = new ManaCost(sa.getManaCost()); } } /** * <p>Constructor for Input_PayManaCost.</p> * * @param sa a {@link forge.card.spellability.SpellAbility} object. */ public Input_PayManaCost(SpellAbility sa) { originalManaCost = sa.getManaCost(); // Change originalCard = sa.getSourceCard(); spell = sa; if (Phase.getGameBegins() == 1) { if (sa.getSourceCard().isCopiedSpell() && sa.isSpell()) { if (spell.getAfterPayMana() != null) stopSetNext(spell.getAfterPayMana()); else { manaCost = new ManaCost("0"); AllZone.getStack().add(spell); } } else { manaCost = AllZone.getGameAction().getSpellCostChange(sa, new ManaCost(originalManaCost)); } } else { manaCost = new ManaCost(sa.getManaCost()); } } /** * <p>resetManaCost.</p> */ private void resetManaCost() { manaCost = new ManaCost(originalManaCost); phyLifeToLose = 0; } /** {@inheritDoc} */ @Override public void selectCard(Card card, PlayerZone zone) { //this is a hack, to prevent lands being able to use mana to pay their own abilities from cards like //Kher Keep, Pendelhaven, Blinkmoth Nexus, and Mikokoro, Center of the Sea, .... if (originalCard.equals(card) && spell.isTapAbility()) { // I'm not sure if this actually prevents anything that wouldn't be handled by canPlay below return; } manaCost = Input_PayManaCostUtil.activateManaAbility(spell, card, manaCost); // only show message if this is the active input if (AllZone.getInputControl().getInput() == this) showMessage(); if (manaCost.isPaid()) { originalCard.setSunburstValue(manaCost.getSunburst()); done(); } } /** {@inheritDoc} */ @Override public void selectPlayer(Player player) { if (player.isHuman()) { if (manaCost.payPhyrexian()) { phyLifeToLose += 2; } showMessage(); } } /** * <p>done.</p> */ private void done() { if (phyLifeToLose > 0) AllZone.getHumanPlayer().payLife(phyLifeToLose, originalCard); if (spell.getSourceCard().isCopiedSpell()) { if (spell.getAfterPayMana() != null) { stopSetNext(spell.getAfterPayMana()); } else AllZone.getInputControl().resetInput(); } else { AllZone.getManaPool().clearPay(spell, false); resetManaCost(); // if tap ability, tap card if (spell.isTapAbility()) originalCard.tap(); if (spell.isUntapAbility()) originalCard.untap(); // if this is a spell, move it to the Stack ZOne if (spell.isSpell()) // already checked for if its a copy AllZone.getGameAction().moveToStack(originalCard); if (spell.getAfterPayMana() != null) stopSetNext(spell.getAfterPayMana()); else { if (skipStack) { spell.resolve(); } else { AllZone.getStack().add(spell); } AllZone.getInputControl().resetInput(); } } } /** {@inheritDoc} */ @Override public void selectButtonCancel() { resetManaCost(); AllZone.getManaPool().unpaid(spell, true); AllZone.getHumanBattlefield().updateObservers();//DO NOT REMOVE THIS, otherwise the cards don't always tap stop(); } /** {@inheritDoc} */ @Override public void showMessage() { ButtonUtil.enableOnlyCancel(); StringBuilder msg = new StringBuilder("Pay Mana Cost: " + manaCost.toString()); if (phyLifeToLose > 0) { msg.append(" ("); msg.append(phyLifeToLose); msg.append(" life paid for phyrexian mana)"); } if (manaCost.containsPhyrexianMana()) { msg.append("\n(Click on your life total to pay life for phyrexian mana.)"); } AllZone.getDisplay().showMessage(msg.toString()); if (manaCost.isPaid() && !new ManaCost(originalManaCost).isPaid()) { originalCard.setSunburstValue(manaCost.getSunburst()); done(); } } }
gpl-3.0
Vallant/design-patterns-study
src/monolithic/src/exception/ElementInsertFailedException.java
190
package exception; /** * Created by stephan on 06/07/17. */ class ElementInsertFailedException extends Exception { public ElementInsertFailedException(String s) { super(s); } }
gpl-3.0
schemaanalyst/schemaanalyst
src/main/java/org/schemaanalyst/mutation/mutator/ListElementAdder.java
1452
package org.schemaanalyst.mutation.mutator; import org.schemaanalyst.mutation.supplier.Supplier; import org.schemaanalyst.util.tuple.Pair; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * <p> * Given a list of elements and a list of alternative elements, this mutator * returns mutants with each alternative element added to the list in turn. * </p> * * @author Phil McMinn * * @param <A> The artefact type * @param <E> The element type */ public class ListElementAdder<A, E> extends Mutator<A, Pair<List<E>>> { private List<E> elements; private List<E> alternatives; private Iterator<E> iterator; private String mutationDescription; public ListElementAdder(Supplier<A, Pair<List<E>>> supplier) { super(supplier); } @Override protected void initialise(Pair<List<E>> pair) { this.elements = pair.getFirst(); this.alternatives = pair.getSecond(); iterator = alternatives.iterator(); } @Override protected boolean isMoreMutationToDo() { return iterator.hasNext(); } @Override protected Pair<List<E>> performMutation(Pair<List<E>> componentToMutate) { E elementToAdd = iterator.next(); mutationDescription = "Added " + elementToAdd; List<E> mutatedElements = new ArrayList<>(elements); mutatedElements.add(elementToAdd); return new Pair<>(mutatedElements, null); } @Override protected String getDescriptionOfLastMutation() { return mutationDescription; } }
gpl-3.0
pillarone/risk-analytics-application
src/groovy/org/pillarone/riskanalytics/application/document/IShowDocumentStrategy.java
173
package org.pillarone.riskanalytics.application.document; public interface IShowDocumentStrategy { void showDocument(String name, byte[] content, String mimeType); }
gpl-3.0
chip/rhodes
platform/android/Rhodes/src/com/rhomobile/rhodes/ui/LogOptionsDialog.java
2297
package com.rhomobile.rhodes.ui; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import com.rho.RhoLogger; import com.rhomobile.rhodes.AndroidR; public class LogOptionsDialog extends Dialog implements OnClickListener { private Button saveButton; private Button closeButton; private Spinner logLevel; private EditText includeClasses; private EditText excludeClasses; public LogOptionsDialog(Context context) { super(context); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); getWindow().requestFeature(Window.FEATURE_NO_TITLE); setContentView(AndroidR.layout.logoptions); saveButton = (Button) findViewById(AndroidR.id.logoptsSaveButton); closeButton = (Button) findViewById(AndroidR.id.logoptsCloseButton); saveButton.setOnClickListener(this); closeButton.setOnClickListener(this); includeClasses = (EditText) this.findViewById(AndroidR.id.includeClasses); includeClasses.setText( RhoLogger.getLogConf().getEnabledCategories() ); excludeClasses = (EditText) this.findViewById(AndroidR.id.excludeClasses); excludeClasses.setText( RhoLogger.getLogConf().getDisabledCategories() ); logLevel = (Spinner) this.findViewById(AndroidR.id.loglevel); ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_spinner_item, new String[] { "Trace","Info","Warning","Error" }); logLevel.setAdapter(spinnerArrayAdapter); logLevel.setSelection( RhoLogger.getLogConf().getMinSeverity() ); } public void onClick(View view) { switch (view.getId()) { case AndroidR.id.logoptsSaveButton: RhoLogger.getLogConf().setMinSeverity(logLevel.getSelectedItemPosition()); RhoLogger.getLogConf().setEnabledCategories(includeClasses.getText().toString()); RhoLogger.getLogConf().setDisabledCategories(excludeClasses.getText().toString()); RhoLogger.getLogConf().saveToFile(); dismiss(); break; case AndroidR.id.logoptsCloseButton: cancel(); break; } } }
gpl-3.0
whilkes/realm-platform
security/src/main/java/net/realmproject/platform/security/authorization/authorizers/HttpMethod.java
774
package net.realmproject.platform.security.authorization.authorizers; import java.util.Collections; import java.util.List; import net.objectof.corc.Action; import net.objectof.corc.web.v2.HttpRequest; import net.realmproject.platform.schema.Person; public class HttpMethod extends AbstractAuthorizer { private List<String> methods; public HttpMethod(String method) { this(Collections.singletonList(method)); } public HttpMethod(List<String> methods) { this.methods = methods; } @Override public boolean authorize(Action action, HttpRequest request, Person person) { String httpMethod = request.getHttpRequest().getMethod(); if (methods.contains(httpMethod)) return true; return false; } }
gpl-3.0
LedgerHQ/GreenBits
app/src/main/java/com/greenaddress/greenapi/Output.java
1302
package com.greenaddress.greenapi; import java.util.Map; public class Output { private Integer subaccount; private Integer pointer; private Integer branch; private String value; private String script; public Output(final Map<?, ?> values) { this.setSubaccount((Integer) values.get("subaccount")); this.setPointer((Integer) values.get("pointer")); this.setBranch((Integer) values.get("branch")); this.setValue((String) values.get("value")); this.setScript((String) values.get("script")); } public Integer getSubaccount() { return subaccount; } public void setSubaccount(Integer subaccount) { this.subaccount = subaccount; } public Integer getPointer() { return pointer; } public void setPointer(Integer pointer) { this.pointer = pointer; } public Integer getBranch() { return branch; } public void setBranch(Integer branch) { this.branch = branch; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getScript() { return script; } public void setScript(String script) { this.script = script; } }
gpl-3.0
sosandstrom/ricotta
ricotta-ost/src/main/java/com/wadpam/ricotta/dao/AppUserDao.java
505
package com.wadpam.ricotta.dao; import com.google.appengine.api.datastore.Key; /** * Business Methods interface for entity AppUser. * This interface is generated by mardao, but edited by developers. * It is not overwritten by the generator once it exists. * * Generated on 2011-09-07T19:26:50.791+0700. * @author mardao DAO generator (net.sf.mardao.plugin.ProcessDomainMojo) */ public interface AppUserDao extends GeneratedAppUserDao<Key, Key> { // TODO: declare your Business Methods here }
gpl-3.0
INTechSenpai/moon-rover
pc/src/threads/ThreadService.java
883
/* * Copyright (C) 2013-2017 Pierre-François Gimenez * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package threads; import container.Service; /** * Une sur-classe pratique pour typer * * @author pf * */ public abstract class ThreadService extends Thread implements Service {}
gpl-3.0
softwareanimal/TextSecure-WinterBreak2015
src/org/thoughtcrime/securesms/ApplicationPreferencesActivity.java
13250
/** * Copyright (C) 2011 Whisper Systems * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.thoughtcrime.securesms; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.preference.PreferenceFragment; import android.util.Log; import android.widget.Toast; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.preferences.AdvancedPreferenceFragment; import org.thoughtcrime.securesms.preferences.AppProtectionPreferenceFragment; import org.thoughtcrime.securesms.preferences.AppearancePreferenceFragment; import org.thoughtcrime.securesms.preferences.NotificationsPreferenceFragment; import org.thoughtcrime.securesms.preferences.SmsMmsPreferenceFragment; import org.thoughtcrime.securesms.preferences.StoragePreferenceFragment; import org.thoughtcrime.securesms.push.TextSecureCommunicationFactory; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.util.Dialogs; import org.thoughtcrime.securesms.util.DynamicLanguage; import org.thoughtcrime.securesms.util.DynamicTheme; import org.thoughtcrime.securesms.util.MemoryCleaner; import org.thoughtcrime.securesms.util.ProgressDialogAsyncTask; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.whispersystems.libaxolotl.util.guava.Optional; import org.whispersystems.textsecure.api.TextSecureAccountManager; import org.whispersystems.textsecure.api.push.exceptions.AuthorizationFailedException; import java.io.IOException; /** * The Activity for application preference display and management. * * @author Moxie Marlinspike * */ public class ApplicationPreferencesActivity extends PassphraseRequiredActionBarActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String TAG = ApplicationPreferencesActivity.class.getSimpleName(); private static final String PREFERENCE_CATEGORY_SMS_MMS = "preference_category_sms_mms"; private static final String PREFERENCE_CATEGORY_NOTIFICATIONS = "preference_category_notifications"; private static final String PREFERENCE_CATEGORY_APP_PROTECTION = "preference_category_app_protection"; private static final String PREFERENCE_CATEGORY_APPEARANCE = "preference_category_appearance"; private static final String PREFERENCE_CATEGORY_STORAGE = "preference_category_storage"; private static final String PREFERENCE_CATEGORY_ADVANCED = "preference_category_advanced"; private static final String PUSH_MESSAGING_PREF = "pref_toggle_push_messaging"; private final DynamicTheme dynamicTheme = new DynamicTheme(); private final DynamicLanguage dynamicLanguage = new DynamicLanguage(); @Override protected void onCreate(Bundle icicle) { dynamicTheme.onCreate(this); dynamicLanguage.onCreate(this); super.onCreate(icicle); this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); Fragment fragment = new ApplicationPreferenceFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(android.R.id.content, fragment); fragmentTransaction.commit(); } @Override public void onResume() { super.onResume(); dynamicTheme.onResume(this); dynamicLanguage.onResume(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Fragment fragment = getSupportFragmentManager().findFragmentById(android.R.id.content); fragment.onActivityResult(requestCode, resultCode, data); } @Override public boolean onSupportNavigateUp() { FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); } else { Intent intent = new Intent(this, ConversationListActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } return true; } @Override public void onDestroy() { MemoryCleaner.clean((MasterSecret) getIntent().getParcelableExtra("master_secret")); super.onDestroy(); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(TextSecurePreferences.THEME_PREF)) { dynamicTheme.onResume(this); } else if (key.equals(TextSecurePreferences.LANGUAGE_PREF)) { dynamicLanguage.onResume(this); Intent intent = new Intent(this, KeyCachingService.class); intent.setAction(KeyCachingService.LOCALE_CHANGE_EVENT); startService(intent); } } public static class ApplicationPreferenceFragment extends PreferenceFragment { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.preferences); initializePushMessagingToggle(); this.findPreference(PREFERENCE_CATEGORY_SMS_MMS) .setOnPreferenceClickListener(new CategoryClickListener(PREFERENCE_CATEGORY_SMS_MMS)); this.findPreference(PREFERENCE_CATEGORY_NOTIFICATIONS) .setOnPreferenceClickListener(new CategoryClickListener(PREFERENCE_CATEGORY_NOTIFICATIONS)); this.findPreference(PREFERENCE_CATEGORY_APP_PROTECTION) .setOnPreferenceClickListener(new CategoryClickListener(PREFERENCE_CATEGORY_APP_PROTECTION)); this.findPreference(PREFERENCE_CATEGORY_APPEARANCE) .setOnPreferenceClickListener(new CategoryClickListener(PREFERENCE_CATEGORY_APPEARANCE)); this.findPreference(PREFERENCE_CATEGORY_STORAGE) .setOnPreferenceClickListener(new CategoryClickListener(PREFERENCE_CATEGORY_STORAGE)); this.findPreference(PREFERENCE_CATEGORY_ADVANCED) .setOnPreferenceClickListener(new CategoryClickListener(PREFERENCE_CATEGORY_ADVANCED)); } @Override public void onResume() { super.onResume(); ((ApplicationPreferencesActivity) getActivity()).getSupportActionBar().setTitle(R.string.text_secure_normal__menu_settings); setCategorySummaries(); } private void setCategorySummaries() { this.findPreference(PREFERENCE_CATEGORY_SMS_MMS) .setSummary(SmsMmsPreferenceFragment.getSummary(getActivity())); this.findPreference(PREFERENCE_CATEGORY_NOTIFICATIONS) .setSummary(NotificationsPreferenceFragment.getSummary(getActivity())); this.findPreference(PREFERENCE_CATEGORY_APP_PROTECTION) .setSummary(AppProtectionPreferenceFragment.getSummary(getActivity())); this.findPreference(PREFERENCE_CATEGORY_APPEARANCE) .setSummary(AppearancePreferenceFragment.getSummary(getActivity())); this.findPreference(PREFERENCE_CATEGORY_STORAGE) .setSummary(StoragePreferenceFragment.getSummary(getActivity())); } private class CategoryClickListener implements Preference.OnPreferenceClickListener { private String category; public CategoryClickListener(String category) { this.category = category; } @Override public boolean onPreferenceClick(Preference preference) { Fragment fragment; switch (category) { case PREFERENCE_CATEGORY_SMS_MMS: fragment = new SmsMmsPreferenceFragment(); break; case PREFERENCE_CATEGORY_NOTIFICATIONS: fragment = new NotificationsPreferenceFragment(); break; case PREFERENCE_CATEGORY_APP_PROTECTION: fragment = new AppProtectionPreferenceFragment(); break; case PREFERENCE_CATEGORY_APPEARANCE: fragment = new AppearancePreferenceFragment(); break; case PREFERENCE_CATEGORY_STORAGE: fragment = new StoragePreferenceFragment(); break; case PREFERENCE_CATEGORY_ADVANCED: fragment = new AdvancedPreferenceFragment(); break; default: throw new AssertionError(); } FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(android.R.id.content, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); return true; } } private void initializePushMessagingToggle() { CheckBoxPreference preference = (CheckBoxPreference)this.findPreference(PUSH_MESSAGING_PREF); preference.setChecked(TextSecurePreferences.isPushRegistered(getActivity())); preference.setOnPreferenceChangeListener(new PushMessagingClickListener()); } private class PushMessagingClickListener implements Preference.OnPreferenceChangeListener { private static final int SUCCESS = 0; private static final int NETWORK_ERROR = 1; private class DisablePushMessagesTask extends ProgressDialogAsyncTask<Void, Void, Integer> { private final CheckBoxPreference checkBoxPreference; public DisablePushMessagesTask(final CheckBoxPreference checkBoxPreference) { super(getActivity(), R.string.ApplicationPreferencesActivity_unregistering, R.string.ApplicationPreferencesActivity_unregistering_for_data_based_communication); this.checkBoxPreference = checkBoxPreference; } @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); switch (result) { case NETWORK_ERROR: Toast.makeText(getActivity(), R.string.ApplicationPreferencesActivity_error_connecting_to_server, Toast.LENGTH_LONG).show(); break; case SUCCESS: checkBoxPreference.setChecked(false); TextSecurePreferences.setPushRegistered(getActivity(), false); break; } } @Override protected Integer doInBackground(Void... params) { try { Context context = getActivity(); TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(context); accountManager.setGcmId(Optional.<String>absent()); GoogleCloudMessaging.getInstance(context).unregister(); return SUCCESS; } catch (AuthorizationFailedException afe) { Log.w(TAG, afe); return SUCCESS; } catch (IOException ioe) { Log.w(TAG, ioe); return NETWORK_ERROR; } } } @Override public boolean onPreferenceChange(final Preference preference, Object newValue) { if (((CheckBoxPreference)preference).isChecked()) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(Dialogs.resolveIcon(getActivity(), R.attr.dialog_info_icon)); builder.setTitle(R.string.ApplicationPreferencesActivity_disable_push_messages); builder.setMessage(R.string.ApplicationPreferencesActivity_this_will_disable_push_messages); builder.setNegativeButton(android.R.string.cancel, null); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new DisablePushMessagesTask((CheckBoxPreference)preference).execute(); } }); builder.show(); } else { Intent nextIntent = new Intent(getActivity(), ApplicationPreferencesActivity.class); nextIntent.putExtra("master_secret", getActivity().getIntent().getParcelableExtra("master_secret")); Intent intent = new Intent(getActivity(), RegistrationActivity.class); intent.putExtra("cancel_button", true); intent.putExtra("next_intent", nextIntent); intent.putExtra("master_secret", getActivity().getIntent().getParcelableExtra("master_secret")); startActivity(intent); } return false; } } } }
gpl-3.0
wittawatj/jtcc
src/org/antlr/runtime/ANTLRStringStream.java
6342
/* [The "BSD licence"] Copyright (c) 2005-2008 Terence Parr All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.antlr.runtime; import java.util.ArrayList; import java.util.List; /** A pretty quick CharStream that pulls all data from an array * directly. Every method call counts in the lexer. Java's * strings aren't very good so I'm avoiding. */ public class ANTLRStringStream implements CharStream { /** The data being scanned */ protected char[] data; /** How many characters are actually in the buffer */ protected int n; /** 0..n-1 index into string of next char */ protected int p=0; /** line number 1..n within the input */ protected int line = 1; /** The index of the character relative to the beginning of the line 0..n-1 */ protected int charPositionInLine = 0; /** tracks how deep mark() calls are nested */ protected int markDepth = 0; /** A list of CharStreamState objects that tracks the stream state * values line, charPositionInLine, and p that can change as you * move through the input stream. Indexed from 1..markDepth. * A null is kept @ index 0. Create upon first call to mark(). */ protected List markers; /** Track the last mark() call result value for use in rewind(). */ protected int lastMarker; /** What is name or source of this char stream? */ public String name; public ANTLRStringStream() { } /** Copy data in string to a local char array */ public ANTLRStringStream(String input) { this(); this.data = input.toCharArray(); this.n = input.length(); } /** This is the preferred constructor as no data is copied */ public ANTLRStringStream(char[] data, int numberOfActualCharsInArray) { this(); this.data = data; this.n = numberOfActualCharsInArray; } /** Reset the stream so that it's in the same state it was * when the object was created *except* the data array is not * touched. */ public void reset() { p = 0; line = 1; charPositionInLine = 0; markDepth = 0; } public void consume() { //System.out.println("prev p="+p+", c="+(char)data[p]); if ( p < n ) { charPositionInLine++; if ( data[p]=='\n' ) { /* System.out.println("newline char found on line: "+line+ "@ pos="+charPositionInLine); */ line++; charPositionInLine=0; } p++; //System.out.println("p moves to "+p+" (c='"+(char)data[p]+"')"); } } public int LA(int i) { if ( i==0 ) { return 0; // undefined } if ( i<0 ) { i++; // e.g., translate LA(-1) to use offset i=0; then data[p+0-1] if ( (p+i-1) < 0 ) { return CharStream.EOF; // invalid; no char before first char } } if ( (p+i-1) >= n ) { //System.out.println("char LA("+i+")=EOF; p="+p); return CharStream.EOF; } //System.out.println("char LA("+i+")="+(char)data[p+i-1]+"; p="+p); //System.out.println("LA("+i+"); p="+p+" n="+n+" data.length="+data.length); return data[p+i-1]; } public int LT(int i) { return LA(i); } /** Return the current input symbol index 0..n where n indicates the * last symbol has been read. The index is the index of char to * be returned from LA(1). */ public int index() { return p; } public int size() { return n; } public int mark() { if ( markers==null ) { markers = new ArrayList(); markers.add(null); // depth 0 means no backtracking, leave blank } markDepth++; CharStreamState state = null; if ( markDepth>=markers.size() ) { state = new CharStreamState(); markers.add(state); } else { state = (CharStreamState)markers.get(markDepth); } state.p = p; state.line = line; state.charPositionInLine = charPositionInLine; lastMarker = markDepth; return markDepth; } public void rewind(int m) { CharStreamState state = (CharStreamState)markers.get(m); // restore stream state seek(state.p); line = state.line; charPositionInLine = state.charPositionInLine; release(m); } public void rewind() { rewind(lastMarker); } public void release(int marker) { // unwind any other markers made after m and release m markDepth = marker; // release this marker markDepth--; } /** consume() ahead until p==index; can't just set p=index as we must * update line and charPositionInLine. */ public void seek(int index) { if ( index<=p ) { p = index; // just jump; don't update stream state (line, ...) return; } // seek forward, consume until p hits index while ( p<index ) { consume(); } } public String substring(int start, int stop) { return new String(data,start,stop-start+1); } public int getLine() { return line; } public int getCharPositionInLine() { return charPositionInLine; } public void setLine(int line) { this.line = line; } public void setCharPositionInLine(int pos) { this.charPositionInLine = pos; } public String getSourceName() { return name; } }
gpl-3.0
McrCoderDojo/robocode-codenvy
robots/sample/Fire.java
2000
/** * Copyright (c) 2001-2016 Mathew A. Nelson and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/epl-v10.html */ package sample; import robocode.HitByBulletEvent; import robocode.HitRobotEvent; import robocode.Robot; import robocode.ScannedRobotEvent; import static robocode.util.Utils.normalRelativeAngleDegrees; import java.awt.*; /** * Fire - a sample robot by Mathew Nelson, and maintained. * <p/> * Sits still. Spins gun around. Moves when hit. * * @author Mathew A. Nelson (original) * @author Flemming N. Larsen (contributor) */ public class Fire extends Robot { int dist = 50; // distance to move when we're hit /** * run: Fire's main run function */ public void run() { // Set colors setBodyColor(Color.orange); setGunColor(Color.orange); setRadarColor(Color.red); setScanColor(Color.red); setBulletColor(Color.red); // Spin the gun around slowly... forever while (true) { turnGunRight(5); } } /** * onScannedRobot: Fire! */ public void onScannedRobot(ScannedRobotEvent e) { // If the other robot is close by, and we have plenty of life, // fire hard! if (e.getDistance() < 50 && getEnergy() > 50) { fire(3); } // otherwise, fire 1. else { fire(1); } // Call scan again, before we turn the gun scan(); } /** * onHitByBullet: Turn perpendicular to the bullet, and move a bit. */ public void onHitByBullet(HitByBulletEvent e) { turnRight(normalRelativeAngleDegrees(90 - (getHeading() - e.getHeading()))); ahead(dist); dist *= -1; scan(); } /** * onHitRobot: Aim at it. Fire Hard! */ public void onHitRobot(HitRobotEvent e) { double turnGunAmt = normalRelativeAngleDegrees(e.getBearing() + getHeading() - getGunHeading()); turnGunRight(turnGunAmt); fire(3); } }
gpl-3.0
wzhxyz/ACManager
src/main/java/jskills/elo/EloRating.java
218
package jskills.elo; import jskills.Rating; /** * An Elo rating represented by a single number (mean). */ public class EloRating extends Rating { public EloRating(double rating) { super(rating, 0); } }
gpl-3.0
sugar-lang/compiler
src/org/sugarj/driver/SDFCommands.java
18569
package org.sugarj.driver; import static org.sugarj.common.FileCommands.toCygwinPath; import static org.sugarj.common.Log.log; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.regex.Pattern; import org.spoofax.interpreter.library.IOAgent; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr.client.ITreeBuilder; import org.spoofax.jsglr.client.InvalidParseTableException; import org.spoofax.jsglr.client.ParseTable; import org.spoofax.jsglr.client.SGLR; import org.spoofax.jsglr.shared.SGLRException; import org.spoofax.jsglr.shared.TokenExpectedException; import org.spoofax.terms.Term; import org.strategoxt.HybridInterpreter; import org.strategoxt.imp.metatooling.stratego.SDFBundleCommand; import org.strategoxt.lang.Context; import org.strategoxt.lang.StrategoExit; import org.strategoxt.permissivegrammars.make_permissive; import org.strategoxt.stratego_gpp.box2text_string_0_1; import org.strategoxt.stratego_sdf.pp_sdf_box_0_0; import org.strategoxt.strc.pp_stratego_string_0_0; import org.strategoxt.tools.main_pack_sdf_0_0; import org.sugarj.cleardep.stamp.FileHashStamper; import org.sugarj.cleardep.stamp.Stamp; import org.sugarj.common.ATermCommands; import org.sugarj.common.FileCommands; import org.sugarj.common.FilteringIOAgent; import org.sugarj.common.Log; import org.sugarj.common.path.AbsolutePath; import org.sugarj.common.path.Path; import org.sugarj.common.util.Pair; import org.sugarj.driver.caching.ModuleKey; import org.sugarj.driver.caching.ModuleKeyCache; import org.sugarj.driver.transformations.extraction.extract_sdf_0_0; import org.sugarj.stdlib.StdLib; /** * This class provides methods for various SDF commands. Each * SDF command is represented by a separate method of a similar * name. * * @author Sebastian Erdweg <seba at informatik uni-marburg de> */ public class SDFCommands { public final static boolean USE_PERMISSIVE_GRAMMARS = false; private final static Pattern SDF_FILE_PATTERN = Pattern.compile(".*\\.sdf"); private static ExecutorService parseExecutorService = Executors.newSingleThreadExecutor(); /* * timeout for parsing files (in milliseconds) */ public static long PARSE_TIMEOUT = 10000; static { try { PARSE_TIMEOUT = Long.parseLong(System.getProperty("org.sugarj.parse_timeout")); Log.log.log("set parse timeout to " + PARSE_TIMEOUT, Log.PARSE); } catch (Exception e) { } } private final SGLR sdfParser; private final ModuleKeyCache<Path> sdfCache; private final Environment environment; public SDFCommands(SGLR sdfParser, ModuleKeyCache<Path> sdfCache, Environment environment) { this.sdfParser = sdfParser; this.sdfCache = sdfCache; this.environment = environment; } private static IOAgent packSdfIOAgent = new FilteringIOAgent(Log.PARSE | Log.DETAIL, " including .*"); private static IOAgent sdf2tableIOAgent = new FilteringIOAgent(Log.PARSE | Log.DETAIL, "Invoking native tool .*"); private static IOAgent makePermissiveIOAgent = new FilteringIOAgent(Log.PARSE | Log.DETAIL, "[ make_permissive | info ].*"); private void packSdf( Path sdf, Path def, Collection<Path> paths, List<Path> baseLanguageGrammars, Path baseLanguageDir) throws IOException { /* * We can include as many paths as we want here, checking the * adequacy of the occurring imports is done elsewhere. */ List<String> cmd = new ArrayList<String>(Arrays.asList(new String[]{ "-i", FileCommands.nativePath(sdf.getAbsolutePath()), "-o", FileCommands.nativePath(def.getAbsolutePath()) })); for (Path grammarFile : baseLanguageGrammars) { Map<String, Stamp> map = new HashMap<String, Stamp>(); map.put(grammarFile.getAbsolutePath(), FileHashStamper.instance.stampOf(grammarFile)); ModuleKey key = new ModuleKey(map, ""); Path permissiveGrammar = lookupGrammarInCache(sdfCache, key); if (permissiveGrammar == null) { permissiveGrammar = FileCommands.newTempFile("def"); makePermissive(new AbsolutePath(grammarFile.getAbsolutePath()), permissiveGrammar); permissiveGrammar = cacheParseTable(sdfCache, key, permissiveGrammar, environment); } cmd.add("-Idef"); cmd.add(FileCommands.nativePath(permissiveGrammar.getAbsolutePath())); } cmd.add("-I"); cmd.add(FileCommands.nativePath(baseLanguageDir.getAbsolutePath())); cmd.add("-I"); cmd.add(FileCommands.nativePath(StdLib.stdLibDir.getAbsolutePath())); for (Path path : paths) if (path.getFile().isDirectory()) { cmd.add("-I"); cmd.add(FileCommands.nativePath(path.getAbsolutePath())); } // Pack-sdf requires a fresh context each time, because it caches grammars, which leads to a heap overflow. Context sdfContext = org.strategoxt.tools.tools.init(); try { sdfContext.setIOAgent(packSdfIOAgent); sdfContext.invokeStrategyCLI(main_pack_sdf_0_0.instance, "pack-sdf", cmd.toArray(new String[cmd.size()])); } catch(StrategoExit e) { if (e.getValue() != 0) { throw new RuntimeException(e); } } if (!def.getFile().exists()) throw new RuntimeException("execution of pack-sdf failed"); } private static void sdf2Table(Path def, Path tbl, String module) throws IOException { sdf2Table(def, tbl, module, false); } private static void sdf2Table(Path def, Path tbl, String module, boolean normalize) throws IOException { String[] cmd; if (!normalize) cmd = new String[] { "-i", toCygwinPath(def.getAbsolutePath()), "-o", toCygwinPath(tbl.getAbsolutePath()), "-m", module }; else cmd = new String[] { "-i", toCygwinPath(def.getAbsolutePath()), "-o", toCygwinPath(tbl.getAbsolutePath()), "-m", module, "-n" }; IStrategoTerm termArgs[] = new IStrategoTerm[cmd.length]; for (int i = 0; i < termArgs.length; i++) termArgs[i] = ATermCommands.makeString(cmd[i], null); Context xtcContext = SugarJContexts.xtcContext(); try { xtcContext.setIOAgent(sdf2tableIOAgent); SDFBundleCommand.getInstance().init(); SDFBundleCommand.getInstance().invoke(xtcContext, "sdf2table", termArgs); } finally { SugarJContexts.releaseContext(xtcContext); } if (!tbl.getFile().exists()) throw new RuntimeException("execution of sdf2table failed"); } private static void normalizeTable(Path def, String module) throws IOException { Path tbl = FileCommands.newTempFile("tbl"); sdf2Table(def, tbl, module, true); FileCommands.deleteTempFiles(tbl); } public void check(Path sdf, String module, Collection<Path> paths, List<Path> baseLanguageGrammars, Path baseLanguageDir) throws IOException { Path def = FileCommands.newTempFile("def"); packSdf(sdf, def, paths, baseLanguageGrammars, baseLanguageDir); normalizeTable(def, module); FileCommands.deleteTempFiles(def); } /** * * @return the filename of the compiled .tbl file. * @throws IOException * @throws InvalidParseTableException * @throws SGLRException * @throws TokenExpectedException */ public Path compile(Path sdf, String module, Set<Path> dependentFiles, List<Path> baseLanguageGrammars, Path baseLanguageDir) throws IOException, InvalidParseTableException, TokenExpectedException, SGLRException { ModuleKey key = getModuleKeyForGrammar(sdf, module, dependentFiles); Path tbl = lookupGrammarInCache(sdfCache, key); if (tbl == null) { tbl = generateParseTable(key, sdf, module, environment.getIncludePath(), baseLanguageGrammars, baseLanguageDir); tbl = cacheParseTable(sdfCache, key, tbl, environment); } if (tbl != null) log.log("use generated table " + tbl, Log.CACHING); return tbl; } private static Path cacheParseTable(ModuleKeyCache<Path> sdfCache, ModuleKey key, Path tbl, Environment environment) throws IOException { if (sdfCache == null) return tbl; log.beginTask("Caching", "Cache parse table", Log.CACHING); try { Path cacheTbl = environment.createCachePath(tbl.getFile().getName()); FileCommands.copyFile(tbl, cacheTbl); Path oldTbl = sdfCache.putGet(key, cacheTbl); FileCommands.delete(oldTbl); log.log("Cache Location: " + cacheTbl, Log.CACHING); return cacheTbl; } finally { log.endTask(); } } private static Path lookupGrammarInCache(ModuleKeyCache<Path> sdfCache, ModuleKey key) { if (sdfCache == null) return null; Path result = null; log.beginTask("Searching", "Search parse table in cache", Log.CACHING); try { result = sdfCache.get(key); if (result == null || !result.getFile().exists()) return null; log.log("Cache location: '" + result + "'", Log.CACHING); return result; } finally { log.endTask(result != null); } } private ModuleKey getModuleKeyForGrammar(Path sdf, String module, Set<Path> dependentFiles) throws IOException, InvalidParseTableException, TokenExpectedException, SGLRException { log.beginTask("Generating", "Generate module key for current grammar", Log.CACHING); try { IStrategoTerm aterm = (IStrategoTerm) sdfParser.parse(FileCommands.readFileAsString(sdf), sdf.getAbsolutePath(), "Sdf2Module"); IStrategoTerm imports = ATermCommands.getApplicationSubterm(aterm, "module", 1); IStrategoTerm body = ATermCommands.getApplicationSubterm(aterm, "module", 2); IStrategoTerm term = ATermCommands.makeTuple(imports, body); return new ModuleKey(environment.getStamper(), dependentFiles, environment.getRoot(), SDF_FILE_PATTERN, term); } catch (Exception e) { throw new SGLRException(sdfParser, "could not parse SDF file " + sdf, e); } finally { log.endTask(); } } private Path generateParseTable(ModuleKey key, Path sdf, String module, Collection<Path> paths, List<Path> baseLanguageGrammars, Path baseLanguageDir) throws IOException, InvalidParseTableException { log.beginTask("Generating", "Generate the parse table", Log.PARSE); try { Path tblFile = null; tblFile = FileCommands.newTempFile("tbl"); Path def = FileCommands.newTempFile("def"); packSdf(sdf, def, paths, baseLanguageGrammars, baseLanguageDir); sdf2Table(def, tblFile, module); FileCommands.deleteTempFiles(def); return tblFile; } finally { log.endTask(); } } public static String makePermissiveSdf(String source) throws IOException { Path def = FileCommands.newTempFile("def"); Path permissiveDef = FileCommands.newTempFile("def-permissive"); FileCommands.writeToFile(def, sdfToDef(source)); makePermissive(def, permissiveDef); String s = defToSdf(FileCommands.readFileAsString(permissiveDef)); // drop "definition\n" FileCommands.deleteTempFiles(def); FileCommands.deleteTempFiles(permissiveDef); return s; } private static void makePermissive(Path def, Path permissiveDef) throws IOException { if (!USE_PERMISSIVE_GRAMMARS) { FileCommands.copyFile(def, permissiveDef); return; } log.beginExecution("make permissive", Log.PARSE, "-i", def.getAbsolutePath(), "-o", permissiveDef.getAbsolutePath()); Context mpContext = SugarJContexts.makePermissiveContext(); mpContext.setIOAgent(makePermissiveIOAgent); try { make_permissive.mainNoExit(mpContext, "-i", def.getAbsolutePath(), "-o", permissiveDef.getAbsolutePath()); } catch (StrategoExit e) { if (e.getValue() != 0) { org.strategoxt.imp.runtime.Environment.logWarning("make permissive failed", e); FileCommands.copyFile(def, permissiveDef); } } finally { SugarJContexts.releaseContext(mpContext); log.endTask(); } } /** * Parses the given source using the given table and implodes the resulting parse tree. * * @param tbl * @param source * @param target * @param start * @return * @throws IOException * @throws InvalidParseTableException * @throws SGLRException * @throws TokenExpectedException */ private static Pair<SGLR, Pair<IStrategoTerm, Integer>> sglr(ParseTable table, final String source, final String sourceDesc, final String start, boolean useRecovery, final boolean parseMax, ITreeBuilder treeBuilder) throws SGLRException { if (treeBuilder instanceof RetractableTreeBuilder && ((RetractableTreeBuilder) treeBuilder).isInitialized()) ((RetractableTokenizer) treeBuilder.getTokenizer()).setKeywordRecognizer(table.getKeywordRecognizer()); final SGLR parser = new SGLR(treeBuilder, table); parser.setUseStructureRecovery(useRecovery); Callable<Pair<IStrategoTerm, Integer>> parseCallable = new Callable<Pair<IStrategoTerm, Integer>>() { @Override public Pair<IStrategoTerm, Integer> call() throws Exception { Object o = parser.parseMax(source, sourceDesc, start); if (o instanceof IStrategoTerm) return Pair.create((IStrategoTerm) o, source.length()); else { Object[] os = (Object[]) o; return Pair.create((IStrategoTerm) os[0], (Integer) os[1]); } }}; Future<Pair<IStrategoTerm, Integer>> res = parseExecutorService.submit(parseCallable); try { Pair<IStrategoTerm, Integer> result = res.get(PARSE_TIMEOUT, TimeUnit.MILLISECONDS); return Pair.create(parser, result); } catch (ExecutionException e) { if (e.getCause() instanceof SGLRException) throw (SGLRException) e.getCause(); throw new RuntimeException("unexpected execution error", e); } catch (InterruptedException e) { throw new SGLRException(parser, "parser was interrupted", e); } catch (TimeoutException e) { res.cancel(true); throw new SGLRException(parser, "parser timed out, timeout at " + PARSE_TIMEOUT + "ms", e); } } public static Pair<SGLR, Pair<IStrategoTerm, Integer>> parseImplode(ParseTable table, String source, String sourceDesc, String start, boolean useRecovery, boolean parseMax, ITreeBuilder treeBuilder) throws IOException, SGLRException { return parseImplode(table, null, source, sourceDesc, start, useRecovery, parseMax, treeBuilder); } private static Pair<SGLR, Pair<IStrategoTerm, Integer>> parseImplode(ParseTable table, Path tbl, String source, String sourceDesc, String start, boolean useRecovery, boolean parseMax, ITreeBuilder treeBuilder) throws IOException, SGLRException { log.beginExecution("parsing", Log.PARSE); Pair<SGLR, Pair<IStrategoTerm, Integer>> result = null; try { result = sglr(table, source, sourceDesc, start, useRecovery, parseMax, treeBuilder); } finally { if (result != null && result.b != null) log.endTask(); else { Path tmpSourceFile = FileCommands.newTempFile(""); FileCommands.writeToFile(tmpSourceFile, source.toString()); log.endTask("failed: " + log.commandLineAsString(new String[] {"jsglri", "-p", tbl == null ? "unknown" : tbl.getAbsolutePath(), "-i " + tmpSourceFile + "-s", start})); } } return result; } /** * Pretty prints the content of the given SDF file. * * @param aterm * @return * @throws IOException */ public static String prettyPrintSDF(IStrategoTerm term, HybridInterpreter interp) throws IOException { Context ctx = interp.getCompiledContext(); IStrategoTerm boxTerm = pp_sdf_box_0_0.instance.invoke(ctx, term); if (boxTerm != null) { IStrategoTerm textTerm = box2text_string_0_1.instance.invoke(ctx, boxTerm, ATermCommands.factory.makeInt(80)); if (textTerm != null) return ATermCommands.getString(textTerm); } throw new ATermCommands.PrettyPrintError(term, "pretty printing SDF AST failed"); } /** * Pretty prints the content of the given Stratego file. * * @param aterm * @return * @throws IOException */ public static String prettyPrintSTR(IStrategoTerm term, HybridInterpreter interp) throws IOException { IStrategoTerm string = pp_stratego_string_0_0.instance.invoke(interp.getCompiledContext(), term); if (string != null) return Term.asJavaString(string); throw new ATermCommands.PrettyPrintError(term, "pretty printing STR AST failed: " + ATermCommands.atermToFile(term)); } private static String sdfToDef(String sdf) { return "definition\n" + sdf; } private static String defToSdf(String def) { return def.substring(11); } /** * Filters SDF statements from the given term and * compiles assimilation statements to SDF. * * @param term a file containing a list of SDF * and Stratego statements. * @param sdf result file * @throws InvalidParseTableException */ public static IStrategoTerm extractSDF(IStrategoTerm term) throws IOException, InvalidParseTableException { IStrategoTerm result = null; Context extractContext = SugarJContexts.extractionContext(); try { result = extract_sdf_0_0.instance.invoke(extractContext, term); } catch (StrategoExit e) { if (e.getValue() != 0 || result == null) throw new RuntimeException("Stratego extraction failed", e); } finally { SugarJContexts.releaseContext(extractContext); } return result; } }
gpl-3.0
servinglynk/hmis-lynk-open-source
hmis-serialize-v2015/src/main/java/com/servinglynk/hmis/warehouse/core/model/Entryssvf.java
2418
package com.servinglynk.hmis.warehouse.core.model; import java.util.Date; import java.util.UUID; import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("entryssvf") public class Entryssvf extends ClientModel{ private UUID entryssvfId; private Integer percentami; private String lastPermanentStreet; private String lastPermanentCity; private String lastPermanentState; private String lastPermanentZip; private Integer addressDataQuality; private Integer hpScreenScore; private String vamcStaction; public UUID getEntryssvfId(){ return entryssvfId; } public void setEntryssvfId(UUID entryssvfId){ this.entryssvfId = entryssvfId; } public Integer getPercentami(){ return percentami; } public void setPercentami(Integer percentami){ this.percentami = percentami; } public String getLastPermanentStreet(){ return lastPermanentStreet; } public void setLastPermanentStreet(String lastPermanentStreet){ this.lastPermanentStreet = lastPermanentStreet; } public String getLastPermanentCity(){ return lastPermanentCity; } public void setLastPermanentCity(String lastPermanentCity){ this.lastPermanentCity = lastPermanentCity; } public String getLastPermanentState(){ return lastPermanentState; } public void setLastPermanentState(String lastPermanentState){ this.lastPermanentState = lastPermanentState; } public String getLastPermanentZip(){ return lastPermanentZip; } public void setLastPermanentZip(String lastPermanentZip){ this.lastPermanentZip = lastPermanentZip; } public Integer getAddressDataQuality(){ return addressDataQuality; } public void setAddressDataQuality(Integer addressDataQuality){ this.addressDataQuality = addressDataQuality; } public Integer getHpScreenScore(){ return hpScreenScore; } public void setHpScreenScore(Integer hpScreenScore){ this.hpScreenScore = hpScreenScore; } public String getVamcStaction(){ return vamcStaction; } public void setVamcStaction(String vamcStaction){ this.vamcStaction = vamcStaction; } }
mpl-2.0
seedstack/io-function
specs/src/main/java/org/seedstack/io/spi/AbstractBaseRenderer.java
575
/* * Copyright © 2013-2020, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.io.spi; import org.seedstack.io.Renderer; /** * This class should be extended when you want to add a <code>Renderer</code> without template. <br> * It implements the {@link Renderer} interface */ public abstract class AbstractBaseRenderer implements Renderer { }
mpl-2.0
carlwilson/veraPDF-library
core/src/main/java/org/verapdf/pdfa/VeraFoundryProvider.java
1512
/** * This file is part of veraPDF Library core, a module of the veraPDF project. * Copyright (c) 2015, veraPDF Consortium <info@verapdf.org> * All rights reserved. * * veraPDF Library core is free software: you can redistribute it and/or modify * it under the terms of either: * * The GNU General public license GPLv3+. * You should have received a copy of the GNU General Public License * along with veraPDF Library core as the LICENSE.GPL file in the root of the source * tree. If not, see http://www.gnu.org/licenses/ or * https://www.gnu.org/licenses/gpl-3.0.en.html. * * The Mozilla Public License MPLv2+. * You should have received a copy of the Mozilla Public License along with * veraPDF Library core as the LICENSE.MPL file in the root of the source tree. * If a copy of the MPL was not distributed with this file, you can obtain one at * http://mozilla.org/MPL/2.0/. */ /** * */ package org.verapdf.pdfa; /** * The {@link VeraFoundryProvider} class simply provides a method to obtain a * {@link VeraPDFFoundry} instance. The class is only necessary to allow * {@link VeraPDFFoundry} implementations to be supplied and switched at runtime. * * @author <a href="mailto:carl@openpreservation.org">Carl Wilson</a> * <a href="https://github.com/carlwilson">carlwilson AT github</a> * @version 0.1 Created 26 Oct 2016:20:29:21 */ public interface VeraFoundryProvider { /** * @return a {@link VeraPDFFoundry} instance. */ public VeraPDFFoundry getInstance(); }
mpl-2.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/DomainObjects/src/ims/clinical/domain/objects/SkinPrepIntraOp.java
15489
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated: 12/10/2015, 13:28 * */ package ims.clinical.domain.objects; /** * * @author Neil McAnaspie * Generated. */ public class SkinPrepIntraOp extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable { public static final int CLASSID = 1072100137; private static final long serialVersionUID = 1072100137L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } /** Theatre Appointment */ private ims.scheduling.domain.objects.Booking_Appointment theatreAppointment; /** Surgical Site Skin Prep Solution */ private ims.domain.lookups.LookupInstance surgicalSiteSkinPrepSolution; /** Prep Site */ private String prepSite; /** Prep Performed By */ private ims.core.resource.people.domain.objects.Hcp prepPerformedBy; /** SystemInformation */ private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation(); public SkinPrepIntraOp (Integer id, int ver) { super(id, ver); } public SkinPrepIntraOp () { super(); } public SkinPrepIntraOp (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); } public Class getRealDomainClass() { return ims.clinical.domain.objects.SkinPrepIntraOp.class; } public ims.scheduling.domain.objects.Booking_Appointment getTheatreAppointment() { return theatreAppointment; } public void setTheatreAppointment(ims.scheduling.domain.objects.Booking_Appointment theatreAppointment) { this.theatreAppointment = theatreAppointment; } public ims.domain.lookups.LookupInstance getSurgicalSiteSkinPrepSolution() { return surgicalSiteSkinPrepSolution; } public void setSurgicalSiteSkinPrepSolution(ims.domain.lookups.LookupInstance surgicalSiteSkinPrepSolution) { this.surgicalSiteSkinPrepSolution = surgicalSiteSkinPrepSolution; } public String getPrepSite() { return prepSite; } public void setPrepSite(String prepSite) { if ( null != prepSite && prepSite.length() > 500 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for prepSite. Tried to set value: "+ prepSite); } this.prepSite = prepSite; } public ims.core.resource.people.domain.objects.Hcp getPrepPerformedBy() { return prepPerformedBy; } public void setPrepPerformedBy(ims.core.resource.people.domain.objects.Hcp prepPerformedBy) { this.prepPerformedBy = prepPerformedBy; } public ims.domain.SystemInformation getSystemInformation() { if (systemInformation == null) systemInformation = new ims.domain.SystemInformation(); return systemInformation; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Instantiation".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*theatreAppointment* :"); if (theatreAppointment != null) { auditStr.append(toShortClassName(theatreAppointment)); auditStr.append(theatreAppointment.getId()); } auditStr.append("; "); auditStr.append("\r\n*surgicalSiteSkinPrepSolution* :"); if (surgicalSiteSkinPrepSolution != null) auditStr.append(surgicalSiteSkinPrepSolution.getText()); auditStr.append("; "); auditStr.append("\r\n*prepSite* :"); auditStr.append(prepSite); auditStr.append("; "); auditStr.append("\r\n*prepPerformedBy* :"); if (prepPerformedBy != null) { auditStr.append(toShortClassName(prepPerformedBy)); auditStr.append(prepPerformedBy.getId()); } auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" id=\"" + this.getId() + "\""); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); String keyClassName = "SkinPrepIntraOp"; String externalSource = ims.configuration.EnvironmentConfig.getImportExportSourceName(); ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + this.getId()); if (impObj == null) { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(this.getId()); impObj.setExternalSource(externalSource); impObj.setDomainObject(this); impObj.setLocalId(this.getId()); impObj.setClassName(keyClassName); domMap.put(keyClassName + "_" + externalSource + "_" + this.getId(), impObj); } return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getTheatreAppointment() != null) { sb.append("<theatreAppointment>"); sb.append(this.getTheatreAppointment().toXMLString(domMap)); sb.append("</theatreAppointment>"); } if (this.getSurgicalSiteSkinPrepSolution() != null) { sb.append("<surgicalSiteSkinPrepSolution>"); sb.append(this.getSurgicalSiteSkinPrepSolution().toXMLString()); sb.append("</surgicalSiteSkinPrepSolution>"); } if (this.getPrepSite() != null) { sb.append("<prepSite>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getPrepSite().toString())); sb.append("</prepSite>"); } if (this.getPrepPerformedBy() != null) { sb.append("<prepPerformedBy>"); sb.append(this.getPrepPerformedBy().toXMLString(domMap)); sb.append("</prepPerformedBy>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); SkinPrepIntraOp domainObject = getSkinPrepIntraOpfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); SkinPrepIntraOp domainObject = getSkinPrepIntraOpfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static SkinPrepIntraOp getSkinPrepIntraOpfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getSkinPrepIntraOpfromXML(doc.getRootElement(), factory, domMap); } public static SkinPrepIntraOp getSkinPrepIntraOpfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!SkinPrepIntraOp.class.getName().equals(className)) { Class clz = Class.forName(className); if (!SkinPrepIntraOp.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the SkinPrepIntraOp class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (SkinPrepIntraOp)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(SkinPrepIntraOp.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } SkinPrepIntraOp ret = null; int extId = Integer.parseInt(el.attributeValue("id")); String externalSource = el.attributeValue("source"); ret = (SkinPrepIntraOp)factory.getImportedDomainObject(SkinPrepIntraOp.class, externalSource, extId); if (ret == null) { ret = new SkinPrepIntraOp(); } String keyClassName = "SkinPrepIntraOp"; ims.configuration.ImportedObject impObj = (ims.configuration.ImportedObject)domMap.get(keyClassName + "_" + externalSource + "_" + extId); if (impObj != null) { return (SkinPrepIntraOp)impObj.getDomainObject(); } else { impObj = new ims.configuration.ImportedObject(); impObj.setExternalId(extId); impObj.setExternalSource(externalSource); impObj.setDomainObject(ret); domMap.put(keyClassName + "_" + externalSource + "_" + extId, impObj); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, SkinPrepIntraOp obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("theatreAppointment"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setTheatreAppointment(ims.scheduling.domain.objects.Booking_Appointment.getBooking_AppointmentfromXML(fldEl, factory, domMap)); } fldEl = el.element("surgicalSiteSkinPrepSolution"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setSurgicalSiteSkinPrepSolution(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("prepSite"); if(fldEl != null) { obj.setPrepSite(new String(fldEl.getTextTrim())); } fldEl = el.element("prepPerformedBy"); if(fldEl != null) { fldEl = fldEl.element("class"); obj.setPrepPerformedBy(ims.core.resource.people.domain.objects.Hcp.getHcpfromXML(fldEl, factory, domMap)); } } public static String[] getCollectionFields() { return new String[]{ }; } public static class FieldNames { public static final String ID = "id"; public static final String TheatreAppointment = "theatreAppointment"; public static final String SurgicalSiteSkinPrepSolution = "surgicalSiteSkinPrepSolution"; public static final String PrepSite = "prepSite"; public static final String PrepPerformedBy = "prepPerformedBy"; } }
agpl-3.0
aatxe/Orpheus
src/net/server/handlers/channel/ChangeMapSpecialHandler.java
1853
/* OrpheusMS: MapleStory Private Server based on OdinMS Copyright (C) 2012 Aaron Weiss <aaron@deviant-core.net> Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.server.handlers.channel; import client.MapleClient; import net.AbstractMaplePacketHandler; import server.MaplePortal; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; public final class ChangeMapSpecialHandler extends AbstractMaplePacketHandler { @SuppressWarnings("unused") public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { slea.readByte(); String startwp = slea.readMapleAsciiString(); slea.readShort(); MaplePortal portal = c.getPlayer().getMap().getPortal(startwp); if ((c.getPlayer().portalDelay() > System.currentTimeMillis()) || c.getPlayer().getBlockedPortals().contains(portal.getScriptName())) { c.announce(MaplePacketCreator.enableActions()); return; } if (portal != null) { portal.enterPortal(c); } else { c.announce(MaplePacketCreator.enableActions()); } } }
agpl-3.0
mjshepherd/phenotips
components/vocabularies/hgnc/api/src/main/java/org/phenotips/vocabulary/internal/RemoteGeneNomenclature.java
18482
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/ */ package org.phenotips.vocabulary.internal; import org.phenotips.vocabulary.Vocabulary; import org.phenotips.vocabulary.VocabularyTerm; import org.xwiki.cache.Cache; import org.xwiki.cache.CacheException; import org.xwiki.cache.CacheManager; import org.xwiki.cache.config.CacheConfiguration; import org.xwiki.cache.eviction.EntryEvictionConfiguration; import org.xwiki.cache.eviction.LRUEvictionConfiguration; import org.xwiki.component.annotation.Component; import org.xwiki.component.phase.Initializable; import org.xwiki.component.phase.InitializationException; import org.xwiki.configuration.ConfigurationSource; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.Consts; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.params.CommonParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; /** * Provides access to the HUGO Gene Nomenclature Committee's GeneNames nomenclature. The prefix is {@code HGNC}. * * @version $Id$ * @since 1.0RC1 */ @Component @Named("hgncRemote") @Singleton public class RemoteGeneNomenclature implements Vocabulary, Initializable { /** * Object used to mark in the cache that a term doesn't exist, since null means that the cache doesn't contain the * requested entry. */ private static final VocabularyTerm EMPTY_MARKER = new JSONOntologyTerm(null, null); private static final String RESPONSE_KEY = "response"; private static final String DATA_KEY = "docs"; private static final String LABEL_KEY = "symbol"; private static final String WILDCARD = "*"; private static final String DEFAULT_OPERATOR = "AND"; private static final Map<String, String> QUERY_OPERATORS = new HashMap<>(); @Inject @Named("xwikiproperties") private ConfigurationSource configuration; private String baseServiceURL; private String searchServiceURL; private String infoServiceURL; private String fetchServiceURL; /** Performs HTTP requests to the remote REST service. */ private final CloseableHttpClient client = HttpClients.createSystem(); @Inject private Logger logger; /** * Cache for the recently accessed terms; useful since the ontology rarely changes, so a search should always return * the same thing. */ private Cache<VocabularyTerm> cache; /** Cache for ontology metadata. */ private Cache<JSONObject> infoCache; /** Cache factory needed for creating the term cache. */ @Inject private CacheManager cacheFactory; @Override public void initialize() throws InitializationException { try { this.baseServiceURL = this.configuration.getProperty("phenotips.ontologies.hgnc.serviceURL", "http://rest.genenames.org/"); this.searchServiceURL = this.baseServiceURL + "search/"; this.infoServiceURL = this.baseServiceURL + "info"; this.fetchServiceURL = this.baseServiceURL + "fetch/"; this.cache = this.cacheFactory.createNewLocalCache(new CacheConfiguration()); EntryEvictionConfiguration infoConfig = new LRUEvictionConfiguration(1); infoConfig.setTimeToLive(300); this.infoCache = this.cacheFactory.createNewLocalCache(new CacheConfiguration(infoConfig)); } catch (final CacheException ex) { throw new InitializationException("Cannot create cache: " + ex.getMessage()); } QUERY_OPERATORS.put("OR", ""); QUERY_OPERATORS.put(DEFAULT_OPERATOR, DEFAULT_OPERATOR + ' '); QUERY_OPERATORS.put("NOT", "-"); } @Override public VocabularyTerm getTerm(String id) { VocabularyTerm result = this.cache.get(id); String safeID; if (result == null) { try { safeID = URLEncoder.encode(id, Consts.UTF_8.name()); } catch (UnsupportedEncodingException e) { safeID = id.replaceAll("\\s", ""); this.logger.warn("Could not find the encoding: {}", Consts.UTF_8.name()); } HttpGet method = new HttpGet(this.fetchServiceURL + "symbol/" + safeID); method.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); try (CloseableHttpResponse httpResponse = this.client.execute(method)) { String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8); JSONObject responseJSON = new JSONObject(response); JSONArray docs = responseJSON.getJSONObject(RESPONSE_KEY).getJSONArray(DATA_KEY); if (docs.length() == 1) { result = new JSONOntologyTerm(docs.getJSONObject(0), this); this.cache.set(id, result); } else { this.cache.set(id, EMPTY_MARKER); } } catch (IOException | JSONException ex) { this.logger.warn("Failed to fetch gene definition: {}", ex.getMessage()); } } return (result == EMPTY_MARKER) ? null : result; } @Override public Set<VocabularyTerm> getTerms(Collection<String> ids) { // FIXME Reimplement with a bunch of async connections fired in parallel Set<VocabularyTerm> result = new LinkedHashSet<>(); for (String id : ids) { VocabularyTerm term = getTerm(id); if (term != null) { result.add(term); } } return result; } @Override public List<VocabularyTerm> search(Map<String, ?> fieldValues) { return search(fieldValues, Collections.<String, String>emptyMap()); } @Override public List<VocabularyTerm> search(Map<String, ?> fieldValues, Map<String, String> queryOptions) { try { HttpGet method = new HttpGet(this.searchServiceURL + URLEncoder.encode(generateQuery(fieldValues), Consts.UTF_8.name())); method.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); try (CloseableHttpResponse httpResponse = this.client.execute(method)) { String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8); JSONObject responseJSON = new JSONObject(response); JSONArray docs = responseJSON.getJSONObject(RESPONSE_KEY).getJSONArray(DATA_KEY); if (docs.length() >= 1) { List<VocabularyTerm> result = new LinkedList<>(); // The remote service doesn't offer any query control, manually select the right range int start = 0; if (queryOptions.containsKey(CommonParams.START) && StringUtils.isNumeric(queryOptions.get(CommonParams.START))) { start = Math.max(0, Integer.parseInt(queryOptions.get(CommonParams.START))); } int end = docs.length(); if (queryOptions.containsKey(CommonParams.ROWS) && StringUtils.isNumeric(queryOptions.get(CommonParams.ROWS))) { end = Math.min(end, start + Integer.parseInt(queryOptions.get(CommonParams.ROWS))); } for (int i = start; i < end; ++i) { result.add(new JSONOntologyTerm(docs.getJSONObject(i), this)); } return result; // This is too slow, for the moment only return summaries // return getTerms(ids); } } catch (IOException | JSONException ex) { this.logger.warn("Failed to search gene names: {}", ex.getMessage()); } } catch (UnsupportedEncodingException ex) { // This will not happen, UTF-8 is always available } return Collections.emptyList(); } @Override public List<VocabularyTerm> search(String input, int maxResults, String sort, String customFilter) { // ignoring sort and customFq String formattedQuery = String.format("%s*", input); Map<String, Object> fieldValues = new HashMap<>(); Map<String, String> queryMap = new HashMap<>(); Map<String, String> rowsMap = new HashMap<>(); queryMap.put(LABEL_KEY, formattedQuery); queryMap.put("alias_symbol", formattedQuery); queryMap.put("prev_symbol", formattedQuery); fieldValues.put("status", "Approved"); fieldValues.put(DEFAULT_OPERATOR, queryMap); rowsMap.put("rows", Integer.toString(maxResults)); return this.search(fieldValues, rowsMap); } @Override public long count(Map<String, ?> fieldValues) { try { HttpGet method = new HttpGet(this.searchServiceURL + URLEncoder.encode(generateQuery(fieldValues), Consts.UTF_8.name())); method.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); try (CloseableHttpResponse httpResponse = this.client.execute(method)) { String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8); JSONObject responseJSON = new JSONObject(response); JSONArray docs = responseJSON.getJSONObject(RESPONSE_KEY).getJSONArray(DATA_KEY); return docs.length(); } catch (IOException | JSONException ex) { this.logger.warn("Failed to count matching gene names: {}", ex.getMessage()); } } catch (UnsupportedEncodingException ex) { // This will not happen, UTF-8 is always available } return -1; } @Override public long getDistance(String fromTermId, String toTermId) { // Flat nomenclature return -1; } @Override public long getDistance(VocabularyTerm fromTerm, VocabularyTerm toTerm) { // Flat nomenclature return -1; } @Override public String getIdentifier() { return "hgncRemote"; } @Override public String getName() { return "HUGO Gene Nomenclature Committee's GeneNames (HGNC)"; } @Override public Set<String> getAliases() { Set<String> result = new HashSet<String>(); result.add(getIdentifier()); result.add("HGNC"); return result; } @Override public long size() { JSONObject info = getInfo(); return info == null ? -1 : info.getLong("numDoc"); } @Override public int reindex(String ontologyUrl) { // Remote ontology, we cannot reindex, but we can clear the local cache this.cache.removeAll(); return 0; } @Override public String getDefaultSourceLocation() { return this.baseServiceURL; } @Override public String getVersion() { JSONObject info = getInfo(); return info == null ? "" : info.getString("lastModified"); } private JSONObject getInfo() { JSONObject info = this.infoCache.get(""); if (info != null) { return info; } HttpGet method = new HttpGet(this.infoServiceURL); method.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()); try (CloseableHttpResponse httpResponse = this.client.execute(method)) { String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8); JSONObject responseJSON = new JSONObject(response); this.infoCache.set("", responseJSON); return responseJSON; } catch (IOException | JSONException ex) { this.logger.warn("Failed to get HGNC information: {}", ex.getMessage()); } return null; } /** * Generate a Lucene query from a map of parameters, to be used in the "q" parameter for Solr. * * @param fieldValues a map with term meta-property values that must be matched by the returned terms; the keys are * property names, like {@code id}, {@code description}, {@code is_a}, and the values can be either a * single value, or a collection of values that can (OR) be matched by the term; * @return the String representation of the equivalent Lucene query */ private String generateQuery(Map<String, ?> fieldValues) { StringBuilder query = new StringBuilder(); for (Map.Entry<String, ?> field : fieldValues.entrySet()) { processQueryPart(query, field, true); } return StringUtils.removeStart(query.toString().trim(), DEFAULT_OPERATOR); } private StringBuilder processQueryPart(StringBuilder query, Map.Entry<String, ?> field, boolean includeOperator) { if (Collection.class.isInstance(field.getValue()) && ((Collection<?>) field.getValue()).isEmpty()) { return query; } if (Map.class.isInstance(field.getValue())) { if (QUERY_OPERATORS.containsKey(field.getKey())) { @SuppressWarnings("unchecked") Map.Entry<String, Map<String, ?>> subquery = (Map.Entry<String, Map<String, ?>>) field; return processSubquery(query, subquery); } else { this.logger.warn("Invalid subquery operator: {}", field.getKey()); return query; } } query.append(' '); if (includeOperator) { query.append(QUERY_OPERATORS.get(DEFAULT_OPERATOR)); } query.append(ClientUtils.escapeQueryChars(field.getKey())); query.append(":("); if (Collection.class.isInstance(field.getValue())) { for (Object value : (Collection<?>) field.getValue()) { String svalue = String.valueOf(value); if (svalue.endsWith(WILDCARD)) { svalue = ClientUtils.escapeQueryChars(StringUtils.removeEnd(svalue, WILDCARD)) + WILDCARD; } else { svalue = ClientUtils.escapeQueryChars(svalue); } query.append(svalue); query.append(' '); } } else { String svalue = String.valueOf(field.getValue()); if (svalue.endsWith(WILDCARD)) { svalue = ClientUtils.escapeQueryChars(StringUtils.removeEnd(svalue, WILDCARD)) + WILDCARD; } else { svalue = ClientUtils.escapeQueryChars(svalue); } query.append(svalue); } query.append(')'); return query; } private StringBuilder processSubquery(StringBuilder query, Map.Entry<String, Map<String, ?>> subquery) { query.append(' ').append(QUERY_OPERATORS.get(subquery.getKey())).append('('); for (Map.Entry<String, ?> field : subquery.getValue().entrySet()) { processQueryPart(query, field, false); } query.append(')'); return query; } private static class JSONOntologyTerm implements VocabularyTerm { private JSONObject data; private Vocabulary ontology; JSONOntologyTerm(JSONObject data, Vocabulary ontology) { this.data = data; this.ontology = ontology; } @Override public String getId() { return this.data.getString(LABEL_KEY); } @Override public String getName() { return this.data.getString("name"); } @Override public String getDescription() { // No description for gene names return ""; } @Override public Set<VocabularyTerm> getParents() { return Collections.emptySet(); } @Override public Set<VocabularyTerm> getAncestors() { return Collections.emptySet(); } @Override public Set<VocabularyTerm> getAncestorsAndSelf() { return Collections.<VocabularyTerm>singleton(this); } @Override public long getDistanceTo(VocabularyTerm other) { return -1; } @Override public Object get(String name) { return this.data.get(name); } @Override public Vocabulary getVocabulary() { return this.ontology; } @Override public String toString() { return "HGNC:" + getId(); } @Override public JSONObject toJSON() { JSONObject json = new JSONObject(); json.put("id", this.getId()); return json; } } }
agpl-3.0
rapidminer/rapidminer-5
src/com/rapidminer/gui/look/fc/BookmarkList.java
5244
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.look.fc; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.SwingTools; /** * The list containing the bookmarks. * * @author Ingo Mierswa */ public class BookmarkList extends JList implements ListSelectionListener, MouseListener { private static final long serialVersionUID = -7109320787696008679L; private static class BookmarkCellRenderer implements ListCellRenderer { private JLabel label = new JLabel(); public BookmarkCellRenderer() { this.label.setBorder(BorderFactory.createEmptyBorder(2,2,2,2)); this.label.setOpaque(true); this.label.setIcon(SwingTools.createIcon("16/star_yellow.png")); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Bookmark bookmark = (Bookmark)value; String name = bookmark.getName(); final String path = bookmark.getPath(); if (isSelected) { label.setBackground(UIManager.getColor("List.selectionBackground")); label.setForeground(UIManager.getColor("List.selectionForeground")); } else { label.setBackground(UIManager.getColor("List.background")); label.setForeground(UIManager.getColor("List.foreground")); } if (!new File(path).exists()) { label.setForeground(Color.GRAY); } label.setText(name); label.setToolTipText("<html><b>" + name + "</b><br>" + path + "</html>"); return label; } } private static final ListCellRenderer RENDERER = new BookmarkCellRenderer(); private FileList fileList; public BookmarkList(BookmarkListModel model, FileList fileList) { super(model); this.fileList = fileList; addListSelectionListener(this); addMouseListener(this); } @Override public ListCellRenderer getCellRenderer() { return RENDERER; } public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { Bookmark selectedBookmark = (Bookmark)getSelectedValue(); if (selectedBookmark != null) { String path = selectedBookmark.getPath(); File bookmarkFile = new File(path); if (bookmarkFile.exists() && bookmarkFile.canRead()) { fileList.filechooserUI.setCurrentDirectoryOfFileChooser(bookmarkFile); } else { JOptionPane.showConfirmDialog(fileList.fc, "Cannot access selected bookmark directory.", "Cannot access directory", JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE); } } } } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { int index = locationToIndex(e.getPoint()); setSelectedIndex(index); evaluatePopup(e); } public void mouseReleased(MouseEvent e) { evaluatePopup(e); } /** Checks if the given mouse event is a popup trigger and creates a new popup menu if necessary. */ private void evaluatePopup(MouseEvent e) { if (e.isPopupTrigger()) { JPopupMenu menu = createBookmarkPopupMenu(); if (menu != null) { menu.show(this, e.getX(), e.getY()); } } } private JPopupMenu createBookmarkPopupMenu() { final Bookmark bookmark = (Bookmark)getSelectedValue(); if (bookmark != null) { JPopupMenu bookmarksPopup = new JPopupMenu(); bookmarksPopup.add(new JMenuItem(new ResourceAction("file_chooser.rename_bookmark") { private static final long serialVersionUID = -3728467995967823779L; public void actionPerformed(ActionEvent e) { fileList.renameBookmark(bookmark); } })); bookmarksPopup.add(new JMenuItem(new ResourceAction("file_chooser.delete_bookmark") { private static final long serialVersionUID = 5432105038105200178L; public void actionPerformed(ActionEvent e) { fileList.deleteBookmark(bookmark); } })); return bookmarksPopup; } else { return null; } } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/OCRR/src/ims/ocrr/forms/newresults/BaseLogic.java
2703
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.ocrr.forms.newresults; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.ocrr.domain.NewResults.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.ocrr.domain.NewResults domain) { setContext(engine, form); this.domain = domain; } public void clearContextInformation() { engine.clearPatientContextInformation(); } public final void free() { super.free(); domain = null; } protected ims.ocrr.domain.NewResults domain; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Oncology/src/ims/oncology/forms/chooseotherfractiondaydialog/AccessLogic.java
2560
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5527.24259) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. package ims.oncology.forms.chooseotherfractiondaydialog; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; // TODO: Add your conditions here. return true; } public boolean isReadOnly() { if(super.isReadOnly()) return true; // TODO: Add your conditions here. return false; } }
agpl-3.0
rapidminer/rapidminer
src/com/rapidminer/gui/dialog/OperatorInfoScreen.java
12611
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.dialog; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.LinkedList; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import com.rapidminer.gui.OperatorDocumentationBrowser; import com.rapidminer.gui.tools.ResourceLabel; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.gui.tools.components.FixedWidthLabel; import com.rapidminer.gui.tools.dialogs.ButtonDialog; import com.rapidminer.operator.ExecutionUnit; import com.rapidminer.operator.Operator; import com.rapidminer.operator.OperatorCapability; import com.rapidminer.operator.OperatorChain; import com.rapidminer.operator.learner.CapabilityProvider; import com.rapidminer.operator.learner.Learner; import com.rapidminer.operator.ports.Port; import com.rapidminer.operator.ports.Ports; /** * An info screen for operators. Shows all important meta data about an operator * like name, group, expected input and delivered output. In case of an operator * chain the desired numbers of inner operators are also shown. * * @author Ingo Mierswa, Tobias Malbrecht, Sebastian Land */ public class OperatorInfoScreen extends ButtonDialog { private static final long serialVersionUID = -6566133238783779634L; private final transient Operator operator; public OperatorInfoScreen(Operator operator) { // TODO: externalize strings and icon names super("operator_info", true,new Object[]{}); this.operator = operator; setTitle(getTitle()); // must be executed after setting member field JTabbedPane tabs = new JTabbedPane(); OperatorDocumentationBrowser browser = new OperatorDocumentationBrowser(); browser.setDisplayedOperator(operator); final JPanel overviewPanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.weighty = 0; c.insets = new Insets(0, 0, 0, 0); if (operator.getOperatorDescription().isDeprecated()) { final JPanel deprecatedPanel = new JPanel(new BorderLayout()); final JLabel label = new JLabel(SwingTools.createIcon("24/sign_warning.png")); label.setHorizontalTextPosition(SwingConstants.CENTER); label.setVerticalTextPosition(SwingConstants.BOTTOM); label.setText("<html><b>Depreceated!</b></html>"); label.setPreferredSize(new Dimension(180,50)); label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 40)); deprecatedPanel.add(label, BorderLayout.WEST); deprecatedPanel.add(createDeprecationInfoPanel(operator), BorderLayout.CENTER); deprecatedPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY), BorderFactory.createEmptyBorder(4, 4, 4, 4))); overviewPanel.add(deprecatedPanel, c); } if (operator instanceof Learner) { JPanel learnerPanel = new JPanel(new BorderLayout()); JLabel label = new JLabel(SwingTools.createIcon("24/briefcase2.png")); label.setHorizontalTextPosition(SwingConstants.CENTER); label.setVerticalTextPosition(SwingConstants.BOTTOM); label.setText("Capabilities"); label.setPreferredSize(new Dimension(180,50)); label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 40)); learnerPanel.add(label, BorderLayout.WEST); learnerPanel.add(createCapabilitiesPanel(operator), BorderLayout.CENTER); learnerPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY), BorderFactory.createEmptyBorder(4, 4, 4, 4))); overviewPanel.add(learnerPanel, c); } // ports if (operator.getInputPorts().getNumberOfPorts() > 0 || operator.getOutputPorts().getNumberOfPorts() > 0) { JPanel portPanel = new JPanel(new BorderLayout()); JLabel label = new JLabel(SwingTools.createIcon("24/plug.png")); label.setHorizontalTextPosition(SwingConstants.CENTER); label.setVerticalTextPosition(SwingConstants.BOTTOM); label.setText("Ports"); label.setPreferredSize(new Dimension(180,50)); label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 40)); portPanel.add(label, BorderLayout.WEST); portPanel.add(createPortsDescriptionPanel("input_ports", "output_ports", operator.getInputPorts(), operator.getOutputPorts()), BorderLayout.CENTER); portPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY), BorderFactory.createEmptyBorder(4, 4, 4, 4))); overviewPanel.add(portPanel, c); } if (operator instanceof OperatorChain) { OperatorChain chain = (OperatorChain) operator; for (ExecutionUnit subprocess : chain.getSubprocesses()) { JPanel subprocessPanel = new JPanel(new BorderLayout()); JLabel label = new JLabel(SwingTools.createIcon("24/elements_selection.png")); label.setHorizontalTextPosition(SwingConstants.CENTER); label.setVerticalTextPosition(SwingConstants.BOTTOM); label.setText(subprocess.getName()); label.setPreferredSize(new Dimension(180,50)); label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 40)); subprocessPanel.add(label, BorderLayout.WEST); subprocessPanel.add(createPortsDescriptionPanel("inner_sources", "inner_sinks", subprocess.getInnerSources(), subprocess.getInnerSinks()), BorderLayout.CENTER); subprocessPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY), BorderFactory.createEmptyBorder(4, 4, 4, 4))); overviewPanel.add(subprocessPanel, c); } } c.fill = GridBagConstraints.BOTH; c.weighty = 1; overviewPanel.add(new JPanel(new BorderLayout()), c); final JScrollPane overviewPane = new JScrollPane(overviewPanel); overviewPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); overviewPane.getViewport().addComponentListener(new ComponentListener() { @Override public void componentHidden(ComponentEvent e) {} @Override public void componentMoved(ComponentEvent e) {} @Override public void componentResized(ComponentEvent e) { // transfer width to contained panel overviewPanel.setPreferredSize(new Dimension((int) overviewPane.getViewport().getExtentSize().getWidth(), (int) overviewPanel.getPreferredSize().getHeight())); } @Override public void componentShown(ComponentEvent e) {} }); tabs.add("Overview", overviewPane); tabs.add("Description", browser); layoutDefault(tabs, NORMAL, makeCloseButton()); } @Override protected Icon getInfoIcon() { return operator.getOperatorDescription().getLargeIcon(); } @Override protected String getInfoText() { return "<html><b>"+operator.getOperatorDescription().getName() + "</b>" + (operator.getOperatorDescription().getGroup().equals("") ? "" : "<br/>Group: "+operator.getOperatorDescription().getGroupName()) + "</html>"; } @Override public String getTitle() { if (operator != null) return super.getTitle() + ": " + operator.getOperatorDescription().getName(); return super.getTitle(); } public static JPanel createPortsDescriptionPanel(String inKey, String outKey, Ports<? extends Port> inputPorts, Ports<? extends Port> outputPorts) { int numberOfInputPorts = inputPorts.getNumberOfPorts(); int numberOfOutputPorts = outputPorts.getNumberOfPorts(); GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(GAP / 2, 0, GAP / 2, 0); c.fill = GridBagConstraints.BOTH; c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 1; c.weighty = 1; final JPanel panel = new JPanel(layout); final Icon inIcon; final Icon outIcon; { JPanel rowPanel = new JPanel(new GridLayout(1, 2)); JLabel label = new ResourceLabel(inKey); label.setText("<html><i>" + label.getText() + "</i></html>"); inIcon = label.getIcon(); label.setIcon(null); rowPanel.add(label); label = new ResourceLabel(outKey); label.setText("<html><i>" + label.getText() + "</i></html>"); outIcon = label.getIcon(); label.setIcon(null); rowPanel.add(label); panel.add(rowPanel, c); } final LinkedList<FixedWidthLabel> labels = new LinkedList<FixedWidthLabel>(); for (int i = 0; i < Math.max(numberOfInputPorts, numberOfOutputPorts); i++) { JPanel rowPanel = new JPanel(new GridLayout(1, 2)); if (i < numberOfInputPorts) { Port port = inputPorts.getPortByIndex(i); FixedWidthLabel label = new FixedWidthLabel(rowPanel.getWidth() / 2, port.getName()); label.setIcon(inIcon); label.setText(//(numberOfInputPorts > 1 ? ("<em>" + (i + 1) + ":</em> ") : "") + port.getName() + (port.getDescription().equals("") ? "" : (" (" + port.getDescription()) + ")")); labels.add(label); rowPanel.add(label); } else { rowPanel.add(new JLabel()); } if (i < numberOfOutputPorts) { Port port = outputPorts.getPortByIndex(i); FixedWidthLabel label = new FixedWidthLabel(rowPanel.getWidth() / 2, port.getName()); label.setIcon(outIcon); label.setText(//(numberOfOutputPorts > 1 ? ("<em>" + (i + 1) + ":</em> ") : "") + port.getName() + (port.getDescription().equals("") ? "" : (" (" + port.getDescription()) + ")")); labels.add(label); rowPanel.add(label); } else { rowPanel.add(new JLabel()); } panel.add(rowPanel, c); } panel.addComponentListener(new ComponentListener() { @Override public void componentHidden(ComponentEvent e) {} @Override public void componentMoved(ComponentEvent e) {} @Override public void componentResized(ComponentEvent e) { // transfer to labels in panel for (FixedWidthLabel label : labels) { label.setWidth((int) (panel.getWidth() / 2.2)); } } @Override public void componentShown(ComponentEvent e) {} }); return panel; } public static JPanel createDeprecationInfoPanel(Operator operator) { final JPanel panel = new JPanel(new BorderLayout()); final FixedWidthLabel info = new FixedWidthLabel(200, operator.getOperatorDescription().getDeprecationInfo()); panel.add(info, BorderLayout.CENTER); panel.addComponentListener(new ComponentListener() { @Override public void componentHidden(ComponentEvent e) {} @Override public void componentMoved(ComponentEvent e) {} @Override public void componentResized(ComponentEvent e) { info.setWidth(panel.getWidth()); } @Override public void componentShown(ComponentEvent e) {} }); return panel; } public static JPanel createCapabilitiesPanel(Operator operator) { CapabilityProvider capabilityProvider = (CapabilityProvider) operator; int length = OperatorCapability.values().length; GridLayout layout = new GridLayout(length / 2, 2); layout.setHgap(GAP); layout.setVgap(GAP); JPanel capabilitiesPanel = new JPanel(layout); for (OperatorCapability capability : OperatorCapability.values()) { JLabel capabilityLabel = new JLabel(capability.getDescription()); try { if (capabilityProvider.supportsCapability(capability)) { capabilityLabel.setIcon(SwingTools.createIcon("16/ok.png")); } else { capabilityLabel.setIcon(SwingTools.createIcon("16/error.png")); } } catch (Exception e) { break; } capabilitiesPanel.add(capabilityLabel); } return capabilitiesPanel; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Emergency/src/ims/emergency/domain/impl/ViewAttendanceClinicalNotesDialogImpl.java
2821
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Florin Blindu using IMS Development Environment (version 1.80 build 5557.23004) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. package ims.emergency.domain.impl; import ims.emergency.domain.AttendanceNotesCc; import ims.emergency.domain.base.impl.BaseViewInvestigationInterventionNotesDialogImpl; public class ViewAttendanceClinicalNotesDialogImpl extends BaseViewInvestigationInterventionNotesDialogImpl { private static final long serialVersionUID = 1L; public ims.emergency.vo.AttendanceClinicalNotesVoCollection listAttendanceNotes(ims.core.patient.vo.PatientRefVo patientRef, ims.core.admin.vo.CareContextRefVo careContextRef, ims.emergency.vo.lookups.AttendanceClinicalNoteType noteType) { AttendanceNotesCc impl = (AttendanceNotesCc)getDomainImpl(AttendanceNotesCcImpl.class); return impl.listNotes(patientRef, null, careContextRef, noteType, null, null, true); } }
agpl-3.0
AlienQueen/alienlabs-skeleton-for-wicket-spring-hibernate
lib/fmj/src.test/net/sf/fmj/test/compat/formats/FormatTest.java
77611
package net.sf.fmj.test.compat.formats; import java.awt.Dimension; import javax.media.Format; import javax.media.format.AudioFormat; import javax.media.format.H261Format; import javax.media.format.H263Format; import javax.media.format.IndexedColorFormat; import javax.media.format.JPEGFormat; import javax.media.format.RGBFormat; import javax.media.format.VideoFormat; import javax.media.format.YUVFormat; import com.sun.media.format.WavAudioFormat; import junit.framework.TestCase; /** * * @author Ken Larson * */ public class FormatTest extends TestCase { class MyFormat extends Format { public MyFormat(String arg0, Class arg1) { super(arg0, arg1); } public MyFormat(String arg0) { super(arg0); } public Class getClazz() { return this.clz; } } public void testWavFormat() { { final WavAudioFormat f = new WavAudioFormat("abc"); assertEquals(f.getEncoding(), "abc"); assertEquals(f.getSampleRate(), (double) Format.NOT_SPECIFIED); assertEquals(f.getSampleSizeInBits(), Format.NOT_SPECIFIED); assertEquals(f.getChannels(), Format.NOT_SPECIFIED); assertEquals(f.getFrameSizeInBits(), Format.NOT_SPECIFIED); assertEquals(f.getAverageBytesPerSecond(), Format.NOT_SPECIFIED); assertEquals(f.getFrameRate(), (double) Format.NOT_SPECIFIED); assertEquals(f.getEndian(), Format.NOT_SPECIFIED); assertEquals(f.getSigned(), Format.NOT_SPECIFIED); assertEquals(f.getDataType(), Format.byteArray); } { final WavAudioFormat f = new WavAudioFormat("abc", 1.0, 2, 3, 4, 5, 6, 7, 8.f, Format.byteArray, new byte[] {(byte) 0}); assertEquals(f.getEncoding(), "abc"); assertEquals(f.getSampleRate(), 1.0); assertEquals(f.getSampleSizeInBits(), 2); assertEquals(f.getChannels(), 3); assertEquals(f.getFrameSizeInBits(), 4); assertEquals(f.getAverageBytesPerSecond(), 5); assertEquals(f.getFrameRate(), 5.0); assertEquals(f.getEndian(), 6); assertEquals(f.getSigned(), 7); assertEquals(f.getDataType(), Format.byteArray); } { final WavAudioFormat f = new WavAudioFormat("abc", 1.0, 2, 3, 4, 10, 6, 7, 8.f, Format.byteArray, new byte[] {(byte) 0}); assertEquals(f.getEncoding(), "abc"); assertEquals(f.getSampleRate(), 1.0); assertEquals(f.getSampleSizeInBits(), 2); assertEquals(f.getChannels(), 3); assertEquals(f.getFrameSizeInBits(), 4); assertEquals(f.getAverageBytesPerSecond(), 10); assertEquals(f.getFrameRate(), 10.0); assertEquals(f.getEndian(), 6); assertEquals(f.getSigned(), 7); assertEquals(f.getDataType(), Format.byteArray); } { final WavAudioFormat f = new WavAudioFormat("abc", 1.0, 2, 3, 4, Format.NOT_SPECIFIED, 6, 7, 8.f, Format.byteArray, new byte[] {(byte) 0}); assertEquals(f.getEncoding(), "abc"); assertEquals(f.getSampleRate(), 1.0); assertEquals(f.getSampleSizeInBits(), 2); assertEquals(f.getChannels(), 3); assertEquals(f.getFrameSizeInBits(), 4); assertEquals(f.getAverageBytesPerSecond(), Format.NOT_SPECIFIED); assertEquals(f.getFrameRate(), (double) Format.NOT_SPECIFIED); assertEquals(f.getEndian(), 6); assertEquals(f.getSigned(), 7); assertEquals(f.getDataType(), Format.byteArray); } { final WavAudioFormat f = new WavAudioFormat("abc", 1.0, 2, 3, 4, 5, new byte[] {(byte) 0}); assertEquals(f.getEncoding(), "abc"); assertEquals(f.getSampleRate(), 1.0); assertEquals(f.getSampleSizeInBits(), 2); assertEquals(f.getChannels(), 3); assertEquals(f.getFrameSizeInBits(), 4); assertEquals(f.getAverageBytesPerSecond(), 5); assertEquals(f.getFrameRate(), 5.0); assertEquals(f.getEndian(), Format.NOT_SPECIFIED); assertEquals(f.getSigned(), Format.NOT_SPECIFIED); assertEquals(f.getDataType(), Format.byteArray); } } public void testToString() { // strings assertEquals(new Format("abc").toString(), "abc"); assertEquals(new Format(null).toString(), null); assertEquals(new Format("abc", Format.byteArray).toString(), "abc"); assertEquals(new Format("abc", Format.intArray).toString(), "abc"); assertEquals(new Format("abc", Format.shortArray).toString(), "abc"); assertEquals(new VideoFormat("abc").toString(), "ABC"); assertEquals(new VideoFormat(null).toString(), "N/A"); assertEquals(new VideoFormat(VideoFormat.MPEG).toString(), "MPEG"); assertEquals(new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f).toString(), "MPEG, 0x0, FrameRate=1.0, Length=1000"); assertEquals(new VideoFormat(VideoFormat.MPEG, null, 1000, Format.byteArray, 1.f).toString(), "MPEG, FrameRate=1.0, Length=1000"); assertEquals(new VideoFormat(VideoFormat.MPEG, null, Format.NOT_SPECIFIED, Format.byteArray, 1.f).toString(), "MPEG, FrameRate=1.0"); assertEquals(new VideoFormat(VideoFormat.CINEPAK).toString(), "CVID"); assertEquals(new VideoFormat(VideoFormat.JPEG_RTP).toString(), "JPEG/RTP"); assertEquals(new VideoFormat(VideoFormat.IRGB).toString(), "IRGB"); assertEquals(new VideoFormat(VideoFormat.INDEO32).toString(), "IV32"); assertEquals(new YUVFormat().toString(), "YUV Video Format: Size = null MaxDataLength = -1 DataType = class [B yuvType = -1 StrideY = -1 StrideUV = -1 OffsetY = -1 OffsetU = -1 OffsetV = -1\n"); assertEquals(new YUVFormat(YUVFormat.YUV_111).toString(), "YUV Video Format: Size = null MaxDataLength = -1 DataType = class [B yuvType = 8 StrideY = -1 StrideUV = -1 OffsetY = -1 OffsetU = -1 OffsetV = -1\n"); assertEquals(new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, 5, 6).toString(), "YUV Video Format: Size = java.awt.Dimension[width=120,height=200] MaxDataLength = 1000 DataType = class [B yuvType = 8 StrideY = 2 StrideUV = 3 OffsetY = 4 OffsetU = 5 OffsetV = 6\n"); assertEquals(new RGBFormat().toString(), "RGB, -1-bit, Masks=-1:-1:-1, PixelStride=-1, LineStride=-1"); assertEquals(new JPEGFormat().toString(), "jpeg video format: dataType = class [B"); assertEquals(new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 1.f, 2, 3).toString(), "jpeg video format: size = 1x1 FrameRate = 1.0 maxDataLength = 1000 dataType = class [S q factor = 2 decimation = 3"); assertEquals(new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 1.f, -1, 3).toString(), "jpeg video format: size = 1x1 FrameRate = 1.0 maxDataLength = 1000 dataType = class [S decimation = 3"); assertEquals(new H261Format().toString(), "H.261 video format"); assertEquals(new H261Format(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1).toString(), "H.261 video format"); assertEquals(new H263Format().toString(), "H.263 video format"); assertEquals(new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, 4, 5, 6).toString(), "H.263 video format"); assertEquals(new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, new byte[] {0, 0}, new byte[] {0, 0}, new byte[] {0, 0}).toString(), "IRGB, 1x1, FrameRate=3.0, Length=2000"); assertEquals(new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, -1.f, 1, 2, new byte[] {0, 0}, new byte[] {0, 0}, new byte[] {0, 0}).toString(), "IRGB, 1x1, Length=2000"); assertEquals(new IndexedColorFormat(new Dimension(1, 1), -1, Format.byteArray, -1.f, 1, 2, new byte[] {0, 0}, new byte[] {0, 0}, new byte[] {0, 0}).toString(), "IRGB, 1x1"); assertEquals(new IndexedColorFormat(null, -1, Format.byteArray, -1.f, 1, 2, new byte[] {0, 0}, new byte[] {0, 0}, new byte[] {0, 0}).toString(), "IRGB"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3).toString(), "dolbyac3, Unknown Sample Rate"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray).toString(), "dolbyac3, 2.0 Hz, 1-bit, Stereo, Unsigned, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 1, 3, 4, 5, 6.0, Format.byteArray).toString(), "dolbyac3, 2.0 Hz, 1-bit, Mono, Unsigned, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 0, 3, 4, 5, 6.0, Format.byteArray).toString(), "dolbyac3, 2.0 Hz, 1-bit, 0-channel, Unsigned, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 3, 3, 4, 5, 6.0, Format.byteArray).toString(), "dolbyac3, 2.0 Hz, 1-bit, 3-channel, Unsigned, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 3, 3, 0, 5, 6.0, Format.byteArray).toString(), "dolbyac3, 2.0 Hz, 1-bit, 3-channel, Unsigned, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 3, 3, 1, 5, 6.0, Format.byteArray).toString(), "dolbyac3, 2.0 Hz, 1-bit, 3-channel, Signed, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 32, 3, 1, 1, 5, 6.0, Format.byteArray).toString(), "dolbyac3, 2.0 Hz, 32-bit, 3-channel, BigEndian, Signed, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 32, 3, 0, 1, 5, 6.0, Format.byteArray).toString(), "dolbyac3, 2.0 Hz, 32-bit, 3-channel, LittleEndian, Signed, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.LINEAR, 2.0, 16, 3, 1, 1, 5, 6.0, Format.byteArray).toString(), "LINEAR, 2.0 Hz, 16-bit, 3-channel, BigEndian, Signed, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.LINEAR, 2.0, 8, 3, 1, 1, 5, 6.0, Format.byteArray).toString(), "LINEAR, 2.0 Hz, 8-bit, 3-channel, Signed, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.LINEAR, 2.0, 9, 3, 1, 1, 5, 6.0, Format.byteArray).toString(), "LINEAR, 2.0 Hz, 9-bit, 3-channel, BigEndian, Signed, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(AudioFormat.LINEAR, 2.0, -1, 3, 1, 1, 5, 6.0, Format.byteArray).toString(), "LINEAR, 2.0 Hz, 3-channel, Signed, 6.0 frame rate, FrameSize=5 bits"); assertEquals(new AudioFormat(null).toString(), "null, Unknown Sample Rate"); } private static class CopiableFormat extends Format { public CopiableFormat(String arg0, Class arg1) { super(arg0, arg1); } public CopiableFormat(String arg0) { super(arg0); } public void doCopy(Format f) { copy(f); } } private static class CopiableVideoFormat extends VideoFormat { public CopiableVideoFormat(String arg0, Dimension arg1, int arg2, Class arg3, float arg4) { super(arg0, arg1, arg2, arg3, arg4); } public CopiableVideoFormat(String arg0) { super(arg0); } public void doCopy(Format f) { copy(f); } } public void testCopy() { { final Format f1 = new Format("abc", Format.shortArray); final CopiableFormat f2 = new CopiableFormat("xyz", Format.byteArray); f2.doCopy(f1); assertEquals(f1.getEncoding(), "abc"); assertEquals(f2.getEncoding(), "xyz"); assertEquals(f1.getDataType(), f2.getDataType()); } { final Format f1 = new Format("abc", null); final CopiableFormat f2 = new CopiableFormat("xyz", Format.byteArray); f2.doCopy(f1); assertEquals(f1.getEncoding(), "abc"); assertEquals(f2.getEncoding(), "xyz"); assertEquals(f1.getDataType(), f2.getDataType()); } { final Format f1 = new Format("abc", null); final CopiableFormat f2 = new CopiableFormat(null, Format.byteArray); f2.doCopy(f1); assertEquals(f1.getEncoding(), "abc"); assertEquals(f2.getEncoding(), null); assertEquals(f1.getDataType(), f2.getDataType()); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final CopiableVideoFormat f2 = new CopiableVideoFormat(VideoFormat.CINEPAK, new Dimension(1, 0), 1001, Format.shortArray, 2.f); f2.doCopy(f1); assertEquals(f1.getEncoding(), "mpeg"); assertEquals(f2.getEncoding(), "cvid"); assertEquals(f1.getDataType(), f2.getDataType()); assertEquals(f1.getFrameRate(), f2.getFrameRate()); assertEquals(f1.getMaxDataLength(), f2.getMaxDataLength()); assertEquals(f1.getSize(), f2.getSize()); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), Format.NOT_SPECIFIED, Format.byteArray, 1.f); final CopiableVideoFormat f2 = new CopiableVideoFormat(VideoFormat.CINEPAK, null, 1001, Format.shortArray, 2.f); f2.doCopy(f1); assertEquals(f1.getEncoding(), "mpeg"); assertEquals(f2.getEncoding(), "cvid"); assertEquals(f1.getDataType(), f2.getDataType()); assertEquals(f1.getFrameRate(), f2.getFrameRate()); assertEquals(f1.getMaxDataLength(), f2.getMaxDataLength()); assertEquals(f1.getSize(), f2.getSize()); } try { final Format f1 = new Format(VideoFormat.MPEG, Format.byteArray); final CopiableVideoFormat f2 = new CopiableVideoFormat(VideoFormat.CINEPAK, null, 1001, Format.shortArray, 2.f); f2.doCopy(f1); assertTrue(false); } catch (ClassCastException e) { } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), Format.NOT_SPECIFIED, Format.byteArray, 1.f); final CopiableFormat f2 = new CopiableFormat(VideoFormat.CINEPAK, Format.shortArray); f2.doCopy(f1); assertEquals(f1.getEncoding(), "mpeg"); assertEquals(f2.getEncoding(), "cvid"); assertEquals(f1.getDataType(), f2.getDataType()); } } public void testIntersects() { // intersects: { final Format f1 = new Format("abc"); final Format f2 = new Format("abc"); assertEquals(f1.intersects(f2), f1); assertEquals(f1.intersects(f2), f2); assertEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f2); } { final Format f1 = new Format("abc"); final Format f2 = new Format("xyz"); assertEquals(f1.intersects(f2), f2); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f2); assertEquals(f2.intersects(f1), f1); } { final Format f1 = new Format("abc"); final Format f2 = new Format(null); assertEquals(f1.intersects(f2), f1); assertNotEquals(f1.intersects(f2), f2); assertEquals(f2.intersects(f1), f1); } { final Format f1 = new Format("abc", Format.byteArray); final Format f2 = new Format(null); assertEquals(f1.intersects(f2), f1); assertNotEquals(f1.intersects(f2), f2); assertEquals(f2.intersects(f1), f1); } { final Format f1 = new Format("abc", Format.byteArray); final Format f2 = new Format("xyz", Format.shortArray); assertEquals(f1.intersects(f2), f2); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f2); assertEquals(f2.intersects(f1), f1); } { final Format f1 = new Format("abc"); final Format f2 = new VideoFormat("abc"); assertEquals(f1.intersects(f2), f2); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f2); } { final Format f1 = new Format("abc"); final Format f2 = new VideoFormat("xyz"); assertEquals(f1.intersects(f2), f2); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f2); } { final Format f1 = new Format("abc"); final Format f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); assertEquals(f1.intersects(f2), f2); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f2); } { final Format f1 = new Format("abc", Format.intArray); final Format f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); assertEquals(f1.intersects(f2), f2); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f2); } { final Format f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final Format f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(1, 0), 1000, Format.byteArray, 1.f); assertEquals(f1.intersects(f2), f1); assertNotEquals(f1.intersects(f2), f2); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f2); } { final Format f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final Format f2 = new VideoFormat(VideoFormat.MPEG, null, 1000, Format.byteArray, 1.f); assertEquals(f1.intersects(f2), f1); assertNotEquals(f1.intersects(f2), f2); assertNotEquals(f2.intersects(f1), f2); assertEquals(f2.intersects(f1), f1); } { final Format f1 = new Format("abc", Format.intArray); final Format f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); assertEquals(f1.intersects(f2), f2); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f2); } { final Format f1 = new Format(null, Format.intArray); final Format f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, null, 1.f); final Format f3 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.intArray, 1.f); assertEquals(f1.intersects(f2), f3); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f3); } { final Format f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.intArray, 2.f); final Format f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(1, 0), 1000, Format.intArray, 1.f); final Format f3 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.intArray, 2.f); final Format f4 = new VideoFormat(VideoFormat.MPEG, new Dimension(1, 0), 1000, Format.intArray, 1.f); assertEquals(f1.intersects(f2), f3); assertNotEquals(f1.intersects(f2), f2); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f4); } { final Format f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.intArray, 2.f); final Format f2 = new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8); final Format f3 = new RGBFormat(new Dimension(0, 0), 1000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8); //System.out.println(f1.intersects(f2)); //System.out.println(f3); assertEquals(f1.intersects(f2), f3); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f1); assertEquals(f2.intersects(f1), f2); } { final Format f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.intArray, Format.NOT_SPECIFIED); final Format f2 = new RGBFormat(new Dimension(1, 1), 2000, null, 2.f, 1, 2, 3, 4, 5, 6, 7, 8); final Format f3 = new RGBFormat(new Dimension(0, 0), 1000, Format.intArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8); final Format f4 = new RGBFormat(new Dimension(1, 1), 2000, Format.intArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8); // System.out.println(f1.intersects(f2)); // System.out.println(f3); assertEquals(f1.intersects(f2), f3); assertNotEquals(f1.intersects(f2), f1); assertNotEquals(f2.intersects(f1), f1); // System.out.println(f2.intersects(f1)); // System.out.println(f4); assertEquals(f2.intersects(f1), f4); } { final Format f1 = new RGBFormat(new Dimension(1, 1), 1000, Format.byteArray, 2.f, 11, 2, 13, 14, 5, 6, 17, 8); final Format f2 = new RGBFormat(new Dimension(1, 0), 2000, Format.intArray, 3.f, 1, 12, 3, 4, 15, 16, 7, 18); final Format f3 = new RGBFormat(new Dimension(1, 1), 1000, Format.intArray, 2.f, 11, 2, 13, 14, 5, 6, 17, 8); final Format f4 = new RGBFormat(new Dimension(1, 0), 2000, Format.byteArray, 3.f, 1, 12, 3, 4, 15, 16, 7, 18); // System.out.println(f1.intersects(f2)); // System.out.println(f3); assertEquals(f1.intersects(f2), f3); assertNotEquals(f1.intersects(f2), f2); assertNotEquals(f2.intersects(f1), f1); // System.out.println(f2.intersects(f1)); // System.out.println(f4); assertEquals(f2.intersects(f1), f4); } { final Format f1 = new RGBFormat(new Dimension(1, 1), 1000, Format.byteArray, 2.f, 11, 2, 13, 14, 5, 6, 17, 8); final Format f2 = new RGBFormat(); final Format f3 = (Format) f1.clone(); final Format f4 = (Format) f1.clone(); // System.out.println(f1.intersects(f2)); // System.out.println(f3); // final Format f1_2 = f1.intersects(f2); assertEquals(f1.intersects(f2), f3); assertNotEquals(f1.intersects(f2), f2); assertEquals(f2.intersects(f1), f1); // final Format f2_1 = f1.intersects(f2); // System.out.println(f2.intersects(f1)); // System.out.println(f4); assertEquals(f2.intersects(f1), f4); } { final Format f1 = new RGBFormat(new Dimension(1, 1), 1000, Format.byteArray, 2.f, 11, 2, 13, 14, 5, 6, 17, 8); final Format f2 = new YUVFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6); assertEquals(f1.intersects(f2), null); assertEquals(f2.intersects(f1), null); } } public void testRelax() { // relax: { final Format f1 = new Format("abc", Format.byteArray); assertTrue(f1.relax().equals(f1)); } { final Format f1 = new Format(null, Format.byteArray); assertTrue(f1.relax().equals(f1)); } { final Format f1 = new Format("abc"); assertTrue(f1.relax().equals(f1)); } { final Format f1 = new Format(null); assertTrue(f1.relax().equals(f1)); } { final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, new byte[] {0, 0}, new byte[] {0, 0}, new byte[] {0, 0}); final IndexedColorFormat f2 = (IndexedColorFormat) f1.relax(); assertFalse(f1.equals(f2)); assertEquals(f2.getRedValues(), f1.getRedValues()); assertEquals(f2.getGreenValues(), f1.getGreenValues()); assertEquals(f2.getBlueValues(), f1.getBlueValues()); assertEquals(f2.getEncoding(), f1.getEncoding()); assertEquals(f2.getDataType(), f1.getDataType()); assertEquals(f2.getFrameRate(), -1.f); assertEquals(f2.getLineStride(), -1); assertEquals(f2.getMapSize(), f1.getMapSize()); assertEquals(f2.getMaxDataLength(), -1); assertEquals(f2.getSize(), null); } { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray); final AudioFormat f2 = (AudioFormat) f1.relax(); assertTrue(f1.equals(f2)); assertEquals(f2.getSampleRate(), f1.getSampleRate()); assertEquals(f2.getChannels(), f1.getChannels()); assertEquals(f2.getEndian(), f1.getEndian()); assertEquals(f2.getEncoding(), f1.getEncoding()); assertEquals(f2.getDataType(), f1.getDataType()); assertEquals(f2.getFrameRate(), f1.getFrameRate()); assertEquals(f2.getFrameSizeInBits(), f1.getFrameSizeInBits()); assertEquals(f2.getSampleSizeInBits(), f1.getSampleSizeInBits()); assertEquals(f2.getSigned(), f1.getSigned()); } { final RGBFormat f1 = new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8); final RGBFormat f2 = (RGBFormat) f1.relax(); assertFalse(f1.equals(f2)); assertEquals(f2.getRedMask(), f1.getRedMask()); assertEquals(f2.getGreenMask(), f1.getGreenMask()); assertEquals(f2.getBlueMask(), f1.getBlueMask()); assertEquals(f2.getEncoding(), f1.getEncoding()); assertEquals(f2.getDataType(), f1.getDataType()); assertEquals(f2.getFrameRate(), -1.f); assertEquals(f2.getLineStride(), -1); assertEquals(f2.getEndian(), f1.getEndian()); assertEquals(f2.getBitsPerPixel(), f1.getBitsPerPixel()); assertEquals(f2.getFlipped(), f1.getFlipped()); assertEquals(f2.getMaxDataLength(), -1); assertEquals(f2.getSize(), null); } { final YUVFormat f1 = new YUVFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6); final YUVFormat f2 = (YUVFormat) f1.relax(); assertFalse(f1.equals(f2)); assertEquals(f2.getEncoding(), f1.getEncoding()); assertEquals(f2.getDataType(), f1.getDataType()); assertEquals(f2.getFrameRate(), -1.f); assertEquals(f2.getMaxDataLength(), -1); assertEquals(f2.getSize(), null); assertEquals(f2.getOffsetU(), -1); assertEquals(f2.getOffsetV(), -1); assertEquals(f2.getOffsetY(), -1); assertEquals(f2.getStrideUV(), -1); assertEquals(f2.getStrideY(), -1); assertEquals(f2.getYuvType(), f1.getYuvType()); } { final JPEGFormat f1 = new JPEGFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2); final JPEGFormat f2 = (JPEGFormat) f1.relax(); assertFalse(f1.equals(f2)); assertEquals(f2.getEncoding(), f1.getEncoding()); assertEquals(f2.getDataType(), f1.getDataType()); assertEquals(f2.getFrameRate(), -1.f); assertEquals(f2.getMaxDataLength(), -1); assertEquals(f2.getSize(), null); assertEquals(f2.getQFactor(), f1.getQFactor()); assertEquals(f2.getDecimation(), f1.getDecimation()); } { final H261Format f1 = new H261Format(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1); final H261Format f2 = (H261Format) f1.relax(); assertFalse(f1.equals(f2)); assertEquals(f2.getEncoding(), f1.getEncoding()); assertEquals(f2.getDataType(), f1.getDataType()); assertEquals(f2.getFrameRate(), -1.f); assertEquals(f2.getMaxDataLength(), -1); assertEquals(f2.getSize(), null); assertEquals(f2.getStillImageTransmission(), f1.getStillImageTransmission()); } { final H263Format f1 = new H263Format(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6); final H263Format f2 = (H263Format) f1.relax(); assertFalse(f1.equals(f2)); assertEquals(f2.getEncoding(), f1.getEncoding()); assertEquals(f2.getDataType(), f1.getDataType()); assertEquals(f2.getFrameRate(), -1.f); assertEquals(f2.getMaxDataLength(), -1); assertEquals(f2.getSize(), null); assertEquals(f2.getAdvancedPrediction(), f1.getAdvancedPrediction()); assertEquals(f2.getArithmeticCoding(), f1.getArithmeticCoding()); assertEquals(f2.getErrorCompensation(), f1.getErrorCompensation()); assertEquals(f2.getHrDB(), f1.getHrDB()); assertEquals(f2.getPBFrames(), f1.getPBFrames()); assertEquals(f2.getUnrestrictedVector(), f1.getUnrestrictedVector()); } } public void testEqualsMatches_IndexedColorFormat1() { { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); final IndexedColorFormat f2 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } // dimension { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); final IndexedColorFormat f2 = new IndexedColorFormat(new Dimension(0, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } // dataType { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); final IndexedColorFormat f2 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.shortArray, 3.f, 1, 2, arr1, arr2, arr3); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } // max { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); final IndexedColorFormat f2 = new IndexedColorFormat(new Dimension(1, 1), 2001, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); final IndexedColorFormat f2 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 4.f, 1, 2, arr1, arr2, arr3); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); final IndexedColorFormat f2 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 2, 2, arr1, arr2, arr3); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); final IndexedColorFormat f2 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 3, arr1, arr2, arr3); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); final IndexedColorFormat f2 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 3, new byte[] {0, 0}, arr2, arr3); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } public void testEqualsMatches_RGBFormat() { final RGBFormat f1 = new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8); // RGBFormat - equal and match: { final RGBFormat[] f2s = new RGBFormat[]{ new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8), (RGBFormat) f1.clone(), (RGBFormat) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { RGBFormat f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // RGBFormat - not equal and not match: { final RGBFormat[] f2s = new RGBFormat[]{ new RGBFormat(new Dimension(1, 2), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.intArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 1.f, 1, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 11, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 12, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 13, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 14, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 15, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 17, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 18), }; for (int i = 0; i < f2s.length; ++i) { RGBFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // RGBFormat - not equal but match: { final RGBFormat[] f2s = new RGBFormat[]{ new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 16, 7, 8), new RGBFormat(null, 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), Format.NOT_SPECIFIED, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, null, 2.f, 1, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, Format.NOT_SPECIFIED, 1, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, Format.NOT_SPECIFIED, 2, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, Format.NOT_SPECIFIED, 3, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, Format.NOT_SPECIFIED, 4, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, Format.NOT_SPECIFIED, 5, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, Format.NOT_SPECIFIED, 6, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, Format.NOT_SPECIFIED, 7, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, Format.NOT_SPECIFIED, 8), new RGBFormat(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6, 7, Format.NOT_SPECIFIED), }; for (int i = 0; i < f2s.length; ++i) { RGBFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches_YUVFormat() { final YUVFormat f1 = new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, 5, 6); // YUVFormat - equal and match: { final YUVFormat[] f2s = new YUVFormat[]{ new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, 5, 6), (YUVFormat) f1.clone(), (YUVFormat) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { YUVFormat f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // YUVFormat - not equal and not match: { final YUVFormat[] f2s = new YUVFormat[]{ new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_411, 2, 3, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 12, 3, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 13, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 14, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, 15, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, 5, 16), }; for (int i = 0; i < f2s.length; ++i) { YUVFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // YUVFormat - not equal but match: { final YUVFormat[] f2s = new YUVFormat[]{ new YUVFormat(null, 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), Format.NOT_SPECIFIED, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, null, 1.f, YUVFormat.YUV_111, 2, 3, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, Format.NOT_SPECIFIED, YUVFormat.YUV_111, 2, 3, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, Format.NOT_SPECIFIED, 2, 3, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, Format.NOT_SPECIFIED, 3, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, Format.NOT_SPECIFIED, 4, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, Format.NOT_SPECIFIED, 5, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, Format.NOT_SPECIFIED, 6), new YUVFormat(new java.awt.Dimension(120, 200), 1000, YUVFormat.byteArray, 1.f, YUVFormat.YUV_111, 2, 3, 4, 5, Format.NOT_SPECIFIED), }; for (int i = 0; i < f2s.length; ++i) { YUVFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches_AudioFormat() { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray); // AudioFormat - equal and match: { final AudioFormat[] f2s = new AudioFormat[]{ new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray), (AudioFormat) f1.clone(), (AudioFormat) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { AudioFormat f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // AudioFormat - not equal and not match: { final AudioFormat[] f2s = new AudioFormat[]{ new AudioFormat(AudioFormat.ALAW, 2.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 3.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 11, 2, 3, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 12, 3, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 13, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 14, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 15, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 16.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, Format.intArray), }; for (int i = 0; i < f2s.length; ++i) { AudioFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // AudioFormat - not equal but match: { final AudioFormat[] f2s = new AudioFormat[]{ new AudioFormat(null, 2.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, Format.NOT_SPECIFIED, 1, 2, 3, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, Format.NOT_SPECIFIED, 2, 3, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, Format.NOT_SPECIFIED, 3, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, Format.NOT_SPECIFIED, 4, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, Format.NOT_SPECIFIED, 5, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, Format.NOT_SPECIFIED, 6.0, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, Format.NOT_SPECIFIED, Format.byteArray), new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, null), }; for (int i = 0; i < f2s.length; ++i) { AudioFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches_H261Format() { final H261Format f1 = new H261Format(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1); // H261Format - equal and match: { final H261Format[] f2s = new H261Format[]{ new H261Format(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1), (H261Format) f1.clone(), (H261Format) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { H261Format f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // H261Format - not equal and not match: { final H261Format[] f2s = new H261Format[]{ new H261Format(new Dimension(1, 2), 2000, Format.byteArray, 3.f, 1), new H261Format(new Dimension(1, 1), 2000, Format.intArray, 3.f, 1), new H261Format(new Dimension(1, 1), 2000, Format.byteArray, 4.f, 1), new H261Format(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 11), }; for (int i = 0; i < f2s.length; ++i) { H261Format f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // H261Format - not equal but match: { final H261Format[] f2s = new H261Format[]{ new H261Format(new Dimension(1, 1), 3000, Format.byteArray, 3.f, 1), new H261Format(null, 2000, Format.byteArray, 3.f, 1), new H261Format(new Dimension(1, 1), Format.NOT_SPECIFIED, Format.byteArray, 3.f, 1), new H261Format(new Dimension(1, 1), 2000, null, 3.f, 1), new H261Format(new Dimension(1, 1), 2000, Format.byteArray, Format.NOT_SPECIFIED, 1), new H261Format(new Dimension(1, 1), 2000, Format.byteArray, 3.f, Format.NOT_SPECIFIED), }; for (int i = 0; i < f2s.length; ++i) { H261Format f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches_H263Format() { final H263Format f1 = new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, 4, 5, 6); // equal and match: { final H263Format[] f2s = new H263Format[]{ new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, 4, 5, 6), (H263Format) f1.clone(), (H263Format) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { H263Format f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // not equal and not match: { final H263Format[] f2s = new H263Format[]{ new H263Format(new Dimension(1, 2), 2000, Format.shortArray, 2.f, 1, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.byteArray, 2.f, 1, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 3.f, 1, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 11, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 12, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 13, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, 14, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, 4, 15, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, 4, 5, 16), }; for (int i = 0; i < f2s.length; ++i) { H263Format f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // not equal but match: { final H263Format[] f2s = new H263Format[]{ new H263Format(new Dimension(1, 1), 2001, Format.shortArray, 2.f, 1, 2, 3, 4, 5, 6), new H263Format(null, 2000, Format.shortArray, 2.f, 1, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), Format.NOT_SPECIFIED, Format.shortArray, 2.f, 1, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, null, 2.f, 1, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, Format.NOT_SPECIFIED, 1, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, Format.NOT_SPECIFIED, 2, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, Format.NOT_SPECIFIED, 3, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, Format.NOT_SPECIFIED, 4, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, Format.NOT_SPECIFIED, 5, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, 4, Format.NOT_SPECIFIED, 6), new H263Format(new Dimension(1, 1), 2000, Format.shortArray, 2.f, 1, 2, 3, 4, 5, Format.NOT_SPECIFIED), }; for (int i = 0; i < f2s.length; ++i) { H263Format f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches_IndexedColorFormat2() { final byte[] arr1 = new byte[] {0, 0}; final byte[] arr2 = new byte[] {0, 0}; final byte[] arr3 = new byte[] {0, 0}; final IndexedColorFormat f1 = new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3); // IndexedColorFormat - equal and match: { final IndexedColorFormat[] f2s = new IndexedColorFormat[]{ new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3), (IndexedColorFormat) f1.clone(), (IndexedColorFormat) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { IndexedColorFormat f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // IndexedColorFormat - not equal and not match: { final IndexedColorFormat[] f2s = new IndexedColorFormat[]{ new IndexedColorFormat(new Dimension(1, 2), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.shortArray, 3.f, 1, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 4.f, 1, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 11, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 12, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr2, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr3, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr1), }; for (int i = 0; i < f2s.length; ++i) { IndexedColorFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // IndexedColorFormat - not equal but match: { final IndexedColorFormat[] f2s = new IndexedColorFormat[]{ new IndexedColorFormat(new Dimension(1, 1), 2001, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3), new IndexedColorFormat(null, 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), Format.NOT_SPECIFIED, Format.byteArray, 3.f, 1, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, null, 3.f, 1, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, Format.NOT_SPECIFIED, 1, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, Format.NOT_SPECIFIED, 2, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, Format.NOT_SPECIFIED, arr1, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, null, arr2, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, null, arr3), new IndexedColorFormat(new Dimension(1, 1), 2000, Format.byteArray, 3.f, 1, 2, arr1, arr2, null), }; for (int i = 0; i < f2s.length; ++i) { IndexedColorFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches_JPEGFormat() { final JPEGFormat f1 = new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 1.f, 2, 3); // equal and match: { final JPEGFormat[] f2s = new JPEGFormat[]{ new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 1.f, 2, 3), (JPEGFormat) f1.clone(), (JPEGFormat) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { JPEGFormat f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // not equal and not match: { final JPEGFormat[] f2s = new JPEGFormat[]{ new JPEGFormat(new Dimension(1, 2), 1000, Format.shortArray, 1.f, 2, 3), new JPEGFormat(new Dimension(1, 1), 1000, Format.byteArray, 1.f, 2, 3), new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 2.f, 2, 3), new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 1.f, 12, 3), new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 1.f, 2, 13), }; for (int i = 0; i < f2s.length; ++i) { JPEGFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // not equal but match: { final JPEGFormat[] f2s = new JPEGFormat[]{ new JPEGFormat(new Dimension(1, 1), 2000, Format.shortArray, 1.f, 2, 3), new JPEGFormat(null, 1000, Format.shortArray, 1.f, 2, 3), new JPEGFormat(new Dimension(1, 1), Format.NOT_SPECIFIED, Format.shortArray, 1.f, 2, 3), new JPEGFormat(new Dimension(1, 1), 1000, null, 1.f, 2, 3), new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, Format.NOT_SPECIFIED, 2, 3), new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 1.f, Format.NOT_SPECIFIED, 3), new JPEGFormat(new Dimension(1, 1), 1000, Format.shortArray, 1.f, 2, Format.NOT_SPECIFIED), }; for (int i = 0; i < f2s.length; ++i) { JPEGFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches_VideoFormat() { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); // equal and match: { final VideoFormat[] f2s = new VideoFormat[]{ new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f), (VideoFormat) f1.clone(), (VideoFormat) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { VideoFormat f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // not equal and not match: { final VideoFormat[] f2s = new VideoFormat[]{ new VideoFormat(VideoFormat.CINEPAK, new Dimension(0, 0), 1000, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(1, 0), 1000, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.shortArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 2.f), }; for (int i = 0; i < f2s.length; ++i) { VideoFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // not equal but match: { final VideoFormat[] f2s = new VideoFormat[]{ new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 2000, Format.byteArray, 1.f), new VideoFormat(null, new Dimension(0, 0), 1000, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, null, 1000, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), Format.NOT_SPECIFIED, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, null, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, Format.NOT_SPECIFIED), }; for (int i = 0; i < f2s.length; ++i) { VideoFormat f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches_Format() { final Format f1 = new Format("abc", Format.byteArray); // equal and match: { final Format[] f2s = new Format[]{ new Format("abc", Format.byteArray), (Format) f1.clone(), (Format) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { Format f2 = f2s[i]; assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); assertTrue(f2.equals(f1)); assertTrue(f2.matches(f1)); } } // not equal and not match: { final Format[] f2s = new Format[]{ new Format("xyz", Format.byteArray), new Format("abc", Format.shortArray), new Format("abc", Format.intArray), }; for (int i = 0; i < f2s.length; ++i) { Format f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); assertFalse(f2.equals(f1)); assertFalse(f2.matches(f1)); } } // not equal but match: { final Format[] f2s = new Format[]{ new Format(null, Format.byteArray), new Format("abc", null), }; for (int i = 0; i < f2s.length; ++i) { Format f2 = f2s[i]; //System.out.println(f2); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); assertFalse(f2.equals(f1)); assertTrue(f2.matches(f1)); } } } public void testEqualsMatches() { // Format: { final Format f1 = new Format("abc"); final Format f2 = new Format("abc"); assertTrue(f1.getEncoding().equals(f2.getEncoding())); assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final Format f1 = new Format("abc", Format.byteArray); final Format f2 = new Format("abc", Format.byteArray); assertTrue(f1.getEncoding().equals(f2.getEncoding())); assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final Format f1 = new Format("abc", Format.byteArray); final Format f2 = new Format("abc", null); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final Format f1 = new Format("abc", Format.byteArray); final Format f2 = new Format("abc", Format.intArray); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); } { final Format f1 = new Format("abc", Format.byteArray); final Format f2 = new Format(null, Format.byteArray); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final Format f1 = new Format("abc"); final Format f2 = new VideoFormat("abc"); assertFalse(f1.equals(f2)); assertFalse(f2.equals(f1)); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f2)); } { final Format f1 = new Format(VideoFormat.MPEG); final Format f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); assertFalse(f1.equals(f2)); assertFalse(f2.equals(f1)); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f2)); } { final Format f1 = new Format("abc", Format.byteArray); final Format f2 = f1.relax(); assertTrue(f1.getEncoding().equals(f2.getEncoding())); assertTrue(f1.getDataType().equals(f2.getDataType())); assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final VideoFormat f1 = new VideoFormat(null); final VideoFormat f2 = new VideoFormat(null); assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG); final VideoFormat f2 = (VideoFormat) f1.clone(); assertTrue(f1 != f2); assertTrue(f1.getEncoding().equals(f2.getEncoding())); assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG_RTP); assertFalse(f1.getEncoding().equals(f2.getEncoding())); assertFalse(f1.equals(f2)); assertFalse(f1.matches(f2)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG); final VideoFormat f2 = (VideoFormat) f1.relax(); assertEquals(f1.getEncoding(), f2.getEncoding()); assertTrue(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = (VideoFormat) f1.relax(); assertEquals(f1.getEncoding(), f2.getEncoding()); assertEquals(null, f2.getSize()); assertEquals(f1.getDataType(), f2.getDataType()); assertEquals(Format.NOT_SPECIFIED, f2.getMaxDataLength()); assertEquals((float) Format.NOT_SPECIFIED, f2.getFrameRate()); assertFalse(f1.equals(f2)); assertTrue(f1.matches(f2)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(1, 0), 1000, Format.byteArray, 1.f); assertFalse(f1.matches(f2)); assertFalse(f2.matches(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG.toLowerCase(), new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG.toUpperCase(), new Dimension(0, 0), 1000, Format.byteArray, 1.f); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f1)); assertTrue(f1.equals(f2)); assertTrue(f2.equals(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG, null, 1000, Format.byteArray, 1.f); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1001, Format.byteArray, 1.f); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), Format.NOT_SPECIFIED, Format.byteArray, 1.f); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(null, new Dimension(0, 0), 1000, Format.byteArray, 1.f); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.intArray, 1.f); assertFalse(f1.matches(f2)); assertFalse(f2.matches(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, null, 1.f); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 2.f); assertFalse(f1.matches(f2)); assertFalse(f2.matches(f1)); } { final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); final VideoFormat f2 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, Format.NOT_SPECIFIED); assertTrue(f1.matches(f2)); assertTrue(f2.matches(f1)); } } // intersection: public void testIntersects_Format() { final Format f1 = new Format("abc", Format.byteArray); // equals f1 { final Format[] f2s = new Format[]{ new Format("abc", Format.byteArray), (Format) f1.clone(), (Format) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { Format f2 = f2s[i]; final Format f3 = f1.intersects(f2); assertTrue(f1.equals(f3)); assertTrue(f1.matches(f3)); assertTrue(f3.equals(f1)); assertTrue(f3.matches(f1)); } } // explicit intersect results { final Format[] f2s = new Format[]{ new Format("xyz", Format.byteArray), new Format("abc", Format.shortArray), new Format("abc", Format.intArray), new Format(null, Format.byteArray), new Format("abc", null), }; final Format[] f1_2s = new Format[]{ new Format("xyz", Format.byteArray), new Format("abc", Format.shortArray), new Format("abc", Format.intArray), new Format("abc", Format.byteArray), new Format("abc", Format.byteArray), }; final Format[] f2_1s = new Format[]{ new Format("abc", Format.byteArray), new Format("abc", Format.byteArray), new Format("abc", Format.byteArray), new Format("abc", Format.byteArray), new Format("abc", Format.byteArray), }; for (int i = 0; i < f2s.length; ++i) { final Format f2 = f2s[i]; final Format f1_2 = f1_2s[i]; final Format f2_1 = f2_1s[i]; final Format f1_2_actual = f1.intersects(f2); final Format f2_1_actual = f2.intersects(f1); // System.out.println("" + f1_2); // System.out.println("" + f1_2_actual); assertTrue(f1_2.equals(f1_2_actual)); assertTrue(f1_2.matches(f1_2_actual)); assertTrue(f1_2_actual.equals(f1_2)); assertTrue(f1_2_actual.matches(f1_2)); // System.out.println("" + f2_1); // System.out.println("" + f2_1_actual); assertTrue(f2_1.equals(f2_1_actual)); assertTrue(f2_1.matches(f2_1_actual)); assertTrue(f2_1_actual.equals(f2_1)); assertTrue(f2_1_actual.matches(f2_1)); } } } public void testIntersects_VideoFormat() { if (false) return; final VideoFormat f1 = new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f); // equals f1 { final VideoFormat[] f2s = new VideoFormat[]{ new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f), (VideoFormat) f1.clone(), (VideoFormat) f1.intersects(f1) }; for (int i = 0; i < f2s.length; ++i) { VideoFormat f2 = f2s[i]; final VideoFormat f3 = (VideoFormat) f1.intersects(f2); assertTrue(f1.equals(f3)); assertTrue(f1.matches(f3)); assertTrue(f3.equals(f1)); assertTrue(f3.matches(f1)); } } // explicit intersect results { final VideoFormat[] f2s = new VideoFormat[]{ new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 2.f), new VideoFormat(VideoFormat.MPEG, new Dimension(1, 0), 1000, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1001, Format.byteArray, 1.f), }; final VideoFormat[] f1_2s = new VideoFormat[]{ new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 1.f), }; final VideoFormat[] f2_1s = new VideoFormat[]{ new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1000, Format.byteArray, 2.f), new VideoFormat(VideoFormat.MPEG, new Dimension(1, 0), 1000, Format.byteArray, 1.f), new VideoFormat(VideoFormat.MPEG, new Dimension(0, 0), 1001, Format.byteArray, 1.f), }; for (int i = 0; i < f2s.length; ++i) { final VideoFormat f2 = f2s[i]; final VideoFormat f1_2 = f1_2s[i]; final VideoFormat f2_1 = f2_1s[i]; final VideoFormat f1_2_actual = (VideoFormat) f1.intersects(f2); final VideoFormat f2_1_actual = (VideoFormat) f2.intersects(f1); // System.out.println(f1_2); // System.out.println(f1_2_actual); assertTrue(f1_2.equals(f1_2_actual)); assertTrue(f1_2.matches(f1_2_actual)); assertTrue(f1_2_actual.equals(f1_2)); assertTrue(f1_2_actual.matches(f1_2)); // System.out.println(f2_1); // System.out.println(f2_1_actual); assertTrue(f2_1.equals(f2_1_actual)); assertTrue(f2_1.matches(f2_1_actual)); assertTrue(f2_1_actual.equals(f2_1)); assertTrue(f2_1_actual.matches(f2_1)); } } } public void testAudioFormat_computeDuration() { if (true) return; // unspecified: { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3); assertEquals(f1.computeDuration(0), -1L); assertEquals(f1.computeDuration(1), -1L); assertEquals(f1.computeDuration(1000), -1L); } final AudioFormat f0 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray); { assertEquals(f0.computeDuration(0), 0L); assertEquals(f0.computeDuration(1), 266666000L); assertEquals(f0.computeDuration(1000), 266666666000L); } // public AudioFormat(String encoding, double sampleRate, // int sampleSizeInBits, int channels, int endian, int signed, // int frameSizeInBits, double frameRate, Class dataType) // sampleRate - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 4.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // sampleRate - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, Format.NOT_SPECIFIED, 1, 2, 3, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // sampleSizeInBits - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 2, 2, 3, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // sampleSizeInBits - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 16, 2, 3, 4, 5, 6.0, Format.shortArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // sampleSizeInBits - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 32, 2, 3, 4, 5, 6.0, Format.intArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // sampleSizeInBits - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, Format.NOT_SPECIFIED, 2, 3, 4, 5, 6.0, Format.intArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // channels - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 8, 3, 3, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // channels - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 8, 1, 3, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // channels - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 8, Format.NOT_SPECIFIED, 3, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // endian - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 4, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // endian - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 0, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // endian - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 1, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // endian - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, Format.NOT_SPECIFIED, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // signed: - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 5, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // signed: - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 0, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // signed: - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 1, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // signed: - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, Format.NOT_SPECIFIED, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // dataType - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, Format.intArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } // dataType - DOES NOT AFFECT. { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 6.0, Format.shortArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); } { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 4.0, 1, 2, 3, 4, 5, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), f0.computeDuration(0)); assertEquals(f1.computeDuration(1), f0.computeDuration(1)); assertEquals(f1.computeDuration(1000), f0.computeDuration(1000)); compare(f1, 0); compare(f1, 1); compare(f1, 1000); } // assertEquals(f0.computeDuration(0), 0L); // assertEquals(f0.computeDuration(1), 266,666,000L); // assertEquals(f0.computeDuration(1000), 266666666000L); // frameSizeInBits: AFFECTS - inversely { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 6, 6.0, Format.byteArray); assertEquals(f1.computeDuration(0), 0L); assertEquals(f1.computeDuration(1), 222222000L); assertEquals(f1.computeDuration(1000), 222222166000L); compare(f1, 0); compare(f1, 1); compare(f1, 1000); } // frameRate: AFFECTS - inversely { final AudioFormat f1 = new AudioFormat(AudioFormat.DOLBYAC3, 2.0, 1, 2, 3, 4, 5, 7.0, Format.byteArray); assertEquals(f1.computeDuration(0), 0L); assertEquals(f1.computeDuration(1), 228571000L); assertEquals(f1.computeDuration(1000), 228571428000L); compare(f1, 0); compare(f1, 1); compare(f1, 1000); } } private static void compare(AudioFormat f1, long length) { System.out.println(f1); System.out.println("length: " + length); long dur = f1.computeDuration(length); long calc = calc(f1, length); System.out.println("" + dur); System.out.println("" + calc); System.out.println("" + (double) dur / (double) calc); System.out.println(); } private static long calc(AudioFormat f1, long length) { return 1000L * (long)((length * 8 * 1000000.0 / ((double) f1.getFrameRate() * (double) (f1.getFrameSizeInBits())))); } public void testConstants() { assertEquals(new H261Format().getEncoding(), "h261"); assertEquals(new H261Format().getStillImageTransmission(), Format.NOT_SPECIFIED); assertEquals(new H261Format().getFrameRate(), (float) Format.NOT_SPECIFIED); assertEquals(new H261Format().getMaxDataLength(), Format.NOT_SPECIFIED); assertEquals(new H261Format().getSize(), null); assertEquals(new H261Format().getDataType(), Format.byteArray); assertEquals(new H263Format().getEncoding(), "h263"); assertEquals(new H263Format().getDataType(), Format.byteArray); final IndexedColorFormat indexedColorFormat = new IndexedColorFormat(new java.awt.Dimension(0, 0), 0, null, 0.f, 0, 0, null, null, null); assertEquals(indexedColorFormat.getEncoding(), "irgb"); assertEquals(indexedColorFormat.getDataType(), null); assertEquals(new JPEGFormat().getEncoding(), "jpeg"); assertEquals(new JPEGFormat().getDecimation(), Format.NOT_SPECIFIED); assertEquals(new JPEGFormat().getQFactor(), Format.NOT_SPECIFIED); assertEquals(new JPEGFormat().getDataType(), Format.byteArray); assertEquals(new RGBFormat().getEncoding(), "rgb"); assertEquals(new RGBFormat().getDataType(), null); assertEquals(new YUVFormat().getEncoding(), "yuv"); assertEquals(new YUVFormat().getOffsetV(), -1); assertTrue(new YUVFormat().getSize() == null); assertEquals(new YUVFormat().getDataType(), Format.byteArray); assertEquals(new AudioFormat(AudioFormat.DOLBYAC3).getDataType(), Format.byteArray); } private void assertNotEquals(Object a, Object b) { if (a == null && b == null) assertFalse(true); else if (a == null || b == null) return; assertFalse(a.equals(b)); } private void assertEquals(double a, double b) { assertTrue(a == b); } }
agpl-3.0
kelvinmbwilo/vims
modules/report/src/main/java/org/openlmis/report/model/report/ConsumptionReport.java
1475
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ package org.openlmis.report.model.report; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.openlmis.report.model.ReportData; @Data @NoArgsConstructor @AllArgsConstructor public class ConsumptionReport implements ReportData { private int year; private String periodString; private String facilityType; private String facility; private String category; private String product; private String supplier; private String reportingGroup; private Integer consumption; }
agpl-3.0
backslash47/jzkit
jzkit_jdbc_plugin/src/main/java/org/jzkit/search/provider/jdbc/Mapping.java
325
package org.jzkit.search.provider.jdbc; import java.util.*; /** * Title: * Description: * Copyright: * * Company: * @author: Ian Ibbotson (ian.ibbotson@sun.com) * @version: $Id: Mapping.java,v 1.1 2004/10/27 14:42:42 ibbo Exp $ */ public interface Mapping { }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Clinical/src/ims/clinical/forms/edischargefutureplansthkcomponent/FormInfo.java
3048
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinical.forms.edischargefutureplansthkcomponent; public final class FormInfo extends ims.framework.FormInfo { private static final long serialVersionUID = 1L; public FormInfo(Integer formId) { super(formId); } public String getNamespaceName() { return "Clinical"; } public String getFormName() { return "EDischargeFuturePlanSthkComponent"; } public int getWidth() { return 848; } public int getHeight() { return 632; } public String[] getContextVariables() { return new String[] { }; } public String getLocalVariablesPrefix() { return "_lv_Clinical.EDischargeFuturePlanSthkComponent.__internal_x_context__" + String.valueOf(getFormId()); } public ims.framework.FormInfo[] getComponentsFormInfo() { ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[0]; return componentsInfo; } public String getImagePath() { return ""; } }
agpl-3.0
bjornna/adl2-core
adl2core-parser/src/test/java/org/openehr/adl/flattener/AttributeExpansionTest.java
1642
/* * ADL2-core * Copyright (c) 2013-2014 Marand d.o.o. (www.marand.com) * * This file is part of ADL2-core. * * ADL2-core is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openehr.adl.flattener; import org.openehr.adl.am.AmQuery; import org.openehr.adl.rm.RmTypes; import org.openehr.jaxb.am.Archetype; import org.openehr.jaxb.am.CObject; import org.testng.annotations.Test; /** * @author markopi */ public class AttributeExpansionTest extends FlattenerTestBase { // @Test // public void testAttributeExpansion() throws Exception { // Archetype flattened = parseAndFlattenArchetype("adl15/openEHR-EHR-EVALUATION.alert-zn.v1.adls"); // // CObject definingCode = AmQuery.get(flattened, "data/items[at0003]/value/defining_code"); // assertCObject(definingCode, RmTypes.TERMINOLOGY_CODE, null, null); // // assertCTerminologyCode(definingCode, "local", // new String[]{"at0.15", "at0.16", "at0.17", "at0.18", "at0.19", "at0.20", "at0.21", "at0.22"}, null); // } }
agpl-3.0
8kdata/mongowp
bson/bson-netty/src/main/java/com/torodb/mongowp/bson/netty/NettyBsonDocumentWriter.java
7652
/* * Copyright 2014 8Kdata Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.torodb.mongowp.bson.netty; import com.google.common.base.Charsets; import com.google.common.primitives.UnsignedInteger; import com.torodb.mongowp.bson.BsonArray; import com.torodb.mongowp.bson.BsonBinary; import com.torodb.mongowp.bson.BsonBoolean; import com.torodb.mongowp.bson.BsonDateTime; import com.torodb.mongowp.bson.BsonDbPointer; import com.torodb.mongowp.bson.BsonDecimal128; import com.torodb.mongowp.bson.BsonDeprecated; import com.torodb.mongowp.bson.BsonDocument; import com.torodb.mongowp.bson.BsonDocument.Entry; import com.torodb.mongowp.bson.BsonDouble; import com.torodb.mongowp.bson.BsonInt32; import com.torodb.mongowp.bson.BsonInt64; import com.torodb.mongowp.bson.BsonJavaScript; import com.torodb.mongowp.bson.BsonJavaScriptWithScope; import com.torodb.mongowp.bson.BsonMax; import com.torodb.mongowp.bson.BsonMin; import com.torodb.mongowp.bson.BsonNull; import com.torodb.mongowp.bson.BsonObjectId; import com.torodb.mongowp.bson.BsonRegex; import com.torodb.mongowp.bson.BsonString; import com.torodb.mongowp.bson.BsonTimestamp; import com.torodb.mongowp.bson.BsonUndefined; import com.torodb.mongowp.bson.BsonValue; import com.torodb.mongowp.bson.BsonValueVisitor; import com.torodb.mongowp.bson.utils.NonIoByteSource; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.annotation.concurrent.ThreadSafe; /** * */ @ThreadSafe public class NettyBsonDocumentWriter { private static final WriterBsonValueVisitor VISITOR = new WriterBsonValueVisitor(); public void writeInto(ByteBuf byteBuf, BsonDocument doc) { doc.accept(VISITOR, byteBuf); } private static class WriterBsonValueVisitor implements BsonValueVisitor<Void, ByteBuf> { void writeCString(ByteBuf buf, String str) { buf.writeBytes(str.getBytes(Charsets.UTF_8)); buf.writeByte(0x00); } void writeString(ByteBuf buf, String str) { byte[] bytes = str.getBytes(Charsets.UTF_8); int length = bytes.length + 1; buf.writeInt(length).writeBytes(bytes).writeByte(0x00); } @Override public Void visit(BsonArray value, ByteBuf arg) { final int docStart = arg.writerIndex(); arg.writeInt(0); // reserve space for doc size int i = 0; for (BsonValue<?> child : value) { try { arg.writeByte(ParsingTools.getByte(child.getType())); } catch (NettyBsonReaderException ex) { throw new AssertionError(ex); } writeCString(arg, Integer.toString(i)); child.accept(this, arg); i++; } arg.writeByte(0x00); int docEnd = arg.writerIndex(); arg.writerIndex(docStart).writeInt(docEnd - docStart).writerIndex(docEnd); return null; } @Override public Void visit(BsonBinary value, ByteBuf arg) { NonIoByteSource byteSource = value.getByteSource(); UnsignedInteger unsignedSize; unsignedSize = UnsignedInteger.valueOf(byteSource.size()); arg.writeInt(unsignedSize.intValue()).writeByte(value.getNumericSubType()); try (OutputStream os = new ByteBufOutputStream(arg)) { value.getByteSource().copyTo(os); } catch (IOException ex) { throw new AssertionError("Unexpected IOException", ex); } return null; } @Override public Void visit(BsonDbPointer value, ByteBuf arg) { writeString(arg, value.getNamespace()); value.getId().accept(this, arg); return null; } @Override public Void visit(BsonDateTime value, ByteBuf arg) { arg.writeLong(value.getMillisFromUnix()); return null; } @Override public Void visit(BsonDocument value, ByteBuf arg) { final int docStart = arg.writerIndex(); arg.writeInt(0); // reserve space for doc size for (Entry<?> entry : value) { BsonValue<?> child = entry.getValue(); try { arg.writeByte(ParsingTools.getByte(child.getType())); } catch (NettyBsonReaderException ex) { throw new AssertionError(ex); } writeCString(arg, entry.getKey()); child.accept(this, arg); } arg.writeByte(0x00); int docEnd = arg.writerIndex(); arg.writerIndex(docStart).writeInt(docEnd - docStart).writerIndex(docEnd); return null; } @Override public Void visit(BsonDouble value, ByteBuf arg) { arg.writeDouble(value.doubleValue()); return null; } @Override public Void visit(BsonInt32 value, ByteBuf arg) { arg.writeInt(value.intValue()); return null; } @Override public Void visit(BsonInt64 value, ByteBuf arg) { arg.writeLong(value.longValue()); return null; } @Override public Void visit(BsonBoolean value, ByteBuf arg) { if (value.getPrimitiveValue()) { arg.writeByte(0x01); } else { arg.writeByte(0x00); } return null; } @Override public Void visit(BsonJavaScript value, ByteBuf arg) { writeString(arg, value.getValue()); return null; } @Override public Void visit(BsonJavaScriptWithScope value, ByteBuf arg) { final int codeWsStart = arg.writerIndex(); arg.writeInt(0); // reserve space for code_w_s size writeString(arg, value.getJavaScript()); value.getScope().accept(VISITOR, arg); final int codeWsEnds = arg.writerIndex(); arg.writerIndex(codeWsStart).writeInt(codeWsEnds - codeWsStart).writerIndex(codeWsEnds); return null; } @Override public Void visit(BsonMax value, ByteBuf arg) { return null; } @Override public Void visit(BsonMin value, ByteBuf arg) { return null; } @Override public Void visit(BsonNull value, ByteBuf arg) { return null; } @Override public Void visit(BsonObjectId value, ByteBuf arg) { arg.writeBytes(value.toByteArray()); return null; } @Override public Void visit(BsonRegex value, ByteBuf arg) { writeCString(arg, value.getPattern()); writeCString(arg, value.getOptionsAsText()); return null; } @Override public Void visit(BsonString value, ByteBuf arg) { writeString(arg, value.getValue()); return null; } @Override public Void visit(BsonUndefined value, ByteBuf arg) { return null; } @Override public Void visit(BsonTimestamp value, ByteBuf arg) { arg.writeInt(value.getOrdinal()).writeInt(value.getSecondsSinceEpoch()); return null; } @Override public Void visit(BsonDeprecated value, ByteBuf arg) { writeString(arg, value.getValue()); return null; } // TODO Review this method @Override public Void visit(BsonDecimal128 value, ByteBuf arg) { byte[] bytes = value.getBytes(); // Assert.assertTrue("Expected 16 bytes but lenght is ", bytes.length == 15); arg.writeBytes(bytes); return null; } } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/nursing/vo/BowelDiarrhoeaConstipationVo.java
8880
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo; /** * Linked to nursing.assessment.Bowel DiarrhoeaConstipation business object (ID: 1015100020). */ public class BowelDiarrhoeaConstipationVo extends ims.nursing.assessment.vo.BowelDiarrhoeaConstipationRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public BowelDiarrhoeaConstipationVo() { } public BowelDiarrhoeaConstipationVo(Integer id, int version) { super(id, version); } public BowelDiarrhoeaConstipationVo(ims.nursing.vo.beans.BowelDiarrhoeaConstipationVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.sufferfrom = bean.getSufferFrom() == null ? null : ims.nursing.vo.lookups.BowelConstipationDiarrhoea.buildLookup(bean.getSufferFrom()); this.status = bean.getStatus() == null ? null : ims.core.vo.lookups.YesNoUnknown.buildLookup(bean.getStatus()); this.details = bean.getDetails(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.beans.BowelDiarrhoeaConstipationVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.sufferfrom = bean.getSufferFrom() == null ? null : ims.nursing.vo.lookups.BowelConstipationDiarrhoea.buildLookup(bean.getSufferFrom()); this.status = bean.getStatus() == null ? null : ims.core.vo.lookups.YesNoUnknown.buildLookup(bean.getStatus()); this.details = bean.getDetails(); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.beans.BowelDiarrhoeaConstipationVoBean bean = null; if(map != null) bean = (ims.nursing.vo.beans.BowelDiarrhoeaConstipationVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.nursing.vo.beans.BowelDiarrhoeaConstipationVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("SUFFERFROM")) return getSufferFrom(); if(fieldName.equals("STATUS")) return getStatus(); if(fieldName.equals("DETAILS")) return getDetails(); return super.getFieldValueByFieldName(fieldName); } public boolean getSufferFromIsNotNull() { return this.sufferfrom != null; } public ims.nursing.vo.lookups.BowelConstipationDiarrhoea getSufferFrom() { return this.sufferfrom; } public void setSufferFrom(ims.nursing.vo.lookups.BowelConstipationDiarrhoea value) { this.isValidated = false; this.sufferfrom = value; } public boolean getStatusIsNotNull() { return this.status != null; } public ims.core.vo.lookups.YesNoUnknown getStatus() { return this.status; } public void setStatus(ims.core.vo.lookups.YesNoUnknown value) { this.isValidated = false; this.status = value; } public boolean getDetailsIsNotNull() { return this.details != null; } public String getDetails() { return this.details; } public static int getDetailsMaxLength() { return 255; } public void setDetails(String value) { this.isValidated = false; this.details = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; BowelDiarrhoeaConstipationVo clone = new BowelDiarrhoeaConstipationVo(this.id, this.version); if(this.sufferfrom == null) clone.sufferfrom = null; else clone.sufferfrom = (ims.nursing.vo.lookups.BowelConstipationDiarrhoea)this.sufferfrom.clone(); if(this.status == null) clone.status = null; else clone.status = (ims.core.vo.lookups.YesNoUnknown)this.status.clone(); clone.details = this.details; clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(BowelDiarrhoeaConstipationVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A BowelDiarrhoeaConstipationVo object cannot be compared an Object of type " + obj.getClass().getName()); } BowelDiarrhoeaConstipationVo compareObj = (BowelDiarrhoeaConstipationVo)obj; int retVal = 0; if (retVal == 0) { if(this.getID_BowelDiarrhoeaConstipation() == null && compareObj.getID_BowelDiarrhoeaConstipation() != null) return -1; if(this.getID_BowelDiarrhoeaConstipation() != null && compareObj.getID_BowelDiarrhoeaConstipation() == null) return 1; if(this.getID_BowelDiarrhoeaConstipation() != null && compareObj.getID_BowelDiarrhoeaConstipation() != null) retVal = this.getID_BowelDiarrhoeaConstipation().compareTo(compareObj.getID_BowelDiarrhoeaConstipation()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.sufferfrom != null) count++; if(this.status != null) count++; if(this.details != null) count++; return count; } public int countValueObjectFields() { return 3; } protected ims.nursing.vo.lookups.BowelConstipationDiarrhoea sufferfrom; protected ims.core.vo.lookups.YesNoUnknown status; protected String details; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/nursing/assessment/vo/BowelOstomyRefVo.java
4718
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.assessment.vo; /** * Linked to nursing.assessment.Bowel Ostomy business object (ID: 1015100004). */ public class BowelOstomyRefVo extends ims.vo.ValueObjectRef implements ims.domain.IDomainGetter { private static final long serialVersionUID = 1L; public BowelOstomyRefVo() { } public BowelOstomyRefVo(Integer id, int version) { super(id, version); } public final boolean getID_BowelOstomyIsNotNull() { return this.id != null; } public final Integer getID_BowelOstomy() { return this.id; } public final void setID_BowelOstomy(Integer value) { this.id = value; } public final int getVersion_BowelOstomy() { return this.version; } public Object clone() { return new BowelOstomyRefVo(this.id, this.version); } public final BowelOstomyRefVo toBowelOstomyRefVo() { if(this.id == null) return this; return new BowelOstomyRefVo(this.id, this.version); } public boolean equals(Object obj) { if(!(obj instanceof BowelOstomyRefVo)) return false; BowelOstomyRefVo compareObj = (BowelOstomyRefVo)obj; if(this.id != null && compareObj.getBoId() != null) return this.id.equals(compareObj.getBoId()); if(this.id != null && compareObj.getBoId() == null) return false; if(this.id == null && compareObj.getBoId() != null) return false; return super.equals(obj); } public int hashCode() { if(this.id != null) return this.id.intValue(); return super.hashCode(); } public boolean isValidated() { return true; } public String[] validate() { return null; } public String getBoClassName() { return "ims.nursing.assessment.domain.objects.BowelOstomy"; } public Class getDomainClass() { return ims.nursing.assessment.domain.objects.BowelOstomy.class; } public String getIItemText() { return toString(); } public String toString() { return this.getClass().toString() + " (ID: " + (this.id == null ? "null" : this.id.toString()) + ")"; } public int compareTo(Object obj) { if (obj == null) return -1; if (!(obj instanceof BowelOstomyRefVo)) throw new ClassCastException("A BowelOstomyRefVo object cannot be compared an Object of type " + obj.getClass().getName()); if (this.id == null) return 1; if (((BowelOstomyRefVo)obj).getBoId() == null) return -1; return this.id.compareTo(((BowelOstomyRefVo)obj).getBoId()); } // this method is not needed. It is here for compatibility purpose only. public int compareTo(Object obj, boolean caseInsensitive) { if(caseInsensitive); // this is to avoid Eclipse warning return compareTo(obj); } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("ID_BOWELOSTOMY")) return getID_BowelOstomy(); return super.getFieldValueByFieldName(fieldName); } }
agpl-3.0
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/domain/WardView.java
8402
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.domain; // Generated from form domain impl public interface WardView extends ims.domain.DomainInterface { // Generated from form domain interface definition /** * Lists all floor layouts */ public ims.core.vo.FloorBedSpaceLayoutLiteVoCollection list(); // Generated from form domain interface definition public ims.core.vo.FloorBedSpaceLayoutVo get(ims.core.layout.vo.FloorBedSpaceLayoutRefVo id); // Generated from form domain interface definition /** * listWardsForCurrentLocation */ public ims.core.vo.LocationLiteVoCollection listWardsForCurrentLocation(ims.framework.interfaces.ILocation parentLocation); // Generated from form domain interface definition /** * listBaysForCurrentWard */ public ims.core.vo.LocationLiteVoCollection listBaysForCurrentWard(ims.framework.interfaces.ILocation parentWard); // Generated from form domain interface definition /** * listLayoutForCurrentBay */ public ims.core.vo.FloorBedSpaceLayoutVo listLayoutForCurrentBay(ims.framework.interfaces.ILocation bay); // Generated from form domain interface definition /** * getBedSpaceState */ public ims.core.vo.BedSpaceStateLiteVo getBedSpaceState(ims.core.layout.vo.BedSpaceRefVo bed); // Generated from form domain interface definition /** * listInpatientEpisodeByWard */ public ims.core.vo.InpatientEpisodeLiteVoCollection listInpatientEpisodeByWard(ims.core.resource.place.vo.LocationRefVo ward); // Generated from form domain interface definition /** * listPendingElectiveAdmission */ public ims.core.vo.PendingElectiveAdmissionAdmitVoCollection listPendingElectiveAdmission(ims.core.resource.place.vo.LocationRefVo voLocation); // Generated from form domain interface definition /** * listEmergencyAdmission */ public ims.core.vo.PendingEmergencyAdmissionAdmitVoCollection listEmergencyAdmission(ims.core.resource.place.vo.LocationRefVo location); // Generated from form domain interface definition /** * listPendingTransfersInByWard */ public ims.core.vo.PendingTransfersLiteVoCollection listPendingTransfersInByWard(ims.core.resource.place.vo.LocationRefVo destWard); // Generated from form domain interface definition /** * listPendingTransfersOutByWard */ public ims.core.vo.PendingTransfersLiteVoCollection listPendingTransfersOutByWard(ims.core.resource.place.vo.LocationRefVo currentLocation); // Generated from form domain interface definition public ims.core.vo.LocationLiteVoCollection listActiveHospitalsLite(); // Generated from form domain interface definition /** * getWardBayConfig */ public ims.core.vo.WardBayConfigForWardViewVo getWardBayConfigByWard(ims.core.resource.place.vo.LocationRefVo ward); // Generated from form domain interface definition /** * listWaitingAreaPatientsByWard */ public ims.core.vo.InpatientEpisodeLiteVoCollection listWaitingAreaPatientsByWard(ims.core.resource.place.vo.LocationRefVo ward); // Generated from form domain interface definition public ims.core.vo.LocMostVo getLocation(ims.core.resource.place.vo.LocationRefVo voLocRef); // Generated from form domain interface definition /** * countInfants (WDEV-7722) */ public int countInfants(ims.core.patient.vo.PatientRefVo patient); // Generated from form domain interface definition /** * cancelTransfer */ public void cancelTransfer(ims.core.vo.PendingTransfersLiteVo voTransfer, ims.core.resource.place.vo.LocationRefVo voCancellingfromWard) throws ims.domain.exceptions.StaleObjectException, ims.domain.exceptions.ForeignKeyViolationException; // Generated from form domain interface definition /** * getMothersAdmission */ public ims.core.vo.AdmissionDetailMotherVo getMothersAdmission(ims.core.patient.vo.PatientRefVo patient); // Generated from form domain interface definition /** * getCareContextForPasEvent */ public ims.core.vo.CareContextShortVo getCareContextForPasEvent(ims.core.admin.pas.vo.PASEventRefVo pasEvent); // Generated from form domain interface definition /** * getSystemReportAndTemplate */ public String[] getSystemReportAndTemplate(Integer imsId); // Generated from form domain interface definition public ims.dto.client.Patient getPatient(String pid, String identifier) throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public ims.dto.client.Patient getCCODTOPatient(String pkey) throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition /** * listHomeLeaveByWard */ public ims.core.vo.InpatientEpisodeLiteVoCollection listHomeLeaveByWard(ims.core.resource.place.vo.LocationRefVo ward); // Generated from form domain interface definition public String getPIDDiagnosisInfo(ims.core.admin.vo.CareContextRefVo careContextRefVo, ims.core.admin.vo.EpisodeOfCareRefVo episodeRefVo); // Generated from form domain interface definition public ims.core.vo.LocationLiteVo getCurrentHospital(ims.framework.interfaces.ILocation location); // Generated from form domain interface definition public ims.core.vo.PatientElectiveListForWardViewVoCollection listPatientElectiveListForWardViewVo(ims.core.resource.place.vo.LocationRefVo ward, ims.framework.utils.Date tcidate); // Generated from form domain interface definition /** * listInpatientEpisodeByWard */ public ims.core.vo.InpatientEpisodeLiteVoCollection listInpatientEpisodeByWard(ims.core.resource.place.vo.LocationRefVo ward, ims.core.patient.vo.PatientRefVo patient); // Generated from form domain interface definition public void updateOccupiedBedsForWardAndBay(ims.core.resource.place.vo.LocationRefVo ward, ims.core.resource.place.vo.LocationRefVo bayOne, ims.core.resource.place.vo.LocationRefVo bayTwo) throws ims.domain.exceptions.StaleObjectException; // Generated from form domain interface definition public ims.core.vo.WardBedStateVoCollection listBedSpacesState(ims.core.vo.BedSpaceVoCollection bedSpaces) throws ims.domain.exceptions.DomainInterfaceException; // Generated from form domain interface definition public ims.core.vo.PatientShort getPatientShort(ims.core.patient.vo.PatientRefVo patient); }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ClinicalAdmin/src/ims/clinicaladmin/domain/TumourOverallStaging.java
2899
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.clinicaladmin.domain; // Generated from form domain impl public interface TumourOverallStaging extends ims.domain.DomainInterface { // Generated from form domain interface definition /** * getTNMValueForSite */ public ims.clinicaladmin.vo.TumourGroupSiteTNMValueListVoCollection getTNMValueForSite(ims.oncology.configuration.vo.TumourSiteRefVo refVo); // Generated from form domain interface definition /** * getGroupForOverallStaging */ public ims.clinicaladmin.vo.TumourGroupSiteForOverallStagingDialogVo getGroupForOverallStaging(ims.oncology.configuration.vo.TumourGroupRefVo voRef); // Generated from form domain interface definition public ims.clinicaladmin.vo.TumourSiteVo getSiteVo(ims.oncology.configuration.vo.TumourSiteRefVo voSiteRefVo); }
agpl-3.0
deerwalk/voltdb
src/frontend/org/voltdb/client/ProcedureCallback.java
1405
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.client; /** * Abstract base class for callbacks that are invoked when an asynchronously invoked transaction receives a response. * Extend this class and provide an implementation of {@link #clientCallback} to receive a response to a * stored procedure invocation. */ public interface ProcedureCallback { /** * Implementation of callback to be provided by client applications. * * @param clientResponse Response to the stored procedure invocation this callback is associated with * @throws Exception on any Exception. */ abstract public void clientCallback(ClientResponse clientResponse) throws Exception; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/vo/interfaces/IPatientJourneyClock.java
2714
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.vo.interfaces; /* * IPatientJourneyClock */ public interface IPatientJourneyClock extends Comparable { /* * Clock Name */ String getIPatientJourneyClockName(); /* * Start Date */ ims.framework.utils.Date getIPatientJourneyClockStartDate(); /* * Stop Date */ ims.framework.utils.Date getIPatientJourneyClockStopDate(); /* * Patient Journey Current Pause */ ims.pathways.vo.PauseDetailsVo getIPatientJourneyCurrentPause(); /* * Patient Journey Pause Details */ ims.pathways.vo.PauseDetailsVoCollection getIPatientJourneyPauseDetails(); }
agpl-3.0
carltonwhitehead/coner
service/src/main/java/org/coner/core/mapper/ConerBaseMapStructConfig.java
177
package org.coner.core.mapper; import org.mapstruct.MapperConfig; @MapperConfig( uses = ConerBaseMapStructMapper.class ) public interface ConerBaseMapStructConfig { }
agpl-3.0
sweble/sweble-wom3
sweble-wom3-core/src/main/java/org/sweble/wom3/Wom3TableBody.java
1054
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package org.sweble.wom3; /** * Denotes the body section of a table. * * Corresponds to the XHTML 1.0 Transitional element "tbody". * * See WomTablePartition for details. */ public interface Wom3TableBody extends Wom3TablePartition, Wom3UniversalAttributes { }
agpl-3.0
aborg0/RapidMiner-Unuk
src/com/rapidminer/gui/dialog/AttributeWeightCellEditor.java
4086
/* * RapidMiner * * Copyright (C) 2001-2013 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.gui.dialog; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractCellEditor; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.JTextField; import com.rapidminer.gui.properties.celleditors.value.PropertyValueCellEditor; import com.rapidminer.operator.Operator; /** * Editor for attribute weights. A text field for numeric values and three * buttons. The first button sets the weight to zero, the second button to 1, * and the third resets the value to the old weight. This editor is used by an * {@link AttributeWeightsTableModel}. * * @author Ingo Mierswa * ingomierswa Exp $ */ public class AttributeWeightCellEditor extends AbstractCellEditor implements PropertyValueCellEditor { private static final long serialVersionUID = 4648838759294286088L; private JPanel panel = new JPanel(); private JTextField textField = new JTextField(12); private GridBagLayout gridBagLayout = new GridBagLayout(); public AttributeWeightCellEditor(double oldValue) { super(); panel.setLayout(gridBagLayout); panel.setToolTipText("The weight for this attribute."); textField.setToolTipText("The weight for this attribute."); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1; gridBagLayout.setConstraints(textField, c); panel.add(textField); c.weightx = 0; addButton(createValueButton("Zero", "0.0"), 1); addButton(createValueButton("One", "1.0"), GridBagConstraints.RELATIVE); addButton(createValueButton("Reset", oldValue + ""), GridBagConstraints.REMAINDER); } /** Does nothing. */ public void setOperator(Operator operator) {} protected JButton createValueButton(String name, final String newValue) { JButton button = new JButton(name); button.setMargin(new Insets(0, 0, 0, 0)); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textField.setText(newValue); fireEditingStopped(); } }); button.setToolTipText("Sets the weight of this attribute to " + newValue + "."); return button; } protected void addButton(JButton button, int gridwidth) { GridBagConstraints c = new GridBagConstraints(); c.gridwidth = gridwidth; c.weightx = 0; c.fill = GridBagConstraints.BOTH; gridBagLayout.setConstraints(button, c); panel.add(button); } public Object getCellEditorValue() { return (textField.getText().trim().length() == 0) ? null : textField.getText().trim(); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int col) { textField.setText((value == null) ? "" : value.toString()); return panel; } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return getTableCellEditorComponent(table, value, isSelected, row, column); } public boolean useEditorAsRenderer() { return true; } @Override public boolean rendersLabel() { return false; } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/vitalsignsbaselineandall/Handlers.java
19919
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.vitalsignsbaselineandall; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode { abstract protected void bindcmbTimePeriodLookup(); abstract protected void defaultcmbTimePeriodLookupValue(); abstract protected void bindcmbPainScoreLookup(); abstract protected void defaultcmbPainScoreLookupValue(); abstract protected void bindcmbPatientConcernLookup(); abstract protected void defaultcmbPatientConcernLookupValue(); abstract protected void bindcmbUrineLookup(); abstract protected void defaultcmbUrineLookupValue(); abstract protected void bindcmbConsciousLookup(); abstract protected void defaultcmbConsciousLookupValue(); abstract protected void bindcmbVisualRightLookup(); abstract protected void defaultcmbVisualRightLookupValue(); abstract protected void bindcmbRightReactionPupilLookup(); abstract protected void defaultcmbRightReactionPupilLookupValue(); abstract protected void bindcmbVisualLeftLookup(); abstract protected void defaultcmbVisualLeftLookupValue(); abstract protected void bindcmbLeftReactionPupilLookup(); abstract protected void defaultcmbLeftReactionPupilLookupValue(); abstract protected void onFormModeChanged(); abstract protected void onMessageBoxClosed(int messageBoxId, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onFormDialogClosed(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException; abstract protected void onRecbrHistoryValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnEditClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnNewClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnSaveClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnCancelClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnCalculateULNAClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onRadioButtonBloodGlucoseGroup1ValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void oncmbTimePeriodValueSet(Object value); abstract protected void onLnkCBGMClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkBMIClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void oncmbPainScoreValueSet(Object value); abstract protected void onLnkPainLadderClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnBMIClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkTemperatureClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkMetricsClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkPeakFlowClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onChkonFiO2ValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkOxygenSaturationClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkRespirationsClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onRadioButtonGroupBPValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkBloodPresureClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkPulseClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void oncmbPatientConcernValueSet(Object value); abstract protected void oncmbUrineValueSet(Object value); abstract protected void oncmbConsciousValueSet(Object value); abstract protected void oncmbVisualRightValueSet(Object value); abstract protected void onLnkGCSClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkPupilsClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onLnkVisualAcuityClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void oncmbRightReactionPupilValueSet(Object value); abstract protected void onCmbVResponseValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onCmbMResponseValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onCmbEyeOpeningValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void oncmbVisualLeftValueSet(Object value); abstract protected void oncmbLeftReactionPupilValueSet(Object value); public final void setContext(ims.framework.UIEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setFormModeChangedEvent(new FormModeChanged() { private static final long serialVersionUID = 1L; public void handle() { onFormModeChanged(); } }); this.form.setMessageBoxClosedEvent(new MessageBoxClosed() { private static final long serialVersionUID = 1L; public void handle(int messageBoxId, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException { onMessageBoxClosed(messageBoxId, result); } }); this.form.setFormOpenEvent(new FormOpen() { private static final long serialVersionUID = 1L; public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException { bindLookups(); onFormOpen(args); } }); this.form.setFormDialogClosedEvent(new FormDialogClosed() { private static final long serialVersionUID = 1L; public void handle(ims.framework.FormName formName, ims.framework.enumerations.DialogResult result) throws ims.framework.exceptions.PresentationLogicException { onFormDialogClosed(formName, result); } }); this.form.recbrHistory().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onRecbrHistoryValueChanged(); } }); this.form.btnEdit().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnEditClick(); } }); this.form.btnNew().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnNewClick(); } }); this.form.btnSave().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnSaveClick(); } }); this.form.btnCancel().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnCancelClick(); } }); this.form.lyrVital().tabPageBaseline().setTabActivatedEvent(new ims.framework.delegates.TabActivated() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onlyrVitaltabPageBaselineActivated(); } }); this.form.lyrVital().tabPageOtherVitalSigns().setTabActivatedEvent(new ims.framework.delegates.TabActivated() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onlyrVitaltabPageOtherVitalSignsActivated(); } }); this.form.lyrVital().tabPageBaseline().btnCalculateULNA().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnCalculateULNAClick(); } }); this.form.lyrVital().tabPageBaseline().BloodGlucoseGroup1().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onRadioButtonBloodGlucoseGroup1ValueChanged(); } }); this.form.lyrVital().tabPageBaseline().cmbTimePeriod().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbTimePeriodValueSet(value); } }); this.form.lyrVital().tabPageBaseline().lnkCBGM().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkCBGMClick(); } }); this.form.lyrVital().tabPageBaseline().lnkBMI().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkBMIClick(); } }); this.form.lyrVital().tabPageBaseline().cmbPainScore().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbPainScoreValueSet(value); } }); this.form.lyrVital().tabPageBaseline().lnkPainLadder().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkPainLadderClick(); } }); this.form.lyrVital().tabPageBaseline().btnBMI().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnBMIClick(); } }); this.form.lyrVital().tabPageBaseline().lnkTemperature().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkTemperatureClick(); } }); this.form.lyrVital().tabPageBaseline().lnkMetrics().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkMetricsClick(); } }); this.form.lyrVital().tabPageBaseline().lnkPeakFlow().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkPeakFlowClick(); } }); this.form.lyrVital().tabPageBaseline().chkonFiO2().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onChkonFiO2ValueChanged(); } }); this.form.lyrVital().tabPageBaseline().lnkOxygenSaturation().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkOxygenSaturationClick(); } }); this.form.lyrVital().tabPageBaseline().lnkRespirations().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkRespirationsClick(); } }); this.form.lyrVital().tabPageBaseline().GroupBP().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onRadioButtonGroupBPValueChanged(); } }); this.form.lyrVital().tabPageBaseline().lnkBloodPresure().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkBloodPresureClick(); } }); this.form.lyrVital().tabPageBaseline().lnkPulse().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkPulseClick(); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbPatientConcern().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbPatientConcernValueSet(value); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbUrine().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbUrineValueSet(value); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbConscious().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbConsciousValueSet(value); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbVisualRight().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbVisualRightValueSet(value); } }); this.form.lyrVital().tabPageOtherVitalSigns().lnkGCS().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkGCSClick(); } }); this.form.lyrVital().tabPageOtherVitalSigns().lnkPupils().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkPupilsClick(); } }); this.form.lyrVital().tabPageOtherVitalSigns().lnkVisualAcuity().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onLnkVisualAcuityClick(); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbRightReactionPupil().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbRightReactionPupilValueSet(value); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbVResponse().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onCmbVResponseValueChanged(); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbMResponse().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onCmbMResponseValueChanged(); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbEyeOpening().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onCmbEyeOpeningValueChanged(); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbVisualLeft().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbVisualLeftValueSet(value); } }); this.form.lyrVital().tabPageOtherVitalSigns().cmbLeftReactionPupil().setValueSetEvent(new ComboBoxValueSet() { private static final long serialVersionUID = 1L; public void handle(Object value) { oncmbLeftReactionPupilValueSet(value); } }); } protected void bindLookups() { bindcmbTimePeriodLookup(); bindcmbPainScoreLookup(); bindcmbVisualRightLookup(); bindcmbRightReactionPupilLookup(); bindcmbVisualLeftLookup(); bindcmbLeftReactionPupilLookup(); } protected void rebindAllLookups() { bindcmbTimePeriodLookup(); bindcmbPainScoreLookup(); bindcmbPatientConcernLookup(); bindcmbUrineLookup(); bindcmbConsciousLookup(); bindcmbVisualRightLookup(); bindcmbRightReactionPupilLookup(); bindcmbVisualLeftLookup(); bindcmbLeftReactionPupilLookup(); } protected void defaultAllLookupValues() { defaultcmbTimePeriodLookupValue(); defaultcmbPainScoreLookupValue(); defaultcmbPatientConcernLookupValue(); defaultcmbUrineLookupValue(); defaultcmbConsciousLookupValue(); defaultcmbVisualRightLookupValue(); defaultcmbRightReactionPupilLookupValue(); defaultcmbVisualLeftLookupValue(); defaultcmbLeftReactionPupilLookupValue(); } private void onlyrVitaltabPageBaselineActivated() { this.form.lyrVital().showtabPageBaseline(); } private void onlyrVitaltabPageOtherVitalSignsActivated() { this.form.lyrVital().showtabPageOtherVitalSigns(); } public void free() { this.engine = null; this.form = null; } protected ims.framework.UIEngine engine; protected GenForm form; }
agpl-3.0
automenta/spimedb
core/src/main/java/spimedb/graph/travel/CrossComponentTravel.java
10536
package spimedb.graph.travel; import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.api.tuple.primitive.ObjectIntPair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import spimedb.graph.MapGraph; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import static org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples.pair; /** * Provides a cross-connected-component traversal functionality for iterator subclasses. * * @param <V> vertex type * @param <E> edge type * @param <D> type of data associated to seen vertices * @author Barak Naveh * @since Jan 31, 2004 */ public abstract class CrossComponentTravel<V, E, D> extends AbstractTravel<V, E> { private static final int CCS_BEFORE_COMPONENT = 1; private static final int CCS_WITHIN_COMPONENT = 2; private static final int CCS_AFTER_COMPONENT = 3; /** * true = in, false = out */ private final boolean inOrOut = true; public CrossComponentTravel(MapGraph<V, E> g, Map<V, D> seen) { this(g, null, seen); } /** * Standard vertex visit state enumeration. */ protected enum VisitColor { /** * Vertex has not been returned via iterator yet. */ WHITE, /** * Vertex has been returned via iterator, but we're not done with all of its out-edges yet. */ GRAY, /** * Vertex has been returned via iterator, and we're done with all of its out-edges. */ BLACK } /** * Connected component traversal started event. */ public static final int CONNECTED_COMPONENT_ENTER = 31; private final ObjectIntPair ccEnterEvent = pair(this, CONNECTED_COMPONENT_ENTER); /** * Connected component traversal finished event. */ public static final int CONNECTED_COMPONENT_EXIT = 32; private final ObjectIntPair ccExitEvent = pair(this, CONNECTED_COMPONENT_EXIT); private final Iterator<V> vertexIterator; /** * Stores the vertices that have been seen during iteration and (optionally) some additional * traversal info regarding each vertex. */ public final Map<V, D> seen; private V startVertex; public final MapGraph<V, E> graph; /** * The connected component state */ private int state = CCS_BEFORE_COMPONENT; /** * Creates a new iterator for the specified graph. Iteration will start at the specified start * vertex. If the specified start vertex is <code> * null</code>, Iteration will start at an arbitrary graph vertex. * * @param g the graph to be iterated. * @param startVertex the vertex iteration to be started. * @param seen * @throws IllegalArgumentException if <code>g==null</code> or does not contain * <code>startVertex</code> */ public CrossComponentTravel(MapGraph<V, E> g, @Nullable V startVertex, @NotNull Map<V, D> seen) { super(); this.seen = seen; this.graph = g; // specifics = createGraphSpecifics(g); vertexIterator = g.vertexSet().iterator(); setCrossComponentTraversal(startVertex == null); // reusableEdgeEvent = new FlyweightEdgeEvent<>(this, null); // reusableVertexEvent = new FlyweightVertexEvent<>(this, null); if (startVertex == null) { // pick a start vertex if graph not empty if (vertexIterator.hasNext()) { this.startVertex = vertexIterator.next(); } else { this.startVertex = null; } } else if (g.containsVertex(startVertex)) { this.startVertex = startVertex; } else { throw new IllegalArgumentException("graph must contain the start vertex"); } } /** * @see java.util.Iterator#hasNext() */ @Override public boolean hasNext() { if (startVertex != null) { encounterStartVertex(); } if (isConnectedComponentExhausted()) { if (state == CCS_WITHIN_COMPONENT) { state = CCS_AFTER_COMPONENT; fireConnectedComponentFinished(ccExitEvent); } if (isCrossComponentTraversal()) { while (vertexIterator.hasNext()) { V v = vertexIterator.next(); if (!isSeenVertex(v)) { encounterVertex(v, null); state = CCS_BEFORE_COMPONENT; return true; } } return false; } else { return false; } } else { return true; } } /** * @see java.util.Iterator#next() */ @Override public V next() { if (startVertex != null) { encounterStartVertex(); } if (hasNext()) { if (state == CCS_BEFORE_COMPONENT) { state = CCS_WITHIN_COMPONENT; fireConnectedComponentStarted(ccEnterEvent); } V nextVertex = provideNextVertex(); //Pair<V, E> incoming = Tuples.pair(currentVertex, ); fireVertexEnter(null, nextVertex); addIncidentEdges(nextVertex); return nextVertex; } else { throw new NoSuchElementException(); } } /** * Returns <tt>true</tt> if there are no more uniterated vertices in the currently iterated * connected component; <tt>false</tt> otherwise. * * @return <tt>true</tt> if there are no more uniterated vertices in the currently iterated * connected component; <tt>false</tt> otherwise. */ protected abstract boolean isConnectedComponentExhausted(); /** * Update data structures the first time we see a vertex. * * @param vertex the vertex encountered * @param edge the edge via which the vertex was encountered, or null if the vertex is a * starting point */ protected abstract void encounterVertex(V vertex, E edge); /** * Returns the vertex to be returned in the following call to the iterator <code>next</code> * method. * * @return the next vertex to be returned by this iterator. */ protected abstract V provideNextVertex(); /** * Access the data stored for a seen vertex. * * @param vertex a vertex which has already been seen. * @return data associated with the seen vertex or <code>null</code> if no data was associated * with the vertex. A <code>null</code> return can also indicate that the vertex was * explicitly associated with <code> * null</code>. */ protected D saw(V vertex) { return seen.get(vertex); } /** * Determines whether a vertex has been seen yet by this traversal. * * @param vertex vertex in question * @return <tt>true</tt> if vertex has already been seen */ protected boolean isSeenVertex(V vertex) { return seen.containsKey(vertex); } /** * Called whenever we re-encounter a vertex. The default implementation does nothing. * * @param vertex the vertex re-encountered * @param edge the edge via which the vertex was re-encountered */ protected abstract void encounterVertexAgain(V vertex, E edge); /** * Stores iterator-dependent data for a vertex that has been seen. * * @param vertex a vertex which has been seen. * @param data data to be associated with the seen vertex. * @return previous value associated with specified vertex or <code> * null</code> if no data was associated with the vertex. A <code> * null</code> return can also indicate that the vertex was explicitly associated with * <code>null</code>. */ protected D putSeenData(V vertex, D data) { return seen.put(vertex, data); } /** * Called when a vertex has been finished (meaning is dependent on traversal represented by * subclass). * * @param vertex vertex which has been finished */ protected void finishVertex(V vertex) { fireVertexFinished(vertex); } private void addIncidentEdges(V s) { boolean firesEdges = wantsEdges(); if (inOrOut) { for (Pair<V, E> p : graph.incomingEdgesOf(s)) { go(s, firesEdges, p.getOne(), p.getTwo()); } } else { for (Pair<E, V> p : graph.outgoingEdgesOf(s)) { go(s, firesEdges, p.getTwo(), p.getOne()); } } } private void go(V s, boolean firesEdges, V t, E edge) { if (firesEdges) fireEdgeTraversed(s, edge, t); if (isSeenVertex(t)) { encounterVertexAgain(t, edge); } else { encounterVertex(t, edge); } } @Override public Iterable<Pair<E, V>> edgesOut(V vertex) { return graph.outgoingEdgesOf(vertex); } // private EdgeTraversalEvent<E> createEdgeTraversalEvent(E edge) { // if (isReuseEvents()) { // reusableEdgeEvent.setEdge(edge); // // return reusableEdgeEvent; // } else { // return new EdgeTraversalEvent<>(this, edge); // } // } // // private ObjectIntPair createVertexTraversalEvent(V vertex) { // if (isReuseEvents()) { // reusableVertexEvent.setVertex(vertex); // // return reusableVertexEvent; // } else { // return new VertexTraversalEvent<>(this, vertex); // } // } private void encounterStartVertex() { encounterVertex(startVertex, null); startVertex = null; } // static interface SimpleContainer<T> { // /** // * Tests if this container is empty. // * // * @return <code>true</code> if empty, otherwise <code>false</code>. // */ // public boolean isEmpty(); // // /** // * Adds the specified object to this container. // * // * @param o the object to be added. // */ // public void add(T o); // // /** // * Remove an object from this container and return it. // * // * @return the object removed from this container. // */ // public T remove(); // } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/scheduling/vo/TheatreDetailVo.java
7611
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.scheduling.vo; /** * Linked to Scheduling.TheatreDetail business object (ID: 1090100008). */ public class TheatreDetailVo extends ims.scheduling.vo.TheatreDetailRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public TheatreDetailVo() { } public TheatreDetailVo(Integer id, int version) { super(id, version); } public TheatreDetailVo(ims.scheduling.vo.beans.TheatreDetailVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.procedure = bean.getProcedure() == null ? null : bean.getProcedure().buildVo(); this.maxno = bean.getMaxNo(); this.isactive = bean.getIsActive(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.scheduling.vo.beans.TheatreDetailVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.procedure = bean.getProcedure() == null ? null : bean.getProcedure().buildVo(map); this.maxno = bean.getMaxNo(); this.isactive = bean.getIsActive(); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.scheduling.vo.beans.TheatreDetailVoBean bean = null; if(map != null) bean = (ims.scheduling.vo.beans.TheatreDetailVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.scheduling.vo.beans.TheatreDetailVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("PROCEDURE")) return getProcedure(); if(fieldName.equals("MAXNO")) return getMaxNo(); if(fieldName.equals("ISACTIVE")) return getIsActive(); return super.getFieldValueByFieldName(fieldName); } public boolean getProcedureIsNotNull() { return this.procedure != null; } public ims.core.vo.ProcedureLiteVo getProcedure() { return this.procedure; } public void setProcedure(ims.core.vo.ProcedureLiteVo value) { this.isValidated = false; this.procedure = value; } public boolean getMaxNoIsNotNull() { return this.maxno != null; } public Integer getMaxNo() { return this.maxno; } public void setMaxNo(Integer value) { this.isValidated = false; this.maxno = value; } public boolean getIsActiveIsNotNull() { return this.isactive != null; } public Boolean getIsActive() { return this.isactive; } public void setIsActive(Boolean value) { this.isValidated = false; this.isactive = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; TheatreDetailVo clone = new TheatreDetailVo(this.id, this.version); if(this.procedure == null) clone.procedure = null; else clone.procedure = (ims.core.vo.ProcedureLiteVo)this.procedure.clone(); clone.maxno = this.maxno; clone.isactive = this.isactive; clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(TheatreDetailVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A TheatreDetailVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((TheatreDetailVo)obj).getBoId() == null) return -1; return this.id.compareTo(((TheatreDetailVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.procedure != null) count++; if(this.maxno != null) count++; if(this.isactive != null) count++; return count; } public int countValueObjectFields() { return 3; } protected ims.core.vo.ProcedureLiteVo procedure; protected Integer maxno; protected Boolean isactive; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/clinical/vo/domain/SurgicalAuditRecoveryVoAssembler.java
29940
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:32 * */ package ims.clinical.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Florin Blindu */ public class SurgicalAuditRecoveryVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.clinical.vo.SurgicalAuditRecoveryVo copy(ims.clinical.vo.SurgicalAuditRecoveryVo valueObjectDest, ims.clinical.vo.SurgicalAuditRecoveryVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_SurgicalAuditRecovery(valueObjectSrc.getID_SurgicalAuditRecovery()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // Patient valueObjectDest.setPatient(valueObjectSrc.getPatient()); // CareContext valueObjectDest.setCareContext(valueObjectSrc.getCareContext()); // AuthoringInformation valueObjectDest.setAuthoringInformation(valueObjectSrc.getAuthoringInformation()); // RecoveryRoomNurse valueObjectDest.setRecoveryRoomNurse(valueObjectSrc.getRecoveryRoomNurse()); // ConfirmPatientArrival valueObjectDest.setConfirmPatientArrival(valueObjectSrc.getConfirmPatientArrival()); // TimeArrivesInRecovery valueObjectDest.setTimeArrivesInRecovery(valueObjectSrc.getTimeArrivesInRecovery()); // TimeWardNotified valueObjectDest.setTimeWardNotified(valueObjectSrc.getTimeWardNotified()); // TimeLeavesRecovery valueObjectDest.setTimeLeavesRecovery(valueObjectSrc.getTimeLeavesRecovery()); // SentTo valueObjectDest.setSentTo(valueObjectSrc.getSentTo()); // HandoverfromRecoveryNurse valueObjectDest.setHandoverfromRecoveryNurse(valueObjectSrc.getHandoverfromRecoveryNurse()); // WardUnitNurse valueObjectDest.setWardUnitNurse(valueObjectSrc.getWardUnitNurse()); // RecoveryLocumBool valueObjectDest.setRecoveryLocumBool(valueObjectSrc.getRecoveryLocumBool()); // RecoveryLocumNurse valueObjectDest.setRecoveryLocumNurse(valueObjectSrc.getRecoveryLocumNurse()); // RecoveryHandoverLocumBool valueObjectDest.setRecoveryHandoverLocumBool(valueObjectSrc.getRecoveryHandoverLocumBool()); // RecoveryHandoverLocumNurse valueObjectDest.setRecoveryHandoverLocumNurse(valueObjectSrc.getRecoveryHandoverLocumNurse()); // WardLocumBool valueObjectDest.setWardLocumBool(valueObjectSrc.getWardLocumBool()); // WardLocumNurse valueObjectDest.setWardLocumNurse(valueObjectSrc.getWardLocumNurse()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createSurgicalAuditRecoveryVoCollectionFromSurgicalAuditRecovery(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.clinical.domain.objects.SurgicalAuditRecovery objects. */ public static ims.clinical.vo.SurgicalAuditRecoveryVoCollection createSurgicalAuditRecoveryVoCollectionFromSurgicalAuditRecovery(java.util.Set domainObjectSet) { return createSurgicalAuditRecoveryVoCollectionFromSurgicalAuditRecovery(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.clinical.domain.objects.SurgicalAuditRecovery objects. */ public static ims.clinical.vo.SurgicalAuditRecoveryVoCollection createSurgicalAuditRecoveryVoCollectionFromSurgicalAuditRecovery(DomainObjectMap map, java.util.Set domainObjectSet) { ims.clinical.vo.SurgicalAuditRecoveryVoCollection voList = new ims.clinical.vo.SurgicalAuditRecoveryVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.clinical.domain.objects.SurgicalAuditRecovery domainObject = (ims.clinical.domain.objects.SurgicalAuditRecovery) iterator.next(); ims.clinical.vo.SurgicalAuditRecoveryVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.clinical.domain.objects.SurgicalAuditRecovery objects. */ public static ims.clinical.vo.SurgicalAuditRecoveryVoCollection createSurgicalAuditRecoveryVoCollectionFromSurgicalAuditRecovery(java.util.List domainObjectList) { return createSurgicalAuditRecoveryVoCollectionFromSurgicalAuditRecovery(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.clinical.domain.objects.SurgicalAuditRecovery objects. */ public static ims.clinical.vo.SurgicalAuditRecoveryVoCollection createSurgicalAuditRecoveryVoCollectionFromSurgicalAuditRecovery(DomainObjectMap map, java.util.List domainObjectList) { ims.clinical.vo.SurgicalAuditRecoveryVoCollection voList = new ims.clinical.vo.SurgicalAuditRecoveryVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.clinical.domain.objects.SurgicalAuditRecovery domainObject = (ims.clinical.domain.objects.SurgicalAuditRecovery) domainObjectList.get(i); ims.clinical.vo.SurgicalAuditRecoveryVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.clinical.domain.objects.SurgicalAuditRecovery set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractSurgicalAuditRecoverySet(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.SurgicalAuditRecoveryVoCollection voCollection) { return extractSurgicalAuditRecoverySet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractSurgicalAuditRecoverySet(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.SurgicalAuditRecoveryVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.clinical.vo.SurgicalAuditRecoveryVo vo = voCollection.get(i); ims.clinical.domain.objects.SurgicalAuditRecovery domainObject = SurgicalAuditRecoveryVoAssembler.extractSurgicalAuditRecovery(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.clinical.domain.objects.SurgicalAuditRecovery list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractSurgicalAuditRecoveryList(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.SurgicalAuditRecoveryVoCollection voCollection) { return extractSurgicalAuditRecoveryList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractSurgicalAuditRecoveryList(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.SurgicalAuditRecoveryVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.clinical.vo.SurgicalAuditRecoveryVo vo = voCollection.get(i); ims.clinical.domain.objects.SurgicalAuditRecovery domainObject = SurgicalAuditRecoveryVoAssembler.extractSurgicalAuditRecovery(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.clinical.domain.objects.SurgicalAuditRecovery object. * @param domainObject ims.clinical.domain.objects.SurgicalAuditRecovery */ public static ims.clinical.vo.SurgicalAuditRecoveryVo create(ims.clinical.domain.objects.SurgicalAuditRecovery domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.clinical.domain.objects.SurgicalAuditRecovery object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.clinical.vo.SurgicalAuditRecoveryVo create(DomainObjectMap map, ims.clinical.domain.objects.SurgicalAuditRecovery domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.clinical.vo.SurgicalAuditRecoveryVo valueObject = (ims.clinical.vo.SurgicalAuditRecoveryVo) map.getValueObject(domainObject, ims.clinical.vo.SurgicalAuditRecoveryVo.class); if ( null == valueObject ) { valueObject = new ims.clinical.vo.SurgicalAuditRecoveryVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.clinical.domain.objects.SurgicalAuditRecovery */ public static ims.clinical.vo.SurgicalAuditRecoveryVo insert(ims.clinical.vo.SurgicalAuditRecoveryVo valueObject, ims.clinical.domain.objects.SurgicalAuditRecovery domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.clinical.domain.objects.SurgicalAuditRecovery */ public static ims.clinical.vo.SurgicalAuditRecoveryVo insert(DomainObjectMap map, ims.clinical.vo.SurgicalAuditRecoveryVo valueObject, ims.clinical.domain.objects.SurgicalAuditRecovery domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_SurgicalAuditRecovery(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // Patient if (domainObject.getPatient() != null) { if(domainObject.getPatient() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getPatient(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setPatient(new ims.core.patient.vo.PatientRefVo(id, -1)); } else { valueObject.setPatient(new ims.core.patient.vo.PatientRefVo(domainObject.getPatient().getId(), domainObject.getPatient().getVersion())); } } // CareContext if (domainObject.getCareContext() != null) { if(domainObject.getCareContext() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getCareContext(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setCareContext(new ims.core.admin.vo.CareContextRefVo(id, -1)); } else { valueObject.setCareContext(new ims.core.admin.vo.CareContextRefVo(domainObject.getCareContext().getId(), domainObject.getCareContext().getVersion())); } } // AuthoringInformation valueObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInformation()) ); // RecoveryRoomNurse valueObject.setRecoveryRoomNurse(ims.core.vo.domain.NurseVoAssembler.create(map, domainObject.getRecoveryRoomNurse()) ); // ConfirmPatientArrival ims.domain.lookups.LookupInstance instance5 = domainObject.getConfirmPatientArrival(); if ( null != instance5 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance5.getImage() != null) { img = new ims.framework.utils.ImagePath(instance5.getImage().getImageId(), instance5.getImage().getImagePath()); } color = instance5.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.YesNo voLookup5 = new ims.core.vo.lookups.YesNo(instance5.getId(),instance5.getText(), instance5.isActive(), null, img, color); ims.core.vo.lookups.YesNo parentVoLookup5 = voLookup5; ims.domain.lookups.LookupInstance parent5 = instance5.getParent(); while (parent5 != null) { if (parent5.getImage() != null) { img = new ims.framework.utils.ImagePath(parent5.getImage().getImageId(), parent5.getImage().getImagePath() ); } else { img = null; } color = parent5.getColor(); if (color != null) color.getValue(); parentVoLookup5.setParent(new ims.core.vo.lookups.YesNo(parent5.getId(),parent5.getText(), parent5.isActive(), null, img, color)); parentVoLookup5 = parentVoLookup5.getParent(); parent5 = parent5.getParent(); } valueObject.setConfirmPatientArrival(voLookup5); } // TimeArrivesInRecovery java.util.Date TimeArrivesInRecovery = domainObject.getTimeArrivesInRecovery(); if ( null != TimeArrivesInRecovery ) { valueObject.setTimeArrivesInRecovery(new ims.framework.utils.DateTime(TimeArrivesInRecovery) ); } // TimeWardNotified java.util.Date TimeWardNotified = domainObject.getTimeWardNotified(); if ( null != TimeWardNotified ) { valueObject.setTimeWardNotified(new ims.framework.utils.DateTime(TimeWardNotified) ); } // TimeLeavesRecovery java.util.Date TimeLeavesRecovery = domainObject.getTimeLeavesRecovery(); if ( null != TimeLeavesRecovery ) { valueObject.setTimeLeavesRecovery(new ims.framework.utils.DateTime(TimeLeavesRecovery) ); } // SentTo valueObject.setSentTo(ims.core.vo.domain.LocationLiteVoAssembler.create(map, domainObject.getSentTo()) ); // HandoverfromRecoveryNurse valueObject.setHandoverfromRecoveryNurse(ims.core.vo.domain.NurseVoAssembler.create(map, domainObject.getHandoverfromRecoveryNurse()) ); // WardUnitNurse valueObject.setWardUnitNurse(ims.core.vo.domain.NurseVoAssembler.create(map, domainObject.getWardUnitNurse()) ); // RecoveryLocumBool valueObject.setRecoveryLocumBool( domainObject.isRecoveryLocumBool() ); // RecoveryLocumNurse valueObject.setRecoveryLocumNurse(domainObject.getRecoveryLocumNurse()); // RecoveryHandoverLocumBool valueObject.setRecoveryHandoverLocumBool( domainObject.isRecoveryHandoverLocumBool() ); // RecoveryHandoverLocumNurse valueObject.setRecoveryHandoverLocumNurse(domainObject.getRecoveryHandoverLocumNurse()); // WardLocumBool valueObject.setWardLocumBool( domainObject.isWardLocumBool() ); // WardLocumNurse valueObject.setWardLocumNurse(domainObject.getWardLocumNurse()); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.clinical.domain.objects.SurgicalAuditRecovery extractSurgicalAuditRecovery(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.SurgicalAuditRecoveryVo valueObject) { return extractSurgicalAuditRecovery(domainFactory, valueObject, new HashMap()); } public static ims.clinical.domain.objects.SurgicalAuditRecovery extractSurgicalAuditRecovery(ims.domain.ILightweightDomainFactory domainFactory, ims.clinical.vo.SurgicalAuditRecoveryVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_SurgicalAuditRecovery(); ims.clinical.domain.objects.SurgicalAuditRecovery domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.clinical.domain.objects.SurgicalAuditRecovery)domMap.get(valueObject); } // ims.clinical.vo.SurgicalAuditRecoveryVo ID_SurgicalAuditRecovery field is unknown domainObject = new ims.clinical.domain.objects.SurgicalAuditRecovery(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_SurgicalAuditRecovery()); if (domMap.get(key) != null) { return (ims.clinical.domain.objects.SurgicalAuditRecovery)domMap.get(key); } domainObject = (ims.clinical.domain.objects.SurgicalAuditRecovery) domainFactory.getDomainObject(ims.clinical.domain.objects.SurgicalAuditRecovery.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_SurgicalAuditRecovery()); ims.core.patient.domain.objects.Patient value1 = null; if ( null != valueObject.getPatient() ) { if (valueObject.getPatient().getBoId() == null) { if (domMap.get(valueObject.getPatient()) != null) { value1 = (ims.core.patient.domain.objects.Patient)domMap.get(valueObject.getPatient()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value1 = domainObject.getPatient(); } else { value1 = (ims.core.patient.domain.objects.Patient)domainFactory.getDomainObject(ims.core.patient.domain.objects.Patient.class, valueObject.getPatient().getBoId()); } } domainObject.setPatient(value1); ims.core.admin.domain.objects.CareContext value2 = null; if ( null != valueObject.getCareContext() ) { if (valueObject.getCareContext().getBoId() == null) { if (domMap.get(valueObject.getCareContext()) != null) { value2 = (ims.core.admin.domain.objects.CareContext)domMap.get(valueObject.getCareContext()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value2 = domainObject.getCareContext(); } else { value2 = (ims.core.admin.domain.objects.CareContext)domainFactory.getDomainObject(ims.core.admin.domain.objects.CareContext.class, valueObject.getCareContext().getBoId()); } } domainObject.setCareContext(value2); domainObject.setAuthoringInformation(ims.core.vo.domain.AuthoringInformationVoAssembler.extractAuthoringInformation(domainFactory, valueObject.getAuthoringInformation(), domMap)); // SaveAsRefVO - treated as a refVo in extract methods ims.core.resource.people.domain.objects.Nurse value4 = null; if ( null != valueObject.getRecoveryRoomNurse() ) { if (valueObject.getRecoveryRoomNurse().getBoId() == null) { if (domMap.get(valueObject.getRecoveryRoomNurse()) != null) { value4 = (ims.core.resource.people.domain.objects.Nurse)domMap.get(valueObject.getRecoveryRoomNurse()); } } else { value4 = (ims.core.resource.people.domain.objects.Nurse)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Nurse.class, valueObject.getRecoveryRoomNurse().getBoId()); } } domainObject.setRecoveryRoomNurse(value4); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value5 = null; if ( null != valueObject.getConfirmPatientArrival() ) { value5 = domainFactory.getLookupInstance(valueObject.getConfirmPatientArrival().getID()); } domainObject.setConfirmPatientArrival(value5); ims.framework.utils.DateTime dateTime6 = valueObject.getTimeArrivesInRecovery(); java.util.Date value6 = null; if ( dateTime6 != null ) { value6 = dateTime6.getJavaDate(); } domainObject.setTimeArrivesInRecovery(value6); ims.framework.utils.DateTime dateTime7 = valueObject.getTimeWardNotified(); java.util.Date value7 = null; if ( dateTime7 != null ) { value7 = dateTime7.getJavaDate(); } domainObject.setTimeWardNotified(value7); ims.framework.utils.DateTime dateTime8 = valueObject.getTimeLeavesRecovery(); java.util.Date value8 = null; if ( dateTime8 != null ) { value8 = dateTime8.getJavaDate(); } domainObject.setTimeLeavesRecovery(value8); // SaveAsRefVO - treated as a refVo in extract methods ims.core.resource.place.domain.objects.Location value9 = null; if ( null != valueObject.getSentTo() ) { if (valueObject.getSentTo().getBoId() == null) { if (domMap.get(valueObject.getSentTo()) != null) { value9 = (ims.core.resource.place.domain.objects.Location)domMap.get(valueObject.getSentTo()); } } else { value9 = (ims.core.resource.place.domain.objects.Location)domainFactory.getDomainObject(ims.core.resource.place.domain.objects.Location.class, valueObject.getSentTo().getBoId()); } } domainObject.setSentTo(value9); // SaveAsRefVO - treated as a refVo in extract methods ims.core.resource.people.domain.objects.Nurse value10 = null; if ( null != valueObject.getHandoverfromRecoveryNurse() ) { if (valueObject.getHandoverfromRecoveryNurse().getBoId() == null) { if (domMap.get(valueObject.getHandoverfromRecoveryNurse()) != null) { value10 = (ims.core.resource.people.domain.objects.Nurse)domMap.get(valueObject.getHandoverfromRecoveryNurse()); } } else { value10 = (ims.core.resource.people.domain.objects.Nurse)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Nurse.class, valueObject.getHandoverfromRecoveryNurse().getBoId()); } } domainObject.setHandoverfromRecoveryNurse(value10); // SaveAsRefVO - treated as a refVo in extract methods ims.core.resource.people.domain.objects.Nurse value11 = null; if ( null != valueObject.getWardUnitNurse() ) { if (valueObject.getWardUnitNurse().getBoId() == null) { if (domMap.get(valueObject.getWardUnitNurse()) != null) { value11 = (ims.core.resource.people.domain.objects.Nurse)domMap.get(valueObject.getWardUnitNurse()); } } else { value11 = (ims.core.resource.people.domain.objects.Nurse)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Nurse.class, valueObject.getWardUnitNurse().getBoId()); } } domainObject.setWardUnitNurse(value11); domainObject.setRecoveryLocumBool(valueObject.getRecoveryLocumBool()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getRecoveryLocumNurse() != null && valueObject.getRecoveryLocumNurse().equals("")) { valueObject.setRecoveryLocumNurse(null); } domainObject.setRecoveryLocumNurse(valueObject.getRecoveryLocumNurse()); domainObject.setRecoveryHandoverLocumBool(valueObject.getRecoveryHandoverLocumBool()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getRecoveryHandoverLocumNurse() != null && valueObject.getRecoveryHandoverLocumNurse().equals("")) { valueObject.setRecoveryHandoverLocumNurse(null); } domainObject.setRecoveryHandoverLocumNurse(valueObject.getRecoveryHandoverLocumNurse()); domainObject.setWardLocumBool(valueObject.getWardLocumBool()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getWardLocumNurse() != null && valueObject.getWardLocumNurse().equals("")) { valueObject.setWardLocumNurse(null); } domainObject.setWardLocumNurse(valueObject.getWardLocumNurse()); return domainObject; } }
agpl-3.0
MicroMappers/Service
mm-media-api/src/main/java/qa/qcri/mm/media/dao/MediaPoolDao.java
465
package qa.qcri.mm.media.dao; import qa.qcri.mm.media.entity.MediaPool; import java.util.List; /** * Created with IntelliJ IDEA. * User: jlucas * Date: 2/22/15 * Time: 11:43 AM * To change this template use File | Settings | File Templates. */ public interface MediaPoolDao extends AbstractDao<MediaPool, String> { public void addToPool(MediaPool mediaPool); public List<MediaPool> getMediaPoolBySourceAndStatus(Long sourceID, Integer status); }
agpl-3.0
zheguang/voltdb
tests/testprocs/org/voltdb_testprocs/regressionsuites/failureprocs/BadVarcharCompare.java
2128
/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb_testprocs.regressionsuites.failureprocs; import org.voltdb.*; @ProcInfo( singlePartition = false ) public class BadVarcharCompare extends VoltProcedure { public final SQLStmt insertSQL = new SQLStmt("insert into BAD_COMPARES (ID, STRINGVAL) values (?, ?);"); public final SQLStmt selectSQL = new SQLStmt("select ID from BAD_COMPARES where STRINGVAL = ?;"); public long run(int id) throws VoltAbortException { long numRows = 0; voltQueueSQL(insertSQL, 1, "one"); voltQueueSQL(insertSQL, 2, "two"); voltQueueSQL(insertSQL, 3, "three"); voltExecuteSQL(); // comparing STRINGVAL to integer 1 causes ENG-800 voltQueueSQL(selectSQL, 1); VoltTable results1[] = voltExecuteSQL(true); if (results1[0].getRowCount() == 1) { VoltTableRow row1 = results1[0].fetchRow(0); numRows = row1.getLong(0); } return numRows; } }
agpl-3.0
exercitussolus/yolo
src/test/java/org/elasticsearch/search/functionscore/FunctionScorePluginTests.java
6719
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.functionscore; import org.apache.lucene.search.ComplexExplanation; import org.apache.lucene.search.Explanation; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.Priority; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.query.functionscore.DecayFunction; import org.elasticsearch.index.query.functionscore.DecayFunctionBuilder; import org.elasticsearch.index.query.functionscore.DecayFunctionParser; import org.elasticsearch.index.query.functionscore.FunctionScoreModule; import org.elasticsearch.plugins.AbstractPlugin; import org.elasticsearch.search.SearchHits; import org.elasticsearch.test.AbstractIntegrationTest; import org.elasticsearch.test.hamcrest.ElasticSearchAssertions; import org.junit.Test; import static org.elasticsearch.client.Requests.indexRequest; import static org.elasticsearch.client.Requests.searchRequest; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource; import static org.elasticsearch.test.AbstractIntegrationTest.ClusterScope; import static org.elasticsearch.test.AbstractIntegrationTest.Scope; import static org.hamcrest.Matchers.equalTo; /** * */ @ClusterScope(scope = Scope.SUITE, numNodes = 1) public class FunctionScorePluginTests extends AbstractIntegrationTest { @Override protected Settings nodeSettings(int nodeOrdinal) { return settingsBuilder() .put("plugin.types", CustomDistanceScorePlugin.class.getName()) .put(super.nodeSettings(nodeOrdinal)) .build(); } @Test public void testPlugin() throws Exception { client().admin() .indices() .prepareCreate("test") .addMapping( "type1", jsonBuilder().startObject().startObject("type1").startObject("properties").startObject("test") .field("type", "string").endObject().startObject("num1").field("type", "date").endObject().endObject() .endObject().endObject()).execute().actionGet(); client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); client().index( indexRequest("test").type("type1").id("1") .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-26").endObject())).actionGet(); client().index( indexRequest("test").type("type1").id("2") .source(jsonBuilder().startObject().field("test", "value").field("num1", "2013-05-27").endObject())).actionGet(); client().admin().indices().prepareRefresh().execute().actionGet(); DecayFunctionBuilder gfb = new CustomDistanceScoreBuilder("num1", "2013-05-28", "+1d"); ActionFuture<SearchResponse> response = client().search(searchRequest().searchType(SearchType.QUERY_THEN_FETCH).source( searchSource().explain(false).query(functionScoreQuery(termQuery("test", "value")).add(gfb)))); SearchResponse sr = response.actionGet(); ElasticSearchAssertions.assertNoFailures(sr); SearchHits sh = sr.getHits(); assertThat(sh.hits().length, equalTo(2)); assertThat(sh.getAt(0).getId(), equalTo("1")); assertThat(sh.getAt(1).getId(), equalTo("2")); } public static class CustomDistanceScorePlugin extends AbstractPlugin { @Override public String name() { return "test-plugin-distance-score"; } @Override public String description() { return "Distance score plugin to test pluggable implementation"; } public void onModule(FunctionScoreModule scoreModule) { scoreModule.registerParser(FunctionScorePluginTests.CustomDistanceScoreParser.class); } } public static class CustomDistanceScoreParser extends DecayFunctionParser { public static final String[] NAMES = { "linear_mult", "linearMult" }; @Override public String[] getNames() { return NAMES; } static final DecayFunction decayFunction = new LinearMultScoreFunction(); @Override public DecayFunction getDecayFunction() { return decayFunction; } static class LinearMultScoreFunction implements DecayFunction { LinearMultScoreFunction() { } @Override public double evaluate(double value, double scale) { return value; } @Override public Explanation explainFunction(String distanceString, double distanceVal, double scale) { ComplexExplanation ce = new ComplexExplanation(); ce.setDescription("" + distanceVal); return ce; } @Override public double processScale(double userGivenScale, double userGivenValue) { return userGivenScale; } } } public class CustomDistanceScoreBuilder extends DecayFunctionBuilder { public CustomDistanceScoreBuilder(String fieldName, Object origin, Object scale) { super(fieldName, origin, scale); } @Override public String getName() { return CustomDistanceScoreParser.NAMES[0]; } } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/therapies/vo/MassageShortVo.java
6485
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.therapies.vo; /** * Linked to therapies.treatment.Massage business object (ID: 1019100016). */ public class MassageShortVo extends ims.therapies.treatment.vo.MassageRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public MassageShortVo() { } public MassageShortVo(Integer id, int version) { super(id, version); } public MassageShortVo(ims.therapies.vo.beans.MassageShortVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.clinicalcontact = bean.getClinicalContact() == null ? null : bean.getClinicalContact().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.therapies.vo.beans.MassageShortVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.clinicalcontact = bean.getClinicalContact() == null ? null : bean.getClinicalContact().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.therapies.vo.beans.MassageShortVoBean bean = null; if(map != null) bean = (ims.therapies.vo.beans.MassageShortVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.therapies.vo.beans.MassageShortVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("CLINICALCONTACT")) return getClinicalContact(); return super.getFieldValueByFieldName(fieldName); } public boolean getClinicalContactIsNotNull() { return this.clinicalcontact != null; } public ims.core.vo.ClinicalContactShortVo getClinicalContact() { return this.clinicalcontact; } public void setClinicalContact(ims.core.vo.ClinicalContactShortVo value) { this.isValidated = false; this.clinicalcontact = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.clinicalcontact == null) listOfErrors.add("ClinicalContact is mandatory"); int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; MassageShortVo clone = new MassageShortVo(this.id, this.version); if(this.clinicalcontact == null) clone.clinicalcontact = null; else clone.clinicalcontact = (ims.core.vo.ClinicalContactShortVo)this.clinicalcontact.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(MassageShortVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A MassageShortVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((MassageShortVo)obj).getBoId() == null) return -1; return this.id.compareTo(((MassageShortVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.clinicalcontact != null) count++; return count; } public int countValueObjectFields() { return 1; } protected ims.core.vo.ClinicalContactShortVo clinicalcontact; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/OCRR/src/ims/ocrr/forms/resultdialog/Logic.java
82414
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Marius Mihalec using IMS Development Environment (version 1.45 build 2263.21661) // Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved. package ims.ocrr.forms.resultdialog; import ims.configuration.AppRight; import ims.configuration.gen.ConfigFlag; import ims.core.clinical.vo.ServiceRefVo; import ims.core.resource.people.vo.HcpRefVo; import ims.core.vo.PatientIdCollection; import ims.core.vo.PatientShort; import ims.core.vo.enums.MosType; import ims.core.vo.lookups.HcpDisType; import ims.core.vo.lookups.PatIdType; import ims.core.vo.lookups.TaxonomyType; import ims.domain.DomainObject; import ims.domain.exceptions.StaleObjectException; import ims.framework.FormName; import ims.framework.controls.DynamicGridCell; import ims.framework.controls.DynamicGridCellItem; import ims.framework.controls.DynamicGridCellItemCollection; import ims.framework.controls.DynamicGridColumn; import ims.framework.controls.DynamicGridRow; import ims.framework.enumerations.DialogResult; import ims.framework.enumerations.DynamicCellType; import ims.framework.enumerations.FormMode; import ims.framework.enumerations.SystemLogLevel; import ims.framework.enumerations.SystemLogType; import ims.framework.exceptions.CodingRuntimeException; import ims.framework.exceptions.PresentationLogicException; import ims.framework.utils.Color; import ims.framework.utils.DateFormat; import ims.ocrr.configuration.vo.AnalyteRefVo; import ims.ocrr.configuration.vo.AnalyteRefVoCollection; import ims.ocrr.helper.ResultDisplayHelper; import ims.ocrr.orderingresults.vo.OrderInvestigationRefVo; import ims.ocrr.vo.ClinicalImagingResultVo; import ims.ocrr.vo.ClinicalResultVo; import ims.ocrr.vo.NewResultOcsOrderVo; import ims.ocrr.vo.NewResultSpecDocVo; import ims.ocrr.vo.OcsPathRadResultVo; import ims.ocrr.vo.OcsPathRadResultVoCollection; import ims.ocrr.vo.OrderInvestigationVo; import ims.ocrr.vo.PathologySpecimenOrderInvestigationVo; import ims.ocrr.vo.PathologySpecimenOrderInvestigationVoCollection; import ims.ocrr.vo.PathologySpecimenVo; import ims.ocrr.vo.ResultDemographicsVo; import ims.ocrr.vo.SecurityLevelConfigVo; import ims.ocrr.vo.lookups.Category; import ims.ocrr.vo.lookups.InvEventType; import ims.ocrr.vo.lookups.OrderInvStatus; import ims.ocrr.vo.lookups.ResultStatus; import ims.ocrr.vo.lookups.ResultValueType; import java.io.File; import java.util.ArrayList; import com.ims.query.builder.client.QueryBuilderClient; import com.ims.query.builder.client.SeedValue; import com.ims.query.builder.client.exceptions.QueryBuilderClientException; public class Logic extends BaseLogic { private static final String PREVIOUS_TEXT_BUTTON = "Previous";// WDEV-15894 private static final String CHECKED_TEXT_BUTTON = "Checked";// WDEV-15894 private static final String NEXT_TEXT_BUTTON = "Next";// WDEV-15894 private static final String EXIT_TEXT_BUTTON = "Exit";// WDEV-15894 private static final String PROVISIONAL = "Provisional";// WDEV-16675 private static final String FINAL = "Final";// WDEV-16675 protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException { initialize(); open(); updateHistory(); //WDEV-11253 mark result as viewed in the history } private void updateHistory() { try { form.getGlobalContext().OCRR.setCurrentPathRadResult(domain.addViewedToStatusHistory(form.getGlobalContext().OCRR.getCurrentPathRadResult())); } catch (StaleObjectException e) { //do nothing here as no reasonable action to take } } private void initialize() { initialiseNavigationButtons();//WDEV-15894 setSpecimenDetailsControlsVisible(false); form.getGlobalContext().OCRR.setSelectedInvs(null); form.txtLabRadNo().setEnabled(false); form.txtCollOrStat().setEnabled(false); form.txtReceived().setEnabled(false); form.lblSite().setVisible(false);// WDEV-16773 form.txtSite().setVisible(false);// WDEV-16773 // WDEV-13321 form.ccMedicReview().initialize(MosType.HCP, HcpDisType.MEDICAL); form.ccMedicReview().isRequired(Boolean.TRUE); form.txtTypeOrExamDt().setVisible(true); form.txtTypeOrExamDt().setEnabled(false); //WDEV-4758 if(!ConfigFlag.DOM.CREATE_ORDERS_WITH_CARECONTEXT_ONLY.getValue()) { form.lblPasEpisodeId().setVisible(false); form.txtPasEpisodeID().setVisible(false); } else { form.txtPasEpisodeID().setEnabled(false); } form.setMode(FormMode.VIEW); if(!ConfigFlag.UI.DISPLAY_HOSPNO_FIELD_ON_RESULTS_FORM.getValue()) { form.txtHospnum().setVisible(false); form.lblPatId().setVisible(false); } else form.txtHospnum().setEnabled(false); //WDEV-13879 form.btnClericalTask().setVisible(engine.hasRight(AppRight.CAN_ALLOCATE_PATIENT_CLERICAL_TASKS)); } //WDEV-15894 private void initialiseNavigationButtons() { form.imbClose().setVisible(!isSTHKModeResultCheck()); form.imbNextSpec().setVisible(!isSTHKModeResultCheck()); form.imbPrevSpec().setVisible(!isSTHKModeResultCheck()); } protected void onLnkViewOrderNotesClick() throws PresentationLogicException { form.htmDocument().setHTML(""); engine.open(form.getForms().OCRR.QuestionsNotes, "Order Notes"); } protected void onImbCloseClick() throws ims.framework.exceptions.PresentationLogicException { close();// WDEV-15894 } // WDEV-15894 private void close() { if(form.getLocalContext().getTempFilesIsNotNull() && form.getLocalContext().getTempFiles().size() > 0) { ArrayList<String> tempFiles =form.getLocalContext().getTempFiles(); for (String tempFile : tempFiles) { File fileToBeDeleted = new File(tempFile); if(!fileToBeDeleted.delete()) { fileToBeDeleted.deleteOnExit(); } } } if(updateRecord() == false) { return; } engine.close(DialogResult.OK); } private boolean updateRecord() { try { HcpRefVo hcp = (HcpRefVo) form.ccMedicReview().getValue(); Integer pickValue = form.getLocalContext().getPickValue(); if (pickValue == null) { engine.showMessage("No value has been chosen from the pick list at the bottom of the report."); return false; } if (pickValue.equals(ResultDisplayHelper.PICK_VIEWED)) { domain.resetAllocatedReviewHCP(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); return true; } OrderInvStatus status = null; if (pickValue.equals(ResultDisplayHelper.PICK_CHKD)) { status = OrderInvStatus.CHECKED; } else if (pickValue.equals(ResultDisplayHelper.PICK_SEEN)) { status = OrderInvStatus.SEEN; } else if (pickValue.equals(ResultDisplayHelper.PICK_QRY)) { status = OrderInvStatus.REVIEW; // WDEV-13321 if (hcp == null) { engine.showMessage("Allocate for review medic is mandatory."); return false; } } if (form.getGlobalContext().OCRR.getCurrentPathRadResult().getCategoryIsNotNull() && form.getGlobalContext().OCRR.getCurrentPathRadResult().getCategory().equals(Category.PATHOLOGY)) { form.getGlobalContext().OCRR.getCurrentPathRadResult().setOrderInvestigation(domain.updatePathologyResultStatus(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation(), status, hcp)); // wdev-11555, WDEV-13321 } else { // -wdev-11555 OrderInvestigationVo temp = domain.updateRadResultStatus(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation(), status, hcp); // WDEV-13321 if (temp != null) form.getGlobalContext().OCRR.getCurrentPathRadResult().setOrderInvestigation(temp); // wdev-11555 } } catch (StaleObjectException e) { // The updated Order Investigation will be returned within the StaleObjectException // We need to update the global context with the new value so that future status updates will work DomainObject obj = e.getStaleObject(); form.getGlobalContext().OCRR.getCurrentPathRadResult().setOrderInvestigation(new OrderInvestigationRefVo(obj.getId(), obj.getVersion())); engine.showMessage(ims.configuration.gen.ConfigFlag.UI.STALE_OBJECT_MESSAGE.getValue()); open(); return false; } form.getGlobalContext().OCRR.setLastUpdatedPathRadResult(form.getGlobalContext().OCRR.getCurrentPathRadResult()); return true; } protected void onImbNextSpecClick() throws PresentationLogicException { // WDEV-13321 move(true); updateControlsState(); } protected void onImbPrevSpecClick() throws PresentationLogicException { // WDEV-13321 move(false); updateControlsState(); } private void open() { form.getLocalContext().setPickValue(null); //this is used for reporting form.getLocalContext().setOrderInv(form.getGlobalContext().OCRR.getCurrentPathRadResultIsNotNull() ? form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation() : null); form.dyngrdResults().getRows().clear(); form.getGlobalContext().OCRR.setSelectedInvsWithResults(null); form.getLocalContext().setAnalytes(null); form.setMode(FormMode.VIEW); disableNavigation(); form.imbClose().setEnabled(false); form.lnkViewPatientDetails().setVisible(false); //form.imbPrint().setEnabled(false); populateCurrentReport(); if(!ConfigFlag.DOM.OCRR_KEEP_RESULT_HISTORY.getValue()) form.btnResultHistory().setVisible(false); //WDEV-13190 updateSecondaryMatchingLabel(); // WDEV-13321 updateCurrentlyForReview(); updateControlsState(); } /** * WDEV-13321 * Function used to update the label for 'Currently Allocated for Review to:" */ private void updateCurrentlyForReview() { StringBuilder displayText = new StringBuilder(""); NewResultSpecDocVo orderInvestigation = domain.getOrderInvestigation(form.getLocalContext().getOrderInv()); if (orderInvestigation != null && orderInvestigation.getAllocatedHCPforReviewIsNotNull()) { //WDEV-13976 displayText.append(orderInvestigation.getAllocatedHCPforReview().toString()); form.lblAllocatedForReview().setValue("Currently Allocated for Review to: "); form.htmAllocatedForReview().setHTML("<b>"+displayText.toString()+"</b>"); //end WDEV-13976 } } //WDEV-13190 private void updateSecondaryMatchingLabel() { boolean showWasSecondaryMatching = false; if(form.getLocalContext().getOrderInvIsNotNull() && form.getLocalContext().getOrderInv().getID_OrderInvestigationIsNotNull()) { showWasSecondaryMatching = domain.wasSecondaryMatching(form.getLocalContext().getOrderInv()); } form.lblSecondaryMatching().setVisible(showWasSecondaryMatching); form.lblSecondaryMatching().setTextColor(Color.Red); form.lblSecondaryMatching().setValue(ConfigFlag.UI.SECONDARY_RESULT_MATCHING_WARNING_MESSAGE.getValue()); } private void disableNavigation() { form.imbPrevSpec().setEnabled(false); form.imbNextSpec().setEnabled(false); } private void clearAllControls() { form.txtName().setValue(null); form.txtDOB().setValue(null); form.txtHospnum().setValue(null); form.txtNHSNo().setValue(null); form.txtLabRadNo().setValue(null); form.lblName().setValue("");//WDEV-16952 form.txtOrderingLocation().setValue(null); form.txtClinician().setValue(null); form.txtRequestedBy().setValue(null); form.txtTypeOrExamDt().setValue(null); form.txtCollOrStat().setValue(null); form.txtReceived().setValue(null); form.txtSite().setValue(null);//WDEV-16773 form.lnkViewOrderNotes().setEnabled(false); form.lnkViewOrderNotes().setTooltip(""); form.dyngrdResults().clear(); form.chkEnableExit().setValue(false); form.chkMarkAsSeen().setValue(false); form.chkMarkAsChecked().setVisible(false); form.chkMarkForReview().setValue(false); PatIdType dispIdType = PatIdType.getNegativeInstance(ConfigFlag.UI.DISPLAY_PATID_TYPE.getValue()); if(dispIdType != null && dispIdType.getText() != null) { if (PatIdType.NHSN.equals(dispIdType) && ConfigFlag.UI.DISPLAY_HOSPNO_FIELD_ON_RESULTS_FORM.getValue()) { form.lblPatId().setValue(PatIdType.HOSPNUM.getText()); } else { form.lblPatId().setValue(dispIdType.getText() + ":"); } } // WDEV-13321 // Clear "Allocated for Review" controls form.lblAllocatedForReview().setValue(""); form.htmAllocatedForReview().setHTML("");//WDEV-13976 form.ccMedicReview().clear(); } private void setNavigationState() { if(form.getGlobalContext().OCRR.getSelectedPathRadResults() == null || form.getGlobalContext().OCRR.getSelectedPathRadResults().size() < 2 || form.getGlobalContext().OCRR.getCurrentPathRadResult() == null) { disableNavigation(); } else { int count = form.getGlobalContext().OCRR.getSelectedPathRadResults().size(); int index = form.getGlobalContext().OCRR.getSelectedPathRadResults().indexOf(form.getGlobalContext().OCRR.getCurrentPathRadResult()) + 1; if(index == 1) { form.imbPrevSpec().setEnabled(false); form.imbNextSpec().setEnabled(true); //form.imbPrevDiscip().setEnabled(false); //form.imbNextDiscip().setEnabled(true); } else if(index == count) { form.imbPrevSpec().setEnabled(true); form.imbNextSpec().setEnabled(false); //form.imbPrevDiscip().setEnabled(true); //form.imbNextDiscip().setEnabled(false); } else { form.imbPrevSpec().setEnabled(true); form.imbNextSpec().setEnabled(true); //form.imbPrevDiscip().setEnabled(true); //form.imbNextDiscip().setEnabled(true); } } } private void move(boolean next) { //WDEV-11253 form.getGlobalContext().OCRR.setSelectedInvs(null); if (!updateRecord()) return; int index = form.getGlobalContext().OCRR.getSelectedPathRadResults().indexOf(form.getGlobalContext().OCRR.getCurrentPathRadResult()) + 1; index = index + (next ? 1 : -1); form.getGlobalContext().OCRR.setCurrentPathRadResult(form.getGlobalContext().OCRR.getSelectedPathRadResults().get(index - 1)); open(); //WDEV-12083 //WDEV-11253 updateHistory(); //WDEV-12083populateCurrentReport(); //WDEV-12083disableNavigation(); if (form.dyngrdResults().getRows().size() > 0 || (form.getLocalContext().gethtmlStringIsNotNull() && form.getLocalContext().gethtmlString().length() > 0)) { form.imbClose().setEnabled(false); form.lnkViewPatientDetails().setVisible(false); } // WDEV-13321 // Clear picked value ('Seen', 'For Review', 'Enable Exit') when moving forward or backward in collection form.getLocalContext().setPickValue(null); //this is used for reporting form.getLocalContext().setOrderInv(form.getGlobalContext().OCRR.getCurrentPathRadResultIsNotNull() ? form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation() : null); } private void setLabels(Category cat, boolean isDFTInv) { if(cat == null) throw new CodingRuntimeException("cat cannot be null in method setLabels"); if (cat.equals(Category.PATHOLOGY)) { engine.setCaption("Pathology - Results"); form.pnlSpecOrExam().setValue("Specimen Details"); form.lblLabRadNo().setValue("Path No."); form.lblTypeOrExamDt().setValue("Type:"); form.lblCollOrStat().setValue("Collected:"); form.lblRcvd().setValue("Received:"); form.lblTypeOrExamDt().setVisible(!isDFTInv && Boolean.FALSE.equals(ConfigFlag.UI.DISPLAY_SPECIMEN_TYPE_AT_INVESTIGATION_LEVEL.getValue())); form.txtTypeOrExamDt().setVisible(!isDFTInv && Boolean.FALSE.equals(ConfigFlag.UI.DISPLAY_SPECIMEN_TYPE_AT_INVESTIGATION_LEVEL.getValue())); } else if (cat.equals(Category.CLINICALIMAGING)) { engine.setCaption("Clinical Imaging - Results"); form.pnlSpecOrExam().setValue("Exam Details"); form.lblLabRadNo().setValue("Rad Order. No."); form.lblTypeOrExamDt().setValue("Exam Date:"); form.lblCollOrStat().setValue("Report Status:"); form.lblRcvd().setValue("Report Date:"); } else if (cat.equals(Category.CLINICAL)) { engine.setCaption("Clinical - Results"); form.pnlSpecOrExam().setValue("Exam Details"); form.lblLabRadNo().setValue("Order. No."); form.lblTypeOrExamDt().setValue("Exam Date:"); form.lblCollOrStat().setValue("Report Status:"); form.lblRcvd().setValue("Report Date:"); } } private boolean populateCurrentReport() { makeButtonsVisibleThatThisSuperCodeMayHaveHiddenForManualResult(); if(form.getGlobalContext().OCRR.getCurrentPathRadResult() == null) return false; form.btnViewPACS().setVisible(false); OcsPathRadResultVo currRep = form.getGlobalContext().OCRR.getCurrentPathRadResult(); if(currRep.getCategoryIsNotNull()) { if (engine.getPreviousNonDialogFormName().equals(form.getForms().OCRR.CAREUKNewResults)//wdev-10391 || engine.getPreviousNonDialogFormName().equals(form.getForms().OCRR.NewResults)//wdev-10391 || engine.getPreviousNonDialogFormName().equals(form.getForms().OCRR.NewResultsSearch)//WDEV-16715 || engine.getPreviousNonDialogFormName().equals(form.getForms().OCRR.PathologyOrders)//wdev-10391 || engine.getPreviousNonDialogFormName().equals(form.getForms().OCRR.RadiologyOrders))//wdev-10391 { form.getGlobalContext().Core.setPatientShort(currRep.getPatient());//wdev-10391 } if (currRep.getCategory().equals(Category.PATHOLOGY)) { //Display Cumalate button for Pathology Reports form.btnCumulResult().setVisible(true); NewResultSpecDocVo voOrderInvestigation = domain.getOrderInvestigation(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); updateButtonStateIfManualResult(voOrderInvestigation != null && voOrderInvestigation.getResultDetails() != null && voOrderInvestigation.getResultDetails().getDocumentResultDetailsIsNotNull());//WDEV-16232 return populateCurrentSpecimen(voOrderInvestigation); } else if(currRep.getCategory().equals(Category.CLINICALIMAGING)) { //Hide Cumalate button for Clinical Imaging Reports form.btnCumulResult().setVisible(false); ClinicalImagingResultVo radRes = domain.getClinicalImagingResult(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); ResultDisplayHelper resultHelper = new ResultDisplayHelper(radRes, form.dyngrdResults(), true, engine); updateButtonStateIfManualResult(radRes.getResultDetails() != null && radRes.getResultDetails().getDocumentResultDetailsIsNotNull());//WDEV-16232 form.getGlobalContext().OCRR.CentricityWebPACS.setAccessionNumber(domain.getCentricityPacsAccessionNumber(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation())); if (form.getGlobalContext().OCRR.CentricityWebPACS.getAccessionNumberIsNotNull() && ConfigFlag.UI.USE_PACS_FUNCTIONALITY.getValue())//wdev-17322 form.btnViewPACS().setVisible(true); return populateCurrentClinicalImaging(radRes,resultHelper); } //WDEV-16361 else if(currRep.getCategory().equals(Category.CLINICAL)) { form.btnCumulResult().setVisible(false); ClinicalResultVo radRes = domain.getClinicalResult(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); updateButtonStateIfManualResult(radRes.getResultDetails() != null && radRes.getResultDetails().getDocumentResultDetailsIsNotNull()); form.getGlobalContext().OCRR.CentricityWebPACS.setAccessionNumber(domain.getCentricityPacsAccessionNumber(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation())); if (form.getGlobalContext().OCRR.CentricityWebPACS.getAccessionNumberIsNotNull() && ConfigFlag.UI.USE_PACS_FUNCTIONALITY.getValue())//wdev-17322 form.btnViewPACS().setVisible(true); return populateCurrentClinical(radRes); } else { //hide Cumalate button for Clinical Reports form.btnCumulResult().setVisible(false); NewResultSpecDocVo voOrderInvestigation = domain.getOrderInvestigation(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); updateButtonStateIfManualResult(voOrderInvestigation.getResultDetails() != null && voOrderInvestigation.getResultDetails().getDocumentResultDetailsIsNotNull());//WDEV-16232 return populateCurrentSpecimen(voOrderInvestigation); } } return true; } //WDEV-16361 private boolean populateCurrentClinical(ClinicalResultVo invest) { if(invest == null) return false; clearAllControls(); displaySpecimenDetailsControlsForDFT(false, null);// WDEV-16501 displaySite(null);// WDEV-16773 if(invest != null && invest.getInvestigationIsNotNull() && invest.getInvestigation().getInvestigationIndexIsNotNull()) setLabels(invest.getInvestigation().getInvestigationIndex().getCategory(), false); setNameLabel(invest); //WDEV-16952 populateResultClinicalDemographics(invest.getOrderDetails().getPatient()); populateOrderDetails(invest.getOrderDetails()); if (invest != null && invest.getResultConclusionCommentsIsNotNull() && invest.getResultConclusionComments().size() > 0) { form.btnComments().setImage(form.getImages().Core.Copy); } else { form.btnComments().setImage(null); } //If current status RESULTED display document if(invest.getResultDetails() != null && invest.getResultDetails().getDocumentResultDetailsIsNotNull())//WDEV-16232 { form.pnlSpecOrExam().setVisible(true); form.htmDocument().setVisible(true); showResultStatusOptions(true); form.dyngrdResults().setVisible(false); if(ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) form.lnkViewPatientDetails().setVisible(true); else form.lnkViewPatientDetails().setVisible(false); form.getLocalContext().setPickValue(ResultDisplayHelper.PICK_VIEWED); //form.htmDocument().setHTML("<embed src='"+ getFileServerURL() + invest.getResultDetails().getDocumentResultDetails().getServerDocument().getFileName() + "#navpanes=0' width='835' height='411'></embed>");//WDEV-16232 form.htmDocument().setHTML("<IFRAME id=\"PostFrame\" name=\"PostFrame\" width=\"100%\" height=\"100%\" frameborder=0 src='" + getFileServerURL() + invest.getResultDetails().getDocumentResultDetails().getServerDocument().getFileName() + "'></IFRAME>");//WDEV-16651 } form.txtLabRadNo().setValue(invest.getPlacerOrdNum()); if (invest.getRepDateTime() != null) form.txtReceived().setValue(invest.getRepDateTime().toString()); if (invest.getResultStatus() != null) form.txtCollOrStat().setValue(invest.getResultStatus().getText()); OcsPathRadResultVoCollection voCollInvs = form.getGlobalContext().OCRR.getSelectedInvs(); if(voCollInvs == null) voCollInvs = new OcsPathRadResultVoCollection(); OcsPathRadResultVo voPathRadResult = new OcsPathRadResultVo(); voPathRadResult.setOrderInvestigation(invest); voPathRadResult.setDescription((invest.getInvestigationIsNotNull() && invest.getInvestigation().getInvestigationIndexIsNotNull() && invest.getInvestigation().getInvestigationIndex().getNameIsNotNull()) ? invest.getInvestigation().getInvestigationIndex().getName():null); voPathRadResult.setCategory(Category.CLINICAL); //Security levels boolean passesSecurity = true; if(form.getGlobalContext().OCRR.getRoleDisciplineSecurityLevelsIsNotNull()) { ServiceRefVo voInvService = invest.getInvestigationIsNotNull() && invest.getInvestigation().getProviderServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationService().getServiceIsNotNull() ? invest.getInvestigation().getProviderService().getLocationService().getService() : null; SecurityLevelConfigVo voInvSecurityLevel = invest.getInvestigationIsNotNull() && invest.getInvestigation().getInvestigationIndexIsNotNull() ? invest.getInvestigation().getInvestigationIndex().getSecurityLevel() : null; if(!form.getGlobalContext().OCRR.getRoleDisciplineSecurityLevels().doesInvPassSecurityCheck(voInvService, voInvSecurityLevel, false)) //WDEV-11622 passesSecurity = false; } if(passesSecurity) voCollInvs.add(voPathRadResult); form.getGlobalContext().OCRR.setSelectedInvs(voCollInvs); return true; } //WDEV-16952 private void setNameLabel(ClinicalResultVo invest) { if(invest != null && invest.getInvestigationIsNotNull() && invest.getInvestigation().getProviderServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationService().getLocation() != null) //wdev-14023 { form.lblName().setValue(invest.getInvestigation().getProviderService().getLocationService().getLocation().getName()); if (invest.getInvestigation().getProviderService().getLocationService().getService() != null) { form.lblName().setValue(form.lblName().getValue() + " (" + invest.getInvestigation().getProviderService().getLocationService().getService().getServiceName() + ")"); } } if(invest != null && invest.getInvestigationIsNotNull() && invest.getInvestigation().getProviderServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationService().getContact() != null) //wdev-14023 { StringBuffer val = new StringBuffer(); if(invest.getInvestigation().getProviderService().getLocationService().getContact().getName() != null) { if(invest.getInvestigation().getProviderService().getLocationService().getContact().getName().getForenameIsNotNull()) { val.append(invest.getInvestigation().getProviderService().getLocationService().getContact().getName().getForename()); } if(invest.getInvestigation().getProviderService().getLocationService().getContact().getName().getSurnameIsNotNull()) { val.append(" ").append(invest.getInvestigation().getProviderService().getLocationService().getContact().getName().getSurname()); } } if(invest.getInvestigation().getProviderService().getLocationService().getContact().getContactNumberIsNotNull()) { val.append(" (").append(invest.getInvestigation().getProviderService().getLocationService().getContact().getContactNumber()).append(")"); } form.lblName().setValue(form.lblName().getValue() + " - " + val); } } //WDEV-16361 private void populateResultClinicalDemographics(PatientShort patient) { if(patient == null) return; if(patient.getNameIsNotNull()) { form.txtName().setValue(patient.getName().toShortForm().toString()); } if(patient.getDobIsNotNull()) { form.txtDOB().setValue(patient.getDob().toString(DateFormat.STANDARD)); } if (patient.getIdentifiersIsNotNull()) { PatientIdCollection collIdentifiers = patient.getIdentifiers(); for (int i=0;i<collIdentifiers.size();i++) { if(collIdentifiers.get(i)!=null && PatIdType.HOSPNUM.equals(collIdentifiers.get(i).getType())) { form.txtHospnum().setValue(collIdentifiers.get(i).getValue()); } if(collIdentifiers.get(i)!=null && PatIdType.NHSN.equals(collIdentifiers.get(i).getType())) { form.txtNHSNo().setValue(collIdentifiers.get(i).getValue()); } } } if (patient.getSex() != null) { form.txtSex().setValue(patient.getSex().getText()); } } private void updateButtonStateIfManualResult(boolean hideButtons) { if(hideButtons) { form.btnCumulResult().setVisible(false); form.btnPrintOrder().setVisible(false); form.btnPrintResult().setVisible(false); form.btnResultHistory().setVisible(false); form.btnStatusHistory().setVisible(false); } } private void makeButtonsVisibleThatThisSuperCodeMayHaveHiddenForManualResult() { form.btnCumulResult().setVisible(true); form.btnPrintOrder().setVisible(true); form.btnPrintResult().setVisible(true); form.btnResultHistory().setVisible(true); form.btnStatusHistory().setVisible(true); } private boolean populateCurrentSpecimen(NewResultSpecDocVo voOrderInvestigation) { if(voOrderInvestigation == null) return false; clearAllControls(); boolean isDFTInv = isDFT(voOrderInvestigation); displaySpecimenDetailsControlsForDFT(isDFTInv, voOrderInvestigation);// WDEV-16501 displaySite(voOrderInvestigation);// WDEV-16773 // WDEV-13320 if (voOrderInvestigation.getSpecimenIsNotNull() && voOrderInvestigation.getSpecimen().size() > 0 && voOrderInvestigation.getSpecimen().get(0) != null && voOrderInvestigation.getSpecimen().get(0).getResultConclusionCommentsIsNotNull() && voOrderInvestigation.getSpecimen().get(0).getResultConclusionComments().size() > 0) { form.btnComments().setImage(form.getImages().Core.Copy); } else { form.btnComments().setImage(null); } if(voOrderInvestigation.getInvestigationIsNotNull() && voOrderInvestigation.getInvestigation().getInvestigationIndexIsNotNull() && voOrderInvestigation.getInvestigation().getInvestigationIndex().getCategoryIsNotNull()) setLabels(voOrderInvestigation.getInvestigation().getInvestigationIndex().getCategory(), isDFTInv); boolean bPopulateGrid = false; form.getLocalContext().sethtmlString(""); //If current status RESULTED display document otherwise populate grid if(voOrderInvestigation.getResultDetails() != null && voOrderInvestigation.getResultDetails().getDocumentResultDetailsIsNotNull())//WDEV-16232 { form.pnlSpecOrExam().setVisible(true); form.htmDocument().setVisible(true); showResultStatusOptions(true); form.dyngrdResults().setVisible(false); //WDEV-10904 String htmlString = "<IFRAME id=\"PostFrame\" name=\"PostFrame\" width=\"100%\" height=\"100%\" frameborder=0 src='" + getFileServerURL() + voOrderInvestigation.getResultDetails().getDocumentResultDetails().getServerDocument().getFileName() + "'></IFRAME>";//WDEV-16232 form.getLocalContext().sethtmlString(htmlString); form.htmDocument().setHTML(htmlString); if(voOrderInvestigation.getInvestigationIsNotNull() && voOrderInvestigation.getInvestigation().getInvestigationIndexIsNotNull() && voOrderInvestigation.getInvestigation().getInvestigationIndex().getCategoryIsNotNull()) if(voOrderInvestigation.getInvestigation().getInvestigationIndex().getCategory().equals(Category.CLINICAL)) { populateOrderDetails(domain.getNewResultOcsOrderVo(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation())); return true; } } else{ form.pnlSpecOrExam().setVisible(false); form.htmDocument().setVisible(false); showResultStatusOptions(false); form.dyngrdResults().setVisible(true); bPopulateGrid = true; } PathologySpecimenVo specimen = null; if(voOrderInvestigation.getSpecimenIsNotNull() && voOrderInvestigation.getSpecimen().size() > 0) { specimen = voOrderInvestigation.getSpecimen().get(0); } if (specimen == null) { if(ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) form.lnkViewPatientDetails().setVisible(true); else form.lnkViewPatientDetails().setVisible(false); } else if (specimen != null) { if(!isDFTInv) { form.txtLabRadNo().setValue(specimen.getFillerOrdNum()); //WDEV-11630 String display = ""; /*WDEV-15552 if(specimen.getResultSpecimenSourceIsNotNull()) display = specimen.getResultSpecimenSource().getText() + (specimen.getSiteCdIsNotNull() ? " - " + specimen.getSiteCd().getText() : ""); else*/ if (specimen.getSpecimenSourceIsNotNull()) display = specimen.getSpecimenSource().getText() + (specimen.getSiteCdIsNotNull() ? " - " + specimen.getSiteCd().getText() : ""); form.txtTypeOrExamDt().setValue(display); if (specimen.getCollDateTimeFillerIsNotNull()) { if (Boolean.FALSE.equals(specimen.getColTimeFillerSupplied())) { form.txtCollOrStat().setValue(specimen.getCollDateTimeFiller().getDate().toString()); } else { form.txtCollOrStat().setValue(specimen.getCollDateTimeFiller().toString()); } } else { if(specimen.getCollDateTimePlacerIsNotNull()) { if (Boolean.FALSE.equals(specimen.getColTimeFillerSupplied())) { form.txtCollOrStat().setValue(specimen.getCollDateTimePlacer().getDate().toString()); } else { form.txtCollOrStat().setValue(specimen.getCollDateTimePlacer().toString()); } } } if(specimen.getReceivedDateTimeIsNotNull()) { if(specimen.getReceivedTimeSuppliedIsNotNull() && specimen.getReceivedTimeSupplied().booleanValue()) form.txtReceived().setValue(specimen.getReceivedDateTime().toString()); else if(specimen.getReceivedDateTime().getDate() != null) form.txtReceived().setValue(specimen.getReceivedDateTime().getDate().toString()); } } populateOrderDetails(specimen.getOrder()); if(specimen.getInvestigationsIsNotNull()) { //JME: 20061017: Sorting them by sysinfo specimen.getInvestigations().sort(); if(specimen.getInvestigations().size() > 0) { for (int i=0; i<specimen.getInvestigations().size(); i++) { PathologySpecimenOrderInvestigationVo vo = specimen.getInvestigations().get(i); ResultDemographicsVo demog=vo.getResultDemographics(); if (demog != null && demog.getNameIsNotNull()) { populateResultDemographics(demog); break; } } populateLabDetails(specimen.getInvestigations().get(0)); if(bPopulateGrid) populateResults(specimen.getInvestigations(), bPopulateGrid); } } if(bPopulateGrid) { createPickerRow(isDFTInv, voOrderInvestigation.getResultStatus()); form.dyngrdResults().resetScrollPosition(); form.dyngrdResults().getRows().expandAll(); } } return true; } // WDEV-16773 private void displaySite(NewResultSpecDocVo voOrderInvestigation) { form.lblSite().setVisible(false); form.txtSite().setVisible(false); if(voOrderInvestigation == null || voOrderInvestigation.getSpecimen() == null || voOrderInvestigation.getSpecimen().size() == 0) return; PathologySpecimenVo lastSpecimen = voOrderInvestigation.getSpecimen().get(voOrderInvestigation.getSpecimen().size() - 1); if(lastSpecimen == null || lastSpecimen.getSiteCd() == null) return; form.lblSite().setVisible(true); form.txtSite().setVisible(true); form.txtSite().setEnabled(false); form.txtSite().setValue(lastSpecimen.getSiteCd().getText()); } //WDEV-16232 private void displaySpecimenDetailsControlsForDFT(boolean isDFTInv, NewResultSpecDocVo voOrderInvestigation)// WDEV-16501 { form.lblLabRadNo().setVisible(!isDFTInv); form.lblTypeOrExamDt().setVisible(!isDFTInv); form.lblCollOrStat().setVisible(!isDFTInv); form.lblRcvd().setVisible(!isDFTInv); form.txtLabRadNo().setVisible(!isDFTInv); form.txtTypeOrExamDt().setVisible(!isDFTInv); form.txtCollOrStat().setVisible(!isDFTInv); form.txtReceived().setVisible(!isDFTInv); form.btnComments().setVisible(!isDFTInv); setSpecimenDetailsControlsVisible(isDFTInv); if(voOrderInvestigation == null) return; form.txtSpecimenCollected().setValue(voOrderInvestigation.getSpecimen() != null ? "" + voOrderInvestigation.getSpecimen().size() : null); form.txtSpecimenResulted().setValue((voOrderInvestigation.getResultDetails() != null && voOrderInvestigation.getResultDetails().getPathologyResultDetails() != null)? "" + voOrderInvestigation.getResultDetails().getPathologyResultDetails().size() : null); form.txtOrderStatus().setValue(getOrderStatus(voOrderInvestigation.getResultStatus()));// WDEV-16675 } // WDEV-16675 private String getOrderStatus(ResultStatus resultStatus) { if(resultStatus == null) return null; if(ResultStatus.PROVISIONAL.equals(resultStatus)) return PROVISIONAL; else if(ResultStatus.FINAL.equals(resultStatus)) return FINAL; return resultStatus.getText(); } private void setSpecimenDetailsControlsVisible(boolean visible) { form.lblSpecCollected().setVisible(visible); form.lblSpecResulted().setVisible(visible); form.lblOderStatus().setVisible(visible);// WDEV-16675 form.txtSpecimenCollected().setVisible(visible); form.txtSpecimenResulted().setVisible(visible); form.txtOrderStatus().setVisible(visible);// WDEV-16675 if(visible) { form.txtSpecimenCollected().setEnabled(false); form.txtSpecimenResulted().setEnabled(false); form.txtOrderStatus().setEnabled(false);// WDEV-16675 } } private void showResultStatusOptions(boolean bVisible) { form.chkEnableExit().setVisible(bVisible); form.chkMarkAsSeen().setVisible(bVisible && engine.hasRight(AppRight.CAN_UPDATE_RESULT_STATUS) && !engine.hasRight(AppRight.MARK_RESULT_AS_CHECKED)); form.chkMarkAsChecked().setVisible(bVisible && engine.hasRight(AppRight.CAN_UPDATE_RESULT_STATUS) && engine.hasRight(AppRight.MARK_RESULT_AS_CHECKED)); form.chkMarkForReview().setVisible(bVisible && engine.hasRight(AppRight.CAN_UPDATE_RESULT_STATUS)); } private String getFileServerURL() { return ConfigFlag.GEN.FILE_SERVER_URL.getValue(); } private boolean populateCurrentClinicalImaging(ClinicalImagingResultVo invest, ResultDisplayHelper resultHelper) { if(invest == null) return false; OcsPathRadResultVoCollection voCollResult = new OcsPathRadResultVoCollection(); clearAllControls(); displaySpecimenDetailsControlsForDFT(false, null);// WDEV-16501 displaySite(null);// WDEV-16773 if(invest != null && invest.getInvestigationIsNotNull() && invest.getInvestigation().getInvestigationIndexIsNotNull()) setLabels(invest.getInvestigation().getInvestigationIndex().getCategory(), false); setNameLabel(invest); populateResultDemographics(invest.getResultDemographics()); populateOrderDetails(invest.getOrderDetails()); // WDEV-13320 if (invest != null && invest.getResultConclusionCommentsIsNotNull() && invest.getResultConclusionComments().size() > 0) { form.btnComments().setImage(form.getImages().Core.Copy); } else { form.btnComments().setImage(null); } boolean bPopulateGrid = false; //If current status RESULTED display document otherwise populate grid if(invest.getResultDetails() != null && invest.getResultDetails().getDocumentResultDetailsIsNotNull())//WDEV-16232 { form.pnlSpecOrExam().setVisible(true); form.htmDocument().setVisible(true); showResultStatusOptions(true); form.dyngrdResults().setVisible(false); if(ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) form.lnkViewPatientDetails().setVisible(true); else form.lnkViewPatientDetails().setVisible(false); form.getLocalContext().setPickValue(ResultDisplayHelper.PICK_VIEWED); form.htmDocument().setHTML("<embed src='"+ getFileServerURL() + invest.getResultDetails().getDocumentResultDetails().getServerDocument().getFileName() + "#navpanes=0' width='835' height='411'></embed>");//WDEV-16232 } else{ form.pnlSpecOrExam().setVisible(false); form.htmDocument().setVisible(false); showResultStatusOptions(false); form.dyngrdResults().setVisible(true); bPopulateGrid = true; } form.txtLabRadNo().setValue(invest.getFillerOrdNum()); if (invest.getResultDetails() != null && invest.getResultDetails().getClinicalResultDetails() != null && invest.getResultDetails().getClinicalResultDetails().getExamDateTime() != null)//WDEV-16232 { if (invest.getResultDetails().getClinicalResultDetails().getExamTimeSupplied().booleanValue())//WDEV-16232 form.txtTypeOrExamDt().setValue(invest.getResultDetails().getClinicalResultDetails().getExamDateTime().toString());//WDEV-16232 else form.txtTypeOrExamDt().setValue(invest.getResultDetails().getClinicalResultDetails().getExamDateTime().getDate().toString());//WDEV-16232 } // JP 09/11/2006 WDEV-2102 if (invest.getRepDateTime() != null) form.txtReceived().setValue(invest.getRepDateTime().toString()); if (invest.getResultStatus() != null) form.txtCollOrStat().setValue(invest.getResultStatus().getText()); OcsPathRadResultVoCollection voCollInvs = form.getGlobalContext().OCRR.getSelectedInvs(); if(voCollInvs == null) voCollInvs = new OcsPathRadResultVoCollection(); OcsPathRadResultVo voPathRadResult = new OcsPathRadResultVo(); voPathRadResult.setOrderInvestigation(invest); voPathRadResult.setDescription(invest.getIOrderResultDisplayInvName()); voPathRadResult.setCategory(Category.CLINICALIMAGING); //WDEV-9780 - security levels boolean passesSecurity = true; if(form.getGlobalContext().OCRR.getRoleDisciplineSecurityLevelsIsNotNull()) { ServiceRefVo voInvService = invest.getInvestigationIsNotNull() && invest.getInvestigation().getProviderServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationService().getServiceIsNotNull() ? invest.getInvestigation().getProviderService().getLocationService().getService() : null; SecurityLevelConfigVo voInvSecurityLevel = invest.getInvestigationIsNotNull() && invest.getInvestigation().getInvestigationIndexIsNotNull() ? invest.getInvestigation().getInvestigationIndex().getSecurityLevel() : null; if(!form.getGlobalContext().OCRR.getRoleDisciplineSecurityLevels().doesInvPassSecurityCheck(voInvService, voInvSecurityLevel, false)) //WDEV-11622 passesSecurity = false; } if(passesSecurity) voCollInvs.add(voPathRadResult); form.getGlobalContext().OCRR.setSelectedInvs(voCollInvs); String displayTextMappingForResultStatus = null;// WDEV-15783 if(invest.getResultStatus() != null)// WDEV-15783 { displayTextMappingForResultStatus = domain.getMappingForResultStatusLookup(invest.getResultStatus(), TaxonomyType.DISPLAY_TEXT); } if(resultHelper.addRadResult(false, displayTextMappingForResultStatus))// WDEV-15783 { if(passesSecurity) voCollResult.add(voPathRadResult); form.getGlobalContext().OCRR.setSelectedInvsWithResults(voCollResult); } /* * --THE REPORT VIEWER PICKER ROW IS ALWAYS THE LAST ROW TO BE ADDED TO THE RESULTS GRID */ if(bPopulateGrid) { createPickerRow(false, null); /* * --THE REPORT VIEWER PICKER ROW IS ALWAYS THE LAST ROW TO BE ADDED TO THE RESULTS GRID - * DO NOT ADD ANY ADDITIONAL ROWS AFTER THE ABOVE METHOD IS CALLED */ form.dyngrdResults().resetScrollPosition(); form.dyngrdResults().getRows().expandAll(); } return true; } private void setNameLabel(ClinicalImagingResultVo invest) { if(invest != null && invest.getInvestigationIsNotNull() && invest.getInvestigation().getProviderServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationService().getLocation() != null) //wdev-14023 { form.lblName().setValue(invest.getInvestigation().getProviderService().getLocationService().getLocation().getName()); if (invest.getInvestigation().getProviderService().getLocationService().getService() != null) { form.lblName().setValue(form.lblName().getValue() + " (" + invest.getInvestigation().getProviderService().getLocationService().getService().getServiceName() + ")"); } } if(invest != null && invest.getInvestigationIsNotNull() && invest.getInvestigation().getProviderServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationServiceIsNotNull() && invest.getInvestigation().getProviderService().getLocationService().getContact() != null) //wdev-14023 { StringBuffer val = new StringBuffer(); if(invest.getInvestigation().getProviderService().getLocationService().getContact().getName() != null) { if(invest.getInvestigation().getProviderService().getLocationService().getContact().getName().getForenameIsNotNull()) { val.append(invest.getInvestigation().getProviderService().getLocationService().getContact().getName().getForename()); } if(invest.getInvestigation().getProviderService().getLocationService().getContact().getName().getSurnameIsNotNull()) { val.append(" ").append(invest.getInvestigation().getProviderService().getLocationService().getContact().getName().getSurname()); } } if(invest.getInvestigation().getProviderService().getLocationService().getContact().getContactNumberIsNotNull()) { val.append(" (").append(invest.getInvestigation().getProviderService().getLocationService().getContact().getContactNumber()).append(")"); } form.lblName().setValue(form.lblName().getValue() + " - " + val); } } private void populateResultDemographics(ResultDemographicsVo demog) { if(demog == null) return; if(demog.getNameIsNotNull()) { form.txtName().setValue(demog.getName().toShortForm().toString()); } if(demog.getDobIsNotNull()) { form.txtDOB().setValue(demog.getDob().toString(DateFormat.STANDARD)); } if(demog.getHospNumIsNotNull()) { form.txtHospnum().setValue(demog.getHospNum()); } if(demog.getNhsNumberIsNotNull()) { form.txtNHSNo().setValue(demog.getNhsNumber()); } if (demog.getSex() != null) { form.txtSex().setValue(demog.getSex().getText()); } } private void populateOrderDetails(NewResultOcsOrderVo order) { form.getGlobalContext().OCRR.setQuestionsNotes(order); if (order == null) return; boolean hasQuestions = order.getClinicalInfoIsNotNull() && order.getClinicalInfo().getCategoryQuestionAnswersIsNotNull() && order.getClinicalInfo().getCategoryQuestionAnswers().size() > 0; boolean hasNotes = order.getAdditClinNotesIsNotNull() && order.getAdditClinNotes().length() > 0; if (hasQuestions || hasNotes) { form.lnkViewOrderNotes().setEnabled(true); form.lnkViewOrderNotes().setTooltip("Click to view Order Notes"); } else { form.lnkViewOrderNotes().setTooltip("No Order Notes Entered"); form.lnkViewOrderNotes().setEnabled(true); } form.txtOrderingLocation().setValue(order.getCorrectLocation()); form.txtClinician().setValue(order.getCorrectClinician()); if (order.getOrderedByIsNotNull() && order.getOrderedBy().getNameIsNotNull()) { form.txtRequestedBy().setValue(order.getOrderedBy().getName().toString()); } if (order.getSysInfoIsNotNull()) form.txtOrderDt().setValue(order.getSysInfo().getCreationDateTime().toString()); //WDEV-4758 if(ConfigFlag.DOM.CREATE_ORDERS_WITH_CARECONTEXT_ONLY.getValue()) { if(order.getCareContextIsNotNull() && order.getCareContext().getPasEventIsNotNull()) form.txtPasEpisodeID().setValue(order.getCareContext().getPasEvent().getPasEpisodeId()); } } private void createPickerRow(boolean isDFTInv, ResultStatus resultStatus) { DynamicGridRow row = form.dyngrdResults().getRows().newRow(); row.setSelectable(false); //row = form.dyngrdResults().getRows().newRow(); if (form.dyngrdResults().getColumns().size() > 0) { if(!isSTHKModeResultCheck())// WDEV-15894 { DynamicGridColumn pickCol = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_PICK); DynamicGridCell cellPick = row.getCells().newCell(pickCol, DynamicCellType.MULTISELECT); cellPick.setWidth(283); cellPick.setTextColor(Color.Blue); cellPick.setAutoPostBack(true); cellPick.setReadOnly(false); cellPick.setMaxCheckedItemsForMultiSelect(new Integer(1)); //WDEV-2780 DynamicGridCellItem item = cellPick.getItems().newItem("Enable Exit", "Enable Exit"); item.setIdentifier(ResultDisplayHelper.PICK_VIEWED); if (engine.hasRight(AppRight.MARK_RESULT_AS_CHECKED) && (!isDFTInv || (isDFTInv && ResultStatus.FINAL.equals(resultStatus)))) { item = cellPick.getItems().newItem("Mark report as Checked", "Mark report as Checked"); item.setIdentifier(ResultDisplayHelper.PICK_CHKD); } else { if (engine.hasRight(AppRight.CAN_UPDATE_RESULT_STATUS) && (!isDFTInv || (isDFTInv && ResultStatus.FINAL.equals(resultStatus)))) { item = cellPick.getItems().newItem("Mark report as Seen", "Mark report as Seen"); item.setIdentifier(ResultDisplayHelper.PICK_SEEN); } } if (engine.hasRight(AppRight.CAN_UPDATE_RESULT_STATUS) && (!isDFTInv || (isDFTInv && ResultStatus.FINAL.equals(resultStatus)))) { item = cellPick.getItems().newItem("Mark report for Review", "Mark report for Review"); item.setIdentifier(ResultDisplayHelper.PICK_QRY); } } else// WDEV-15894 - starts here { DynamicGridColumn pCol = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_PREVIEW); if(pCol != null) { boolean canDisplayPreviewButton = canDisplayPreviewButton(); DynamicGridCell cellP = row.getCells().newCell(pCol, canDisplayPreviewButton ? DynamicCellType.BUTTON : DynamicCellType.EMPTY); cellP.setWidth(80); if(canDisplayPreviewButton) { cellP.setButtonText(PREVIOUS_TEXT_BUTTON); cellP.setAutoPostBack(true); cellP.setIdentifier(ResultDisplayHelper.BUTTON_PREVIEW); } } DynamicGridColumn cCol = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_CHECKED_EXIT); if(cCol != null) { DynamicGridCell cellC = row.getCells().newCell(cCol, DynamicCellType.BUTTON); cellC.setWidth(120); cellC.setAutoPostBack(true); cellC.setIdentifier(ResultDisplayHelper.BUTTON_CHKD); cellC.setButtonText(hasMarkResultAsCheckedRoleRight() ? CHECKED_TEXT_BUTTON : EXIT_TEXT_BUTTON); } DynamicGridColumn nCol = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_NEXT); if(nCol != null) { boolean canDisplayNextButton = canDisplayNextButton(); DynamicGridCell cellN = row.getCells().newCell(nCol, canDisplayNextButton ? DynamicCellType.BUTTON : DynamicCellType.EMPTY); cellN.setWidth(80); if(canDisplayNextButton) { cellN.setButtonText(NEXT_TEXT_BUTTON); cellN.setAutoPostBack(true); cellN.setIdentifier(ResultDisplayHelper.BUTTON_NEXT); } } }// WDEV-15894 - ends here DynamicGridCell cell = row.getCells().newCell(form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_NAME), DynamicCellType.STRING); cell.setWidth(528); cell.setReadOnly(true); DynamicGridColumn colTest = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_TEST); if (colTest != null) { cell = row.getCells().newCell(colTest, DynamicCellType.LABEL); colTest.setWidth(0); cell.setWidth(0); } DynamicGridColumn colValue = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_VALUE); if (colValue != null) { cell = row.getCells().newCell(colValue, DynamicCellType.LABEL); colValue.setWidth(0); cell.setWidth(0); } DynamicGridColumn colUnits = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_UNITS); if (colUnits != null) { cell = row.getCells().newCell(colUnits, DynamicCellType.LABEL); colUnits.setWidth(0); cell.setWidth(0); } DynamicGridColumn colRefRange = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_REF_RANGE); if (colRefRange != null) { cell = row.getCells().newCell(colRefRange, DynamicCellType.LABEL); colRefRange.setWidth(0); cell.setWidth(0); } DynamicGridColumn colComments = form.dyngrdResults().getColumns().getByIdentifier(ResultDisplayHelper.COL_COMMENTS); if (colComments != null) { cell = row.getCells().newCell(colComments, DynamicCellType.WRAPTEXT); colComments.setWidth(0); cell.setWidth(0); } } } // WDEV-15894 private boolean canDisplayNextButton() { if(form.getGlobalContext().OCRR.getSelectedPathRadResults() != null && form.getGlobalContext().OCRR.getCurrentPathRadResult() != null && form.getGlobalContext().OCRR.getSelectedPathRadResults().indexOf(form.getGlobalContext().OCRR.getCurrentPathRadResult()) < (form.getGlobalContext().OCRR.getSelectedPathRadResults().size() - 1)) { return true; } return false; } // WDEV-15894 private boolean canDisplayPreviewButton() { if(form.getGlobalContext().OCRR.getSelectedPathRadResults() != null && form.getGlobalContext().OCRR.getCurrentPathRadResult() != null && form.getGlobalContext().OCRR.getSelectedPathRadResults().indexOf(form.getGlobalContext().OCRR.getCurrentPathRadResult()) > 0) { return true; } return false; } // WDEV-15894 private boolean hasMarkResultAsCheckedRoleRight() { return engine.hasRight(AppRight.MARK_RESULT_AS_CHECKED); } // WDEV-15894 private boolean isSTHKModeResultCheck() { return ConfigFlag.UI.STHK_MODE_RESULT_CHECK.getValue(); } private void populateResults(PathologySpecimenOrderInvestigationVoCollection investigations, boolean bPopulateGrid) { if(investigations == null) return; for(int x = 0; x < investigations.size(); x++) { populateInvestigationResults(investigations.get(x), bPopulateGrid); } } private void populateInvestigationResults(PathologySpecimenOrderInvestigationVo investigation, boolean bPopulateGrid) { if(investigation == null) throw new CodingRuntimeException("investigation is null in method populateInvestigationResults"); ResultDisplayHelper resultHelper = null; //WDEV-9780 if(form.getGlobalContext().OCRR.getRoleDisciplineSecurityLevelsIsNotNull()) { ServiceRefVo voInvService = investigation.getInvestigationIsNotNull() && investigation.getInvestigation().getProviderServiceIsNotNull() && investigation.getInvestigation().getProviderService().getLocationServiceIsNotNull() && investigation.getInvestigation().getProviderService().getLocationService().getServiceIsNotNull() ? investigation.getInvestigation().getProviderService().getLocationService().getService() : null; SecurityLevelConfigVo voInvSecurityLevel = investigation.getInvestigationIsNotNull() && investigation.getInvestigation().getInvestigationIndexIsNotNull() ? investigation.getInvestigation().getInvestigationIndex().getSecurityLevel() : null; if(!form.getGlobalContext().OCRR.getRoleDisciplineSecurityLevels().doesInvPassSecurityCheck(voInvService, voInvSecurityLevel, false)) //WDEV-11622 return; } if(investigation.getResultDetails() != null && investigation.getResultDetails().getPathologyResultDetailsIsNotNull() && investigation.getResultDetails().getPathologyResultDetails().size() > 0 && investigation.getResultDetails().getPathologyResultDetails().get(0) != null && investigation.getResultDetails().getPathologyResultDetails().get(0).getResultComponentsIsNotNull() && investigation.getResultDetails().getPathologyResultDetails().get(0).getResultComponents().size() > 0 && investigation.getResultDetails().getPathologyResultDetails().get(0).getResultComponents().get(0) != null && ResultValueType.ED.equals(investigation.getResultDetails().getPathologyResultDetails().get(0).getResultComponents().get(0).getResValType()))//WDEV-16232 { form.pnlSpecOrExam().setVisible(true); showResultStatusOptions(!bPopulateGrid); if(ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) form.lnkViewPatientDetails().setVisible(true); else form.lnkViewPatientDetails().setVisible(false); form.getLocalContext().setPickValue(ResultDisplayHelper.PICK_VIEWED); updateButtonStateIfManualResult(true); } if (investigation.getResultDetails() != null && investigation.getResultDetails().getPathologyResultDetailsIsNotNull()) { for(int i=0; i<investigation.getResultDetails().getPathologyResultDetails().size(); i++) { if (investigation.getResultDetails().getPathologyResultDetails().get(i) != null && investigation.getResultDetails().getPathologyResultDetails().get(i).getResultComponentsIsNotNull())//WDEV-16232 { for(int x = 0; x < investigation.getResultDetails().getPathologyResultDetails().get(i).getResultComponents().size(); x++)//WDEV-16232 { addAnalyte(investigation.getResultDetails().getPathologyResultDetails().get(i).getResultComponents().get(x).getAnalyte());//WDEV-16232 } } } } try { resultHelper = new ResultDisplayHelper(investigation, form.dyngrdResults(), engine); resultHelper.setAnalytes(form.getLocalContext().getAnalytes()); OcsPathRadResultVoCollection voCollResult = form.getGlobalContext().OCRR.getSelectedInvsWithResults(); if(voCollResult == null) voCollResult = new OcsPathRadResultVoCollection(); OcsPathRadResultVoCollection voCollInvs = form.getGlobalContext().OCRR.getSelectedInvs(); if(voCollInvs == null) voCollInvs = new OcsPathRadResultVoCollection(); OcsPathRadResultVo voPathRadResult = new OcsPathRadResultVo(); voPathRadResult.setOrderInvestigation(investigation); voPathRadResult.setDescription(investigation.getIOrderResultDisplayInvName()); voPathRadResult.setCategory(Category.PATHOLOGY); voCollInvs.add(voPathRadResult); form.getGlobalContext().OCRR.setSelectedInvs(voCollInvs); String displayTextMappingForResultStatus = null;// WDEV-15783 if(investigation.getResultStatus() != null)// WDEV-15783 { displayTextMappingForResultStatus = domain.getMappingForResultStatusLookup(investigation.getResultStatus(), TaxonomyType.DISPLAY_TEXT); } if(resultHelper.addPathResult(false, displayTextMappingForResultStatus))// WDEV-15783 { //WDEV-9780 boolean passesSecurity = true; if(form.getGlobalContext().OCRR.getRoleDisciplineSecurityLevelsIsNotNull()) { ServiceRefVo voInvService = investigation.getInvestigationIsNotNull() && investigation.getInvestigation().getProviderServiceIsNotNull() && investigation.getInvestigation().getProviderService().getLocationServiceIsNotNull() && investigation.getInvestigation().getProviderService().getLocationService().getServiceIsNotNull() ? investigation.getInvestigation().getProviderService().getLocationService().getService() : null; SecurityLevelConfigVo voInvSecurityLevel = investigation.getInvestigationIsNotNull() && investigation.getInvestigation().getInvestigationIndexIsNotNull() ? investigation.getInvestigation().getInvestigationIndex().getSecurityLevel() : null; if(!form.getGlobalContext().OCRR.getRoleDisciplineSecurityLevels().doesInvPassSecurityCheck(voInvService, voInvSecurityLevel, false)) //WDEV-11622 passesSecurity = false; } if(passesSecurity) voCollResult.add(voPathRadResult); form.getGlobalContext().OCRR.setSelectedInvsWithResults(voCollResult); } if (resultHelper != null && resultHelper.getTemporaryFiles() != null && resultHelper.getTemporaryFiles().size() >0) { ArrayList<String> tempFiles = form.getLocalContext().getTempFiles(); if (tempFiles == null) tempFiles = new ArrayList<String>(); for (String tempFile : resultHelper.getTemporaryFiles()) { tempFiles.add(tempFile); } form.getLocalContext().setTempFiles(tempFiles); } } catch (Exception e) { int EventId = engine.createSystemLogEntry(SystemLogType.APPLICATION, SystemLogLevel.FATALERROR, "Error displaying result for patient investigation id:" + investigation.getBoId() + "\n" + e.getMessage()).getSystemLogEventId(); engine.showMessage("Error displaying patient result.\nFor more information plese look in 'System Log' form and search by eventId = " + EventId); displayResultWhenInboundMessageCorrupted(); return; } } private boolean isDFT(NewResultSpecDocVo result) //WDEV-16232 { if(result == null || result.getInvestigation() == null) return false; if(InvEventType.TIME_SERIES.equals(result.getInvestigation().getEventType())) return true; return false; } //WDEV-14353 private void displayResultWhenInboundMessageCorrupted() { form.pnlSpecOrExam().setVisible(true); form.htmDocument().setVisible(true); showResultStatusOptions(true); form.dyngrdResults().setVisible(false); if(ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) form.lnkViewPatientDetails().setVisible(true); else form.lnkViewPatientDetails().setVisible(false); form.getLocalContext().setPickValue(ResultDisplayHelper.PICK_VIEWED); form.getLocalContext().sethtmlString(""); form.htmDocument().setHTML(""); updateButtonStateIfManualResult(true); } private void populateLabDetails(PathologySpecimenOrderInvestigationVo investigation) { if(investigation == null) return; if(investigation.getInvestigation() == null) return; if(investigation.getInvestigation().getProviderService() == null) return; if(investigation.getInvestigation().getProviderService().getLocationService() == null) return; setNameLabel(investigation); } private void setNameLabel(PathologySpecimenOrderInvestigationVo investigation) { if(investigation.getInvestigation().getProviderService().getLocationService().getLocation() != null) { form.lblName().setValue(investigation.getInvestigation().getProviderService().getLocationService().getLocation().getName()); if (investigation.getInvestigation().getProviderService().getLocationService().getService() != null) { form.lblName().setValue(form.lblName().getValue() + " (" + investigation.getInvestigation().getProviderService().getLocationService().getService().getServiceName() + ")"); } } if(investigation.getInvestigation().getProviderService().getLocationService().getContact() != null) { StringBuffer val = new StringBuffer(); if(investigation.getInvestigation().getProviderService().getLocationService().getContact().getName() != null) { if(investigation.getInvestigation().getProviderService().getLocationService().getContact().getName().getForenameIsNotNull()) { val.append(investigation.getInvestigation().getProviderService().getLocationService().getContact().getName().getForename()); } if(investigation.getInvestigation().getProviderService().getLocationService().getContact().getName().getSurnameIsNotNull()) { val.append(" ").append(investigation.getInvestigation().getProviderService().getLocationService().getContact().getName().getSurname()); } } if(investigation.getInvestigation().getProviderService().getLocationService().getContact().getContactNumberIsNotNull()) { val.append(" (").append(investigation.getInvestigation().getProviderService().getLocationService().getContact().getContactNumber()).append(")"); } form.lblName().setValue(form.lblName().getValue() + " - " + val); } } protected void onDyngrdResultsCellValueChanged(DynamicGridCell cell) { disableNavigation(); form.imbClose().setEnabled(false); form.lnkViewPatientDetails().setVisible(false); //form.imbPrint().setEnabled(false); // WDEV-13321 form.getLocalContext().setPickValue(null); DynamicGridCellItemCollection items = cell.getItems(); for (int i = 0; i < items.size(); i++) { DynamicGridCellItem item = items.get(i); if (item.isChecked()) { form.imbClose().setEnabled(true); //form.imbPrint().setEnabled(true); if(ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) form.lnkViewPatientDetails().setVisible(true); else form.lnkViewPatientDetails().setVisible(false); form.getLocalContext().setPickValue((Integer)item.getIdentifier()); setNavigationState(); } } // WDEV-13321 // Default to responsible HCP clinician if (ResultDisplayHelper.PICK_QRY.equals(form.getLocalContext().getPickValue())) { // WDEV-18052 - Do not default in Medic // NewResultOcsOrderVo result = domain.getNewResultOcsOrderVo(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); // // // WDEV-14097 // // Default in only if the 'Responsible HCP' is a MEDIC // if (result.getResponsibleClinicianIsNotNull() && HcpDisType.MEDICAL.equals(result.getResponsibleClinician().getHcpType())) // { // form.ccMedicReview().setValue(result.getResponsibleClinician()); // } } else { form.ccMedicReview().clear(); } // WDEV-13321 updateControlsState(); } protected void onBtnCumulResultClick() throws PresentationLogicException { displayCumulateResults(); } private void displayCumulateResults() { OcsPathRadResultVo currRep = form.getGlobalContext().OCRR.getCurrentPathRadResult(); if(currRep == null) return; if(currRep.getCategoryIsNotNull()) { if (currRep.getCategory().equals(Category.PATHOLOGY)) { PathologySpecimenVo specimen = domain.getSpecimen(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); if(specimen != null && specimen.getOrderIsNotNull())//WDEV-16463 { form.getGlobalContext().Core.setSecondPatientShort(specimen.getOrder().getPatient()); } } else if (currRep.getCategory().equals(Category.CLINICALIMAGING)) { ClinicalImagingResultVo radRes = domain.getClinicalImagingResult(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); if(radRes != null && radRes.getOrderDetailsIsNotNull())//WDEV-16463 { form.getGlobalContext().Core.setSecondPatientShort(radRes.getOrderDetails().getPatient()); } } } form.getGlobalContext().OCRR.setCumulateAnalytes(form.getLocalContext().getAnalytes()); if(form.getGlobalContext().OCRR.getCurrentPathRadResult() != null) { form.getGlobalContext().OCRR.setOrderInvestigationReference(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); } engine.open(form.getForms().OCRR.CumulateResults); } protected void onBtnResultHistoryClick() throws PresentationLogicException { engine.open(form.getForms().OCRR.ResultHistory); } protected void onBtnStatusHistoryClick() throws PresentationLogicException { engine.open(form.getForms().OCRR.OrderInvStatusHistory); } private void addAnalyte(AnalyteRefVo value) { if(value == null) return; AnalyteRefVoCollection analytes = form.getLocalContext().getAnalytes(); if(analytes == null) analytes = new AnalyteRefVoCollection(); if(analytes.indexOf(value) >= 0) return; analytes.add(value); form.getLocalContext().setAnalytes(analytes); } @Override protected void onBtnPrintOrderClick() throws PresentationLogicException { String urlQueryServer = ConfigFlag.GEN.QUERY_SERVER_URL.getValue(); String urlReportServer = ConfigFlag.GEN.REPORT_SERVER_URL.getValue(); OcsPathRadResultVo currRep = form.getGlobalContext().OCRR.getCurrentPathRadResult(); if(currRep == null) return; Object[] obj = null; QueryBuilderClient client = new QueryBuilderClient(urlQueryServer, engine.getSessionId()); if(currRep.getCategoryIsNotNull()) { if (currRep.getCategory().equals(Category.PATHOLOGY)) { PathologySpecimenVo specimen = domain.getSpecimen(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); //we need a better way to do this obj = domain.getSystemReportAndTemplate(new Integer(90)); client.addSeed(new SeedValue("OrderSpecimen_id", specimen.getID_OrderSpecimen(), Integer.class)); } else if (currRep.getCategory().equals(Category.CLINICALIMAGING)) { ClinicalImagingResultVo radRes = domain.getClinicalImagingResult(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); //we need a better way to do this obj = domain.getSystemReportAndTemplate(new Integer(91)); client.addSeed(new SeedValue("OrderInvestigation_id", radRes.getID_OrderInvestigation(), Integer.class)); } } if(obj == null || obj.length < 2) { engine.showMessage("I could not get the report and template !"); return; } if(obj[0] == null || obj[1] == null) { engine.showMessage("The report has not been deployed !"); return; } String resultUrl = ""; try { resultUrl = client.buildReportAsUrl((String)obj[0], (String)obj[1], urlReportServer, "PDF", "", 1); } catch (QueryBuilderClientException e1) { engine.showMessage("Error creating report: " + e1.getMessage()); return; } engine.openUrl(resultUrl); /* ReportVoCollection coll = domain.listAssignedReports(new Integer(engine.getFormName().getID())); ReportVo rep = null; if(coll != null && coll.size() > 0) { for (int i = 0; i < coll.size(); i++) { if(coll.get(i).getSeeds() == null || coll.get(i).getSeeds().size() == 0) { if(rep != null) { engine.showMessage("More than one report assigned to this form."); return; } rep = coll.get(i); } else rep = coll.get(i); } if(rep == null) engine.showMessage("I could not find a suitable report for this form.\n\rPlease go to Admin->Reports and assign a report to this form."); if(rep != null && rep.getTemplatesIsNotNull() && rep.getTemplates().size() > 0) { ReportTemplateVo template = rep.getTemplates().get(0); String[] obj = null; try { obj = domain.getReportAndTemplate(rep.getID_ReportBo(), template.getID_TemplateBo()); } catch (DomainInterfaceException e) { engine.showMessage("Error retrieving report template !\r\n" + e.getMessage()); return; } if(obj == null || obj.length == 0) { engine.showMessage("I could not get the report and template !"); return; } QueryBuilderClient client = new QueryBuilderClient(urlQueryServer, engine.getSessionId()); client.addSeed(new SeedValue("OrderInvestigation_id", form.getLocalContext().getOrderInv().getBoId(), Integer.class)); String resultUrl = ""; try { resultUrl = client.buildReportAsUrl(obj[0], obj[1], urlReportServer, "PDF", "", 1); } catch (QueryBuilderClientException e1) { engine.showMessage("Error creating report: " + e1.getMessage()); return; } engine.openUrl(resultUrl); } } else { engine.showMessage("No report was assigned to this form.\n\rPlease go to Admin->Reports and assign a report to this form."); } */ } @Override protected void onBtnPrintResultClick() throws PresentationLogicException { String urlQueryServer = ConfigFlag.GEN.QUERY_SERVER_URL.getValue(); String urlReportServer = ConfigFlag.GEN.REPORT_SERVER_URL.getValue(); //we need a better way to do this Object[] obj = domain.getSystemReportAndTemplate(new Integer(75)); if(obj == null || obj.length < 2) { engine.showMessage("I could not get the report and template !"); return; } if(obj[0] == null || obj[1] == null) { engine.showMessage("The report has not been deployed !"); return; } QueryBuilderClient client = new QueryBuilderClient(urlQueryServer, engine.getSessionId()); client.addSeed(new SeedValue("OrderInvestigation_id", form.getLocalContext().getOrderInv().getBoId(), Integer.class)); String resultUrl = ""; try { resultUrl = client.buildReportAsUrl((String)obj[0], (String)obj[1], urlReportServer, "PDF", "", 1); } catch (QueryBuilderClientException e1) { engine.showMessage("Error creating report: " + e1.getMessage()); return; } engine.openUrl(resultUrl); } protected void onFormDialogClosed(FormName formName, DialogResult result) throws PresentationLogicException { // WDEV-15894 if(form.getForms().OCRR.OrderInvStatusHistory.equals(formName)) { form.getGlobalContext().OCRR.setCurrentPathRadResult(domain.refreshCurrentPathRadResult(form.getGlobalContext().OCRR.getCurrentPathRadResult())); } form.htmDocument().setHTML(form.getLocalContext().gethtmlString()); open(); // WDEV-13321 } protected void onBtnViewPACSClick() throws PresentationLogicException { form.htmDocument().setHTML("");//WDEV-14843 form.getGlobalContext().OCRR.CentricityWebPACS.setAccessionNumber(domain.getCentricityPacsAccessionNumber(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation())); engine.open(form.getForms().OCRR.CentricityWebPACSViewer,true,true); } protected void onLnkViewPatientDetailsClick() throws PresentationLogicException { if(updateRecord() == false) { return; } form.getGlobalContext().Core.setPatientToBeDisplayed(form.getGlobalContext().Core.getPatientShort()); engine.close(DialogResult.YES); } @Override protected void onChkMarkForReviewValueChanged() throws PresentationLogicException { form.getLocalContext().setPickValue(ResultDisplayHelper.PICK_QRY); if(form.chkMarkForReview().getValue()) { form.imbClose().setEnabled(true); //WDEV-10904,wdev-11989 if(ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) { form.lnkViewPatientDetails().setVisible(true); form.lnkViewPatientDetails().setEnabled(true); } form.btnCumulResult(); setNavigationState(); } else { form.imbClose().setEnabled(false); //WDEV-10904 form.lnkViewPatientDetails().setVisible(false); form.lnkViewPatientDetails().setEnabled(false); disableNavigation(); form.getLocalContext().setPickValue(null); } form.chkEnableExit().setValue(false); form.chkMarkAsSeen().setValue(false); form.chkMarkAsChecked().setValue(false); // WDEV-18052 - Do not default in HCP // WDEV-13321 // Default to responsible HCP clinician // NewResultOcsOrderVo result = domain.getNewResultOcsOrderVo(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation()); // // // WDEV-14097 // // Default to 'Responsible Clinician' only if MEDICAL // if (result.getResponsibleClinicianIsNotNull() && HcpDisType.MEDICAL.equals(result.getResponsibleClinician().getHcpType())) // { // form.ccMedicReview().setValue(result.getResponsibleClinician()); // } // WDEV-13321 updateControlsState(); } /** * WDEV-13321 * Function used to update the state of the controls on screen */ private void updateControlsState() { Integer pickValue = form.getLocalContext().getPickValue(); form.ccMedicReview().setVisible(ResultDisplayHelper.PICK_QRY.equals(pickValue)); form.lblAllocateforReview().setVisible(ResultDisplayHelper.PICK_QRY.equals(pickValue)); } @Override protected void onChkMarkAsSeenValueChanged() throws PresentationLogicException { form.getLocalContext().setPickValue(ResultDisplayHelper.PICK_SEEN); if (form.chkMarkAsSeen().getValue()) { form.imbClose().setEnabled(true); // WDEV-10904,wdev-11989 if (ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) { form.lnkViewPatientDetails().setVisible(true); form.lnkViewPatientDetails().setEnabled(true); } setNavigationState(); } else { form.imbClose().setEnabled(false); // WDEV-10904 form.lnkViewPatientDetails().setVisible(false); form.lnkViewPatientDetails().setEnabled(false); disableNavigation(); } // WDEV-13321 form.ccMedicReview().clear(); form.chkEnableExit().setValue(false); form.chkMarkForReview().setValue(false); updateControlsState(); } @Override protected void onChkMarkAsCheckedValueChanged() throws PresentationLogicException { form.getLocalContext().setPickValue(ResultDisplayHelper.PICK_CHKD); if (form.chkMarkAsChecked().getValue()) { form.imbClose().setEnabled(true); // WDEV-10904,wdev-11989 if (ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) { form.lnkViewPatientDetails().setVisible(true); form.lnkViewPatientDetails().setEnabled(true); } setNavigationState(); } else { form.imbClose().setEnabled(false); // WDEV-10904 form.lnkViewPatientDetails().setVisible(false); form.lnkViewPatientDetails().setEnabled(false); disableNavigation(); } // WDEV-13321 form.ccMedicReview().clear(); form.chkEnableExit().setValue(false); form.chkMarkForReview().setValue(false); updateControlsState(); } @Override protected void onChkEnableExitValueChanged() throws PresentationLogicException { form.getLocalContext().setPickValue(ResultDisplayHelper.PICK_VIEWED); setNavigationState(); if(form.chkEnableExit().getValue()) { form.imbClose().setEnabled(true); //WDEV-10904,wdev-11989 if(ConfigFlag.UI.DISPLAY_RESULT_PATIENT_DETAILS_LINK.getValue()) { form.lnkViewPatientDetails().setVisible(true); form.lnkViewPatientDetails().setEnabled(true); } } else { form.imbClose().setEnabled(false); //WDEV-10904 form.lnkViewPatientDetails().setVisible(false); form.lnkViewPatientDetails().setEnabled(false); disableNavigation(); } // WDEV-13321 form.ccMedicReview().clear(); form.chkMarkAsSeen().setValue(false); form.chkMarkAsChecked().setValue(false); form.chkMarkForReview().setValue(false); updateControlsState(); } /** * WDEV-13320 */ @Override protected void onBtnCommentsClick() throws PresentationLogicException { form.htmDocument().setHTML("");//WDEV-14341 // Open comments dialog engine.open(form.getForms().OCRR.ResultCommentsDialog); } @Override //WDEV-13879 protected void onBtnClericalTaskClick() throws PresentationLogicException { //FB latest changes for WDEV-13879 - 12.01.2012 if (domain.getMosUser() == null)//WDEV-15411 { engine.showMessage("Only MOS users can access this form! Current user is not a MOS user."); return ; } form.htmDocument().setHTML("");//WDEV-14843 form.getGlobalContext().Core.setPatientClericalTask(domain.getPatientClericalTask(form.getGlobalContext().OCRR.getCurrentPathRadResult().getOrderInvestigation())); engine.open(form.getForms().Core.PatientClericalTaskDialog,false); // WDEV-14080 } // WDEV-15894 @Override protected void onDyngrdResultsCellButtonClicked(DynamicGridCell cell) { if(isSTHKModeResultCheck()) { if(cell.getIdentifier().equals(ResultDisplayHelper.BUTTON_CHKD)) { form.getLocalContext().setPickValue(hasMarkResultAsCheckedRoleRight() ? ResultDisplayHelper.PICK_CHKD : ResultDisplayHelper.PICK_VIEWED); close(); } else if(cell.getIdentifier().equals(ResultDisplayHelper.BUTTON_NEXT)) { form.getLocalContext().setPickValue(hasMarkResultAsCheckedRoleRight() ? ResultDisplayHelper.PICK_CHKD : ResultDisplayHelper.PICK_VIEWED); move(true); } else if(cell.getIdentifier().equals(ResultDisplayHelper.BUTTON_PREVIEW)) { form.getLocalContext().setPickValue(hasMarkResultAsCheckedRoleRight() ? ResultDisplayHelper.PICK_CHKD : ResultDisplayHelper.PICK_VIEWED); move(false); } } updateControlsState(); } }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Nursing/src/ims/nursing/domain/ClinicalNoteDialog.java
2611
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.domain; // Generated from form domain impl public interface ClinicalNoteDialog extends ims.domain.DomainInterface { // Generated from form domain interface definition /** * saves a clinical note */ public ims.nursing.vo.NursingClinicalNotesVo saveClinicalNotes(ims.nursing.vo.NursingClinicalNotesVo voNotes) throws ims.domain.exceptions.StaleObjectException; // Generated from form domain interface definition public ims.core.vo.HcpLiteVo getHcpLite(Integer idHcp); }
agpl-3.0
bencaldwell/ua-server-sdk
ua-server/src/main/java/com/digitalpetri/opcua/sdk/core/model/objects/BaseObjectType.java
837
/* * digitalpetri OPC-UA SDK * * Copyright (C) 2015 Kevin Herron * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.digitalpetri.opcua.sdk.core.model.objects; public interface BaseObjectType { }
agpl-3.0