diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/elasticlogger-logback-appender/src/org/hibnet/elasticlogger/ElasticLoggerAppender.java b/elasticlogger-logback-appender/src/org/hibnet/elasticlogger/ElasticLoggerAppender.java
index afc6a5d..0c7b2ae 100644
--- a/elasticlogger-logback-appender/src/org/hibnet/elasticlogger/ElasticLoggerAppender.java
+++ b/elasticlogger-logback-appender/src/org/hibnet/elasticlogger/ElasticLoggerAppender.java
@@ -1,144 +1,148 @@
package org.hibnet.elasticlogger;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import org.elasticsearch.client.Client;
import org.elasticsearch.node.Node;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxyUtil;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
public class ElasticLoggerAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private String clusterName = "elasticsearch";
private String indexName = "elasticlogger";
private String indexType = "log";
private int queueSize = 1000;
private Node node;
private volatile Client client;
private Queue<String> queue;
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public void setIndexType(String indexType) {
this.indexType = indexType;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
}
@Override
public void start() {
queue = new LinkedBlockingQueue<String>(queueSize);
// do make the make the logger (and probably the application too) wait for elasticsearch to boot
new Thread(new Runnable() {
@Override
public void run() {
node = nodeBuilder().client(true).clusterName(clusterName).node();
client = node.client();
// now that the client has started, empty the buffered events
while (!queue.isEmpty()) {
doIndex(queue.poll());
}
// Note : there may be some very edge case where the queue might be still not empty here, but it seems
// very unlikely, and we accept here to lost these events to avoid too much synchronization between the
// threads
}
}, "ElasticloggerAppender node client starter").start();
super.start();
}
@Override
public void stop() {
if (node != null) {
node.close();
}
super.stop();
}
@Override
protected void append(ILoggingEvent event) {
JsonBuilder jsonBuilder = new JsonBuilder();
jsonBuilder.add("level", event.getLevel());
jsonBuilder.add("message", event.getMessage());
jsonBuilder.add("marker", event.getMarker());
jsonBuilder.add("loggerName", event.getLoggerName());
if (event.getMdc() != null) {
for (Entry<String, String> mdcEntry : event.getMdc().entrySet()) {
jsonBuilder.add("mdc_" + mdcEntry.getKey(), mdcEntry.getValue());
}
}
jsonBuilder.add("threadName", event.getThreadName());
jsonBuilder.add("timeStamp", Long.toString(event.getTimeStamp()));
jsonBuilder.add("stackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
String json = jsonBuilder.getResult();
if (client == null) { // the client maybe not be ready yet
- queue.add(json);
+ boolean added = queue.add(json);
+ if (!added) {
+ addError("ElasticLoggerAppender queue is full, too much events while waiting the"
+ + " elasticsearch client to boot. Some events are then lost.");
+ }
} else {
doIndex(json);
}
}
private void doIndex(String json) {
client.prepareIndex(indexName, indexType).setSource(json).execute();
// not that we don't wait for the response, but this is nice, we don't want to have the main thread wait for
// some remote logging indexation
}
private static class JsonBuilder {
private StringBuilder builder = new StringBuilder("{");
private boolean first = true;
private void add(String name, Object value) {
if (value == null) {
return;
}
add(name, value.toString());
}
private void add(String name, String value) {
if (value == null || value.length() == 0) {
return;
}
if (first) {
builder.append('\"');
} else {
builder.append(",\"");
}
first = false;
builder.append(name);
builder.append("\":\"");
builder.append(value.replaceAll("\"", "\\\""));
builder.append('\"');
}
private String getResult() {
builder.append('}');
return builder.toString();
}
}
}
| true | true | protected void append(ILoggingEvent event) {
JsonBuilder jsonBuilder = new JsonBuilder();
jsonBuilder.add("level", event.getLevel());
jsonBuilder.add("message", event.getMessage());
jsonBuilder.add("marker", event.getMarker());
jsonBuilder.add("loggerName", event.getLoggerName());
if (event.getMdc() != null) {
for (Entry<String, String> mdcEntry : event.getMdc().entrySet()) {
jsonBuilder.add("mdc_" + mdcEntry.getKey(), mdcEntry.getValue());
}
}
jsonBuilder.add("threadName", event.getThreadName());
jsonBuilder.add("timeStamp", Long.toString(event.getTimeStamp()));
jsonBuilder.add("stackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
String json = jsonBuilder.getResult();
if (client == null) { // the client maybe not be ready yet
queue.add(json);
} else {
doIndex(json);
}
}
| protected void append(ILoggingEvent event) {
JsonBuilder jsonBuilder = new JsonBuilder();
jsonBuilder.add("level", event.getLevel());
jsonBuilder.add("message", event.getMessage());
jsonBuilder.add("marker", event.getMarker());
jsonBuilder.add("loggerName", event.getLoggerName());
if (event.getMdc() != null) {
for (Entry<String, String> mdcEntry : event.getMdc().entrySet()) {
jsonBuilder.add("mdc_" + mdcEntry.getKey(), mdcEntry.getValue());
}
}
jsonBuilder.add("threadName", event.getThreadName());
jsonBuilder.add("timeStamp", Long.toString(event.getTimeStamp()));
jsonBuilder.add("stackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
String json = jsonBuilder.getResult();
if (client == null) { // the client maybe not be ready yet
boolean added = queue.add(json);
if (!added) {
addError("ElasticLoggerAppender queue is full, too much events while waiting the"
+ " elasticsearch client to boot. Some events are then lost.");
}
} else {
doIndex(json);
}
}
|
diff --git a/src/com/jpii/navalbattle/gui/LoggingInWindow.java b/src/com/jpii/navalbattle/gui/LoggingInWindow.java
index c3678779..879d6bc2 100644
--- a/src/com/jpii/navalbattle/gui/LoggingInWindow.java
+++ b/src/com/jpii/navalbattle/gui/LoggingInWindow.java
@@ -1,77 +1,77 @@
package com.jpii.navalbattle.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import com.jpii.navalbattle.data.Constants;
@SuppressWarnings("serial")
public class LoggingInWindow extends Window {
private Timer timer;
private int currentImage = 0;
private int length = 0;
public LoggingInWindow() {
setUndecorated(true);
getContentPane().setLayout(null);
JProgressBar progressBar = new JProgressBar();
final JLabel label = new JLabel("");
- progressBar.setBounds(0, 297, 485, 14);
- label.setBounds(0, 0, 485, 311);
+ progressBar.setBounds(0, 326, 492, 14);
+ label.setBounds(0, 0, 492, 340);
progressBar.setIndeterminate(true);
getContentPane().add(progressBar);
getContentPane().add(label);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
length += Constants.SPLASH_DURATION;
if (currentImage == 0) {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/roketgamer_title.png")));
}
else if (currentImage == 1) {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/navalbattle_title.png")));
}
else {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/jpii_title.png")));
}
if (currentImage == 2)
currentImage = 0;
else
currentImage++;
if (length > Constants.SPLASH_SCREEN_TIMEOUT)
openMenu();
}
};
timer = new Timer(Constants.SPLASH_DURATION,al);
timer.start();
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
openMenu();
}
});
}
boolean alreadyOpened = false;
public void openMenu() {
if (!alreadyOpened) {
alreadyOpened = true;
new MainMenuWindow().setVisible(true);
setVisible(false);
dispose();
}
}
public void setVisible(boolean visible){
super.setVisible(visible);
}
}
| true | true | public LoggingInWindow() {
setUndecorated(true);
getContentPane().setLayout(null);
JProgressBar progressBar = new JProgressBar();
final JLabel label = new JLabel("");
progressBar.setBounds(0, 297, 485, 14);
label.setBounds(0, 0, 485, 311);
progressBar.setIndeterminate(true);
getContentPane().add(progressBar);
getContentPane().add(label);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
length += Constants.SPLASH_DURATION;
if (currentImage == 0) {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/roketgamer_title.png")));
}
else if (currentImage == 1) {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/navalbattle_title.png")));
}
else {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/jpii_title.png")));
}
if (currentImage == 2)
currentImage = 0;
else
currentImage++;
if (length > Constants.SPLASH_SCREEN_TIMEOUT)
openMenu();
}
};
timer = new Timer(Constants.SPLASH_DURATION,al);
timer.start();
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
openMenu();
}
});
}
| public LoggingInWindow() {
setUndecorated(true);
getContentPane().setLayout(null);
JProgressBar progressBar = new JProgressBar();
final JLabel label = new JLabel("");
progressBar.setBounds(0, 326, 492, 14);
label.setBounds(0, 0, 492, 340);
progressBar.setIndeterminate(true);
getContentPane().add(progressBar);
getContentPane().add(label);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
length += Constants.SPLASH_DURATION;
if (currentImage == 0) {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/roketgamer_title.png")));
}
else if (currentImage == 1) {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/navalbattle_title.png")));
}
else {
label.setIcon(new ImageIcon(LoggingInWindow.class.getResource("/com/jpii/navalbattle/res/jpii_title.png")));
}
if (currentImage == 2)
currentImage = 0;
else
currentImage++;
if (length > Constants.SPLASH_SCREEN_TIMEOUT)
openMenu();
}
};
timer = new Timer(Constants.SPLASH_DURATION,al);
timer.start();
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
openMenu();
}
});
}
|
diff --git a/server-config/src/main/java/org/apache/directory/server/config/beans/MavibotPartitionBean.java b/server-config/src/main/java/org/apache/directory/server/config/beans/MavibotPartitionBean.java
index a3e58b6210..3fa1073c37 100644
--- a/server-config/src/main/java/org/apache/directory/server/config/beans/MavibotPartitionBean.java
+++ b/server-config/src/main/java/org/apache/directory/server/config/beans/MavibotPartitionBean.java
@@ -1,61 +1,61 @@
/*
* 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.directory.server.config.beans;
/**
* A class used to store the MavibotPartition configuration.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class MavibotPartitionBean extends PartitionBean
{
/**
* Create a new JdbmPartitionBean instance
*/
public MavibotPartitionBean()
{
}
/**
* {@inheritDoc}
*/
public String toString( String tabs )
{
StringBuilder sb = new StringBuilder();
- sb.append( tabs ).append( "JdbmPartitionBean :\n" );
+ sb.append( tabs ).append( "MavibotPartitionBean :\n" );
sb.append( super.toString( tabs ) );
return sb.toString();
}
/**
* {@inheritDoc}
*/
public String toString()
{
return toString( "" );
}
}
| true | true | public String toString( String tabs )
{
StringBuilder sb = new StringBuilder();
sb.append( tabs ).append( "JdbmPartitionBean :\n" );
sb.append( super.toString( tabs ) );
return sb.toString();
}
| public String toString( String tabs )
{
StringBuilder sb = new StringBuilder();
sb.append( tabs ).append( "MavibotPartitionBean :\n" );
sb.append( super.toString( tabs ) );
return sb.toString();
}
|
diff --git a/despacho.backend/ejbModule/despacho/backend/servicios/ServicioOrdenesDespachoBean.java b/despacho.backend/ejbModule/despacho/backend/servicios/ServicioOrdenesDespachoBean.java
index e64a5c1..c5a557b 100644
--- a/despacho.backend/ejbModule/despacho/backend/servicios/ServicioOrdenesDespachoBean.java
+++ b/despacho.backend/ejbModule/despacho/backend/servicios/ServicioOrdenesDespachoBean.java
@@ -1,152 +1,151 @@
package despacho.backend.servicios;
import java.util.*;
import javax.ejb.*;
import javax.jws.*;
import ar.edu.uade.integracion.VO.ItemSolicitudArticuloVO;
import ar.edu.uade.integracion.VO.OrdenDespachoVO;
import ar.edu.uade.integracion.VO.SolicitudArticuloVO;
import despacho.backend.administradores.*;
import despacho.backend.entities.*;
import despacho.backend.utils.Configuracion;
import despacho.backend.utils.Logger;
import despacho.backend.utils.MensajeAsincronico;
import despacho.backend.utils.MensajeSincronicoRest;
import despacho.backend.utils.MensajeSincronicoWS;
@Stateless
@WebService(name = Configuracion.IngresoOrdenDespachoServiceName)
public class ServicioOrdenesDespachoBean implements ServicioOrdenesDespacho {
@EJB
private AdministradorOrdenesDespacho administradorOrdenesDespacho;
@EJB
private AdministradorArticulos administradorArticulos;
@Override
@WebMethod
// DCH02. Logistica ingresa nuevas ordenes de despacho
public void ingresarOrdenDespacho(OrdenDespachoVO ordenDespacho) {
try {
if (ordenDespacho == null) {
return;
}
Logger.info("Nueva Orden de despacho: " + ordenDespacho.getCodOrden());
List<SolicitudArticulo> articulos = new ArrayList<SolicitudArticulo>();
// Por cada articulo de la orden, se debe obtener el Deposito que lo administra y solicitarlo asincronicamente
List<ItemSolicitudArticuloVO> articulosOrden = ordenDespacho.getArticulos();
if (articulosOrden != null) {
for (ItemSolicitudArticuloVO articuloOrden : articulosOrden) {
String codigoArticulo = articuloOrden.getIdArticulo();
Articulo articulo = this.administradorArticulos.get(codigoArticulo);
if (articulo == null) {
Logger.error("El articulo con codigo " + codigoArticulo + " no existe.");
break;
}
// Obtengo el deposito asociado al articulo
String nombreDeposito = articulo.getIdDeposito();
// Solicitar articulo
Logger.info("Solicitando articulo " + articulo.getIdArticulo() + " al deposito " + nombreDeposito + "...");
// El id de la solicitud es "{CodigoOrden}-{IdArticulo}"
String idSolicitudArticulo = ordenDespacho.getCodOrden() + "-" + articuloOrden.getIdArticulo();
List<ItemSolicitudArticuloVO> articulosSolicitud = new ArrayList<ItemSolicitudArticuloVO>();
articulosSolicitud.add(articuloOrden);
SolicitudArticuloVO solicitudDeposito = new SolicitudArticuloVO();
solicitudDeposito.setEstado(EstadoSolicitudArticulo.SOLICITADO);
solicitudDeposito.setFecha(new Date());
solicitudDeposito.setIdDespacho(Configuracion.getInstancia().get().get("NombreDespacho"));
solicitudDeposito.setIdSolicitudArticulo(idSolicitudArticulo);
solicitudDeposito.setArticulos(articulosSolicitud);
// Solicitar articulo al deposito
MensajeAsincronico.enviarObjeto(
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Url"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Nombre"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Usuario"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Password"),
solicitudDeposito);
// Guardar la solicitud por Deposito
SolicitudArticulo solicitud = new SolicitudArticulo();
solicitud.setId(idSolicitudArticulo);
solicitud.setEstado(EstadoSolicitudArticulo.SOLICITADO);
solicitud.setCantidad(articuloOrden.getCantSolicitada());
solicitud.setArticulo(articulo);
solicitud.setFecha(solicitudDeposito.getFecha());
solicitud.setCodigoOrden(ordenDespacho.getCodOrden());
- this.administradorArticulos.guardarSolicitud(solicitud);
articulos.add(solicitud);
}
}
// Guardar la orden. Se deben registrar como pendientes de entrega
OrdenDespacho nuevaOrdenDespacho = new OrdenDespacho();
nuevaOrdenDespacho.setEstado(EstadoOrdenDespacho.PENDIENTE_ENTREGA);
nuevaOrdenDespacho.setCodOrden(ordenDespacho.getCodOrden());
nuevaOrdenDespacho.setCodPortal(ordenDespacho.getCodPortal());
nuevaOrdenDespacho.setCodVenta(ordenDespacho.getCodVenta());
nuevaOrdenDespacho.setFecha(new Date());
nuevaOrdenDespacho.setNombreUsuario(ordenDespacho.getNombreUsuario());
nuevaOrdenDespacho.setArticulos(articulos);
this.administradorOrdenesDespacho.agregar(nuevaOrdenDespacho);
Logger.info("Listo (DCH02 - Logistica ingresa nuevas ordenes de despacho)");
}
catch (Exception e) {
e.printStackTrace();
Logger.error(e.getMessage());
}
}
@Override
// DCH04. Env�o Cambio de Estado de Despacho (Entrega)
public void completarOrdenDespacho(String codigo) {
// TODO: Quien llama a este metodo?
Logger.info("Completar Orden de Despacho: " + codigo);
OrdenDespacho orden = this.administradorOrdenesDespacho.get(codigo);
if (orden == null) {
Logger.error("La orden de despacho con codigo " + codigo + " no existe.");
return;
}
// Informar a los portales que todos los articulos de una Orden de Despacho est�n listos para Entrega
for (String nombrePortal: Configuracion.getInstancia().getPortales()) {
Logger.info("Informando al portal " + nombrePortal + " que la orden de despacho fue completada...");
MensajeSincronicoWS.informarOrdenListaEntrega(null, nombrePortal); // TODO: ver que objeto enviar
}
// Informar en comunicaci�n sincr�nica (REST) al m�dulo Log�stica
Logger.info("Informando a Logistica que la orden de despacho fue completada...");
try {
MensajeSincronicoRest.post(
Configuracion.getInstancia().get().get("Logistica-OrdenDespachoListaRest-Url"),
null); // TODO: ver que objeto enviar
} catch (Exception e) {
e.printStackTrace();
Logger.error(e.getMessage());
}
// El sistema debe registrar y cambiar de estado a la Orden de Despacho y marcarla como entregada
orden.setEstado(EstadoOrdenDespacho.ENTREGADA);
this.administradorOrdenesDespacho.actualizar(orden);
Logger.info("Listo (DCH04)!");
}
}
| true | true | public void ingresarOrdenDespacho(OrdenDespachoVO ordenDespacho) {
try {
if (ordenDespacho == null) {
return;
}
Logger.info("Nueva Orden de despacho: " + ordenDespacho.getCodOrden());
List<SolicitudArticulo> articulos = new ArrayList<SolicitudArticulo>();
// Por cada articulo de la orden, se debe obtener el Deposito que lo administra y solicitarlo asincronicamente
List<ItemSolicitudArticuloVO> articulosOrden = ordenDespacho.getArticulos();
if (articulosOrden != null) {
for (ItemSolicitudArticuloVO articuloOrden : articulosOrden) {
String codigoArticulo = articuloOrden.getIdArticulo();
Articulo articulo = this.administradorArticulos.get(codigoArticulo);
if (articulo == null) {
Logger.error("El articulo con codigo " + codigoArticulo + " no existe.");
break;
}
// Obtengo el deposito asociado al articulo
String nombreDeposito = articulo.getIdDeposito();
// Solicitar articulo
Logger.info("Solicitando articulo " + articulo.getIdArticulo() + " al deposito " + nombreDeposito + "...");
// El id de la solicitud es "{CodigoOrden}-{IdArticulo}"
String idSolicitudArticulo = ordenDespacho.getCodOrden() + "-" + articuloOrden.getIdArticulo();
List<ItemSolicitudArticuloVO> articulosSolicitud = new ArrayList<ItemSolicitudArticuloVO>();
articulosSolicitud.add(articuloOrden);
SolicitudArticuloVO solicitudDeposito = new SolicitudArticuloVO();
solicitudDeposito.setEstado(EstadoSolicitudArticulo.SOLICITADO);
solicitudDeposito.setFecha(new Date());
solicitudDeposito.setIdDespacho(Configuracion.getInstancia().get().get("NombreDespacho"));
solicitudDeposito.setIdSolicitudArticulo(idSolicitudArticulo);
solicitudDeposito.setArticulos(articulosSolicitud);
// Solicitar articulo al deposito
MensajeAsincronico.enviarObjeto(
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Url"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Nombre"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Usuario"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Password"),
solicitudDeposito);
// Guardar la solicitud por Deposito
SolicitudArticulo solicitud = new SolicitudArticulo();
solicitud.setId(idSolicitudArticulo);
solicitud.setEstado(EstadoSolicitudArticulo.SOLICITADO);
solicitud.setCantidad(articuloOrden.getCantSolicitada());
solicitud.setArticulo(articulo);
solicitud.setFecha(solicitudDeposito.getFecha());
solicitud.setCodigoOrden(ordenDespacho.getCodOrden());
this.administradorArticulos.guardarSolicitud(solicitud);
articulos.add(solicitud);
}
}
// Guardar la orden. Se deben registrar como pendientes de entrega
OrdenDespacho nuevaOrdenDespacho = new OrdenDespacho();
nuevaOrdenDespacho.setEstado(EstadoOrdenDespacho.PENDIENTE_ENTREGA);
nuevaOrdenDespacho.setCodOrden(ordenDespacho.getCodOrden());
nuevaOrdenDespacho.setCodPortal(ordenDespacho.getCodPortal());
nuevaOrdenDespacho.setCodVenta(ordenDespacho.getCodVenta());
nuevaOrdenDespacho.setFecha(new Date());
nuevaOrdenDespacho.setNombreUsuario(ordenDespacho.getNombreUsuario());
nuevaOrdenDespacho.setArticulos(articulos);
this.administradorOrdenesDespacho.agregar(nuevaOrdenDespacho);
Logger.info("Listo (DCH02 - Logistica ingresa nuevas ordenes de despacho)");
}
catch (Exception e) {
e.printStackTrace();
Logger.error(e.getMessage());
}
}
| public void ingresarOrdenDespacho(OrdenDespachoVO ordenDespacho) {
try {
if (ordenDespacho == null) {
return;
}
Logger.info("Nueva Orden de despacho: " + ordenDespacho.getCodOrden());
List<SolicitudArticulo> articulos = new ArrayList<SolicitudArticulo>();
// Por cada articulo de la orden, se debe obtener el Deposito que lo administra y solicitarlo asincronicamente
List<ItemSolicitudArticuloVO> articulosOrden = ordenDespacho.getArticulos();
if (articulosOrden != null) {
for (ItemSolicitudArticuloVO articuloOrden : articulosOrden) {
String codigoArticulo = articuloOrden.getIdArticulo();
Articulo articulo = this.administradorArticulos.get(codigoArticulo);
if (articulo == null) {
Logger.error("El articulo con codigo " + codigoArticulo + " no existe.");
break;
}
// Obtengo el deposito asociado al articulo
String nombreDeposito = articulo.getIdDeposito();
// Solicitar articulo
Logger.info("Solicitando articulo " + articulo.getIdArticulo() + " al deposito " + nombreDeposito + "...");
// El id de la solicitud es "{CodigoOrden}-{IdArticulo}"
String idSolicitudArticulo = ordenDespacho.getCodOrden() + "-" + articuloOrden.getIdArticulo();
List<ItemSolicitudArticuloVO> articulosSolicitud = new ArrayList<ItemSolicitudArticuloVO>();
articulosSolicitud.add(articuloOrden);
SolicitudArticuloVO solicitudDeposito = new SolicitudArticuloVO();
solicitudDeposito.setEstado(EstadoSolicitudArticulo.SOLICITADO);
solicitudDeposito.setFecha(new Date());
solicitudDeposito.setIdDespacho(Configuracion.getInstancia().get().get("NombreDespacho"));
solicitudDeposito.setIdSolicitudArticulo(idSolicitudArticulo);
solicitudDeposito.setArticulos(articulosSolicitud);
// Solicitar articulo al deposito
MensajeAsincronico.enviarObjeto(
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Url"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Nombre"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Usuario"),
Configuracion.getInstancia().get().get(nombreDeposito + "-SolicitarArticuloQueue-Password"),
solicitudDeposito);
// Guardar la solicitud por Deposito
SolicitudArticulo solicitud = new SolicitudArticulo();
solicitud.setId(idSolicitudArticulo);
solicitud.setEstado(EstadoSolicitudArticulo.SOLICITADO);
solicitud.setCantidad(articuloOrden.getCantSolicitada());
solicitud.setArticulo(articulo);
solicitud.setFecha(solicitudDeposito.getFecha());
solicitud.setCodigoOrden(ordenDespacho.getCodOrden());
articulos.add(solicitud);
}
}
// Guardar la orden. Se deben registrar como pendientes de entrega
OrdenDespacho nuevaOrdenDespacho = new OrdenDespacho();
nuevaOrdenDespacho.setEstado(EstadoOrdenDespacho.PENDIENTE_ENTREGA);
nuevaOrdenDespacho.setCodOrden(ordenDespacho.getCodOrden());
nuevaOrdenDespacho.setCodPortal(ordenDespacho.getCodPortal());
nuevaOrdenDespacho.setCodVenta(ordenDespacho.getCodVenta());
nuevaOrdenDespacho.setFecha(new Date());
nuevaOrdenDespacho.setNombreUsuario(ordenDespacho.getNombreUsuario());
nuevaOrdenDespacho.setArticulos(articulos);
this.administradorOrdenesDespacho.agregar(nuevaOrdenDespacho);
Logger.info("Listo (DCH02 - Logistica ingresa nuevas ordenes de despacho)");
}
catch (Exception e) {
e.printStackTrace();
Logger.error(e.getMessage());
}
}
|
diff --git a/src/uk/org/catnip/eddie/parser/State.java b/src/uk/org/catnip/eddie/parser/State.java
index 0d3d341..1b33f77 100644
--- a/src/uk/org/catnip/eddie/parser/State.java
+++ b/src/uk/org/catnip/eddie/parser/State.java
@@ -1,400 +1,400 @@
/*
* Eddie RSS and Atom feed parser
* Copyright (C) 2006 David Pashley
*
* 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.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Linking this library statically or dynamically with other modules is making a
* combined work based on this library. Thus, the terms and conditions of the GNU
* General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and
* to copy and distribute the resulting executable under a liense certified by the
* Open Source Initative (http://www.opensource.org), provided that you also meet,
* for each linked independent module, the terms and conditions of the license of
* that module. An independent module is a module which is not derived from or
* based on this library. If you modify this library, you may extend this
* exception to your version of the library, but you are not obligated to do so.
* If you do not wish to do so, delete this exception statement from your version.
*/
package uk.org.catnip.eddie.parser;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.AttributesImpl;
import java.lang.StringBuilder;
import java.util.Map;
import java.util.Hashtable;
import org.apache.log4j.Logger;
import java.net.URI;
import java.net.URISyntaxException;
public class State {
private static Map<String,String> element_aliases = createElementAliases();
static Logger log = Logger.getLogger(State.class);
private static Map<String,String> namespace_aliases = createNamespaceAliases();
private static Map<String,String> createElementAliases() {
Map<String,String> aliases = new Hashtable<String,String>();
aliases.put("abstract", "description");
aliases.put("body", "content");
aliases.put("content:encoded", "content_encoded");
aliases.put("dcterms:created", "created");
aliases.put("dc:author", "author");
aliases.put("dc:creator", "author");
aliases.put("dc:contributor", "contributor");
aliases.put("dc:date", "modified");
aliases.put("dc:language", "language");
aliases.put("dc:publisher", "publisher");
aliases.put("dc:rights", "copyright");
aliases.put("dc:subject", "category");
aliases.put("dc:title", "title");
aliases.put("dcterms:modified", "modified");
aliases.put("item", "entry");
aliases.put("itunes:author", "author");
aliases.put("itunes:block", "itunes_block");
aliases.put("itunes:category", "itunes_category");
aliases.put("itunes:duration", "itunes_duration");
aliases.put("itunes:email", "email");
aliases.put("itunes:explicit", "itunes_explicit");
aliases.put("itunes:image", "image");
aliases.put("itunes:keywords", "itunes_keywords");
aliases.put("itunes:link", "link");
aliases.put("itunes:owner", "publisher");
aliases.put("itunes:name", "name");
aliases.put("itunes:subtitle", "subtitle");
aliases.put("itunes:summary", "description");
aliases.put("feedinfo", "channel");
aliases.put("fullitem", "content_encoded");
aliases.put("homepage", "url");
aliases.put("keywords", "category");
aliases.put("dcterms:issued", "issued");
aliases.put("managingeditor", "author");
aliases.put("product", "item");
aliases.put("producturl", "link");
aliases.put("pubdate", "modified");
aliases.put("published", "dcterms_created");
aliases.put("rights", "copyright");
aliases.put("tagline", "subtitle");
aliases.put("uri", "url");
aliases.put("webmaster", "publisher");
aliases.put("wfw:comment", "wfw_comment");
aliases.put("wfw:commentrss", "wfw_commentrss");
aliases.put("xhtml_body", "body");
aliases.put("updated", "modified");
return aliases;
}
private static Map<String,String> createNamespaceAliases() {
Map<String,String> aliases = new Hashtable<String,String>();
// aliases.put("http://backend.userland.com/rss", "");
// aliases.put("http://blogs.law.harvard.edu/tech/rss", "");
// aliases.put("http://purl.org/rss/1.0/", "");
// aliases.put("http://my.netscape.com/rdf/simple/0.9/", "");
// aliases.put("http://example.com/newformat#", "");
// aliases.put("http://example.com/necho", "");
// aliases.put("http://purl.org/echo/", "");
// aliases.put("uri/of/echo/namespace#", "");
// aliases.put("http://purl.org/pie/", "");
// aliases.put("http://purl.org/atom/ns#", "");
// aliases.put("http://purl.org/rss/1.0/modules/rss091#", "");
aliases.put("http://webns.net/mvcb/", "admin");
aliases.put("http://purl.org/rss/1.0/modules/aggregation/", "ag");
aliases.put("http://purl.org/rss/1.0/modules/annotate/", "annotate");
aliases.put("http://media.tangent.org/rss/1.0/", "audio");
aliases.put("http://backend.userland.com/blogChannelModule",
"blogChannel");
aliases.put("http://web.resource.org/cc/", "cc");
aliases.put("http://backend.userland.com/creativeCommonsRssModule",
"creativeCommons");
aliases.put("http://purl.org/rss/1.0/modules/company", "co");
aliases.put("http://purl.org/rss/1.0/modules/content/", "content");
aliases.put("http://my.theinfo.org/changed/1.0/rss/", "cp");
aliases.put("http://purl.org/dc/elements/1.1/", "dc");
aliases.put("http://purl.org/dc/terms/", "dcterms");
aliases.put("http://purl.org/rss/1.0/modules/email/", "email");
aliases.put("http://purl.org/rss/1.0/modules/event/", "ev");
aliases.put("http://postneo.com/icbm/", "icbm");
aliases.put("http://purl.org/rss/1.0/modules/image/", "image");
aliases.put("http://xmlns.com/foaf/0.1/", "foaf");
aliases.put("http://freshmeat.net/rss/fm/", "fm");
aliases.put("http://www.itunes.com/dtds/podcast-1.0.dtd", "itunes");
aliases.put("http://example.com/dtds/podcast-1.0.dtd", "itunes");
aliases.put("http://purl.org/rss/1.0/modules/link/", "l");
aliases.put("http://madskills.com/public/xml/rss/module/pingback/",
"pingback");
aliases.put("http://prismstandard.org/namespaces/1.2/basic/", "prism");
aliases.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf");
aliases.put("http://www.w3.org/2000/01/rdf-schema#", "rdfs");
aliases.put("http://purl.org/rss/1.0/modules/reference/", "ref");
aliases.put("http://purl.org/rss/1.0/modules/richequiv/", "reqv");
aliases.put("http://purl.org/rss/1.0/modules/search/", "search");
aliases.put("http://purl.org/rss/1.0/modules/slash/", "slash");
aliases.put("http://purl.org/rss/1.0/modules/servicestatus/", "ss");
aliases.put("http://hacks.benhammersley.com/rss/streaming/", "str");
aliases.put("http://purl.org/rss/1.0/modules/subscription/", "sub");
aliases.put("http://purl.org/rss/1.0/modules/syndication/", "sy");
aliases.put("http://purl.org/rss/1.0/modules/taxonomy/", "taxo");
aliases.put("http://purl.org/rss/1.0/modules/threading/", "thr");
aliases.put("http://purl.org/rss/1.0/modules/textinput/", "ti");
aliases.put("http://madskills.com/public/xml/rss/module/trackback/",
"trackback");
- aliases.put("http://wellformedweb.org/CommentAPI/", "wfw");
+ aliases.put("http://wellformedweb.org/commentapi/", "wfw");
aliases.put("http://purl.org/rss/1.0/modules/wiki/", "wiki");
aliases.put("http://schemas.xmlsoap.org/soap/envelope/", "soap");
aliases.put("http://www.w3.org/1999/xhtml", "xhtml");
aliases.put("http://www.w3.org/XML/1998/namespace", "xml");
return aliases;
}
private Attributes atts = new AttributesImpl();
private URI base;
public boolean content = false;
private String element;
private boolean expectingText = false;
private String language;
private String localName;
private String mode;
private String namespace;
private String qName;
private StringBuilder text = new StringBuilder();
private String type;
private String uri;
public State() {
}
public State(String uri, String localName, String qName) {
this.uri = uri;
this.localName = localName.toLowerCase();
if (namespace_aliases.containsKey(this.uri.toLowerCase())) {
this.namespace = (String) namespace_aliases.get(this.uri.toLowerCase());
}
this.element = aliasElement(this.namespace, this.localName);
this.qName = qName;
}
public State(String uri, String localName, String qName, Attributes atts,
State prev) {
this.uri = uri;
this.localName = localName.toLowerCase();
this.qName = qName;
this.atts = atts;
if (namespace_aliases.containsKey(this.uri.toLowerCase())) {
this.namespace = (String) namespace_aliases.get(this.uri.toLowerCase());
}
this.element = aliasElement(this.namespace, this.localName);
this.type = this.getAttr("type", prev.type);
this.mode = this.getAttr("mode", prev.mode);
if (this.type == null || this.type.equals("")) {
this.type = "text/plain";
}
this.language = this.getAttr("xml:lang", prev.getLanguage());
this.setBase(this.getAttr("xml:base", prev.getBase()));
if (this.isBaseRelative()) {
this.resolveBaseWith(prev.getBase());
}
// log.debug(this);
}
public void addText(String str) {
text.append(str);
}
private String aliasElement(String namespace, String element) {
if (namespace != null && !namespace.equals("xhtml")) {
element = namespace + ":" + element;
}
if (element_aliases.containsKey(element)) {
return (String) element_aliases.get(element);
}
return element;
}
public String getAttr(String key) {
return this.getAttr(key, null);
}
public String getAttr(String key, String default_value) {
// TODO: remove this hack
if (key.equals("type") && namespace != null
&& namespace.equals("xhtml")) {
return "application/xhtml+xml";
}
String ret = atts.getValue(key);
if (ret == null) {
ret = default_value;
}
log.trace("getAttr: " + key + " = '" + ret + "'");
return ret;
}
public String getBase() {
if (base != null) {
return base.toString();
} else {
return null;
}
}
public String getElement() {
return element;
}
public String getLanguage() {
return language;
}
public String getText() {
return text.toString();
}
public String getType() {
return type;
}
public String getUri() {
return uri;
}
public String resolveUri(String uri) {
if (base == null) {
return uri;
}
if (uri == null) {
return uri;
}
return base.resolve(uri).toString();
}
public boolean isBaseRelative() {
if (this.base == null) { return false; }
return !this.base.isAbsolute();
}
public void resolveBaseWith(String uri) {
try {
if (this.base != null && uri != null) {
URI real_base = new URI(uri);
this.base = real_base.resolve(this.base);
}
} catch (Exception e){
log.warn("exception", e);
}
}
public void setBase(String base) {
if (base != null) {
base = base.replaceAll("^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)", "$1$3");
try {
if (this.base != null) {
this.base = this.base.resolve(base);
} else {
this.base = new URI(base);
}
} catch (URISyntaxException e) {
log.warn(e);
try {
this.base = new URI("");
} catch (URISyntaxException ex) {
log.warn(ex);
}
}
}
}
public void setElement(String element) {
this.element = element;
}
public void setLanguage(String language) {
this.language = language;
}
public void setType(String type) {
if (type.equals("text")) {
this.type = "text/plain";
} else if (type.equals("html")) {
this.type = "text/html";
} else if (type.equals("xhtml")) {
this.type = "application/xhtml+xml";
} else {
this.type = type;
}
}
public void setUri(String uri) {
this.uri = uri;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("element = '" + element + "', ");
sb.append("mode = '" + mode + "', ");
sb.append("type = '" + type + "', ");
sb.append("base = '" + base + "', ");
sb.append("language = '" + language + "', ");
sb.append("namespace = '" + namespace + "', ");
sb.append("uri = '" + uri + "', ");
sb.append("qname = '" + qName + "', ");
sb.append("localname = '" + localName + "', ");
sb.append("text = '" + text + "'");
sb.append("}");
return sb.toString();
}
public boolean isExpectingText() {
return expectingText;
}
public void setExpectingText(boolean expectingText) {
this.expectingText = expectingText;
}
public Attributes getAttributes() {
return atts;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
}
| true | true | private static Map<String,String> createNamespaceAliases() {
Map<String,String> aliases = new Hashtable<String,String>();
// aliases.put("http://backend.userland.com/rss", "");
// aliases.put("http://blogs.law.harvard.edu/tech/rss", "");
// aliases.put("http://purl.org/rss/1.0/", "");
// aliases.put("http://my.netscape.com/rdf/simple/0.9/", "");
// aliases.put("http://example.com/newformat#", "");
// aliases.put("http://example.com/necho", "");
// aliases.put("http://purl.org/echo/", "");
// aliases.put("uri/of/echo/namespace#", "");
// aliases.put("http://purl.org/pie/", "");
// aliases.put("http://purl.org/atom/ns#", "");
// aliases.put("http://purl.org/rss/1.0/modules/rss091#", "");
aliases.put("http://webns.net/mvcb/", "admin");
aliases.put("http://purl.org/rss/1.0/modules/aggregation/", "ag");
aliases.put("http://purl.org/rss/1.0/modules/annotate/", "annotate");
aliases.put("http://media.tangent.org/rss/1.0/", "audio");
aliases.put("http://backend.userland.com/blogChannelModule",
"blogChannel");
aliases.put("http://web.resource.org/cc/", "cc");
aliases.put("http://backend.userland.com/creativeCommonsRssModule",
"creativeCommons");
aliases.put("http://purl.org/rss/1.0/modules/company", "co");
aliases.put("http://purl.org/rss/1.0/modules/content/", "content");
aliases.put("http://my.theinfo.org/changed/1.0/rss/", "cp");
aliases.put("http://purl.org/dc/elements/1.1/", "dc");
aliases.put("http://purl.org/dc/terms/", "dcterms");
aliases.put("http://purl.org/rss/1.0/modules/email/", "email");
aliases.put("http://purl.org/rss/1.0/modules/event/", "ev");
aliases.put("http://postneo.com/icbm/", "icbm");
aliases.put("http://purl.org/rss/1.0/modules/image/", "image");
aliases.put("http://xmlns.com/foaf/0.1/", "foaf");
aliases.put("http://freshmeat.net/rss/fm/", "fm");
aliases.put("http://www.itunes.com/dtds/podcast-1.0.dtd", "itunes");
aliases.put("http://example.com/dtds/podcast-1.0.dtd", "itunes");
aliases.put("http://purl.org/rss/1.0/modules/link/", "l");
aliases.put("http://madskills.com/public/xml/rss/module/pingback/",
"pingback");
aliases.put("http://prismstandard.org/namespaces/1.2/basic/", "prism");
aliases.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf");
aliases.put("http://www.w3.org/2000/01/rdf-schema#", "rdfs");
aliases.put("http://purl.org/rss/1.0/modules/reference/", "ref");
aliases.put("http://purl.org/rss/1.0/modules/richequiv/", "reqv");
aliases.put("http://purl.org/rss/1.0/modules/search/", "search");
aliases.put("http://purl.org/rss/1.0/modules/slash/", "slash");
aliases.put("http://purl.org/rss/1.0/modules/servicestatus/", "ss");
aliases.put("http://hacks.benhammersley.com/rss/streaming/", "str");
aliases.put("http://purl.org/rss/1.0/modules/subscription/", "sub");
aliases.put("http://purl.org/rss/1.0/modules/syndication/", "sy");
aliases.put("http://purl.org/rss/1.0/modules/taxonomy/", "taxo");
aliases.put("http://purl.org/rss/1.0/modules/threading/", "thr");
aliases.put("http://purl.org/rss/1.0/modules/textinput/", "ti");
aliases.put("http://madskills.com/public/xml/rss/module/trackback/",
"trackback");
aliases.put("http://wellformedweb.org/CommentAPI/", "wfw");
aliases.put("http://purl.org/rss/1.0/modules/wiki/", "wiki");
aliases.put("http://schemas.xmlsoap.org/soap/envelope/", "soap");
aliases.put("http://www.w3.org/1999/xhtml", "xhtml");
aliases.put("http://www.w3.org/XML/1998/namespace", "xml");
return aliases;
}
| private static Map<String,String> createNamespaceAliases() {
Map<String,String> aliases = new Hashtable<String,String>();
// aliases.put("http://backend.userland.com/rss", "");
// aliases.put("http://blogs.law.harvard.edu/tech/rss", "");
// aliases.put("http://purl.org/rss/1.0/", "");
// aliases.put("http://my.netscape.com/rdf/simple/0.9/", "");
// aliases.put("http://example.com/newformat#", "");
// aliases.put("http://example.com/necho", "");
// aliases.put("http://purl.org/echo/", "");
// aliases.put("uri/of/echo/namespace#", "");
// aliases.put("http://purl.org/pie/", "");
// aliases.put("http://purl.org/atom/ns#", "");
// aliases.put("http://purl.org/rss/1.0/modules/rss091#", "");
aliases.put("http://webns.net/mvcb/", "admin");
aliases.put("http://purl.org/rss/1.0/modules/aggregation/", "ag");
aliases.put("http://purl.org/rss/1.0/modules/annotate/", "annotate");
aliases.put("http://media.tangent.org/rss/1.0/", "audio");
aliases.put("http://backend.userland.com/blogChannelModule",
"blogChannel");
aliases.put("http://web.resource.org/cc/", "cc");
aliases.put("http://backend.userland.com/creativeCommonsRssModule",
"creativeCommons");
aliases.put("http://purl.org/rss/1.0/modules/company", "co");
aliases.put("http://purl.org/rss/1.0/modules/content/", "content");
aliases.put("http://my.theinfo.org/changed/1.0/rss/", "cp");
aliases.put("http://purl.org/dc/elements/1.1/", "dc");
aliases.put("http://purl.org/dc/terms/", "dcterms");
aliases.put("http://purl.org/rss/1.0/modules/email/", "email");
aliases.put("http://purl.org/rss/1.0/modules/event/", "ev");
aliases.put("http://postneo.com/icbm/", "icbm");
aliases.put("http://purl.org/rss/1.0/modules/image/", "image");
aliases.put("http://xmlns.com/foaf/0.1/", "foaf");
aliases.put("http://freshmeat.net/rss/fm/", "fm");
aliases.put("http://www.itunes.com/dtds/podcast-1.0.dtd", "itunes");
aliases.put("http://example.com/dtds/podcast-1.0.dtd", "itunes");
aliases.put("http://purl.org/rss/1.0/modules/link/", "l");
aliases.put("http://madskills.com/public/xml/rss/module/pingback/",
"pingback");
aliases.put("http://prismstandard.org/namespaces/1.2/basic/", "prism");
aliases.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf");
aliases.put("http://www.w3.org/2000/01/rdf-schema#", "rdfs");
aliases.put("http://purl.org/rss/1.0/modules/reference/", "ref");
aliases.put("http://purl.org/rss/1.0/modules/richequiv/", "reqv");
aliases.put("http://purl.org/rss/1.0/modules/search/", "search");
aliases.put("http://purl.org/rss/1.0/modules/slash/", "slash");
aliases.put("http://purl.org/rss/1.0/modules/servicestatus/", "ss");
aliases.put("http://hacks.benhammersley.com/rss/streaming/", "str");
aliases.put("http://purl.org/rss/1.0/modules/subscription/", "sub");
aliases.put("http://purl.org/rss/1.0/modules/syndication/", "sy");
aliases.put("http://purl.org/rss/1.0/modules/taxonomy/", "taxo");
aliases.put("http://purl.org/rss/1.0/modules/threading/", "thr");
aliases.put("http://purl.org/rss/1.0/modules/textinput/", "ti");
aliases.put("http://madskills.com/public/xml/rss/module/trackback/",
"trackback");
aliases.put("http://wellformedweb.org/commentapi/", "wfw");
aliases.put("http://purl.org/rss/1.0/modules/wiki/", "wiki");
aliases.put("http://schemas.xmlsoap.org/soap/envelope/", "soap");
aliases.put("http://www.w3.org/1999/xhtml", "xhtml");
aliases.put("http://www.w3.org/XML/1998/namespace", "xml");
return aliases;
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandWarp.java b/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandWarp.java
index 459ad64fb..1997a641a 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandWarp.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandWarp.java
@@ -1,180 +1,177 @@
package com.ForgeEssentials.commands;
import java.util.List;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.tileentity.TileEntityCommandBlock;
import com.ForgeEssentials.api.permissions.IPermRegisterEvent;
import com.ForgeEssentials.api.permissions.PermissionsAPI;
import com.ForgeEssentials.api.permissions.RegGroup;
import com.ForgeEssentials.api.permissions.query.PermQueryPlayer;
import com.ForgeEssentials.commands.util.CommandDataManager;
import com.ForgeEssentials.commands.util.FEcmdModuleCommands;
import com.ForgeEssentials.commands.util.Warp;
import com.ForgeEssentials.core.PlayerInfo;
import com.ForgeEssentials.util.FunctionHelper;
import com.ForgeEssentials.util.Localization;
import com.ForgeEssentials.util.OutputHandler;
import com.ForgeEssentials.util.TeleportCenter;
import com.ForgeEssentials.util.AreaSelector.WarpPoint;
/**
* Now uses TeleportCenter.
* @author Dries007
*/
public class CommandWarp extends FEcmdModuleCommands
{
@Override
public String getCommandName()
{
return "warp";
}
@Override
public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 0)
{
String msg = "";
for (String warp : CommandDataManager.warps.keySet())
{
- if (PermissionsAPI.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + "." + args[0].toLowerCase())))
- {
- msg = warp + ", " + msg;
- }
+ msg = warp + ", " + msg;
}
sender.sendChatToPlayer(msg);
}
else if (args.length == 1)
{
if (CommandDataManager.warps.containsKey(args[0].toLowerCase()))
{
if (PermissionsAPI.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + "." + args[0].toLowerCase())))
{
Warp warp = CommandDataManager.warps.get(args[0].toLowerCase());
PlayerInfo playerInfo = PlayerInfo.getPlayerInfo(sender.username);
playerInfo.back = new WarpPoint(sender);
TeleportCenter.addToTpQue(warp.getPoint(), sender);
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_PERMDENIED));
}
}
else
{
OutputHandler.chatError(sender, Localization.get("command.warp.notfound"));
}
}
else if (args.length == 2)
{
if (PermissionsAPI.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + ".admin")))
{
if (args[0].equalsIgnoreCase("set"))
{
if (CommandDataManager.warps.containsKey(args[1].toLowerCase()))
{
OutputHandler.chatError(sender, Localization.get("command.warp.alreadyexists"));
}
else
{
CommandDataManager.addWarp(new Warp(args[1].toLowerCase(), new WarpPoint(sender)));
OutputHandler.chatConfirmation(sender, Localization.get(Localization.DONE));
}
}
else if (args[0].equalsIgnoreCase("del"))
{
if (CommandDataManager.warps.containsKey(args[1].toLowerCase()))
{
CommandDataManager.removeWarp(CommandDataManager.warps.get(args[1]));
OutputHandler.chatConfirmation(sender, Localization.get(Localization.DONE));
}
else
{
OutputHandler.chatError(sender, Localization.get("command.warp.notfound"));
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxPlayer(sender));
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_PERMDENIED));
}
}
}
@Override
public void processCommandConsole(ICommandSender sender, String[] args)
{
if (args.length == 2)
{
if (CommandDataManager.warps.containsKey(args[1].toLowerCase()))
{
EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]);
if (player != null)
{
Warp warp = CommandDataManager.warps.get(args[1].toLowerCase());
PlayerInfo.getPlayerInfo(player.username).back = new WarpPoint(player);
TeleportCenter.addToTpQue(warp.getPoint(), player);
}
else
{
OutputHandler.chatError(sender, Localization.format(Localization.ERROR_NOPLAYER, args[0]));
}
}
else
{
OutputHandler.info("CommandBlock Error: " + Localization.get("command.warp.notfound"));
}
}
}
@Override
public boolean canConsoleUseCommand()
{
return false;
}
@Override
public boolean canCommandBlockUseCommand(TileEntityCommandBlock te)
{
return true;
}
@Override
public void registerExtraPermissions(IPermRegisterEvent event)
{
event.registerPermissionLevel(getCommandPerm() + ".admin", RegGroup.OWNERS);
}
@Override
public String getCommandPerm()
{
return "ForgeEssentials.BasicCommands." + getCommandName();
}
@Override
public List<?> addTabCompletionOptions(ICommandSender sender, String[] args)
{
if (args.length == 1)
return getListOfStringsFromIterableMatchingLastWord(args, CommandDataManager.warps.keySet());
else if (args.length == 2)
return getListOfStringsMatchingLastWord(args, "set", "del");
else
return null;
}
@Override
public RegGroup getReggroup()
{
return RegGroup.OWNERS;
}
}
| true | true | public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 0)
{
String msg = "";
for (String warp : CommandDataManager.warps.keySet())
{
if (PermissionsAPI.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + "." + args[0].toLowerCase())))
{
msg = warp + ", " + msg;
}
}
sender.sendChatToPlayer(msg);
}
else if (args.length == 1)
{
if (CommandDataManager.warps.containsKey(args[0].toLowerCase()))
{
if (PermissionsAPI.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + "." + args[0].toLowerCase())))
{
Warp warp = CommandDataManager.warps.get(args[0].toLowerCase());
PlayerInfo playerInfo = PlayerInfo.getPlayerInfo(sender.username);
playerInfo.back = new WarpPoint(sender);
TeleportCenter.addToTpQue(warp.getPoint(), sender);
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_PERMDENIED));
}
}
else
{
OutputHandler.chatError(sender, Localization.get("command.warp.notfound"));
}
}
else if (args.length == 2)
{
if (PermissionsAPI.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + ".admin")))
{
if (args[0].equalsIgnoreCase("set"))
{
if (CommandDataManager.warps.containsKey(args[1].toLowerCase()))
{
OutputHandler.chatError(sender, Localization.get("command.warp.alreadyexists"));
}
else
{
CommandDataManager.addWarp(new Warp(args[1].toLowerCase(), new WarpPoint(sender)));
OutputHandler.chatConfirmation(sender, Localization.get(Localization.DONE));
}
}
else if (args[0].equalsIgnoreCase("del"))
{
if (CommandDataManager.warps.containsKey(args[1].toLowerCase()))
{
CommandDataManager.removeWarp(CommandDataManager.warps.get(args[1]));
OutputHandler.chatConfirmation(sender, Localization.get(Localization.DONE));
}
else
{
OutputHandler.chatError(sender, Localization.get("command.warp.notfound"));
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxPlayer(sender));
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_PERMDENIED));
}
}
}
| public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 0)
{
String msg = "";
for (String warp : CommandDataManager.warps.keySet())
{
msg = warp + ", " + msg;
}
sender.sendChatToPlayer(msg);
}
else if (args.length == 1)
{
if (CommandDataManager.warps.containsKey(args[0].toLowerCase()))
{
if (PermissionsAPI.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + "." + args[0].toLowerCase())))
{
Warp warp = CommandDataManager.warps.get(args[0].toLowerCase());
PlayerInfo playerInfo = PlayerInfo.getPlayerInfo(sender.username);
playerInfo.back = new WarpPoint(sender);
TeleportCenter.addToTpQue(warp.getPoint(), sender);
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_PERMDENIED));
}
}
else
{
OutputHandler.chatError(sender, Localization.get("command.warp.notfound"));
}
}
else if (args.length == 2)
{
if (PermissionsAPI.checkPermAllowed(new PermQueryPlayer(sender, getCommandPerm() + ".admin")))
{
if (args[0].equalsIgnoreCase("set"))
{
if (CommandDataManager.warps.containsKey(args[1].toLowerCase()))
{
OutputHandler.chatError(sender, Localization.get("command.warp.alreadyexists"));
}
else
{
CommandDataManager.addWarp(new Warp(args[1].toLowerCase(), new WarpPoint(sender)));
OutputHandler.chatConfirmation(sender, Localization.get(Localization.DONE));
}
}
else if (args[0].equalsIgnoreCase("del"))
{
if (CommandDataManager.warps.containsKey(args[1].toLowerCase()))
{
CommandDataManager.removeWarp(CommandDataManager.warps.get(args[1]));
OutputHandler.chatConfirmation(sender, Localization.get(Localization.DONE));
}
else
{
OutputHandler.chatError(sender, Localization.get("command.warp.notfound"));
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxPlayer(sender));
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_PERMDENIED));
}
}
}
|
diff --git a/TaskListRSF-OTP/tool/src/java/org/sakaiproject/tool/tasklist/rsf/TaskListProducer.java b/TaskListRSF-OTP/tool/src/java/org/sakaiproject/tool/tasklist/rsf/TaskListProducer.java
index 6ac27b6..64c6f01 100644
--- a/TaskListRSF-OTP/tool/src/java/org/sakaiproject/tool/tasklist/rsf/TaskListProducer.java
+++ b/TaskListRSF-OTP/tool/src/java/org/sakaiproject/tool/tasklist/rsf/TaskListProducer.java
@@ -1,128 +1,128 @@
/*
* Created on May 29, 2006
*/
package org.sakaiproject.tool.tasklist.rsf;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.sakaiproject.tool.tasklist.api.Task;
import uk.org.ponder.rsf.components.ELReference;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIDeletionBinding;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.DefaultView;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.stringutil.StringList;
public class TaskListProducer implements ViewComponentProducer,
NavigationCaseReporter, DefaultView {
public static final String VIEW_ID = "TaskList";
private Locale locale;
private List taskList;
private String siteId;
private String userId;
private String username;
public String getViewID() {
return VIEW_ID;
}
public void setTaskList(List taskList) {
this.taskList = taskList;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public void setSiteId(String siteId) {
this.siteId = siteId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserName(String username) {
this.username = username;
}
public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
UIOutput.make(tofill, "current-username", username);
// Illustrates fetching messages from locator - remaining messages are
// written out in template - localising HTML template directly is
// probably easier than localising properties files.
UIOutput.make(tofill, "task-list-title", null,
"#{messageLocator.task_list_title}");
UIForm newtask = UIForm.make(tofill, "new-task-form");
UIInput.make(newtask, "new-task-name", "#{Task.new 1.task}");
// no binding for this command since "commit" is a null-action using OTP
UICommand.make(newtask, "submit-new-task");
// pre-bind the task's owner to avoid annoying the handler having to fetch
// it
newtask.parameters.add(new UIELBinding("#{Task.new 1.owner}", userId));
newtask.parameters.add(new UIELBinding("#{Task.new 1.siteId}", siteId));
UIForm deleteform = UIForm.make(tofill, "delete-task-form");
// Create a multiple selection control for the tasks to be deleted.
// We will fill in the options at the loop end once we have collected them.
UISelect deleteselect = UISelect.makeMultiple(deleteform, "delete-select",
null, "#{deleteIds}", new String[] {});
StringList deletable = new StringList();
// JSF DateTimeConverter is a fun piece of kit - now here's a good way to
// shed 600 lines:
// http://fisheye5.cenqua.com/viewrep/javaserverfaces-sources/jsf-api/src/javax/faces/convert/DateTimeConverter.java
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT, locale);
for (int i = 0; i < taskList.size(); ++i) {
Task task = (Task) taskList.get(i);
boolean candelete = task.getOwner().equals(userId);
UIBranchContainer taskrow = UIBranchContainer.make(deleteform,
candelete ? "task-row:deletable"
- : "task-row:nondeletable");
+ : "task-row:nondeletable", Integer.toString(i));
if (candelete) {
UISelectChoice.make(taskrow, "task-select", deleteselect.getFullID(),
deletable.size());
deletable.add(task.getId().toString());
}
UIOutput.make(taskrow, "task-name", task.getTask());
UIOutput.make(taskrow, "task-owner", task.getOwner());
UIOutput.make(taskrow, "task-date", df.format(task.getCreationDate()));
}
deleteselect.optionlist.setValue(deletable.toStringArray());
deleteform.parameters.add(new UIDeletionBinding("#{Task}",
new ELReference("#{deleteIds}")));
// similarly no action binding here since deletion binding does all
UICommand.make(deleteform, "delete-tasks");
}
public List reportNavigationCases() {
List togo = new ArrayList();
// Always navigate back to this view (actually the RSF default)
togo.add(new NavigationCase(null, new SimpleViewParameters(VIEW_ID)));
return togo;
}
}
| true | true | public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
UIOutput.make(tofill, "current-username", username);
// Illustrates fetching messages from locator - remaining messages are
// written out in template - localising HTML template directly is
// probably easier than localising properties files.
UIOutput.make(tofill, "task-list-title", null,
"#{messageLocator.task_list_title}");
UIForm newtask = UIForm.make(tofill, "new-task-form");
UIInput.make(newtask, "new-task-name", "#{Task.new 1.task}");
// no binding for this command since "commit" is a null-action using OTP
UICommand.make(newtask, "submit-new-task");
// pre-bind the task's owner to avoid annoying the handler having to fetch
// it
newtask.parameters.add(new UIELBinding("#{Task.new 1.owner}", userId));
newtask.parameters.add(new UIELBinding("#{Task.new 1.siteId}", siteId));
UIForm deleteform = UIForm.make(tofill, "delete-task-form");
// Create a multiple selection control for the tasks to be deleted.
// We will fill in the options at the loop end once we have collected them.
UISelect deleteselect = UISelect.makeMultiple(deleteform, "delete-select",
null, "#{deleteIds}", new String[] {});
StringList deletable = new StringList();
// JSF DateTimeConverter is a fun piece of kit - now here's a good way to
// shed 600 lines:
// http://fisheye5.cenqua.com/viewrep/javaserverfaces-sources/jsf-api/src/javax/faces/convert/DateTimeConverter.java
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT, locale);
for (int i = 0; i < taskList.size(); ++i) {
Task task = (Task) taskList.get(i);
boolean candelete = task.getOwner().equals(userId);
UIBranchContainer taskrow = UIBranchContainer.make(deleteform,
candelete ? "task-row:deletable"
: "task-row:nondeletable");
if (candelete) {
UISelectChoice.make(taskrow, "task-select", deleteselect.getFullID(),
deletable.size());
deletable.add(task.getId().toString());
}
UIOutput.make(taskrow, "task-name", task.getTask());
UIOutput.make(taskrow, "task-owner", task.getOwner());
UIOutput.make(taskrow, "task-date", df.format(task.getCreationDate()));
}
deleteselect.optionlist.setValue(deletable.toStringArray());
deleteform.parameters.add(new UIDeletionBinding("#{Task}",
new ELReference("#{deleteIds}")));
// similarly no action binding here since deletion binding does all
UICommand.make(deleteform, "delete-tasks");
}
| public void fillComponents(UIContainer tofill, ViewParameters viewparams,
ComponentChecker checker) {
UIOutput.make(tofill, "current-username", username);
// Illustrates fetching messages from locator - remaining messages are
// written out in template - localising HTML template directly is
// probably easier than localising properties files.
UIOutput.make(tofill, "task-list-title", null,
"#{messageLocator.task_list_title}");
UIForm newtask = UIForm.make(tofill, "new-task-form");
UIInput.make(newtask, "new-task-name", "#{Task.new 1.task}");
// no binding for this command since "commit" is a null-action using OTP
UICommand.make(newtask, "submit-new-task");
// pre-bind the task's owner to avoid annoying the handler having to fetch
// it
newtask.parameters.add(new UIELBinding("#{Task.new 1.owner}", userId));
newtask.parameters.add(new UIELBinding("#{Task.new 1.siteId}", siteId));
UIForm deleteform = UIForm.make(tofill, "delete-task-form");
// Create a multiple selection control for the tasks to be deleted.
// We will fill in the options at the loop end once we have collected them.
UISelect deleteselect = UISelect.makeMultiple(deleteform, "delete-select",
null, "#{deleteIds}", new String[] {});
StringList deletable = new StringList();
// JSF DateTimeConverter is a fun piece of kit - now here's a good way to
// shed 600 lines:
// http://fisheye5.cenqua.com/viewrep/javaserverfaces-sources/jsf-api/src/javax/faces/convert/DateTimeConverter.java
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.SHORT, locale);
for (int i = 0; i < taskList.size(); ++i) {
Task task = (Task) taskList.get(i);
boolean candelete = task.getOwner().equals(userId);
UIBranchContainer taskrow = UIBranchContainer.make(deleteform,
candelete ? "task-row:deletable"
: "task-row:nondeletable", Integer.toString(i));
if (candelete) {
UISelectChoice.make(taskrow, "task-select", deleteselect.getFullID(),
deletable.size());
deletable.add(task.getId().toString());
}
UIOutput.make(taskrow, "task-name", task.getTask());
UIOutput.make(taskrow, "task-owner", task.getOwner());
UIOutput.make(taskrow, "task-date", df.format(task.getCreationDate()));
}
deleteselect.optionlist.setValue(deletable.toStringArray());
deleteform.parameters.add(new UIDeletionBinding("#{Task}",
new ELReference("#{deleteIds}")));
// similarly no action binding here since deletion binding does all
UICommand.make(deleteform, "delete-tasks");
}
|
diff --git a/Android/SpaceMerchant/src/edu/gatech/cs2340/group29/spacemerchant/util/GameDataSource.java b/Android/SpaceMerchant/src/edu/gatech/cs2340/group29/spacemerchant/util/GameDataSource.java
index 7f6466c..d605455 100644
--- a/Android/SpaceMerchant/src/edu/gatech/cs2340/group29/spacemerchant/util/GameDataSource.java
+++ b/Android/SpaceMerchant/src/edu/gatech/cs2340/group29/spacemerchant/util/GameDataSource.java
@@ -1,556 +1,556 @@
/**
* @author MetaGalactic Merchants
* @version 1.0
*
*/
package edu.gatech.cs2340.group29.spacemerchant.util;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import edu.gatech.cs2340.group29.spacemerchant.model.Game;
import edu.gatech.cs2340.group29.spacemerchant.model.Inventory;
import edu.gatech.cs2340.group29.spacemerchant.model.Item;
import edu.gatech.cs2340.group29.spacemerchant.model.Planet;
import edu.gatech.cs2340.group29.spacemerchant.model.Player;
import edu.gatech.cs2340.group29.spacemerchant.model.Ship;
import edu.gatech.cs2340.group29.spacemerchant.model.Universe;
/**
* The Class GameDataSource.
*/
public class GameDataSource
{
private static String[] ALL_GAME_COLUMNS = { "game", "planet", "difficulty", "name",
"money", "pilotSkillPoints", "fighterSkillPoints", "traderSkillPoints",
"engineerSkillPoints", "head", "body", "legs", "feet", "fuselage", "cabin",
"boosters"};
private static String[] ALL_PLANET_COLUMNS = { "planet", "game", "techLevel",
"resourceType", "name", "xCoord" ,"yCoord", "money", "base", "land", "cloud" };
private static String[] ALL_ITEM_COLUMNS = { "item", "game", "type",
"name", "drawable" };
private SQLiteDatabase database;
private DatabaseHelper databaseHelper;
private Context context;
/**
* Instantiates a new game data source.
*
* @param context the Context
*/
public GameDataSource( Context context )
{
this.context = context;
databaseHelper = new DatabaseHelper( context );
}
/**
* Open.
*
* @throws SQLiteException the sQ lite exception
*/
public void open() throws SQLiteException
{
database = databaseHelper.getWritableDatabase();
}
/**
* Close.
*/
public void close()
{
database.close();
databaseHelper.close();
}
/**
* Inserts a planet into database without associated gameID.
* Used to store currentPlanet planet object
* @param planet
* @return long planetID
*/
private long createPlanet( Planet planet )
{
return createPlanet(planet, -1);
}
/**
* Inserts planet into database.
* @param planet
* @param gameID
* @return long planetID
*/
private long createPlanet( Planet planet, long gameID )
{
int techLevel = planet.getTechLevel();
int resourceType = planet.getResourceType();
String planetName = planet.getName();
int xCoord = planet.getX();
int yCoord = planet.getY();
int money = planet.getMoney();
int base = planet.getBase();
int land = planet.getLand();
int cloud = planet.getCloud();
ContentValues values = new ContentValues();
if( gameID > 0 )
{
values.put("game", gameID);
}
values.put("techLevel", techLevel);
values.put("resourceType", resourceType);
values.put("name", planetName);
values.put("xCoord", xCoord);
values.put("yCoord", yCoord);
values.put("money", money);
values.put("base", base);
values.put("land", land);
values.put("cloud", cloud);
long planetID = database.insert( "tb_planet", null, values );
return planetID;
}
/**
* Inserts inventory item into SQLite database
* @param item
* @param gameID
* @return long itemID
*/
private long createItem( Item item, long gameID)
{
ContentValues values = new ContentValues();
String itemName = item.getName();
int drawable = item.getDrawable();
int itemType = item.getType();
values.put( "game", gameID );
values.put( "type", itemType );
values.put( "name", itemName );
values.put( "drawable", drawable );
long itemID = database.insert( "tb_item", null, values);
return itemID;
}
/**
* Updates game in SQLite database
*/
public long updateGame( Game game )
{
long gameID = game.getGameID();
//remove currentPlanet from database
String query = ""
+ "delete from tb_planet where planet in "
+ " (select planet from tb_game where game = ? ) ";
database.rawQuery( query, new String[] { Long.toString(gameID) } );
//remove all saved inventory from database
database.delete( "tb_item", "game = ?" , new String[] { Long.toString(gameID) });
Planet currentPlanet = game.getPlanet();
Player player = game.getPlayer();
Ship ship = player.getShip();
Inventory inventory = player.getInventory();
// insert currentPlanet into database
long currentPlanetID = createPlanet( currentPlanet );
//insert game, player, ship into database
int money = player.getMoney();
int[] stats = player.getStats();
int head = player.getHead();
int body = player.getBody();
int legs = player.getLegs();
int feet = player.getFeet();
int fuselage = ship.getFuselage();
int cabin = ship.getCabin();
int boosters = ship.getBoosters();
ContentValues values = new ContentValues();
values.put("planet",currentPlanetID);
values.put("money",money);
values.put("pilotSkillPoints",stats[0]);
values.put("fighterSkillPoints",stats[1]);
values.put("traderSkillPoints",stats[2]);
values.put("engineerSkillPoints",stats[3]);
values.put("head",head);
values.put("body",body);
values.put("legs",legs);
values.put("feet",feet);
values.put("fuselage",fuselage);
values.put("cabin",cabin);
values.put("boosters",boosters);
database.update( "tb_game", values, "game = ?" , new String[] { Long.toString(gameID) });
//insert inventory into database
LinkedList<Item>[] inventoryItems = inventory.getContents();
for( LinkedList<Item> inventoryItemsByType : inventoryItems )
{
for( Item item : inventoryItemsByType)
{
createItem(item, gameID);
}
}
return gameID;
}
/**
* Inserts game and associated planet, player, inventory
* and item objects into SQLite database
*
* @param Game game to be stored
* @return long gameID
*/
public long createGame( Game game )
{
Planet currentPlanet = game.getPlanet();
Universe universe = game.getUniverse();
Player player = game.getPlayer();
Ship ship = player.getShip();
// insert planet into database
ContentValues values = new ContentValues();
long currentPlanetID = createPlanet( currentPlanet );
//insert game, player, ship into database
int difficulty = game.getDifficulty();
String name = player.getName();
int money = player.getMoney();
int[] stats = player.getStats();
int head = player.getHead();
int body = player.getBody();
int legs = player.getLegs();
int feet = player.getFeet();
int fuselage = ship.getFuselage();
int cabin = ship.getCabin();
int boosters = ship.getBoosters();
values = new ContentValues();
values.put("difficulty",difficulty);
values.put("planet",currentPlanetID);
values.put("name",name);
values.put("money",money);
values.put("pilotSkillPoints",stats[0]);
values.put("fighterSkillPoints",stats[1]);
values.put("traderSkillPoints",stats[2]);
values.put("engineerSkillPoints",stats[3]);
values.put("head",head);
values.put("body",body);
values.put("legs",legs);
values.put("feet",feet);
values.put("fuselage",fuselage);
values.put("cabin",cabin);
values.put("boosters",boosters);
long gameID = database.insert( "tb_game", null, values );
game.setID( gameID );
//insert universe into database
ArrayList<Planet> universePlanets = universe.getUniverse();
for( Planet universePlanet: universePlanets )
{
createPlanet(universePlanet, gameID);
}
return gameID;
}
/**
* Delete game.
*
* @param game the Game
*/
public void deleteGame( Game game )
{
long gameID = game.getID();
//remove currentPlanet from database
String query = ""
+ "delete from tb_planet where planet in "
+ " (select planet from tb_game where game = ? ) ";
database.rawQuery( query, new String[] { Long.toString(gameID) } );
database.delete( "tb_game", "game=" + gameID, null );
database.delete( "tb_item", "game=" + gameID, null );
database.delete( "tb_planet", "game=" + gameID, null );
}
/**
* Gets the game list.
*
* @return the game list
*/
public List<Game> getGameList()
{
List<Game> games = new ArrayList<Game>();
Cursor cursor = database.query( "tb_game", ALL_GAME_COLUMNS, null, null, null, null, null );
cursor.moveToFirst();
while ( !cursor.isAfterLast() )
{
Game game = cursorToGame( cursor );
games.add(game);
cursor.moveToNext();
}
cursor.close();
return games;
}
/**
* Gets the game by id.
*
* @param gameID the long
* @return the game by id
*/
public Game getGameByID( long gameID )
{
Cursor cursor = database.query( "tb_game", ALL_GAME_COLUMNS, "game=" + gameID, null, null, null, null );
cursor.moveToFirst();
Game game = cursorToGame( cursor );
cursor.close();
return game;
}
/**
* Gets the planet by id.
*
* @param planetID the long
* @return the planet by id
*/
public Planet getPlanetByID( long planetID )
{
Cursor cursor = database.query( "tb_planet", ALL_PLANET_COLUMNS, "planet=" + planetID, null, null, null, null );
cursor.moveToFirst();
Planet planet = cursorToPlanet( cursor );
cursor.close();
return planet;
}
/**
* Gets the planets by game id.
*
* @param gameID the long
* @return the planets by game id
*/
public ArrayList<Planet> getPlanetsByGameID( long gameID )
{
ArrayList<Planet> planets = new ArrayList<Planet>();
Cursor cursor = database.query( "tb_planet", ALL_PLANET_COLUMNS, "game=" + gameID,
null, null, null, null );
cursor.moveToFirst();
while ( !cursor.isAfterLast() )
{
Planet planet = cursorToPlanet( cursor );
planets.add( planet );
cursor.moveToNext();
}
cursor.close();
return planets;
}
/**
* Cursor to game.
*
* @param cursor the Cursor
* @return the game
*/
public Game cursorToGame( Cursor cursor )
{
int gameID = cursor.getInt(0);
long currentPlanetID = cursor.getInt(1);
int difficulty = cursor.getInt(2);
String name = cursor.getString(3);
int money = cursor.getInt(4);
int pilotSkillPoints = cursor.getInt(5);
int fighterSkillPoints = cursor.getInt(6);
int traderSkillPoints = cursor.getInt(7);
int engineerSkillPoints = cursor.getInt(8);
int head = cursor.getInt(9);
int body = cursor.getInt(10);
int legs = cursor.getInt(11);
int feet = cursor.getInt(12);
int fuselage = cursor.getInt(13);
int cabin = cursor.getInt(14);
int boosters = cursor.getInt(15);
//instantiate all the objects that are nested in the game object
Ship ship = new Ship();
- Inventory inventory = new Inventory();
+ Inventory inventory = new Inventory( engineerSkillPoints );
Player player = new Player();
Universe universe = new Universe(difficulty, context);
Planet currentPlanet = getPlanetByID(currentPlanetID);
Game game = new Game( context );
//set up ship object
ship.setFuselage(fuselage);
ship.setCabin(cabin);
ship.setBoosters(boosters);
//set up inventory object
ArrayList<Item> items = getItemsByGameID(gameID);
Item[] playerInventoryItems = items.toArray(new Item[items.size()]);
inventory.addAll(playerInventoryItems);
//set up player object
player.setName( name );
player.setMoney( money );
int[] stats = {pilotSkillPoints, fighterSkillPoints, traderSkillPoints, engineerSkillPoints};
player.setStats( stats );
player.setHead(head);
player.setBody(body);
player.setLegs(legs);
player.setFeet(feet);
player.setShip(ship);
player.setInventory(inventory);
//set up universe object
ArrayList<Planet> planets = getPlanetsByGameID( gameID );
universe.setUniverse(planets);
//set up game object
game.setID( gameID );
game.setDifficulty( difficulty );
game.setPlayer( player );
game.setPlanet( currentPlanet );
game.setUniverse( universe );
return game;
}
/**
* Cursor to planet.
*
* @param cursor the Cursor
* @return the planet
*/
public Planet cursorToPlanet( Cursor cursor )
{
Planet planet = new Planet(cursor.getString(4), cursor.getInt(5), cursor.getInt(6), context );
planet.setTechLevel(cursor.getInt(2));
planet.setResourceType(cursor.getInt(3));
planet.setMoney(cursor.getInt(7));
planet.setBase(cursor.getInt(8));
planet.setLand(cursor.getInt(9));
planet.setCloud(cursor.getInt(10));
return planet;
}
/**
* Converts database cursor into item
* @param cursor
* @return Item object
*/
private Item cursorToItem(Cursor cursor)
{
int type = cursor.getInt(2);
String name = cursor.getString(3);
int drawable = cursor.getInt(4);
Item item = new Item(type, name, drawable);
return item;
}
/**
* Gets all of the inventory items associated with a specified game
* @param gameID
* @return ArrayList of games
*/
private ArrayList<Item> getItemsByGameID( long gameID )
{
ArrayList<Item> items = new ArrayList<Item>();
Cursor cursor = database.query( "tb_item", ALL_ITEM_COLUMNS, "game=" + gameID,
null, null, null, null );
cursor.moveToFirst();
while( !cursor.isAfterLast() )
{
items.add((cursorToItem(cursor)));
cursor.moveToNext();
}
cursor.close();
return items;
}
}
| true | true | public Game cursorToGame( Cursor cursor )
{
int gameID = cursor.getInt(0);
long currentPlanetID = cursor.getInt(1);
int difficulty = cursor.getInt(2);
String name = cursor.getString(3);
int money = cursor.getInt(4);
int pilotSkillPoints = cursor.getInt(5);
int fighterSkillPoints = cursor.getInt(6);
int traderSkillPoints = cursor.getInt(7);
int engineerSkillPoints = cursor.getInt(8);
int head = cursor.getInt(9);
int body = cursor.getInt(10);
int legs = cursor.getInt(11);
int feet = cursor.getInt(12);
int fuselage = cursor.getInt(13);
int cabin = cursor.getInt(14);
int boosters = cursor.getInt(15);
//instantiate all the objects that are nested in the game object
Ship ship = new Ship();
Inventory inventory = new Inventory();
Player player = new Player();
Universe universe = new Universe(difficulty, context);
Planet currentPlanet = getPlanetByID(currentPlanetID);
Game game = new Game( context );
//set up ship object
ship.setFuselage(fuselage);
ship.setCabin(cabin);
ship.setBoosters(boosters);
//set up inventory object
ArrayList<Item> items = getItemsByGameID(gameID);
Item[] playerInventoryItems = items.toArray(new Item[items.size()]);
inventory.addAll(playerInventoryItems);
//set up player object
player.setName( name );
player.setMoney( money );
int[] stats = {pilotSkillPoints, fighterSkillPoints, traderSkillPoints, engineerSkillPoints};
player.setStats( stats );
player.setHead(head);
player.setBody(body);
player.setLegs(legs);
player.setFeet(feet);
player.setShip(ship);
player.setInventory(inventory);
//set up universe object
ArrayList<Planet> planets = getPlanetsByGameID( gameID );
universe.setUniverse(planets);
//set up game object
game.setID( gameID );
game.setDifficulty( difficulty );
game.setPlayer( player );
game.setPlanet( currentPlanet );
game.setUniverse( universe );
return game;
}
| public Game cursorToGame( Cursor cursor )
{
int gameID = cursor.getInt(0);
long currentPlanetID = cursor.getInt(1);
int difficulty = cursor.getInt(2);
String name = cursor.getString(3);
int money = cursor.getInt(4);
int pilotSkillPoints = cursor.getInt(5);
int fighterSkillPoints = cursor.getInt(6);
int traderSkillPoints = cursor.getInt(7);
int engineerSkillPoints = cursor.getInt(8);
int head = cursor.getInt(9);
int body = cursor.getInt(10);
int legs = cursor.getInt(11);
int feet = cursor.getInt(12);
int fuselage = cursor.getInt(13);
int cabin = cursor.getInt(14);
int boosters = cursor.getInt(15);
//instantiate all the objects that are nested in the game object
Ship ship = new Ship();
Inventory inventory = new Inventory( engineerSkillPoints );
Player player = new Player();
Universe universe = new Universe(difficulty, context);
Planet currentPlanet = getPlanetByID(currentPlanetID);
Game game = new Game( context );
//set up ship object
ship.setFuselage(fuselage);
ship.setCabin(cabin);
ship.setBoosters(boosters);
//set up inventory object
ArrayList<Item> items = getItemsByGameID(gameID);
Item[] playerInventoryItems = items.toArray(new Item[items.size()]);
inventory.addAll(playerInventoryItems);
//set up player object
player.setName( name );
player.setMoney( money );
int[] stats = {pilotSkillPoints, fighterSkillPoints, traderSkillPoints, engineerSkillPoints};
player.setStats( stats );
player.setHead(head);
player.setBody(body);
player.setLegs(legs);
player.setFeet(feet);
player.setShip(ship);
player.setInventory(inventory);
//set up universe object
ArrayList<Planet> planets = getPlanetsByGameID( gameID );
universe.setUniverse(planets);
//set up game object
game.setID( gameID );
game.setDifficulty( difficulty );
game.setPlayer( player );
game.setPlanet( currentPlanet );
game.setUniverse( universe );
return game;
}
|
diff --git a/src/haven/SkelSprite.java b/src/haven/SkelSprite.java
index 2b97c5fd..6b146ed6 100644
--- a/src/haven/SkelSprite.java
+++ b/src/haven/SkelSprite.java
@@ -1,117 +1,118 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, 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 for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.util.*;
import haven.Skeleton.Pose;
import haven.Skeleton.PoseMod;
public class SkelSprite extends Sprite {
private final Skeleton skel;
public final Pose pose;
private PoseMod[] mods = new PoseMod[0];
private boolean stat = true;
private final Rendered[] parts;
public static final Factory fact = new Factory() {
public Sprite create(Owner owner, Resource res, Message sdt) {
if(res.layer(Skeleton.Res.class) == null)
return(null);
return(new SkelSprite(owner, res, sdt));
}
};
public static int decnum(Message sdt) {
if(sdt == null)
return(0);
int ret = 0, off = 0;
while(!sdt.eom()) {
ret |= sdt.uint8() << off;
off += 8;
}
return(ret);
}
private SkelSprite(Owner owner, Resource res, Message sdt) {
super(owner, res);
skel = res.layer(Skeleton.Res.class).s;
pose = skel.new Pose(skel.bindpose);
+ int fl = sdt.eom()?0xffff0000:SkelSprite.decnum(sdt);
Collection<Rendered> rl = new LinkedList<Rendered>();
for(FastMesh.MeshRes mr : res.layers(FastMesh.MeshRes.class)) {
- if(mr.mat != null) {
+ if((mr.mat != null) && ((mr.id < 0) || (((1 << mr.id) & fl) != 0))) {
if(mr.m.boned()) {
String bnm = mr.m.boneidp();
if(bnm == null) {
rl.add(mr.mat.get().apply(new MorphedMesh(mr.m, pose)));
} else {
rl.add(pose.bonetrans2(skel.bones.get(bnm).idx).apply(mr.mat.get().apply(mr.m)));
}
} else {
rl.add(mr.mat.get().apply(mr.m));
}
}
}
this.parts = rl.toArray(new Rendered[0]);
- chposes(decnum(sdt));
+ chposes(fl);
}
private void chposes(int mask) {
Collection<PoseMod> poses = new LinkedList<PoseMod>();
stat = true;
pose.reset();
for(Skeleton.ResPose p : res.layers(Skeleton.ResPose.class)) {
if((p.id < 0) || ((mask & (1 << p.id)) != 0)) {
Skeleton.TrackMod mod = p.forskel(skel, p.defmode);
if(!mod.stat)
stat = false;
poses.add(mod);
mod.apply(pose);
}
}
pose.gbuild();
this.mods = poses.toArray(new PoseMod[0]);
}
public Order setup(RenderList rl) {
for(Rendered p : parts)
rl.add(p, null);
/* rl.add(pose.debug, null); */
return(null);
}
public boolean tick(int dt) {
if(!stat) {
pose.reset();
for(PoseMod m : mods) {
m.tick(dt / 1000.0f);
m.apply(pose);
}
pose.gbuild();
}
return(false);
}
}
| false | true | private SkelSprite(Owner owner, Resource res, Message sdt) {
super(owner, res);
skel = res.layer(Skeleton.Res.class).s;
pose = skel.new Pose(skel.bindpose);
Collection<Rendered> rl = new LinkedList<Rendered>();
for(FastMesh.MeshRes mr : res.layers(FastMesh.MeshRes.class)) {
if(mr.mat != null) {
if(mr.m.boned()) {
String bnm = mr.m.boneidp();
if(bnm == null) {
rl.add(mr.mat.get().apply(new MorphedMesh(mr.m, pose)));
} else {
rl.add(pose.bonetrans2(skel.bones.get(bnm).idx).apply(mr.mat.get().apply(mr.m)));
}
} else {
rl.add(mr.mat.get().apply(mr.m));
}
}
}
this.parts = rl.toArray(new Rendered[0]);
chposes(decnum(sdt));
}
| private SkelSprite(Owner owner, Resource res, Message sdt) {
super(owner, res);
skel = res.layer(Skeleton.Res.class).s;
pose = skel.new Pose(skel.bindpose);
int fl = sdt.eom()?0xffff0000:SkelSprite.decnum(sdt);
Collection<Rendered> rl = new LinkedList<Rendered>();
for(FastMesh.MeshRes mr : res.layers(FastMesh.MeshRes.class)) {
if((mr.mat != null) && ((mr.id < 0) || (((1 << mr.id) & fl) != 0))) {
if(mr.m.boned()) {
String bnm = mr.m.boneidp();
if(bnm == null) {
rl.add(mr.mat.get().apply(new MorphedMesh(mr.m, pose)));
} else {
rl.add(pose.bonetrans2(skel.bones.get(bnm).idx).apply(mr.mat.get().apply(mr.m)));
}
} else {
rl.add(mr.mat.get().apply(mr.m));
}
}
}
this.parts = rl.toArray(new Rendered[0]);
chposes(fl);
}
|
diff --git a/jsf-ri/src/com/sun/faces/config/AnnotationScanner.java b/jsf-ri/src/com/sun/faces/config/AnnotationScanner.java
index 0719b4792..08c02c3d5 100644
--- a/jsf-ri/src/com/sun/faces/config/AnnotationScanner.java
+++ b/jsf-ri/src/com/sun/faces/config/AnnotationScanner.java
@@ -1,897 +1,900 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. 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 and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.config;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.lang.annotation.Annotation;
import javax.faces.component.FacesComponent;
import javax.faces.component.behavior.FacesBehavior;
import javax.faces.convert.FacesConverter;
import javax.faces.event.NamedEvent;
import javax.faces.bean.ManagedBean;
import javax.faces.render.FacesBehaviorRenderer;
import javax.faces.render.FacesRenderer;
import javax.faces.validator.FacesValidator;
import javax.servlet.ServletContext;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.Util;
import com.sun.faces.spi.AnnotationProvider;
import static com.sun.faces.config.WebConfiguration.WebContextInitParameter.AnnotationScanPackages;
/**
* This class is responsible for scanning the class file bytes of
* classes contained within the web application for any of the known
* Faces configuration Annotations:
* <ul>
* <li>javax.faces.component.FacesBehavior</li>
* <li>javax.faces.render.FacesBehaviorRenderer</li>
* <li>javax.faces.component.FacesComponent</li>
* <li>javax.faces.convert.FacesConverter</li>
* <li>javax.faces.validator.FacesValidator</li>
* <li>javax.faces.render.FacesRenderer</li>
* <li>javax.faces.bean.ManagedBean</li>
* <li>javax.faces.event.NamedEvent</li>
* </ul>
*/
public class AnnotationScanner extends AnnotationProvider {
private static final Logger LOGGER = FacesLogger.CONFIG.getLogger();
// Matcher.group(1) == the URL to the JAR file itself.
// Matcher.group(2) == the name of the JAR.
private static final Pattern JAR_PATTERN = Pattern.compile("(.*/(\\S*\\.jar)).*");
private static final String WEB_INF_CLASSES = "/WEB-INF/classes/";
private static final String WILDCARD = "*";
private static final Set<String> FACES_ANNOTATIONS;
private static final Set<Class<? extends Annotation>> FACES_ANNOTATION_TYPE;
static {
HashSet<String> annotations = new HashSet<String>(8, 1.0f);
Collections.addAll(annotations,
"Ljavax/faces/component/FacesComponent;",
"Ljavax/faces/convert/FacesConverter;",
"Ljavax/faces/validator/FacesValidator;",
"Ljavax/faces/render/FacesRenderer;",
"Ljavax/faces/bean/ManagedBean;",
"Ljavax/faces/event/NamedEvent;",
"Ljavax/faces/component/behavior/FacesBehavior;",
"Ljavax/faces/render/FacesBehaviorRenderer;");
FACES_ANNOTATIONS = Collections.unmodifiableSet(annotations);
HashSet<Class<? extends Annotation>> annotationInstances =
new HashSet<Class<? extends Annotation>>(8, 1.0f);
Collections.addAll(annotationInstances,
FacesComponent.class,
FacesConverter.class,
FacesValidator.class,
FacesRenderer.class,
ManagedBean.class,
NamedEvent.class,
FacesBehavior.class,
FacesBehaviorRenderer.class);
FACES_ANNOTATION_TYPE = Collections.unmodifiableSet(annotationInstances);
}
private ClassFile classFileScanner;
private String[] webInfClassesPackages;
private Map<String,String[]> classpathPackages;
// ------------------------------------------------------------ Constructors
/**
* Creates a new <code>AnnotationScanner</code> instance.
*
* @param sc the <code>ServletContext</code> for the application to be
* scanned
*/
public AnnotationScanner(ServletContext sc) {
super(sc);
classFileScanner = new ClassFile();
WebConfiguration webConfig = WebConfiguration.getInstance(sc);
if (webConfig.isSet(AnnotationScanPackages)) {
classpathPackages = new HashMap<String,String[]>(4);
webInfClassesPackages = new String[0];
String[] options = webConfig.getOptionValue(AnnotationScanPackages, "\\s+");
List<String> packages = new ArrayList<String>(4);
for (String option : options) {
if (option.length() == 0) {
continue;
}
if (option.startsWith("jar:")) {
String[] parts = Util.split(option, ":");
if (parts.length != 3) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING,
"jsf.annotation.scanner.configuration.invalid",
new String[] { AnnotationScanPackages.getQualifiedName(), option });
}
} else {
if (WILDCARD.equals(parts[1]) && !classpathPackages.containsKey(WILDCARD)) {
classpathPackages.clear();
classpathPackages.put(WILDCARD, normalizeJarPackages(Util.split(parts[2], ",")));
} else if (WILDCARD.equals(parts[1]) && classpathPackages.containsKey(WILDCARD)) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(Level.WARNING,
"jsf.annotation.scanner.configuration.duplicate.wildcard",
new String[] { AnnotationScanPackages.getQualifiedName(), option });
}
} else {
if (!classpathPackages.containsKey(WILDCARD)) {
classpathPackages.put(parts[1], normalizeJarPackages(Util.split(parts[2], ",")));
}
}
}
} else {
if (WILDCARD.equals(option) && !packages.contains(WILDCARD)) {
packages.clear();
packages.add(WILDCARD);
} else {
if (!packages.contains(WILDCARD)) {
packages.add(option);
}
}
}
}
webInfClassesPackages = packages.toArray(new String[packages.size()]);
}
}
// ---------------------------------------------------------- Public Methods
/**
* @return a <code>Map</code> of classes mapped to a specific annotation type.
* If no annotations are present, or the application is considered
* <code>metadata-complete</code> <code>null</code> will be returned.
*/
public Map<Class<? extends Annotation>,Set<Class<?>>> getAnnotatedClasses(Set<URL> urls) {
Set<String> classList = new HashSet<String>();
processWebInfClasses(sc, classList);
processClasspath(urls, classList);
Map<Class<? extends Annotation>,Set<Class<?>>> annotatedClasses = null;
if (classList.size() > 0) {
annotatedClasses = new HashMap<Class<? extends Annotation>,Set<Class<?>>>(6, 1.0f);
for (String className : classList) {
try {
Class<?> clazz = Util.loadClass(className, this);
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
Class<? extends Annotation> annoType =
annotation.annotationType();
if (FACES_ANNOTATION_TYPE.contains(annoType)) {
Set<Class<?>> classes = annotatedClasses.get(annoType);
if (classes == null) {
classes = new HashSet<Class<?>>();
annotatedClasses.put(annoType, classes);
}
classes.add(clazz);
}
}
} catch (ClassNotFoundException cnfe) {
// shouldn't happen..
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"Unable to load annotated class: {0}",
className);
LOGGER.log(Level.SEVERE, "", cnfe);
}
} catch (NoClassDefFoundError ncdfe) {
// this is more likely
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"Unable to load annotated class: {0}, reason: {1}",
new Object[] { className, ncdfe.toString()});
}
}
}
}
return ((annotatedClasses != null)
? annotatedClasses
: Collections.<Class<? extends Annotation>, Set<Class<?>>>emptyMap());
}
// --------------------------------------------------------- Private Methods
/**
* Scans for annotations on classes within JAR files on the classpath.
*
* @param urls to a faces-config documents that allow us to refer to
* unique jar files on the classpath
* @param classList the <code>Set</code> to which annotated classes
* will be added
*/
private void processClasspath(Set<URL> urls, Set<String> classList) {
for (URL url : urls) {
try {
Matcher m = JAR_PATTERN.matcher(url.toString());
if (m.matches()) {
String jarName = m.group(2);
if (!processJar(jarName)) {
continue;
}
StringBuilder sb = new StringBuilder(32);
String us = m.group(1);
if (!us.startsWith("jar:")) {
sb.append("jar:");
}
sb.append(us).append("!/");
URL u = new URL(sb.toString());
JarFile jarFile =
((JarURLConnection) u.openConnection()).getJarFile();
processJarEntries(jarFile,
((classpathPackages != null)
? classpathPackages.get(jarName)
: null),
classList);
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Unable to match URL to a jar file: " + url
.toString());
}
}
} catch (Exception e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"Unable to process annotations for url, {0}. Reason: "
+ e.toString(),
new Object[]{url});
LOGGER.log(Level.SEVERE, "", e);
}
}
}
}
/**
* Called by {@link ConstantPoolInfo} when processing the bytes of the
* class file.
*
* @param value the String value as provided from {@link ConstantPoolInfo}
* @return <code>true</code> if the value is one of the known
* Faces annotations, otherwise <code>false</code>
*/
private static boolean isAnnotation(String value) {
return FACES_ANNOTATIONS.contains(value);
}
/**
* Process the entries in the provided <code>JarFile</code> looking for
* class files that may be annotated with any of the Faces configuration
* annotations.
*
* @param jarFile the JAR to process
* @param allowedPackages the packages that should be scanned within the jar
* @param classList the <code>Set</code> to which annotated classes
* will be added
*/
private void processJarEntries(JarFile jarFile, String[] allowedPackages, Set<String> classList) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"Scanning JAR {0} for annotations...",
jarFile.getName());
}
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
if (entry.isDirectory()) {
continue;
}
String name = entry.getName();
if (name.startsWith("META-INF")) {
continue;
}
if (name.endsWith(".class")) {
String cname = convertToClassName(name);
if (!processClass(cname, allowedPackages)) {
continue;
}
ReadableByteChannel channel = null;
try {
channel = Channels.newChannel(jarFile.getInputStream(entry));
if (classFileScanner.containsAnnotation(channel)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"[JAR] Found annotated Class: {0}",
cname);
}
classList.add(cname);
}
} catch (IOException e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"Unexpected exception scanning JAR {0} for annotations",
jarFile.getName());
LOGGER.log(Level.SEVERE,
e.toString(),
e);
}
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException ignored) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
ignored.toString(),
ignored);
}
}
}
}
}
}
}
/**
* Scan <code>WEB-INF/classes</code> for classes that may be annotated
* with any of the Faces configuration annotations.
*
* @param sc the <code>ServletContext</code> for the application being
* scanned
* @param classList the <code>Set</code> to which annotated classes
* will be added
*/
private void processWebInfClasses(ServletContext sc, Set<String> classList) {
processWebInfClasses(sc, WEB_INF_CLASSES, classList);
}
/**
* Scan <code>WEB-INF/classes</code> for classes that may be annotated
* with any of the Faces configuration annotations.
*
* @param sc the <code>ServletContext</code> for the application being
* scanned
* @param path the path to start the scan from
* @param classList the <code>Set</code> to which annotated classes
* will be added
*/
private void processWebInfClasses(ServletContext sc,
String path,
Set<String> classList) {
//noinspection unchecked
Set<String> paths = sc.getResourcePaths(path);
processWebInfClasses(sc, paths, classList);
}
/**
* Scan <code>WEB-INF/classes</code> for classes that may be annotated
* with any of the Faces configuration annotations.
*
* @param sc the <code>ServletContext</code> for the application being
* scanned
* @param paths a set of paths to process
* @param classList the <code>Set</code> to which annotated classes
* will be added
*/
private void processWebInfClasses(ServletContext sc,
Set<String> paths,
Set<String> classList) {
if (paths != null && !paths.isEmpty()) {
for (String pathElement : paths) {
if (pathElement.endsWith("/")) {
processWebInfClasses(sc, pathElement, classList);
} else {
if (pathElement.endsWith(".class")) {
String cname = convertToClassName(WEB_INF_CLASSES,
pathElement);
if (!processClass(cname, webInfClassesPackages)) {
continue;
}
if (containsAnnotation(sc, pathElement)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"[WEB-INF/classes] Found annotated Class: {0}",
cname);
}
classList.add(cname);
}
}
}
}
}
}
private String[] normalizeJarPackages(String[] packages) {
if (packages.length == 0) {
return packages;
}
List<String> normalizedPackages = new ArrayList<String>(packages.length);
for (String pkg : packages) {
if (WILDCARD.equals(pkg)) {
normalizedPackages.clear();
normalizedPackages.add(WILDCARD);
break;
} else {
normalizedPackages.add(pkg);
}
}
return normalizedPackages.toArray(new String[normalizedPackages.size()]);
}
/**
* @param sc the <code>ServletContext</code> for the application being
* scanned
* @param pathElement the full path to the classfile to be scanned
* @return <code>true</code> if the class contains one of the Faces
* configuration annotations
*/
private boolean containsAnnotation(ServletContext sc, String pathElement) {
ReadableByteChannel channel = null;
try {
URL url = sc.getResource(pathElement);
channel = Channels.newChannel(url.openStream());
return classFileScanner.containsAnnotation(channel);
} catch (MalformedURLException e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
e.toString(),
e);
}
} catch (IOException ioe) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
ioe.toString(),
ioe);
}
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException ignored) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
ignored.toString(),
ignored);
}
}
}
}
return false;
}
/**
* Utility method for converting paths to fully qualified class names.
*
* @param pathEntry a path entry to a class file
*
* @return a fully qualfied class name using dot notation
*/
private String convertToClassName(String pathEntry) {
return convertToClassName(null, pathEntry);
}
/**
* Utility method for converting paths to fully qualified class names.
*
* @param prefix the prefix that should be stripped from the class name
* before converting it
* @param pathEntry a path to a class file
*
* @return a fully qualfied class name using dot notation
*/
private String convertToClassName(String prefix, String pathEntry) {
String className = pathEntry;
if (prefix != null) {
// remove the prefix
className = className.substring(prefix.length());
}
// remove the .class suffix
className = className.substring(0, (className.length() - 6));
return className.replace('/', '.');
}
private boolean processJar(String entry) {
return (classpathPackages == null
|| (classpathPackages.containsKey(entry)
|| classpathPackages.containsKey(WILDCARD)));
}
/**
* @param candidate the class that should be processed
* @param packages the packages of classes that are allowed to be processed
* @return <code>true</code> if the class should be processed further,
* otherwise, <code>false</code>
*/
private boolean processClass(String candidate, String[] packages) {
if (packages == null) {
return true;
}
for (String packageName : packages) {
if (candidate.startsWith(packageName) || WILDCARD.equals(packageName)) {
return true;
}
}
return false;
}
// ----------------------------------------------------------- Inner Classes
/**
* This class is encapsulating binary .class file information as defined at
* http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html
* <p/>
* This is used by the annotation frameworks to quickly scan .class files
* for the presence of annotations. This avoid the annotation framework
* having to load each .class file in the class loader.
* <p/>
* Taken from the GlassFish V2 source base.
*/
@SuppressWarnings({"UnusedDeclaration"})
private static final class ClassFile {
private static final int magic = 0xCAFEBABE;
public static final int ACC_PUBLIC = 0x1;
public static final int ACC_PRIVATE = 0x2;
public static final int ACC_PROTECTED = 0x4;
public static final int ACC_STATIC = 0x8;
public static final int ACC_FINAL = 0x10;
public static final int ACC_SYNCHRONIZED = 0x20;
public static final int ACC_THREADSAFE = 0x40;
public static final int ACC_TRANSIENT = 0x80;
public static final int ACC_NATIVE = 0x100;
public static final int ACC_INTERFACE = 0x200;
public static final int ACC_ABSTRACT = 0x400;
public short majorVersion;
public short minorVersion;
public ConstantPoolInfo constantPool[];
public short accessFlags;
public ConstantPoolInfo thisClass;
public ConstantPoolInfo superClass;
public ConstantPoolInfo interfaces[];
/**
* bunch of stuff I really don't care too much for now.
* <p/>
* FieldInfo fields[]; MethodInfo methods[];
* AttributeInfo attributes[];
*/
ByteBuffer header;
ConstantPoolInfo constantPoolInfo = new ConstantPoolInfo();
// ------------------------------------------------------------ Constructors
/**
* Creates a new instance of ClassFile
*/
public ClassFile() {
header = ByteBuffer.allocate(12000);
}
// ---------------------------------------------------------- Public Methods
public void setConstantPoolInfo(ConstantPoolInfo poolInfo) {
constantPoolInfo = poolInfo;
}
/**
* Read the input channel and initialize instance data structure.
*
* @param in a <code>ReadableByteChannel</code> that provides the bytes
* of the classfile
*
* @return <code>true</code> if the bytes representing this classfile include
* one of the annotations we're looking for.
*
* @throws IOException if an I/O error occurs while reading the class
*/
public boolean containsAnnotation(ReadableByteChannel in)
throws IOException {
/**
* this is the .class file layout
*
ClassFile {
u4 magic;
u2 minor_version;
u2 major_version;
u2 constant_pool_count;
cp_info constant_pool[constant_pool_count-1];
u2 access_flags;
u2 this_class;
u2 super_class;
u2 interfaces_count;
u2 interfaces[interfaces_count];
u2 fields_count;
field_info fields[fields_count];
u2 methods_count;
method_info methods[methods_count];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
**/
header.clear();
long read = (long) in.read(header);
if (read == -1) {
return false;
}
header.rewind();
if (header.getInt() != magic) {
return false;
}
minorVersion = header.getShort();
majorVersion = header.getShort();
int constantPoolSize = header.getShort();
return constantPoolInfo
.containsAnnotation(constantPoolSize, header, in);
}
} // END ClassFile
private static class ConstantPoolInfo {
private static final Logger LOGGER = FacesLogger.CONFIG.getLogger();
public static final byte CLASS = 7;
public static final int FIELDREF = 9;
public static final int METHODREF = 10;
public static final int STRING = 8;
public static final int INTEGER = 3;
public static final int FLOAT = 4;
public static final int LONG = 5;
public static final int DOUBLE = 6;
public static final int INTERFACEMETHODREF = 11;
public static final int NAMEANDTYPE = 12;
public static final int ASCIZ = 1;
public static final int UNICODE = 2;
byte[] bytes = new byte[Short.MAX_VALUE];
// ------------------------------------------------------------ Constructors
/**
* Creates a new instance of ConstantPoolInfo
*/
public ConstantPoolInfo() {
}
// ---------------------------------------------------------- Public Methods
/**
* Read the input channel and initialize instance data structure.
*
* @param constantPoolSize the constant pool size for this class file
* @param buffer the ByteBuffer used to store the bytes from <code>in</code>
* @param in ReadableByteChannel from which the class file bytes are
* read
*
* @return <code>true</code> if the bytes representing this classfile include
* one of the annotations we're looking for.
*
* @throws IOException if an I/O error occurs while reading the class
*/
public boolean containsAnnotation(int constantPoolSize,
final ByteBuffer buffer,
final ReadableByteChannel in)
throws IOException {
for (int i = 1; i < constantPoolSize; i++) {
if (!refill(buffer, in, 1)) {
- return false;
+ return true;
}
final byte type = buffer.get();
switch (type) {
case ASCIZ:
case UNICODE:
if (!refill(buffer, in, 2)) {
- return false;
+ return true;
}
final short length = buffer.getShort();
if (length < 0 || length > Short.MAX_VALUE) {
return true;
}
+ if (length > buffer.capacity()) {
+ return true;
+ }
if (!refill(buffer, in, length)) {
- return false;
+ return true;
}
buffer.get(bytes, 0, length);
/* to speed up the process, I am comparing the first few
* bytes to Ljava since all annotations are in the java
* package, the reduces dramatically the number or String
* construction
*/
if (bytes[0] == 'L' && bytes[1] == 'j' && bytes[2] == 'a') {
String stringValue;
if (type == ASCIZ) {
stringValue =
new String(bytes, 0, length, "US-ASCII");
} else {
stringValue = new String(bytes, 0, length);
}
if (AnnotationScanner.isAnnotation(stringValue)) {
return true;
}
}
break;
case CLASS:
case STRING:
if (!refill(buffer, in, 2)) {
- return false;
+ return true;
}
buffer.getShort();
break;
case FIELDREF:
case METHODREF:
case INTERFACEMETHODREF:
case INTEGER:
case FLOAT:
if (!refill(buffer, in, 4)) {
- return false;
+ return true;
}
buffer.position(buffer.position() + 4);
break;
case LONG:
case DOUBLE:
if (!refill(buffer, in, 8)) {
- return false;
+ return true;
}
buffer.position(buffer.position() + 8);
// for long, and double, they use 2 constantPool
i++;
break;
case NAMEANDTYPE:
if (!refill(buffer, in, 4)) {
- return false;
+ return true;
}
buffer.getShort();
buffer.getShort();
break;
default:
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"Unknow type constant pool {0} at position {1}",
new Object[]{type, i});
}
break;
}
}
return false;
}
// ----------------------------------------------------- Private Methods
private boolean refill(ByteBuffer buffer,
ReadableByteChannel in,
int requestLen) throws IOException {
int cap = buffer.capacity();
if (buffer.position() + requestLen > cap) {
buffer.compact();
int read = in.read(buffer);
if (read < 0) {
return false;
}
buffer.rewind();
}
return true;
}
} // END ConstantPoolInfo
}
| false | true | public boolean containsAnnotation(int constantPoolSize,
final ByteBuffer buffer,
final ReadableByteChannel in)
throws IOException {
for (int i = 1; i < constantPoolSize; i++) {
if (!refill(buffer, in, 1)) {
return false;
}
final byte type = buffer.get();
switch (type) {
case ASCIZ:
case UNICODE:
if (!refill(buffer, in, 2)) {
return false;
}
final short length = buffer.getShort();
if (length < 0 || length > Short.MAX_VALUE) {
return true;
}
if (!refill(buffer, in, length)) {
return false;
}
buffer.get(bytes, 0, length);
/* to speed up the process, I am comparing the first few
* bytes to Ljava since all annotations are in the java
* package, the reduces dramatically the number or String
* construction
*/
if (bytes[0] == 'L' && bytes[1] == 'j' && bytes[2] == 'a') {
String stringValue;
if (type == ASCIZ) {
stringValue =
new String(bytes, 0, length, "US-ASCII");
} else {
stringValue = new String(bytes, 0, length);
}
if (AnnotationScanner.isAnnotation(stringValue)) {
return true;
}
}
break;
case CLASS:
case STRING:
if (!refill(buffer, in, 2)) {
return false;
}
buffer.getShort();
break;
case FIELDREF:
case METHODREF:
case INTERFACEMETHODREF:
case INTEGER:
case FLOAT:
if (!refill(buffer, in, 4)) {
return false;
}
buffer.position(buffer.position() + 4);
break;
case LONG:
case DOUBLE:
if (!refill(buffer, in, 8)) {
return false;
}
buffer.position(buffer.position() + 8);
// for long, and double, they use 2 constantPool
i++;
break;
case NAMEANDTYPE:
if (!refill(buffer, in, 4)) {
return false;
}
buffer.getShort();
buffer.getShort();
break;
default:
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"Unknow type constant pool {0} at position {1}",
new Object[]{type, i});
}
break;
}
}
return false;
}
| public boolean containsAnnotation(int constantPoolSize,
final ByteBuffer buffer,
final ReadableByteChannel in)
throws IOException {
for (int i = 1; i < constantPoolSize; i++) {
if (!refill(buffer, in, 1)) {
return true;
}
final byte type = buffer.get();
switch (type) {
case ASCIZ:
case UNICODE:
if (!refill(buffer, in, 2)) {
return true;
}
final short length = buffer.getShort();
if (length < 0 || length > Short.MAX_VALUE) {
return true;
}
if (length > buffer.capacity()) {
return true;
}
if (!refill(buffer, in, length)) {
return true;
}
buffer.get(bytes, 0, length);
/* to speed up the process, I am comparing the first few
* bytes to Ljava since all annotations are in the java
* package, the reduces dramatically the number or String
* construction
*/
if (bytes[0] == 'L' && bytes[1] == 'j' && bytes[2] == 'a') {
String stringValue;
if (type == ASCIZ) {
stringValue =
new String(bytes, 0, length, "US-ASCII");
} else {
stringValue = new String(bytes, 0, length);
}
if (AnnotationScanner.isAnnotation(stringValue)) {
return true;
}
}
break;
case CLASS:
case STRING:
if (!refill(buffer, in, 2)) {
return true;
}
buffer.getShort();
break;
case FIELDREF:
case METHODREF:
case INTERFACEMETHODREF:
case INTEGER:
case FLOAT:
if (!refill(buffer, in, 4)) {
return true;
}
buffer.position(buffer.position() + 4);
break;
case LONG:
case DOUBLE:
if (!refill(buffer, in, 8)) {
return true;
}
buffer.position(buffer.position() + 8);
// for long, and double, they use 2 constantPool
i++;
break;
case NAMEANDTYPE:
if (!refill(buffer, in, 4)) {
return true;
}
buffer.getShort();
buffer.getShort();
break;
default:
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE,
"Unknow type constant pool {0} at position {1}",
new Object[]{type, i});
}
break;
}
}
return false;
}
|
diff --git a/src/net/rptools/maptool/client/ui/token/EditTokenDialog.java b/src/net/rptools/maptool/client/ui/token/EditTokenDialog.java
index 4e922fb1..56e1d28d 100644
--- a/src/net/rptools/maptool/client/ui/token/EditTokenDialog.java
+++ b/src/net/rptools/maptool/client/ui/token/EditTokenDialog.java
@@ -1,1207 +1,1207 @@
/*
* 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 net.rptools.maptool.client.ui.token;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Transparency;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.AbstractListModel;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.text.JTextComponent;
import net.rptools.maptool.client.MapTool;
import net.rptools.maptool.client.MapToolUtil;
import net.rptools.maptool.client.functions.AbstractTokenAccessorFunction;
import net.rptools.maptool.client.functions.TokenBarFunction;
import net.rptools.maptool.client.swing.AbeillePanel;
import net.rptools.maptool.client.swing.GenericDialog;
import net.rptools.maptool.model.Asset;
import net.rptools.maptool.model.AssetManager;
import net.rptools.maptool.model.Association;
import net.rptools.maptool.model.Grid;
import net.rptools.maptool.model.MacroButtonProperties;
import net.rptools.maptool.model.ObservableList;
import net.rptools.maptool.model.Player;
import net.rptools.maptool.model.Token;
import net.rptools.maptool.model.TokenFootprint;
import net.rptools.maptool.util.ImageManager;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;
import com.jidesoft.grid.AbstractPropertyTableModel;
import com.jidesoft.grid.Property;
import com.jidesoft.grid.PropertyPane;
import com.jidesoft.grid.PropertyTable;
import com.jidesoft.swing.CheckBoxListWithSelectable;
import com.jidesoft.swing.DefaultSelectable;
import com.jidesoft.swing.Selectable;
/**
* This dialog is used to display all of the token states and notes to the user.
*/
public class EditTokenDialog extends AbeillePanel {
private Token token;
private boolean tokenSaved;
private GenericDialog dialog;
private ImageAssetPanel imagePanel;
// private CharSheetController controller;
/**
* The size used to constrain the icon.
*/
public static final int SIZE = 64;
/**
* Create a new token notes dialog.
*
* @param token
* The token being displayed.
*/
public EditTokenDialog() {
super("net/rptools/maptool/client/ui/forms/tokenPropertiesDialog.jfrm");
panelInit();
}
public void initPlayerNotesTextArea() {
getNotesTextArea().addMouseListener(new MouseHandler(getNotesTextArea()));
}
public void initGMNotesTextArea() {
getGMNotesTextArea().addMouseListener(new MouseHandler(getGMNotesTextArea()));
getComponent("@GMNotes").setEnabled(MapTool.getPlayer().isGM());
}
public void showDialog(Token token) {
this.token = token;
dialog = new GenericDialog("Edit Token", MapTool.getFrame(), this) {
@Override
public void closeDialog() {
// TODO: I don't like this. There should really be a AbeilleDialog class that does this
unbind();
super.closeDialog();
}
};
bind(token);
getRootPane().setDefaultButton(getOKButton());
dialog.showDialog();
}
@Override
public void bind(Object model) {
// ICON
getTokenIconPanel().setImageId(token.getImageAssetId());
// PROPERTIES
updatePropertyTypeCombo();
updatePropertiesTable(token.getPropertyType());
// SIGHT
updateSightTypeCombo();
// STATES
Component[] statePanels = getStatesPanel().getComponents();
Component barPanel = null;
for (int j = 0; j < statePanels.length; j++) {
if ("bar".equals(statePanels[j].getName())) {
barPanel = statePanels[j];
continue;
}
Component[] states = ((Container)statePanels[j]).getComponents();
for (int i = 0; i < states.length; i++) {
JCheckBox state = (JCheckBox) states[i];
state.setSelected(AbstractTokenAccessorFunction.getBooleanValue(token.getState(state.getText())));
}
} // endfor
// BARS
if (barPanel != null) {
Component[] bars = ((Container)barPanel).getComponents();
for (int i = 0; i < bars.length; i += 2) {
JCheckBox cb = (JCheckBox)((Container)bars[i]).getComponent(1);
JSlider bar = (JSlider) bars[i + 1];
if (token.getState(bar.getName()) == null) {
cb.setSelected(true);
bar.setEnabled(false);
bar.setValue(100);
} else {
cb.setSelected(false);
bar.setEnabled(true);
bar.setValue((int)(TokenBarFunction.getBigDecimalValue(token.getState(bar.getName())).doubleValue() * 100));
} // endif
} // endfor
} // endif
// OWNER LIST
EventQueue.invokeLater(new Runnable() {
public void run() {
getOwnerList().setModel(new OwnerListModel());
}
});
// MACRO TABLE
EventQueue.invokeLater(new Runnable() {
public void run() {
getMacroTable().setModel(new MacroTableModel(token));
}
});
// SPEECH TABLE
EventQueue.invokeLater(new Runnable() {
public void run() {
getSpeechTable().setModel(new SpeechTableModel(token));
}
});
// Player player = MapTool.getPlayer();
// boolean editable = player.isGM()
// || !MapTool.getServerPolicy().useStrictTokenManagement() || token.isOwner(player.getName());
// getAllPlayersCheckBox().setSelected(token.isOwnedByAll());
// OTHER
getShapeCombo().setSelectedItem(token.getShape());
if (token.isSnapToScale()) {
getSizeCombo().setSelectedItem(token.getFootprint(MapTool.getFrame().getCurrentZoneRenderer().getZone().getGrid()));
} else {
getSizeCombo().setSelectedIndex(0);
}
getPropertyTypeCombo().setSelectedItem(token.getPropertyType());
getSightTypeCombo().setSelectedItem(token.getSightType() != null ? token.getSightType() : MapTool.getCampaign().getCampaignProperties().getDefaultSightType());
getCharSheetPanel().setImageId(token.getCharsheetImage());
getPortraitPanel().setImageId(token.getPortraitImage());
getTokenLayoutPanel().setToken(token);
// Character Sheets
// controller = null;
// String form = MapTool.getCampaign().getCharacterSheets().get(token.getPropertyType());
// if (form == null) return;
// URL formUrl = getClass().getClassLoader().getResource(form);
// if (formUrl == null) return;
// controller = new CharSheetController(formUrl, null);
// HashMap<String, Object> properties = new HashMap<String, Object>();
// for (String prop : token.getPropertyNames())
// properties.put(prop, token.getProperty(prop));
// controller.setData(properties);
// controller.getPanel().setName("characterSheet");
// replaceComponent("sheetPanel", "characterSheet", controller.getPanel());
super.bind(model);
}
public JTabbedPane getTabbedPane() {
return (JTabbedPane)getComponent("tabs");
}
public JTextArea getNotesTextArea() {
return (JTextArea) getComponent("@notes");
}
public JTextArea getGMNotesTextArea() {
return (JTextArea) getComponent("@GMNotes");
}
// private JLabel getGMNameLabel() {
// return (JLabel) getComponent("tokenGMNameLabel");
// }
//
// public JTextField getNameTextField() {
// return (JTextField) getComponent("tokenName");
// }
//
// public JTextField getGMNameTextField() {
// return (JTextField) getComponent("tokenGMName");
// }
public void initTypeCombo() {
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement(Token.Type.NPC);
model.addElement(Token.Type.PC);
// getTypeCombo().setModel(model);
}
public JComboBox getTypeCombo() {
return (JComboBox) getComponent("@type");
}
public void initTokenIconPanel() {
getTokenIconPanel().setPreferredSize(new Dimension(100, 100));
getTokenIconPanel().setMinimumSize(new Dimension(100, 100));
}
public ImageAssetPanel getTokenIconPanel() {
if (imagePanel == null) {
imagePanel = new ImageAssetPanel();
imagePanel.setAllowEmptyImage(false);
replaceComponent("mainPanel", "tokenImage", imagePanel);
}
return imagePanel;
}
public void initShapeCombo() {
getShapeCombo().setModel(new DefaultComboBoxModel(Token.TokenShape.values()));
}
public JComboBox getShapeCombo() {
return (JComboBox) getComponent("shape");
}
public void initSizeCombo() {
DefaultComboBoxModel model = new DefaultComboBoxModel(MapTool.getFrame().getCurrentZoneRenderer().getZone().getGrid().getFootprints().toArray());
model.insertElementAt("Free Size", 0);
getSizeCombo().setModel(model);
}
public void initPropertyTypeCombo() {
updatePropertyTypeCombo();
}
private void updatePropertyTypeCombo() {
List<String> typeList = new ArrayList<String>(MapTool.getCampaign().getTokenTypes());
Collections.sort(typeList);
DefaultComboBoxModel model = new DefaultComboBoxModel(typeList.toArray());
getPropertyTypeCombo().setModel(model);
getPropertyTypeCombo().addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
updatePropertiesTable((String)getPropertyTypeCombo().getSelectedItem());
}
});
}
private void updateSightTypeCombo() {
List<String> typeList = new ArrayList<String>(MapTool.getCampaign().getSightTypes());
Collections.sort(typeList);
DefaultComboBoxModel model = new DefaultComboBoxModel(typeList.toArray());
getSightTypeCombo().setModel(model);
}
private void updatePropertiesTable(final String propertyType) {
EventQueue.invokeLater(new Runnable() {
public void run() {
getPropertyTable().setModel(new TokenPropertyTableModel());
getPropertyTable().expandAll();
}
});
}
public JComboBox getSizeCombo() {
return (JComboBox) getComponent("size");
}
public JComboBox getPropertyTypeCombo() {
return (JComboBox) getComponent("propertyTypeCombo");
}
public JComboBox getSightTypeCombo() {
return (JComboBox) getComponent("sightTypeCombo");
}
public void initOKButton() {
getOKButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (commit()) {
unbind();
dialog.closeDialog();
}
}
});
}
@Override
public boolean commit() {
// Commit any in-process edits
if (getMacroTable().isEditing()) {
getMacroTable().getCellEditor().stopCellEditing();
}
if (getSpeechTable().isEditing()) {
getSpeechTable().getCellEditor().stopCellEditing();
}
if (getPropertyTable().isEditing()) {
getPropertyTable().getCellEditor().stopCellEditing();
}
// Commit the changes to the token properties
if (!super.commit()) {
return false;
}
// SIZE
token.setSnapToScale(getSizeCombo().getSelectedIndex() != 0);
if (getSizeCombo().getSelectedIndex() > 0) {
Grid grid = MapTool.getFrame().getCurrentZoneRenderer().getZone().getGrid();
token.setFootprint(grid, (TokenFootprint) getSizeCombo().getSelectedItem());
}
// Other
token.setPropertyType((String)getPropertyTypeCombo().getSelectedItem());
token.setSightType((String)getSightTypeCombo().getSelectedItem());
// Get the states
Component[] stateComponents = getStatesPanel().getComponents();
Component barPanel = null;
for (int j = 0; j < stateComponents.length; j++) {
if ("bar".equals(stateComponents[j].getName())) {
barPanel = stateComponents[j];
continue;
}
Component[] components = ((Container)stateComponents[j]).getComponents();
for (int i = 0; i < components.length; i++) {
JCheckBox cb = (JCheckBox) components[i];
String state = cb.getText();
token.setState(state, cb.isSelected() ? Boolean.TRUE : Boolean.FALSE);
}
} // endfor
// BARS
if (barPanel != null) {
Component[] bars = ((Container)barPanel).getComponents();
for (int i = 0; i < bars.length; i += 2) {
JCheckBox cb = (JCheckBox)((Container)bars[i]).getComponent(1);
JSlider bar = (JSlider) bars[i + 1];
BigDecimal value = cb.isSelected() ? null : new BigDecimal(bar.getValue()).divide(new BigDecimal(100));
token.setState(bar.getName(), value);
bar.setValue((int)(TokenBarFunction.getBigDecimalValue(token.getState(bar.getName())).doubleValue() * 100));
}
}
// Ownership
token.clearAllOwners();
for (int i = 0; i < getOwnerList().getModel().getSize(); i++) {
DefaultSelectable selectable = (DefaultSelectable) getOwnerList().getModel().getElementAt(i);
if (selectable.isSelected()) {
token.addOwner((String) selectable.getObject());
}
}
// SHAPE
token.setShape((Token.TokenShape)getShapeCombo().getSelectedItem());
// Macros
token.replaceMacroList(((MacroTableModel)getMacroTable().getModel()).getMacroList());
token.setSpeechMap(((KeyValueTableModel)getSpeechTable().getModel()).getMap());
// Properties
((TokenPropertyTableModel)getPropertyTable().getModel()).applyTo(token);
// Charsheet
token.setCharsheetImage(getCharSheetPanel().getImageId());
if (token.getCharsheetImage() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(token.getCharsheetImage())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getCharsheetImage()));
}
}
// IMAGE
if (!token.getImageAssetId().equals(getTokenIconPanel().getImageId())) {
MapToolUtil.uploadAsset(AssetManager.getAsset(getTokenIconPanel().getImageId()));
token.setImageAsset(null, getTokenIconPanel().getImageId()); // Default image for now
}
// PORTRAIT
if (getPortraitPanel().getImageId() != null) {
// Make sure the server has the image
- if (!MapTool.getCampaign().containsAsset(token.getPortraitImage())) {
- MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getPortraitImage()));
+ if (!MapTool.getCampaign().containsAsset(getPortraitPanel().getImageId())) {
+ MapTool.serverCommand().putAsset(AssetManager.getAsset(getPortraitPanel().getImageId()));
}
}
token.setPortraitImage(getPortraitPanel().getImageId());
// LAYOUT
token.setSizeScale(getTokenLayoutPanel().getSizeScale());
token.setAnchor(getTokenLayoutPanel().getAnchorX(), getTokenLayoutPanel().getAnchorY());
// OTHER
tokenSaved = true;
// // Character Sheet
// Map<String, Object> properties = controller.getData();
// for (String prop : token.getPropertyNames())
// token.setProperty(prop, properties.get(prop));
// Update UI
MapTool.getFrame().updateTokenTree();
MapTool.getFrame().resetTokenPanels();
return true;
}
public JButton getOKButton() {
return (JButton) getComponent("okButton");
}
public void initCancelButton() {
getCancelButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
unbind();
dialog.closeDialog();
}
});
}
public JButton getCancelButton() {
return (JButton) getComponent("cancelButton");
}
public PropertyTable getPropertyTable() {
return (PropertyTable) getComponent("propertiesTable");
}
public void initStatesPanel() {
// Group the states first into individual panels
List<BooleanTokenOverlay> overlays = new ArrayList<BooleanTokenOverlay>(MapTool.getCampaign().getTokenStatesMap().values());
Map<String, JPanel> groups = new TreeMap<String, JPanel>();
groups.put("", new JPanel(new FormLayout("0px:grow 2px 0px:grow 2px 0px:grow 2px 0px:grow")));
for (BooleanTokenOverlay overlay : overlays) {
String group = overlay.getGroup();
if (group != null && (group = group.trim()).length() != 0) {
JPanel panel = groups.get(group);
if (panel == null) {
panel = new JPanel(new FormLayout("0px:grow 2px 0px:grow 2px 0px:grow 2px 0px:grow"));
panel.setBorder(BorderFactory.createTitledBorder(group));
groups.put(group, panel);
} // endif
} // endif
} // endfor
// Add the group panels and bar panel to the states panel
JPanel panel = getStatesPanel();
panel.removeAll();
FormLayout layout = new FormLayout("0px:grow");
panel.setLayout(layout);
int row = 1;
for (JPanel gPanel : groups.values()) {
layout.appendRow(new RowSpec("pref"));
layout.appendRow(new RowSpec("2px"));
panel.add(gPanel, new CellConstraints(1, row));
row += 2;
} // endfor
layout.appendRow(new RowSpec("pref"));
layout.appendRow(new RowSpec("2px"));
JPanel barPanel = new JPanel(new FormLayout("right:pref 2px pref 5px right:pref 2px pref"));
panel.add(barPanel, new CellConstraints(1, row));
// Add the individual check boxes.
for (BooleanTokenOverlay state : overlays) {
String group = state.getGroup();
panel = groups.get("");
if (group != null && (group = group.trim()).length() != 0)
panel = groups.get(group);
int x = panel.getComponentCount() % 4;
int y = panel.getComponentCount() / 4;
if (x == 0) {
layout = (FormLayout)panel.getLayout();
if (y != 0) layout.appendRow(new RowSpec("2px"));
layout.appendRow(new RowSpec("pref"));
} // endif
panel.add(new JCheckBox(state.getName()), new CellConstraints(x * 2 + 1, y * 2 + 1));
} // endif
// Add sliders to the bar panel
if (MapTool.getCampaign().getTokenBarsMap().size() > 0) {
layout = (FormLayout)barPanel.getLayout();
barPanel.setName("bar");
barPanel.setBorder(BorderFactory.createTitledBorder("Bars"));
int count = 0;
row = 0;
for (BarTokenOverlay bar : MapTool.getCampaign().getTokenBarsMap().values()) {
int working = count % 2;
if (working == 0) { // slider row
layout.appendRow(new RowSpec("pref"));
row += 1;
}
JPanel labelPanel = new JPanel(new FormLayout("pref", "pref 2px:grow pref"));
barPanel.add(labelPanel, new CellConstraints(1 + working * 4, row));
labelPanel.add(new JLabel(bar.getName() + ":"), new CellConstraints(1, 1, CellConstraints.RIGHT, CellConstraints.TOP));
JSlider slider = new JSlider(0, 100);
JCheckBox hide = new JCheckBox("Hide");
hide.putClientProperty("JSlider", slider);
hide.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider js = (JSlider)((JCheckBox)e.getSource()).getClientProperty("JSlider");
js.setEnabled(!((JCheckBox)e.getSource()).isSelected());
}
});
labelPanel.add(hide, new CellConstraints(1, 3, CellConstraints.RIGHT, CellConstraints.TOP));
slider.setName(bar.getName());
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.createStandardLabels(20);
slider.setMajorTickSpacing(10);
barPanel.add(slider, new CellConstraints(3 + working * 4, row));
if (working != 0) { // spacer row
layout.appendRow(new RowSpec("2px"));
row += 1;
}
count += 1;
}
} // endif
}
public JPanel getStatesPanel() {
return (JPanel) getComponent("statesPanel");
}
public JTable getMacroTable() {
return (JTable) getComponent("macroTable");
}
public JTable getSpeechTable() {
return (JTable) getComponent("speechTable");
}
public JButton getSpeechClearAllButton() {
return (JButton) getComponent("speechClearAllButton");
}
public JButton getMacroClearAllButton() {
return (JButton) getComponent("macroClearAllButton");
}
private JLabel getVisibleLabel() {
return (JLabel) getComponent("visibleLabel");
}
private JPanel getGMNotesPanel() {
return (JPanel) getComponent("gmNotesPanel");
}
public CheckBoxListWithSelectable getOwnerList() {
return (CheckBoxListWithSelectable) getComponent("ownerList");
}
public void initMacroPanel() {
getMacroClearAllButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!MapTool.confirm("Are you sure you want to clear all macros for this token?")) {
return;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
getMacroTable().setModel(new MacroTableModel(token,true));
}
});
}
});
}
public void initSpeechPanel() {
getSpeechClearAllButton().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!MapTool.confirm("Are you sure you want to clear all speech for this token?")) {
return;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
getSpeechTable().setModel(new SpeechTableModel());
}
});
}
});
}
public void initOwnershipPanel() {
CheckBoxListWithSelectable list = new CheckBoxListWithSelectable();
list.setName("ownerList");
replaceComponent("ownershipPanel", "ownershipList", new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
}
// public void initNotesPanel() {
// getNotesTextArea().addMouseListener(new MouseHandler(getNotesTextArea()));
// getGMNotesTextArea().addMouseListener(new MouseHandler(getGMNotesTextArea()));
// }
public void initTokenDetails() {
// tokenGMNameLabel = panel.getLabel("tokenGMNameLabel");
}
public void initTokenLayoutPanel() {
TokenLayoutPanel layoutPanel = new TokenLayoutPanel();
layoutPanel.setPreferredSize(new Dimension(150, 125));
layoutPanel.setName("tokenLayout");
replaceComponent("tokenLayoutPanel", "tokenLayout", layoutPanel);
}
public void initCharsheetPanel() {
ImageAssetPanel panel = new ImageAssetPanel();
panel.setPreferredSize(new Dimension(150, 125));
panel.setName("charsheet");
panel.setLayout(new GridLayout());
replaceComponent("charsheetPanel", "charsheet", panel);
}
public void initPortraitPanel() {
ImageAssetPanel panel = new ImageAssetPanel();
panel.setPreferredSize(new Dimension(150, 125));
panel.setName("portrait");
panel.setLayout(new GridLayout());
replaceComponent("portraitPanel", "portrait", panel);
}
public ImageAssetPanel getPortraitPanel() {
return (ImageAssetPanel) getComponent("portrait");
}
public ImageAssetPanel getCharSheetPanel() {
return (ImageAssetPanel) getComponent("charsheet");
}
public TokenLayoutPanel getTokenLayoutPanel() {
return (TokenLayoutPanel) getComponent("tokenLayout");
}
public void initPropertiesPanel() {
PropertyTable propertyTable = new PropertyTable();
propertyTable.setName("propertiesTable");
PropertyPane pane = new PropertyPane(propertyTable);
pane.setPreferredSize(new Dimension(100, 300));
replaceComponent("propertiesPanel", "propertiesTable", pane);
}
// /**
// * Set the currently displayed token.
// *
// * @param aToken
// * The token to be displayed
// */
// public void setToken(Token aToken) {
//
// if (aToken == token)
// return;
// if (token != null) {
// token.removeModelChangeListener(this);
// }
//
// token = aToken;
//
// if (token != null) {
// token.addModelChangeListener(this);
//
// List<String> typeList = new ArrayList<String>();
// typeList.addAll(MapTool.getCampaign().getTokenTypes());
// Collections.sort(typeList);
// getPropertyTypeCombo().setModel(new DefaultComboBoxModel(typeList.toArray()));
//
// setFields();
// updateView();
// }
//
// getTabbedPane().setSelectedIndex(0);
// }
// private void updateView() {
//
// Player player = MapTool.getPlayer();
//
// boolean isEnabled = player.isGM() || token.isOwner(player.getName());
//
// getTabbedPane().setEnabledAt(INDX_PROPERTIES, isEnabled);
// getTabbedPane().setEnabledAt(INDX_STATE, isEnabled);
// getTabbedPane().setEnabledAt(INDX_MACROS, isEnabled);
// getTabbedPane().setEnabledAt(INDX_SPEECH, isEnabled);
// getTabbedPane().setEnabledAt(INDX_OWNERSHIP, isEnabled);
// getTabbedPane().setEnabledAt(INDX_CONFIG, isEnabled);
//
// // Set the editable & enabled state
// boolean editable = player.isGM() || !MapTool.getServerPolicy().useStrictTokenManagement() || token.isOwner(player.getName());
// getOKButton().setEnabled(editable);
//
// getNotesTextArea().setEditable(editable);
// getNameTextField().setEditable(editable);
// getShapeCombo().setEnabled(editable);
// getSizeCombo().setEnabled(editable);
// getSnapToGridCheckBox().setEnabled(editable);
// getVisibleCheckBox().setEnabled(editable);
// getTypeCombo().setSelectedItem(token.getType());
//
// getGMNotesPanel().setVisible(player.isGM());
// getGMNameTextField().setVisible(player.isGM());
// getGMNameLabel().setVisible(player.isGM());
// getTypeCombo().setEnabled(player.isGM());
// getVisibleCheckBox().setVisible(player.isGM());
// getVisibleLabel().setVisible(player.isGM());
//
// }
/**
* Get and icon from the asset manager and scale it properly.
*
* @return An icon scaled to fit within a cell.
*/
private Icon getTokenIcon() {
// Get the base image && find the new size for the icon
BufferedImage assetImage = null;
Asset asset = AssetManager.getAsset(token.getImageAssetId());
if (asset == null) {
assetImage = ImageManager.UNKNOWN_IMAGE;
} else {
assetImage = ImageManager.getImage(asset, this);
}
// Need to resize?
if (assetImage.getWidth() > SIZE || assetImage.getHeight() > SIZE) {
Dimension dim = new Dimension(assetImage.getWidth(), assetImage
.getWidth());
if (dim.height < dim.width) {
dim.height = (int) ((dim.height / (double) dim.width) * SIZE);
dim.width = SIZE;
} else {
dim.width = (int) ((dim.width / (double) dim.height) * SIZE);
dim.height = SIZE;
}
BufferedImage image = new BufferedImage(dim.width, dim.height,
Transparency.BITMASK);
Graphics2D g = image.createGraphics();
g.drawImage(assetImage, 0, 0, dim.width, dim.height, null);
assetImage = image;
}
return new ImageIcon(assetImage);
}
/** @return Getter for tokenSaved */
public boolean isTokenSaved() {
return tokenSaved;
}
////
// HANDLER
public class MouseHandler extends MouseAdapter {
JTextArea source;
public MouseHandler(JTextArea source) {
this.source = source;
}
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
JPopupMenu menu = new JPopupMenu();
JMenuItem sendToChatItem = new JMenuItem("Send to Chat");
sendToChatItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedText = source.getSelectedText();
if (selectedText == null) {
selectedText = source.getText();
}
// TODO: COmbine this with the code int MacroButton
JTextComponent commandArea = MapTool.getFrame().getCommandPanel().getCommandTextArea();
commandArea.setText(commandArea.getText() + selectedText);
commandArea.requestFocusInWindow();
}
});
menu.add(sendToChatItem);
JMenuItem sendAsEmoteItem = new JMenuItem("Send as Emit");
sendAsEmoteItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedText = source.getSelectedText();
if (selectedText == null) {
selectedText = source.getText();
}
// TODO: COmbine this with the code int MacroButton
JTextComponent commandArea = MapTool.getFrame().getCommandPanel().getCommandTextArea();
commandArea.setText("/emit " + selectedText);
commandArea.requestFocusInWindow();
MapTool.getFrame().getCommandPanel().commitCommand();
}
});
menu.add(sendAsEmoteItem);
menu.show((JComponent)e.getSource(), e.getX(), e.getY());
}
}
}
////
// MODELS
private class TokenPropertyTableModel extends AbstractPropertyTableModel {
private Map<String, String> propertyMap;
private List<net.rptools.maptool.model.TokenProperty> propertyList;
private Map<String, String> getPropertyMap() {
if (propertyMap == null) {
propertyMap = new HashMap<String, String>();
List<net.rptools.maptool.model.TokenProperty> propertyList = getPropertyList();
for (net.rptools.maptool.model.TokenProperty property : propertyList) {
String value = (String) token.getProperty(property.getName());
if (value == null) {
value = property.getDefaultValue();
}
propertyMap.put(property.getName(), value);
}
}
return propertyMap;
}
private List<net.rptools.maptool.model.TokenProperty> getPropertyList() {
if (propertyList == null) {
propertyList = MapTool.getCampaign().getTokenPropertyList((String)getPropertyTypeCombo().getSelectedItem());
}
return propertyList;
}
public void applyTo(Token token) {
for (net.rptools.maptool.model.TokenProperty property : getPropertyList()) {
String value = getPropertyMap().get(property.getName());
if (property.getDefaultValue() != null && property.getDefaultValue().equals(value)) {
token.setProperty(property.getName(), null); // Clear original value
continue;
}
token.setProperty(property.getName(), value);
}
}
@Override
public Property getProperty(int index) {
return new TokenProperty(getPropertyList().get(index).getName());
}
@Override
public int getPropertyCount() {
return getPropertyList() != null ? getPropertyList().size() : 0;
}
private class TokenProperty extends Property {
private String key;
public TokenProperty(String key) {
super(key, key, String.class, "Core");
this.key = key;
}
@Override
public Object getValue() {
return getPropertyMap().get(key);
}
@Override
public void setValue(Object value) {
getPropertyMap().put(key, (String)value);
}
@Override
public boolean hasValue() {
return getPropertyMap().get(key) != null;
}
}
}
private class OwnerListModel extends AbstractListModel {
List<Selectable> ownerList = new ArrayList<Selectable>();
public OwnerListModel() {
List<String> list = new ArrayList<String>();
Set<String> ownerSet = token.getOwners();
list.addAll(ownerSet);
ObservableList<Player> playerList = MapTool.getPlayerList();
for (Object item : playerList) {
Player player = (Player) item;
String playerId = player.getName();
if (!list.contains(playerId)) {
list.add(playerId);
}
}
Collections.sort(list);
for (String id : list) {
Selectable selectable = new DefaultSelectable(id);
selectable.setSelected(ownerSet.contains(id));
ownerList.add(selectable);
}
}
public Object getElementAt(int index) {
return ownerList.get(index);
}
public int getSize() {
return ownerList.size();
}
}
private static class MacroTableModel extends AbstractTableModel {
private Association<String, String> newRow = new Association<String, String>("", "");
private List<MacroButtonProperties> macroList;
private Token token;
public MacroTableModel(Token token) {
this(token, false);
}
public MacroTableModel(Token token, boolean clearList) {
this.token = token;
if (clearList){
macroList = new ArrayList<MacroButtonProperties>();
} else {
this.macroList = token.getMacroList(true);
}
Collections.sort(this.macroList);
}
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return macroList.size() + 1;
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex == getRowCount() - 1) {
switch(columnIndex) {
case 0: return newRow.getLeft();
case 1: return newRow.getRight();
}
return "";
}
switch (columnIndex) {
case 0: return macroList.get(rowIndex).getLabel();
case 1: return macroList.get(rowIndex).getCommand();
}
return "";
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (rowIndex == getRowCount() - 1) {
switch(columnIndex) {
case 0: newRow.setLeft((String)aValue); break;
case 1: newRow.setRight((String)aValue); break;
}
MacroButtonProperties newMacro = new MacroButtonProperties(token.getMacroNextIndex());
newMacro.setLabel(newRow.getLeft());
newMacro.setCommand(newRow.getRight());
newMacro.setApplyToTokens(true);
macroList.add(newMacro);
newRow = new Association<String, String>("", "");
return;
}
switch(columnIndex) {
case 0: macroList.get(rowIndex).setLabel((String)aValue); break;
case 1: macroList.get(rowIndex).setCommand((String)aValue); break;
}
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0: return "Label";
case 1: return "Command";
}
return "";
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
public List<MacroButtonProperties> getMacroList() {
return macroList;
}
}
private static class SpeechTableModel extends KeyValueTableModel {
public SpeechTableModel(Token token) {
List<Association<String, String>> rowList = new ArrayList<Association<String, String>>();
for (String speechName : token.getSpeechNames()) {
rowList.add(new Association<String, String>(speechName, token.getSpeech(speechName)));
}
Collections.sort(rowList, new Comparator<Association<String, String>>() {
public int compare(Association<String, String> o1, Association<String, String> o2) {
return o1.getLeft().compareToIgnoreCase(o2.getLeft());
}
});
init(rowList);
}
public SpeechTableModel() {
init(new ArrayList<Association<String, String>>());
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0: return "ID";
case 1: return "Speech Text";
}
return "";
}
}
private static class KeyValueTableModel extends AbstractTableModel {
private Association<String, String> newRow = new Association<String, String>("", "");
private List<Association<String, String>> rowList;
protected void init(List<Association<String, String>> rowList) {
this.rowList = rowList;
}
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return rowList.size() + 1;
}
public Object getValueAt(int rowIndex, int columnIndex) {
if (rowIndex == getRowCount() - 1) {
switch(columnIndex) {
case 0: return newRow.getLeft();
case 1: return newRow.getRight();
}
return "";
}
switch (columnIndex) {
case 0: return rowList.get(rowIndex).getLeft();
case 1: return rowList.get(rowIndex).getRight();
}
return "";
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (rowIndex == getRowCount() - 1) {
switch(columnIndex) {
case 0: newRow.setLeft((String)aValue); break;
case 1: newRow.setRight((String)aValue); break;
}
rowList.add(newRow);
newRow = new Association<String, String>("", "");
return;
}
switch(columnIndex) {
case 0: rowList.get(rowIndex).setLeft((String)aValue); break;
case 1: rowList.get(rowIndex).setRight((String)aValue); break;
}
}
@Override
public String getColumnName(int column) {
switch (column) {
case 0: return "Key";
case 1: return "Value";
}
return "";
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
public Map<String, String> getMap() {
Map<String, String> map = new HashMap<String, String>();
for (Association<String, String> row : rowList) {
if (row.getLeft() == null || row.getLeft().trim().length() == 0) {
continue;
}
map.put(row.getLeft(), row.getRight());
}
return map;
}
}
}
| true | true | public boolean commit() {
// Commit any in-process edits
if (getMacroTable().isEditing()) {
getMacroTable().getCellEditor().stopCellEditing();
}
if (getSpeechTable().isEditing()) {
getSpeechTable().getCellEditor().stopCellEditing();
}
if (getPropertyTable().isEditing()) {
getPropertyTable().getCellEditor().stopCellEditing();
}
// Commit the changes to the token properties
if (!super.commit()) {
return false;
}
// SIZE
token.setSnapToScale(getSizeCombo().getSelectedIndex() != 0);
if (getSizeCombo().getSelectedIndex() > 0) {
Grid grid = MapTool.getFrame().getCurrentZoneRenderer().getZone().getGrid();
token.setFootprint(grid, (TokenFootprint) getSizeCombo().getSelectedItem());
}
// Other
token.setPropertyType((String)getPropertyTypeCombo().getSelectedItem());
token.setSightType((String)getSightTypeCombo().getSelectedItem());
// Get the states
Component[] stateComponents = getStatesPanel().getComponents();
Component barPanel = null;
for (int j = 0; j < stateComponents.length; j++) {
if ("bar".equals(stateComponents[j].getName())) {
barPanel = stateComponents[j];
continue;
}
Component[] components = ((Container)stateComponents[j]).getComponents();
for (int i = 0; i < components.length; i++) {
JCheckBox cb = (JCheckBox) components[i];
String state = cb.getText();
token.setState(state, cb.isSelected() ? Boolean.TRUE : Boolean.FALSE);
}
} // endfor
// BARS
if (barPanel != null) {
Component[] bars = ((Container)barPanel).getComponents();
for (int i = 0; i < bars.length; i += 2) {
JCheckBox cb = (JCheckBox)((Container)bars[i]).getComponent(1);
JSlider bar = (JSlider) bars[i + 1];
BigDecimal value = cb.isSelected() ? null : new BigDecimal(bar.getValue()).divide(new BigDecimal(100));
token.setState(bar.getName(), value);
bar.setValue((int)(TokenBarFunction.getBigDecimalValue(token.getState(bar.getName())).doubleValue() * 100));
}
}
// Ownership
token.clearAllOwners();
for (int i = 0; i < getOwnerList().getModel().getSize(); i++) {
DefaultSelectable selectable = (DefaultSelectable) getOwnerList().getModel().getElementAt(i);
if (selectable.isSelected()) {
token.addOwner((String) selectable.getObject());
}
}
// SHAPE
token.setShape((Token.TokenShape)getShapeCombo().getSelectedItem());
// Macros
token.replaceMacroList(((MacroTableModel)getMacroTable().getModel()).getMacroList());
token.setSpeechMap(((KeyValueTableModel)getSpeechTable().getModel()).getMap());
// Properties
((TokenPropertyTableModel)getPropertyTable().getModel()).applyTo(token);
// Charsheet
token.setCharsheetImage(getCharSheetPanel().getImageId());
if (token.getCharsheetImage() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(token.getCharsheetImage())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getCharsheetImage()));
}
}
// IMAGE
if (!token.getImageAssetId().equals(getTokenIconPanel().getImageId())) {
MapToolUtil.uploadAsset(AssetManager.getAsset(getTokenIconPanel().getImageId()));
token.setImageAsset(null, getTokenIconPanel().getImageId()); // Default image for now
}
// PORTRAIT
if (getPortraitPanel().getImageId() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(token.getPortraitImage())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getPortraitImage()));
}
}
token.setPortraitImage(getPortraitPanel().getImageId());
// LAYOUT
token.setSizeScale(getTokenLayoutPanel().getSizeScale());
token.setAnchor(getTokenLayoutPanel().getAnchorX(), getTokenLayoutPanel().getAnchorY());
// OTHER
tokenSaved = true;
// // Character Sheet
// Map<String, Object> properties = controller.getData();
// for (String prop : token.getPropertyNames())
// token.setProperty(prop, properties.get(prop));
// Update UI
MapTool.getFrame().updateTokenTree();
MapTool.getFrame().resetTokenPanels();
return true;
}
| public boolean commit() {
// Commit any in-process edits
if (getMacroTable().isEditing()) {
getMacroTable().getCellEditor().stopCellEditing();
}
if (getSpeechTable().isEditing()) {
getSpeechTable().getCellEditor().stopCellEditing();
}
if (getPropertyTable().isEditing()) {
getPropertyTable().getCellEditor().stopCellEditing();
}
// Commit the changes to the token properties
if (!super.commit()) {
return false;
}
// SIZE
token.setSnapToScale(getSizeCombo().getSelectedIndex() != 0);
if (getSizeCombo().getSelectedIndex() > 0) {
Grid grid = MapTool.getFrame().getCurrentZoneRenderer().getZone().getGrid();
token.setFootprint(grid, (TokenFootprint) getSizeCombo().getSelectedItem());
}
// Other
token.setPropertyType((String)getPropertyTypeCombo().getSelectedItem());
token.setSightType((String)getSightTypeCombo().getSelectedItem());
// Get the states
Component[] stateComponents = getStatesPanel().getComponents();
Component barPanel = null;
for (int j = 0; j < stateComponents.length; j++) {
if ("bar".equals(stateComponents[j].getName())) {
barPanel = stateComponents[j];
continue;
}
Component[] components = ((Container)stateComponents[j]).getComponents();
for (int i = 0; i < components.length; i++) {
JCheckBox cb = (JCheckBox) components[i];
String state = cb.getText();
token.setState(state, cb.isSelected() ? Boolean.TRUE : Boolean.FALSE);
}
} // endfor
// BARS
if (barPanel != null) {
Component[] bars = ((Container)barPanel).getComponents();
for (int i = 0; i < bars.length; i += 2) {
JCheckBox cb = (JCheckBox)((Container)bars[i]).getComponent(1);
JSlider bar = (JSlider) bars[i + 1];
BigDecimal value = cb.isSelected() ? null : new BigDecimal(bar.getValue()).divide(new BigDecimal(100));
token.setState(bar.getName(), value);
bar.setValue((int)(TokenBarFunction.getBigDecimalValue(token.getState(bar.getName())).doubleValue() * 100));
}
}
// Ownership
token.clearAllOwners();
for (int i = 0; i < getOwnerList().getModel().getSize(); i++) {
DefaultSelectable selectable = (DefaultSelectable) getOwnerList().getModel().getElementAt(i);
if (selectable.isSelected()) {
token.addOwner((String) selectable.getObject());
}
}
// SHAPE
token.setShape((Token.TokenShape)getShapeCombo().getSelectedItem());
// Macros
token.replaceMacroList(((MacroTableModel)getMacroTable().getModel()).getMacroList());
token.setSpeechMap(((KeyValueTableModel)getSpeechTable().getModel()).getMap());
// Properties
((TokenPropertyTableModel)getPropertyTable().getModel()).applyTo(token);
// Charsheet
token.setCharsheetImage(getCharSheetPanel().getImageId());
if (token.getCharsheetImage() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(token.getCharsheetImage())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(token.getCharsheetImage()));
}
}
// IMAGE
if (!token.getImageAssetId().equals(getTokenIconPanel().getImageId())) {
MapToolUtil.uploadAsset(AssetManager.getAsset(getTokenIconPanel().getImageId()));
token.setImageAsset(null, getTokenIconPanel().getImageId()); // Default image for now
}
// PORTRAIT
if (getPortraitPanel().getImageId() != null) {
// Make sure the server has the image
if (!MapTool.getCampaign().containsAsset(getPortraitPanel().getImageId())) {
MapTool.serverCommand().putAsset(AssetManager.getAsset(getPortraitPanel().getImageId()));
}
}
token.setPortraitImage(getPortraitPanel().getImageId());
// LAYOUT
token.setSizeScale(getTokenLayoutPanel().getSizeScale());
token.setAnchor(getTokenLayoutPanel().getAnchorX(), getTokenLayoutPanel().getAnchorY());
// OTHER
tokenSaved = true;
// // Character Sheet
// Map<String, Object> properties = controller.getData();
// for (String prop : token.getPropertyNames())
// token.setProperty(prop, properties.get(prop));
// Update UI
MapTool.getFrame().updateTokenTree();
MapTool.getFrame().resetTokenPanels();
return true;
}
|
diff --git a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdater.java b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdater.java
index 6d1a767a0..1dad876de 100644
--- a/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdater.java
+++ b/bundles/org.eclipse.equinox.p2.ui.sdk.scheduler/src/org/eclipse/equinox/internal/p2/ui/sdk/scheduler/AutomaticUpdater.java
@@ -1,511 +1,506 @@
/*******************************************************************************
* Copyright (c) 2008 IBM Corporation and others.
* 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.internal.p2.ui.sdk.scheduler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.EventObject;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.jobs.*;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus;
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.ProvisioningListener;
import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest;
import org.eclipse.equinox.internal.provisional.p2.engine.*;
import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.internal.provisional.p2.ui.*;
import org.eclipse.equinox.internal.provisional.p2.ui.model.Updates;
import org.eclipse.equinox.internal.provisional.p2.ui.operations.*;
import org.eclipse.equinox.internal.provisional.p2.ui.policy.Policy;
import org.eclipse.equinox.internal.provisional.p2.updatechecker.IUpdateListener;
import org.eclipse.equinox.internal.provisional.p2.updatechecker.UpdateEvent;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.*;
import org.eclipse.ui.progress.WorkbenchJob;
import org.eclipse.ui.statushandlers.StatusManager;
/**
* @since 3.5
*/
public class AutomaticUpdater implements IUpdateListener {
StatusLineCLabelContribution updateAffordance;
AutomaticUpdateAction updateAction;
IStatusLineManager statusLineManager;
IInstallableUnit[] iusWithUpdates;
String profileId;
AutomaticUpdatesPopup popup;
ProvisioningListener profileChangeListener;
IJobChangeListener provisioningJobListener;
boolean alreadyValidated = false;
boolean alreadyDownloaded = false;
private static final String AUTO_UPDATE_STATUS_ITEM = "AutoUpdatesStatus"; //$NON-NLS-1$
public AutomaticUpdater() {
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.equinox.internal.provisional.p2.updatechecker.IUpdateListener
* #
* updatesAvailable(org.eclipse.equinox.internal.provisional.p2.updatechecker
* .UpdateEvent)
*/
public void updatesAvailable(final UpdateEvent event) {
final boolean download = getPreferenceStore().getBoolean(
PreferenceConstants.PREF_DOWNLOAD_ONLY);
profileId = event.getProfileId();
iusWithUpdates = event.getIUs();
validateUpdates(null, true);
alreadyDownloaded = false;
if (iusWithUpdates.length <= 0) {
clearUpdatesAvailable();
return;
}
registerProfileChangeListener();
registerProvisioningJobListener();
// Download the items if the preference dictates before
// showing the user that updates are available.
try {
if (download) {
ElementQueryDescriptor descriptor = Policy.getDefault()
.getQueryProvider().getQueryDescriptor(
new Updates(event.getProfileId(), event
.getIUs()));
IInstallableUnit[] replacements = (IInstallableUnit[]) descriptor.queryable
.query(descriptor.query, descriptor.collector, null)
.toArray(IInstallableUnit.class);
if (replacements.length > 0) {
ProfileChangeRequest request = ProfileChangeRequest
.createByProfileId(event.getProfileId());
request.removeInstallableUnits(iusWithUpdates);
request.addInstallableUnits(replacements);
final PlannerResolutionOperation operation = new PlannerResolutionOperation(
AutomaticUpdateMessages.AutomaticUpdater_ResolutionOperationLabel, iusWithUpdates,
event.getProfileId(), request, new MultiStatus(
AutomaticUpdatePlugin.PLUGIN_ID, 0, null,
null), false);
if ((operation.execute(new NullProgressMonitor())).isOK()) {
Job job = ProvisioningOperationRunner
.schedule(
new ProfileModificationOperation(
AutomaticUpdateMessages.AutomaticUpdater_AutomaticDownloadOperationName,
event.getProfileId(), operation
.getProvisioningPlan(),
new DownloadPhaseSet(), false),
StatusManager.LOG);
job.addJobChangeListener(new JobChangeAdapter() {
public void done(IJobChangeEvent jobEvent) {
alreadyDownloaded = true;
IStatus status = jobEvent.getResult();
if (status.isOK()) {
createUpdateAction();
PlatformUI.getWorkbench().getDisplay()
.asyncExec(new Runnable() {
public void run() {
updateAction
.suppressWizard(true);
- updateAction
- .performAction(
- iusWithUpdates,
- event
- .getProfileId(),
- operation);
+ updateAction.run();
}
});
} else if (status.getSeverity() != IStatus.CANCEL) {
ProvUI.reportStatus(status,
StatusManager.LOG);
}
}
});
}
}
} else {
createUpdateAction();
PlatformUI.getWorkbench().getDisplay().asyncExec(
new Runnable() {
public void run() {
updateAction.suppressWizard(true);
updateAction.run();
}
});
}
} catch (ProvisionException e) {
ProvUI
.handleException(
e,
AutomaticUpdateMessages.AutomaticUpdater_ErrorCheckingUpdates,
StatusManager.LOG);
}
}
/*
* Validate that iusToBeUpdated is valid, and reset the cache. If
* isKnownToBeAvailable is false, then recheck that the update is available.
* isKnownToBeAvailable should be false when the update list might be stale
* (Reminding the user of updates may happen long after the update check.
* This reduces the risk of notifying the user of updates and then not
* finding them .)
*/
void validateUpdates(IProgressMonitor monitor, boolean isKnownToBeAvailable) {
ArrayList list = new ArrayList();
for (int i = 0; i < iusWithUpdates.length; i++) {
try {
if (isKnownToBeAvailable
|| ProvisioningUtil.getPlanner().updatesFor(
iusWithUpdates[i], new ProvisioningContext(),
monitor).length > 0) {
if (validToUpdate(iusWithUpdates[i]))
list.add(iusWithUpdates[i]);
}
} catch (ProvisionException e) {
ProvUI
.handleException(
e,
AutomaticUpdateMessages.AutomaticUpdater_ErrorCheckingUpdates,
StatusManager.LOG);
continue;
} catch (OperationCanceledException e) {
// Nothing to report
}
}
iusWithUpdates = (IInstallableUnit[]) list
.toArray(new IInstallableUnit[list.size()]);
}
// A proposed update is valid if it is still visible to the user as an
// installed item (it is a root)
// and if it is not locked for updating.
private boolean validToUpdate(IInstallableUnit iu) {
int lock = IInstallableUnit.LOCK_NONE;
boolean isRoot = false;
try {
IProfile profile = ProvisioningUtil.getProfile(profileId);
String value = profile.getInstallableUnitProperty(iu,
IInstallableUnit.PROP_PROFILE_LOCKED_IU);
if (value != null)
lock = Integer.parseInt(value);
value = profile.getInstallableUnitProperty(iu,
IInstallableUnit.PROP_PROFILE_ROOT_IU);
isRoot = value == null ? false : Boolean.valueOf(value)
.booleanValue();
} catch (ProvisionException e) {
// ignore
} catch (NumberFormatException e) {
// ignore and assume no lock
}
return isRoot && (lock & IInstallableUnit.LOCK_UPDATE) == 0;
}
Shell getWorkbenchWindowShell() {
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
return activeWindow != null ? activeWindow.getShell() : null;
}
IStatusLineManager getStatusLineManager() {
if (statusLineManager != null)
return statusLineManager;
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
if (activeWindow == null)
return null;
// YUCK! YUCK! YUCK!
// IWorkbenchWindow does not define getStatusLineManager(), yet
// WorkbenchWindow does
try {
Method method = activeWindow.getClass().getDeclaredMethod(
"getStatusLineManager", new Class[0]); //$NON-NLS-1$
try {
Object statusLine = method.invoke(activeWindow, new Object[0]);
if (statusLine instanceof IStatusLineManager) {
statusLineManager = (IStatusLineManager) statusLine;
return statusLineManager;
}
} catch (InvocationTargetException e) {
// oh well
} catch (IllegalAccessException e) {
// I tried
}
} catch (NoSuchMethodException e) {
// can't blame us for trying.
}
IWorkbenchPartSite site = activeWindow.getActivePage().getActivePart()
.getSite();
if (site instanceof IViewSite) {
statusLineManager = ((IViewSite) site).getActionBars()
.getStatusLineManager();
} else if (site instanceof IEditorSite) {
statusLineManager = ((IEditorSite) site).getActionBars()
.getStatusLineManager();
}
return statusLineManager;
}
void updateStatusLine() {
IStatusLineManager manager = getStatusLineManager();
if (manager != null)
manager.update(true);
}
void createUpdateAffordance() {
updateAffordance = new StatusLineCLabelContribution(
AUTO_UPDATE_STATUS_ITEM, 5);
updateAffordance.addListener(SWT.MouseDown, new Listener() {
public void handleEvent(Event event) {
launchUpdate();
}
});
IStatusLineManager manager = getStatusLineManager();
if (manager != null) {
manager.add(updateAffordance);
manager.update(true);
}
}
void setUpdateAffordanceState(boolean isValid) {
if (updateAffordance == null)
return;
if (isValid) {
updateAffordance
.setTooltip(AutomaticUpdateMessages.AutomaticUpdater_ClickToReviewUpdates);
updateAffordance.setImage(ProvUIImages
.getImage(ProvUIImages.IMG_TOOL_UPDATE));
} else {
updateAffordance
.setTooltip(AutomaticUpdateMessages.AutomaticUpdater_ClickToReviewUpdatesWithProblems);
updateAffordance.setImage(ProvUIImages
.getImage(ProvUIImages.IMG_TOOL_UPDATE_PROBLEMS));
}
IStatusLineManager manager = getStatusLineManager();
if (manager != null) {
manager.update(true);
}
}
void checkUpdateAffordanceEnablement() {
// We don't currently support enablement in the affordance,
// so we hide it if it should not be enabled.
if (updateAffordance == null)
return;
boolean shouldBeVisible = !ProvisioningOperationRunner
.hasScheduledOperations();
if (updateAffordance.isVisible() != shouldBeVisible) {
IStatusLineManager manager = getStatusLineManager();
if (manager != null) {
updateAffordance.setVisible(shouldBeVisible);
manager.update(true);
}
}
}
void createUpdatePopup() {
popup = new AutomaticUpdatesPopup(getWorkbenchWindowShell(),
alreadyDownloaded, getPreferenceStore());
popup.open();
}
void createUpdateAction() {
if (updateAction == null)
updateAction = new AutomaticUpdateAction(this,
getSelectionProvider(), profileId);
}
void clearUpdatesAvailable() {
if (updateAffordance != null) {
IStatusLineManager manager = getStatusLineManager();
if (manager != null) {
manager.remove(updateAffordance);
manager.update(true);
}
updateAffordance.dispose();
updateAffordance = null;
}
if (popup != null) {
popup.close(false);
popup = null;
}
alreadyValidated = false;
}
ISelectionProvider getSelectionProvider() {
return new ISelectionProvider() {
/*
* (non-Javadoc)
*
* @seeorg.eclipse.jface.viewers.ISelectionProvider#
* addSelectionChangedListener
* (org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addSelectionChangedListener(
ISelectionChangedListener listener) {
// Ignore because the selection won't change
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
return new StructuredSelection(iusWithUpdates);
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.jface.viewers.ISelectionProvider#
* removeSelectionChangedListener
* (org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removeSelectionChangedListener(
ISelectionChangedListener listener) {
// ignore because the selection is static
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.viewers.ISelectionProvider#setSelection(org
* .eclipse.jface.viewers.ISelection)
*/
public void setSelection(ISelection sel) {
throw new UnsupportedOperationException(
"This ISelectionProvider is static, and cannot be modified."); //$NON-NLS-1$
}
};
}
public void launchUpdate() {
alreadyValidated = true;
updateAction.suppressWizard(false);
updateAction.run();
}
private void registerProfileChangeListener() {
if (profileChangeListener == null) {
profileChangeListener = new ProvisioningListener() {
public void notify(EventObject o) {
if (o instanceof ProfileEvent) {
ProfileEvent event = (ProfileEvent) o;
if (event.getReason() == ProfileEvent.CHANGED
&& profileId.equals(event.getProfileId())) {
validateUpdates();
}
}
}
};
IProvisioningEventBus bus = AutomaticUpdatePlugin.getDefault()
.getProvisioningEventBus();
if (bus != null)
bus.addListener(profileChangeListener);
}
}
private void registerProvisioningJobListener() {
if (provisioningJobListener == null) {
provisioningJobListener = new JobChangeAdapter() {
public void done(IJobChangeEvent event) {
IWorkbench workbench = PlatformUI.getWorkbench();
if (workbench == null || workbench.isClosing())
return;
if (workbench.getDisplay() == null)
return;
workbench.getDisplay().asyncExec(new Runnable() {
public void run() {
checkUpdateAffordanceEnablement();
}
});
}
public void scheduled(final IJobChangeEvent event) {
IWorkbench workbench = PlatformUI.getWorkbench();
if (workbench == null || workbench.isClosing())
return;
if (workbench.getDisplay() == null)
return;
workbench.getDisplay().asyncExec(new Runnable() {
public void run() {
checkUpdateAffordanceEnablement();
}
});
}
};
ProvisioningOperationRunner
.addJobChangeListener(provisioningJobListener);
}
}
/*
* The profile has changed. Make sure our toUpdate list is still valid and
* if there is nothing to update, get rid of the update popup and
* affordance.
*/
void validateUpdates() {
Job validateJob = new WorkbenchJob("Update validate job") { //$NON-NLS-1$
public IStatus runInUIThread(IProgressMonitor monitor) {
if (monitor.isCanceled())
return Status.CANCEL_STATUS;
validateUpdates(monitor, false);
if (iusWithUpdates.length == 0)
clearUpdatesAvailable();
else {
createUpdateAction();
updateAction.suppressWizard(true);
updateAction.run();
}
return Status.OK_STATUS;
}
};
validateJob.setSystem(true);
validateJob.setPriority(Job.SHORT);
validateJob.schedule();
}
public void shutdown() {
if (provisioningJobListener != null) {
ProvisioningOperationRunner
.removeJobChangeListener(provisioningJobListener);
provisioningJobListener = null;
}
if (profileChangeListener == null)
return;
IProvisioningEventBus bus = AutomaticUpdatePlugin.getDefault()
.getProvisioningEventBus();
if (bus != null)
bus.removeListener(profileChangeListener);
profileChangeListener = null;
statusLineManager = null;
}
IPreferenceStore getPreferenceStore() {
return AutomaticUpdatePlugin.getDefault().getPreferenceStore();
}
}
| true | true | public void updatesAvailable(final UpdateEvent event) {
final boolean download = getPreferenceStore().getBoolean(
PreferenceConstants.PREF_DOWNLOAD_ONLY);
profileId = event.getProfileId();
iusWithUpdates = event.getIUs();
validateUpdates(null, true);
alreadyDownloaded = false;
if (iusWithUpdates.length <= 0) {
clearUpdatesAvailable();
return;
}
registerProfileChangeListener();
registerProvisioningJobListener();
// Download the items if the preference dictates before
// showing the user that updates are available.
try {
if (download) {
ElementQueryDescriptor descriptor = Policy.getDefault()
.getQueryProvider().getQueryDescriptor(
new Updates(event.getProfileId(), event
.getIUs()));
IInstallableUnit[] replacements = (IInstallableUnit[]) descriptor.queryable
.query(descriptor.query, descriptor.collector, null)
.toArray(IInstallableUnit.class);
if (replacements.length > 0) {
ProfileChangeRequest request = ProfileChangeRequest
.createByProfileId(event.getProfileId());
request.removeInstallableUnits(iusWithUpdates);
request.addInstallableUnits(replacements);
final PlannerResolutionOperation operation = new PlannerResolutionOperation(
AutomaticUpdateMessages.AutomaticUpdater_ResolutionOperationLabel, iusWithUpdates,
event.getProfileId(), request, new MultiStatus(
AutomaticUpdatePlugin.PLUGIN_ID, 0, null,
null), false);
if ((operation.execute(new NullProgressMonitor())).isOK()) {
Job job = ProvisioningOperationRunner
.schedule(
new ProfileModificationOperation(
AutomaticUpdateMessages.AutomaticUpdater_AutomaticDownloadOperationName,
event.getProfileId(), operation
.getProvisioningPlan(),
new DownloadPhaseSet(), false),
StatusManager.LOG);
job.addJobChangeListener(new JobChangeAdapter() {
public void done(IJobChangeEvent jobEvent) {
alreadyDownloaded = true;
IStatus status = jobEvent.getResult();
if (status.isOK()) {
createUpdateAction();
PlatformUI.getWorkbench().getDisplay()
.asyncExec(new Runnable() {
public void run() {
updateAction
.suppressWizard(true);
updateAction
.performAction(
iusWithUpdates,
event
.getProfileId(),
operation);
}
});
} else if (status.getSeverity() != IStatus.CANCEL) {
ProvUI.reportStatus(status,
StatusManager.LOG);
}
}
});
}
}
} else {
createUpdateAction();
PlatformUI.getWorkbench().getDisplay().asyncExec(
new Runnable() {
public void run() {
updateAction.suppressWizard(true);
updateAction.run();
}
});
}
} catch (ProvisionException e) {
ProvUI
.handleException(
e,
AutomaticUpdateMessages.AutomaticUpdater_ErrorCheckingUpdates,
StatusManager.LOG);
}
}
| public void updatesAvailable(final UpdateEvent event) {
final boolean download = getPreferenceStore().getBoolean(
PreferenceConstants.PREF_DOWNLOAD_ONLY);
profileId = event.getProfileId();
iusWithUpdates = event.getIUs();
validateUpdates(null, true);
alreadyDownloaded = false;
if (iusWithUpdates.length <= 0) {
clearUpdatesAvailable();
return;
}
registerProfileChangeListener();
registerProvisioningJobListener();
// Download the items if the preference dictates before
// showing the user that updates are available.
try {
if (download) {
ElementQueryDescriptor descriptor = Policy.getDefault()
.getQueryProvider().getQueryDescriptor(
new Updates(event.getProfileId(), event
.getIUs()));
IInstallableUnit[] replacements = (IInstallableUnit[]) descriptor.queryable
.query(descriptor.query, descriptor.collector, null)
.toArray(IInstallableUnit.class);
if (replacements.length > 0) {
ProfileChangeRequest request = ProfileChangeRequest
.createByProfileId(event.getProfileId());
request.removeInstallableUnits(iusWithUpdates);
request.addInstallableUnits(replacements);
final PlannerResolutionOperation operation = new PlannerResolutionOperation(
AutomaticUpdateMessages.AutomaticUpdater_ResolutionOperationLabel, iusWithUpdates,
event.getProfileId(), request, new MultiStatus(
AutomaticUpdatePlugin.PLUGIN_ID, 0, null,
null), false);
if ((operation.execute(new NullProgressMonitor())).isOK()) {
Job job = ProvisioningOperationRunner
.schedule(
new ProfileModificationOperation(
AutomaticUpdateMessages.AutomaticUpdater_AutomaticDownloadOperationName,
event.getProfileId(), operation
.getProvisioningPlan(),
new DownloadPhaseSet(), false),
StatusManager.LOG);
job.addJobChangeListener(new JobChangeAdapter() {
public void done(IJobChangeEvent jobEvent) {
alreadyDownloaded = true;
IStatus status = jobEvent.getResult();
if (status.isOK()) {
createUpdateAction();
PlatformUI.getWorkbench().getDisplay()
.asyncExec(new Runnable() {
public void run() {
updateAction
.suppressWizard(true);
updateAction.run();
}
});
} else if (status.getSeverity() != IStatus.CANCEL) {
ProvUI.reportStatus(status,
StatusManager.LOG);
}
}
});
}
}
} else {
createUpdateAction();
PlatformUI.getWorkbench().getDisplay().asyncExec(
new Runnable() {
public void run() {
updateAction.suppressWizard(true);
updateAction.run();
}
});
}
} catch (ProvisionException e) {
ProvUI
.handleException(
e,
AutomaticUpdateMessages.AutomaticUpdater_ErrorCheckingUpdates,
StatusManager.LOG);
}
}
|
diff --git a/src/me/drton/flightplot/export/ExportRunner.java b/src/me/drton/flightplot/export/ExportRunner.java
index 5488e1c..616cc3d 100644
--- a/src/me/drton/flightplot/export/ExportRunner.java
+++ b/src/me/drton/flightplot/export/ExportRunner.java
@@ -1,69 +1,74 @@
package me.drton.flightplot.export;
import me.drton.flightplot.FormatErrorException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/**
* Created by ada on 19.01.14.
*/
public class ExportRunner implements Runnable {
private TrackReader reader;
private TrackExporter exporter;
private String statusMessage;
private Runnable finishedCallback;
private File destination;
public ExportRunner(TrackReader reader, TrackExporter exporter, File destination){
this.reader = reader;
this.exporter = exporter;
this.destination = destination;
}
@Override
public void run() {
try{
doExport(this.destination);
} catch (Exception e) {
this.statusMessage = "Error: " + e;
e.printStackTrace();
}
finish();
}
private void finish(){
if(null != this.finishedCallback){
this.finishedCallback.run();
}
}
private void doExport(File exportFile) throws IOException, FormatErrorException {
// get time of first point to use it as track title
- // TODO: < does this work if there was no GPS fix in the beginning?
TrackPoint point = this.reader.readNextPoint();
this.reader.reset();
- DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String trackTitle = dateFormat.format(point.time) + " UTC";
- this.exporter.exportToFile(exportFile, trackTitle);
- this.statusMessage =
- String.format("Successfully exported track %s to %s", trackTitle, exportFile.getAbsoluteFile());
+ if(null != point){
+ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ String trackTitle = dateFormat.format(point.time) + " UTC";
+ this.exporter.exportToFile(exportFile, trackTitle);
+ this.statusMessage =
+ String.format("Successfully exported track %s to %s", trackTitle, exportFile.getAbsoluteFile());
+ }
+ else {
+ this.statusMessage =
+ String.format("Couldn't find any data to export");
+ }
}
public String getStatusMessage() {
return statusMessage;
}
public void setFinishedCallback(Runnable finishedCallback) {
this.finishedCallback = finishedCallback;
}
}
| false | true | private void doExport(File exportFile) throws IOException, FormatErrorException {
// get time of first point to use it as track title
// TODO: < does this work if there was no GPS fix in the beginning?
TrackPoint point = this.reader.readNextPoint();
this.reader.reset();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String trackTitle = dateFormat.format(point.time) + " UTC";
this.exporter.exportToFile(exportFile, trackTitle);
this.statusMessage =
String.format("Successfully exported track %s to %s", trackTitle, exportFile.getAbsoluteFile());
}
| private void doExport(File exportFile) throws IOException, FormatErrorException {
// get time of first point to use it as track title
TrackPoint point = this.reader.readNextPoint();
this.reader.reset();
if(null != point){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String trackTitle = dateFormat.format(point.time) + " UTC";
this.exporter.exportToFile(exportFile, trackTitle);
this.statusMessage =
String.format("Successfully exported track %s to %s", trackTitle, exportFile.getAbsoluteFile());
}
else {
this.statusMessage =
String.format("Couldn't find any data to export");
}
}
|
diff --git a/src/de/andreasgiemza/jgeagle/JGeagle.java b/src/de/andreasgiemza/jgeagle/JGeagle.java
index 1cfaa46..b74d3a9 100644
--- a/src/de/andreasgiemza/jgeagle/JGeagle.java
+++ b/src/de/andreasgiemza/jgeagle/JGeagle.java
@@ -1,510 +1,510 @@
/*
* The MIT License
*
* Copyright 2013 Andreas Giemza.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.andreasgiemza.jgeagle;
import de.andreasgiemza.jgeagle.repo.data.EagleFile;
import de.andreasgiemza.jgeagle.gui.EagleFilesTree;
import de.andreasgiemza.jgeagle.gui.CommitsTables;
import de.andreasgiemza.jgeagle.gui.SheetsAndDiffImage;
import de.andreasgiemza.jgeagle.options.Options;
import de.andreasgiemza.jgeagle.panels.AboutPanel;
import de.andreasgiemza.jgeagle.panels.CreateImagesPanel;
import de.andreasgiemza.jgeagle.panels.DeleteImagesPanel;
import de.andreasgiemza.jgeagle.panels.PreferencesPanel;
import de.andreasgiemza.jgeagle.repo.Repo;
import java.awt.Toolkit;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.revwalk.RevCommit;
/**
*
* @author Andreas Giemza
*/
public class JGeagle extends javax.swing.JFrame {
private final Options options;
private final EagleFilesTree eagleFilesTree;
private final CommitsTables commitsTables;
private final SheetsAndDiffImage sheetsAndDiffImage;
private Repo repo;
/**
* Creates new form JGeagle
*/
public JGeagle() {
initComponents();
setLocation(new Double((Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2) - (this.getWidth() / 2)).intValue(),
new Double((Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2) - (this.getHeight() / 2)).intValue());
options = new Options();
eagleFilesTree = new EagleFilesTree(this, eagleFilesJTree);
commitsTables = new CommitsTables(this, oldCommitsTable, newCommitsTable);
sheetsAndDiffImage = new SheetsAndDiffImage(
options,
sheetComboBox,
sheetButton,
diffImageButton);
}
public void eagleFileSelected(EagleFile eagleFile) {
if (eagleFile == null) {
commitsTables.reset();
return;
}
repo.getEagleFileLogAndStatus(options, eagleFile);
commitsTables.updateOldCommitsTable(eagleFile);
commitsTables.resetNewCommitsTable();
sheetsAndDiffImage.reset();
}
public void oldCommitSelected(EagleFile eagleFile, RevCommit oldCommit) {
commitsTables.updateNewCommitsTable(eagleFile, oldCommit);
sheetsAndDiffImage.reset();
}
public void newCommitSelected(
EagleFile eagleFile,
RevCommit oldCommit,
RevCommit newCommit) {
options.cleanTempDir();
if (eagleFile.getFileExtension().equals(EagleFile.BRD)) {
sheetsAndDiffImage.brdSelected();
} else {
sheetsAndDiffImage.schSelected(repo, eagleFile, oldCommit, newCommit);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
repositoryFileChooser = new javax.swing.JFileChooser();
eagleFilesPanel = new javax.swing.JPanel();
eagleFilesScrollPane = new javax.swing.JScrollPane();
eagleFilesJTree = new javax.swing.JTree();
eagleFilesExpandAllButton = new javax.swing.JButton();
eagleFilesCollapseAllButton = new javax.swing.JButton();
commitsPanel = new javax.swing.JPanel();
oldCommitsPanel = new javax.swing.JPanel();
oldCommitsScrollPane = new javax.swing.JScrollPane();
oldCommitsTable = new javax.swing.JTable();
newCommitsPanel = new javax.swing.JPanel();
newCommitsScrollPane = new javax.swing.JScrollPane();
newCommitsTable = new javax.swing.JTable();
variousPanel = new javax.swing.JPanel();
sheetPanel = new javax.swing.JPanel();
sheetButton = new javax.swing.JButton();
sheetComboBox = new javax.swing.JComboBox();
diffImagePanel = new javax.swing.JPanel();
diffImageButton = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
repositoryMenu = new javax.swing.JMenu();
repositoryMenuItem = new javax.swing.JMenuItem();
toolsMenu = new javax.swing.JMenu();
createImagesMenuItem = new javax.swing.JMenuItem();
deleteImagesMenuItem = new javax.swing.JMenuItem();
optionsMenu = new javax.swing.JMenu();
preferencesMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenuItem = new javax.swing.JMenuItem();
repositoryFileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("JGeagle");
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("de/andreasgiemza/jgeagle/gui/icons/jgeagle.png")));
eagleFilesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Files"));
eagleFilesJTree.setModel(null);
eagleFilesScrollPane.setViewportView(eagleFilesJTree);
eagleFilesExpandAllButton.setText("Expand all");
eagleFilesExpandAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eagleFilesExpandAllButtonActionPerformed(evt);
}
});
eagleFilesCollapseAllButton.setText("Collapse all");
eagleFilesCollapseAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eagleFilesCollapseAllButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout eagleFilesPanelLayout = new javax.swing.GroupLayout(eagleFilesPanel);
eagleFilesPanel.setLayout(eagleFilesPanelLayout);
eagleFilesPanelLayout.setHorizontalGroup(
eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(eagleFilesPanelLayout.createSequentialGroup()
.addComponent(eagleFilesScrollPane)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(eagleFilesExpandAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(eagleFilesCollapseAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)))
);
eagleFilesPanelLayout.setVerticalGroup(
eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(eagleFilesPanelLayout.createSequentialGroup()
.addComponent(eagleFilesExpandAllButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(eagleFilesCollapseAllButton))
.addComponent(eagleFilesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
);
commitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Commits"));
commitsPanel.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
oldCommitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Old"));
oldCommitsPanel.setLayout(new javax.swing.BoxLayout(oldCommitsPanel, javax.swing.BoxLayout.LINE_AXIS));
oldCommitsTable.setAutoCreateRowSorter(true);
oldCommitsScrollPane.setViewportView(oldCommitsTable);
oldCommitsPanel.add(oldCommitsScrollPane);
commitsPanel.add(oldCommitsPanel);
newCommitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("New"));
newCommitsPanel.setLayout(new javax.swing.BoxLayout(newCommitsPanel, javax.swing.BoxLayout.LINE_AXIS));
newCommitsTable.setAutoCreateRowSorter(true);
newCommitsScrollPane.setViewportView(newCommitsTable);
newCommitsPanel.add(newCommitsScrollPane);
commitsPanel.add(newCommitsPanel);
variousPanel.setLayout(new java.awt.GridLayout(1, 0));
sheetPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Sheet"));
sheetPanel.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
sheetButton.setText("Count");
sheetButton.setEnabled(false);
sheetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sheetButtonActionPerformed(evt);
}
});
sheetPanel.add(sheetButton);
sheetComboBox.setEnabled(false);
sheetPanel.add(sheetComboBox);
variousPanel.add(sheetPanel);
diffImagePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Diff image"));
diffImageButton.setText("Make and/or show");
diffImageButton.setEnabled(false);
diffImageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
diffImageButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout diffImagePanelLayout = new javax.swing.GroupLayout(diffImagePanel);
diffImagePanel.setLayout(diffImagePanelLayout);
diffImagePanelLayout.setHorizontalGroup(
diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(diffImageButton, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
);
diffImagePanelLayout.setVerticalGroup(
diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(diffImageButton)
);
variousPanel.add(diffImagePanel);
repositoryMenu.setText("Repository");
repositoryMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
repositoryMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/open.png"))); // NOI18N
repositoryMenuItem.setText("Open");
repositoryMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
repositoryMenuItemActionPerformed(evt);
}
});
repositoryMenu.add(repositoryMenuItem);
menuBar.add(repositoryMenu);
toolsMenu.setText("Tools");
- createImagesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
+ createImagesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
createImagesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/createimages.png"))); // NOI18N
createImagesMenuItem.setText("Create images");
createImagesMenuItem.setEnabled(false);
createImagesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createImagesMenuItemActionPerformed(evt);
}
});
toolsMenu.add(createImagesMenuItem);
deleteImagesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
deleteImagesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/deleteimages.png"))); // NOI18N
deleteImagesMenuItem.setText("Delete images");
deleteImagesMenuItem.setEnabled(false);
deleteImagesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteImagesMenuItemActionPerformed(evt);
}
});
toolsMenu.add(deleteImagesMenuItem);
menuBar.add(toolsMenu);
optionsMenu.setText("Options");
preferencesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
preferencesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/preferences.png"))); // NOI18N
preferencesMenuItem.setText("Preferences");
preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
preferencesMenuItemActionPerformed(evt);
}
});
optionsMenu.add(preferencesMenuItem);
menuBar.add(optionsMenu);
helpMenu.setText("Help");
- aboutMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
+ aboutMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK));
aboutMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/about.png"))); // NOI18N
aboutMenuItem.setText("About");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutMenuItemActionPerformed(evt);
}
});
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(eagleFilesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(commitsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(variousPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(eagleFilesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commitsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(variousPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void eagleFilesExpandAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eagleFilesExpandAllButtonActionPerformed
eagleFilesTree.expandAll();
}//GEN-LAST:event_eagleFilesExpandAllButtonActionPerformed
private void eagleFilesCollapseAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eagleFilesCollapseAllButtonActionPerformed
eagleFilesTree.collapseAll();
}//GEN-LAST:event_eagleFilesCollapseAllButtonActionPerformed
private void sheetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sheetButtonActionPerformed
sheetsAndDiffImage.countSheets(
repo,
commitsTables.getEagleFile(),
commitsTables.getOldCommit(),
commitsTables.getNewCommit());
}//GEN-LAST:event_sheetButtonActionPerformed
private void diffImageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_diffImageButtonActionPerformed
try {
sheetsAndDiffImage.createDiffImage(
repo,
commitsTables.getEagleFile(),
commitsTables.getOldCommit(),
commitsTables.getNewCommit());
} catch (IOException | InterruptedException ex) {
Logger.getLogger(JGeagle.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_diffImageButtonActionPerformed
private void repositoryMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_repositoryMenuItemActionPerformed
int returnVal = repositoryFileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
eagleFilesTree.reset();
commitsTables.reset();
try {
repo = new Repo(options, repositoryFileChooser.getSelectedFile().toPath());
} catch (IOException | GitAPIException ex) {
JOptionPane.showMessageDialog(this,
"Please select a valid git repository!",
"Not a valid git repository!",
JOptionPane.ERROR_MESSAGE);
return;
}
eagleFilesTree.buildAndDisplayTree(repo);
createImagesMenuItem.setEnabled(true);
deleteImagesMenuItem.setEnabled(true);
}
}//GEN-LAST:event_repositoryMenuItemActionPerformed
private void preferencesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_preferencesMenuItemActionPerformed
JDialog dialog = new JDialog(this, "Preferences", true);
dialog.getContentPane().add(new PreferencesPanel(dialog, options));
dialog.pack();
dialog.setLocation(
new Double((Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2) - (dialog.getWidth() / 2)).intValue(),
new Double((Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2) - (dialog.getHeight() / 2)).intValue());
dialog.setResizable(false);
dialog.setVisible(true);
}//GEN-LAST:event_preferencesMenuItemActionPerformed
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
JDialog dialog = new JDialog(this, "About", true);
dialog.getContentPane().add(new AboutPanel());
dialog.pack();
dialog.setLocation(
new Double((Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2) - (dialog.getWidth() / 2)).intValue(),
new Double((Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2) - (dialog.getHeight() / 2)).intValue());
dialog.setResizable(false);
dialog.setVisible(true);
}//GEN-LAST:event_aboutMenuItemActionPerformed
private void createImagesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createImagesMenuItemActionPerformed
JDialog dialog = new JDialog(this, "Create images", true);
dialog.getContentPane().add(new CreateImagesPanel(options, repo));
dialog.pack();
dialog.setLocation(
new Double((Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2) - (dialog.getWidth() / 2)).intValue(),
new Double((Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2) - (dialog.getHeight() / 2)).intValue());
dialog.setResizable(false);
dialog.setVisible(true);
}//GEN-LAST:event_createImagesMenuItemActionPerformed
private void deleteImagesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteImagesMenuItemActionPerformed
JDialog dialog = new JDialog(this, "Delete images", true);
dialog.getContentPane().add(new DeleteImagesPanel(options, repo));
dialog.pack();
dialog.setLocation(
new Double((Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2) - (dialog.getWidth() / 2)).intValue(),
new Double((Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2) - (dialog.getHeight() / 2)).intValue());
dialog.setResizable(false);
dialog.setVisible(true);
}//GEN-LAST:event_deleteImagesMenuItemActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Windows look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Windows is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JGeagle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new JGeagle().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutMenuItem;
private javax.swing.JPanel commitsPanel;
private javax.swing.JMenuItem createImagesMenuItem;
private javax.swing.JMenuItem deleteImagesMenuItem;
private javax.swing.JButton diffImageButton;
private javax.swing.JPanel diffImagePanel;
private javax.swing.JButton eagleFilesCollapseAllButton;
private javax.swing.JButton eagleFilesExpandAllButton;
private javax.swing.JTree eagleFilesJTree;
private javax.swing.JPanel eagleFilesPanel;
private javax.swing.JScrollPane eagleFilesScrollPane;
private javax.swing.JMenu helpMenu;
private javax.swing.JMenuBar menuBar;
private javax.swing.JPanel newCommitsPanel;
private javax.swing.JScrollPane newCommitsScrollPane;
private javax.swing.JTable newCommitsTable;
private javax.swing.JPanel oldCommitsPanel;
private javax.swing.JScrollPane oldCommitsScrollPane;
private javax.swing.JTable oldCommitsTable;
private javax.swing.JMenu optionsMenu;
private javax.swing.JMenuItem preferencesMenuItem;
private javax.swing.JFileChooser repositoryFileChooser;
private javax.swing.JMenu repositoryMenu;
private javax.swing.JMenuItem repositoryMenuItem;
private javax.swing.JButton sheetButton;
private javax.swing.JComboBox sheetComboBox;
private javax.swing.JPanel sheetPanel;
private javax.swing.JMenu toolsMenu;
private javax.swing.JPanel variousPanel;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
repositoryFileChooser = new javax.swing.JFileChooser();
eagleFilesPanel = new javax.swing.JPanel();
eagleFilesScrollPane = new javax.swing.JScrollPane();
eagleFilesJTree = new javax.swing.JTree();
eagleFilesExpandAllButton = new javax.swing.JButton();
eagleFilesCollapseAllButton = new javax.swing.JButton();
commitsPanel = new javax.swing.JPanel();
oldCommitsPanel = new javax.swing.JPanel();
oldCommitsScrollPane = new javax.swing.JScrollPane();
oldCommitsTable = new javax.swing.JTable();
newCommitsPanel = new javax.swing.JPanel();
newCommitsScrollPane = new javax.swing.JScrollPane();
newCommitsTable = new javax.swing.JTable();
variousPanel = new javax.swing.JPanel();
sheetPanel = new javax.swing.JPanel();
sheetButton = new javax.swing.JButton();
sheetComboBox = new javax.swing.JComboBox();
diffImagePanel = new javax.swing.JPanel();
diffImageButton = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
repositoryMenu = new javax.swing.JMenu();
repositoryMenuItem = new javax.swing.JMenuItem();
toolsMenu = new javax.swing.JMenu();
createImagesMenuItem = new javax.swing.JMenuItem();
deleteImagesMenuItem = new javax.swing.JMenuItem();
optionsMenu = new javax.swing.JMenu();
preferencesMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenuItem = new javax.swing.JMenuItem();
repositoryFileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("JGeagle");
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("de/andreasgiemza/jgeagle/gui/icons/jgeagle.png")));
eagleFilesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Files"));
eagleFilesJTree.setModel(null);
eagleFilesScrollPane.setViewportView(eagleFilesJTree);
eagleFilesExpandAllButton.setText("Expand all");
eagleFilesExpandAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eagleFilesExpandAllButtonActionPerformed(evt);
}
});
eagleFilesCollapseAllButton.setText("Collapse all");
eagleFilesCollapseAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eagleFilesCollapseAllButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout eagleFilesPanelLayout = new javax.swing.GroupLayout(eagleFilesPanel);
eagleFilesPanel.setLayout(eagleFilesPanelLayout);
eagleFilesPanelLayout.setHorizontalGroup(
eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(eagleFilesPanelLayout.createSequentialGroup()
.addComponent(eagleFilesScrollPane)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(eagleFilesExpandAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(eagleFilesCollapseAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)))
);
eagleFilesPanelLayout.setVerticalGroup(
eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(eagleFilesPanelLayout.createSequentialGroup()
.addComponent(eagleFilesExpandAllButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(eagleFilesCollapseAllButton))
.addComponent(eagleFilesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
);
commitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Commits"));
commitsPanel.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
oldCommitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Old"));
oldCommitsPanel.setLayout(new javax.swing.BoxLayout(oldCommitsPanel, javax.swing.BoxLayout.LINE_AXIS));
oldCommitsTable.setAutoCreateRowSorter(true);
oldCommitsScrollPane.setViewportView(oldCommitsTable);
oldCommitsPanel.add(oldCommitsScrollPane);
commitsPanel.add(oldCommitsPanel);
newCommitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("New"));
newCommitsPanel.setLayout(new javax.swing.BoxLayout(newCommitsPanel, javax.swing.BoxLayout.LINE_AXIS));
newCommitsTable.setAutoCreateRowSorter(true);
newCommitsScrollPane.setViewportView(newCommitsTable);
newCommitsPanel.add(newCommitsScrollPane);
commitsPanel.add(newCommitsPanel);
variousPanel.setLayout(new java.awt.GridLayout(1, 0));
sheetPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Sheet"));
sheetPanel.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
sheetButton.setText("Count");
sheetButton.setEnabled(false);
sheetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sheetButtonActionPerformed(evt);
}
});
sheetPanel.add(sheetButton);
sheetComboBox.setEnabled(false);
sheetPanel.add(sheetComboBox);
variousPanel.add(sheetPanel);
diffImagePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Diff image"));
diffImageButton.setText("Make and/or show");
diffImageButton.setEnabled(false);
diffImageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
diffImageButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout diffImagePanelLayout = new javax.swing.GroupLayout(diffImagePanel);
diffImagePanel.setLayout(diffImagePanelLayout);
diffImagePanelLayout.setHorizontalGroup(
diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(diffImageButton, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
);
diffImagePanelLayout.setVerticalGroup(
diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(diffImageButton)
);
variousPanel.add(diffImagePanel);
repositoryMenu.setText("Repository");
repositoryMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
repositoryMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/open.png"))); // NOI18N
repositoryMenuItem.setText("Open");
repositoryMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
repositoryMenuItemActionPerformed(evt);
}
});
repositoryMenu.add(repositoryMenuItem);
menuBar.add(repositoryMenu);
toolsMenu.setText("Tools");
createImagesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
createImagesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/createimages.png"))); // NOI18N
createImagesMenuItem.setText("Create images");
createImagesMenuItem.setEnabled(false);
createImagesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createImagesMenuItemActionPerformed(evt);
}
});
toolsMenu.add(createImagesMenuItem);
deleteImagesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
deleteImagesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/deleteimages.png"))); // NOI18N
deleteImagesMenuItem.setText("Delete images");
deleteImagesMenuItem.setEnabled(false);
deleteImagesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteImagesMenuItemActionPerformed(evt);
}
});
toolsMenu.add(deleteImagesMenuItem);
menuBar.add(toolsMenu);
optionsMenu.setText("Options");
preferencesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
preferencesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/preferences.png"))); // NOI18N
preferencesMenuItem.setText("Preferences");
preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
preferencesMenuItemActionPerformed(evt);
}
});
optionsMenu.add(preferencesMenuItem);
menuBar.add(optionsMenu);
helpMenu.setText("Help");
aboutMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
aboutMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/about.png"))); // NOI18N
aboutMenuItem.setText("About");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutMenuItemActionPerformed(evt);
}
});
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(eagleFilesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(commitsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(variousPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(eagleFilesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commitsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(variousPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
repositoryFileChooser = new javax.swing.JFileChooser();
eagleFilesPanel = new javax.swing.JPanel();
eagleFilesScrollPane = new javax.swing.JScrollPane();
eagleFilesJTree = new javax.swing.JTree();
eagleFilesExpandAllButton = new javax.swing.JButton();
eagleFilesCollapseAllButton = new javax.swing.JButton();
commitsPanel = new javax.swing.JPanel();
oldCommitsPanel = new javax.swing.JPanel();
oldCommitsScrollPane = new javax.swing.JScrollPane();
oldCommitsTable = new javax.swing.JTable();
newCommitsPanel = new javax.swing.JPanel();
newCommitsScrollPane = new javax.swing.JScrollPane();
newCommitsTable = new javax.swing.JTable();
variousPanel = new javax.swing.JPanel();
sheetPanel = new javax.swing.JPanel();
sheetButton = new javax.swing.JButton();
sheetComboBox = new javax.swing.JComboBox();
diffImagePanel = new javax.swing.JPanel();
diffImageButton = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
repositoryMenu = new javax.swing.JMenu();
repositoryMenuItem = new javax.swing.JMenuItem();
toolsMenu = new javax.swing.JMenu();
createImagesMenuItem = new javax.swing.JMenuItem();
deleteImagesMenuItem = new javax.swing.JMenuItem();
optionsMenu = new javax.swing.JMenu();
preferencesMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
aboutMenuItem = new javax.swing.JMenuItem();
repositoryFileChooser.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("JGeagle");
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("de/andreasgiemza/jgeagle/gui/icons/jgeagle.png")));
eagleFilesPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Files"));
eagleFilesJTree.setModel(null);
eagleFilesScrollPane.setViewportView(eagleFilesJTree);
eagleFilesExpandAllButton.setText("Expand all");
eagleFilesExpandAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eagleFilesExpandAllButtonActionPerformed(evt);
}
});
eagleFilesCollapseAllButton.setText("Collapse all");
eagleFilesCollapseAllButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
eagleFilesCollapseAllButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout eagleFilesPanelLayout = new javax.swing.GroupLayout(eagleFilesPanel);
eagleFilesPanel.setLayout(eagleFilesPanelLayout);
eagleFilesPanelLayout.setHorizontalGroup(
eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(eagleFilesPanelLayout.createSequentialGroup()
.addComponent(eagleFilesScrollPane)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(eagleFilesExpandAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(eagleFilesCollapseAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)))
);
eagleFilesPanelLayout.setVerticalGroup(
eagleFilesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(eagleFilesPanelLayout.createSequentialGroup()
.addComponent(eagleFilesExpandAllButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(eagleFilesCollapseAllButton))
.addComponent(eagleFilesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
);
commitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Commits"));
commitsPanel.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
oldCommitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Old"));
oldCommitsPanel.setLayout(new javax.swing.BoxLayout(oldCommitsPanel, javax.swing.BoxLayout.LINE_AXIS));
oldCommitsTable.setAutoCreateRowSorter(true);
oldCommitsScrollPane.setViewportView(oldCommitsTable);
oldCommitsPanel.add(oldCommitsScrollPane);
commitsPanel.add(oldCommitsPanel);
newCommitsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("New"));
newCommitsPanel.setLayout(new javax.swing.BoxLayout(newCommitsPanel, javax.swing.BoxLayout.LINE_AXIS));
newCommitsTable.setAutoCreateRowSorter(true);
newCommitsScrollPane.setViewportView(newCommitsTable);
newCommitsPanel.add(newCommitsScrollPane);
commitsPanel.add(newCommitsPanel);
variousPanel.setLayout(new java.awt.GridLayout(1, 0));
sheetPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Sheet"));
sheetPanel.setLayout(new java.awt.GridLayout(1, 0, 5, 0));
sheetButton.setText("Count");
sheetButton.setEnabled(false);
sheetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sheetButtonActionPerformed(evt);
}
});
sheetPanel.add(sheetButton);
sheetComboBox.setEnabled(false);
sheetPanel.add(sheetComboBox);
variousPanel.add(sheetPanel);
diffImagePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Diff image"));
diffImageButton.setText("Make and/or show");
diffImageButton.setEnabled(false);
diffImageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
diffImageButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout diffImagePanelLayout = new javax.swing.GroupLayout(diffImagePanel);
diffImagePanel.setLayout(diffImagePanelLayout);
diffImagePanelLayout.setHorizontalGroup(
diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(diffImageButton, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE)
);
diffImagePanelLayout.setVerticalGroup(
diffImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(diffImageButton)
);
variousPanel.add(diffImagePanel);
repositoryMenu.setText("Repository");
repositoryMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
repositoryMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/open.png"))); // NOI18N
repositoryMenuItem.setText("Open");
repositoryMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
repositoryMenuItemActionPerformed(evt);
}
});
repositoryMenu.add(repositoryMenuItem);
menuBar.add(repositoryMenu);
toolsMenu.setText("Tools");
createImagesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
createImagesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/createimages.png"))); // NOI18N
createImagesMenuItem.setText("Create images");
createImagesMenuItem.setEnabled(false);
createImagesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createImagesMenuItemActionPerformed(evt);
}
});
toolsMenu.add(createImagesMenuItem);
deleteImagesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK));
deleteImagesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/deleteimages.png"))); // NOI18N
deleteImagesMenuItem.setText("Delete images");
deleteImagesMenuItem.setEnabled(false);
deleteImagesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteImagesMenuItemActionPerformed(evt);
}
});
toolsMenu.add(deleteImagesMenuItem);
menuBar.add(toolsMenu);
optionsMenu.setText("Options");
preferencesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
preferencesMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/preferences.png"))); // NOI18N
preferencesMenuItem.setText("Preferences");
preferencesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
preferencesMenuItemActionPerformed(evt);
}
});
optionsMenu.add(preferencesMenuItem);
menuBar.add(optionsMenu);
helpMenu.setText("Help");
aboutMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.CTRL_MASK));
aboutMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/de/andreasgiemza/jgeagle/gui/icons/about.png"))); // NOI18N
aboutMenuItem.setText("About");
aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
aboutMenuItemActionPerformed(evt);
}
});
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(eagleFilesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(commitsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(variousPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(eagleFilesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commitsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(variousPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/CCProbe/source/CCProbe.java b/CCProbe/source/CCProbe.java
index 666a0ea..86345f0 100644
--- a/CCProbe/source/CCProbe.java
+++ b/CCProbe/source/CCProbe.java
@@ -1,312 +1,312 @@
import waba.ui.*;
import waba.util.*;
import waba.fx.*;
import org.concord.waba.extra.ui.*;
import org.concord.waba.extra.event.*;
import org.concord.LabBook.*;
import org.concord.CCProbe.*;
public class CCProbe extends MainView
implements DialogListener
{
LabBookSession mainSession;
Menu edit;
Title title;
int yOffset = 0;
int newIndex = 0;
String aboutTitle = "About CCProbe";
String [] creationTypes = {"Folder", "Notes", "Data Collector",
"Drawing","UnitConvertor","Image"};
String [] palmFileStrings = {"Beam LabBook", aboutTitle};
String [] javaFileStrings = {aboutTitle, "Serial Port Setup..", "-",
"Exit"};
String [] ceFileStrings = {aboutTitle, "-", "Exit"};
int []creationID = {0x00010100};
public void onStart()
{
super.onStart();
LObjDictionary loDict = null;
LabBook.registerFactory(new DataObjFactory());
// Dialog.showImages = false;
// ImagePane.showImages = false;
graph.Bin.START_DATA_SIZE = 25000;
graph.LargeFloatArray.MaxNumChunks = 25;
int dictHeight = myHeight;
LabBookDB lbDB;
String plat = waba.sys.Vm.getPlatform();
if(plat.equals("PalmOS")){
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
GraphSettings.MAX_COLLECTIONS = 1;
graph.GraphViewLine.scrollStepSize = 0.45f;
lbDB = new LabBookCatalog("LabBook");
CCTextArea.INTER_LINE_SPACING = 0;
Dialog.showImages = false;
} else if(plat.equals("Java")){
/*
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
*/
// GraphSettings.MAX_COLLECTIONS = 1;
- // lbDB = new LabBookCatalog("LabBook");
+ lbDB = new LabBookCatalog("LabBook");
// Dialog.showImages = false;
- lbDB = new LabBookFile("LabBook");
+ // lbDB = new LabBookFile("LabBook");
} else {
lbDB = new LabBookFile("LabBook");
GraphSettings.MAX_COLLECTIONS = 4;
}
if(myHeight < 180){
yOffset = 13;
dictHeight -= 13;
if(title == null) title = new Title("CCProbe");
title.setRect(0,0,width, 13);
me.add(title);
}
if(lbDB.getError()){
// Error;
exit(0);
}
if(plat.equals("PalmOS")){
addFileMenuItems(palmFileStrings, null);
} else if(plat.equals("Java")){
addFileMenuItems(javaFileStrings, null);
} else {
addFileMenuItems(ceFileStrings, null);
}
Debug.println("Openning");
labBook.open(lbDB);
LabObjectPtr rootPtr = labBook.getRoot();
mainSession = rootPtr.getSession();
loDict = (LObjDictionary)mainSession.getObj(rootPtr);
if(loDict == null){
loDict = DefaultFactory.createDictionary();
loDict.setName("Home");
mainSession.storeNew(loDict);
labBook.store(loDict);
}
LabObjectView view = (LabObjectView)loDict.getView(this, true, mainSession);
view.setRect(x,yOffset,width,dictHeight);
view.setShowMenus(true);
me.add(view);
lObjView = view;
newIndex = loDict.getChildCount();
if(plat.equals("PalmOS")){
((LObjDictionaryView)view).checkForBeam();
}
}
public String [] getCreateNames()
{
String []createNames = creationTypes;
if(creationID != null){
for(int i = 0; i < creationID.length; i++){
int factoryType = (creationID[i] & 0xFFFF0000);
factoryType >>>= 16;
int objID = creationID[i] & 0xFFFF;
LabObjectFactory factory = null;
for(int f = 0; f < LabBook.objFactories.length; f++){
if(LabBook.objFactories[f] == null) continue;
if(LabBook.objFactories[f].getFactoryType() == factoryType){
factory = LabBook.objFactories[f];
break;
}
}
if(factory != null){
LabObjDescriptor []desc = factory.getLabBookObjDesc();
if(desc != null){
for(int d = 0; d < desc.length; d++){
if(desc[d] == null) continue;
if(desc[d].objType == objID){
String name = desc[d].name;
if(name != null){
String []newNames = new String[createNames.length+1];
waba.sys.Vm.copyArray(createNames,0,newNames,0,createNames.length);
newNames[createNames.length] = name;
createNames = newNames;
}
}
}
}
}
}
}
return createNames;
}
public void createObj(String objType, LObjDictionaryView dView)
{
LabObject newObj = null;
// boolean autoEdit = false;
boolean autoEdit = true;
boolean autoProp = true;
for(int f = 0; f < LabBook.objFactories.length; f++){
if(LabBook.objFactories[f] == null) continue;
LabObjDescriptor []desc = LabBook.objFactories[f].getLabBookObjDesc();
if(desc == null) continue;
boolean doExit = false;
for(int d = 0; d < desc.length; d++){
if(desc[d] == null) continue;
if(objType.equals(desc[d].name)){
newObj = LabBook.objFactories[f].makeNewObj(desc[d].objType);
if(objType.equals("Folder")){
autoEdit = false;
} else if(objType.equals("Data Collector")){
autoEdit = false;
}
doExit = true;
break;
}
}
if(doExit) break;
}
if(newObj != null){
dView.getSession().storeNew(newObj);
if(newIndex == 0){
newObj.setName(objType);
} else {
newObj.setName(objType + " " + newIndex);
}
newIndex++;
dView.insertAtSelected(newObj);
// The order seems to matter here.
// insert and selected for some reason nulls the pointer.
// perhaps by doing a commit?
// newObj.store();
if(autoEdit){
dView.openSelected(true);
} else if(autoProp){
dView.showProperties(newObj);
}
}
}
Dialog beamLBDialog = null;
public void dialogClosed(DialogEvent e)
{
String command = e.getActionCommand();
if(e.getSource() == beamLBDialog){
if(command.equals("Beam")){
waba.sys.Vm.exec("CCBeam", "LabBook,,," +
"LabBook for CCProbe", 0, true);
}
}
}
public void reload(LabObjectView source)
{
if(source != lObjView) Debug.println("Error source being removed");
LabObject obj = source.getLabObject();
LabBookSession oldSession = source.getSession();
source.close();
me.remove(source);
if(title != null){
me.remove(title);
}
LabObjectView replacement = obj.getView(this, true, oldSession);
// This automatically does the layout call for us
waba.fx.Rect myRect = content.getRect();
myHeight = myRect.height;
int dictHeight = myHeight;
if(myHeight < 180){
yOffset = 13;
dictHeight -= 13;
if(title == null) title = new Title("CCProbe");
title.setRect(0,0,width, 13);
me.add(title);
}
replacement.setRect(x,yOffset,width,dictHeight);
replacement.setShowMenus(true);
me.add(replacement);
lObjView = replacement;
}
public void actionPerformed(ActionEvent e)
{
String command;
Debug.println("Got action: " + e.getActionCommand());
if(e.getSource() == file){
command = e.getActionCommand();
if(command.equals("Exit")){
handleQuit();
}else if(command.equals(aboutTitle)){
handleAbout();
} else if(command.equals("Beam LabBook")){
String [] buttons = {"Beam", "Cancel"};
beamLBDialog = Dialog.showConfirmDialog(this, "Confirm",
"Close CCProbe on the receiving| " +
"Palm before beaming.",
buttons,
Dialog.INFO_DIALOG);
} else if(command.equals("Serial Port Setup..")){
DataExport.showSerialDialog();
} else {
super.actionPerformed(e);
}
}
}
public void onExit()
{
Debug.println("closing");
if(labBook != null){
if(curFullView != null){
curFullView.close();
} else {
lObjView.close();
}
labBook.commit();
labBook.close();
}
}
public void handleQuit(){
Debug.println("commiting");
if(curFullView != null){
curFullView.close();
curFullView = null;
} else if(lObjView != null) {
lObjView.close();
}
if(labBook != null){
labBook.commit();
labBook.close();
labBook = null;
exit(0);
}
}
public void handleAbout(){
Dialog.showAboutDialog(aboutTitle,AboutMessages.getMessage());
}
}
| false | true | public void onStart()
{
super.onStart();
LObjDictionary loDict = null;
LabBook.registerFactory(new DataObjFactory());
// Dialog.showImages = false;
// ImagePane.showImages = false;
graph.Bin.START_DATA_SIZE = 25000;
graph.LargeFloatArray.MaxNumChunks = 25;
int dictHeight = myHeight;
LabBookDB lbDB;
String plat = waba.sys.Vm.getPlatform();
if(plat.equals("PalmOS")){
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
GraphSettings.MAX_COLLECTIONS = 1;
graph.GraphViewLine.scrollStepSize = 0.45f;
lbDB = new LabBookCatalog("LabBook");
CCTextArea.INTER_LINE_SPACING = 0;
Dialog.showImages = false;
} else if(plat.equals("Java")){
/*
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
*/
// GraphSettings.MAX_COLLECTIONS = 1;
// lbDB = new LabBookCatalog("LabBook");
// Dialog.showImages = false;
lbDB = new LabBookFile("LabBook");
} else {
lbDB = new LabBookFile("LabBook");
GraphSettings.MAX_COLLECTIONS = 4;
}
if(myHeight < 180){
yOffset = 13;
dictHeight -= 13;
if(title == null) title = new Title("CCProbe");
title.setRect(0,0,width, 13);
me.add(title);
}
if(lbDB.getError()){
// Error;
exit(0);
}
if(plat.equals("PalmOS")){
addFileMenuItems(palmFileStrings, null);
} else if(plat.equals("Java")){
addFileMenuItems(javaFileStrings, null);
} else {
addFileMenuItems(ceFileStrings, null);
}
Debug.println("Openning");
labBook.open(lbDB);
LabObjectPtr rootPtr = labBook.getRoot();
mainSession = rootPtr.getSession();
loDict = (LObjDictionary)mainSession.getObj(rootPtr);
if(loDict == null){
loDict = DefaultFactory.createDictionary();
loDict.setName("Home");
mainSession.storeNew(loDict);
labBook.store(loDict);
}
LabObjectView view = (LabObjectView)loDict.getView(this, true, mainSession);
view.setRect(x,yOffset,width,dictHeight);
view.setShowMenus(true);
me.add(view);
lObjView = view;
newIndex = loDict.getChildCount();
if(plat.equals("PalmOS")){
((LObjDictionaryView)view).checkForBeam();
}
}
| public void onStart()
{
super.onStart();
LObjDictionary loDict = null;
LabBook.registerFactory(new DataObjFactory());
// Dialog.showImages = false;
// ImagePane.showImages = false;
graph.Bin.START_DATA_SIZE = 25000;
graph.LargeFloatArray.MaxNumChunks = 25;
int dictHeight = myHeight;
LabBookDB lbDB;
String plat = waba.sys.Vm.getPlatform();
if(plat.equals("PalmOS")){
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
GraphSettings.MAX_COLLECTIONS = 1;
graph.GraphViewLine.scrollStepSize = 0.45f;
lbDB = new LabBookCatalog("LabBook");
CCTextArea.INTER_LINE_SPACING = 0;
Dialog.showImages = false;
} else if(plat.equals("Java")){
/*
graph.Bin.START_DATA_SIZE = 4000;
graph.LargeFloatArray.MaxNumChunks = 4;
*/
// GraphSettings.MAX_COLLECTIONS = 1;
lbDB = new LabBookCatalog("LabBook");
// Dialog.showImages = false;
// lbDB = new LabBookFile("LabBook");
} else {
lbDB = new LabBookFile("LabBook");
GraphSettings.MAX_COLLECTIONS = 4;
}
if(myHeight < 180){
yOffset = 13;
dictHeight -= 13;
if(title == null) title = new Title("CCProbe");
title.setRect(0,0,width, 13);
me.add(title);
}
if(lbDB.getError()){
// Error;
exit(0);
}
if(plat.equals("PalmOS")){
addFileMenuItems(palmFileStrings, null);
} else if(plat.equals("Java")){
addFileMenuItems(javaFileStrings, null);
} else {
addFileMenuItems(ceFileStrings, null);
}
Debug.println("Openning");
labBook.open(lbDB);
LabObjectPtr rootPtr = labBook.getRoot();
mainSession = rootPtr.getSession();
loDict = (LObjDictionary)mainSession.getObj(rootPtr);
if(loDict == null){
loDict = DefaultFactory.createDictionary();
loDict.setName("Home");
mainSession.storeNew(loDict);
labBook.store(loDict);
}
LabObjectView view = (LabObjectView)loDict.getView(this, true, mainSession);
view.setRect(x,yOffset,width,dictHeight);
view.setShowMenus(true);
me.add(view);
lObjView = view;
newIndex = loDict.getChildCount();
if(plat.equals("PalmOS")){
((LObjDictionaryView)view).checkForBeam();
}
}
|
diff --git a/src/org/jruby/runtime/LastCallStatus.java b/src/org/jruby/runtime/LastCallStatus.java
index 2e42a45e0..e39ab0286 100644
--- a/src/org/jruby/runtime/LastCallStatus.java
+++ b/src/org/jruby/runtime/LastCallStatus.java
@@ -1,85 +1,85 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.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.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2002 Jan Arne Petersen <[email protected]>
* Copyright (C) 2002-2004 Anders Bengtsson <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.runtime;
import org.jruby.Ruby;
import org.jruby.util.IdUtil;
/**
*
* @author jpetersen
* @version $Revision$
*/
public class LastCallStatus {
private static final Object NORMAL = new Object();
private static final Object PRIVATE = new Object();
private static final Object PROTECTED = new Object();
private static final Object VARIABLE = new Object();
private final Ruby runtime;
private Object status = NORMAL;
public LastCallStatus(Ruby runtime) {
this.runtime = runtime;
}
public void setNormal() {
status = NORMAL;
}
public void setPrivate() {
status = PRIVATE;
}
public void setProtected() {
status = PROTECTED;
}
public void setVariable() {
status = VARIABLE;
}
public Ruby getRuntime() {
return runtime;
}
public String errorMessageFormat(String name) {
- String format = "Undefined method '%s' for %s%s%s";
+ String format = "undefined method `%s' for %s%s%s";
if (status == PRIVATE) {
format = "private method '%s' called for %s%s%s";
} else if (status == PROTECTED) {
format = "protected method '%s' called for %s%s%s";
} else if (status == VARIABLE) {
if (IdUtil.isLocal(name)) {
format = "Undefined local variable or method '%s' for %s%s%s";
}
}
return format;
}
}
| true | true | public String errorMessageFormat(String name) {
String format = "Undefined method '%s' for %s%s%s";
if (status == PRIVATE) {
format = "private method '%s' called for %s%s%s";
} else if (status == PROTECTED) {
format = "protected method '%s' called for %s%s%s";
} else if (status == VARIABLE) {
if (IdUtil.isLocal(name)) {
format = "Undefined local variable or method '%s' for %s%s%s";
}
}
return format;
}
| public String errorMessageFormat(String name) {
String format = "undefined method `%s' for %s%s%s";
if (status == PRIVATE) {
format = "private method '%s' called for %s%s%s";
} else if (status == PROTECTED) {
format = "protected method '%s' called for %s%s%s";
} else if (status == VARIABLE) {
if (IdUtil.isLocal(name)) {
format = "Undefined local variable or method '%s' for %s%s%s";
}
}
return format;
}
|
diff --git a/src/di/kdd/smartmonitor/protocol/PeerNode.java b/src/di/kdd/smartmonitor/protocol/PeerNode.java
index 566b005..b9a8a1d 100644
--- a/src/di/kdd/smartmonitor/protocol/PeerNode.java
+++ b/src/di/kdd/smartmonitor/protocol/PeerNode.java
@@ -1,145 +1,145 @@
package di.kdd.smartmonitor.protocol;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.util.Log;
import di.kdd.smartmonitor.middleware.TimeSynchronization;
import di.kdd.smartmonitor.protocol.ISmartMonitor.Tag;
public final class PeerNode extends DistributedSystemNode implements Runnable {
/* The socket that the peer holds in order to get command messages from the Master */
private ServerSocket commandsServerSocket;
private TimeSynchronization timeSync = new TimeSynchronization();
private static final String TAG = "peer";
/***
* Sends a JOIN message to the Master node and if it gets accepted,
* starts a thread that accepts commands from the Master
* @param socket The connected to the Master node socket
*/
public PeerNode(Socket socket) {
Message message;
try {
/* Start command-serving thread */
new Thread(this).start();
/* The Master node was found, send the JOIN message */
message = new Message(Tag.JOIN);
send(socket, message);
}
catch(Exception e) {
Log.e(TAG, "Failed to join the system: " + e.getMessage());
e.printStackTrace();
}
finally {
try {
socket.close();
}
catch(IOException e) {
}
}
}
/***
* Accepts a socket connection on the COMMAND_PORT and waits for commands from the Master
*/
@Override
public void run() {
Socket masterSocket;
BufferedReader in;
android.os.Debug.waitForDebugger();
Log.i(TAG, "Command-serving thread was started");
try {
commandsServerSocket = new ServerSocket(ISmartMonitor.COMMAND_PORT);
commandsServerSocket.setReuseAddress(true);
masterSocket = commandsServerSocket.accept();
- Log.i(TAG, "Accepted command socket from " + masterSocket.getRemoteSocketAddress().toString());
+ Log.i(TAG, "Accepted command socket from " + masterSocket.getInetAddress().toString());
}
catch(IOException e) {
Log.e(TAG, "Failed to accept command socket");
e.printStackTrace();
return;
}
/* Listen on MasterSocket for incoming commands from the Master */
Log.i(TAG, "Listening for commands from the Master node");
while(!this.isInterrupted()) {
try {
Message message;
message = receive(masterSocket);
switch(message.getTag()) {
case PEER_DATA:
Log.i(TAG, "Received PEER_DATA command");
message = receive(masterSocket);
peerData.addPeersFromMessage(message);
break;
case SYNC:
Log.i(TAG, "Received SYNC command");
timeSync.timeReference(Long.parseLong(message.getPayload()));
break;
case NEW_PEER:
Log.i(TAG, "Received NEW_PEER command");
peerData.addPeerIP(message.getPayload());
break;
case START_SAMPLING:
Log.i(TAG, "Received START_SAMPLING command");
break;
case STOP_SAMPLING:
Log.i(TAG, "Received STOP_SAMPLING command");
break;
case SEND_PEAKS:
Log.i(TAG, "Received SEND_PEAKS command");
break;
default:
Log.e(TAG, "Not implemented Tag handling: " + message.getTag().toString());
break;
}
}
catch(IOException e) {
Log.e(TAG, "Error while listening to commands from Master node");
e.printStackTrace();
}
}
}
@Override
public void disconnect() {
this.interrupt();
try {
commandsServerSocket.close();
}
catch(IOException e) {
}
}
@Override
public boolean isMaster() {
return false;
}
}
| true | true | public void run() {
Socket masterSocket;
BufferedReader in;
android.os.Debug.waitForDebugger();
Log.i(TAG, "Command-serving thread was started");
try {
commandsServerSocket = new ServerSocket(ISmartMonitor.COMMAND_PORT);
commandsServerSocket.setReuseAddress(true);
masterSocket = commandsServerSocket.accept();
Log.i(TAG, "Accepted command socket from " + masterSocket.getRemoteSocketAddress().toString());
}
catch(IOException e) {
Log.e(TAG, "Failed to accept command socket");
e.printStackTrace();
return;
}
/* Listen on MasterSocket for incoming commands from the Master */
Log.i(TAG, "Listening for commands from the Master node");
while(!this.isInterrupted()) {
try {
Message message;
message = receive(masterSocket);
switch(message.getTag()) {
case PEER_DATA:
Log.i(TAG, "Received PEER_DATA command");
message = receive(masterSocket);
peerData.addPeersFromMessage(message);
break;
case SYNC:
Log.i(TAG, "Received SYNC command");
timeSync.timeReference(Long.parseLong(message.getPayload()));
break;
case NEW_PEER:
Log.i(TAG, "Received NEW_PEER command");
peerData.addPeerIP(message.getPayload());
break;
case START_SAMPLING:
Log.i(TAG, "Received START_SAMPLING command");
break;
case STOP_SAMPLING:
Log.i(TAG, "Received STOP_SAMPLING command");
break;
case SEND_PEAKS:
Log.i(TAG, "Received SEND_PEAKS command");
break;
default:
Log.e(TAG, "Not implemented Tag handling: " + message.getTag().toString());
break;
}
}
catch(IOException e) {
Log.e(TAG, "Error while listening to commands from Master node");
e.printStackTrace();
}
}
}
| public void run() {
Socket masterSocket;
BufferedReader in;
android.os.Debug.waitForDebugger();
Log.i(TAG, "Command-serving thread was started");
try {
commandsServerSocket = new ServerSocket(ISmartMonitor.COMMAND_PORT);
commandsServerSocket.setReuseAddress(true);
masterSocket = commandsServerSocket.accept();
Log.i(TAG, "Accepted command socket from " + masterSocket.getInetAddress().toString());
}
catch(IOException e) {
Log.e(TAG, "Failed to accept command socket");
e.printStackTrace();
return;
}
/* Listen on MasterSocket for incoming commands from the Master */
Log.i(TAG, "Listening for commands from the Master node");
while(!this.isInterrupted()) {
try {
Message message;
message = receive(masterSocket);
switch(message.getTag()) {
case PEER_DATA:
Log.i(TAG, "Received PEER_DATA command");
message = receive(masterSocket);
peerData.addPeersFromMessage(message);
break;
case SYNC:
Log.i(TAG, "Received SYNC command");
timeSync.timeReference(Long.parseLong(message.getPayload()));
break;
case NEW_PEER:
Log.i(TAG, "Received NEW_PEER command");
peerData.addPeerIP(message.getPayload());
break;
case START_SAMPLING:
Log.i(TAG, "Received START_SAMPLING command");
break;
case STOP_SAMPLING:
Log.i(TAG, "Received STOP_SAMPLING command");
break;
case SEND_PEAKS:
Log.i(TAG, "Received SEND_PEAKS command");
break;
default:
Log.e(TAG, "Not implemented Tag handling: " + message.getTag().toString());
break;
}
}
catch(IOException e) {
Log.e(TAG, "Error while listening to commands from Master node");
e.printStackTrace();
}
}
}
|
diff --git a/user/super/com/google/gwt/emul/java/util/Date.java b/user/super/com/google/gwt/emul/java/util/Date.java
index 98bd244dc..240f49bd9 100644
--- a/user/super/com/google/gwt/emul/java/util/Date.java
+++ b/user/super/com/google/gwt/emul/java/util/Date.java
@@ -1,335 +1,335 @@
/*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.util;
import com.google.gwt.core.client.JavaScriptObject;
import java.io.Serializable;
/**
* Represents a date and time.
*/
public class Date implements Cloneable, Comparable<Date>, Serializable {
/**
* Used only by toString().
*/
private static final String[] DAYS = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
/**
* Used only by toString().
*/
private static final String[] MONTHS = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
public static long parse(String s) {
long d = (long) parse0(s);
if (d != -1) {
return d;
} else {
throw new IllegalArgumentException();
}
}
// CHECKSTYLE_OFF: Matching the spec.
public static long UTC(int year, int month, int date, int hrs,
int min, int sec) {
return (long) utc0(year, month, date, hrs, min, sec);
}
// CHECKSTYLE_ON
/**
* Ensure a number is displayed with two digits.
*
* @return a two-character base 10 representation of the number
*/
protected static String padTwo(int number) {
if (number < 10) {
return "0" + number;
} else {
return String.valueOf(number);
}
}
/**
* Return the names for the days of the week as specified by the Date
* specification.
*/
@SuppressWarnings("unused") // called by JSNI
private static String dayToString(int day) {
return DAYS[day];
}
/**
* Return the names for the months of the year as specified by the Date
* specification.
*/
@SuppressWarnings("unused") // called by JSNI
private static String monthToString(int month) {
return MONTHS[month];
}
private static native double parse0(String s) /*-{
var d = Date.parse(s);
return isNaN(d) ? -1 : d;
}-*/;
/**
* Throw an exception if jsdate is not an object.
*
* @param val
*/
@SuppressWarnings("unused") // called by JSNI
private static void throwJsDateException(String val) {
throw new IllegalStateException("jsdate is " + val);
}
private static native double utc0(int year, int month, int date, int hrs,
int min, int sec) /*-{
return Date.UTC(year + 1900, month, date, hrs, min, sec);
}-*/;
/**
* JavaScript Date instance.
*/
@SuppressWarnings("unused") // used from JSNI
private JavaScriptObject jsdate;
public Date() {
init();
}
public Date(int year, int month, int date) {
init(year, month, date, 0, 0, 0);
}
public Date(int year, int month, int date, int hrs, int min) {
init(year, month, date, hrs, min, 0);
}
public Date(int year, int month, int date, int hrs, int min, int sec) {
init(year, month, date, hrs, min, sec);
}
public Date(long date) {
init(date);
}
public Date(String date) {
init(Date.parse(date));
}
public boolean after(Date when) {
return getTime() > when.getTime();
}
public boolean before(Date when) {
return getTime() < when.getTime();
}
public Object clone() {
return new Date(getTime());
}
public int compareTo(Date other) {
long thisTime = getTime();
long otherTime = other.getTime();
if (thisTime < otherTime) {
return -1;
} else if (thisTime > otherTime) {
return 1;
} else {
return 0;
}
}
@Override
public boolean equals(Object obj) {
return ((obj instanceof Date) && (getTime() == ((Date) obj).getTime()));
}
public native int getDate() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getDate();
}-*/;
public native int getDay() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getDay();
}-*/;
public native int getHours() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getHours();
}-*/;
public native int getMinutes() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getMinutes();
}-*/;
public native int getMonth() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getMonth();
}-*/;
public native int getSeconds() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getSeconds();
}-*/;
public long getTime() {
return (long) getTime0();
}
public native int getTimezoneOffset() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getTimezoneOffset();
}-*/;
public native int getYear() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getFullYear()-1900;
}-*/;
@Override
public int hashCode() {
return (int) (this.getTime() ^ (this.getTime() >>> 32));
}
public native void setDate(int date) /*-{
[email protected]::checkJsDate()();
[email protected]::jsdate.setDate(date);
}-*/;
public native void setHours(int hours) /*-{
[email protected]::checkJsDate()();
[email protected]::jsdate.setHours(hours);
}-*/;
public native void setMinutes(int minutes) /*-{
[email protected]::checkJsDate()();
[email protected]::jsdate.setMinutes(minutes);
}-*/;
public native void setMonth(int month) /*-{
[email protected]::checkJsDate()();
[email protected]::jsdate.setMonth(month);
}-*/;
public native void setSeconds(int seconds) /*-{
[email protected]::checkJsDate()();
[email protected]::jsdate.setSeconds(seconds);
}-*/;
public void setTime(long time) {
setTime0(time);
}
public native void setYear(int year) /*-{
[email protected]::checkJsDate()();
[email protected]::jsdate.setFullYear(year + 1900);
}-*/;
public native String toGMTString() /*-{
[email protected]::checkJsDate()();
var d = [email protected]::jsdate;
var padTwo = @java.util.Date::padTwo(I);
var month =
@java.util.Date::monthToString(I)([email protected]::jsdate.getUTCMonth());
return d.getUTCDate() + " " +
month + " " +
d.getUTCFullYear() + " " +
padTwo(d.getUTCHours()) + ":" +
padTwo(d.getUTCMinutes()) + ":" +
padTwo(d.getUTCSeconds()) +
" GMT";
}-*/;
public native String toLocaleString() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.toLocaleString();
}-*/;
@Override
public native String toString() /*-{
[email protected]::checkJsDate()();
var d = [email protected]::jsdate;
var padTwo = @java.util.Date::padTwo(I);
var day =
@java.util.Date::dayToString(I)(d.getDay());
var month =
@java.util.Date::monthToString(I)(d.getMonth());
// Compute timezone offset. The value that getTimezoneOffset returns is
// backwards for the transformation that we want.
var offset = -d.getTimezoneOffset();
var hourOffset = String((offset >= 0) ?
"+" + Math.floor(offset / 60) : Math.ceil(offset / 60));
var minuteOffset = padTwo(Math.abs(offset) % 60);
return day + " " + month + " " +
padTwo(d.getDate()) + " " +
padTwo(d.getHours()) + ":" +
padTwo(d.getMinutes()) + ":" +
padTwo(d.getSeconds()) +
" GMT" + hourOffset + minuteOffset +
- + " " + d.getFullYear();
+ " " + d.getFullYear();
}-*/;
/**
* Check that jsdate is valid and throw an exception if not.
*/
@SuppressWarnings("unused") // called by JSNI
private native void checkJsDate() /*-{
if ([email protected]::jsdate
|| typeof [email protected]::jsdate != "object") {
@java.util.Date::throwJsDateException(Ljava/lang/String;)(""
+ [email protected]::jsdate);
}
}-*/;
private native double getTime0() /*-{
[email protected]::checkJsDate()();
return [email protected]::jsdate.getTime();
}-*/;
private native void init() /*-{
[email protected]::jsdate = new Date();
}-*/;
private native void init(double date) /*-{
[email protected]::jsdate = new Date(date);
}-*/;
private native void init(int year, int month, int date, int hrs, int min,
int sec) /*-{
[email protected]::jsdate = new Date();
[email protected]::checkJsDate()();
[email protected]::jsdate.setFullYear(year + 1900, month, date);
[email protected]::jsdate.setHours(hrs, min, sec, 0);
}-*/;
private native void setTime0(double time) /*-{
[email protected]::checkJsDate()();
[email protected]::jsdate.setTime(time);
}-*/;
}
| true | true | public native String toString() /*-{
[email protected]::checkJsDate()();
var d = [email protected]::jsdate;
var padTwo = @java.util.Date::padTwo(I);
var day =
@java.util.Date::dayToString(I)(d.getDay());
var month =
@java.util.Date::monthToString(I)(d.getMonth());
// Compute timezone offset. The value that getTimezoneOffset returns is
// backwards for the transformation that we want.
var offset = -d.getTimezoneOffset();
var hourOffset = String((offset >= 0) ?
"+" + Math.floor(offset / 60) : Math.ceil(offset / 60));
var minuteOffset = padTwo(Math.abs(offset) % 60);
return day + " " + month + " " +
padTwo(d.getDate()) + " " +
padTwo(d.getHours()) + ":" +
padTwo(d.getMinutes()) + ":" +
padTwo(d.getSeconds()) +
" GMT" + hourOffset + minuteOffset +
+ " " + d.getFullYear();
}-*/;
| public native String toString() /*-{
[email protected]::checkJsDate()();
var d = [email protected]::jsdate;
var padTwo = @java.util.Date::padTwo(I);
var day =
@java.util.Date::dayToString(I)(d.getDay());
var month =
@java.util.Date::monthToString(I)(d.getMonth());
// Compute timezone offset. The value that getTimezoneOffset returns is
// backwards for the transformation that we want.
var offset = -d.getTimezoneOffset();
var hourOffset = String((offset >= 0) ?
"+" + Math.floor(offset / 60) : Math.ceil(offset / 60));
var minuteOffset = padTwo(Math.abs(offset) % 60);
return day + " " + month + " " +
padTwo(d.getDate()) + " " +
padTwo(d.getHours()) + ":" +
padTwo(d.getMinutes()) + ":" +
padTwo(d.getSeconds()) +
" GMT" + hourOffset + minuteOffset +
" " + d.getFullYear();
}-*/;
|
diff --git a/src/java/se/idega/idegaweb/commune/accounting/invoice/business/InvoiceChildcareThread.java b/src/java/se/idega/idegaweb/commune/accounting/invoice/business/InvoiceChildcareThread.java
index daf8064b..9dea1683 100644
--- a/src/java/se/idega/idegaweb/commune/accounting/invoice/business/InvoiceChildcareThread.java
+++ b/src/java/se/idega/idegaweb/commune/accounting/invoice/business/InvoiceChildcareThread.java
@@ -1,799 +1,799 @@
package se.idega.idegaweb.commune.accounting.invoice.business;
import is.idega.idegaweb.member.business.MemberFamilyLogic;
import is.idega.idegaweb.member.business.NoChildrenFound;
import is.idega.idegaweb.member.business.NoCohabitantFound;
import is.idega.idegaweb.member.business.NoCustodianFound;
import java.rmi.RemoteException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeSet;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import se.idega.idegaweb.commune.accounting.export.data.ExportDataMapping;
import se.idega.idegaweb.commune.accounting.invoice.data.ConstantStatus;
import se.idega.idegaweb.commune.accounting.invoice.data.InvoiceHeader;
import se.idega.idegaweb.commune.accounting.invoice.data.InvoiceRecord;
import se.idega.idegaweb.commune.accounting.invoice.data.PaymentRecord;
import se.idega.idegaweb.commune.accounting.invoice.data.RegularInvoiceEntry;
import se.idega.idegaweb.commune.accounting.invoice.data.SortableSibling;
import se.idega.idegaweb.commune.accounting.posting.business.MissingMandatoryFieldException;
import se.idega.idegaweb.commune.accounting.posting.business.PostingException;
import se.idega.idegaweb.commune.accounting.posting.business.PostingParametersException;
import se.idega.idegaweb.commune.accounting.regulations.business.BruttoIncomeException;
import se.idega.idegaweb.commune.accounting.regulations.business.LowIncomeException;
import se.idega.idegaweb.commune.accounting.regulations.business.PaymentFlowConstant;
import se.idega.idegaweb.commune.accounting.regulations.business.RegSpecConstant;
import se.idega.idegaweb.commune.accounting.regulations.business.RegulationException;
import se.idega.idegaweb.commune.accounting.regulations.business.RegulationsBusiness;
import se.idega.idegaweb.commune.accounting.regulations.business.RuleTypeConstant;
import se.idega.idegaweb.commune.accounting.regulations.data.ConditionParameter;
import se.idega.idegaweb.commune.accounting.regulations.data.PostingDetail;
import se.idega.idegaweb.commune.accounting.regulations.data.Regulation;
import se.idega.idegaweb.commune.accounting.regulations.data.RegulationSpecType;
import se.idega.idegaweb.commune.accounting.regulations.data.RegulationSpecTypeHome;
import se.idega.idegaweb.commune.accounting.school.data.Provider;
import se.idega.idegaweb.commune.childcare.data.ChildCareContract;
import se.idega.idegaweb.commune.childcare.data.EmploymentType;
import com.idega.block.school.data.SchoolCategory;
import com.idega.block.school.data.SchoolCategoryHome;
import com.idega.block.school.data.SchoolClassMember;
import com.idega.block.school.data.SchoolType;
import com.idega.business.IBOLookup;
import com.idega.core.location.data.Address;
import com.idega.data.IDOLookup;
import com.idega.data.IDOLookupException;
import com.idega.presentation.IWContext;
import com.idega.user.business.UserBusiness;
import com.idega.user.data.User;
import com.idega.util.Age;
/**
* Holds most of the logic for the batchjob that creates the information that is base for invoicing
* and payment data, that is sent to external finance system.
*
* @author Joakim
*
* @see se.idega.idegaweb.commune.accounting.invoice.business.PaymentThreadElementarySchool
* @see se.idega.idegaweb.commune.accounting.invoice.business.PaymentThreadHighSchool
* @see se.idega.idegaweb.commune.accounting.invoice.business.BillingThread
*/
public class InvoiceChildcareThread extends BillingThread{
private static final String HOURS_PER_WEEK = "hours/week"; //Localize this text in the user interface
private ChildCareContract contract;
private PostingDetail postingDetail;
//private int childcare;
private Map siblingOrders = new HashMap();
// private String ownPosting, doublePosting;
public InvoiceChildcareThread(Date month, IWContext iwc){
super(month,iwc);
}
/**
* The thread that does the acctual work on the batch process
* @see java.lang.Runnable#run()
*/
public void run(){
try {
category = ((SchoolCategoryHome) IDOLookup.getHome(SchoolCategory.class)).findChildcareCategory();
categoryPosting = (ExportDataMapping) IDOLookup.getHome(ExportDataMapping.class).findByPrimaryKeyIDO(category.getPrimaryKey());
createBatchRunLogger(category);
//Create all the billing info derrived from the contracts
contracts();
//Create all the billing info derrived from the regular payments
regularInvoice();
//VAT
calcVAT();
batchRunLoggerDone();
} catch (Exception e) {
//This is a spawned off thread, so we cannot report back errors to the browser, just log them
e.printStackTrace();
createNewErrorMessage("invoice.severeError","invoice.DBSetupProblem");
batchRunLoggerDone();
}
}
/**
* Creates all the invoice headers, invoice records, payment headers and payment records
* for the childcare contracts
*/
private void contracts(){
Collection contractArray = new ArrayList();
Collection regulationArray = new ArrayList();
User custodian;
Age age;
int hours;
float totalSum;
InvoiceRecord invoiceRecord, subvention;
try {
- contractArray = getChildCareContractHome().findByDateRange(startPeriod.getDate(), endPeriod.getDate());
+ contractArray = getChildCareContractHome().findByDateRangeWhereStatusActive(startPeriod.getDate(), endPeriod.getDate());
log.info("# of contracts = "+contractArray.size());
Iterator contractIter = contractArray.iterator();
errorOrder = 0;
//Loop through all contracts
while(contractIter.hasNext())
{
contract = (ChildCareContract)contractIter.next();
errorRelated = new StringBuffer();
errorRelated.append("ChildcareContract "+contract.getPrimaryKey()+"<br>");
errorRelated.append("Contract "+contract.getContractID()+"<br>");
// **Fetch invoice receiver
custodian = contract.getApplication().getOwner();
errorRelated.append("Custodian "+custodian.getName()+"<br>");
//**Fetch the reference at the provider
school = contract.getApplication().getProvider();
errorRelated.append("School "+school.getName()+"<br>");
log.info("School = "+school);
// **Get or create the invoice header
InvoiceHeader invoiceHeader;
try{
try{
invoiceHeader = getInvoiceHeaderHome().findByCustodian(custodian);
} catch (FinderException e) {
//No header was found so we have to create it
invoiceHeader = getInvoiceHeaderHome().create();
//Fill in all the field available at this times
invoiceHeader.setSchoolCategory(category);
invoiceHeader.setPeriod(startPeriod.getDate());
invoiceHeader.setCustodianId(((Integer)custodian.getPrimaryKey()).intValue());
invoiceHeader.setDateCreated(currentDate);
invoiceHeader.setCreatedBy(BATCH_TEXT);
// SN: posting not applicable in invoice header anymore
// invoiceHeader.setOwnPosting(categoryPosting.getAccount());
// invoiceHeader.setDoublePosting(categoryPosting.getCounterAccount());
invoiceHeader.setStatus(ConstantStatus.PRELIMINARY);
System.out.println("Store Invoice Header with Category '"+invoiceHeader.getSchoolCategoryID());
System.out.println("and custodian "+invoiceHeader.getCustodianId());
System.out.println("Databean: "+invoiceHeader);
invoiceHeader.store();
}
errorRelated.append("InvoiceHeader "+invoiceHeader.getPrimaryKey()+"<br>");
// **Calculate how big part of time period this contract is valid for
calculateTime(contract.getValidFromDate(), contract.getTerminatedDate());
totalSum = 0;
subvention = null;
//
//Get the check for the contract
//
RegulationsBusiness regBus = getRegulationsBusiness();
//Get all the parameters needed to select the correct contract
SchoolClassMember schoolClassMember = contract.getSchoolClassMmeber();
System.out.println("Contract id "+contract.getPrimaryKey());
System.out.println("SchoolClassMmeberid "+schoolClassMember.getPrimaryKey());
SchoolType schoolType = schoolClassMember.getSchoolType();
String childcareType =schoolType.getLocalizationKey();
errorRelated.append("SchoolType "+schoolType.getName()+"<br>");
errorRelated.append("Child "+contract.getChild().getName()+"<br>");
//childcare = ((Integer)schoolClassMember.getSchoolType().getPrimaryKey()).intValue();
hours = contract.getCareTime();
age = new Age(contract.getChild().getDateOfBirth());
ArrayList conditions = new ArrayList();
errorRelated.append("Hours "+contract.getCareTime()+"<br>");
errorRelated.append("Age "+contract.getChild().getDateOfBirth()+"<br>");
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_OPERATION,childcareType));
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_HOURS,new Integer(hours)));
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_AGE_INTERVAL,new Integer(age.getYears())));
String employment = "";
EmploymentType employmentType = contract.getEmploymentType();
if(employmentType!= null){
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_EMPLOYMENT,employmentType.getPrimaryKey()));
employment = employmentType.getLocalizationKey();
errorRelated.append("EmploymentType "+employment+"<br>");
}
log.info("\n School type: "+childcareType+
"\n Hours "+hours+
"\n Years "+age.getYears()+
"\n Emplyment "+employment);
//Select a specific row from the regulation, given the following restrictions
log.info("Getting posting detail for:\n" +
" Category:"+category.getCategory()+"\n"+
" PaymentFlowConstant.OUT:"+PaymentFlowConstant.OUT+"\n"+
" currentDate:"+currentDate+"\n"+
" RuleTypeConstant.DERIVED:"+RuleTypeConstant.DERIVED+"\n"+
" RegSpecConstant.CHECK:"+RegSpecConstant.CHECK+"\n"+
" conditions:"+conditions.size()+"\n"+
" totalSum:"+totalSum+"\n"+
" contract:"+contract.getPrimaryKey()+"\n"
);
errorRelated.append("Category:"+category.getCategory()+"<br>"+
"PaymentFlowConstant.OUT:"+PaymentFlowConstant.OUT+"<br>"+
"currentDate:"+currentDate+"\n"+
"RuleTypeConstant.DERIVED:"+RuleTypeConstant.DERIVED+"<br>"+
"RegSpecConstant.CHECK:"+RegSpecConstant.CHECK+"<br>"+
"conditions:"+conditions.size()+"<br>"+
"totalSum:"+totalSum+"<br>"+
"contract:"+contract.getPrimaryKey()+"<br>");
postingDetail = regBus.getPostingDetailByOperationFlowPeriodConditionTypeRegSpecType(
category.getCategory(), //The ID that selects barnomsorg in the regulation
PaymentFlowConstant.OUT, //The payment flow is out
currentDate, //Current date to select the correct date range
RuleTypeConstant.DERIVED, //The conditiontype
RegSpecConstant.CHECK, //The ruleSpecType shall be Check
conditions, //The conditions that need to fulfilled
totalSum, //Sent in to be used for "Specialutrakning"
contract); //Sent in to be used for "Specialutrakning"
if(postingDetail == null){
throw new RegulationException("reg_exp_no_results","No regulations found.");
}
System.out.println("RuleSpecType to use: "+postingDetail.getTerm());
Provider provider = new Provider(((Integer)contract.getApplication().getProvider().getPrimaryKey()).intValue());
RegulationSpecType regSpecType = getRegulationSpecTypeHome().findByRegulationSpecType(RegSpecConstant.CHECK);
errorRelated.append("Regel Spec Typ "+regSpecType+"<br>");
String[] postings = getPostingBusiness().getPostingStrings(
category, schoolClassMember.getSchoolType(), ((Integer)regSpecType.getPrimaryKey()).intValue(), provider,currentDate);
String[] checkPost = getPostingBusiness().getPostingStrings(
category, schoolClassMember.getSchoolType(), ((Integer)getRegulationSpecTypeHome().findByRegulationSpecType(RegSpecConstant.CHECKTAXA).getPrimaryKey()).intValue(), provider,currentDate);
log.info("About to create payment record check");
PaymentRecord paymentRecord = createPaymentRecord(postingDetail, postings[0], checkPost[0]); //MUST create payment record first, since it is used in invoice record
log.info("created payment record, Now creating invoice record");
// **Create the invoice record
invoiceRecord = createInvoiceRecordForCheck(invoiceHeader,
school.getName()+", "+contract.getCareTime()+" "+HOURS_PER_WEEK, paymentRecord, postings[0], postings[1]);
log.info("created invoice record");
totalSum = postingDetail.getAmount()*months;
int siblingOrder = getSiblingOrder(contract);
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_SIBLING_NR,
new Integer(siblingOrder)));
log.info(" Sibling order set to: "+siblingOrder+" for "+schoolClassMember.getStudent().getName());
//Get all the rules for this contract
regulationArray = regBus.getAllRegulationsByOperationFlowPeriodConditionTypeRegSpecType(
category.getCategory(),//The ID that selects barnomsorg in the regulation
PaymentFlowConstant.IN, //The payment flow is out
startPeriod.getDate(), //Current date to select the correct date range
RuleTypeConstant.DERIVED, //The conditiontype
null,
conditions //The conditions that need to fulfilled
);
String tmpErrorRelated = errorRelated.toString();
log.info("Found "+regulationArray.size()+" regulations that apply.");
Iterator regulationIter = regulationArray.iterator();
while(regulationIter.hasNext())
{
errorRelated = new StringBuffer(tmpErrorRelated);
try {
Regulation regulation = (Regulation)regulationIter.next();
errorRelated.append("Regel "+regulation.getName()+"<br>");
log.info("regulation "+regulation.getName());
postingDetail = regBus.getPostingDetailForContract(
totalSum,
contract,
regulation,
startPeriod.getDate(),
conditions);
if(postingDetail==null){
log.warning("Posting detail is null!"+
"\n tot sum "+totalSum+
"\n contract "+contract.getPrimaryKey()+
"\n regulation "+regulation.getName()+
"\n start period "+startPeriod.toString()+
"\n # of conditions"+conditions.size());
throw new RegulationException("reg_exp_no_results", "No regulation match conditions");
}
errorRelated.append("Posting detail "+postingDetail+"<br>");
// **Create the invoice record
//TODO (JJ) get these strings from the postingDetail instead.
System.out.println("Regspectyp: "+postingDetail.getRuleSpecType());
System.out.println("Regspectyp: "+regulation.getRegSpecType().getLocalizationKey());
postingDetail.setRuleSpecType(regulation.getRegSpecType().getLocalizationKey()); //TODO (JJ) This is a patch, Pallis func should probably return the right one in the first place.
System.out.println("InvoiceHeader "+invoiceHeader.getPrimaryKey());
// RegulationSpecType regulationSpecType = getRegulationSpecTypeHome().findByRegulationSpecType(postingDetail.getRuleSpecType());
postings = getPostingBusiness().getPostingStrings(category, schoolClassMember.getSchoolType(), ((Integer)regulation.getRegSpecType().getPrimaryKey()).intValue(), provider,currentDate);
invoiceRecord = createInvoiceRecord(invoiceHeader, postings[0], "");
//Need to store the subvention row, so that it can be adjusted later if needed
if(postingDetail.getRuleSpecType()== RegSpecConstant.SUBVENTION){
subvention = invoiceRecord;
}
totalSum += postingDetail.getAmount()*months;
}
catch (BruttoIncomeException e) {
//Who cares!!!
}
catch (LowIncomeException e) {
//No low income registered...
}
catch (RegulationException e1) {
e1.printStackTrace();
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorFindingRegulationWhenItWasExpected");
}
}
//Make sure that the sum is not less than 0
log.info("Total sum is:"+totalSum);
if(totalSum<0){
if(subvention!=null){
log.info("Sum too low, changing subvention from "+subvention.getAmount()+"...to "+subvention.getAmount()+totalSum);
subvention.setAmount(subvention.getAmount()+totalSum);
subvention.store();
} else {
log.info("Sum too low, but no subvention found. Creating error message");
createNewErrorMessage(errorRelated.toString(),"invoice.noSubventionFoundAndSumLessThanZero");
}
}
}catch (NullPointerException e1) {
e1.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ReferenceErrorPossiblyNullInPrimaryKeyInDB");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ReferenceErrorPossiblyNullInPrimaryKeyInDB");
}
}catch (RegulationException e1) {
e1.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorFindingCheckRegulation");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ErrorFindingCheckRegulation");
}
} catch(MissingMandatoryFieldException e){
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.MissingMandatoryFieldInPostingParameter");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.MissingMandatoryFieldInPostingParameter");
}
} catch (PostingParametersException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorInPostingParameter");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ErrorInPostingParameter");
}
} catch (PostingException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.PostingParameterIncorrectlyFormatted");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.PostingParameterIncorrectlyFormatted");
}
} catch (CreateException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.DBProblem");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.DBProblem");
}
} catch (EJBException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.EJBError");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.EJBError");
}
} catch (SiblingOrderException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.CouldNotGetSiblingOrder");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.CouldNotGetSiblingOrder");
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
createNewErrorMessage("invoice.severeError","invoice.SeriousErrorBatchrunTerminated");
} catch (FinderException e) {
e.printStackTrace();
createNewErrorMessage("invoice.severeError","invoice.NoContractsFound");
}
}
/**
* Creates all the invoice headers, invoice records, payment headers and payment records
* for the Regular payments
*/
private void regularInvoice(){
int childID;
RegularInvoiceEntry regularInvoiceEntry=null;
try {
Iterator regularInvoiceIter = getRegularInvoiceBusiness().findRegularInvoicesForPeriodeAndCategory(startPeriod.getDate(), category).iterator();
//Go through all the regular invoices
while(regularInvoiceIter.hasNext()){
try{
User custodian = null;
InvoiceHeader invoiceHeader = null;
int custodianID = -1;
regularInvoiceEntry = (RegularInvoiceEntry)regularInvoiceIter.next();
StringBuffer errorRelated = new StringBuffer("RegularInvoiceEntry ID "+regularInvoiceEntry.getPrimaryKey()+"<br>");
//Get the child and then look up the custodian
childID = regularInvoiceEntry.getUserID();
errorRelated.append("Child "+childID+"<br>");
MemberFamilyLogic familyLogic = (MemberFamilyLogic) IBOLookup.getServiceInstance(iwc, MemberFamilyLogic.class);
User child = (User) IDOLookup.findByPrimaryKey(User.class, new Integer(childID));
errorRelated.append("Child name "+child.getName()+"<br>");
Iterator custodianIter = familyLogic.getCustodiansFor(child).iterator();
while (custodianIter.hasNext() && invoiceHeader == null) {
custodian = (User) custodianIter.next();
try{
invoiceHeader = getInvoiceHeaderHome().findByCustodianID(((Integer)custodian.getPrimaryKey()).intValue());
custodianID = ((Integer)custodian.getPrimaryKey()).intValue();
errorRelated.append("Parent "+custodianID+"<br>");
} catch (FinderException e) {
//That's OK, just keep looking
}
}
if(invoiceHeader==null){
// try{
// invoiceHeader = getInvoiceHeaderHome().findByCustodianID(custodianID);
// } catch (FinderException e) {
//No header was found so we have to create it
invoiceHeader = getInvoiceHeaderHome().create();
//Fill in all the field available at this times
invoiceHeader.setSchoolCategory(category);
invoiceHeader.setPeriod(startPeriod.getDate());
invoiceHeader.setCustodianId(custodianID);
invoiceHeader.setDateCreated(currentDate);
invoiceHeader.setCreatedBy(BATCH_TEXT);
// SN: posting not applicable in invoice header anymore
// invoiceHeader.setOwnPosting(categoryPosting.getAccount());
// invoiceHeader.setDoublePosting(categoryPosting.getCounterAccount());
invoiceHeader.setStatus(ConstantStatus.PRELIMINARY);
invoiceHeader.store();
createNewErrorMessage(errorRelated.toString(),"invoice.CouldNotFindCustodianForRegularInvoice");
}
errorRelated.append("Note "+regularInvoiceEntry.getNote()+"<br>");
calculateTime(new Date(regularInvoiceEntry.getFrom().getTime()),
new Date(regularInvoiceEntry.getTo().getTime()));
InvoiceRecord invoiceRecord = getInvoiceRecordHome().create();
invoiceRecord.setInvoiceHeader(invoiceHeader);
invoiceRecord.setInvoiceText(regularInvoiceEntry.getNote());
invoiceRecord.setProviderId(regularInvoiceEntry.getSchool());
invoiceRecord.setRuleText(regularInvoiceEntry.getNote());
invoiceRecord.setDays(days);
invoiceRecord.setPeriodStartCheck(startPeriod.getDate());
invoiceRecord.setPeriodEndCheck(endPeriod.getDate());
invoiceRecord.setPeriodStartPlacement(startTime.getDate());
invoiceRecord.setPeriodEndPlacement(endTime.getDate());
invoiceRecord.setDateCreated(currentDate);
invoiceRecord.setCreatedBy(BATCH_TEXT);
invoiceRecord.setAmount(regularInvoiceEntry.getAmount()*months);
invoiceRecord.setAmountVAT(regularInvoiceEntry.getVAT()*months);
invoiceRecord.setVATType(regularInvoiceEntry.getVatRuleId());
invoiceRecord.setRegSpecType(regularInvoiceEntry.getRegSpecType());
invoiceRecord.setOwnPosting(regularInvoiceEntry.getOwnPosting());
invoiceRecord.setDoublePosting(regularInvoiceEntry.getDoublePosting());
invoiceRecord.store();
} catch (RemoteException e) {
e.printStackTrace();
createNewErrorMessage(errorRelated.toString(),"invoice.DBSetupProblem");
} catch (CreateException e) {
e.printStackTrace();
createNewErrorMessage(errorRelated.toString(),"invoice.DBSetupProblem");
}
}
} catch (RemoteException e) {
e.printStackTrace();
createNewErrorMessage("invoice.RegularInvoices","invoice.CouldNotFindAnyRegularInvoicesTerminating");
} catch (FinderException e) {
e.printStackTrace();
createNewErrorMessage("invoice.RegularInvoices","invoice.CouldNotFindAnyRegularInvoicesTerminating");
}
}
/**
* Creates all the invoice headers, invoice records, payment headers and payment records
* for the Regular payments
*/
/*
protected void regularPayment() {
PostingDetail postingDetail = null;
try {
Iterator regularPaymentIter = getRegularPaymentBusiness().findRegularPaymentsForPeriodeAndCategory(startPeriod.getDate(), category).iterator();
//Go through all the regular payments
while (regularPaymentIter.hasNext()) {
RegularPaymentEntry regularPaymentEntry = (RegularPaymentEntry) regularPaymentIter.next();
postingDetail = new PostingDetail(regularPaymentEntry);
createPaymentRecord(postingDetail, regularPaymentEntry.getOwnPosting(), regularPaymentEntry.getDoublePosting());
}
}
catch (Exception e) {
e.printStackTrace();
if (postingDetail != null) {
createNewErrorMessage(postingDetail.getTerm(), "payment.DBSetupProblem");
}
else {
createNewErrorMessage("payment.severeError", "payment.DBSetupProblem");
}
}
}
*/
/**
* Code to set all the sibling order used to calculate the sibling discount for each contract.
* At the moment there is no sibling order column in the User object, so this function is not used.
* Instead the getSiblingOrder(ChildCareContract contract) is used.
*
* This methode will probably not be used getSiblingOrder() will take care of the whole work
*
* @param contractIter
*/
/*
private void setSiblingOrder(Iterator contractIter){
boolean found;
TreeSet sortedSiblings;
//Zero all sibling orders
ChildCareContract contract;
//Itterate through all contracts
while(contractIter.hasNext()){
contract = (ChildCareContract)contractIter.next();
sortedSiblings = new TreeSet();
SortableSibling sortableChild = new SortableSibling(contract.getChild());
sortedSiblings.add(sortableChild);
List parents = contract.getChild().getParentGroups();
Iterator parentIter = parents.iterator();
//Itterate through parents
while(parentIter.hasNext()){
User parent = (User)parentIter.next();
Iterator siblingsIter = parent.getChildren();
//Itterate through their kids
Collection addr1Coll = contract.getChild().getAddresses();
while(siblingsIter.hasNext())
{
User sibling = (User) siblingsIter.next();
//If kids have same address add to collection
found = false;
Collection addr2Coll = sibling.getAddresses();
Iterator addr1Iter = addr1Coll.iterator();
while(addr1Iter.hasNext() && found==false){
Address addr1 = (Address)addr1Iter.next();
Iterator addr2Iter = addr2Coll.iterator();
while(addr2Iter.hasNext() && found==false){
Address addr2 = (Address)addr2Iter.next();
if(addr1.getPrimaryKey().equals(addr2.getPrimaryKey())){
found = true;
}
}
}
//Sort kids in age order
if(found){
SortableSibling sortableSibling = new SortableSibling(sibling);
if(!sortedSiblings.contains(sortableSibling)){
sortedSiblings.add(sortableSibling);
}
}
}
}
// Here we need to set the order to the User objects if allowed to create an extra col
sortedSiblings.headSet(sortableChild).size();
}
}
*/
/**
* Calculates the sibling order for the child connected to a contract
* and also stores the order for all of its siblings.
*
* @param contract
* @return the sibling order for the child connected to the contract
*/
private int getSiblingOrder(ChildCareContract contract) throws EJBException, SiblingOrderException, IDOLookupException, RemoteException, CreateException{
UserBusiness userBus = (UserBusiness) IBOLookup.getServiceInstance(iwc, UserBusiness.class);
// log.info("Trying to get sibling order for "+contract.getChild().getName());
//First see if the child already has been given a sibling order
MemberFamilyLogic familyLogic = (MemberFamilyLogic) IBOLookup.getServiceInstance(iwc, MemberFamilyLogic.class);
Integer order = (Integer)siblingOrders.get(contract.getChild().getPrimaryKey());
if(order != null)
{
// log.info("Sibling order already calculated: "+order.intValue());
return order.intValue(); //Sibling order already calculated.
}
TreeSet sortedSiblings = new TreeSet(); //Container for the siblings that keeps them in sorted order
Address childAddress = userBus.getUsersMainAddress(contract.getChild());
//Add the child to the sibbling collection right away to make sure it will be in there
//This should really happen in the main loop below as well, but this is done since
//the realtionships seem to be a bit unreliable
sortedSiblings.add(new SortableSibling(contract.getChild()));
//Gather up a collection of the parents and their cohabitants
Collection parents; //Collection parents only hold the biological parents
try {
parents = familyLogic.getCustodiansFor(contract.getChild());
} catch (NoCustodianFound e1) {
throw new SiblingOrderException("No custodians found for the child.");
}
//Adults hold all the adults that could be living on the same address
Collection adults = new ArrayList(parents);
Iterator parentIter = parents.iterator();
//Itterate through parents
while(parentIter.hasNext()){
User parent = (User)parentIter.next();
// log.info("Found parent: "+parent.getName());
try {
// log.info("Found cohabitant: "+familyLogic.getCohabitantFor(parent));
adults.add(familyLogic.getCohabitantFor(parent));
} catch (NoCohabitantFound e) {
}
}
//Loop through all adults
Iterator adultIter = adults.iterator();
while(adultIter.hasNext()){
User adult = (User)adultIter.next();
// log.info("Getting children for "+adult.getName());
Iterator siblingsIter;
try {
siblingsIter = familyLogic.getChildrenFor(adult).iterator();
//Itterate through their kids
while(siblingsIter.hasNext())
{
User sibling = (User) siblingsIter.next();
// log.info("Checking child: "+sibling.getName());
//Check if the sibling has a valid contract of right type
try {
getChildCareContractHome().findValidContractByChild(((Integer)sibling.getPrimaryKey()).intValue(),startPeriod.getDate());
//If kids have same address add to collection
Address siblingAddress = userBus.getUsersMainAddress(contract.getChild());
// log.info("cpa "+childAddress.getPostalAddress()+
// "\ncc "+childAddress.getCity()+
// "\ncPOB "+childAddress.getStreetAddress()+
// "\nspa "+siblingAddress.getPostalAddress()+
// "\nsc "+siblingAddress.getCity()+
// "\nsPOB "+siblingAddress.getStreetAddress()
// );
if(childAddress.getPostalAddress().equals(siblingAddress.getPostalAddress()) &&
childAddress.getCity().equals(siblingAddress.getCity()) &&
childAddress.getStreetAddress().equals(siblingAddress.getStreetAddress())){
// log.info(("child was at same address, adding"));
SortableSibling sortableSibling = new SortableSibling(sibling);
if(!sortedSiblings.contains(sortableSibling)){
sortedSiblings.add(sortableSibling);
}
}
} catch (FinderException e) {
//If sibling don't have a childcare contract we just ignore it
} catch (NullPointerException e) {
//If sibling doesn't have an address or contract, it won't be counted in the sibling order
createNewErrorMessage(contract.getChild().getName(),"invoice.ChildHasNoAddress");
}
}
} catch (RemoteException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (NoChildrenFound e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Store the sorting order
Iterator sortedIter = sortedSiblings.iterator();
int orderNr = 1;
while(sortedIter.hasNext()){
SortableSibling sortableSibling = (SortableSibling)sortedIter.next();
siblingOrders.put(sortableSibling.getSibling().getPrimaryKey(),new Integer(orderNr));
log.info("Added child "+sortableSibling.getSibling()+" as sibling "+orderNr+" out of "+sortedSiblings.size());
orderNr++;
}
//Look up the order of the child that started the whole thing
order = (Integer)siblingOrders.get(contract.getChild().getPrimaryKey());
if(order != null)
{
return order.intValue();
}
//This should really never happen
throw new SiblingOrderException("Could not find the sibling order.");
}
/**
* Creates an invoice record with the specific descriptive text for the check.
* @param invoiceHeader
* @param header
* @param paymentRecord
* @return the created invoice record
* @throws PostingParametersException
* @throws PostingException
* @throws RemoteException
* @throws CreateException
* @throws MissingMandatoryFieldException
*/
private InvoiceRecord createInvoiceRecordForCheck(InvoiceHeader invoiceHeader, String header, PaymentRecord paymentRecord, String ownPosting, String doublePosting) throws PostingParametersException, PostingException, RemoteException, CreateException, MissingMandatoryFieldException{
InvoiceRecord invoiceRecord = getInvoiceRecordHome().create();
invoiceRecord.setInvoiceHeader(invoiceHeader);
invoiceRecord.setInvoiceText(header);
//set the reference to payment record (utbetalningsposten)
invoiceRecord.setPaymentRecordId(paymentRecord);
return createInvoiceRecordSub(invoiceRecord, ownPosting, doublePosting);
}
/**
* Creates an invoice record
* @param invoiceHeader
* @return the created invoice record
* @throws PostingParametersException
* @throws PostingException
* @throws RemoteException
* @throws CreateException
* @throws MissingMandatoryFieldException
*/
private InvoiceRecord createInvoiceRecord(InvoiceHeader invoiceHeader, String ownPosting, String doublePosting) throws PostingParametersException, PostingException, RemoteException, CreateException, MissingMandatoryFieldException{
InvoiceRecord invoiceRecord = getInvoiceRecordHome().create();
invoiceRecord.setInvoiceHeader(invoiceHeader);
invoiceRecord.setInvoiceText(postingDetail.getTerm());
return createInvoiceRecordSub(invoiceRecord, ownPosting, doublePosting);
}
/**
* Does all the work of creating an invoice record that is the same for both check
* and non-check invoice records
*
* @param invoiceRecord
* @return the created invoice record
* @throws CreateException
* @throws PostingParametersException
* @throws PostingException
* @throws RemoteException
* @throws MissingMandatoryFieldException
*/
private InvoiceRecord createInvoiceRecordSub(InvoiceRecord invoiceRecord, String ownPosting, String doublePosting) throws CreateException, PostingParametersException, PostingException, RemoteException, MissingMandatoryFieldException{
invoiceRecord.setProviderId(school);
// invoiceRecord.setContractId(contract.getContractID());
invoiceRecord.setSchoolClassMember(contract.getSchoolClassMmeber());
invoiceRecord.setRuleText(postingDetail.getTerm());
invoiceRecord.setDays(days);
invoiceRecord.setPeriodStartCheck(startPeriod.getDate());
invoiceRecord.setPeriodEndCheck(endPeriod.getDate());
invoiceRecord.setPeriodStartPlacement(startTime.getDate());
invoiceRecord.setPeriodEndPlacement(endTime.getDate());
invoiceRecord.setDateCreated(currentDate);
invoiceRecord.setCreatedBy(BATCH_TEXT);
invoiceRecord.setAmount(postingDetail.getAmount()*months);
invoiceRecord.setAmountVAT(postingDetail.getVat()*months);
invoiceRecord.setVATType(postingDetail.getVatRegulationID());
invoiceRecord.setOrderId(postingDetail.getOrderID());
RegulationSpecTypeHome regSpecTypeHome = (RegulationSpecTypeHome) IDOLookup.getHome(RegulationSpecType.class);
try {
RegulationSpecType regSpecType = regSpecTypeHome.findByRegulationSpecType(postingDetail.getRuleSpecType());
invoiceRecord.setRegSpecType(regSpecType);
} catch (Exception e) {
e.printStackTrace ();
}
//Set the posting strings
invoiceRecord.setOwnPosting(ownPosting);
invoiceRecord.setDoublePosting(doublePosting);
invoiceRecord.store();
return invoiceRecord;
}
}
| true | true | private void contracts(){
Collection contractArray = new ArrayList();
Collection regulationArray = new ArrayList();
User custodian;
Age age;
int hours;
float totalSum;
InvoiceRecord invoiceRecord, subvention;
try {
contractArray = getChildCareContractHome().findByDateRange(startPeriod.getDate(), endPeriod.getDate());
log.info("# of contracts = "+contractArray.size());
Iterator contractIter = contractArray.iterator();
errorOrder = 0;
//Loop through all contracts
while(contractIter.hasNext())
{
contract = (ChildCareContract)contractIter.next();
errorRelated = new StringBuffer();
errorRelated.append("ChildcareContract "+contract.getPrimaryKey()+"<br>");
errorRelated.append("Contract "+contract.getContractID()+"<br>");
// **Fetch invoice receiver
custodian = contract.getApplication().getOwner();
errorRelated.append("Custodian "+custodian.getName()+"<br>");
//**Fetch the reference at the provider
school = contract.getApplication().getProvider();
errorRelated.append("School "+school.getName()+"<br>");
log.info("School = "+school);
// **Get or create the invoice header
InvoiceHeader invoiceHeader;
try{
try{
invoiceHeader = getInvoiceHeaderHome().findByCustodian(custodian);
} catch (FinderException e) {
//No header was found so we have to create it
invoiceHeader = getInvoiceHeaderHome().create();
//Fill in all the field available at this times
invoiceHeader.setSchoolCategory(category);
invoiceHeader.setPeriod(startPeriod.getDate());
invoiceHeader.setCustodianId(((Integer)custodian.getPrimaryKey()).intValue());
invoiceHeader.setDateCreated(currentDate);
invoiceHeader.setCreatedBy(BATCH_TEXT);
// SN: posting not applicable in invoice header anymore
// invoiceHeader.setOwnPosting(categoryPosting.getAccount());
// invoiceHeader.setDoublePosting(categoryPosting.getCounterAccount());
invoiceHeader.setStatus(ConstantStatus.PRELIMINARY);
System.out.println("Store Invoice Header with Category '"+invoiceHeader.getSchoolCategoryID());
System.out.println("and custodian "+invoiceHeader.getCustodianId());
System.out.println("Databean: "+invoiceHeader);
invoiceHeader.store();
}
errorRelated.append("InvoiceHeader "+invoiceHeader.getPrimaryKey()+"<br>");
// **Calculate how big part of time period this contract is valid for
calculateTime(contract.getValidFromDate(), contract.getTerminatedDate());
totalSum = 0;
subvention = null;
//
//Get the check for the contract
//
RegulationsBusiness regBus = getRegulationsBusiness();
//Get all the parameters needed to select the correct contract
SchoolClassMember schoolClassMember = contract.getSchoolClassMmeber();
System.out.println("Contract id "+contract.getPrimaryKey());
System.out.println("SchoolClassMmeberid "+schoolClassMember.getPrimaryKey());
SchoolType schoolType = schoolClassMember.getSchoolType();
String childcareType =schoolType.getLocalizationKey();
errorRelated.append("SchoolType "+schoolType.getName()+"<br>");
errorRelated.append("Child "+contract.getChild().getName()+"<br>");
//childcare = ((Integer)schoolClassMember.getSchoolType().getPrimaryKey()).intValue();
hours = contract.getCareTime();
age = new Age(contract.getChild().getDateOfBirth());
ArrayList conditions = new ArrayList();
errorRelated.append("Hours "+contract.getCareTime()+"<br>");
errorRelated.append("Age "+contract.getChild().getDateOfBirth()+"<br>");
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_OPERATION,childcareType));
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_HOURS,new Integer(hours)));
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_AGE_INTERVAL,new Integer(age.getYears())));
String employment = "";
EmploymentType employmentType = contract.getEmploymentType();
if(employmentType!= null){
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_EMPLOYMENT,employmentType.getPrimaryKey()));
employment = employmentType.getLocalizationKey();
errorRelated.append("EmploymentType "+employment+"<br>");
}
log.info("\n School type: "+childcareType+
"\n Hours "+hours+
"\n Years "+age.getYears()+
"\n Emplyment "+employment);
//Select a specific row from the regulation, given the following restrictions
log.info("Getting posting detail for:\n" +
" Category:"+category.getCategory()+"\n"+
" PaymentFlowConstant.OUT:"+PaymentFlowConstant.OUT+"\n"+
" currentDate:"+currentDate+"\n"+
" RuleTypeConstant.DERIVED:"+RuleTypeConstant.DERIVED+"\n"+
" RegSpecConstant.CHECK:"+RegSpecConstant.CHECK+"\n"+
" conditions:"+conditions.size()+"\n"+
" totalSum:"+totalSum+"\n"+
" contract:"+contract.getPrimaryKey()+"\n"
);
errorRelated.append("Category:"+category.getCategory()+"<br>"+
"PaymentFlowConstant.OUT:"+PaymentFlowConstant.OUT+"<br>"+
"currentDate:"+currentDate+"\n"+
"RuleTypeConstant.DERIVED:"+RuleTypeConstant.DERIVED+"<br>"+
"RegSpecConstant.CHECK:"+RegSpecConstant.CHECK+"<br>"+
"conditions:"+conditions.size()+"<br>"+
"totalSum:"+totalSum+"<br>"+
"contract:"+contract.getPrimaryKey()+"<br>");
postingDetail = regBus.getPostingDetailByOperationFlowPeriodConditionTypeRegSpecType(
category.getCategory(), //The ID that selects barnomsorg in the regulation
PaymentFlowConstant.OUT, //The payment flow is out
currentDate, //Current date to select the correct date range
RuleTypeConstant.DERIVED, //The conditiontype
RegSpecConstant.CHECK, //The ruleSpecType shall be Check
conditions, //The conditions that need to fulfilled
totalSum, //Sent in to be used for "Specialutrakning"
contract); //Sent in to be used for "Specialutrakning"
if(postingDetail == null){
throw new RegulationException("reg_exp_no_results","No regulations found.");
}
System.out.println("RuleSpecType to use: "+postingDetail.getTerm());
Provider provider = new Provider(((Integer)contract.getApplication().getProvider().getPrimaryKey()).intValue());
RegulationSpecType regSpecType = getRegulationSpecTypeHome().findByRegulationSpecType(RegSpecConstant.CHECK);
errorRelated.append("Regel Spec Typ "+regSpecType+"<br>");
String[] postings = getPostingBusiness().getPostingStrings(
category, schoolClassMember.getSchoolType(), ((Integer)regSpecType.getPrimaryKey()).intValue(), provider,currentDate);
String[] checkPost = getPostingBusiness().getPostingStrings(
category, schoolClassMember.getSchoolType(), ((Integer)getRegulationSpecTypeHome().findByRegulationSpecType(RegSpecConstant.CHECKTAXA).getPrimaryKey()).intValue(), provider,currentDate);
log.info("About to create payment record check");
PaymentRecord paymentRecord = createPaymentRecord(postingDetail, postings[0], checkPost[0]); //MUST create payment record first, since it is used in invoice record
log.info("created payment record, Now creating invoice record");
// **Create the invoice record
invoiceRecord = createInvoiceRecordForCheck(invoiceHeader,
school.getName()+", "+contract.getCareTime()+" "+HOURS_PER_WEEK, paymentRecord, postings[0], postings[1]);
log.info("created invoice record");
totalSum = postingDetail.getAmount()*months;
int siblingOrder = getSiblingOrder(contract);
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_SIBLING_NR,
new Integer(siblingOrder)));
log.info(" Sibling order set to: "+siblingOrder+" for "+schoolClassMember.getStudent().getName());
//Get all the rules for this contract
regulationArray = regBus.getAllRegulationsByOperationFlowPeriodConditionTypeRegSpecType(
category.getCategory(),//The ID that selects barnomsorg in the regulation
PaymentFlowConstant.IN, //The payment flow is out
startPeriod.getDate(), //Current date to select the correct date range
RuleTypeConstant.DERIVED, //The conditiontype
null,
conditions //The conditions that need to fulfilled
);
String tmpErrorRelated = errorRelated.toString();
log.info("Found "+regulationArray.size()+" regulations that apply.");
Iterator regulationIter = regulationArray.iterator();
while(regulationIter.hasNext())
{
errorRelated = new StringBuffer(tmpErrorRelated);
try {
Regulation regulation = (Regulation)regulationIter.next();
errorRelated.append("Regel "+regulation.getName()+"<br>");
log.info("regulation "+regulation.getName());
postingDetail = regBus.getPostingDetailForContract(
totalSum,
contract,
regulation,
startPeriod.getDate(),
conditions);
if(postingDetail==null){
log.warning("Posting detail is null!"+
"\n tot sum "+totalSum+
"\n contract "+contract.getPrimaryKey()+
"\n regulation "+regulation.getName()+
"\n start period "+startPeriod.toString()+
"\n # of conditions"+conditions.size());
throw new RegulationException("reg_exp_no_results", "No regulation match conditions");
}
errorRelated.append("Posting detail "+postingDetail+"<br>");
// **Create the invoice record
//TODO (JJ) get these strings from the postingDetail instead.
System.out.println("Regspectyp: "+postingDetail.getRuleSpecType());
System.out.println("Regspectyp: "+regulation.getRegSpecType().getLocalizationKey());
postingDetail.setRuleSpecType(regulation.getRegSpecType().getLocalizationKey()); //TODO (JJ) This is a patch, Pallis func should probably return the right one in the first place.
System.out.println("InvoiceHeader "+invoiceHeader.getPrimaryKey());
// RegulationSpecType regulationSpecType = getRegulationSpecTypeHome().findByRegulationSpecType(postingDetail.getRuleSpecType());
postings = getPostingBusiness().getPostingStrings(category, schoolClassMember.getSchoolType(), ((Integer)regulation.getRegSpecType().getPrimaryKey()).intValue(), provider,currentDate);
invoiceRecord = createInvoiceRecord(invoiceHeader, postings[0], "");
//Need to store the subvention row, so that it can be adjusted later if needed
if(postingDetail.getRuleSpecType()== RegSpecConstant.SUBVENTION){
subvention = invoiceRecord;
}
totalSum += postingDetail.getAmount()*months;
}
catch (BruttoIncomeException e) {
//Who cares!!!
}
catch (LowIncomeException e) {
//No low income registered...
}
catch (RegulationException e1) {
e1.printStackTrace();
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorFindingRegulationWhenItWasExpected");
}
}
//Make sure that the sum is not less than 0
log.info("Total sum is:"+totalSum);
if(totalSum<0){
if(subvention!=null){
log.info("Sum too low, changing subvention from "+subvention.getAmount()+"...to "+subvention.getAmount()+totalSum);
subvention.setAmount(subvention.getAmount()+totalSum);
subvention.store();
} else {
log.info("Sum too low, but no subvention found. Creating error message");
createNewErrorMessage(errorRelated.toString(),"invoice.noSubventionFoundAndSumLessThanZero");
}
}
}catch (NullPointerException e1) {
e1.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ReferenceErrorPossiblyNullInPrimaryKeyInDB");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ReferenceErrorPossiblyNullInPrimaryKeyInDB");
}
}catch (RegulationException e1) {
e1.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorFindingCheckRegulation");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ErrorFindingCheckRegulation");
}
} catch(MissingMandatoryFieldException e){
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.MissingMandatoryFieldInPostingParameter");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.MissingMandatoryFieldInPostingParameter");
}
} catch (PostingParametersException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorInPostingParameter");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ErrorInPostingParameter");
}
} catch (PostingException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.PostingParameterIncorrectlyFormatted");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.PostingParameterIncorrectlyFormatted");
}
} catch (CreateException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.DBProblem");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.DBProblem");
}
} catch (EJBException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.EJBError");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.EJBError");
}
} catch (SiblingOrderException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.CouldNotGetSiblingOrder");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.CouldNotGetSiblingOrder");
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
createNewErrorMessage("invoice.severeError","invoice.SeriousErrorBatchrunTerminated");
} catch (FinderException e) {
e.printStackTrace();
createNewErrorMessage("invoice.severeError","invoice.NoContractsFound");
}
}
| private void contracts(){
Collection contractArray = new ArrayList();
Collection regulationArray = new ArrayList();
User custodian;
Age age;
int hours;
float totalSum;
InvoiceRecord invoiceRecord, subvention;
try {
contractArray = getChildCareContractHome().findByDateRangeWhereStatusActive(startPeriod.getDate(), endPeriod.getDate());
log.info("# of contracts = "+contractArray.size());
Iterator contractIter = contractArray.iterator();
errorOrder = 0;
//Loop through all contracts
while(contractIter.hasNext())
{
contract = (ChildCareContract)contractIter.next();
errorRelated = new StringBuffer();
errorRelated.append("ChildcareContract "+contract.getPrimaryKey()+"<br>");
errorRelated.append("Contract "+contract.getContractID()+"<br>");
// **Fetch invoice receiver
custodian = contract.getApplication().getOwner();
errorRelated.append("Custodian "+custodian.getName()+"<br>");
//**Fetch the reference at the provider
school = contract.getApplication().getProvider();
errorRelated.append("School "+school.getName()+"<br>");
log.info("School = "+school);
// **Get or create the invoice header
InvoiceHeader invoiceHeader;
try{
try{
invoiceHeader = getInvoiceHeaderHome().findByCustodian(custodian);
} catch (FinderException e) {
//No header was found so we have to create it
invoiceHeader = getInvoiceHeaderHome().create();
//Fill in all the field available at this times
invoiceHeader.setSchoolCategory(category);
invoiceHeader.setPeriod(startPeriod.getDate());
invoiceHeader.setCustodianId(((Integer)custodian.getPrimaryKey()).intValue());
invoiceHeader.setDateCreated(currentDate);
invoiceHeader.setCreatedBy(BATCH_TEXT);
// SN: posting not applicable in invoice header anymore
// invoiceHeader.setOwnPosting(categoryPosting.getAccount());
// invoiceHeader.setDoublePosting(categoryPosting.getCounterAccount());
invoiceHeader.setStatus(ConstantStatus.PRELIMINARY);
System.out.println("Store Invoice Header with Category '"+invoiceHeader.getSchoolCategoryID());
System.out.println("and custodian "+invoiceHeader.getCustodianId());
System.out.println("Databean: "+invoiceHeader);
invoiceHeader.store();
}
errorRelated.append("InvoiceHeader "+invoiceHeader.getPrimaryKey()+"<br>");
// **Calculate how big part of time period this contract is valid for
calculateTime(contract.getValidFromDate(), contract.getTerminatedDate());
totalSum = 0;
subvention = null;
//
//Get the check for the contract
//
RegulationsBusiness regBus = getRegulationsBusiness();
//Get all the parameters needed to select the correct contract
SchoolClassMember schoolClassMember = contract.getSchoolClassMmeber();
System.out.println("Contract id "+contract.getPrimaryKey());
System.out.println("SchoolClassMmeberid "+schoolClassMember.getPrimaryKey());
SchoolType schoolType = schoolClassMember.getSchoolType();
String childcareType =schoolType.getLocalizationKey();
errorRelated.append("SchoolType "+schoolType.getName()+"<br>");
errorRelated.append("Child "+contract.getChild().getName()+"<br>");
//childcare = ((Integer)schoolClassMember.getSchoolType().getPrimaryKey()).intValue();
hours = contract.getCareTime();
age = new Age(contract.getChild().getDateOfBirth());
ArrayList conditions = new ArrayList();
errorRelated.append("Hours "+contract.getCareTime()+"<br>");
errorRelated.append("Age "+contract.getChild().getDateOfBirth()+"<br>");
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_OPERATION,childcareType));
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_HOURS,new Integer(hours)));
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_AGE_INTERVAL,new Integer(age.getYears())));
String employment = "";
EmploymentType employmentType = contract.getEmploymentType();
if(employmentType!= null){
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_EMPLOYMENT,employmentType.getPrimaryKey()));
employment = employmentType.getLocalizationKey();
errorRelated.append("EmploymentType "+employment+"<br>");
}
log.info("\n School type: "+childcareType+
"\n Hours "+hours+
"\n Years "+age.getYears()+
"\n Emplyment "+employment);
//Select a specific row from the regulation, given the following restrictions
log.info("Getting posting detail for:\n" +
" Category:"+category.getCategory()+"\n"+
" PaymentFlowConstant.OUT:"+PaymentFlowConstant.OUT+"\n"+
" currentDate:"+currentDate+"\n"+
" RuleTypeConstant.DERIVED:"+RuleTypeConstant.DERIVED+"\n"+
" RegSpecConstant.CHECK:"+RegSpecConstant.CHECK+"\n"+
" conditions:"+conditions.size()+"\n"+
" totalSum:"+totalSum+"\n"+
" contract:"+contract.getPrimaryKey()+"\n"
);
errorRelated.append("Category:"+category.getCategory()+"<br>"+
"PaymentFlowConstant.OUT:"+PaymentFlowConstant.OUT+"<br>"+
"currentDate:"+currentDate+"\n"+
"RuleTypeConstant.DERIVED:"+RuleTypeConstant.DERIVED+"<br>"+
"RegSpecConstant.CHECK:"+RegSpecConstant.CHECK+"<br>"+
"conditions:"+conditions.size()+"<br>"+
"totalSum:"+totalSum+"<br>"+
"contract:"+contract.getPrimaryKey()+"<br>");
postingDetail = regBus.getPostingDetailByOperationFlowPeriodConditionTypeRegSpecType(
category.getCategory(), //The ID that selects barnomsorg in the regulation
PaymentFlowConstant.OUT, //The payment flow is out
currentDate, //Current date to select the correct date range
RuleTypeConstant.DERIVED, //The conditiontype
RegSpecConstant.CHECK, //The ruleSpecType shall be Check
conditions, //The conditions that need to fulfilled
totalSum, //Sent in to be used for "Specialutrakning"
contract); //Sent in to be used for "Specialutrakning"
if(postingDetail == null){
throw new RegulationException("reg_exp_no_results","No regulations found.");
}
System.out.println("RuleSpecType to use: "+postingDetail.getTerm());
Provider provider = new Provider(((Integer)contract.getApplication().getProvider().getPrimaryKey()).intValue());
RegulationSpecType regSpecType = getRegulationSpecTypeHome().findByRegulationSpecType(RegSpecConstant.CHECK);
errorRelated.append("Regel Spec Typ "+regSpecType+"<br>");
String[] postings = getPostingBusiness().getPostingStrings(
category, schoolClassMember.getSchoolType(), ((Integer)regSpecType.getPrimaryKey()).intValue(), provider,currentDate);
String[] checkPost = getPostingBusiness().getPostingStrings(
category, schoolClassMember.getSchoolType(), ((Integer)getRegulationSpecTypeHome().findByRegulationSpecType(RegSpecConstant.CHECKTAXA).getPrimaryKey()).intValue(), provider,currentDate);
log.info("About to create payment record check");
PaymentRecord paymentRecord = createPaymentRecord(postingDetail, postings[0], checkPost[0]); //MUST create payment record first, since it is used in invoice record
log.info("created payment record, Now creating invoice record");
// **Create the invoice record
invoiceRecord = createInvoiceRecordForCheck(invoiceHeader,
school.getName()+", "+contract.getCareTime()+" "+HOURS_PER_WEEK, paymentRecord, postings[0], postings[1]);
log.info("created invoice record");
totalSum = postingDetail.getAmount()*months;
int siblingOrder = getSiblingOrder(contract);
conditions.add(new ConditionParameter(RuleTypeConstant.CONDITION_ID_SIBLING_NR,
new Integer(siblingOrder)));
log.info(" Sibling order set to: "+siblingOrder+" for "+schoolClassMember.getStudent().getName());
//Get all the rules for this contract
regulationArray = regBus.getAllRegulationsByOperationFlowPeriodConditionTypeRegSpecType(
category.getCategory(),//The ID that selects barnomsorg in the regulation
PaymentFlowConstant.IN, //The payment flow is out
startPeriod.getDate(), //Current date to select the correct date range
RuleTypeConstant.DERIVED, //The conditiontype
null,
conditions //The conditions that need to fulfilled
);
String tmpErrorRelated = errorRelated.toString();
log.info("Found "+regulationArray.size()+" regulations that apply.");
Iterator regulationIter = regulationArray.iterator();
while(regulationIter.hasNext())
{
errorRelated = new StringBuffer(tmpErrorRelated);
try {
Regulation regulation = (Regulation)regulationIter.next();
errorRelated.append("Regel "+regulation.getName()+"<br>");
log.info("regulation "+regulation.getName());
postingDetail = regBus.getPostingDetailForContract(
totalSum,
contract,
regulation,
startPeriod.getDate(),
conditions);
if(postingDetail==null){
log.warning("Posting detail is null!"+
"\n tot sum "+totalSum+
"\n contract "+contract.getPrimaryKey()+
"\n regulation "+regulation.getName()+
"\n start period "+startPeriod.toString()+
"\n # of conditions"+conditions.size());
throw new RegulationException("reg_exp_no_results", "No regulation match conditions");
}
errorRelated.append("Posting detail "+postingDetail+"<br>");
// **Create the invoice record
//TODO (JJ) get these strings from the postingDetail instead.
System.out.println("Regspectyp: "+postingDetail.getRuleSpecType());
System.out.println("Regspectyp: "+regulation.getRegSpecType().getLocalizationKey());
postingDetail.setRuleSpecType(regulation.getRegSpecType().getLocalizationKey()); //TODO (JJ) This is a patch, Pallis func should probably return the right one in the first place.
System.out.println("InvoiceHeader "+invoiceHeader.getPrimaryKey());
// RegulationSpecType regulationSpecType = getRegulationSpecTypeHome().findByRegulationSpecType(postingDetail.getRuleSpecType());
postings = getPostingBusiness().getPostingStrings(category, schoolClassMember.getSchoolType(), ((Integer)regulation.getRegSpecType().getPrimaryKey()).intValue(), provider,currentDate);
invoiceRecord = createInvoiceRecord(invoiceHeader, postings[0], "");
//Need to store the subvention row, so that it can be adjusted later if needed
if(postingDetail.getRuleSpecType()== RegSpecConstant.SUBVENTION){
subvention = invoiceRecord;
}
totalSum += postingDetail.getAmount()*months;
}
catch (BruttoIncomeException e) {
//Who cares!!!
}
catch (LowIncomeException e) {
//No low income registered...
}
catch (RegulationException e1) {
e1.printStackTrace();
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorFindingRegulationWhenItWasExpected");
}
}
//Make sure that the sum is not less than 0
log.info("Total sum is:"+totalSum);
if(totalSum<0){
if(subvention!=null){
log.info("Sum too low, changing subvention from "+subvention.getAmount()+"...to "+subvention.getAmount()+totalSum);
subvention.setAmount(subvention.getAmount()+totalSum);
subvention.store();
} else {
log.info("Sum too low, but no subvention found. Creating error message");
createNewErrorMessage(errorRelated.toString(),"invoice.noSubventionFoundAndSumLessThanZero");
}
}
}catch (NullPointerException e1) {
e1.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ReferenceErrorPossiblyNullInPrimaryKeyInDB");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ReferenceErrorPossiblyNullInPrimaryKeyInDB");
}
}catch (RegulationException e1) {
e1.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorFindingCheckRegulation");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ErrorFindingCheckRegulation");
}
} catch(MissingMandatoryFieldException e){
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.MissingMandatoryFieldInPostingParameter");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.MissingMandatoryFieldInPostingParameter");
}
} catch (PostingParametersException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.ErrorInPostingParameter");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.ErrorInPostingParameter");
}
} catch (PostingException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.PostingParameterIncorrectlyFormatted");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.PostingParameterIncorrectlyFormatted");
}
} catch (CreateException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.DBProblem");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.DBProblem");
}
} catch (EJBException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.EJBError");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.EJBError");
}
} catch (SiblingOrderException e) {
e.printStackTrace();
if(errorRelated != null){
createNewErrorMessage(errorRelated.toString(),"invoice.CouldNotGetSiblingOrder");
} else{
createNewErrorMessage(contract.getChild().getName(),"invoice.CouldNotGetSiblingOrder");
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
createNewErrorMessage("invoice.severeError","invoice.SeriousErrorBatchrunTerminated");
} catch (FinderException e) {
e.printStackTrace();
createNewErrorMessage("invoice.severeError","invoice.NoContractsFound");
}
}
|
diff --git a/webmacro/src/org/webmacro/directive/ParseDirective.java b/webmacro/src/org/webmacro/directive/ParseDirective.java
index b8880ca5..ea8a31f5 100755
--- a/webmacro/src/org/webmacro/directive/ParseDirective.java
+++ b/webmacro/src/org/webmacro/directive/ParseDirective.java
@@ -1,66 +1,66 @@
package org.webmacro.directive;
import java.io.*;
import org.webmacro.*;
import org.webmacro.engine.*;
public class ParseDirective extends Directive {
private static final int PARSE_TEMPLATE = 1;
private Macro template;
private static final ArgDescriptor[]
myArgs = new ArgDescriptor[] {
new QuotedStringArg(PARSE_TEMPLATE),
};
private static final DirectiveDescriptor
myDescr = new DirectiveDescriptor("parse", ParseDirective.class,
myArgs, null);
public static DirectiveDescriptor getDescriptor() {
return myDescr;
}
public Object build(DirectiveBuilder builder,
BuildContext bc)
throws BuildException {
Object o = builder.getArg(PARSE_TEMPLATE, bc);
if (o instanceof Macro) {
template = (Macro) o;
return this;
}
else
try {
return bc.getBroker().get("template", o.toString());
} catch (NotFoundException ne) {
throw new BuildException("Template " + o + " not found: ", ne);
}
}
public void write(FastWriter out, Context context)
throws ContextException, IOException {
String fname = template.evaluate(context).toString();
try {
Template tmpl = (Template) context.getBroker().get("template", fname);
tmpl.write(out,context);
} catch (IOException e) {
- String warning = "Error reading template " + fname;
+ String warning = "Error reading template: " + fname;
context.getLog("engine").warning(warning, e);
- out.write("<!--\nWARNING: " + warning + " \n-->");
+ writeWarning(warning, out);
} catch (Exception e) {
String warning = "Template not found: " + fname;
context.getLog("engine").warning(warning,e);
- out.write("<!--\nWARNING: " + warning + " \n-->");
+ writeWarning(warning, out);
}
}
public void accept(TemplateVisitor v) {
v.beginDirective(myDescr.name);
v.visitDirectiveArg("ParseTemplate", template);
v.endDirective();
}
}
| false | true | public void write(FastWriter out, Context context)
throws ContextException, IOException {
String fname = template.evaluate(context).toString();
try {
Template tmpl = (Template) context.getBroker().get("template", fname);
tmpl.write(out,context);
} catch (IOException e) {
String warning = "Error reading template " + fname;
context.getLog("engine").warning(warning, e);
out.write("<!--\nWARNING: " + warning + " \n-->");
} catch (Exception e) {
String warning = "Template not found: " + fname;
context.getLog("engine").warning(warning,e);
out.write("<!--\nWARNING: " + warning + " \n-->");
}
}
| public void write(FastWriter out, Context context)
throws ContextException, IOException {
String fname = template.evaluate(context).toString();
try {
Template tmpl = (Template) context.getBroker().get("template", fname);
tmpl.write(out,context);
} catch (IOException e) {
String warning = "Error reading template: " + fname;
context.getLog("engine").warning(warning, e);
writeWarning(warning, out);
} catch (Exception e) {
String warning = "Template not found: " + fname;
context.getLog("engine").warning(warning,e);
writeWarning(warning, out);
}
}
|
diff --git a/src/net/charabia/jsmoothgen/application/gui/editors/SkeletonProperties.java b/src/net/charabia/jsmoothgen/application/gui/editors/SkeletonProperties.java
index 52c3bc7..da25554 100644
--- a/src/net/charabia/jsmoothgen/application/gui/editors/SkeletonProperties.java
+++ b/src/net/charabia/jsmoothgen/application/gui/editors/SkeletonProperties.java
@@ -1,206 +1,209 @@
/*
JSmooth: a VM wrapper toolkit for Windows
Copyright (C) 2003 Rodrigo Reyes <[email protected]>
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.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package net.charabia.jsmoothgen.application.gui.editors;
import net.charabia.jsmoothgen.skeleton.*;
import net.charabia.jsmoothgen.application.*;
import net.charabia.jsmoothgen.application.gui.*;
import net.charabia.jsmoothgen.application.gui.util.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import com.l2fprod.common.swing.*;
import com.l2fprod.common.propertysheet.*;
public class SkeletonProperties extends Editor implements JSmoothModelBean.SkeletonChangedListener
{
private PropertySheetPanel m_skelprops = new PropertySheetPanel();
private String m_currentSkelName = null;
private SkeletonBean m_skel = null;
public class SkeletonPropertyProxy extends DefaultProperty
{
SkeletonProperty m_property;
public SkeletonPropertyProxy(SkeletonProperty prop)
{
m_property = prop;
}
public String getDisplayName()
{
return m_property.getLabel();
}
public String getName()
{
System.out.println("proxy, getname " + m_property.getIdName());
return m_property.getIdName();
}
public String getShortDescription()
{
return m_property.getDescription();
}
public Class getType()
{
if (m_property.getType().equals("boolean"))
return Boolean.class;
else if (m_property.getType().equals("textarea"))
return String.class;
else if (m_property.getType().equals("string"))
return String.class;
return String.class;
}
public boolean isEditable()
{
return true;
}
public Object getValue()
{
if (m_property.getType().equals("boolean"))
return new Boolean(m_property.getValue().equals("1"));
return m_property.getValue();
}
public void setValue(Object o)
{
System.out.println("SET VALUE " + o);
if (o instanceof Boolean)
{
if (((Boolean)o).booleanValue() == true)
m_property.setValue("1");
else
m_property.setValue("0");
}
else
{
m_property.setValue(o.toString());
}
}
}
public SkeletonProperties()
{
setLayout(new BorderLayout());
add(BorderLayout.CENTER, m_skelprops);
m_skelprops.setDescriptionVisible(true);
m_skelprops.setToolBarVisible(false);
}
public Dimension getPreferredSize()
{
return new Dimension(100,200);
}
public void setProperties()
{
m_skel = null;
if (m_currentSkelName != null)
m_skel = Main.SKELETONS.getSkeleton(m_currentSkelName);
SkeletonProperty[] sprops = null;
if (m_skel != null)
sprops = m_skel.getSkeletonProperties();
else
sprops = new SkeletonProperty[0];
SkeletonPropertyProxy[] proxy = new SkeletonPropertyProxy[sprops.length];
for (int i=0; i<sprops.length; i++)
{
proxy[i] = new SkeletonPropertyProxy( sprops[i] );
System.out.println("Added property " + sprops[i].getLabel());
}
JSmoothModelBean.Property[] jsprop = m_model.getSkeletonProperties();
- for (int i=0; i<jsprop.length; i++)
+ if (jsprop != null)
{
- // search for the proxy and set the value
- for (int j=0; j<proxy.length; j++)
+ for (int i=0; i<jsprop.length; i++)
{
- if (proxy[j].getName().equals(jsprop[i].getKey()))
+ // search for the proxy and set the value
+ for (int j=0; j<proxy.length; j++)
{
- proxy[j].setValue(jsprop[i].getValue());
- break;
+ if (proxy[j].getName().equals(jsprop[i].getKey()))
+ {
+ proxy[j].setValue(jsprop[i].getValue());
+ break;
+ }
}
}
}
m_skelprops.setProperties(proxy);
}
public void dataChanged()
{
System.out.println("SkeletonProperties: data changed, " + m_model.getSkeletonName());
if (m_model.getSkeletonName() == null)
{
m_currentSkelName = null;
setProperties();
return;
}
if ( ! m_model.getSkeletonName().equalsIgnoreCase(m_currentSkelName))
{
m_currentSkelName = m_model.getSkeletonName();
setProperties();
}
}
public void updateModel()
{
if (m_skel != null)
{
SkeletonProperty[] sp = m_skel.getSkeletonProperties();
JSmoothModelBean.Property[] props = new JSmoothModelBean.Property[sp.length];
for (int i=0; i<sp.length; i++)
{
props[i] = new JSmoothModelBean.Property();
props[i].setKey(sp[i].getIdName());
props[i].setValue(sp[i].getValue());
System.out.println(props[i]);
}
m_model.setSkeletonProperties(props);
}
}
public void skeletonChanged()
{
dataChanged();
}
public String getLabel()
{
return "SKELETONPROPERTIES_LABEL";
}
public String getDescription()
{
return "SKELETONPROPERTIES_HELP";
}
}
| false | true | public void setProperties()
{
m_skel = null;
if (m_currentSkelName != null)
m_skel = Main.SKELETONS.getSkeleton(m_currentSkelName);
SkeletonProperty[] sprops = null;
if (m_skel != null)
sprops = m_skel.getSkeletonProperties();
else
sprops = new SkeletonProperty[0];
SkeletonPropertyProxy[] proxy = new SkeletonPropertyProxy[sprops.length];
for (int i=0; i<sprops.length; i++)
{
proxy[i] = new SkeletonPropertyProxy( sprops[i] );
System.out.println("Added property " + sprops[i].getLabel());
}
JSmoothModelBean.Property[] jsprop = m_model.getSkeletonProperties();
for (int i=0; i<jsprop.length; i++)
{
// search for the proxy and set the value
for (int j=0; j<proxy.length; j++)
{
if (proxy[j].getName().equals(jsprop[i].getKey()))
{
proxy[j].setValue(jsprop[i].getValue());
break;
}
}
}
m_skelprops.setProperties(proxy);
}
| public void setProperties()
{
m_skel = null;
if (m_currentSkelName != null)
m_skel = Main.SKELETONS.getSkeleton(m_currentSkelName);
SkeletonProperty[] sprops = null;
if (m_skel != null)
sprops = m_skel.getSkeletonProperties();
else
sprops = new SkeletonProperty[0];
SkeletonPropertyProxy[] proxy = new SkeletonPropertyProxy[sprops.length];
for (int i=0; i<sprops.length; i++)
{
proxy[i] = new SkeletonPropertyProxy( sprops[i] );
System.out.println("Added property " + sprops[i].getLabel());
}
JSmoothModelBean.Property[] jsprop = m_model.getSkeletonProperties();
if (jsprop != null)
{
for (int i=0; i<jsprop.length; i++)
{
// search for the proxy and set the value
for (int j=0; j<proxy.length; j++)
{
if (proxy[j].getName().equals(jsprop[i].getKey()))
{
proxy[j].setValue(jsprop[i].getValue());
break;
}
}
}
}
m_skelprops.setProperties(proxy);
}
|
diff --git a/common-src/source/org/alt60m/gcx/ConnexionBar.java b/common-src/source/org/alt60m/gcx/ConnexionBar.java
index ed0d2e6e..3e5b6146 100644
--- a/common-src/source/org/alt60m/gcx/ConnexionBar.java
+++ b/common-src/source/org/alt60m/gcx/ConnexionBar.java
@@ -1,203 +1,203 @@
package org.alt60m.gcx;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.alt60m.cas.CASHelper;
import org.alt60m.cas.CASUser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gcx.cas.CASProxyURLConnection;
import edu.yale.its.tp.cas.proxy.ProxyTicketReceptor;
public class ConnexionBar {
private static Log log = LogFactory.getLog(ConnexionBar.class);
private static Map<String, CacheEntry> cache = new HashMap<String, CacheEntry>();
private static CASHelper helper;
//Yeah, I don't really like this...but it's kind hard to get the
//logoutCallback url otherwise without some refactoring I'm not willing
//to commit to
public static void setCasHelper(CASHelper helper) {
ConnexionBar.helper = helper;
}
private CASUser user;
private String logoutUrl;
/**
* See also ProxyTicketReceptor.java
* @author Matthew.Drees
*
*/
private class CacheEntry {
public CacheEntry(String bar) {
this.bar = bar;
cacheTimestamp = new Date();
}
static final int validTime = 1 * 60 * 60 * 1000; //in ms
public String bar;
public Date cacheTimestamp;
public boolean expired() {
return (new Date().getTime() - cacheTimestamp.getTime() > validTime);
}
}
//the cache might grow kinda large, since entries are never removed, but I don't
//think it will pose a problem. It's not persisted across context restarts.
public static void clearCache() {
cache.clear();
}
public ConnexionBar(CASUser user, HttpServletRequest request) {
if (user == null) {
throw new IllegalArgumentException("Must be initialized with a non-null user");
}
this.user = user;
logoutUrl = helper.getLogoutUrl(request);
}
public String render()
{
CacheEntry cacheEntry = cache.get(user.getGUID());
if (cacheEntry != null && !cacheEntry.expired()) {
return cacheEntry.bar;
}
String pgtIou = user.getPgtIou();
if (pgtIou != null) {
String bar = getBar(pgtIou, user.getGUID());
if (bar != null) {
bar = replaceLogoutLink(bar);
cache.put(user.getGUID(), new CacheEntry(bar));
return bar;
} else {
log.warn("Unable to fetch bar");
}
} else {
log.warn("user " + user.getUsername() + " has no pgtIou");
}
if (cacheEntry != null) { //better an expired bar than none at all
return cacheEntry.bar;
}
return null;
}
private String replaceLogoutLink(String bar) {
String wrongLogoutUrl = ""https://signin.mygcx.org/cas/logout"";
return bar.replace(wrongLogoutUrl, """ + logoutUrl + """);
}
public static String getBar(String pgtiou) {
return getBar(pgtiou, null);
}
public static String getBar(String pgtiou, String guid) {
if (pgtiou == null) {
throw new IllegalArgumentException("Cannot accept null pgtiou!");
}
String content = null;
- String barTicketService = "https://www.mygcx.org/module/CampusStaff/omnibar/omnibar";
- String barService = "https://www.mygcx.org/module/CampusStaff/omnibar/omnibar";
+ String barTicketService = "https://www.mygcx.org/CampusStaff/module/omnibar/omnibar";
+ String barService = "https://www.mygcx.org/CampusStaff/module/omnibar/omnibar";
String signinService = "signin.mygcx.org";
try {
content = getBar(pgtiou, barTicketService, barService, signinService);
} catch (IOException e) {
//TODO: if it's the first time a user logs in, GCX doesn't like to
//send the toolbar. So rerequest the toolbar. Remove this when GCX
//team fixes their server.
//
//update: this shouldnt' be necessary, since the first time a user
//logs in, we add them to gcx (in simplesecuritymanager). But it
//doesn't hurt to leave it for now.
if (e.getMessage().indexOf(
"Server returned HTTP response code: 401") != -1) {
log.warn("First attempt to get bar failed due to 401; Retrying...");
try { //First try to add them to our community, since that might cause a failure...
if (guid != null) {
CommunityAdminInterface cai = new CommunityAdminInterface("CampusStaff");
if (!cai.addToGroup(guid, "Members")) {
log.error("User not added to CampusStaff: " + cai.getError());
}
} else {
log.warn("GUID is null when trying to add user to CampusStaff after getBar failure.", e);
}
} catch (IOException e2) {
log.error("Exception occured during attempt to add user to CampusStaff after getBar failure", e2);
} catch (CommunityAdminInterfaceException e3) {
log.error("Exception occured during attempt to add user to CampusStaff after getBar failure", e3);
}
try { //Try to get the bar again
content = getBar(pgtiou, barTicketService, barService, signinService);
} catch (IOException e1) {
log.error("Exception occured during second attempt to get ConneXionBar", e1);
}
} else {
log.warn("Exception Occured getting bar: ", e);
}
}
return content;
}
private static String getBar(String pgtiou, String barTicketService, String barService, String signinService) throws IOException {
log.debug("Getting connexion bar for pgtiou " + pgtiou);
String content = null;
String proxyticket = ProxyTicketReceptor.getProxyTicket(pgtiou,
barTicketService);
log.info("proxyticket: " + proxyticket);
log.info("barTicketService: " + barTicketService);
if (proxyticket == null)
log.warn("No ticket given from receptor!");
else {
CASProxyURLConnection proxyCon = new CASProxyURLConnection(
signinService);
String received = proxyCon.getURL(barService, proxyticket);
if (proxyCon.wasSuccess() && received != null) {
try {
content = parseBar(received);
}
catch (ArrayIndexOutOfBoundsException e) {
log.error("Didn't receive ConnexionBar as expected", e);
}
// content = received;
} else {
//TODO: retry with real service url?
log.error("Connection failed: " + proxyCon.getError());
}
}
return content;
}
//Remove XML tags from beginning and end of bar, unescape characters
private static String parseBar(String bar) throws ArrayIndexOutOfBoundsException {
log.info(bar);
String resultPlusEnd = (bar.split("<reportdata>",2))[1];
String result = (resultPlusEnd.split("</reportdata>",2))[0];
// String result = bar;
result = result.replace("<", "<");
result = result.replace(">", ">");
result = result.replace("'", "'");
result = result.replace(""", "\"");
//We should be logging on with www but it isn't working for some reason,
//so the bar comes back with http/gcx3 links, when it should be https/www
result = result.replace("http://gcx3", "https://www");
return result;
}
}
| true | true | public static String getBar(String pgtiou, String guid) {
if (pgtiou == null) {
throw new IllegalArgumentException("Cannot accept null pgtiou!");
}
String content = null;
String barTicketService = "https://www.mygcx.org/module/CampusStaff/omnibar/omnibar";
String barService = "https://www.mygcx.org/module/CampusStaff/omnibar/omnibar";
String signinService = "signin.mygcx.org";
try {
content = getBar(pgtiou, barTicketService, barService, signinService);
} catch (IOException e) {
//TODO: if it's the first time a user logs in, GCX doesn't like to
//send the toolbar. So rerequest the toolbar. Remove this when GCX
//team fixes their server.
//
//update: this shouldnt' be necessary, since the first time a user
//logs in, we add them to gcx (in simplesecuritymanager). But it
//doesn't hurt to leave it for now.
if (e.getMessage().indexOf(
"Server returned HTTP response code: 401") != -1) {
log.warn("First attempt to get bar failed due to 401; Retrying...");
try { //First try to add them to our community, since that might cause a failure...
if (guid != null) {
CommunityAdminInterface cai = new CommunityAdminInterface("CampusStaff");
if (!cai.addToGroup(guid, "Members")) {
log.error("User not added to CampusStaff: " + cai.getError());
}
} else {
log.warn("GUID is null when trying to add user to CampusStaff after getBar failure.", e);
}
} catch (IOException e2) {
log.error("Exception occured during attempt to add user to CampusStaff after getBar failure", e2);
} catch (CommunityAdminInterfaceException e3) {
log.error("Exception occured during attempt to add user to CampusStaff after getBar failure", e3);
}
try { //Try to get the bar again
content = getBar(pgtiou, barTicketService, barService, signinService);
} catch (IOException e1) {
log.error("Exception occured during second attempt to get ConneXionBar", e1);
}
} else {
log.warn("Exception Occured getting bar: ", e);
}
}
return content;
}
| public static String getBar(String pgtiou, String guid) {
if (pgtiou == null) {
throw new IllegalArgumentException("Cannot accept null pgtiou!");
}
String content = null;
String barTicketService = "https://www.mygcx.org/CampusStaff/module/omnibar/omnibar";
String barService = "https://www.mygcx.org/CampusStaff/module/omnibar/omnibar";
String signinService = "signin.mygcx.org";
try {
content = getBar(pgtiou, barTicketService, barService, signinService);
} catch (IOException e) {
//TODO: if it's the first time a user logs in, GCX doesn't like to
//send the toolbar. So rerequest the toolbar. Remove this when GCX
//team fixes their server.
//
//update: this shouldnt' be necessary, since the first time a user
//logs in, we add them to gcx (in simplesecuritymanager). But it
//doesn't hurt to leave it for now.
if (e.getMessage().indexOf(
"Server returned HTTP response code: 401") != -1) {
log.warn("First attempt to get bar failed due to 401; Retrying...");
try { //First try to add them to our community, since that might cause a failure...
if (guid != null) {
CommunityAdminInterface cai = new CommunityAdminInterface("CampusStaff");
if (!cai.addToGroup(guid, "Members")) {
log.error("User not added to CampusStaff: " + cai.getError());
}
} else {
log.warn("GUID is null when trying to add user to CampusStaff after getBar failure.", e);
}
} catch (IOException e2) {
log.error("Exception occured during attempt to add user to CampusStaff after getBar failure", e2);
} catch (CommunityAdminInterfaceException e3) {
log.error("Exception occured during attempt to add user to CampusStaff after getBar failure", e3);
}
try { //Try to get the bar again
content = getBar(pgtiou, barTicketService, barService, signinService);
} catch (IOException e1) {
log.error("Exception occured during second attempt to get ConneXionBar", e1);
}
} else {
log.warn("Exception Occured getting bar: ", e);
}
}
return content;
}
|
diff --git a/src/com/android/gallery3d/app/OrientationManager.java b/src/com/android/gallery3d/app/OrientationManager.java
index a8ef99ad8..0e033ebe4 100644
--- a/src/com/android/gallery3d/app/OrientationManager.java
+++ b/src/com/android/gallery3d/app/OrientationManager.java
@@ -1,215 +1,223 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* 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.android.gallery3d.app;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.provider.Settings;
import android.view.OrientationEventListener;
import android.view.Surface;
import com.android.gallery3d.ui.OrientationSource;
import java.util.ArrayList;
public class OrientationManager implements OrientationSource {
private static final String TAG = "OrientationManager";
public interface Listener {
public void onOrientationCompensationChanged();
}
// Orientation hysteresis amount used in rounding, in degrees
private static final int ORIENTATION_HYSTERESIS = 5;
private Activity mActivity;
private ArrayList<Listener> mListeners;
private MyOrientationEventListener mOrientationListener;
// The degrees of the device rotated clockwise from its natural orientation.
private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
// If the framework orientation is locked.
private boolean mOrientationLocked = false;
// The orientation compensation: if the framwork orientation is locked, the
// device orientation and the framework orientation may be different, so we
// need to rotate the UI. For example, if this value is 90, the UI
// components should be rotated 90 degrees counter-clockwise.
private int mOrientationCompensation = 0;
// This is true if "Settings -> Display -> Rotation Lock" is checked. We
// don't allow the orientation to be unlocked if the value is true.
private boolean mRotationLockedSetting = false;
public OrientationManager(Activity activity) {
mActivity = activity;
mListeners = new ArrayList<Listener>();
mOrientationListener = new MyOrientationEventListener(activity);
}
public void resume() {
ContentResolver resolver = mActivity.getContentResolver();
mRotationLockedSetting = Settings.System.getInt(
resolver, Settings.System.ACCELEROMETER_ROTATION, 0) != 1;
mOrientationListener.enable();
}
public void pause() {
mOrientationListener.disable();
}
public void addListener(Listener listener) {
synchronized (mListeners) {
mListeners.add(listener);
}
}
public void removeListener(Listener listener) {
synchronized (mListeners) {
mListeners.remove(listener);
}
}
////////////////////////////////////////////////////////////////////////////
// Orientation handling
//
// We can choose to lock the framework orientation or not. If we lock the
// framework orientation, we calculate a a compensation value according to
// current device orientation and send it to listeners. If we don't lock
// the framework orientation, we always set the compensation value to 0.
////////////////////////////////////////////////////////////////////////////
// Lock the framework orientation to the current device orientation
public void lockOrientation() {
if (mOrientationLocked) return;
mOrientationLocked = true;
+ int displayRotation = getDisplayRotation();
// Display rotation >= 180 means we need to use the REVERSE landscape/portrait
- boolean standard = getDisplayRotation() < 180;
+ boolean standard = displayRotation < 180;
if (mActivity.getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
Log.d(TAG, "lock orientation to landscape");
mActivity.setRequestedOrientation(standard
? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
: ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
+ if (displayRotation == 90 || displayRotation == 270) {
+ // If displayRotation = 90 or 270 then we are on a landscape
+ // device. On landscape devices, portrait is a 90 degree
+ // clockwise rotation from landscape, so we need
+ // to flip which portrait we pick as display rotation is counter clockwise
+ standard = !standard;
+ }
Log.d(TAG, "lock orientation to portrait");
mActivity.setRequestedOrientation(standard
? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
: ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
updateCompensation();
}
// Unlock the framework orientation, so it can change when the device
// rotates.
public void unlockOrientation() {
if (!mOrientationLocked) return;
if (mRotationLockedSetting) return;
mOrientationLocked = false;
Log.d(TAG, "unlock orientation");
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
disableCompensation();
}
// Calculate the compensation value and send it to listeners.
private void updateCompensation() {
if (mOrientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
return;
}
int orientationCompensation =
(mOrientation + getDisplayRotation(mActivity)) % 360;
if (mOrientationCompensation != orientationCompensation) {
mOrientationCompensation = orientationCompensation;
notifyListeners();
}
}
// Make the compensation value 0 and send it to listeners.
private void disableCompensation() {
if (mOrientationCompensation != 0) {
mOrientationCompensation = 0;
notifyListeners();
}
}
private void notifyListeners() {
synchronized (mListeners) {
for (int i = 0, n = mListeners.size(); i < n; i++) {
mListeners.get(i).onOrientationCompensationChanged();
}
}
}
// This listens to the device orientation, so we can update the compensation.
private class MyOrientationEventListener extends OrientationEventListener {
public MyOrientationEventListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
// We keep the last known orientation. So if the user first orient
// the camera then point the camera to floor or sky, we still have
// the correct orientation.
if (orientation == ORIENTATION_UNKNOWN) return;
mOrientation = roundOrientation(orientation, mOrientation);
// If the framework orientation is locked, we update the
// compensation value and notify the listeners.
if (mOrientationLocked) updateCompensation();
}
}
@Override
public int getDisplayRotation() {
return getDisplayRotation(mActivity);
}
@Override
public int getCompensation() {
return mOrientationCompensation;
}
private static int roundOrientation(int orientation, int orientationHistory) {
boolean changeOrientation = false;
if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
changeOrientation = true;
} else {
int dist = Math.abs(orientation - orientationHistory);
dist = Math.min(dist, 360 - dist);
changeOrientation = (dist >= 45 + ORIENTATION_HYSTERESIS);
}
if (changeOrientation) {
return ((orientation + 45) / 90 * 90) % 360;
}
return orientationHistory;
}
private static int getDisplayRotation(Activity activity) {
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
switch (rotation) {
case Surface.ROTATION_0: return 0;
case Surface.ROTATION_90: return 90;
case Surface.ROTATION_180: return 180;
case Surface.ROTATION_270: return 270;
}
return 0;
}
}
| false | true | public void lockOrientation() {
if (mOrientationLocked) return;
mOrientationLocked = true;
// Display rotation >= 180 means we need to use the REVERSE landscape/portrait
boolean standard = getDisplayRotation() < 180;
if (mActivity.getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
Log.d(TAG, "lock orientation to landscape");
mActivity.setRequestedOrientation(standard
? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
: ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
Log.d(TAG, "lock orientation to portrait");
mActivity.setRequestedOrientation(standard
? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
: ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
updateCompensation();
}
| public void lockOrientation() {
if (mOrientationLocked) return;
mOrientationLocked = true;
int displayRotation = getDisplayRotation();
// Display rotation >= 180 means we need to use the REVERSE landscape/portrait
boolean standard = displayRotation < 180;
if (mActivity.getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
Log.d(TAG, "lock orientation to landscape");
mActivity.setRequestedOrientation(standard
? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
: ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
} else {
if (displayRotation == 90 || displayRotation == 270) {
// If displayRotation = 90 or 270 then we are on a landscape
// device. On landscape devices, portrait is a 90 degree
// clockwise rotation from landscape, so we need
// to flip which portrait we pick as display rotation is counter clockwise
standard = !standard;
}
Log.d(TAG, "lock orientation to portrait");
mActivity.setRequestedOrientation(standard
? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
: ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
updateCompensation();
}
|
diff --git a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/editors/template/outline/QuickOutlinePatternFilter.java b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/editors/template/outline/QuickOutlinePatternFilter.java
index 71c83ae2..861e0a0e 100644
--- a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/editors/template/outline/QuickOutlinePatternFilter.java
+++ b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/editors/template/outline/QuickOutlinePatternFilter.java
@@ -1,43 +1,41 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Obeo.
* 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.internal.ide.ui.editors.template.outline;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.dialogs.PatternFilter;
/**
* We'll use a custom filter for our quick outline as the tree we display to the user contains the elements'
* type : "template", "query", "macro" ... and we don't want this to be taken into account when filtering.
*
* @author <a href="mailto:[email protected]">Laurent Goubet</a>
*/
public class QuickOutlinePatternFilter extends PatternFilter {
/**
* {@inheritDoc}
*
* @see org.eclipse.ui.dialogs.PatternFilter#isLeafMatch(org.eclipse.jface.viewers.Viewer,
* java.lang.Object)
*/
@Override
protected boolean isLeafMatch(Viewer viewer, Object element) {
String labelText = ((ILabelProvider)((StructuredViewer)viewer).getLabelProvider()).getText(element);
if (labelText == null) {
return false;
}
- // The label starts with the element type (template, query, ...) : trim it
- String elementName = labelText.substring(labelText.indexOf(' ') + 1);
- return wordMatches(elementName);
+ return wordMatches(labelText);
}
}
| true | true | protected boolean isLeafMatch(Viewer viewer, Object element) {
String labelText = ((ILabelProvider)((StructuredViewer)viewer).getLabelProvider()).getText(element);
if (labelText == null) {
return false;
}
// The label starts with the element type (template, query, ...) : trim it
String elementName = labelText.substring(labelText.indexOf(' ') + 1);
return wordMatches(elementName);
}
| protected boolean isLeafMatch(Viewer viewer, Object element) {
String labelText = ((ILabelProvider)((StructuredViewer)viewer).getLabelProvider()).getText(element);
if (labelText == null) {
return false;
}
return wordMatches(labelText);
}
|
diff --git a/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationsCursorAdapter.java b/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationsCursorAdapter.java
index dbe290b3..ffac7665 100644
--- a/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationsCursorAdapter.java
+++ b/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationsCursorAdapter.java
@@ -1,234 +1,234 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]>
*
* SWADroid 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.
*
* SWADroid 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 SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.modules.notifications;
import java.util.Date;
import es.ugr.swad.swadroid.R;
import es.ugr.swad.swadroid.modules.Messages;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Custom adapter for display notifications
* @author Juan Miguel Boyero Corral <[email protected]>
*
*/
public class NotificationsCursorAdapter extends CursorAdapter {
private boolean [] contentVisible;
Context ctx;
/**
* Constructor
* @param context Application context
* @param c Database cursor
*/
public NotificationsCursorAdapter(Context context, Cursor c) {
super(context, c);
ctx = context;
int numRows = c.getCount();
contentVisible = new boolean[numRows];
for(int i=0; i<numRows; i++) {
contentVisible[i] = false;
}
}
/**
* Constructor
* @param context Application context
* @param c Database cursor
* @param autoRequery Flag to set autoRequery function
*/
public NotificationsCursorAdapter(Context context, Cursor c,
boolean autoRequery) {
super(context, c, autoRequery);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
final Context ctx = context;
final Long notificationCode = cursor.getLong(cursor.getColumnIndex("id"));
long unixTime;
String type, sender, senderFirstname, senderSurname1, senderSurname2, summaryText;
String contentText;
String[] dateContent;
Date d;
int numRows = cursor.getCount();
if(contentVisible.length == 0) {
contentVisible = new boolean[numRows];
}
view.setScrollContainer(false);
TextView eventType = (TextView) view.findViewById(R.id.eventType);
TextView eventDate = (TextView) view.findViewById(R.id.eventDate);
TextView eventTime = (TextView) view.findViewById(R.id.eventTime);
TextView eventSender = (TextView) view.findViewById(R.id.eventSender);
TextView location = (TextView) view.findViewById(R.id.eventLocation);
final TextView summary = (TextView) view.findViewById(R.id.eventSummary);
TextView content = (TextView) view.findViewById(R.id.eventText);
ImageView notificationIcon = (ImageView) view.findViewById(R.id.notificationIcon);
ImageView messageReplyButton = (ImageView) view.findViewById(R.id.messageReplyButton);
OnClickListener replyMessageListener = new OnClickListener() {
public void onClick(View v) {
Intent activity = new Intent(ctx.getApplicationContext(), Messages.class);
activity.putExtra("notificationCode", notificationCode);
activity.putExtra("summary", summary.getText().toString());
ctx.startActivity(activity);
}
};
if(eventType != null) {
type = cursor.getString(cursor.getColumnIndex("eventType"));
messageReplyButton.setVisibility(View.GONE);
if(type.equals("examAnnouncement"))
{
type = context.getString(R.string.examAnnouncement);
notificationIcon.setImageResource(R.drawable.announce);
} else if(type.equals("marksFile"))
{
type = context.getString(R.string.marksFile);
notificationIcon.setImageResource(R.drawable.grades);
} else if(type.equals("notice"))
{
type = context.getString(R.string.notice);
notificationIcon.setImageResource(R.drawable.note);
} else if(type.equals("message"))
{
type = context.getString(R.string.message);
notificationIcon.setImageResource(R.drawable.recmsg);
messageReplyButton.setOnClickListener(replyMessageListener);
messageReplyButton.setVisibility(View.VISIBLE);
} else if(type.equals("forumReply"))
{
type = context.getString(R.string.forumReply);
notificationIcon.setImageResource(R.drawable.forum);
} else if(type.equals("assignment"))
{
type = context.getString(R.string.assignment);
notificationIcon.setImageResource(R.drawable.desk);
} else if(type.equals("survey"))
{
type = context.getString(R.string.survey);
notificationIcon.setImageResource(R.drawable.survey);
} else {
type = context.getString(R.string.unknownNotification);
notificationIcon.setImageResource(R.drawable.ic_launcher_swadroid);
}
eventType.setText(type);
}
if((eventDate != null) && (eventTime != null)){
unixTime = Long.parseLong(cursor.getString(cursor.getColumnIndex("eventTime")));
d = new Date(unixTime * 1000);
dateContent = d.toLocaleString().split(" ");
eventDate.setText(dateContent[0]);
eventTime.setText(dateContent[1]);
}
if(eventSender != null){
sender = "";
senderFirstname = cursor.getString(cursor.getColumnIndex("userFirstname"));
senderSurname1 = cursor.getString(cursor.getColumnIndex("userSurname1"));
senderSurname2 = cursor.getString(cursor.getColumnIndex("userSurname2"));
//Empty fields checking
if(!senderFirstname.equals("anyType{}"))
sender += senderFirstname + " ";
if(!senderSurname1.equals("anyType{}"))
sender += senderSurname1 + " ";
if(!senderSurname2.equals("anyType{}"))
sender += senderSurname2;
eventSender.setText(sender);
}
if(location != null) {
location.setText(cursor.getString(cursor.getColumnIndex("location")));
}
if(summary != null){
summaryText = cursor.getString(cursor.getColumnIndex("summary"));
//Empty field checking
if(summaryText.equals("anyType{}"))
summaryText = context.getString(R.string.noSubjectMsg);
summary.setText(Html.fromHtml(summaryText));
}
if((content != null)){
contentText = cursor.getString(cursor.getColumnIndex("content"));
//Empty field checking
if(contentText.equals("anyType{}"))
contentText = context.getString(R.string.noContentMsg);
- content.setText(Html.fromHtml(contentText));
+ content.setText(contentText);
if(contentVisible[cursor.getPosition()]) {
content.setVisibility(View.VISIBLE);
} else {
content.setVisibility(View.GONE);
}
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater vi = LayoutInflater.from(context);
View v = vi.inflate(R.layout.notifications_list_item, parent, false);
return v;
}
/**
* If the notification is not a mark, shows or hides its content
* If the notification is a mark, launches a WebView activity to show it
* @param position Notification position in the ListView
*/
/*public void toggleContentVisibility(int position) {
String viewType, marksType;
View view = this.getView(position, null, null);
TextView eventType = (TextView) view.findViewById(R.id.eventType);
TextView content = (TextView) view.findViewById(R.id.eventText);
viewType = String.valueOf(eventType.getText());
marksType = ctx.getString(R.string.marksFile);
if(viewType.equals(marksType)) {
Intent activity = new Intent(ctx.getApplicationContext(), NotificationItem.class);
activity.putExtra("content", content.getText().toString());
ctx.startActivity(activity);
} else {
contentVisible[position] = !contentVisible[position];
this.notifyDataSetChanged();
}
}*/
}
| true | true | public void bindView(View view, Context context, Cursor cursor) {
final Context ctx = context;
final Long notificationCode = cursor.getLong(cursor.getColumnIndex("id"));
long unixTime;
String type, sender, senderFirstname, senderSurname1, senderSurname2, summaryText;
String contentText;
String[] dateContent;
Date d;
int numRows = cursor.getCount();
if(contentVisible.length == 0) {
contentVisible = new boolean[numRows];
}
view.setScrollContainer(false);
TextView eventType = (TextView) view.findViewById(R.id.eventType);
TextView eventDate = (TextView) view.findViewById(R.id.eventDate);
TextView eventTime = (TextView) view.findViewById(R.id.eventTime);
TextView eventSender = (TextView) view.findViewById(R.id.eventSender);
TextView location = (TextView) view.findViewById(R.id.eventLocation);
final TextView summary = (TextView) view.findViewById(R.id.eventSummary);
TextView content = (TextView) view.findViewById(R.id.eventText);
ImageView notificationIcon = (ImageView) view.findViewById(R.id.notificationIcon);
ImageView messageReplyButton = (ImageView) view.findViewById(R.id.messageReplyButton);
OnClickListener replyMessageListener = new OnClickListener() {
public void onClick(View v) {
Intent activity = new Intent(ctx.getApplicationContext(), Messages.class);
activity.putExtra("notificationCode", notificationCode);
activity.putExtra("summary", summary.getText().toString());
ctx.startActivity(activity);
}
};
if(eventType != null) {
type = cursor.getString(cursor.getColumnIndex("eventType"));
messageReplyButton.setVisibility(View.GONE);
if(type.equals("examAnnouncement"))
{
type = context.getString(R.string.examAnnouncement);
notificationIcon.setImageResource(R.drawable.announce);
} else if(type.equals("marksFile"))
{
type = context.getString(R.string.marksFile);
notificationIcon.setImageResource(R.drawable.grades);
} else if(type.equals("notice"))
{
type = context.getString(R.string.notice);
notificationIcon.setImageResource(R.drawable.note);
} else if(type.equals("message"))
{
type = context.getString(R.string.message);
notificationIcon.setImageResource(R.drawable.recmsg);
messageReplyButton.setOnClickListener(replyMessageListener);
messageReplyButton.setVisibility(View.VISIBLE);
} else if(type.equals("forumReply"))
{
type = context.getString(R.string.forumReply);
notificationIcon.setImageResource(R.drawable.forum);
} else if(type.equals("assignment"))
{
type = context.getString(R.string.assignment);
notificationIcon.setImageResource(R.drawable.desk);
} else if(type.equals("survey"))
{
type = context.getString(R.string.survey);
notificationIcon.setImageResource(R.drawable.survey);
} else {
type = context.getString(R.string.unknownNotification);
notificationIcon.setImageResource(R.drawable.ic_launcher_swadroid);
}
eventType.setText(type);
}
if((eventDate != null) && (eventTime != null)){
unixTime = Long.parseLong(cursor.getString(cursor.getColumnIndex("eventTime")));
d = new Date(unixTime * 1000);
dateContent = d.toLocaleString().split(" ");
eventDate.setText(dateContent[0]);
eventTime.setText(dateContent[1]);
}
if(eventSender != null){
sender = "";
senderFirstname = cursor.getString(cursor.getColumnIndex("userFirstname"));
senderSurname1 = cursor.getString(cursor.getColumnIndex("userSurname1"));
senderSurname2 = cursor.getString(cursor.getColumnIndex("userSurname2"));
//Empty fields checking
if(!senderFirstname.equals("anyType{}"))
sender += senderFirstname + " ";
if(!senderSurname1.equals("anyType{}"))
sender += senderSurname1 + " ";
if(!senderSurname2.equals("anyType{}"))
sender += senderSurname2;
eventSender.setText(sender);
}
if(location != null) {
location.setText(cursor.getString(cursor.getColumnIndex("location")));
}
if(summary != null){
summaryText = cursor.getString(cursor.getColumnIndex("summary"));
//Empty field checking
if(summaryText.equals("anyType{}"))
summaryText = context.getString(R.string.noSubjectMsg);
summary.setText(Html.fromHtml(summaryText));
}
if((content != null)){
contentText = cursor.getString(cursor.getColumnIndex("content"));
//Empty field checking
if(contentText.equals("anyType{}"))
contentText = context.getString(R.string.noContentMsg);
content.setText(Html.fromHtml(contentText));
if(contentVisible[cursor.getPosition()]) {
content.setVisibility(View.VISIBLE);
} else {
content.setVisibility(View.GONE);
}
}
}
| public void bindView(View view, Context context, Cursor cursor) {
final Context ctx = context;
final Long notificationCode = cursor.getLong(cursor.getColumnIndex("id"));
long unixTime;
String type, sender, senderFirstname, senderSurname1, senderSurname2, summaryText;
String contentText;
String[] dateContent;
Date d;
int numRows = cursor.getCount();
if(contentVisible.length == 0) {
contentVisible = new boolean[numRows];
}
view.setScrollContainer(false);
TextView eventType = (TextView) view.findViewById(R.id.eventType);
TextView eventDate = (TextView) view.findViewById(R.id.eventDate);
TextView eventTime = (TextView) view.findViewById(R.id.eventTime);
TextView eventSender = (TextView) view.findViewById(R.id.eventSender);
TextView location = (TextView) view.findViewById(R.id.eventLocation);
final TextView summary = (TextView) view.findViewById(R.id.eventSummary);
TextView content = (TextView) view.findViewById(R.id.eventText);
ImageView notificationIcon = (ImageView) view.findViewById(R.id.notificationIcon);
ImageView messageReplyButton = (ImageView) view.findViewById(R.id.messageReplyButton);
OnClickListener replyMessageListener = new OnClickListener() {
public void onClick(View v) {
Intent activity = new Intent(ctx.getApplicationContext(), Messages.class);
activity.putExtra("notificationCode", notificationCode);
activity.putExtra("summary", summary.getText().toString());
ctx.startActivity(activity);
}
};
if(eventType != null) {
type = cursor.getString(cursor.getColumnIndex("eventType"));
messageReplyButton.setVisibility(View.GONE);
if(type.equals("examAnnouncement"))
{
type = context.getString(R.string.examAnnouncement);
notificationIcon.setImageResource(R.drawable.announce);
} else if(type.equals("marksFile"))
{
type = context.getString(R.string.marksFile);
notificationIcon.setImageResource(R.drawable.grades);
} else if(type.equals("notice"))
{
type = context.getString(R.string.notice);
notificationIcon.setImageResource(R.drawable.note);
} else if(type.equals("message"))
{
type = context.getString(R.string.message);
notificationIcon.setImageResource(R.drawable.recmsg);
messageReplyButton.setOnClickListener(replyMessageListener);
messageReplyButton.setVisibility(View.VISIBLE);
} else if(type.equals("forumReply"))
{
type = context.getString(R.string.forumReply);
notificationIcon.setImageResource(R.drawable.forum);
} else if(type.equals("assignment"))
{
type = context.getString(R.string.assignment);
notificationIcon.setImageResource(R.drawable.desk);
} else if(type.equals("survey"))
{
type = context.getString(R.string.survey);
notificationIcon.setImageResource(R.drawable.survey);
} else {
type = context.getString(R.string.unknownNotification);
notificationIcon.setImageResource(R.drawable.ic_launcher_swadroid);
}
eventType.setText(type);
}
if((eventDate != null) && (eventTime != null)){
unixTime = Long.parseLong(cursor.getString(cursor.getColumnIndex("eventTime")));
d = new Date(unixTime * 1000);
dateContent = d.toLocaleString().split(" ");
eventDate.setText(dateContent[0]);
eventTime.setText(dateContent[1]);
}
if(eventSender != null){
sender = "";
senderFirstname = cursor.getString(cursor.getColumnIndex("userFirstname"));
senderSurname1 = cursor.getString(cursor.getColumnIndex("userSurname1"));
senderSurname2 = cursor.getString(cursor.getColumnIndex("userSurname2"));
//Empty fields checking
if(!senderFirstname.equals("anyType{}"))
sender += senderFirstname + " ";
if(!senderSurname1.equals("anyType{}"))
sender += senderSurname1 + " ";
if(!senderSurname2.equals("anyType{}"))
sender += senderSurname2;
eventSender.setText(sender);
}
if(location != null) {
location.setText(cursor.getString(cursor.getColumnIndex("location")));
}
if(summary != null){
summaryText = cursor.getString(cursor.getColumnIndex("summary"));
//Empty field checking
if(summaryText.equals("anyType{}"))
summaryText = context.getString(R.string.noSubjectMsg);
summary.setText(Html.fromHtml(summaryText));
}
if((content != null)){
contentText = cursor.getString(cursor.getColumnIndex("content"));
//Empty field checking
if(contentText.equals("anyType{}"))
contentText = context.getString(R.string.noContentMsg);
content.setText(contentText);
if(contentVisible[cursor.getPosition()]) {
content.setVisibility(View.VISIBLE);
} else {
content.setVisibility(View.GONE);
}
}
}
|
diff --git a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/gprof/dialog/OpenGmonDialog.java b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/gprof/dialog/OpenGmonDialog.java
index ebd73a4e9..8ec06ea28 100644
--- a/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/gprof/dialog/OpenGmonDialog.java
+++ b/gprof/org.eclipse.linuxtools.gprof/src/org/eclipse/linuxtools/gprof/dialog/OpenGmonDialog.java
@@ -1,252 +1,252 @@
/*******************************************************************************
* Copyright (c) 2009 STMicroelectronics.
* 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Xavier Raynaud <[email protected]> - initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.gprof.dialog;
import java.io.File;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.variables.IStringVariableManager;
import org.eclipse.core.variables.VariablesPlugin;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.linuxtools.gprof.Activator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceComparator;
/**
* This dialog box is opened when user clicks on a gmon file.
* it alows the user to choose the binary file who produced the gmon file.
* @author Xavier Raynaud <[email protected]>
*
*/
public class OpenGmonDialog extends Dialog {
/* Inputs */
private Text binText;
private String binValue;
/* buttons */
private Button binBrowseWorkspaceButton;
private Button binBrowseFileSystemButton;
/* error label */
private Label errorLabel;
/* validation boolean */
private boolean binaryValid;
/* internal listener */
private BinaryModifyListener binModifyListener = new BinaryModifyListener();
private final String defaultValue;
private final IPath gmonFile;
/**
* Constructor
* @param parentShell
* @param binPath the path to a binary file.
*/
public OpenGmonDialog(Shell parentShell, String binPath, IPath gmonFile) {
super(parentShell);
this.gmonFile = gmonFile;
setShellStyle(getShellStyle() | SWT.RESIZE);
this.defaultValue = binPath;
}
/**
* Gets the Binary file selected by the user
* @return a path to a binary file
*/
public String getBinaryFile() {
return binValue;
}
protected Control createContents(Composite parent) {
Control composite = super.createContents(parent);
validateBinary();
return composite;
}
protected Control createDialogArea(Composite parent) {
this.getShell().setText("Gmon File Viewer: binary file...");
Composite composite = (Composite) super.createDialogArea(parent);
/* first line */
Group c = new Group(composite, SWT.NONE);
c.setText("Binary File");
- c.setToolTipText("Please enter here the binary file who produced the trace.");
+ c.setToolTipText("Please enter here the binary file which produced the profile data.");
GridLayout layout = new GridLayout(2,false);
c.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
c.setLayoutData(data);
Label binLabel = new Label(c,SWT.NONE);
- binLabel.setText("Please enter here the binary file who produced the trace");
+ binLabel.setText("Please enter here the binary file which produced the profile data.");
data = new GridData();
data.horizontalSpan = 2;
binLabel.setLayoutData(data);
binText = new Text(c,SWT.BORDER);
binText.setText(this.defaultValue);
data = new GridData(GridData.FILL_HORIZONTAL);
data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH;
binText.setLayoutData(data);
binText.addModifyListener(binModifyListener);
Composite cbBin = new Composite(c,SWT.NONE);
data = new GridData(GridData.HORIZONTAL_ALIGN_END);
cbBin.setLayoutData(data);
cbBin.setLayout(new GridLayout(2, true));
binBrowseWorkspaceButton = new Button(cbBin, SWT.PUSH);
binBrowseWorkspaceButton.setText("&Workspace...");
binBrowseWorkspaceButton.addSelectionListener(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent sev)
{
handleBrowseWorkspace("Open Binary file...", binText);
}
}
);
binBrowseFileSystemButton = new Button(cbBin, SWT.PUSH);
binBrowseFileSystemButton.setText("&File System...");
binBrowseFileSystemButton.addSelectionListener(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent sev)
{
handleBrowse("Open Binary file...", binText);
}
}
);
/* 2sd line */
errorLabel = new Label(composite,SWT.NONE);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 3;
errorLabel.setLayoutData(data);
errorLabel.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_RED));
c.layout();
return composite;
}
private void validateBinary() {
binValue = binText.getText();
IStringVariableManager mgr = VariablesPlugin.getDefault().getStringVariableManager();
try {
binValue = mgr.performStringSubstitution(binValue, false);
} catch (CoreException _) {
// do nothing: never occurs
}
File f = new File(binValue);
if (f.exists()) {
binaryValid = true;
getButton(IDialogConstants.OK_ID).setEnabled(binaryValid);
errorLabel.setText("");
} else {
binaryValid = false;
getButton(IDialogConstants.OK_ID).setEnabled(false);
if (!binValue.equals("")) {
errorLabel.setText("\"" + binText.getText() + "\" doesn't exist");
} else {
errorLabel.setText("Please enter a binary file");
}
return;
}
}
private class BinaryModifyListener implements ModifyListener
{
public void modifyText(ModifyEvent e) {
validateBinary();
}
}
protected void handleBrowseWorkspace(String msg, Text text) {
ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
dialog.setTitle(msg);
dialog.setMessage(msg);
dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
dialog.setAllowMultiple(false);
IContainer c = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(this.gmonFile);
if (c != null) dialog.setInitialSelection(c.getProject());
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] selection)
{
if (selection.length != 1) {
return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "", null); //$NON-NLS-1$
}
if (!(selection[0] instanceof IFile)) {
return new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "", null); //$NON-NLS-1$
}
return new Status(IStatus.OK, Activator.PLUGIN_ID, 0, "", null); //$NON-NLS-1$
}
});
if (dialog.open() == IDialogConstants.OK_ID) {
IResource resource = (IResource) dialog.getFirstResult();
text.setText("${resource_loc:" + resource.getFullPath() + "}");
}
}
protected void handleBrowse(String msg, Text text)
{
FileDialog dialog = new FileDialog(this.getShell(),SWT.OPEN);
dialog.setText(msg);
String t = text.getText();
IStringVariableManager mgr = VariablesPlugin.getDefault().getStringVariableManager();
try {
t = mgr.performStringSubstitution(t, false);
} catch (CoreException _) {
// do nothing: never occurs
}
File f = new File(t);
t = f.getParent();
if (t == null || t.length() == 0) {
t = this.gmonFile.removeLastSegments(1).toOSString();
}
dialog.setFilterPath(t);
String s = dialog.open();
if (s != null) text.setText(s);
}
}
| false | true | protected Control createDialogArea(Composite parent) {
this.getShell().setText("Gmon File Viewer: binary file...");
Composite composite = (Composite) super.createDialogArea(parent);
/* first line */
Group c = new Group(composite, SWT.NONE);
c.setText("Binary File");
c.setToolTipText("Please enter here the binary file who produced the trace.");
GridLayout layout = new GridLayout(2,false);
c.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
c.setLayoutData(data);
Label binLabel = new Label(c,SWT.NONE);
binLabel.setText("Please enter here the binary file who produced the trace");
data = new GridData();
data.horizontalSpan = 2;
binLabel.setLayoutData(data);
binText = new Text(c,SWT.BORDER);
binText.setText(this.defaultValue);
data = new GridData(GridData.FILL_HORIZONTAL);
data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH;
binText.setLayoutData(data);
binText.addModifyListener(binModifyListener);
Composite cbBin = new Composite(c,SWT.NONE);
data = new GridData(GridData.HORIZONTAL_ALIGN_END);
cbBin.setLayoutData(data);
cbBin.setLayout(new GridLayout(2, true));
binBrowseWorkspaceButton = new Button(cbBin, SWT.PUSH);
binBrowseWorkspaceButton.setText("&Workspace...");
binBrowseWorkspaceButton.addSelectionListener(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent sev)
{
handleBrowseWorkspace("Open Binary file...", binText);
}
}
);
binBrowseFileSystemButton = new Button(cbBin, SWT.PUSH);
binBrowseFileSystemButton.setText("&File System...");
binBrowseFileSystemButton.addSelectionListener(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent sev)
{
handleBrowse("Open Binary file...", binText);
}
}
);
/* 2sd line */
errorLabel = new Label(composite,SWT.NONE);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 3;
errorLabel.setLayoutData(data);
errorLabel.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_RED));
c.layout();
return composite;
}
| protected Control createDialogArea(Composite parent) {
this.getShell().setText("Gmon File Viewer: binary file...");
Composite composite = (Composite) super.createDialogArea(parent);
/* first line */
Group c = new Group(composite, SWT.NONE);
c.setText("Binary File");
c.setToolTipText("Please enter here the binary file which produced the profile data.");
GridLayout layout = new GridLayout(2,false);
c.setLayout(layout);
GridData data = new GridData(GridData.FILL_BOTH);
c.setLayoutData(data);
Label binLabel = new Label(c,SWT.NONE);
binLabel.setText("Please enter here the binary file which produced the profile data.");
data = new GridData();
data.horizontalSpan = 2;
binLabel.setLayoutData(data);
binText = new Text(c,SWT.BORDER);
binText.setText(this.defaultValue);
data = new GridData(GridData.FILL_HORIZONTAL);
data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH;
binText.setLayoutData(data);
binText.addModifyListener(binModifyListener);
Composite cbBin = new Composite(c,SWT.NONE);
data = new GridData(GridData.HORIZONTAL_ALIGN_END);
cbBin.setLayoutData(data);
cbBin.setLayout(new GridLayout(2, true));
binBrowseWorkspaceButton = new Button(cbBin, SWT.PUSH);
binBrowseWorkspaceButton.setText("&Workspace...");
binBrowseWorkspaceButton.addSelectionListener(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent sev)
{
handleBrowseWorkspace("Open Binary file...", binText);
}
}
);
binBrowseFileSystemButton = new Button(cbBin, SWT.PUSH);
binBrowseFileSystemButton.setText("&File System...");
binBrowseFileSystemButton.addSelectionListener(
new SelectionAdapter()
{
public void widgetSelected(SelectionEvent sev)
{
handleBrowse("Open Binary file...", binText);
}
}
);
/* 2sd line */
errorLabel = new Label(composite,SWT.NONE);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 3;
errorLabel.setLayoutData(data);
errorLabel.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_RED));
c.layout();
return composite;
}
|
diff --git a/expenditure-tracking/src/module/mission/domain/PersonelExpenseItem.java b/expenditure-tracking/src/module/mission/domain/PersonelExpenseItem.java
index db0ae9ff..f27dfb9d 100644
--- a/expenditure-tracking/src/module/mission/domain/PersonelExpenseItem.java
+++ b/expenditure-tracking/src/module/mission/domain/PersonelExpenseItem.java
@@ -1,194 +1,194 @@
package module.mission.domain;
import module.organization.domain.Person;
import myorg.domain.util.Money;
import myorg.util.BundleUtil;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
public abstract class PersonelExpenseItem extends PersonelExpenseItem_Base {
private transient Mission missionForCreation;
public PersonelExpenseItem() {
super();
}
@Override
public String getItemDescription() {
return BundleUtil.getFormattedStringFromResourceBundle("resources/MissionResources",
"label.mission.items.personel.expense");
}
@Override
public boolean isPersonelExpenseItem() {
return true;
}
public Mission getMissionForCreation() {
return missionForCreation;
}
public void setMissionForCreation(final Mission mission) {
missionForCreation = mission;
}
@Override
public Money getPrevisionaryCosts() {
return getValue();
}
public int calculateNumberOfDays() {
final LocalDate startDate = getStart().toLocalDate();
final LocalDate endDate = getEnd().toLocalDate().plusDays(1);
return Days.daysBetween(startDate, endDate).getDays();
}
@Override
public void delete() {
removeDailyPersonelExpenseCategory();
super.delete();
}
public double getWeightedExpenseFactor() {
return getExpenseFactor();
}
public double getExpenseFactor() {
double result = 0.0;
for (final Person person : getPeopleSet()) {
result += getExpenseFactor(person);
}
return result;
}
public double getExpenseFactor(final Person person) {
double result = 0.0;
if (getPeopleSet().contains(person)) {
final Mission mission = getMissionVersion().getMission();
final PersonelExpenseItem firstPersonelExpenseItem = findFirstPersonelExpenseItemFor(mission, person);
final PersonelExpenseItem lastPersonelExpenseItem = findLastPersonelExpenseItemFor(mission, person);
int numberOfDays = calculateNumberOfDays();
if (this == firstPersonelExpenseItem) {
numberOfDays--;
result += mission.getFirstDayPersonelDayExpensePercentage(this);
}
- if (this == lastPersonelExpenseItem) {
+ if (this == lastPersonelExpenseItem && numberOfDays > 0) {
numberOfDays--;
result += mission.getLastDayPersonelDayExpensePercentage(this);
}
result += numberOfDays;
}
return result;
}
private static PersonelExpenseItem findFirstPersonelExpenseItemFor(final Mission mission, final Person person) {
PersonelExpenseItem result = null;
for (final MissionItem missionItem : mission.getMissionItemsSet()) {
if (missionItem.isPersonelExpenseItem()) {
final PersonelExpenseItem personelExpenseItem = (PersonelExpenseItem) missionItem;
if (personelExpenseItem.getPeopleSet().contains(person)) {
if (result == null || personelExpenseItem.getStart().isBefore(result.getStart())) {
result = personelExpenseItem;
}
}
}
}
return result;
}
private static PersonelExpenseItem findLastPersonelExpenseItemFor(final Mission mission, final Person person) {
PersonelExpenseItem result = null;
for (final MissionItem missionItem : mission.getMissionItemsSet()) {
if (missionItem.isPersonelExpenseItem()) {
final PersonelExpenseItem personelExpenseItem = (PersonelExpenseItem) missionItem;
if (personelExpenseItem.getPeopleSet().contains(person)) {
if (result == null || personelExpenseItem.getStart().isAfter(result.getStart())) {
result = personelExpenseItem;
}
}
}
}
return result;
}
public static int calculateNumberOfFullPersonelExpenseDays(final Mission mission, final Person person) {
int result = 0;
for (final MissionItem missionItem : mission.getMissionItemsSet()) {
if (missionItem instanceof PersonelExpenseItem && missionItem.getPeopleSet().contains(person)) {
final PersonelExpenseItem personelExpenseItem = (PersonelExpenseItem) missionItem;
result += personelExpenseItem.calculateNumberOfDays();
}
}
return result;
}
@Override
public boolean isConsistent() {
final Mission mission = getMissionVersion().getMission();
final DateTime departure = mission.getDaparture();
final DateTime arrival = mission.getArrival();
return getStart().isBefore(getEnd()) && !getStart().isBefore(departure) && !getEnd().isAfter(arrival) && super.isConsistent();
}
@Override
public void hookAfterChanges() {
super.hookAfterChanges();
final Mission mission = getMissionVersion().getMission();
for (final MissionItem missionItem : mission.getMissionItemsSet()) {
if (missionItem != this && missionItem.isPersonelExpenseItem()) {
if (!missionItem.areAllCostsDistributed()) {
missionItem.distributeCosts();
}
}
}
}
public int getNunberOfLunchesToDiscount(final Person person) {
int result = 0;
if (hasPeople(person)) {
final Mission mission = getMissionVersion().getMission();
final PersonelExpenseItem firstPersonelExpenseItem = findFirstPersonelExpenseItemFor(mission, person);
final PersonelExpenseItem lastPersonelExpenseItem = findLastPersonelExpenseItemFor(mission, person);
int numberOfDays = calculateNumberOfDays();
if (this == firstPersonelExpenseItem) {
numberOfDays--;
result += mission.getNunberOfLunchesToDiscountOnFirstPersonelExpenseDay(this);
}
if (this == lastPersonelExpenseItem) {
numberOfDays--;
result += mission.getNunberOfLunchesToDiscountOnLastPersonelExpenseDay(this);
}
result += numberOfDays;
}
return result;
}
@Override
public boolean requiresFundAllocation() {
return false;
}
@Override
protected void setNewVersionInformation(final MissionItem missionItem) {
final PersonelExpenseItem personelExpenseItem = (PersonelExpenseItem) missionItem;
personelExpenseItem.setStart(getStart());
personelExpenseItem.setEnd(getEnd());
personelExpenseItem.setDailyPersonelExpenseCategory(getDailyPersonelExpenseCategory());
}
@Override
public boolean isAvailableForEdit() {
final MissionVersion missionVersion = getMissionVersion();
final Mission mission = missionVersion.getMission();
return super.isAvailableForEdit() || mission.isTerminatedWithChanges();
}
@Override
protected boolean canAutoArchive() {
return false;
}
}
| true | true | public double getExpenseFactor(final Person person) {
double result = 0.0;
if (getPeopleSet().contains(person)) {
final Mission mission = getMissionVersion().getMission();
final PersonelExpenseItem firstPersonelExpenseItem = findFirstPersonelExpenseItemFor(mission, person);
final PersonelExpenseItem lastPersonelExpenseItem = findLastPersonelExpenseItemFor(mission, person);
int numberOfDays = calculateNumberOfDays();
if (this == firstPersonelExpenseItem) {
numberOfDays--;
result += mission.getFirstDayPersonelDayExpensePercentage(this);
}
if (this == lastPersonelExpenseItem) {
numberOfDays--;
result += mission.getLastDayPersonelDayExpensePercentage(this);
}
result += numberOfDays;
}
return result;
}
| public double getExpenseFactor(final Person person) {
double result = 0.0;
if (getPeopleSet().contains(person)) {
final Mission mission = getMissionVersion().getMission();
final PersonelExpenseItem firstPersonelExpenseItem = findFirstPersonelExpenseItemFor(mission, person);
final PersonelExpenseItem lastPersonelExpenseItem = findLastPersonelExpenseItemFor(mission, person);
int numberOfDays = calculateNumberOfDays();
if (this == firstPersonelExpenseItem) {
numberOfDays--;
result += mission.getFirstDayPersonelDayExpensePercentage(this);
}
if (this == lastPersonelExpenseItem && numberOfDays > 0) {
numberOfDays--;
result += mission.getLastDayPersonelDayExpensePercentage(this);
}
result += numberOfDays;
}
return result;
}
|
diff --git a/src/test/java/com/mashape/client/test/http/AuthUtilTest.java b/src/test/java/com/mashape/client/test/http/AuthUtilTest.java
index 72f9232..897cbe1 100644
--- a/src/test/java/com/mashape/client/test/http/AuthUtilTest.java
+++ b/src/test/java/com/mashape/client/test/http/AuthUtilTest.java
@@ -1,40 +1,40 @@
/*
*
* Mashape Java Client library.
* Copyright (C) 2011 Mashape, 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* The author of this software is Mashape, Inc.
* For any question or feedback please contact us at: [email protected]
*
*/
package com.mashape.client.test.http;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.mashape.client.http.AuthUtil;
public class AuthUtilTest {
@Test
public void testRequestToken() {
- assertEquals(112, AuthUtil.generateAuthenticationHeader("ciao", "marco").getValue().length());
- assertEquals(112, AuthUtil.generateAuthenticationHeader("ciao", "piipopopopopopopo").getValue().length());
+ assertEquals(108, AuthUtil.generateAuthenticationHeader("ciao", "marco").getValue().length());
+ assertEquals(108, AuthUtil.generateAuthenticationHeader("ciao", "piipopopopopopopo").getValue().length());
}
}
| true | true | public void testRequestToken() {
assertEquals(112, AuthUtil.generateAuthenticationHeader("ciao", "marco").getValue().length());
assertEquals(112, AuthUtil.generateAuthenticationHeader("ciao", "piipopopopopopopo").getValue().length());
}
| public void testRequestToken() {
assertEquals(108, AuthUtil.generateAuthenticationHeader("ciao", "marco").getValue().length());
assertEquals(108, AuthUtil.generateAuthenticationHeader("ciao", "piipopopopopopopo").getValue().length());
}
|
diff --git a/src/java/com/stackframe/sarariman/Timesheet.java b/src/java/com/stackframe/sarariman/Timesheet.java
index 7e3beee..1818b29 100644
--- a/src/java/com/stackframe/sarariman/Timesheet.java
+++ b/src/java/com/stackframe/sarariman/Timesheet.java
@@ -1,400 +1,400 @@
/*
* Copyright (C) 2009 StackFrame, LLC
* This code is licensed under GPLv2.
*/
package com.stackframe.sarariman;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author mcculley
*/
public class Timesheet {
// FIXME: These hard coded task numbers should come from a config file.
private static final int holidayTask = 4;
private static final int PTOTask = 5;
private final Sarariman sarariman;
private final int employeeNumber;
private final Date week;
private final Logger logger = Logger.getLogger(getClass().getName());
public Timesheet(Sarariman sarariman, int employeeNumber, Date week) {
this.sarariman = sarariman;
this.employeeNumber = employeeNumber;
this.week = week;
}
public static Timesheet lookup(Sarariman sarariman, int employeeNumber, java.util.Date week) {
return new Timesheet(sarariman, employeeNumber, new Date(week.getTime()));
}
public double getRegularHours() throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement(
"SELECT SUM(hours.duration) AS total " +
"FROM hours " +
"WHERE employee=? AND hours.date >= ? AND hours.date < DATE_ADD(?, INTERVAL 7 DAY) AND hours.task != ? AND hours.task != ?");
try {
ps.setInt(1, employeeNumber);
ps.setDate(2, week);
ps.setDate(3, week);
ps.setInt(4, holidayTask);
ps.setInt(5, PTOTask);
ResultSet resultSet = ps.executeQuery();
try {
if (!resultSet.first()) {
return 0;
} else {
String total = resultSet.getString("total");
return total == null ? 0 : Double.parseDouble(total);
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public double getTotalHours() throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement(
"SELECT SUM(hours.duration) AS total " +
"FROM hours " +
"WHERE employee=? AND hours.date >= ? AND hours.date < DATE_ADD(?, INTERVAL 7 DAY)");
try {
ps.setInt(1, employeeNumber);
ps.setDate(2, week);
ps.setDate(3, week);
ResultSet resultSet = ps.executeQuery();
try {
if (!resultSet.first()) {
return 0;
} else {
String total = resultSet.getString("total");
return total == null ? 0 : Double.parseDouble(total);
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public Map<Calendar, BigDecimal> getHoursByDay() throws SQLException {
Map<Calendar, BigDecimal> map = new LinkedHashMap<Calendar, BigDecimal>();
for (int i = 0; i < 7; i++) {
Calendar calendar = new GregorianCalendar();
calendar.set(week.getYear() + 1900, week.getMonth(), week.getDate());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
- calendar.roll(Calendar.DATE, i);
+ calendar.add(Calendar.DATE, i);
map.put(calendar, new BigDecimal(0));
}
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement(
"SELECT duration, date " +
"FROM hours " +
"WHERE employee=? AND hours.date >= ? AND hours.date < DATE_ADD(?, INTERVAL 7 DAY)");
try {
ps.setInt(1, employeeNumber);
ps.setDate(2, week);
ps.setDate(3, week);
ResultSet resultSet = ps.executeQuery();
try {
while (resultSet.next()) {
Date date = resultSet.getDate("date");
Calendar calendar = new GregorianCalendar();
calendar.set(date.getYear() + 1900, date.getMonth(), date.getDate());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
BigDecimal duration = resultSet.getBigDecimal("duration");
map.put(calendar, map.get(calendar).add(duration));
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
return map;
}
private double getHours(int task) throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement(
"SELECT SUM(hours.duration) AS total " +
"FROM hours " +
"WHERE employee=? AND hours.date >= ? AND hours.date < DATE_ADD(?, INTERVAL 7 DAY) AND hours.task = ?");
try {
ps.setInt(1, employeeNumber);
ps.setDate(2, week);
ps.setDate(3, week);
ps.setInt(4, task);
ResultSet resultSet = ps.executeQuery();
try {
if (!resultSet.first()) {
return 0;
} else {
String total = resultSet.getString("total");
return total == null ? 0 : Double.parseDouble(total);
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public double getHours(Date day) throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT SUM(duration) AS total FROM hours WHERE employee=? AND date=?");
try {
ps.setInt(1, employeeNumber);
ps.setDate(2, day);
ResultSet resultSet = ps.executeQuery();
try {
if (!resultSet.first()) {
return 0;
} else {
String total = resultSet.getString("total");
return total == null ? 0 : Double.parseDouble(total);
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public double getPTOHours() throws SQLException {
return getHours(PTOTask);
}
public double getHolidayHours() throws SQLException {
return getHours(holidayTask);
}
public boolean isSubmitted() throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT * FROM timecards WHERE date = ? AND employee = ?");
try {
ps.setDate(1, week);
ps.setInt(2, employeeNumber);
ResultSet resultSet = ps.executeQuery();
try {
return resultSet.first();
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public Employee getApprover() throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT approver FROM timecards WHERE date = ? AND employee = ?");
try {
ps.setDate(1, week);
ps.setInt(2, employeeNumber);
ResultSet resultSet = ps.executeQuery();
try {
if (!resultSet.first()) {
return null;
} else {
int employee = resultSet.getInt("approver");
return sarariman.getDirectory().getByNumber().get(employee);
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public Timestamp getApprovedTimestamp() throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT approved_timestamp FROM timecards WHERE date = ? AND employee = ?");
try {
ps.setDate(1, week);
ps.setInt(2, employeeNumber);
ResultSet resultSet = ps.executeQuery();
try {
if (!resultSet.first()) {
return null;
} else {
return resultSet.getTimestamp("approved_timestamp");
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public Timestamp getSubmittedTimestamp() throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT submitted_timestamp FROM timecards WHERE date = ? AND employee = ?");
try {
ps.setDate(1, week);
ps.setInt(2, employeeNumber);
ResultSet resultSet = ps.executeQuery();
try {
if (!resultSet.first()) {
return null;
} else {
return resultSet.getTimestamp("submitted_timestamp");
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public boolean isApproved() throws SQLException {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("SELECT * FROM timecards WHERE date = ? AND employee = ?");
try {
ps.setDate(1, week);
ps.setInt(2, employeeNumber);
ResultSet resultSet = ps.executeQuery();
try {
if (!resultSet.first()) {
return false;
} else {
return resultSet.getBoolean("approved");
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
}
public boolean approve(Employee user) {
try {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("UPDATE timecards SET approved=true, approver=?, approved_timestamp=? WHERE date=? AND employee=?");
try {
ps.setInt(1, user.getNumber());
ps.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
ps.setDate(3, week);
ps.setInt(4, employeeNumber);
int rowCount = ps.executeUpdate();
if (rowCount != 1) {
logger.severe("update for week=" + week + " and employee=" + employeeNumber + " did not modify a row");
return false;
} else {
Employee employee = sarariman.getDirectory().getByNumber().get(employeeNumber);
sarariman.getEmailDispatcher().send(employee.getEmail(), null, "timesheet approved",
"Timesheet approved for " + employee.getFullName() + " for week of " + week + ".");
return true;
}
} finally {
ps.close();
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "caught exception approving timesheet", se);
return false;
}
}
public static boolean approve(Timesheet timesheet, Employee user) {
return timesheet.approve(user);
}
public boolean reject() {
try {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("DELETE FROM timecards WHERE date=? AND employee=?");
try {
ps.setDate(1, week);
ps.setInt(2, employeeNumber);
int rowCount = ps.executeUpdate();
if (rowCount != 1) {
logger.severe("reject for week=" + week + " and employee=" + employeeNumber + " did not modify a row");
return false;
} else {
Employee employee = sarariman.getDirectory().getByNumber().get(employeeNumber);
sarariman.getEmailDispatcher().send(employee.getEmail(), null, "timesheet rejected",
"Timesheet rejected for " + employee.getFullName() + " for week of " + week + ".");
return true;
}
} finally {
ps.close();
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "caught exception rejecting timesheet", se);
return false;
}
}
public static boolean reject(Timesheet timesheet) {
return timesheet.reject();
}
public boolean submit() {
try {
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement("INSERT INTO timecards (employee, date, approved) values(?, ?, false)");
try {
ps.setInt(1, employeeNumber);
ps.setDate(2, week);
int rowCount = ps.executeUpdate();
if (rowCount != 1) {
logger.severe("submit for week=" + week + " and employee=" + employeeNumber + " did not modify a row");
return false;
} else {
Employee employee = sarariman.getDirectory().getByNumber().get(employeeNumber);
sarariman.getEmailDispatcher().send(EmailDispatcher.addresses(sarariman.getApprovers()), null,
"timesheet submitted",
"Timesheet submitted for " + employee.getFullName() + " for week of " + week + ".");
return true;
}
} finally {
ps.close();
}
} catch (SQLException se) {
logger.log(Level.SEVERE, "caught exception submitting timesheet", se);
return false;
}
}
public static boolean submit(Timesheet timesheet) {
return timesheet.submit();
}
@Override
public String toString() {
return "{employee=" + employeeNumber + ",week=" + week + "}";
}
}
| true | true | public Map<Calendar, BigDecimal> getHoursByDay() throws SQLException {
Map<Calendar, BigDecimal> map = new LinkedHashMap<Calendar, BigDecimal>();
for (int i = 0; i < 7; i++) {
Calendar calendar = new GregorianCalendar();
calendar.set(week.getYear() + 1900, week.getMonth(), week.getDate());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.roll(Calendar.DATE, i);
map.put(calendar, new BigDecimal(0));
}
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement(
"SELECT duration, date " +
"FROM hours " +
"WHERE employee=? AND hours.date >= ? AND hours.date < DATE_ADD(?, INTERVAL 7 DAY)");
try {
ps.setInt(1, employeeNumber);
ps.setDate(2, week);
ps.setDate(3, week);
ResultSet resultSet = ps.executeQuery();
try {
while (resultSet.next()) {
Date date = resultSet.getDate("date");
Calendar calendar = new GregorianCalendar();
calendar.set(date.getYear() + 1900, date.getMonth(), date.getDate());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
BigDecimal duration = resultSet.getBigDecimal("duration");
map.put(calendar, map.get(calendar).add(duration));
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
return map;
}
| public Map<Calendar, BigDecimal> getHoursByDay() throws SQLException {
Map<Calendar, BigDecimal> map = new LinkedHashMap<Calendar, BigDecimal>();
for (int i = 0; i < 7; i++) {
Calendar calendar = new GregorianCalendar();
calendar.set(week.getYear() + 1900, week.getMonth(), week.getDate());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.add(Calendar.DATE, i);
map.put(calendar, new BigDecimal(0));
}
Connection connection = sarariman.getConnection();
PreparedStatement ps = connection.prepareStatement(
"SELECT duration, date " +
"FROM hours " +
"WHERE employee=? AND hours.date >= ? AND hours.date < DATE_ADD(?, INTERVAL 7 DAY)");
try {
ps.setInt(1, employeeNumber);
ps.setDate(2, week);
ps.setDate(3, week);
ResultSet resultSet = ps.executeQuery();
try {
while (resultSet.next()) {
Date date = resultSet.getDate("date");
Calendar calendar = new GregorianCalendar();
calendar.set(date.getYear() + 1900, date.getMonth(), date.getDate());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
BigDecimal duration = resultSet.getBigDecimal("duration");
map.put(calendar, map.get(calendar).add(duration));
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
return map;
}
|
diff --git a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
index 4b90b9bc..f40e599d 100644
--- a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
+++ b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
@@ -1,824 +1,829 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ethan Hugg
* Terry Lucas
* Milen Nankov
* David P. Caldwell <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.xmlimpl;
import org.mozilla.javascript.*;
import org.mozilla.javascript.xml.*;
import java.util.ArrayList;
class XMLList extends XMLObjectImpl implements Function {
static final long serialVersionUID = -4543618751670781135L;
private XmlNode.InternalList _annos;
private XMLObjectImpl targetObject = null;
private XmlNode.QName targetProperty = null;
XMLList(XMLLibImpl lib, Scriptable scope, XMLObject prototype) {
super(lib, scope, prototype);
_annos = new XmlNode.InternalList();
}
/* TODO Will probably end up unnecessary as we move things around */
XmlNode.InternalList getNodeList() {
return _annos;
}
// TODO Should be XMLObjectImpl, XMLName?
void setTargets(XMLObjectImpl object, XmlNode.QName property) {
targetObject = object;
targetProperty = property;
}
/* TODO: original author marked this as deprecated */
private XML getXmlFromAnnotation(int index) {
return getXML(_annos, index);
}
@Override
XML getXML() {
if (length() == 1) return getXmlFromAnnotation(0);
return null;
}
private void internalRemoveFromList(int index) {
_annos.remove(index);
}
void replace(int index, XML xml) {
if (index < length()) {
XmlNode.InternalList newAnnoList = new XmlNode.InternalList();
newAnnoList.add(_annos, 0, index);
newAnnoList.add(xml);
newAnnoList.add(_annos, index+1, length());
_annos = newAnnoList;
}
}
private void insert(int index, XML xml) {
if (index < length()) {
XmlNode.InternalList newAnnoList = new XmlNode.InternalList();
newAnnoList.add(_annos, 0, index);
newAnnoList.add(xml);
newAnnoList.add(_annos, index, length());
_annos = newAnnoList;
}
}
//
//
// methods overriding ScriptableObject
//
//
@Override
public String getClassName() {
return "XMLList";
}
//
//
// methods overriding IdScriptableObject
//
//
@Override
public Object get(int index, Scriptable start) {
//Log("get index: " + index);
if (index >= 0 && index < length()) {
return getXmlFromAnnotation(index);
} else {
return Scriptable.NOT_FOUND;
}
}
@Override
boolean hasXMLProperty(XMLName xmlName) {
boolean result = false;
// Has now should return true if the property would have results > 0 or
// if it's a method name
String name = xmlName.localName();
if ((getPropertyList(xmlName).length() > 0) ||
(getMethod(name) != NOT_FOUND)) {
result = true;
}
return result;
}
@Override
public boolean has(int index, Scriptable start) {
return 0 <= index && index < length();
}
@Override
void putXMLProperty(XMLName xmlName, Object value) {
//Log("put property: " + name);
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (length() > 1) {
throw ScriptRuntime.typeError(
"Assignment to lists with more than one item is not supported");
} else if (length() == 0) {
// Secret sauce for super-expandos.
// We set an element here, and then add ourselves to our target.
if (targetObject != null && targetProperty != null &&
targetProperty.getLocalName() != null &&
targetProperty.getLocalName().length() > 0)
{
// Add an empty element with our targetProperty name and
// then set it.
XML xmlValue = newTextElementXML(null, targetProperty, null);
addToList(xmlValue);
if(xmlName.isAttributeName()) {
setAttribute(xmlName, value);
} else {
XML xml = item(0);
xml.putXMLProperty(xmlName, value);
// Update the list with the new item at location 0.
replace(0, item(0));
}
// Now add us to our parent
XMLName name2 = XMLName.formProperty(
targetProperty.getNamespace().getUri(),
targetProperty.getLocalName());
targetObject.putXMLProperty(name2, this);
} else {
throw ScriptRuntime.typeError(
"Assignment to empty XMLList without targets not supported");
}
} else if(xmlName.isAttributeName()) {
setAttribute(xmlName, value);
} else {
XML xml = item(0);
xml.putXMLProperty(xmlName, value);
// Update the list with the new item at location 0.
replace(0, item(0));
if (targetObject != null && targetProperty != null &&
targetProperty.getLocalName() != null)
{
// Now add us to our parent
XMLName name2 = XMLName.formProperty(
targetProperty.getNamespace().getUri(),
targetProperty.getLocalName());
targetObject.putXMLProperty(name2, this);
}
}
}
@Override
Object getXMLProperty(XMLName name) {
return getPropertyList(name);
}
private void replaceNode(XML xml, XML with) {
xml.replaceWith(with);
}
@Override
public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
if (xmlValue == null) {
- xmlValue = item(0).copy();
+ XML x = item(0);
+ xmlValue = x == null
+ ? newTextElementXML(null,targetProperty,null)
+ : x.copy();
}
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
- parent = item(index).parent();
+ parent = item(index).parent();
+ } else if (length() == 0) {
+ parent = targetObject != null ? targetObject.getXML() : parent();
} else {
- // Appending
- parent = parent();
+ // Appending
+ parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
private XML getXML(XmlNode.InternalList _annos, int index) {
if (index >= 0 && index < length()) {
return xmlFromNode(_annos.item(index));
} else {
return null;
}
}
@Override
void deleteXMLProperty(XMLName name) {
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
if (xml.isElement()) {
xml.deleteXMLProperty(name);
}
}
}
@Override
public void delete(int index) {
if (index >= 0 && index < length()) {
XML xml = getXmlFromAnnotation(index);
xml.remove();
internalRemoveFromList(index);
}
}
@Override
public Object[] getIds() {
Object enumObjs[];
if (isPrototype()) {
enumObjs = new Object[0];
} else {
enumObjs = new Object[length()];
for (int i = 0; i < enumObjs.length; i++) {
enumObjs[i] = Integer.valueOf(i);
}
}
return enumObjs;
}
public Object[] getIdsForDebug() {
return getIds();
}
// XMLList will remove will delete all items in the list (a set delete) this differs from the XMLList delete operator.
void remove() {
int nLen = length();
for (int i = nLen - 1; i >= 0; i--) {
XML xml = getXmlFromAnnotation(i);
if (xml != null) {
xml.remove();
internalRemoveFromList(i);
}
}
}
XML item(int index) {
return _annos != null
? getXmlFromAnnotation(index) : createEmptyXML();
}
private void setAttribute(XMLName xmlName, Object value) {
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
xml.setAttribute(xmlName, value);
}
}
void addToList(Object toAdd) {
_annos.addToList(toAdd);
}
//
//
// Methods from section 12.4.4 in the spec
//
//
@Override
XMLList child(int index) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).child(index));
}
return result;
}
@Override
XMLList child(XMLName xmlName) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).child(xmlName));
}
return result;
}
@Override
void addMatches(XMLList rv, XMLName name) {
for (int i=0; i<length(); i++) {
getXmlFromAnnotation(i).addMatches(rv, name);
}
}
@Override
XMLList children() {
ArrayList<XML> list = new ArrayList<XML>();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
if (xml != null) {
XMLList childList = xml.children();
int cChildren = childList.length();
for (int j = 0; j < cChildren; j++) {
list.add(childList.item(j));
}
}
}
XMLList allChildren = newXMLList();
int sz = list.size();
for (int i = 0; i < sz; i++) {
allChildren.addToList(list.get(i));
}
return allChildren;
}
@Override
XMLList comments() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.comments());
}
return result;
}
@Override
XMLList elements(XMLName name) {
XMLList rv = newXMLList();
for (int i=0; i<length(); i++) {
XML xml = getXmlFromAnnotation(i);
rv.addToList(xml.elements(name));
}
return rv;
}
@Override
boolean contains(Object xml) {
boolean result = false;
for (int i = 0; i < length(); i++) {
XML member = getXmlFromAnnotation(i);
if (member.equivalentXml(xml)) {
result = true;
break;
}
}
return result;
}
@Override
XMLObjectImpl copy() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.copy());
}
return result;
}
@Override
boolean hasOwnProperty(XMLName xmlName) {
if (isPrototype()) {
String property = xmlName.localName();
return (findPrototypeId(property) != 0);
} else {
return (getPropertyList(xmlName).length() > 0);
}
}
@Override
boolean hasComplexContent() {
boolean complexContent;
int length = length();
if (length == 0) {
complexContent = false;
} else if (length == 1) {
complexContent = getXmlFromAnnotation(0).hasComplexContent();
} else {
complexContent = false;
for (int i = 0; i < length; i++) {
XML nextElement = getXmlFromAnnotation(i);
if (nextElement.isElement()) {
complexContent = true;
break;
}
}
}
return complexContent;
}
@Override
boolean hasSimpleContent() {
if (length() == 0) {
return true;
} else if (length() == 1) {
return getXmlFromAnnotation(0).hasSimpleContent();
} else {
for (int i=0; i<length(); i++) {
XML nextElement = getXmlFromAnnotation(i);
if (nextElement.isElement()) {
return false;
}
}
return true;
}
}
@Override
int length() {
int result = 0;
if (_annos != null) {
result = _annos.length();
}
return result;
}
@Override
void normalize() {
for (int i = 0; i < length(); i++) {
getXmlFromAnnotation(i).normalize();
}
}
/**
* If list is empty, return undefined, if elements have different parents return undefined,
* If they all have the same parent, return that parent
*/
@Override
Object parent() {
if (length() == 0) return Undefined.instance;
XML candidateParent = null;
for (int i = 0; i < length(); i++) {
Object currParent = getXmlFromAnnotation(i).parent();
if (!(currParent instanceof XML)) return Undefined.instance;
XML xml = (XML)currParent;
if (i == 0) {
// Set the first for the rest to compare to.
candidateParent = xml;
} else {
if (candidateParent.is(xml)) {
// keep looking
} else {
return Undefined.instance;
}
}
}
return candidateParent;
}
@Override
XMLList processingInstructions(XMLName xmlName) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.processingInstructions(xmlName));
}
return result;
}
@Override
boolean propertyIsEnumerable(Object name) {
long index;
if (name instanceof Integer) {
index = ((Integer)name).intValue();
} else if (name instanceof Number) {
double x = ((Number)name).doubleValue();
index = (long)x;
if (index != x) {
return false;
}
if (index == 0 && 1.0 / x < 0) {
// Negative 0
return false;
}
} else {
String s = ScriptRuntime.toString(name);
index = ScriptRuntime.testUint32String(s);
}
return (0 <= index && index < length());
}
@Override
XMLList text() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).text());
}
return result;
}
@Override
public String toString() {
// ECMA357 10.1.2
if (hasSimpleContent()) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < length(); i++) {
XML next = getXmlFromAnnotation(i);
if (next.isComment() || next.isProcessingInstruction()) {
// do nothing
} else {
sb.append(next.toString());
}
}
return sb.toString();
} else {
return toXMLString();
}
}
@Override
String toSource(int indent) {
return toXMLString();
}
@Override
String toXMLString() {
// See ECMA 10.2.1
StringBuffer sb = new StringBuffer();
for (int i=0; i<length(); i++) {
if (getProcessor().isPrettyPrinting() && i != 0) {
sb.append('\n');
}
sb.append(getXmlFromAnnotation(i).toXMLString());
}
return sb.toString();
}
@Override
Object valueOf() {
return this;
}
//
// Other public Functions from XMLObject
//
@Override
boolean equivalentXml(Object target) {
boolean result = false;
// Zero length list should equate to undefined
if (target instanceof Undefined && length() == 0) {
result = true;
} else if (length() == 1) {
result = getXmlFromAnnotation(0).equivalentXml(target);
} else if (target instanceof XMLList) {
XMLList otherList = (XMLList) target;
if (otherList.length() == length()) {
result = true;
for (int i = 0; i < length(); i++) {
if (!getXmlFromAnnotation(i).equivalentXml(otherList.getXmlFromAnnotation(i))) {
result = false;
break;
}
}
}
}
return result;
}
private XMLList getPropertyList(XMLName name) {
XMLList propertyList = newXMLList();
XmlNode.QName qname = null;
if (!name.isDescendants() && !name.isAttributeName()) {
// Only set the targetProperty if this is a regular child get
// and not a descendant or attribute get
qname = name.toQname();
}
propertyList.setTargets(this, qname);
for (int i = 0; i < length(); i++) {
propertyList.addToList(
getXmlFromAnnotation(i).getPropertyList(name));
}
return propertyList;
}
private Object applyOrCall(boolean isApply,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args) {
String methodName = isApply ? "apply" : "call";
if(!(thisObj instanceof XMLList) ||
((XMLList)thisObj).targetProperty == null)
throw ScriptRuntime.typeError1("msg.isnt.function",
methodName);
return ScriptRuntime.applyOrCall(isApply, cx, scope, thisObj, args);
}
@Override
protected Object jsConstructor(Context cx, boolean inNewExpr,
Object[] args)
{
if (args.length == 0) {
return newXMLList();
} else {
Object arg0 = args[0];
if (!inNewExpr && arg0 instanceof XMLList) {
// XMLList(XMLList) returns the same object.
return arg0;
}
return newXMLListFrom(arg0);
}
}
/**
* See ECMA 357, 11_2_2_1, Semantics, 3_e.
*/
@Override
public Scriptable getExtraMethodSource(Context cx) {
if (length() == 1) {
return getXmlFromAnnotation(0);
}
return null;
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args) {
// This XMLList is being called as a Function.
// Let's find the real Function object.
if(targetProperty == null)
throw ScriptRuntime.notFunctionError(this);
String methodName = targetProperty.getLocalName();
boolean isApply = methodName.equals("apply");
if(isApply || methodName.equals("call"))
return applyOrCall(isApply, cx, scope, thisObj, args);
Callable method = ScriptRuntime.getElemFunctionAndThis(
this, methodName, cx);
// Call lastStoredScriptable to clear stored thisObj
// but ignore the result as the method should use the supplied
// thisObj, not one from redirected call
ScriptRuntime.lastStoredScriptable(cx);
return method.call(cx, scope, thisObj, args);
}
public Scriptable construct(Context cx, Scriptable scope, Object[] args) {
throw ScriptRuntime.typeError1("msg.not.ctor", "XMLList");
}
}
| false | true | public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
if (xmlValue == null) {
xmlValue = item(0).copy();
}
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
| public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
if (xmlValue == null) {
XML x = item(0);
xmlValue = x == null
? newTextElementXML(null,targetProperty,null)
: x.copy();
}
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else if (length() == 0) {
parent = targetObject != null ? targetObject.getXML() : parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
|
diff --git a/src/main/java/net/chiisana/builddit/command/PlotCommand.java b/src/main/java/net/chiisana/builddit/command/PlotCommand.java
index 9e3450c..1669eca 100644
--- a/src/main/java/net/chiisana/builddit/command/PlotCommand.java
+++ b/src/main/java/net/chiisana/builddit/command/PlotCommand.java
@@ -1,210 +1,212 @@
package net.chiisana.builddit.command;
import net.chiisana.builddit.controller.BuildditPlot;
import net.chiisana.builddit.controller.Plot;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.HashSet;
public class PlotCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("plot"))
{
if (!(sender instanceof Player))
{
sender.sendMessage("Builddit Plot only have in game commands.");
return true;
}
Player player = (Player)sender;
String subCmd;
if (args.length == 0)
{
// No length, output help
subCmd = "help";
} else {
subCmd = args[0];
}
if (subCmd.equalsIgnoreCase("help"))
{
/*
int page;
if (args.length < 2)
{
page = 1;
} else {
page = Integer.parseInt(args[1]);
page = page > 0 ? page : 1; // No page 0, not a number from user.
}
sender.sendMessage("Builddit Plot Commands (Page " + page + " of Y)"); // For future
*/
player.sendMessage("Builddit Plot Commands");
player.sendMessage("====================================");
player.sendMessage(" claim - attempt to claim the plot.");
player.sendMessage(" unclaim - unclaim the plot.");
player.sendMessage(" clear - clear (regenerate) the plot (warning: no undo).");
player.sendMessage(" reset - clear + unclaim the plot (warning: no undo).");
player.sendMessage(" auth <name> - authorizes <name> to work on the plot.");
player.sendMessage(" unauth <name> - unauthorizes <name> to work on the plot.");
return true;
}
Plot currentPlot = BuildditPlot.getInstance().getPlotAt(player.getLocation());
if (currentPlot == null)
{
player.sendMessage("Unable to acquire plot on your current position. Database server may be down right now. Please contact the server admin and try again later.");
return true;
}
if (subCmd.equalsIgnoreCase("claim"))
{
String result = this._claim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("unclaim"))
{
String result = this._unclaim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("clear"))
{
String result = this._clear(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("reset"))
{
String result = this._clear(currentPlot, player);
player.sendMessage(result);
result = this._unclaim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("auth"))
{
if (args.length < 2)
{
player.sendMessage("You must specify who you are authorizing. Example usage: ");
player.sendMessage("/plot auth huang_a -- this authorizes huang_a to work on the plot.");
return true;
}
String target = args[1];
if (currentPlot.authorize(target, player))
{
// Also add permissions to all connected plots
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
for (Plot plot : connectedPlots)
{
plot.authorize(target, player);
}
player.sendMessage(target + " has been added to the authorized users list.");
return true;
} else {
player.sendMessage("You do not own the plot, so you cannot modify the authorized users list.");
return true;
}
}
else if (subCmd.equalsIgnoreCase("unauth"))
{
if (args.length < 2)
{
player.sendMessage("You must specify who you are unauthorizing. Example usage: ");
player.sendMessage("/plot unauth huang_a -- this unauthorizes huang_a to work on the plot.");
}
String target = args[1];
if (currentPlot.unauthorize(target, player))
{
// Also remove permissions from all connected plots
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
for (Plot plot : connectedPlots)
{
plot.unauthorize(target, player);
}
player.sendMessage(target + " has been removed from the authorized users list.");
return true;
} else {
player.sendMessage("You do not own the plot, so you cannot modify the authorized users list.");
return true;
}
}
else if (subCmd.equalsIgnoreCase("list-auth"))
{
if (currentPlot.getOwner().equals(player.getName()))
{
player.sendMessage("People authorized to edit this plot: ");
String authorizedList = "";
for(String authorized : currentPlot.getAuthorized())
{
authorizedList = authorizedList + ", " + authorized;
}
- authorizedList = authorizedList.substring(2); // truncate the first ", "
+ if (authorizedList.length() > 3) {
+ authorizedList = authorizedList.substring(2); // truncate the first ", "
+ }
player.sendMessage(authorizedList);
}
}
else if (subCmd.equalsIgnoreCase("test-connected"))
{
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
player.sendMessage("Connected Plots (" + connectedPlots.size() + "): ");
for(Plot plot : connectedPlots)
{
player.sendMessage(plot.toString());
}
}
}
return false;
}
private String _claim(Plot plot, Player player) {
// Claiming a plot is pretty straight forward: try to claim it, and let player know result
switch(plot.claim(player)) {
case 1:
HashSet<Plot> connectedPlot = plot.getConnectedPlots();
for (Plot neighbour : connectedPlot)
{
// Claiming a connected plot, inherit authorizations accordingly
plot.copyAuthFrom(neighbour);
break;
}
return "You have successfully claimed the plot.";
case 0:
return "Plot is already owned by " + plot.getOwner() + ".";
case -1:
return "Database server is unavailable at this time. Please try again later.";
default:
return "You should never be seeing this message. Something went wrong, blame the developer.";
}
}
private String _unclaim(Plot plot, Player player) {
// Unclaiming is a bit less straight forward: only allow if player owns it or is admin
switch(plot.unclaim(player)) {
case 1:
return "You have successfully unclaimed the plot.";
case 0:
return "You do not own the plot, so you cannot unclaim it.";
case -1:
return "Database server is unavailable at this time. Please try again later.";
default:
return "You should never be seeing this message. Something went wrong, blame the developer.";
}
}
private String _clear(Plot plot, Player player) {
// Clearing the plot: only allow if player owns it or is admin
if (plot.clear(player))
{
return "Plot content have been cleared.";
} else {
return "You do not own the plot, so you cannot clear it.";
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("plot"))
{
if (!(sender instanceof Player))
{
sender.sendMessage("Builddit Plot only have in game commands.");
return true;
}
Player player = (Player)sender;
String subCmd;
if (args.length == 0)
{
// No length, output help
subCmd = "help";
} else {
subCmd = args[0];
}
if (subCmd.equalsIgnoreCase("help"))
{
/*
int page;
if (args.length < 2)
{
page = 1;
} else {
page = Integer.parseInt(args[1]);
page = page > 0 ? page : 1; // No page 0, not a number from user.
}
sender.sendMessage("Builddit Plot Commands (Page " + page + " of Y)"); // For future
*/
player.sendMessage("Builddit Plot Commands");
player.sendMessage("====================================");
player.sendMessage(" claim - attempt to claim the plot.");
player.sendMessage(" unclaim - unclaim the plot.");
player.sendMessage(" clear - clear (regenerate) the plot (warning: no undo).");
player.sendMessage(" reset - clear + unclaim the plot (warning: no undo).");
player.sendMessage(" auth <name> - authorizes <name> to work on the plot.");
player.sendMessage(" unauth <name> - unauthorizes <name> to work on the plot.");
return true;
}
Plot currentPlot = BuildditPlot.getInstance().getPlotAt(player.getLocation());
if (currentPlot == null)
{
player.sendMessage("Unable to acquire plot on your current position. Database server may be down right now. Please contact the server admin and try again later.");
return true;
}
if (subCmd.equalsIgnoreCase("claim"))
{
String result = this._claim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("unclaim"))
{
String result = this._unclaim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("clear"))
{
String result = this._clear(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("reset"))
{
String result = this._clear(currentPlot, player);
player.sendMessage(result);
result = this._unclaim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("auth"))
{
if (args.length < 2)
{
player.sendMessage("You must specify who you are authorizing. Example usage: ");
player.sendMessage("/plot auth huang_a -- this authorizes huang_a to work on the plot.");
return true;
}
String target = args[1];
if (currentPlot.authorize(target, player))
{
// Also add permissions to all connected plots
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
for (Plot plot : connectedPlots)
{
plot.authorize(target, player);
}
player.sendMessage(target + " has been added to the authorized users list.");
return true;
} else {
player.sendMessage("You do not own the plot, so you cannot modify the authorized users list.");
return true;
}
}
else if (subCmd.equalsIgnoreCase("unauth"))
{
if (args.length < 2)
{
player.sendMessage("You must specify who you are unauthorizing. Example usage: ");
player.sendMessage("/plot unauth huang_a -- this unauthorizes huang_a to work on the plot.");
}
String target = args[1];
if (currentPlot.unauthorize(target, player))
{
// Also remove permissions from all connected plots
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
for (Plot plot : connectedPlots)
{
plot.unauthorize(target, player);
}
player.sendMessage(target + " has been removed from the authorized users list.");
return true;
} else {
player.sendMessage("You do not own the plot, so you cannot modify the authorized users list.");
return true;
}
}
else if (subCmd.equalsIgnoreCase("list-auth"))
{
if (currentPlot.getOwner().equals(player.getName()))
{
player.sendMessage("People authorized to edit this plot: ");
String authorizedList = "";
for(String authorized : currentPlot.getAuthorized())
{
authorizedList = authorizedList + ", " + authorized;
}
authorizedList = authorizedList.substring(2); // truncate the first ", "
player.sendMessage(authorizedList);
}
}
else if (subCmd.equalsIgnoreCase("test-connected"))
{
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
player.sendMessage("Connected Plots (" + connectedPlots.size() + "): ");
for(Plot plot : connectedPlots)
{
player.sendMessage(plot.toString());
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("plot"))
{
if (!(sender instanceof Player))
{
sender.sendMessage("Builddit Plot only have in game commands.");
return true;
}
Player player = (Player)sender;
String subCmd;
if (args.length == 0)
{
// No length, output help
subCmd = "help";
} else {
subCmd = args[0];
}
if (subCmd.equalsIgnoreCase("help"))
{
/*
int page;
if (args.length < 2)
{
page = 1;
} else {
page = Integer.parseInt(args[1]);
page = page > 0 ? page : 1; // No page 0, not a number from user.
}
sender.sendMessage("Builddit Plot Commands (Page " + page + " of Y)"); // For future
*/
player.sendMessage("Builddit Plot Commands");
player.sendMessage("====================================");
player.sendMessage(" claim - attempt to claim the plot.");
player.sendMessage(" unclaim - unclaim the plot.");
player.sendMessage(" clear - clear (regenerate) the plot (warning: no undo).");
player.sendMessage(" reset - clear + unclaim the plot (warning: no undo).");
player.sendMessage(" auth <name> - authorizes <name> to work on the plot.");
player.sendMessage(" unauth <name> - unauthorizes <name> to work on the plot.");
return true;
}
Plot currentPlot = BuildditPlot.getInstance().getPlotAt(player.getLocation());
if (currentPlot == null)
{
player.sendMessage("Unable to acquire plot on your current position. Database server may be down right now. Please contact the server admin and try again later.");
return true;
}
if (subCmd.equalsIgnoreCase("claim"))
{
String result = this._claim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("unclaim"))
{
String result = this._unclaim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("clear"))
{
String result = this._clear(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("reset"))
{
String result = this._clear(currentPlot, player);
player.sendMessage(result);
result = this._unclaim(currentPlot, player);
player.sendMessage(result);
return true;
}
else if (subCmd.equalsIgnoreCase("auth"))
{
if (args.length < 2)
{
player.sendMessage("You must specify who you are authorizing. Example usage: ");
player.sendMessage("/plot auth huang_a -- this authorizes huang_a to work on the plot.");
return true;
}
String target = args[1];
if (currentPlot.authorize(target, player))
{
// Also add permissions to all connected plots
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
for (Plot plot : connectedPlots)
{
plot.authorize(target, player);
}
player.sendMessage(target + " has been added to the authorized users list.");
return true;
} else {
player.sendMessage("You do not own the plot, so you cannot modify the authorized users list.");
return true;
}
}
else if (subCmd.equalsIgnoreCase("unauth"))
{
if (args.length < 2)
{
player.sendMessage("You must specify who you are unauthorizing. Example usage: ");
player.sendMessage("/plot unauth huang_a -- this unauthorizes huang_a to work on the plot.");
}
String target = args[1];
if (currentPlot.unauthorize(target, player))
{
// Also remove permissions from all connected plots
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
for (Plot plot : connectedPlots)
{
plot.unauthorize(target, player);
}
player.sendMessage(target + " has been removed from the authorized users list.");
return true;
} else {
player.sendMessage("You do not own the plot, so you cannot modify the authorized users list.");
return true;
}
}
else if (subCmd.equalsIgnoreCase("list-auth"))
{
if (currentPlot.getOwner().equals(player.getName()))
{
player.sendMessage("People authorized to edit this plot: ");
String authorizedList = "";
for(String authorized : currentPlot.getAuthorized())
{
authorizedList = authorizedList + ", " + authorized;
}
if (authorizedList.length() > 3) {
authorizedList = authorizedList.substring(2); // truncate the first ", "
}
player.sendMessage(authorizedList);
}
}
else if (subCmd.equalsIgnoreCase("test-connected"))
{
HashSet<Plot> connectedPlots = currentPlot.getConnectedPlots();
player.sendMessage("Connected Plots (" + connectedPlots.size() + "): ");
for(Plot plot : connectedPlots)
{
player.sendMessage(plot.toString());
}
}
}
return false;
}
|
diff --git a/examples/jms/paging/src/org/jboss/jms/example/PagingExample.java b/examples/jms/paging/src/org/jboss/jms/example/PagingExample.java
index 1dc144f52..3cf6950f2 100644
--- a/examples/jms/paging/src/org/jboss/jms/example/PagingExample.java
+++ b/examples/jms/paging/src/org/jboss/jms/example/PagingExample.java
@@ -1,162 +1,162 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jms.example;
import org.jboss.common.example.JBMExample;
import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.InitialContext;
/**
* A simple JMS Queue example that creates a producer and consumer on a queue and sends then receives a message.
*
* @author <a href="[email protected]">Clebert Suconic</a>
*/
public class PagingExample extends JBMExample
{
public static void main(String[] args)
{
new PagingExample().run(args);
}
public boolean runExample() throws Exception
{
Connection connection = null;
InitialContext initialContext = null;
try
{
// Step 1. Create an initial context to perform the JNDI lookup.
initialContext = getContext(0);
// Step 2. Perform a lookup on the Connection Factory
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
// Step 3. We look-up the JMS queue object from JNDI. pagingQueue is configured to hold a very limited number
// of bytes in memory
Queue pageQueue = (Queue)initialContext.lookup("/queue/pagingQueue");
// Step 4. Lookup for a JMS Queue
Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue");
// Step 5. Create a JMS Connection
connection = cf.createConnection();
// Step 6. Create a JMS Session
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
// Step 7. Create a JMS Message Producer for pageQueueAddress
MessageProducer pageMessageProducer = session.createProducer(pageQueue);
// Step 8. We don't need persistent messages in order to use paging. (This step is optional)
pageMessageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Step 9. Create a Binary Bytes Message with 10K arbitrary bytes
BytesMessage message = session.createBytesMessage();
message.writeBytes(new byte[10 * 1024]);
// Step 10. Send only 20 messages to the Queue. This will be already enough for pagingQueue. Look at
// ./paging/config/jbm-queues.xml for the config.
for (int i = 0; i < 20; i++)
{
pageMessageProducer.send(message);
}
// Step 11. Create a JMS Message Producer
MessageProducer messageProducer = session.createProducer(queue);
// Step 12. We don't need persistent messages in order to use paging. (This step is optional)
messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Step 13. Send the message for about 30K, which should be over the memory limit imposed by the server
for (int i = 0; i < 30000; i++)
{
messageProducer.send(message);
}
// Step 14. if you pause this example here, you will see several files under ./build/data/paging
// Thread.sleep(30000); // if you want to just our of curiosity, you can sleep here and inspect the created
// files just for
// Step 15. Create a JMS Message Consumer
MessageConsumer messageConsumer = session.createConsumer(queue);
// Step 16. Start the JMS Connection. This step will activate the subscribers to receive messages.
connection.start();
// Step 17. Receive the messages. It's important to ACK for messages as JBM will not read messages from paging
// until messages are ACKed
for (int i = 0; i < 30000; i++)
{
message = (BytesMessage)messageConsumer.receive(3000);
- if (i % 1000 == 0)
+ if (i % 100 == 0)
{
System.out.println("Received " + i + " messages");
message.acknowledge();
}
}
message.acknowledge();
// Step 18. Receive the messages from the Queue names pageQueue. Create the proper consumer for that
messageConsumer.close();
messageConsumer = session.createConsumer(pageQueue);
for (int i = 0; i < 20; i++)
{
message = (BytesMessage)messageConsumer.receive(1000);
System.out.println("Received message " + i + " from pageQueue");
message.acknowledge();
}
return true;
}
finally
{
// And finally, always remember to close your JMS connections after use, in a finally block. Closing a JMS
// connection will automatically close all of its sessions, consumers, producer and browser objects
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}
}
}
| true | true | public boolean runExample() throws Exception
{
Connection connection = null;
InitialContext initialContext = null;
try
{
// Step 1. Create an initial context to perform the JNDI lookup.
initialContext = getContext(0);
// Step 2. Perform a lookup on the Connection Factory
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
// Step 3. We look-up the JMS queue object from JNDI. pagingQueue is configured to hold a very limited number
// of bytes in memory
Queue pageQueue = (Queue)initialContext.lookup("/queue/pagingQueue");
// Step 4. Lookup for a JMS Queue
Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue");
// Step 5. Create a JMS Connection
connection = cf.createConnection();
// Step 6. Create a JMS Session
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
// Step 7. Create a JMS Message Producer for pageQueueAddress
MessageProducer pageMessageProducer = session.createProducer(pageQueue);
// Step 8. We don't need persistent messages in order to use paging. (This step is optional)
pageMessageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Step 9. Create a Binary Bytes Message with 10K arbitrary bytes
BytesMessage message = session.createBytesMessage();
message.writeBytes(new byte[10 * 1024]);
// Step 10. Send only 20 messages to the Queue. This will be already enough for pagingQueue. Look at
// ./paging/config/jbm-queues.xml for the config.
for (int i = 0; i < 20; i++)
{
pageMessageProducer.send(message);
}
// Step 11. Create a JMS Message Producer
MessageProducer messageProducer = session.createProducer(queue);
// Step 12. We don't need persistent messages in order to use paging. (This step is optional)
messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Step 13. Send the message for about 30K, which should be over the memory limit imposed by the server
for (int i = 0; i < 30000; i++)
{
messageProducer.send(message);
}
// Step 14. if you pause this example here, you will see several files under ./build/data/paging
// Thread.sleep(30000); // if you want to just our of curiosity, you can sleep here and inspect the created
// files just for
// Step 15. Create a JMS Message Consumer
MessageConsumer messageConsumer = session.createConsumer(queue);
// Step 16. Start the JMS Connection. This step will activate the subscribers to receive messages.
connection.start();
// Step 17. Receive the messages. It's important to ACK for messages as JBM will not read messages from paging
// until messages are ACKed
for (int i = 0; i < 30000; i++)
{
message = (BytesMessage)messageConsumer.receive(3000);
if (i % 1000 == 0)
{
System.out.println("Received " + i + " messages");
message.acknowledge();
}
}
message.acknowledge();
// Step 18. Receive the messages from the Queue names pageQueue. Create the proper consumer for that
messageConsumer.close();
messageConsumer = session.createConsumer(pageQueue);
for (int i = 0; i < 20; i++)
{
message = (BytesMessage)messageConsumer.receive(1000);
System.out.println("Received message " + i + " from pageQueue");
message.acknowledge();
}
return true;
}
finally
{
// And finally, always remember to close your JMS connections after use, in a finally block. Closing a JMS
// connection will automatically close all of its sessions, consumers, producer and browser objects
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}
}
| public boolean runExample() throws Exception
{
Connection connection = null;
InitialContext initialContext = null;
try
{
// Step 1. Create an initial context to perform the JNDI lookup.
initialContext = getContext(0);
// Step 2. Perform a lookup on the Connection Factory
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
// Step 3. We look-up the JMS queue object from JNDI. pagingQueue is configured to hold a very limited number
// of bytes in memory
Queue pageQueue = (Queue)initialContext.lookup("/queue/pagingQueue");
// Step 4. Lookup for a JMS Queue
Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue");
// Step 5. Create a JMS Connection
connection = cf.createConnection();
// Step 6. Create a JMS Session
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
// Step 7. Create a JMS Message Producer for pageQueueAddress
MessageProducer pageMessageProducer = session.createProducer(pageQueue);
// Step 8. We don't need persistent messages in order to use paging. (This step is optional)
pageMessageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Step 9. Create a Binary Bytes Message with 10K arbitrary bytes
BytesMessage message = session.createBytesMessage();
message.writeBytes(new byte[10 * 1024]);
// Step 10. Send only 20 messages to the Queue. This will be already enough for pagingQueue. Look at
// ./paging/config/jbm-queues.xml for the config.
for (int i = 0; i < 20; i++)
{
pageMessageProducer.send(message);
}
// Step 11. Create a JMS Message Producer
MessageProducer messageProducer = session.createProducer(queue);
// Step 12. We don't need persistent messages in order to use paging. (This step is optional)
messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
// Step 13. Send the message for about 30K, which should be over the memory limit imposed by the server
for (int i = 0; i < 30000; i++)
{
messageProducer.send(message);
}
// Step 14. if you pause this example here, you will see several files under ./build/data/paging
// Thread.sleep(30000); // if you want to just our of curiosity, you can sleep here and inspect the created
// files just for
// Step 15. Create a JMS Message Consumer
MessageConsumer messageConsumer = session.createConsumer(queue);
// Step 16. Start the JMS Connection. This step will activate the subscribers to receive messages.
connection.start();
// Step 17. Receive the messages. It's important to ACK for messages as JBM will not read messages from paging
// until messages are ACKed
for (int i = 0; i < 30000; i++)
{
message = (BytesMessage)messageConsumer.receive(3000);
if (i % 100 == 0)
{
System.out.println("Received " + i + " messages");
message.acknowledge();
}
}
message.acknowledge();
// Step 18. Receive the messages from the Queue names pageQueue. Create the proper consumer for that
messageConsumer.close();
messageConsumer = session.createConsumer(pageQueue);
for (int i = 0; i < 20; i++)
{
message = (BytesMessage)messageConsumer.receive(1000);
System.out.println("Received message " + i + " from pageQueue");
message.acknowledge();
}
return true;
}
finally
{
// And finally, always remember to close your JMS connections after use, in a finally block. Closing a JMS
// connection will automatically close all of its sessions, consumers, producer and browser objects
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}
}
|
diff --git a/src/com/example/forestgame/gameinterface/Respawn.java b/src/com/example/forestgame/gameinterface/Respawn.java
index 31c5175..f778752 100644
--- a/src/com/example/forestgame/gameinterface/Respawn.java
+++ b/src/com/example/forestgame/gameinterface/Respawn.java
@@ -1,146 +1,146 @@
package com.example.forestgame.gameinterface;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.TextureRegion;
import android.util.Log;
import com.example.forestgame.GameScene;
import com.example.forestgame.MainActivity;
import com.example.forestgame.SlotMatrix;
import com.example.forestgame.element.Element;
import com.example.forestgame.element.TableOfElements;
public class Respawn {
private boolean isEmpty;
private Element element;
private GameScene gameScene;
TextureRegion respawnTexture;
Sprite respawnSprite;
TextureRegion movingTexture;
Sprite movingSprite;
public Respawn(GameScene scene) {
gameScene = scene;
generateElement();
}
public void generateElement() {
element = TableOfElements.getRandomElement();
isEmpty = false;
show();
}
public boolean isEmpty() {
return isEmpty;
}
public Element getElement() {
return element;
}
public void setElement(Element e)
{
element = e;
}
public void clear() {
element = null;
isEmpty = true;
show();
}
//For Animation
public void backToRespawn(Element e)
{
respawnSprite.setPosition(MainActivity.TEXTURE_WIDTH * 27 / 50, MainActivity.TEXTURE_HEIGHT * 1381 / 2000);
}
public void show() {
if(!isEmpty) {
respawnTexture = MainActivity.mainActivity.storage.getTexture(TableOfElements
. getTextureName
( element));
respawnSprite = new Sprite ( MainActivity.TEXTURE_WIDTH * 27 / 50
, MainActivity.TEXTURE_HEIGHT * 1381 / 2000
, MainActivity.TEXTURE_WIDTH * 61 / 250
, MainActivity.TEXTURE_HEIGHT * 303 / 2000
, respawnTexture
, MainActivity.mainActivity.getVertexBufferObjectManager()){
int row = 8;
int colum = 8;
@Override
public boolean onAreaTouched( TouchEvent pSceneTouchEvent
, float pTouchAreaLocalX
, float pTouchAreaLocalY) {
if (pSceneTouchEvent.isActionDown()) {
row = 8;
colum = 8;
Log.d("resp", "touch");
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
} else if (pSceneTouchEvent.isActionUp()) {
Log.d("resp", "no touch");
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
if (colum == 7 && row == 7 && gameScene.prison.isEmpty()) {
Log.d("resp", "newprison");
gameScene.prison.addElement(element);
clear();
generateElement();
}
else if (row < 6 && colum < 6 && gameScene.getSlotMatrix().isSlotEmpty(row, colum)){
Log.d("resp", "newSlot");
gameScene.getSlotMatrix().putToSlot(element, row, colum);
clear();
generateElement();
}
else {
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
Log.d("resp","nowhere");
backToRespawn(element);
}
} else if (pSceneTouchEvent.isActionMove()) {
Log.d("resp", "move");
float touchX = pSceneTouchEvent.getX() - this.getWidth() / 2;
float touchY = pSceneTouchEvent.getY() - this.getHeight() / 2;
this.setPosition(touchX, touchY - this.getHeight() / 2);
gameScene.moveElement(touchX, touchY);
colum = gameScene.getPutInColum();
row = gameScene.getPutInRow();
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
}
return true;
}
};
gameScene.attachChild(respawnSprite);
gameScene.registerTouchArea(respawnSprite);
gameScene.setTouchAreaBindingOnActionDownEnabled(true);
gameScene.setTouchAreaBindingOnActionMoveEnabled(true);
- respawnSprite.setZIndex(300);
+ respawnSprite.setZIndex(400);
respawnSprite.getParent().sortChildren();
}
else gameScene.detachChild(respawnSprite);
}
}
| true | true | public void show() {
if(!isEmpty) {
respawnTexture = MainActivity.mainActivity.storage.getTexture(TableOfElements
. getTextureName
( element));
respawnSprite = new Sprite ( MainActivity.TEXTURE_WIDTH * 27 / 50
, MainActivity.TEXTURE_HEIGHT * 1381 / 2000
, MainActivity.TEXTURE_WIDTH * 61 / 250
, MainActivity.TEXTURE_HEIGHT * 303 / 2000
, respawnTexture
, MainActivity.mainActivity.getVertexBufferObjectManager()){
int row = 8;
int colum = 8;
@Override
public boolean onAreaTouched( TouchEvent pSceneTouchEvent
, float pTouchAreaLocalX
, float pTouchAreaLocalY) {
if (pSceneTouchEvent.isActionDown()) {
row = 8;
colum = 8;
Log.d("resp", "touch");
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
} else if (pSceneTouchEvent.isActionUp()) {
Log.d("resp", "no touch");
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
if (colum == 7 && row == 7 && gameScene.prison.isEmpty()) {
Log.d("resp", "newprison");
gameScene.prison.addElement(element);
clear();
generateElement();
}
else if (row < 6 && colum < 6 && gameScene.getSlotMatrix().isSlotEmpty(row, colum)){
Log.d("resp", "newSlot");
gameScene.getSlotMatrix().putToSlot(element, row, colum);
clear();
generateElement();
}
else {
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
Log.d("resp","nowhere");
backToRespawn(element);
}
} else if (pSceneTouchEvent.isActionMove()) {
Log.d("resp", "move");
float touchX = pSceneTouchEvent.getX() - this.getWidth() / 2;
float touchY = pSceneTouchEvent.getY() - this.getHeight() / 2;
this.setPosition(touchX, touchY - this.getHeight() / 2);
gameScene.moveElement(touchX, touchY);
colum = gameScene.getPutInColum();
row = gameScene.getPutInRow();
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
}
return true;
}
};
gameScene.attachChild(respawnSprite);
gameScene.registerTouchArea(respawnSprite);
gameScene.setTouchAreaBindingOnActionDownEnabled(true);
gameScene.setTouchAreaBindingOnActionMoveEnabled(true);
respawnSprite.setZIndex(300);
respawnSprite.getParent().sortChildren();
}
else gameScene.detachChild(respawnSprite);
}
| public void show() {
if(!isEmpty) {
respawnTexture = MainActivity.mainActivity.storage.getTexture(TableOfElements
. getTextureName
( element));
respawnSprite = new Sprite ( MainActivity.TEXTURE_WIDTH * 27 / 50
, MainActivity.TEXTURE_HEIGHT * 1381 / 2000
, MainActivity.TEXTURE_WIDTH * 61 / 250
, MainActivity.TEXTURE_HEIGHT * 303 / 2000
, respawnTexture
, MainActivity.mainActivity.getVertexBufferObjectManager()){
int row = 8;
int colum = 8;
@Override
public boolean onAreaTouched( TouchEvent pSceneTouchEvent
, float pTouchAreaLocalX
, float pTouchAreaLocalY) {
if (pSceneTouchEvent.isActionDown()) {
row = 8;
colum = 8;
Log.d("resp", "touch");
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
} else if (pSceneTouchEvent.isActionUp()) {
Log.d("resp", "no touch");
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
if (colum == 7 && row == 7 && gameScene.prison.isEmpty()) {
Log.d("resp", "newprison");
gameScene.prison.addElement(element);
clear();
generateElement();
}
else if (row < 6 && colum < 6 && gameScene.getSlotMatrix().isSlotEmpty(row, colum)){
Log.d("resp", "newSlot");
gameScene.getSlotMatrix().putToSlot(element, row, colum);
clear();
generateElement();
}
else {
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
Log.d("resp","nowhere");
backToRespawn(element);
}
} else if (pSceneTouchEvent.isActionMove()) {
Log.d("resp", "move");
float touchX = pSceneTouchEvent.getX() - this.getWidth() / 2;
float touchY = pSceneTouchEvent.getY() - this.getHeight() / 2;
this.setPosition(touchX, touchY - this.getHeight() / 2);
gameScene.moveElement(touchX, touchY);
colum = gameScene.getPutInColum();
row = gameScene.getPutInRow();
Log.d("resp", Integer.toString(row));
Log.d("resp", Integer.toString(colum));
}
return true;
}
};
gameScene.attachChild(respawnSprite);
gameScene.registerTouchArea(respawnSprite);
gameScene.setTouchAreaBindingOnActionDownEnabled(true);
gameScene.setTouchAreaBindingOnActionMoveEnabled(true);
respawnSprite.setZIndex(400);
respawnSprite.getParent().sortChildren();
}
else gameScene.detachChild(respawnSprite);
}
|
diff --git a/libraries/javalib/java/lang/ClassLoader.java b/libraries/javalib/java/lang/ClassLoader.java
index d0b762251..8252bba63 100644
--- a/libraries/javalib/java/lang/ClassLoader.java
+++ b/libraries/javalib/java/lang/ClassLoader.java
@@ -1,242 +1,244 @@
/*
* Java core library component.
*
* Copyright (c) 1997, 1998
* Transvirtual Technologies, Inc. All rights reserved.
*
* See the file "license.terms" for information on usage and redistribution
* of this file.
*/
package java.lang;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Vector;
import kaffe.lang.SystemClassLoader;
public abstract class ClassLoader {
/**
* To prevent any classes from being gc'd before we are gc'd, we keep them
* in this hashtable. The contents of this table correspond to entries
* in the VM-internal class entry pool. This table only contains classes
* for which we are the defining loader (ie, not classes for which we are
* merely the initiating loader).
*/
private final Hashtable loadedClasses = new Hashtable();
private ProtectionDomain defaultProtectionDomain;
private final ClassLoader parent;
protected ClassLoader() {
this(getSystemClassLoader());
}
protected ClassLoader(ClassLoader parent) {
System.getSecurityManager().checkCreateClassLoader();
this.parent = parent;
}
public Class loadClass(String name) throws ClassNotFoundException {
return (loadClass(name, false));
}
protected Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c;
// Search for class...
search: {
// First, see if already loaded by this class
if ((c = findLoadedClass(name)) != null) {
break search;
}
// Second, try the parent class loader
try {
if (parent != null) {
c = parent.loadClass(name, resolve);
+ break search;
} else if (this != getSystemClassLoader()) {
c = getSystemClassLoader()
.loadClass(name, resolve);
+ break search;
}
- break search;
- } catch (ClassNotFoundException e) { }
+ } catch (ClassNotFoundException e) {
+ }
// Third, try findClass()
if ((c = findClass(name)) == null) {
throw new ClassNotFoundException(name);
}
}
// Now, optionally resolve the class
if (resolve) {
resolveClass(c);
}
return (c);
}
protected Class findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
/**
* @deprecated
*/
protected final Class defineClass(byte data[], int off, int len)
throws ClassFormatError {
return (defineClass(null, data, off, len));
}
protected final Class defineClass(String name, byte data[], int off, int len)
throws ClassFormatError {
if (defaultProtectionDomain == null) {
// XXX FIXME..
defaultProtectionDomain = new ProtectionDomain(null, null);
}
return defineClass(name, data, off, len, defaultProtectionDomain);
}
protected final Class defineClass(String name, byte data[], int off,
int len, ProtectionDomain pd) throws ClassFormatError {
if (off < 0 || len < 0 || off + len > data.length) {
throw new IndexOutOfBoundsException();
}
Class clazz = defineClass0(name, data, off, len);
if (name != null) {
loadedClasses.put(name, clazz);
}
else {
loadedClasses.put(clazz.getName(), clazz);
}
return (clazz);
}
protected final void resolveClass(Class c) {
resolveClass0(c);
}
protected final Class findSystemClass(String name)
throws ClassNotFoundException {
return getSystemClassLoader().findClass(name);
}
public final ClassLoader getParent() {
return parent;
}
protected final void setSigners(Class cl, Object signers[]) {
throw new kaffe.util.NotImplemented(getClass().getName()
+ ".setSigners()");
}
protected final Class findLoadedClass(String name) {
return findLoadedClass0(name);
}
public URL getResource(String name) {
try {
return (URL)getResources(name).nextElement();
} catch (IOException e) {
} catch (NoSuchElementException e) {
}
return null;
}
public final Enumeration getResources(String name) throws IOException {
Vector v = new Vector();
ClassLoader p;
if (parent != null) {
p = parent;
} else if (this != getSystemClassLoader()) {
p = getSystemClassLoader();
} else {
p = null;
}
if (p != null) {
for (Enumeration e = p.getResources(name);
e.hasMoreElements(); )
v.addElement(e.nextElement());
}
for (Enumeration e = findResources(name); e.hasMoreElements(); )
v.addElement(e.nextElement());
return v.elements();
}
protected Enumeration findResources(String name) throws IOException {
return new Vector().elements(); // ie, an empty Enumeration
}
protected URL findResource(String name) {
try {
return (URL)findResources(name).nextElement();
} catch (IOException e) {
} catch (NoSuchElementException e) {
}
return null;
}
public static URL getSystemResource(String name) {
return getSystemClassLoader().getResource(name);
}
public static Enumeration getSystemResources(String name) throws IOException {
return getSystemClassLoader().getResources(name);
}
public InputStream getResourceAsStream(String name) {
URL url = getResource(name);
if (url != null) {
try {
return url.openStream();
} catch (IOException e) {
}
}
return null;
}
public static InputStream getSystemResourceAsStream(String name) {
return getSystemClassLoader().getResourceAsStream(name);
}
public static ClassLoader getSystemClassLoader() {
return SystemClassLoader.getClassLoader();
}
protected Package definePackage(String name, String specTitle,
String specVersion, String specVendor, String implTitle,
String implVersion, String implVendor, URL sealBase)
throws IllegalArgumentException {
throw new kaffe.util.NotImplemented(getClass().getName()
+ ".definePackage()");
}
protected Package getPackage(String name) {
throw new kaffe.util.NotImplemented(getClass().getName()
+ ".getPackage()");
}
protected Package[] getPackages() {
throw new kaffe.util.NotImplemented(getClass().getName()
+ ".getPackages()");
}
protected String findLibrary(String libname) {
return null;
}
private native Class defineClass0(String name, byte data[], int off, int len);
private native Class findLoadedClass0(String name);
private native void resolveClass0(Class cls);
}
| false | true | protected Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c;
// Search for class...
search: {
// First, see if already loaded by this class
if ((c = findLoadedClass(name)) != null) {
break search;
}
// Second, try the parent class loader
try {
if (parent != null) {
c = parent.loadClass(name, resolve);
} else if (this != getSystemClassLoader()) {
c = getSystemClassLoader()
.loadClass(name, resolve);
}
break search;
} catch (ClassNotFoundException e) { }
// Third, try findClass()
if ((c = findClass(name)) == null) {
throw new ClassNotFoundException(name);
}
}
// Now, optionally resolve the class
if (resolve) {
resolveClass(c);
}
return (c);
}
| protected Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c;
// Search for class...
search: {
// First, see if already loaded by this class
if ((c = findLoadedClass(name)) != null) {
break search;
}
// Second, try the parent class loader
try {
if (parent != null) {
c = parent.loadClass(name, resolve);
break search;
} else if (this != getSystemClassLoader()) {
c = getSystemClassLoader()
.loadClass(name, resolve);
break search;
}
} catch (ClassNotFoundException e) {
}
// Third, try findClass()
if ((c = findClass(name)) == null) {
throw new ClassNotFoundException(name);
}
}
// Now, optionally resolve the class
if (resolve) {
resolveClass(c);
}
return (c);
}
|
diff --git a/src/com/madhackerdesigns/neverbelate/ui/WarningDialog.java b/src/com/madhackerdesigns/neverbelate/ui/WarningDialog.java
index e8d795f..8fe0b75 100644
--- a/src/com/madhackerdesigns/neverbelate/ui/WarningDialog.java
+++ b/src/com/madhackerdesigns/neverbelate/ui/WarningDialog.java
@@ -1,667 +1,670 @@
/**
*
*/
package com.madhackerdesigns.neverbelate.ui;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.madhackerdesigns.neverbelate.R;
import com.madhackerdesigns.neverbelate.provider.AlertsContract;
import com.madhackerdesigns.neverbelate.provider.AlertsHelper;
import com.madhackerdesigns.neverbelate.service.NeverBeLateService;
import com.madhackerdesigns.neverbelate.service.ServiceCommander;
import com.madhackerdesigns.neverbelate.service.WakefulServiceReceiver;
import com.madhackerdesigns.neverbelate.settings.PreferenceHelper;
import com.madhackerdesigns.neverbelate.ui.UserLocationOverlay.OnLocationChangedListener;
import com.madhackerdesigns.neverbelate.util.AdHelper;
import com.madhackerdesigns.neverbelate.util.Logger;
/**
* @author flintinatux
*
*/
public class WarningDialog extends MapActivity implements ServiceCommander {
// private static tokens
private static final int ALERT_TOKEN = 1;
private static final String LOG_TAG = "NeverBeLateWarning";
private static final boolean ADMOB = true;
// static strings for intent stuff
private static final String PACKAGE_NAME = "com.madhackerdesigns.neverbelate";
public static final String EXTRA_URI = PACKAGE_NAME + ".uri";
private static final String MAPS_URL = "http://maps.google.com/maps";
// static strings for view tags
private static final String TAG_ALERT_LIST = "alert_list";
private static final String TAG_TRAFFIC_VIEW = "traffic_view";
// Dialog id's
private static final int DLG_NAV = 0;
// fields to hold shared preferences and ad stuff
private AdHelper mAdHelper;
// private IAdManager mAdManager;
private boolean mAdJustShown = false;
private PreferenceHelper mPrefs;
// other fields
private AlertQueryHandler mHandler;
private ArrayList<EventHolder> mEventHolders = new ArrayList<EventHolder>();
private List<String> mDestList = new ArrayList<String>();
private boolean mInsistentStopped = false;
private MapView mMapView;
private ViewSwitcher mSwitcher;
private UserLocationOverlay mUserLocationOverlay;
// fields for handling locations
private ArrayList<OverlayItem> mDest = new ArrayList<OverlayItem>();
private OnLocationChangedListener mListener;
private GeoPoint mOrig;
/* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.warning_dialog);
setTitle(R.string.advance_warning_title);
Logger.d(LOG_TAG, "Title is set.");
// Load the preferences and Pontiflex IAdManager
Context applicationContext = getApplicationContext();
mAdHelper = new AdHelper(applicationContext);
// mAdManager = AdManagerFactory.createInstance(getApplication());
mPrefs = new PreferenceHelper(applicationContext);
// Grab the view switcher, inflate and add the departure window and traffic views
ViewSwitcher switcher = (ViewSwitcher) findViewById(R.id.view_switcher);
View alertListView = View.inflate(this, R.layout.alert_list_view, null);
View trafficView = View.inflate(this, R.layout.traffic_view_layout, null);
alertListView.setTag(TAG_ALERT_LIST);
trafficView.setTag(TAG_TRAFFIC_VIEW);
switcher.addView(alertListView);
switcher.addView(trafficView);
mSwitcher = switcher;
Logger.d(LOG_TAG, "ViewSwitcher loaded.");
// Enable the user location to the map (early, to feed the location to the AdMob banner)
if (mMapView == null) { mMapView = (MapView) findViewById(R.id.mapview); }
mUserLocationOverlay = new UserLocationOverlay(this, mMapView);
boolean providersEnabled = mUserLocationOverlay.enableMyLocation();
if (providersEnabled) {
Logger.d(LOG_TAG, "User location updates enabled.");
}
// Adjust the warning text to include early arrival if set
final Long earlyArrival = mPrefs.getEarlyArrival() / 60000;
if (!earlyArrival.equals(new Long(0))) {
final TextView tv_warningText = (TextView) findViewById(R.id.warning_text);
final Resources res = getResources();
String warningText = res.getString(R.string.warning_text);
String onTime = res.getString(R.string.on_time);
String minutesEarly = res.getString(R.string.minutes_early);
warningText = warningText.replaceFirst(onTime, earlyArrival + " " + minutesEarly);
tv_warningText.setText(warningText);
}
// Load up the list of alerts
loadAlertList();
// Set the "View Traffic" button action
Button trafficButton = (Button) findViewById(R.id.traffic_button);
trafficButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Switch to the traffic view and setup the MapView
Logger.d(LOG_TAG, "'View Traffic' button clicked, switching to traffic view...");
stopInsistentAlarm();
loadTrafficView();
}
});
Logger.d(LOG_TAG, "Traffic button added.");
// Load up an AdMob banner
if (ADMOB) {
AdRequest request = new AdRequest();
if (providersEnabled) { request.setLocation(mUserLocationOverlay.getLastFix()); }
AdView adView = (AdView) findViewById(R.id.ad_view);
adView.loadAd(request);
Logger.d(LOG_TAG, "AdMob banner loaded.");
}
mUserLocationOverlay.disableMyLocation();
}
private void loadAlertList() {
// Query the AlertProvider for alerts that are fired, but not dismissed
ContentResolver cr = getContentResolver();
if (mHandler == null) { mHandler = new AlertQueryHandler(cr); }
Uri contentUri = AlertsContract.Alerts.CONTENT_URI;
String[] projection = AlertsHelper.ALERT_PROJECTION;
String selection =
AlertsContract.Alerts.FIRED + "=? AND " +
AlertsContract.Alerts.DISMISSED + "=?";
String[] selectionArgs = new String[] { "1", "0" };
mHandler.startQuery(ALERT_TOKEN, getApplicationContext(),
contentUri, projection, selection, selectionArgs, null);
Logger.d(LOG_TAG, "AlertProvider queried for alerts.");
}
private class AlertQueryHandler extends AsyncQueryHandler {
public AlertQueryHandler(ContentResolver cr) {
super(cr);
}
/* (non-Javadoc)
* @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
*/
@SuppressWarnings("deprecation")
@Override
protected void onQueryComplete(int token, Object context, Cursor cursor) {
// Let the activity manage the cursor life-cycle
startManagingCursor(cursor);
Logger.d(LOG_TAG, "Query returned...");
// Now fill in the content of the WarningDialog
switch (token) {
case ALERT_TOKEN:
if (cursor.moveToFirst()) {
- // Store away the event information
- EventHolder eh = new EventHolder();
- eh.json = cursor.getString(AlertsHelper.PROJ_JSON);
- eh.title = cursor.getString(AlertsHelper.PROJ_TITLE);
- eh.location = cursor.getString(AlertsHelper.PROJ_LOCATION);
- mEventHolders.add(eh);
+ do {
+ // Store away the event information
+ EventHolder eh = new EventHolder();
+ eh.json = cursor.getString(AlertsHelper.PROJ_JSON);
+ eh.title = cursor.getString(AlertsHelper.PROJ_TITLE);
+ eh.location = cursor.getString(AlertsHelper.PROJ_LOCATION);
+ mEventHolders.add(eh);
+ } while (cursor.moveToNext());
// Calculate the departure window. Note that first row in cursor should be
// the first upcoming event instance, since it is sorted by begin time, ascending.
+ cursor.moveToFirst();
long begin = cursor.getLong(AlertsHelper.PROJ_BEGIN);
long duration = cursor.getLong(AlertsHelper.PROJ_DURATION);
TextView departureWindow = (TextView) findViewById(R.id.departure_window);
long departureTime = begin - duration;
long now = new Date().getTime();
Resources res = getResources();
String unitMinutes = res.getString(R.string.unit_minutes);
String departureString;
if (departureTime > now) {
departureString = "in " + (int)((departureTime - now) / 60000 + 1)
+ " " + unitMinutes + "!";
} else {
departureString = "NOW!";
}
departureWindow.setText(departureString);
departureWindow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
// Load the copyrights
Set<String> copyrights = new HashSet<String>();
do {
copyrights.add(cursor.getString(AlertsHelper.PROJ_COPYRIGHTS));
} while (cursor.moveToNext());
String copyrightString = "";
TextView copyrightText = (TextView) findViewById(R.id.copyright_text);
copyrightText.setText(copyrightString);
// Attach the cursor to the alert list view
cursor.moveToFirst();
EventListAdapter adapter = new EventListAdapter((Context) context,
R.layout.event_list_item, cursor, true);
ListView lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
} else {
// TODO: Do something else safe. This really shouldn't happen, though.
}
}
// Set the "Snooze" button label
Resources res = getResources();
Button snoozeButton = (Button) findViewById(R.id.snooze_button);
int count = cursor.getCount();
if (count > 1) {
snoozeButton.setText(res.getString(R.string.snooze_all_button_text));
} else {
snoozeButton.setText(res.getString(R.string.snooze_button_text));
}
// Enable or disable snooze per user preference
if (mPrefs.getEarlyArrival().equals(new Long(0))) {
snoozeButton.setVisibility(View.GONE);
Logger.d(LOG_TAG, "Snooze button disabled.");
} else {
snoozeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Snooze the alert, and finish the activity
snoozeAlert();
finish();
}
});
Logger.d(LOG_TAG, "Snooze button added.");
}
// Set the "Dismiss" button action
Button dismissButton = (Button) findViewById(R.id.dismiss_button);
if (count > 1) {
dismissButton.setText(res.getString(R.string.dismiss_all_button_text));
} else {
dismissButton.setText(res.getString(R.string.dismiss_button_text));
}
dismissButton.setOnClickListener(new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
// For now, to dismiss, cancel notification and finish
dismissAlert();
finish();
}
});
Logger.d(LOG_TAG, "Dismiss button loaded.");
}
}
/**
*
*/
private void snoozeAlert() {
// With respect to ads, consider a SNOOZE as a DISMISS
mAdHelper.setWarningDismissed(true);
// Set a new alarm to notify for this same event instance
Logger.d(LOG_TAG, "'Snooze' button clicked.");
long now = new Date().getTime();
long warnTime = now + mPrefs.getSnoozeDuration();
String warnTimeString = NeverBeLateService.FullDateTime(warnTime);
Logger.d(LOG_TAG, "Alarm will be set to warn user again at " + warnTimeString);
Context context = getApplicationContext();
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, WakefulServiceReceiver.class);
intent.putExtra(EXTRA_SERVICE_COMMAND, NOTIFY);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarm.set(AlarmManager.RTC_WAKEUP, warnTime, alarmIntent);
// Ask the Service to just SNOOZE the event, which just clears the notification
intent = new Intent(context, NeverBeLateService.class);
intent.putExtra(EXTRA_SERVICE_COMMAND, SNOOZE);
startService(intent);
}
/**
*
*/
private void dismissAlert() {
// Tell the AdHelper that this warning has been dismissed
mAdHelper.setWarningDismissed(true);
// Ask the Service to just DISMISS the alert, which marks the alert as DISMISSED. Duh.
Context context = getApplicationContext();
Intent cancelIntent = new Intent(context, NeverBeLateService.class);
cancelIntent.putExtra(EXTRA_SERVICE_COMMAND, DISMISS);
startService(cancelIntent);
}
private void stopInsistentAlarm() {
Logger.d(LOG_TAG, "Stopping insistent alarm.");
if (!mInsistentStopped) {
mInsistentStopped = true;
Context context = getApplicationContext();
Intent i = new Intent(context, NeverBeLateService.class);
i.putExtra(EXTRA_SERVICE_COMMAND, SILENCE);
startService(i);
}
}
private void switchToAlertListView() {
mSwitcher.showPrevious();
Logger.d(LOG_TAG, "Switched to alert list view.");
}
private void switchToTrafficView() {
mSwitcher.showNext();
Logger.d(LOG_TAG, "Switched to traffic view.");
}
/**
*
*/
private void loadTrafficView() {
// Log a little
Logger.d(LOG_TAG, "Loading traffic view.");
// Get mapview and add zoom controls
MapView mapView = mMapView;
if (mapView != null) { Logger.d(LOG_TAG, "MapView loaded."); }
mapView.setBuiltInZoomControls(true);
// Turn on the traffic (as early as possible)
mapView.setTraffic(true);
// Add the Back button action
Button backButton = (Button) findViewById(R.id.back_button);
backButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switchToAlertListView();
mUserLocationOverlay.disableMyLocation();
mUserLocationOverlay.disableCompass();
}
});
// Add the Navigate button
Button btnNav = (Button) findViewById(R.id.btn_nav);
btnNav.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ArrayList<EventHolder> eventHolders = mEventHolders;
if (eventHolders.size() == 1) {
// If only one event location, immediately send intent
startNavigation(eventHolders.get(0).location);
} else if (eventHolders.size() >= 2) {
// If two or more locations, ask user to choose first
showDialog(DLG_NAV);
}
}
});
// Get the UserLocationOverlay to draw both flags and stay updated
UserLocationOverlay overlay = mUserLocationOverlay;
// Parse the json directions data
final Iterator<EventHolder> eventIterator = mEventHolders.iterator();
do {
try {
// Get the next EventHolder
EventHolder eh = eventIterator.next();
// Get the zoom span and zoom center from the route
JSONObject directions = new JSONObject(eh.json);
JSONObject route = directions.getJSONArray("routes").getJSONObject(0);
// If the origin is null, pull the origin coordinates
JSONObject leg = route.getJSONArray("legs").getJSONObject(0);
if (mOrig == null) {
int latOrigE6 = (int) (1.0E6 * leg.getJSONObject("start_location").getDouble("lat"));
int lonOrigE6 = (int) (1.0E6 * leg.getJSONObject("start_location").getDouble("lng"));
mOrig = new GeoPoint(latOrigE6, lonOrigE6);
}
// Get the destination coordinates from the leg
int latDestE6 = (int) (1.0E6 * leg.getJSONObject("end_location").getDouble("lat"));
int lonDestE6 = (int) (1.0E6 * leg.getJSONObject("end_location").getDouble("lng"));
// Create a GeoPoint for the destination and push onto MapOverlay
GeoPoint destPoint = new GeoPoint(latDestE6, lonDestE6);
mDest.add(new OverlayItem(destPoint, eh.title, eh.location));
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} while (eventIterator.hasNext());
// Create and store new OnLocationChangedListener
if (mListener == null) {
mListener = new UserLocationOverlay.OnLocationChangedListener() {
public void onLocationChanged(Location location) {
// If we are ready, then draw the locations
if (mDest.size() > 0 && mOrig != null) {
drawLocations(location);
}
}
};
}
// Set the listener and draw the initial locations
overlay.setOnLocationChangedListener(mListener);
mListener.onLocationChanged(null);
overlay.enableMyLocation();
overlay.enableCompass();
// // Load an interstitial ad if it's time
// AdHelper adHelper = mAdHelper;
// if (adHelper.isTimeToShowAd()) {
// adHelper.setAdShown(true);
// mAdJustShown = true;
//// mAdManager.showAd();
// mAdManager.startMultiOfferActivity();
// } else {
// Otherwise, switch to the traffic view
switchToTrafficView();
// }
}
public void drawLocations(Location current) {
final MapView mapView = mMapView;
// Use origin point if current is null
GeoPoint userLoc;
if (current != null) {
int lat = (int) (1.0E6 * current.getLatitude());
int lon = (int) (1.0E6 * current.getLongitude());
userLoc = new GeoPoint(lat, lon);
} else {
userLoc = mOrig;
}
// Add the user location to the map bounds
MapBounds bounds = new MapBounds();
bounds.addPoint(userLoc.getLatitudeE6(), userLoc.getLongitudeE6());
// Create an overlay with a blue flag for the user location
Drawable blueDrawable = getResources().getDrawable(R.drawable.flag_blue);
MapOverlay blueOverlay = new MapOverlay(this, blueDrawable);
blueOverlay.addOverlay(new OverlayItem(userLoc, null, null));
// Add the blue overlay
List<Overlay> mapOverlays = mapView.getOverlays();
mapOverlays.clear();
mapOverlays.add(blueOverlay);
// Always rebuild red overlay to get the bounds correct
Drawable redDrawable = getResources().getDrawable(R.drawable.flag_red);
MapOverlay redOverlay = new MapOverlay(this, redDrawable);
final Iterator<OverlayItem> destIterator = mDest.iterator();
do {
OverlayItem item = destIterator.next();
redOverlay.addOverlay(item);
GeoPoint dest = item.getPoint();
bounds.addPoint(dest.getLatitudeE6(), dest.getLongitudeE6());
} while (destIterator.hasNext());
mapOverlays.add(redOverlay);
// Get map controller, animate to zoom center, and set zoom span
final MapController mapController = mapView.getController();
GeoPoint zoomCenter = new GeoPoint(bounds.getLatCenterE6(), bounds.getLonCenterE6());
mapController.animateTo(zoomCenter);
mapController.zoomToSpan(bounds.getLatSpanE6(), bounds.getLonSpanE6());
}
private void startNavigation(String dest) {
Uri.Builder b = Uri.parse(MAPS_URL).buildUpon();
b.appendQueryParameter("daddr", dest);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, b.build());
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
}
/* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Context context = getApplicationContext();
switch (id) {
case DLG_NAV:
for (EventHolder eh : mEventHolders) {
mDestList.add(eh.location);
}
builder.setTitle(R.string.dlg_nav_title)
.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, mDestList),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Pull out the selected destination and send nav intent
startNavigation(mDestList.get(which));
}
});
break;
}
return builder.create();
}
/* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
// Disable the user location
if (mUserLocationOverlay != null) {
mUserLocationOverlay.disableMyLocation();
mUserLocationOverlay.disableCompass();
}
}
/* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
// Re-enable the user location
if (mUserLocationOverlay != null &&
((String) mSwitcher.getCurrentView().getTag()).equals(TAG_TRAFFIC_VIEW)) {
mUserLocationOverlay.enableMyLocation();
mUserLocationOverlay.enableCompass();
}
// Switch to the traffic view if an ad was just shown
if (mAdJustShown) {
switchToTrafficView();
mAdJustShown = false;
}
}
@Override
protected boolean isRouteDisplayed() {
// No route will be displayed, since that would cover up the traffic
return false;
}
private class EventHolder {
String json;
String title;
String location;
}
private class MapBounds {
private int mLatMinE6 = 0;
private int mLatMaxE6 = 0;
private int mLonMinE6 = 0;
private int mLonMaxE6 = 0;
private static final double RATIO = 1.25;
protected MapBounds() {
super();
}
protected void addPoint(int latE6, int lonE6) {
// Check if this latitude is the minimum
if (mLatMinE6 == 0 || latE6 < mLatMinE6) { mLatMinE6 = latE6; }
// Check if this latitude is the maximum
if (mLatMaxE6 == 0 || latE6 > mLatMaxE6) { mLatMaxE6 = latE6; }
// Check if this longitude is the minimum
if (mLonMinE6 == 0 || lonE6 < mLonMinE6) { mLonMinE6 = lonE6; }
// Check if this longitude is the maximum
if (mLonMaxE6 == 0 || lonE6 > mLonMaxE6) { mLonMaxE6 = lonE6; }
}
protected int getLatSpanE6() {
return (int) Math.abs(RATIO * (mLatMaxE6 - mLatMinE6));
}
protected int getLonSpanE6() {
return (int) Math.abs(RATIO * (mLonMaxE6 - mLonMinE6));
}
protected int getLatCenterE6() {
return (int) (mLatMaxE6 + mLatMinE6)/2;
}
protected int getLonCenterE6() {
return (int) (mLonMaxE6 + mLonMinE6)/2;
}
}
}
| false | true | protected void onQueryComplete(int token, Object context, Cursor cursor) {
// Let the activity manage the cursor life-cycle
startManagingCursor(cursor);
Logger.d(LOG_TAG, "Query returned...");
// Now fill in the content of the WarningDialog
switch (token) {
case ALERT_TOKEN:
if (cursor.moveToFirst()) {
// Store away the event information
EventHolder eh = new EventHolder();
eh.json = cursor.getString(AlertsHelper.PROJ_JSON);
eh.title = cursor.getString(AlertsHelper.PROJ_TITLE);
eh.location = cursor.getString(AlertsHelper.PROJ_LOCATION);
mEventHolders.add(eh);
// Calculate the departure window. Note that first row in cursor should be
// the first upcoming event instance, since it is sorted by begin time, ascending.
long begin = cursor.getLong(AlertsHelper.PROJ_BEGIN);
long duration = cursor.getLong(AlertsHelper.PROJ_DURATION);
TextView departureWindow = (TextView) findViewById(R.id.departure_window);
long departureTime = begin - duration;
long now = new Date().getTime();
Resources res = getResources();
String unitMinutes = res.getString(R.string.unit_minutes);
String departureString;
if (departureTime > now) {
departureString = "in " + (int)((departureTime - now) / 60000 + 1)
+ " " + unitMinutes + "!";
} else {
departureString = "NOW!";
}
departureWindow.setText(departureString);
departureWindow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
// Load the copyrights
Set<String> copyrights = new HashSet<String>();
do {
copyrights.add(cursor.getString(AlertsHelper.PROJ_COPYRIGHTS));
} while (cursor.moveToNext());
String copyrightString = "";
TextView copyrightText = (TextView) findViewById(R.id.copyright_text);
copyrightText.setText(copyrightString);
// Attach the cursor to the alert list view
cursor.moveToFirst();
EventListAdapter adapter = new EventListAdapter((Context) context,
R.layout.event_list_item, cursor, true);
ListView lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
} else {
// TODO: Do something else safe. This really shouldn't happen, though.
}
}
// Set the "Snooze" button label
Resources res = getResources();
Button snoozeButton = (Button) findViewById(R.id.snooze_button);
int count = cursor.getCount();
if (count > 1) {
snoozeButton.setText(res.getString(R.string.snooze_all_button_text));
} else {
snoozeButton.setText(res.getString(R.string.snooze_button_text));
}
// Enable or disable snooze per user preference
if (mPrefs.getEarlyArrival().equals(new Long(0))) {
snoozeButton.setVisibility(View.GONE);
Logger.d(LOG_TAG, "Snooze button disabled.");
} else {
snoozeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Snooze the alert, and finish the activity
snoozeAlert();
finish();
}
});
Logger.d(LOG_TAG, "Snooze button added.");
}
// Set the "Dismiss" button action
Button dismissButton = (Button) findViewById(R.id.dismiss_button);
if (count > 1) {
dismissButton.setText(res.getString(R.string.dismiss_all_button_text));
} else {
dismissButton.setText(res.getString(R.string.dismiss_button_text));
}
dismissButton.setOnClickListener(new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
// For now, to dismiss, cancel notification and finish
dismissAlert();
finish();
}
});
Logger.d(LOG_TAG, "Dismiss button loaded.");
}
| protected void onQueryComplete(int token, Object context, Cursor cursor) {
// Let the activity manage the cursor life-cycle
startManagingCursor(cursor);
Logger.d(LOG_TAG, "Query returned...");
// Now fill in the content of the WarningDialog
switch (token) {
case ALERT_TOKEN:
if (cursor.moveToFirst()) {
do {
// Store away the event information
EventHolder eh = new EventHolder();
eh.json = cursor.getString(AlertsHelper.PROJ_JSON);
eh.title = cursor.getString(AlertsHelper.PROJ_TITLE);
eh.location = cursor.getString(AlertsHelper.PROJ_LOCATION);
mEventHolders.add(eh);
} while (cursor.moveToNext());
// Calculate the departure window. Note that first row in cursor should be
// the first upcoming event instance, since it is sorted by begin time, ascending.
cursor.moveToFirst();
long begin = cursor.getLong(AlertsHelper.PROJ_BEGIN);
long duration = cursor.getLong(AlertsHelper.PROJ_DURATION);
TextView departureWindow = (TextView) findViewById(R.id.departure_window);
long departureTime = begin - duration;
long now = new Date().getTime();
Resources res = getResources();
String unitMinutes = res.getString(R.string.unit_minutes);
String departureString;
if (departureTime > now) {
departureString = "in " + (int)((departureTime - now) / 60000 + 1)
+ " " + unitMinutes + "!";
} else {
departureString = "NOW!";
}
departureWindow.setText(departureString);
departureWindow.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
// Load the copyrights
Set<String> copyrights = new HashSet<String>();
do {
copyrights.add(cursor.getString(AlertsHelper.PROJ_COPYRIGHTS));
} while (cursor.moveToNext());
String copyrightString = "";
TextView copyrightText = (TextView) findViewById(R.id.copyright_text);
copyrightText.setText(copyrightString);
// Attach the cursor to the alert list view
cursor.moveToFirst();
EventListAdapter adapter = new EventListAdapter((Context) context,
R.layout.event_list_item, cursor, true);
ListView lv = (ListView) findViewById(R.id.list_view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// Stop insistent alarm
stopInsistentAlarm();
}
});
} else {
// TODO: Do something else safe. This really shouldn't happen, though.
}
}
// Set the "Snooze" button label
Resources res = getResources();
Button snoozeButton = (Button) findViewById(R.id.snooze_button);
int count = cursor.getCount();
if (count > 1) {
snoozeButton.setText(res.getString(R.string.snooze_all_button_text));
} else {
snoozeButton.setText(res.getString(R.string.snooze_button_text));
}
// Enable or disable snooze per user preference
if (mPrefs.getEarlyArrival().equals(new Long(0))) {
snoozeButton.setVisibility(View.GONE);
Logger.d(LOG_TAG, "Snooze button disabled.");
} else {
snoozeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Snooze the alert, and finish the activity
snoozeAlert();
finish();
}
});
Logger.d(LOG_TAG, "Snooze button added.");
}
// Set the "Dismiss" button action
Button dismissButton = (Button) findViewById(R.id.dismiss_button);
if (count > 1) {
dismissButton.setText(res.getString(R.string.dismiss_all_button_text));
} else {
dismissButton.setText(res.getString(R.string.dismiss_button_text));
}
dismissButton.setOnClickListener(new OnClickListener() {
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
// For now, to dismiss, cancel notification and finish
dismissAlert();
finish();
}
});
Logger.d(LOG_TAG, "Dismiss button loaded.");
}
|
diff --git a/src/java/org/jivesoftware/sparkimpl/preference/sounds/SoundPreference.java b/src/java/org/jivesoftware/sparkimpl/preference/sounds/SoundPreference.java
index 09030f2f..d9729170 100644
--- a/src/java/org/jivesoftware/sparkimpl/preference/sounds/SoundPreference.java
+++ b/src/java/org/jivesoftware/sparkimpl/preference/sounds/SoundPreference.java
@@ -1,320 +1,320 @@
/**
* $Revision: $
* $Date: $
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Lesser Public License (LGPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.sparkimpl.preference.sounds;
import com.thoughtworks.xstream.XStream;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.spark.preference.Preference;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.WindowsFileSystemView;
import org.jivesoftware.spark.util.log.Log;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* Preferences to handle Sounds played within Spark.
*
* @author Derek DeMoro
*/
public class SoundPreference implements Preference {
private XStream xstream = new XStream();
private SoundPreferences preferences;
private SoundPanel soundPanel;
public static String NAMESPACE = "Sounds";
public SoundPreference() {
xstream.alias("sounds", SoundPreferences.class);
}
public String getTitle() {
return "Sound Preferences";
}
public Icon getIcon() {
return SparkRes.getImageIcon(SparkRes.SOUND_PREFERENCES_IMAGE);
}
public String getTooltip() {
return "Sounds";
}
public String getListName() {
return "Sounds";
}
public String getNamespace() {
return NAMESPACE;
}
public JComponent getGUI() {
if (soundPanel == null) {
soundPanel = new SoundPanel();
}
return soundPanel;
}
public void loadFromFile() {
if (preferences != null) {
return;
}
if (!getSoundSettingsFile().exists()) {
preferences = new SoundPreferences();
}
else {
// Do Initial Load from FileSystem.
File settingsFile = getSoundSettingsFile();
try {
FileReader reader = new FileReader(settingsFile);
preferences = (SoundPreferences)xstream.fromXML(reader);
}
catch (Exception e) {
Log.error("Error loading Sound Preferences.", e);
preferences = new SoundPreferences();
}
}
}
public void load() {
if (soundPanel == null) {
soundPanel = new SoundPanel();
}
SwingWorker worker = new SwingWorker() {
public Object construct() {
loadFromFile();
return preferences;
}
public void finished() {
// Set default settings
soundPanel.setIncomingMessageSound(preferences.getIncomingSound());
soundPanel.playIncomingSound(preferences.isPlayIncomingSound());
soundPanel.setOutgoingMessageSound(preferences.getOutgoingSound());
soundPanel.playOutgoingSound(preferences.isPlayOutgoingSound());
soundPanel.setOfflineSound(preferences.getOfflineSound());
soundPanel.playOfflineSound(preferences.isPlayOfflineSound());
}
};
worker.start();
}
public void commit() {
preferences.setIncomingSound(soundPanel.getIncomingSound());
preferences.setOutgoingSound(soundPanel.getOutgoingSound());
preferences.setOfflineSound(soundPanel.getOfflineSound());
preferences.setPlayIncomingSound(soundPanel.playIncomingSound());
preferences.setPlayOutgoingSound(soundPanel.playOutgoingSound());
preferences.setPlayOfflineSound(soundPanel.playOfflineSound());
saveSoundsFile();
}
public boolean isDataValid() {
return true;
}
public String getErrorMessage() {
return null;
}
public Object getData() {
return null;
}
private class SoundPanel extends JPanel {
final JCheckBox incomingMessageBox = new JCheckBox();
final JTextField incomingMessageSound = new JTextField();
final JButton incomingBrowseButton = new JButton();
final JCheckBox outgoingMessageBox = new JCheckBox();
final JTextField outgoingMessageSound = new JTextField();
final JButton outgoingBrowseButton = new JButton();
final JCheckBox userOfflineCheckbox = new JCheckBox();
final JTextField userOfflineField = new JTextField();
final JButton offlineBrowseButton = new JButton();
private JFileChooser fc;
public SoundPanel() {
setLayout(new GridBagLayout());
// Add ResourceUtils
- ResourceUtils.resButton(incomingMessageBox, "&Play sound when new message arrives");
- ResourceUtils.resButton(outgoingMessageBox, "&Play sound when a message is sent");
- ResourceUtils.resButton(userOfflineCheckbox, "&Play sound when user goes offline");
+ ResourceUtils.resButton(incomingMessageBox, "Play sound when new message &arrives");
+ ResourceUtils.resButton(outgoingMessageBox, "Play sound when a message is &sent");
+ ResourceUtils.resButton(userOfflineCheckbox, "Play sound when user goes &offline");
ResourceUtils.resButton(incomingBrowseButton, "&Browse");
ResourceUtils.resButton(outgoingBrowseButton, "B&rowse");
ResourceUtils.resButton(offlineBrowseButton, "Br&owse");
// Handle incoming sounds
add(incomingMessageBox, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(incomingMessageSound, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(incomingBrowseButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle sending sounds
add(outgoingMessageBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingMessageSound, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingBrowseButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle User Online Sound
add(userOfflineCheckbox, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(userOfflineField, new GridBagConstraints(0, 5, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(offlineBrowseButton, new GridBagConstraints(1, 5, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
incomingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Incoming Sound File", incomingMessageSound);
}
});
outgoingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Outgoing Sound File", outgoingMessageSound);
}
});
offlineBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Offline Sound File", userOfflineField);
}
});
}
public void setIncomingMessageSound(String path) {
incomingMessageSound.setText(path);
}
public void setOutgoingMessageSound(String path) {
outgoingMessageSound.setText(path);
}
public void setOfflineSound(String path) {
userOfflineField.setText(path);
}
public void playIncomingSound(boolean play) {
incomingMessageBox.setSelected(play);
}
public void playOutgoingSound(boolean play) {
outgoingMessageBox.setSelected(play);
}
public void playOfflineSound(boolean play) {
userOfflineCheckbox.setSelected(play);
}
public String getIncomingSound() {
return incomingMessageSound.getText();
}
public boolean playIncomingSound() {
return incomingMessageBox.isSelected();
}
public boolean playOutgoingSound() {
return outgoingMessageBox.isSelected();
}
public String getOutgoingSound() {
return outgoingMessageSound.getText();
}
public boolean playOfflineSound() {
return userOfflineCheckbox.isSelected();
}
public String getOfflineSound() {
return userOfflineField.getText();
}
private void pickFile(String title, JTextField field) {
if (fc == null) {
fc = new JFileChooser();
if (Spark.isWindows()) {
fc.setFileSystemView(new WindowsFileSystemView());
}
}
fc.setDialogTitle(title);
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
field.setText(file.getAbsolutePath());
}
else {
}
}
}
private File getSoundSettingsFile() {
File file = new File(Spark.getUserHome(), "Spark");
if (!file.exists()) {
file.mkdirs();
}
return new File(file, "sound-settings.xml");
}
private void saveSoundsFile() {
try {
FileWriter writer = new FileWriter(getSoundSettingsFile());
xstream.toXML(preferences, writer);
}
catch (Exception e) {
Log.error("Error saving sound settings.", e);
}
}
public SoundPreferences getPreferences() {
if (preferences == null) {
load();
}
return preferences;
}
public void shutdown() {
}
}
| true | true | public SoundPanel() {
setLayout(new GridBagLayout());
// Add ResourceUtils
ResourceUtils.resButton(incomingMessageBox, "&Play sound when new message arrives");
ResourceUtils.resButton(outgoingMessageBox, "&Play sound when a message is sent");
ResourceUtils.resButton(userOfflineCheckbox, "&Play sound when user goes offline");
ResourceUtils.resButton(incomingBrowseButton, "&Browse");
ResourceUtils.resButton(outgoingBrowseButton, "B&rowse");
ResourceUtils.resButton(offlineBrowseButton, "Br&owse");
// Handle incoming sounds
add(incomingMessageBox, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(incomingMessageSound, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(incomingBrowseButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle sending sounds
add(outgoingMessageBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingMessageSound, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingBrowseButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle User Online Sound
add(userOfflineCheckbox, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(userOfflineField, new GridBagConstraints(0, 5, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(offlineBrowseButton, new GridBagConstraints(1, 5, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
incomingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Incoming Sound File", incomingMessageSound);
}
});
outgoingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Outgoing Sound File", outgoingMessageSound);
}
});
offlineBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Offline Sound File", userOfflineField);
}
});
}
| public SoundPanel() {
setLayout(new GridBagLayout());
// Add ResourceUtils
ResourceUtils.resButton(incomingMessageBox, "Play sound when new message &arrives");
ResourceUtils.resButton(outgoingMessageBox, "Play sound when a message is &sent");
ResourceUtils.resButton(userOfflineCheckbox, "Play sound when user goes &offline");
ResourceUtils.resButton(incomingBrowseButton, "&Browse");
ResourceUtils.resButton(outgoingBrowseButton, "B&rowse");
ResourceUtils.resButton(offlineBrowseButton, "Br&owse");
// Handle incoming sounds
add(incomingMessageBox, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(incomingMessageSound, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(incomingBrowseButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle sending sounds
add(outgoingMessageBox, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingMessageSound, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(outgoingBrowseButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Handle User Online Sound
add(userOfflineCheckbox, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
add(userOfflineField, new GridBagConstraints(0, 5, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
add(offlineBrowseButton, new GridBagConstraints(1, 5, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
incomingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Incoming Sound File", incomingMessageSound);
}
});
outgoingBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Outgoing Sound File", outgoingMessageSound);
}
});
offlineBrowseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pickFile("Choose Offline Sound File", userOfflineField);
}
});
}
|
diff --git a/kernel/src/tests/org/jboss/test/kernel/config/support/CustomCollection.java b/kernel/src/tests/org/jboss/test/kernel/config/support/CustomCollection.java
index 8a9bbc84..c688337b 100644
--- a/kernel/src/tests/org/jboss/test/kernel/config/support/CustomCollection.java
+++ b/kernel/src/tests/org/jboss/test/kernel/config/support/CustomCollection.java
@@ -1,54 +1,54 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.kernel.config.support;
import java.util.ArrayList;
/**
* A CustomCollection.
*
* @author <a href="[email protected]">Adrian Brock</a>
* @version $Revision$
*/
public class CustomCollection extends ArrayList
{
/** The serialVersionUID */
private static final long serialVersionUID = 3762538897183683896L;
/** Whether the collection was pre instantited */
private boolean preInstantiated;
public CustomCollection()
{
- this.preInstantiated = true;
+ this.preInstantiated = false;
}
public CustomCollection(boolean preInstantiated)
{
this.preInstantiated = preInstantiated;
}
public boolean getPreInstantiated()
{
return preInstantiated;
}
}
| true | true | public CustomCollection()
{
this.preInstantiated = true;
}
| public CustomCollection()
{
this.preInstantiated = false;
}
|
diff --git a/s4-core/src/test/java/io/s4/ft/CheckpointingTest.java b/s4-core/src/test/java/io/s4/ft/CheckpointingTest.java
index 17c497e..3304893 100644
--- a/s4-core/src/test/java/io/s4/ft/CheckpointingTest.java
+++ b/s4-core/src/test/java/io/s4/ft/CheckpointingTest.java
@@ -1,120 +1,120 @@
package io.s4.ft;
import io.s4.serialize.KryoSerDeser;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import junit.framework.Assert;
import org.apache.commons.codec.binary.Base64;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.NIOServerCnxn.Factory;
import org.junit.Test;
import com.esotericsoftware.reflectasm.FieldAccess;
public class CheckpointingTest extends S4TestCase {
private static boolean delete;
public static File DEFAULT_TEST_OUTPUT_DIR = new File(
System.getProperty("user.dir") + File.separator + "tmp");
public static File DEFAULT_STORAGE_DIR = new File(
DEFAULT_TEST_OUTPUT_DIR.getAbsolutePath() + File.separator
+ "storage");
// TODO add timeout
@Test
public void testCheckpointStorage() throws Exception {
Factory zookeeperServerConnectionFactory = null;
try {
zookeeperServerConnectionFactory = TestUtils
.startZookeeperServer();
final ZooKeeper zk = TestUtils.createZkClient();
try {
// FIXME can't figure out where this is retained
zk.delete("/value1Set", -1);
} catch (Exception ignored) {
}
try {
// FIXME can't figure out where this is retained
zk.delete("/value2Set", -1);
} catch (Exception ignored) {
}
try {
// FIXME can't figure out where this is retained
zk.delete("/checkpointed", -1);
} catch (Exception ignored) {
}
// 0. cleanup storage dir
if (DEFAULT_STORAGE_DIR.exists()) {
TestUtils.deleteDirectoryContents(DEFAULT_STORAGE_DIR);
}
DEFAULT_STORAGE_DIR.mkdirs();
// 1. instantiate S4 app
initializeS4App(getClass());
// 2. generate a simple event that creates and changes the state of
// the
// PE
// NOTE: coordinate through zookeeper
final CountDownLatch signalValue1Set = new CountDownLatch(1);
TestUtils.watchAndSignalCreation("/value1Set", signalValue1Set, zk);
EventGenerator gen = new EventGenerator();
gen.injectValueEvent(new KeyValue("value1", "message1"), "Stream1",
0);
signalValue1Set.await();
StatefulTestPE pe = (StatefulTestPE) S4TestCase.registeredPEs
.get(new SafeKeeperId("Stream1", "statefulPE",
StatefulTestPE.class.getName(), null));
Assert.assertEquals("message1", pe.getValue1());
Assert.assertEquals("", pe.getValue2());
// 3. generate a checkpoint event
final CountDownLatch signalCheckpointed = new CountDownLatch(1);
TestUtils.watchAndSignalCreation("/checkpointed",
signalCheckpointed, zk);
pe.initiateCheckpoint();
signalCheckpointed.await();
SafeKeeperId safeKeeperId = pe.getSafeKeeperId();
File expected = new File(System.getProperty("user.dir")
+ File.separator
+ "tmp"
+ File.separator
+ "storage"
+ File.separator
+ safeKeeperId.getPrototypeId()
+ File.separator
- + Base64.encodeBase64String(safeKeeperId
+ + Base64.encodeBase64URLSafeString(safeKeeperId
.getStringRepresentation().getBytes()));
// 4. verify that state was correctly persisted
Assert.assertTrue(expected.exists());
StatefulTestPE refPE = new StatefulTestPE();
refPE.setValue1("message1");
refPE.setId("statefulPE");
KryoSerDeser kryoSerDeser = new KryoSerDeser();
byte[] refBytes = kryoSerDeser.serialize(refPE);
Assert.assertTrue(Arrays.equals(refBytes,
TestUtils.readFileAsByteArray(expected)));
} finally {
TestUtils.stopZookeeperServer(zookeeperServerConnectionFactory);
}
}
}
| true | true | public void testCheckpointStorage() throws Exception {
Factory zookeeperServerConnectionFactory = null;
try {
zookeeperServerConnectionFactory = TestUtils
.startZookeeperServer();
final ZooKeeper zk = TestUtils.createZkClient();
try {
// FIXME can't figure out where this is retained
zk.delete("/value1Set", -1);
} catch (Exception ignored) {
}
try {
// FIXME can't figure out where this is retained
zk.delete("/value2Set", -1);
} catch (Exception ignored) {
}
try {
// FIXME can't figure out where this is retained
zk.delete("/checkpointed", -1);
} catch (Exception ignored) {
}
// 0. cleanup storage dir
if (DEFAULT_STORAGE_DIR.exists()) {
TestUtils.deleteDirectoryContents(DEFAULT_STORAGE_DIR);
}
DEFAULT_STORAGE_DIR.mkdirs();
// 1. instantiate S4 app
initializeS4App(getClass());
// 2. generate a simple event that creates and changes the state of
// the
// PE
// NOTE: coordinate through zookeeper
final CountDownLatch signalValue1Set = new CountDownLatch(1);
TestUtils.watchAndSignalCreation("/value1Set", signalValue1Set, zk);
EventGenerator gen = new EventGenerator();
gen.injectValueEvent(new KeyValue("value1", "message1"), "Stream1",
0);
signalValue1Set.await();
StatefulTestPE pe = (StatefulTestPE) S4TestCase.registeredPEs
.get(new SafeKeeperId("Stream1", "statefulPE",
StatefulTestPE.class.getName(), null));
Assert.assertEquals("message1", pe.getValue1());
Assert.assertEquals("", pe.getValue2());
// 3. generate a checkpoint event
final CountDownLatch signalCheckpointed = new CountDownLatch(1);
TestUtils.watchAndSignalCreation("/checkpointed",
signalCheckpointed, zk);
pe.initiateCheckpoint();
signalCheckpointed.await();
SafeKeeperId safeKeeperId = pe.getSafeKeeperId();
File expected = new File(System.getProperty("user.dir")
+ File.separator
+ "tmp"
+ File.separator
+ "storage"
+ File.separator
+ safeKeeperId.getPrototypeId()
+ File.separator
+ Base64.encodeBase64String(safeKeeperId
.getStringRepresentation().getBytes()));
// 4. verify that state was correctly persisted
Assert.assertTrue(expected.exists());
StatefulTestPE refPE = new StatefulTestPE();
refPE.setValue1("message1");
refPE.setId("statefulPE");
KryoSerDeser kryoSerDeser = new KryoSerDeser();
byte[] refBytes = kryoSerDeser.serialize(refPE);
Assert.assertTrue(Arrays.equals(refBytes,
TestUtils.readFileAsByteArray(expected)));
} finally {
TestUtils.stopZookeeperServer(zookeeperServerConnectionFactory);
}
}
| public void testCheckpointStorage() throws Exception {
Factory zookeeperServerConnectionFactory = null;
try {
zookeeperServerConnectionFactory = TestUtils
.startZookeeperServer();
final ZooKeeper zk = TestUtils.createZkClient();
try {
// FIXME can't figure out where this is retained
zk.delete("/value1Set", -1);
} catch (Exception ignored) {
}
try {
// FIXME can't figure out where this is retained
zk.delete("/value2Set", -1);
} catch (Exception ignored) {
}
try {
// FIXME can't figure out where this is retained
zk.delete("/checkpointed", -1);
} catch (Exception ignored) {
}
// 0. cleanup storage dir
if (DEFAULT_STORAGE_DIR.exists()) {
TestUtils.deleteDirectoryContents(DEFAULT_STORAGE_DIR);
}
DEFAULT_STORAGE_DIR.mkdirs();
// 1. instantiate S4 app
initializeS4App(getClass());
// 2. generate a simple event that creates and changes the state of
// the
// PE
// NOTE: coordinate through zookeeper
final CountDownLatch signalValue1Set = new CountDownLatch(1);
TestUtils.watchAndSignalCreation("/value1Set", signalValue1Set, zk);
EventGenerator gen = new EventGenerator();
gen.injectValueEvent(new KeyValue("value1", "message1"), "Stream1",
0);
signalValue1Set.await();
StatefulTestPE pe = (StatefulTestPE) S4TestCase.registeredPEs
.get(new SafeKeeperId("Stream1", "statefulPE",
StatefulTestPE.class.getName(), null));
Assert.assertEquals("message1", pe.getValue1());
Assert.assertEquals("", pe.getValue2());
// 3. generate a checkpoint event
final CountDownLatch signalCheckpointed = new CountDownLatch(1);
TestUtils.watchAndSignalCreation("/checkpointed",
signalCheckpointed, zk);
pe.initiateCheckpoint();
signalCheckpointed.await();
SafeKeeperId safeKeeperId = pe.getSafeKeeperId();
File expected = new File(System.getProperty("user.dir")
+ File.separator
+ "tmp"
+ File.separator
+ "storage"
+ File.separator
+ safeKeeperId.getPrototypeId()
+ File.separator
+ Base64.encodeBase64URLSafeString(safeKeeperId
.getStringRepresentation().getBytes()));
// 4. verify that state was correctly persisted
Assert.assertTrue(expected.exists());
StatefulTestPE refPE = new StatefulTestPE();
refPE.setValue1("message1");
refPE.setId("statefulPE");
KryoSerDeser kryoSerDeser = new KryoSerDeser();
byte[] refBytes = kryoSerDeser.serialize(refPE);
Assert.assertTrue(Arrays.equals(refBytes,
TestUtils.readFileAsByteArray(expected)));
} finally {
TestUtils.stopZookeeperServer(zookeeperServerConnectionFactory);
}
}
|
diff --git a/TeaLeaf/src/com/tealeaf/EventQueue.java b/TeaLeaf/src/com/tealeaf/EventQueue.java
index fd39b06..de6fe96 100644
--- a/TeaLeaf/src/com/tealeaf/EventQueue.java
+++ b/TeaLeaf/src/com/tealeaf/EventQueue.java
@@ -1,61 +1,61 @@
package com.tealeaf;
import java.util.Queue;
import com.tealeaf.event.Event;
public class EventQueue {
private static Queue<String> events = new java.util.concurrent.ConcurrentLinkedQueue<String>();
private static Object lock = new Object();
public static void pushEvent(Event e) {
synchronized (lock) {
events.add(e.pack());
}
}
protected static String popEvent() {
return events.poll();
}
private static String[] getEvents() {
String[] ret;
synchronized (lock) {
ret = new String[events.size()];
events.toArray(ret);
events.clear();
}
return ret;
}
public static void dispatchEvents() {
String[] e = getEvents();
if (e.length > 256) {
String[] batch256 = new String[256];
int ii, len = e.length;
for (ii = 0; ii < len; ii += 256) {
int batchLength = len - ii;
if (batchLength < 256) {
break;
}
System.arraycopy(e, ii, batch256, 0, 256);
NativeShim.dispatchEvents(batch256);
}
- if (ii < len) {
- int batchLength = len - ii;
+ if (len & 255) {
+ int batchLength = len & 255;
String[] batch = new String[batchLength];
- System.arraycopy(e, ii, batch, 0, batchLength);
+ System.arraycopy(e, len & ~255, batch, 0, batchLength);
NativeShim.dispatchEvents(batch);
}
} else {
NativeShim.dispatchEvents(e);
}
}
}
| false | true | public static void dispatchEvents() {
String[] e = getEvents();
if (e.length > 256) {
String[] batch256 = new String[256];
int ii, len = e.length;
for (ii = 0; ii < len; ii += 256) {
int batchLength = len - ii;
if (batchLength < 256) {
break;
}
System.arraycopy(e, ii, batch256, 0, 256);
NativeShim.dispatchEvents(batch256);
}
if (ii < len) {
int batchLength = len - ii;
String[] batch = new String[batchLength];
System.arraycopy(e, ii, batch, 0, batchLength);
NativeShim.dispatchEvents(batch);
}
} else {
NativeShim.dispatchEvents(e);
}
}
| public static void dispatchEvents() {
String[] e = getEvents();
if (e.length > 256) {
String[] batch256 = new String[256];
int ii, len = e.length;
for (ii = 0; ii < len; ii += 256) {
int batchLength = len - ii;
if (batchLength < 256) {
break;
}
System.arraycopy(e, ii, batch256, 0, 256);
NativeShim.dispatchEvents(batch256);
}
if (len & 255) {
int batchLength = len & 255;
String[] batch = new String[batchLength];
System.arraycopy(e, len & ~255, batch, 0, batchLength);
NativeShim.dispatchEvents(batch);
}
} else {
NativeShim.dispatchEvents(e);
}
}
|
diff --git a/src/com/mewin/wgFlyFlag/PlayerListener.java b/src/com/mewin/wgFlyFlag/PlayerListener.java
index 7751c4a..3f5a603 100644
--- a/src/com/mewin/wgFlyFlag/PlayerListener.java
+++ b/src/com/mewin/wgFlyFlag/PlayerListener.java
@@ -1,41 +1,41 @@
/*
* Copyright (C) 2013 mewin<[email protected]>
*
* 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 com.mewin.wgFlyFlag;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
public class PlayerListener implements Listener
{
private WGFlyFlagPlugin plugin;
public PlayerListener(WGFlyFlagPlugin plugin)
{
this.plugin = plugin;
}
public void onEntityDamage(EntityDamageEvent e)
{
if(e.getEntity() instanceof Player)
{
- plugin.lastPvp.put((Player)e.getEntity(), Long.valueOf(System.currentTimeMillis()));
+ plugin.lastPvp.put((Player) e.getEntity(), System.currentTimeMillis());
}
}
}
| true | true | public void onEntityDamage(EntityDamageEvent e)
{
if(e.getEntity() instanceof Player)
{
plugin.lastPvp.put((Player)e.getEntity(), Long.valueOf(System.currentTimeMillis()));
}
}
| public void onEntityDamage(EntityDamageEvent e)
{
if(e.getEntity() instanceof Player)
{
plugin.lastPvp.put((Player) e.getEntity(), System.currentTimeMillis());
}
}
|
diff --git a/src/main/groovy/lang/MetaClass.java b/src/main/groovy/lang/MetaClass.java
index 559299c43..3e2c0d63e 100644
--- a/src/main/groovy/lang/MetaClass.java
+++ b/src/main/groovy/lang/MetaClass.java
@@ -1,935 +1,935 @@
/*
$Id$
Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
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 "groovy" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Codehaus. For written permission,
please contact [email protected].
4. Products derived from this Software may not be called "groovy"
nor may "groovy" appear in their names without prior written
permission of The Codehaus. "groovy" is a registered
trademark of The Codehaus.
5. Due credit should be given to The Codehaus -
http://groovy.codehaus.org/
THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED 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 CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package groovy.lang;
import java.beans.BeanInfo;
import java.beans.EventSetDescriptor;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.CompileUnit;
import org.codehaus.groovy.classgen.CompilerFacade;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.InvokerException;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;
import org.codehaus.groovy.runtime.MethodClosure;
import org.codehaus.groovy.runtime.MethodHelper;
import org.codehaus.groovy.runtime.NoSuchMethodException;
import org.codehaus.groovy.runtime.NoSuchPropertyException;
import org.objectweb.asm.ClassWriter;
/**
* Allows methods to be dynamically added to existing classes at runtime
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @version $Revision$
*/
public class MetaClass {
protected static final Object[] EMPTY_ARRAY = {
};
protected static final Object[] ARRAY_WITH_NULL = { null };
private MetaClassRegistry registry;
private Class theClass;
private ClassNode classNode;
private Map methodIndex = new HashMap();
private Map staticMethodIndex = new HashMap();
private Map newStaticInstanceMethodIndex = new HashMap();
private Map propertyDescriptors = Collections.synchronizedMap(new HashMap());
private Map listeners = new HashMap();
private Method genericGetMethod;
private Method genericSetMethod;
private List constructors;
public MetaClass(MetaClassRegistry registry, Class theClass) throws IntrospectionException {
this.registry = registry;
this.theClass = theClass;
constructors = Arrays.asList(theClass.getDeclaredConstructors());
addMethods(theClass);
// introspect
BeanInfo info = Introspector.getBeanInfo(theClass);
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
for (int i = 0; i < descriptors.length; i++) {
PropertyDescriptor descriptor = descriptors[i];
propertyDescriptors.put(descriptor.getName(), descriptor);
}
EventSetDescriptor[] eventDescriptors = info.getEventSetDescriptors();
for (int i = 0; i < eventDescriptors.length; i++) {
EventSetDescriptor descriptor = eventDescriptors[i];
Method[] listenerMethods = descriptor.getListenerMethods();
for (int j = 0; j < listenerMethods.length; j++) {
Method listenerMethod = listenerMethods[j];
listeners.put(listenerMethod.getName(), descriptor.getAddListenerMethod());
}
}
// now lets see if there are any methods on one of my interfaces
Class[] interfaces = theClass.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
addNewStaticMethodsFrom(interfaces[i]);
}
// lets add all the base class methods
Class c = theClass;
while (true) {
c = c.getSuperclass();
if (c == null) {
break;
}
addNewStaticMethodsFrom(c);
addMethods(c);
}
}
/**
* @return all the normal instance methods avaiable on this class for the given name
*/
public List getMethods(String name) {
List answer = (List) methodIndex.get(name);
if (answer == null) {
return Collections.EMPTY_LIST;
}
return answer;
}
/**
* @return all the normal static methods avaiable on this class for the given name
*/
public List getStaticMethods(String name) {
List answer = (List) staticMethodIndex.get(name);
if (answer == null) {
return Collections.EMPTY_LIST;
}
return answer;
}
/**
* Allows static method definitions to be added to a meta class as if it was an instance
* method
*
* @param method
*/
public void addNewStaticInstanceMethod(Method method) {
String name = method.getName();
List list = (List) newStaticInstanceMethodIndex.get(name);
if (list == null) {
list = new ArrayList();
newStaticInstanceMethodIndex.put(name, list);
}
list.add(method);
}
public Object invokeMethod(Object object, String methodName, Object arguments) {
/*
System.out.println(
"MetaClass: Invoking method on object: " + object + " method: " + methodName + " arguments: " + arguments);
*/
return invokeMethod(object, methodName, asArray(arguments));
}
/**
* Invokes the given method on the object.
*
*/
public Object invokeMethod(Object object, String methodName, Object[] arguments) {
/*
System
.out
.println(
"MetaClass(Object[]) Invoking method on object: "
+ object
+ " method: "
+ methodName
+ " arguments: "
+ InvokerHelper.toString(arguments));
//System.out.println("Type of first arg: " + arguments[0] + " type: " + arguments[0].getClass());
*/
if (object == null) {
throw new InvokerException("Cannot invoke method: " + methodName + " on null object");
}
List methods = getMethods(methodName);
if (!methods.isEmpty()) {
Method method = (Method) chooseMethod(methodName, methods, arguments);
if (method != null) {
return doMethodInvoke(object, method, arguments);
}
}
// lets see if there's a new static method we've added in groovy-land to this class
List newStaticInstanceMethods = getNewStaticInstanceMethods(methodName);
int size = (arguments != null) ? arguments.length : 0;
Object[] staticArguments = new Object[size + 1];
staticArguments[0] = object;
if (size > 0) {
System.arraycopy(arguments, 0, staticArguments, 1, size);
}
Method method = null;
if (!newStaticInstanceMethods.isEmpty()) {
method = (Method) chooseMethod(methodName, newStaticInstanceMethods, staticArguments);
}
if (method == null) {
method = findNewStaticInstanceMethod(methodName, staticArguments);
}
if (method != null) {
return doMethodInvoke(null, method, staticArguments);
}
// lets try a static method then
return invokeStaticMethod(object, methodName, arguments);
}
public Object invokeStaticMethod(Object object, String methodName, Object[] arguments) {
// System.out.println("Calling static method: " + methodName + " on args: " + InvokerHelper.toString(arguments));
List methods = getStaticMethods(methodName);
if (!methods.isEmpty()) {
Method method = (Method) chooseMethod(methodName, methods, arguments);
if (method != null) {
return doMethodInvoke(theClass, method, arguments);
}
}
if (theClass != Class.class) {
try {
return registry.getMetaClass(Class.class).invokeMethod(object, methodName, arguments);
}
catch (InvokerException e) {
// throw our own exception
}
}
throw new NoSuchMethodException(methodName, theClass);
}
public Object invokeConstructor(Object[] arguments) {
Constructor constructor = (Constructor) chooseMethod("<init>", constructors, arguments);
if (constructor != null) {
return doConstructorInvoke(constructor, arguments);
}
throw new InvokerException("Could not find matching constructor for class: " + theClass.getName());
}
/**
* @return the currently registered static methods against this class
*/
public List getNewStaticInstanceMethods(String methodName) {
List newStaticInstanceMethods = (List) newStaticInstanceMethodIndex.get(methodName);
if (newStaticInstanceMethods == null) {
return Collections.EMPTY_LIST;
}
return newStaticInstanceMethods;
}
/**
* @return the given property's value on the object
*/
public Object getProperty(final Object object, final String property) {
PropertyDescriptor descriptor = (PropertyDescriptor) propertyDescriptors.get(property);
if (descriptor != null) {
Method method = descriptor.getReadMethod();
if (method == null) {
throw new InvokerException("Cannot read property: " + property);
}
return doMethodInvoke(object, method, EMPTY_ARRAY);
}
if (genericGetMethod != null) {
Object[] arguments = { property };
Object answer = doMethodInvoke(object, genericGetMethod, arguments);
if (answer != null) {
return answer;
}
}
// is the property the name of a method - in which case return a
// closure
List methods = getMethods(property);
if (!methods.isEmpty()) {
return new MethodClosure(object, property);
}
/** @todo or are we an extensible groovy class? */
if (genericGetMethod != null) {
return null;
}
else {
/** @todo these special cases should be special MetaClasses maybe */
if (object instanceof Class) {
// lets try a static field
return getStaticProperty((Class) object, property);
}
if (object instanceof Collection) {
return DefaultGroovyMethods.get((Collection) object, property);
}
if (object instanceof Object[]) {
return DefaultGroovyMethods.get(Arrays.asList((Object[]) object), property);
}
throw new NoSuchPropertyException(property, theClass);
}
}
/**
* Sets the property value on an object
*/
public void setProperty(Object object, String property, Object newValue) {
PropertyDescriptor descriptor = (PropertyDescriptor) propertyDescriptors.get(property);
if (descriptor != null) {
Method method = descriptor.getWriteMethod();
if (method == null) {
throw new InvokerException("Cannot set read-only property: " + property);
}
Object[] arguments = { newValue };
try {
doMethodInvoke(object, method, arguments);
}
catch (InvokerException e) {
// if the value is a List see if we can construct the value
// from a constructor
if (newValue instanceof List) {
List list = (List) newValue;
int params = list.size();
Constructor[] constructors = descriptor.getPropertyType().getConstructors();
for (int i = 0; i < constructors.length; i++) {
Constructor constructor = constructors[i];
if (constructor.getParameterTypes().length == params) {
//System.out.println("Found constructor: " + constructor);
Object value = doConstructorInvoke(constructor, list.toArray());
doMethodInvoke(object, method, new Object[] { value });
return;
}
}
}
throw e;
}
return;
}
Method addListenerMethod = (Method) listeners.get(property);
if (addListenerMethod != null && newValue instanceof Closure) {
// lets create a dynamic proxy
Object proxy = createListenerProxy(addListenerMethod.getParameterTypes()[0], property, (Closure) newValue);
doMethodInvoke(object, addListenerMethod, new Object[] { proxy });
return;
}
if (genericSetMethod != null) {
Object[] arguments = { property, newValue };
doMethodInvoke(object, genericSetMethod, arguments);
return;
}
/** @todo or are we an extensible class? */
// lets try invoke the set method
String method = "set" + property.substring(0, 1).toUpperCase() + property.substring(1, property.length());
invokeMethod(object, method, new Object[] { newValue });
}
public ClassNode getClassNode() {
if (classNode == null && GroovyObject.class.isAssignableFrom(theClass)) {
// lets try load it from the classpath
String className = theClass.getName();
String groovyFile = className;
int idx = groovyFile.indexOf('$');
if (idx > 0) {
groovyFile = groovyFile.substring(0, idx);
}
groovyFile = groovyFile.replace('.', '/') + ".groovy";
//System.out.println("Attempting to load: " + groovyFile);
URL url = theClass.getClassLoader().getResource(groovyFile);
if (url == null) {
url = Thread.currentThread().getContextClassLoader().getResource(groovyFile);
}
if (url != null) {
try {
InputStream in = url.openStream();
/** @todo there is no CompileUnit in scope so class name
* checking won't work but that mostly affects the bytecode generation
* rather than viewing the AST
*/
CompilerFacade compiler = new CompilerFacade(theClass.getClassLoader(), new CompileUnit()) {
protected void onClass(ClassWriter classWriter, ClassNode classNode) {
if (classNode.getName().equals(theClass.getName())) {
//System.out.println("Found: " + classNode.getName());
MetaClass.this.classNode = classNode;
}
}
};
compiler.parseClass(in, groovyFile);
}
catch (Exception e) {
throw new InvokerException("Exception thrown parsing: " + groovyFile + ". Reason: " + e, e);
}
}
}
return classNode;
}
public String toString() {
return super.toString() + "[" + theClass + "]";
}
// Implementation methods
//-------------------------------------------------------------------------
/**
* Converts the given object into an array; if its an array then just
* cast otherwise wrap it in an array
*/
protected Object[] asArray(Object arguments) {
if (arguments == null) {
return EMPTY_ARRAY;
}
if (arguments instanceof Tuple) {
Tuple tuple = (Tuple) arguments;
return tuple.toArray();
}
if (arguments instanceof Object[]) {
return (Object[]) arguments;
}
else {
return new Object[] { arguments };
}
}
/**
* @param listenerType the interface of the listener to proxy
* @param listenerMethodName the name of the method in the listener API to call the closure on
* @param closure the closure to invoke on the listenerMethodName method invocation
* @return a dynamic proxy which calls the given closure on the given method name
*/
protected Object createListenerProxy(Class listenerType, final String listenerMethodName, final Closure closure) {
InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object object, Method method, Object[] arguments) throws Throwable {
if (listenerMethodName.equals(method.getName())) {
/** @todo hack! */
closure.call(arguments[0]);
}
return null;
}
};
return Proxy.newProxyInstance(listenerType.getClassLoader(), new Class[] { listenerType }, handler);
}
/**
* Adds all the methods declared in the given class to the metaclass
* ignoring any matching methods already defined by a derived class
*
* @param theClass
*/
protected void addMethods(Class theClass) {
Method[] methodArray = theClass.getDeclaredMethods();
for (int i = 0; i < methodArray.length; i++) {
Method method = methodArray[i];
String name = method.getName();
if (isGenericGetMethod(method) && genericGetMethod == null) {
genericGetMethod = method;
}
else if (isGenericSetMethod(method) && genericSetMethod == null) {
genericSetMethod = method;
}
if (MethodHelper.isStatic(method)) {
List list = (List) staticMethodIndex.get(name);
if (list == null) {
list = new ArrayList();
staticMethodIndex.put(name, list);
list.add(method);
}
else {
if (!containsMatchingMethod(list, method)) {
list.add(method);
}
}
}
else {
List list = (List) methodIndex.get(name);
if (list == null) {
list = new ArrayList();
methodIndex.put(name, list);
list.add(method);
}
else {
if (!containsMatchingMethod(list, method)) {
list.add(method);
}
}
}
}
}
/**
* @return true if a method of the same matching prototype was found in the list
*/
protected boolean containsMatchingMethod(List list, Method method) {
for (Iterator iter = list.iterator(); iter.hasNext();) {
Method aMethod = (Method) iter.next();
Class[] params1 = aMethod.getParameterTypes();
Class[] params2 = method.getParameterTypes();
if (params1.length == params2.length) {
boolean matches = true;
for (int i = 0; i < params1.length; i++) {
if (params1[i] != params2[i]) {
matches = false;
break;
}
}
if (matches) {
return true;
}
}
}
return false;
}
/**
* Adds all of the newly defined methods from the given class to this
* metaclass
*
* @param theClass
*/
protected void addNewStaticMethodsFrom(Class theClass) {
MetaClass interfaceMetaClass = registry.getMetaClass(theClass);
Iterator iter = interfaceMetaClass.newStaticInstanceMethodIndex.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String name = (String) entry.getKey();
List values = (List) entry.getValue();
if (values != null) {
// lets add these methods to me
List list = (List) newStaticInstanceMethodIndex.get(name);
if (list == null) {
list = new ArrayList();
newStaticInstanceMethodIndex.put(name, list);
}
list.addAll(values);
}
}
}
/**
* @return the value of the static property of the given class
*/
protected Object getStaticProperty(Class aClass, String property) {
try {
Field field = aClass.getField(property);
if (field != null) {
return field.get(null);
}
}
catch (Exception e) {
throw new InvokerException("Could not evaluate property: " + property, e);
}
throw new InvokerException("No such property: " + property);
}
/**
* Lets walk the base class & interfaces list to see if we can find the method
*/
protected Method findNewStaticInstanceMethod(String methodName, Object[] staticArguments) {
if (theClass.equals(Object.class)) {
return null;
}
MetaClass superClass = registry.getMetaClass(theClass.getSuperclass());
List list = superClass.getNewStaticInstanceMethods(methodName);
if (!list.isEmpty()) {
Method method = (Method) chooseMethod(methodName, list, staticArguments);
if (method != null) {
// lets cache it for next invocation
addNewStaticInstanceMethod(method);
}
return method;
}
return superClass.findNewStaticInstanceMethod(methodName, staticArguments);
}
protected Object doMethodInvoke(Object object, Method method, Object[] argumentArray) {
- //System.out.println("Evaluating method: " + method);
- //System.out.println("on object: " + object + " with arguments: " + InvokerHelper.toString(argumentArray));
- //System.out.println(this.theClass);
+// System.out.println("Evaluating method: " + method);
+// System.out.println("on object: " + object + " with arguments: " + InvokerHelper.toString(argumentArray));
+// System.out.println(this.theClass);
try {
if (registry.useAccessible()) {
method.setAccessible(true);
}
if (argumentArray == null) {
argumentArray = EMPTY_ARRAY;
}
else
if (method.getParameterTypes().length == 1 && argumentArray.length == 0) {
argumentArray = ARRAY_WITH_NULL;
}
return method.invoke(object, argumentArray);
}
catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof Error) {
Error error = (Error) t;
throw error;
}
if (t instanceof RuntimeException) {
RuntimeException runtimeEx = (RuntimeException) t;
throw runtimeEx;
}
throw new InvokerInvocationException(e);
}
catch (IllegalAccessException e) {
throw new InvokerException(
"could not access method: "
+ method
+ " on: "
+ object
+ " with arguments: "
+ InvokerHelper.toString(argumentArray)
+ " reason: "
+ e,
e);
}
catch (Exception e) {
throw new InvokerException(
"failed to invoke method: "
+ method
+ " on: "
+ object
+ " with arguments: "
+ InvokerHelper.toString(argumentArray)
+ " reason: "
+ e,
e);
}
}
protected Object doConstructorInvoke(Constructor constructor, Object[] argumentArray) {
//System.out.println("Evaluating constructor: " + constructor + " with arguments: " + InvokerHelper.toString(argumentArray));
//System.out.println(this.theClass);
try {
return constructor.newInstance(argumentArray);
}
catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof Error) {
Error error = (Error) t;
throw error;
}
if (t instanceof RuntimeException) {
RuntimeException runtimeEx = (RuntimeException) t;
throw runtimeEx;
}
throw new InvokerInvocationException(e);
}
catch (IllegalAccessException e) {
throw new InvokerException(
"could not access constructor: "
+ constructor
+ " with arguments: "
+ InvokerHelper.toString(argumentArray)
+ " reason: "
+ e,
e);
}
catch (Exception e) {
throw new InvokerException(
"failed to invoke constructor: "
+ constructor
+ " with arguments: "
+ InvokerHelper.toString(argumentArray)
+ " reason: "
+ e,
e);
}
}
/**
* Chooses the correct method to use from a list of methods which match by name.
*
* @param methods the possible methods to choose from
* @param arguments the original argument to the method
* @return
*/
protected Object chooseMethod(String methodName, List methods, Object[] arguments) {
int methodCount = methods.size();
if (methodCount <= 0) {
return null;
}
else if (methodCount == 1) {
return methods.get(0);
}
Object answer = null;
if (arguments.length == 1 && arguments[0] == null) {
answer = chooseMostGeneralMethodWith1Param(methods);
}
else if (arguments.length == 0) {
answer = chooseEmptyMethodParams(methods);
}
else {
int size = arguments.length;
List matchingMethods = new ArrayList();
for (Iterator iter = methods.iterator(); iter.hasNext();) {
Object method = iter.next();
Class[] paramTypes = getParameterTypes(method);
if (paramTypes.length == size) {
// lets check the parameter types match
boolean validMethod = true;
for (int i = 0; i < size; i++) {
Object value = arguments[i];
if (!isCompatibleInstance(paramTypes[i], value)) {
validMethod = false;
}
}
if (validMethod) {
matchingMethods.add(method);
}
}
}
if (matchingMethods.isEmpty()) {
return null;
}
else if (matchingMethods.size() == 1) {
return matchingMethods.get(0);
}
return chooseMostSpecificParams(methodName, matchingMethods, arguments);
}
if (answer != null) {
return answer;
}
throw new InvokerException(
"Could not find which method to invoke from this list: "
+ methods
+ " for arguments: "
+ InvokerHelper.toString(arguments));
}
protected Object chooseMostSpecificParams(String name, List matchingMethods, Object[] arguments) {
Object answer = null;
int size = arguments.length;
Class[] mostSpecificTypes = null;
for (Iterator iter = matchingMethods.iterator(); iter.hasNext();) {
Object method = iter.next();
Class[] paramTypes = getParameterTypes(method);
if (answer == null) {
answer = method;
mostSpecificTypes = paramTypes;
}
else {
boolean useThisMethod = false;
for (int i = 0; i < size; i++) {
Class mostSpecificType = mostSpecificTypes[i];
Class type = paramTypes[i];
if (!type.isAssignableFrom(mostSpecificType)) {
useThisMethod = true;
break;
}
}
if (useThisMethod) {
if (size > 1) {
checkForInvalidOverloading(name, mostSpecificTypes, paramTypes);
}
answer = method;
mostSpecificTypes = paramTypes;
}
}
}
return answer;
}
/**
* Checks that one of the parameter types is a superset of the other
* and that the two lists of types don't conflict. e.g.
* foo(String, Object) and foo(Object, String) would conflict if called with
* foo("a", "b").
*
* Note that this method is only called with 2 possible signnatures. i.e. possible
* invalid combinations will already have been filtered out. So if there were
* methods foo(String, Object) and foo(Object, String) then one of these would be
* already filtered out if foo was called as foo(12, "a")
*/
protected void checkForInvalidOverloading(String name, Class[] baseTypes, Class[] derivedTypes) {
for (int i = 0, size = baseTypes.length; i < size; i++) {
Class baseType = baseTypes[i];
Class derivedType = derivedTypes[i];
if (!baseType.isAssignableFrom(derivedType)) {
throw new InvokerException(
"Ambiguous method overloading for method: "
+ name
+ ". Cannot resolve which method to invoke due to overlapping prototypes between: "
+ InvokerHelper.toString(baseTypes)
+ " and: "
+ InvokerHelper.toString(derivedTypes));
}
}
}
protected Class[] getParameterTypes(Object methodOrConstructor) {
if (methodOrConstructor instanceof Method) {
Method method = (Method) methodOrConstructor;
return method.getParameterTypes();
}
if (methodOrConstructor instanceof Constructor) {
Constructor constructor = (Constructor) methodOrConstructor;
return constructor.getParameterTypes();
}
throw new IllegalArgumentException("Must be a Method or Constructor");
}
/**
* @return the method with 1 parameter which takes the most general type of object (e.g. Object)
*/
protected Object chooseMostGeneralMethodWith1Param(List methods) {
// lets look for methods with 1 argument which matches the type of the arguments
Class closestClass = null;
Object answer = null;
for (Iterator iter = methods.iterator(); iter.hasNext();) {
Object method = iter.next();
Class[] paramTypes = getParameterTypes(method);
int paramLength = paramTypes.length;
if (paramLength == 1) {
Class theType = paramTypes[0];
if (closestClass == null || theType.isAssignableFrom(closestClass)) {
closestClass = theType;
answer = method;
}
}
}
return answer;
}
/**
* @return the method with 1 parameter which takes the most general type of object (e.g. Object)
*/
protected Object chooseEmptyMethodParams(List methods) {
for (Iterator iter = methods.iterator(); iter.hasNext();) {
Object method = iter.next();
Class[] paramTypes = getParameterTypes(method);
int paramLength = paramTypes.length;
if (paramLength == 0) {
return method;
}
}
return null;
}
protected boolean isCompatibleInstance(Class type, Object value) {
boolean answer = value == null || type.isInstance(value);
if (!answer) {
if (type.isPrimitive() && value instanceof Number) {
if (type == int.class) {
return value instanceof Integer;
}
else if (type == double.class) {
return value instanceof Double;
}
else if (type == long.class) {
return value instanceof Long;
}
else if (type == float.class) {
return value instanceof Float;
}
else if (type == char.class) {
return value instanceof Character;
}
else if (type == byte.class) {
return value instanceof Byte;
}
else if (type == short.class) {
return value instanceof Short;
}
}
}
return answer;
}
protected boolean isGenericSetMethod(Method method) {
return method.getName().equals("set") && method.getParameterTypes().length == 2;
}
protected boolean isGenericGetMethod(Method method) {
if (method.getName().equals("get")) {
Class[] parameterTypes = method.getParameterTypes();
return parameterTypes.length == 1 && parameterTypes[0] == String.class;
}
return false;
}
}
| true | true | protected Object doMethodInvoke(Object object, Method method, Object[] argumentArray) {
//System.out.println("Evaluating method: " + method);
//System.out.println("on object: " + object + " with arguments: " + InvokerHelper.toString(argumentArray));
//System.out.println(this.theClass);
try {
if (registry.useAccessible()) {
method.setAccessible(true);
}
if (argumentArray == null) {
argumentArray = EMPTY_ARRAY;
}
else
if (method.getParameterTypes().length == 1 && argumentArray.length == 0) {
argumentArray = ARRAY_WITH_NULL;
}
return method.invoke(object, argumentArray);
}
catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof Error) {
Error error = (Error) t;
throw error;
}
if (t instanceof RuntimeException) {
RuntimeException runtimeEx = (RuntimeException) t;
throw runtimeEx;
}
throw new InvokerInvocationException(e);
}
catch (IllegalAccessException e) {
throw new InvokerException(
"could not access method: "
+ method
+ " on: "
+ object
+ " with arguments: "
+ InvokerHelper.toString(argumentArray)
+ " reason: "
+ e,
e);
}
catch (Exception e) {
throw new InvokerException(
"failed to invoke method: "
+ method
+ " on: "
+ object
+ " with arguments: "
+ InvokerHelper.toString(argumentArray)
+ " reason: "
+ e,
e);
}
}
| protected Object doMethodInvoke(Object object, Method method, Object[] argumentArray) {
// System.out.println("Evaluating method: " + method);
// System.out.println("on object: " + object + " with arguments: " + InvokerHelper.toString(argumentArray));
// System.out.println(this.theClass);
try {
if (registry.useAccessible()) {
method.setAccessible(true);
}
if (argumentArray == null) {
argumentArray = EMPTY_ARRAY;
}
else
if (method.getParameterTypes().length == 1 && argumentArray.length == 0) {
argumentArray = ARRAY_WITH_NULL;
}
return method.invoke(object, argumentArray);
}
catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
if (t instanceof Error) {
Error error = (Error) t;
throw error;
}
if (t instanceof RuntimeException) {
RuntimeException runtimeEx = (RuntimeException) t;
throw runtimeEx;
}
throw new InvokerInvocationException(e);
}
catch (IllegalAccessException e) {
throw new InvokerException(
"could not access method: "
+ method
+ " on: "
+ object
+ " with arguments: "
+ InvokerHelper.toString(argumentArray)
+ " reason: "
+ e,
e);
}
catch (Exception e) {
throw new InvokerException(
"failed to invoke method: "
+ method
+ " on: "
+ object
+ " with arguments: "
+ InvokerHelper.toString(argumentArray)
+ " reason: "
+ e,
e);
}
}
|
diff --git a/uk.ac.gda.common/src/gda/util/LibGdaCommon.java b/uk.ac.gda.common/src/gda/util/LibGdaCommon.java
index e827eb7..12a6fcc 100644
--- a/uk.ac.gda.common/src/gda/util/LibGdaCommon.java
+++ b/uk.ac.gda.common/src/gda/util/LibGdaCommon.java
@@ -1,52 +1,52 @@
/*-
* Copyright © 2012 Diamond Light Source Ltd.
*
* This file is part of GDA.
*
* GDA is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 as published by the Free
* Software Foundation.
*
* GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>.
*/
package gda.util;
import org.apache.commons.lang.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LibGdaCommon {
private static final Logger logger = LoggerFactory.getLogger(LibGdaCommon.class);
private static boolean LIBRARY_AVAILABLE = false;
static {
final String libname = "gda_common";
try {
if (SystemUtils.IS_OS_LINUX) {
System.loadLibrary(libname);
LIBRARY_AVAILABLE = true;
}
} catch (Throwable e) {
logger.warn("Couldn't load " + libname + " library", e);
}
}
public static String getFullNameOfUser(String username) {
if (LIBRARY_AVAILABLE) {
return _getFullNameOfUser(username);
}
- return null;
+ return username; // We may well have the right user name originally. (Fix for windows.)
}
private static native String _getFullNameOfUser(String username);
}
| true | true | public static String getFullNameOfUser(String username) {
if (LIBRARY_AVAILABLE) {
return _getFullNameOfUser(username);
}
return null;
}
| public static String getFullNameOfUser(String username) {
if (LIBRARY_AVAILABLE) {
return _getFullNameOfUser(username);
}
return username; // We may well have the right user name originally. (Fix for windows.)
}
|
diff --git a/config/src/main/java/com/typesafe/config/ConfigFactory.java b/config/src/main/java/com/typesafe/config/ConfigFactory.java
index f818a2c..ce8ab19 100644
--- a/config/src/main/java/com/typesafe/config/ConfigFactory.java
+++ b/config/src/main/java/com/typesafe/config/ConfigFactory.java
@@ -1,835 +1,836 @@
/**
* Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com>
*/
package com.typesafe.config;
import java.io.File;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Callable;
import com.typesafe.config.impl.ConfigImpl;
import com.typesafe.config.impl.Parseable;
/**
* Contains static methods for creating {@link Config} instances.
*
* <p>
* See also {@link ConfigValueFactory} which contains static methods for
* converting Java values into a {@link ConfigObject}. You can then convert a
* {@code ConfigObject} into a {@code Config} with {@link ConfigObject#toConfig}.
*
* <p>
* The static methods with "load" in the name do some sort of higher-level
* operation potentially parsing multiple resources and resolving substitutions,
* while the ones with "parse" in the name just create a {@link ConfigValue}
* from a resource and nothing else.
*
* <p> You can find an example app and library <a
* href="https://github.com/typesafehub/config/tree/master/examples">on
* GitHub</a>. Also be sure to read the <a
* href="package-summary.html#package_description">package
* overview</a> which describes the big picture as shown in those
* examples.
*/
public final class ConfigFactory {
private ConfigFactory() {
}
/**
* Loads an application's configuration from the given classpath resource or
* classpath resource basename, sandwiches it between default reference
* config and default overrides, and then resolves it. The classpath
* resource is "raw" (it should have no "/" prefix, and is not made relative
* to any package, so it's like {@link ClassLoader#getResource} not
* {@link Class#getResource}).
*
* <p>
* Resources are loaded from the current thread's
* {@link Thread#getContextClassLoader()}. In general, a library needs its
* configuration to come from the class loader used to load that library, so
* the proper "reference.conf" are present.
*
* <p>
* The loaded object will already be resolved (substitutions have already
* been processed). As a result, if you add more fallbacks then they won't
* be seen by substitutions. Substitutions are the "${foo.bar}" syntax. If
* you want to parse additional files or something then you need to use
* {@link #load(Config)}.
*
* <p>
* To load a standalone resource (without the default reference and default
* overrides), use {@link #parseResourcesAnySyntax(String)} rather than this
* method. To load only the reference config use {@link #defaultReference()}
* and to load only the overrides use {@link #defaultOverrides()}.
*
* @param resourceBasename
* name (optionally without extension) of a resource on classpath
* @return configuration for an application relative to context class loader
*/
public static Config load(String resourceBasename) {
return load(resourceBasename, ConfigParseOptions.defaults(),
ConfigResolveOptions.defaults());
}
/**
* Like {@link #load(String)} but uses the supplied class loader instead of
* the current thread's context class loader.
*
* <p>
* To load a standalone resource (without the default reference and default
* overrides), use {@link #parseResourcesAnySyntax(ClassLoader, String)}
* rather than this method. To load only the reference config use
* {@link #defaultReference(ClassLoader)} and to load only the overrides use
* {@link #defaultOverrides(ClassLoader)}.
*
* @param loader
* @param resourceBasename
* @return configuration for an application relative to given class loader
*/
public static Config load(ClassLoader loader, String resourceBasename) {
return load(resourceBasename, ConfigParseOptions.defaults().setClassLoader(loader),
ConfigResolveOptions.defaults());
}
/**
* Like {@link #load(String)} but allows you to specify parse and resolve
* options.
*
* @param resourceBasename
* the classpath resource name with optional extension
* @param parseOptions
* options to use when parsing the resource
* @param resolveOptions
* options to use when resolving the stack
* @return configuration for an application
*/
public static Config load(String resourceBasename, ConfigParseOptions parseOptions,
ConfigResolveOptions resolveOptions) {
Config appConfig = ConfigFactory.parseResourcesAnySyntax(resourceBasename, parseOptions);
return load(parseOptions.getClassLoader(), appConfig, resolveOptions);
}
/**
* Like {@link #load(String,ConfigParseOptions,ConfigResolveOptions)} but
* has a class loader parameter that overrides any from the
* {@code ConfigParseOptions}.
*
* @param loader
* class loader in which to find resources (overrides loader in
* parse options)
* @param resourceBasename
* the classpath resource name with optional extension
* @param parseOptions
* options to use when parsing the resource (class loader
* overridden)
* @param resolveOptions
* options to use when resolving the stack
* @return configuration for an application
*/
public static Config load(ClassLoader loader, String resourceBasename,
ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) {
return load(resourceBasename, parseOptions.setClassLoader(loader), resolveOptions);
}
/**
* Assembles a standard configuration using a custom <code>Config</code>
* object rather than loading "application.conf". The <code>Config</code>
* object will be sandwiched between the default reference config and
* default overrides and then resolved.
*
* @param config
* the application's portion of the configuration
* @return resolved configuration with overrides and fallbacks added
*/
public static Config load(Config config) {
return load(Thread.currentThread().getContextClassLoader(), config);
}
public static Config load(ClassLoader loader, Config config) {
return load(loader, config, ConfigResolveOptions.defaults());
}
/**
* Like {@link #load(Config)} but allows you to specify
* {@link ConfigResolveOptions}.
*
* @param config
* the application's portion of the configuration
* @param resolveOptions
* options for resolving the assembled config stack
* @return resolved configuration with overrides and fallbacks added
*/
public static Config load(Config config, ConfigResolveOptions resolveOptions) {
return load(Thread.currentThread().getContextClassLoader(), config, resolveOptions);
}
/**
* Like {@link #load(Config,ConfigResolveOptions)} but allows you to specify
* a class loader other than the context class loader.
*
* @param loader
* class loader to use when looking up override and reference
* configs
* @param config
* the application's portion of the configuration
* @param resolveOptions
* options for resolving the assembled config stack
* @return resolved configuration with overrides and fallbacks added
*/
public static Config load(ClassLoader loader, Config config, ConfigResolveOptions resolveOptions) {
return defaultOverrides(loader).withFallback(config).withFallback(defaultReference(loader))
.resolve(resolveOptions);
}
private static Config loadDefaultConfig(ClassLoader loader) {
return loadDefaultConfig(loader, ConfigParseOptions.defaults());
}
private static Config loadDefaultConfig(ClassLoader loader, ConfigParseOptions parseOptions) {
return loadDefaultConfig(loader, parseOptions, ConfigResolveOptions.defaults());
}
private static Config loadDefaultConfig(ClassLoader loader, ConfigResolveOptions resolveOptions) {
return loadDefaultConfig(loader, ConfigParseOptions.defaults(), resolveOptions);
}
private static Config loadDefaultConfig(ClassLoader loader, ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) {
int specified = 0;
// override application.conf with config.file, config.resource,
// config.url if requested.
String resource = System.getProperty("config.resource");
if (resource != null)
specified += 1;
String file = System.getProperty("config.file");
if (file != null)
specified += 1;
String url = System.getProperty("config.url");
if (url != null)
specified += 1;
if (specified == 0) {
return load(loader, "application", parseOptions, resolveOptions);
} else if (specified > 1) {
throw new ConfigException.Generic("You set more than one of config.file='" + file
+ "', config.url='" + url + "', config.resource='" + resource
+ "'; don't know which one to use!");
} else {
+ // the override file/url/resource MUST be present or it's an error
+ ConfigParseOptions overrideOptions = parseOptions.setAllowMissing(false);
if (resource != null) {
if (resource.startsWith("/"))
resource = resource.substring(1);
// this deliberately does not parseResourcesAnySyntax; if
// people want that they can use an include statement.
- return load(loader, parseResources(loader, resource, parseOptions), resolveOptions);
+ Config parsedResources = parseResources(loader, resource, overrideOptions);
+ return load(loader, parsedResources, resolveOptions);
} else if (file != null) {
- return load(
- loader,
- parseFile(new File(file), parseOptions), resolveOptions);
+ Config parsedFile = parseFile(new File(file), overrideOptions);
+ return load(loader, parsedFile, resolveOptions);
} else {
try {
- return load(
- loader,
- parseURL(new URL(url), parseOptions), resolveOptions);
+ Config parsedURL = parseURL(new URL(url), overrideOptions);
+ return load(loader, parsedURL, resolveOptions);
} catch (MalformedURLException e) {
throw new ConfigException.Generic("Bad URL in config.url system property: '"
+ url + "': " + e.getMessage(), e);
}
}
}
}
/**
* Loads a default configuration, equivalent to {@link #load(String)
* load("application")} in most cases. This configuration should be used by
* libraries and frameworks unless an application provides a different one.
* <p>
* This method may return a cached singleton so will not see changes to
* system properties or config files. (Use {@link #invalidateCaches()} to
* force it to reload.)
* <p>
* If the system properties <code>config.resource</code>,
* <code>config.file</code>, or <code>config.url</code> are set, then the
* classpath resource, file, or URL specified in those properties will be
* used rather than the default
* <code>application.{conf,json,properties}</code> classpath resources.
* These system properties should not be set in code (after all, you can
* just parse whatever you want manually and then use {@link #load(Config)}
* if you don't want to use <code>application.conf</code>). The properties
* are intended for use by the person or script launching the application.
* For example someone might have a <code>production.conf</code> that
* include <code>application.conf</code> but then change a couple of values.
* When launching the app they could specify
* <code>-Dconfig.resource=production.conf</code> to get production mode.
* <p>
* If no system properties are set to change the location of the default
* configuration, <code>ConfigFactory.load()</code> is equivalent to
* <code>ConfigFactory.load("application")</code>.
*
* @return configuration for an application
*/
public static Config load() {
return load(Thread.currentThread().getContextClassLoader());
}
/**
* Like {@link #load()} but allows specifying parse options
*
* @param parseOptions
* Options for parsing resources
* @return configuration for an application
*/
public static Config load(ConfigParseOptions parseOptions) {
return load(Thread.currentThread().getContextClassLoader(), parseOptions);
}
/**
* Like {@link #load()} but allows specifying a class loader other than the
* thread's current context class loader.
*
* @param loader
* class loader for finding resources
* @return configuration for an application
*/
public static Config load(final ClassLoader loader) {
return ConfigImpl.computeCachedConfig(loader, "load", new Callable<Config>() {
@Override
public Config call() {
return loadDefaultConfig(loader);
}
});
}
/**
* Like {@link #load()} but allows specifying a class loader other than the
* thread's current context class loader, and parse options
*
* @param loader
* class loader for finding resources
* @param parseOptions
* Options for parsing resources
* @return configuration for an application
*/
public static Config load(ClassLoader loader, ConfigParseOptions parseOptions) {
return loadDefaultConfig(loader, parseOptions);
}
/**
* Like {@link #load()} but allows specifying a class loader other than the
* thread's current context class loader, and resolve options
*
* @param loader
* class loader for finding resources
* @param resolveOptions
* options for resolving the assembled config stack
* @return configuration for an application
*/
public static Config load(ClassLoader loader, ConfigResolveOptions resolveOptions) {
return loadDefaultConfig(loader, resolveOptions);
}
/**
* Like {@link #load()} but allows specifying a class loader other than the
* thread's current context class loader, parse options, and resolve options
*
* @param loader
* class loader for finding resources
* @param parseOptions
* Options for parsing resources
* @param resolveOptions
* options for resolving the assembled config stack
* @return configuration for an application
*/
public static Config load(ClassLoader loader, ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) {
return loadDefaultConfig(loader, parseOptions, resolveOptions);
}
/**
* Obtains the default reference configuration, which is currently created
* by merging all resources "reference.conf" found on the classpath and
* overriding the result with system properties. The returned reference
* configuration will already have substitutions resolved.
*
* <p>
* Libraries and frameworks should ship with a "reference.conf" in their
* jar.
*
* <p>
* The reference config must be looked up in the class loader that contains
* the libraries that you want to use with this config, so the
* "reference.conf" for each library can be found. Use
* {@link #defaultReference(ClassLoader)} if the context class loader is not
* suitable.
*
* <p>
* The {@link #load()} methods merge this configuration for you
* automatically.
*
* <p>
* Future versions may look for reference configuration in more places. It
* is not guaranteed that this method <em>only</em> looks at
* "reference.conf".
*
* @return the default reference config for context class loader
*/
public static Config defaultReference() {
return defaultReference(Thread.currentThread().getContextClassLoader());
}
/**
* Like {@link #defaultReference()} but allows you to specify a class loader
* to use rather than the current context class loader.
*
* @param loader
* @return the default reference config for this class loader
*/
public static Config defaultReference(ClassLoader loader) {
return ConfigImpl.defaultReference(loader);
}
/**
* Obtains the default override configuration, which currently consists of
* system properties. The returned override configuration will already have
* substitutions resolved.
*
* <p>
* The {@link #load()} methods merge this configuration for you
* automatically.
*
* <p>
* Future versions may get overrides in more places. It is not guaranteed
* that this method <em>only</em> uses system properties.
*
* @return the default override configuration
*/
public static Config defaultOverrides() {
return systemProperties();
}
/**
* Like {@link #defaultOverrides()} but allows you to specify a class loader
* to use rather than the current context class loader.
*
* @param loader
* @return the default override configuration
*/
public static Config defaultOverrides(ClassLoader loader) {
return systemProperties();
}
/**
* Reloads any cached configs, picking up changes to system properties for
* example. Because a {@link Config} is immutable, anyone with a reference
* to the old configs will still have the same outdated objects. However,
* new calls to {@link #load()} or {@link #defaultOverrides()} or
* {@link #defaultReference} may return a new object.
* <p>
* This method is primarily intended for use in unit tests, for example,
* that may want to update a system property then confirm that it's used
* correctly. In many cases, use of this method may indicate there's a
* better way to set up your code.
* <p>
* Caches may be reloaded immediately or lazily; once you call this method,
* the reload can occur at any time, even during the invalidation process.
* So FIRST make the changes you'd like the caches to notice, then SECOND
* call this method to invalidate caches. Don't expect that invalidating,
* making changes, then calling {@link #load()}, will work. Make changes
* before you invalidate.
*/
public static void invalidateCaches() {
// We rely on this having the side effect that it drops
// all caches
ConfigImpl.reloadSystemPropertiesConfig();
}
/**
* Gets an empty configuration. See also {@link #empty(String)} to create an
* empty configuration with a description, which may improve user-visible
* error messages.
*
* @return an empty configuration
*/
public static Config empty() {
return empty(null);
}
/**
* Gets an empty configuration with a description to be used to create a
* {@link ConfigOrigin} for this <code>Config</code>. The description should
* be very short and say what the configuration is, like "default settings"
* or "foo settings" or something. (Presumably you will merge some actual
* settings into this empty config using {@link Config#withFallback}, making
* the description more useful.)
*
* @param originDescription
* description of the config
* @return an empty configuration
*/
public static Config empty(String originDescription) {
return ConfigImpl.emptyConfig(originDescription);
}
/**
* Gets a <code>Config</code> containing the system properties from
* {@link java.lang.System#getProperties()}, parsed and converted as with
* {@link #parseProperties}.
* <p>
* This method can return a global immutable singleton, so it's preferred
* over parsing system properties yourself.
* <p>
* {@link #load} will include the system properties as overrides already, as
* will {@link #defaultReference} and {@link #defaultOverrides}.
*
* <p>
* Because this returns a singleton, it will not notice changes to system
* properties made after the first time this method is called. Use
* {@link #invalidateCaches()} to force the singleton to reload if you
* modify system properties.
*
* @return system properties parsed into a <code>Config</code>
*/
public static Config systemProperties() {
return ConfigImpl.systemPropertiesAsConfig();
}
/**
* Gets a <code>Config</code> containing the system's environment variables.
* This method can return a global immutable singleton.
*
* <p>
* Environment variables are used as fallbacks when resolving substitutions
* whether or not this object is included in the config being resolved, so
* you probably don't need to use this method for most purposes. It can be a
* nicer API for accessing environment variables than raw
* {@link java.lang.System#getenv(String)} though, since you can use methods
* such as {@link Config#getInt}.
*
* @return system environment variables parsed into a <code>Config</code>
*/
public static Config systemEnvironment() {
return ConfigImpl.envVariablesAsConfig();
}
/**
* Converts a Java {@link java.util.Properties} object to a
* {@link ConfigObject} using the rules documented in the <a
* href="https://github.com/typesafehub/config/blob/master/HOCON.md">HOCON
* spec</a>. The keys in the <code>Properties</code> object are split on the
* period character '.' and treated as paths. The values will all end up as
* string values. If you have both "a=foo" and "a.b=bar" in your properties
* file, so "a" is both the object containing "b" and the string "foo", then
* the string value is dropped.
*
* <p>
* If you want to have <code>System.getProperties()</code> as a
* ConfigObject, it's better to use the {@link #systemProperties()} method
* which returns a cached global singleton.
*
* @param properties
* a Java Properties object
* @param options
* @return the parsed configuration
*/
public static Config parseProperties(Properties properties,
ConfigParseOptions options) {
return Parseable.newProperties(properties, options).parse().toConfig();
}
public static Config parseProperties(Properties properties) {
return parseProperties(properties, ConfigParseOptions.defaults());
}
public static Config parseReader(Reader reader, ConfigParseOptions options) {
return Parseable.newReader(reader, options).parse().toConfig();
}
public static Config parseReader(Reader reader) {
return parseReader(reader, ConfigParseOptions.defaults());
}
public static Config parseURL(URL url, ConfigParseOptions options) {
return Parseable.newURL(url, options).parse().toConfig();
}
public static Config parseURL(URL url) {
return parseURL(url, ConfigParseOptions.defaults());
}
public static Config parseFile(File file, ConfigParseOptions options) {
return Parseable.newFile(file, options).parse().toConfig();
}
public static Config parseFile(File file) {
return parseFile(file, ConfigParseOptions.defaults());
}
/**
* Parses a file with a flexible extension. If the <code>fileBasename</code>
* already ends in a known extension, this method parses it according to
* that extension (the file's syntax must match its extension). If the
* <code>fileBasename</code> does not end in an extension, it parses files
* with all known extensions and merges whatever is found.
*
* <p>
* In the current implementation, the extension ".conf" forces
* {@link ConfigSyntax#CONF}, ".json" forces {@link ConfigSyntax#JSON}, and
* ".properties" forces {@link ConfigSyntax#PROPERTIES}. When merging files,
* ".conf" falls back to ".json" falls back to ".properties".
*
* <p>
* Future versions of the implementation may add additional syntaxes or
* additional extensions. However, the ordering (fallback priority) of the
* three current extensions will remain the same.
*
* <p>
* If <code>options</code> forces a specific syntax, this method only parses
* files with an extension matching that syntax.
*
* <p>
* If {@link ConfigParseOptions#getAllowMissing options.getAllowMissing()}
* is true, then no files have to exist; if false, then at least one file
* has to exist.
*
* @param fileBasename
* a filename with or without extension
* @param options
* parse options
* @return the parsed configuration
*/
public static Config parseFileAnySyntax(File fileBasename,
ConfigParseOptions options) {
return ConfigImpl.parseFileAnySyntax(fileBasename, options).toConfig();
}
public static Config parseFileAnySyntax(File fileBasename) {
return parseFileAnySyntax(fileBasename, ConfigParseOptions.defaults());
}
/**
* Parses all resources on the classpath with the given name and merges them
* into a single <code>Config</code>.
*
* <p>
* If the resource name does not begin with a "/", it will have the supplied
* class's package added to it, in the same way as
* {@link java.lang.Class#getResource}.
*
* <p>
* Duplicate resources with the same name are merged such that ones returned
* earlier from {@link ClassLoader#getResources} fall back to (have higher
* priority than) the ones returned later. This implies that resources
* earlier in the classpath override those later in the classpath when they
* configure the same setting. However, in practice real applications may
* not be consistent about classpath ordering, so be careful. It may be best
* to avoid assuming too much.
*
* @param klass
* <code>klass.getClassLoader()</code> will be used to load
* resources, and non-absolute resource names will have this
* class's package added
* @param resource
* resource to look up, relative to <code>klass</code>'s package
* or absolute starting with a "/"
* @param options
* parse options
* @return the parsed configuration
*/
public static Config parseResources(Class<?> klass, String resource,
ConfigParseOptions options) {
return Parseable.newResources(klass, resource, options).parse()
.toConfig();
}
public static Config parseResources(Class<?> klass, String resource) {
return parseResources(klass, resource, ConfigParseOptions.defaults());
}
/**
* Parses classpath resources with a flexible extension. In general, this
* method has the same behavior as
* {@link #parseFileAnySyntax(File,ConfigParseOptions)} but for classpath
* resources instead, as in {@link #parseResources}.
*
* <p>
* There is a thorny problem with this method, which is that
* {@link java.lang.ClassLoader#getResources} must be called separately for
* each possible extension. The implementation ends up with separate lists
* of resources called "basename.conf" and "basename.json" for example. As a
* result, the ideal ordering between two files with different extensions is
* unknown; there is no way to figure out how to merge the two lists in
* classpath order. To keep it simple, the lists are simply concatenated,
* with the same syntax priorities as
* {@link #parseFileAnySyntax(File,ConfigParseOptions) parseFileAnySyntax()}
* - all ".conf" resources are ahead of all ".json" resources which are
* ahead of all ".properties" resources.
*
* @param klass
* class which determines the <code>ClassLoader</code> and the
* package for relative resource names
* @param resourceBasename
* a resource name as in {@link java.lang.Class#getResource},
* with or without extension
* @param options
* parse options (class loader is ignored in favor of the one
* from klass)
* @return the parsed configuration
*/
public static Config parseResourcesAnySyntax(Class<?> klass, String resourceBasename,
ConfigParseOptions options) {
return ConfigImpl.parseResourcesAnySyntax(klass, resourceBasename,
options).toConfig();
}
public static Config parseResourcesAnySyntax(Class<?> klass, String resourceBasename) {
return parseResourcesAnySyntax(klass, resourceBasename, ConfigParseOptions.defaults());
}
/**
* Parses all resources on the classpath with the given name and merges them
* into a single <code>Config</code>.
*
* <p>
* This works like {@link java.lang.ClassLoader#getResource}, not like
* {@link java.lang.Class#getResource}, so the name never begins with a
* slash.
*
* <p>
* See {@link #parseResources(Class,String,ConfigParseOptions)} for full
* details.
*
* @param loader
* will be used to load resources by setting this loader on the
* provided options
* @param resource
* resource to look up
* @param options
* parse options (class loader is ignored)
* @return the parsed configuration
*/
public static Config parseResources(ClassLoader loader, String resource,
ConfigParseOptions options) {
return Parseable.newResources(resource, options.setClassLoader(loader)).parse().toConfig();
}
public static Config parseResources(ClassLoader loader, String resource) {
return parseResources(loader, resource, ConfigParseOptions.defaults());
}
/**
* Parses classpath resources with a flexible extension. In general, this
* method has the same behavior as
* {@link #parseFileAnySyntax(File,ConfigParseOptions)} but for classpath
* resources instead, as in
* {@link #parseResources(ClassLoader,String,ConfigParseOptions)}.
*
* <p>
* {@link #parseResourcesAnySyntax(Class,String,ConfigParseOptions)} differs
* in the syntax for the resource name, but otherwise see
* {@link #parseResourcesAnySyntax(Class,String,ConfigParseOptions)} for
* some details and caveats on this method.
*
* @param loader
* class loader to look up resources in, will be set on options
* @param resourceBasename
* a resource name as in
* {@link java.lang.ClassLoader#getResource}, with or without
* extension
* @param options
* parse options (class loader ignored)
* @return the parsed configuration
*/
public static Config parseResourcesAnySyntax(ClassLoader loader, String resourceBasename,
ConfigParseOptions options) {
return ConfigImpl.parseResourcesAnySyntax(resourceBasename, options.setClassLoader(loader))
.toConfig();
}
public static Config parseResourcesAnySyntax(ClassLoader loader, String resourceBasename) {
return parseResourcesAnySyntax(loader, resourceBasename, ConfigParseOptions.defaults());
}
/**
* Like {@link #parseResources(ClassLoader,String,ConfigParseOptions)} but
* uses thread's current context class loader.
*/
public static Config parseResources(String resource, ConfigParseOptions options) {
return Parseable.newResources(resource, options)
.parse().toConfig();
}
/**
* Like {@link #parseResources(ClassLoader,String)} but uses thread's
* current context class loader.
*/
public static Config parseResources(String resource) {
return parseResources(resource, ConfigParseOptions.defaults());
}
/**
* Like
* {@link #parseResourcesAnySyntax(ClassLoader,String,ConfigParseOptions)}
* but uses thread's current context class loader.
*/
public static Config parseResourcesAnySyntax(String resourceBasename, ConfigParseOptions options) {
return ConfigImpl.parseResourcesAnySyntax(resourceBasename, options).toConfig();
}
/**
* Like {@link #parseResourcesAnySyntax(ClassLoader,String)} but uses
* thread's current context class loader.
*/
public static Config parseResourcesAnySyntax(String resourceBasename) {
return parseResourcesAnySyntax(resourceBasename, ConfigParseOptions.defaults());
}
public static Config parseString(String s, ConfigParseOptions options) {
return Parseable.newString(s, options).parse().toConfig();
}
public static Config parseString(String s) {
return parseString(s, ConfigParseOptions.defaults());
}
/**
* Creates a {@code Config} based on a {@link java.util.Map} from paths to
* plain Java values. Similar to
* {@link ConfigValueFactory#fromMap(Map,String)}, except the keys in the
* map are path expressions, rather than keys; and correspondingly it
* returns a {@code Config} instead of a {@code ConfigObject}. This is more
* convenient if you are writing literal maps in code, and less convenient
* if you are getting your maps from some data source such as a parser.
*
* <p>
* An exception will be thrown (and it is a bug in the caller of the method)
* if a path is both an object and a value, for example if you had both
* "a=foo" and "a.b=bar", then "a" is both the string "foo" and the parent
* object of "b". The caller of this method should ensure that doesn't
* happen.
*
* @param values
* @param originDescription
* description of what this map represents, like a filename, or
* "default settings" (origin description is used in error
* messages)
* @return the map converted to a {@code Config}
*/
public static Config parseMap(Map<String, ? extends Object> values,
String originDescription) {
return ConfigImpl.fromPathMap(values, originDescription).toConfig();
}
/**
* See the other overload of {@link #parseMap(Map, String)} for details,
* this one just uses a default origin description.
*
* @param values
* @return the map converted to a {@code Config}
*/
public static Config parseMap(Map<String, ? extends Object> values) {
return parseMap(values, null);
}
}
| false | true | private static Config loadDefaultConfig(ClassLoader loader, ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) {
int specified = 0;
// override application.conf with config.file, config.resource,
// config.url if requested.
String resource = System.getProperty("config.resource");
if (resource != null)
specified += 1;
String file = System.getProperty("config.file");
if (file != null)
specified += 1;
String url = System.getProperty("config.url");
if (url != null)
specified += 1;
if (specified == 0) {
return load(loader, "application", parseOptions, resolveOptions);
} else if (specified > 1) {
throw new ConfigException.Generic("You set more than one of config.file='" + file
+ "', config.url='" + url + "', config.resource='" + resource
+ "'; don't know which one to use!");
} else {
if (resource != null) {
if (resource.startsWith("/"))
resource = resource.substring(1);
// this deliberately does not parseResourcesAnySyntax; if
// people want that they can use an include statement.
return load(loader, parseResources(loader, resource, parseOptions), resolveOptions);
} else if (file != null) {
return load(
loader,
parseFile(new File(file), parseOptions), resolveOptions);
} else {
try {
return load(
loader,
parseURL(new URL(url), parseOptions), resolveOptions);
} catch (MalformedURLException e) {
throw new ConfigException.Generic("Bad URL in config.url system property: '"
+ url + "': " + e.getMessage(), e);
}
}
}
}
| private static Config loadDefaultConfig(ClassLoader loader, ConfigParseOptions parseOptions, ConfigResolveOptions resolveOptions) {
int specified = 0;
// override application.conf with config.file, config.resource,
// config.url if requested.
String resource = System.getProperty("config.resource");
if (resource != null)
specified += 1;
String file = System.getProperty("config.file");
if (file != null)
specified += 1;
String url = System.getProperty("config.url");
if (url != null)
specified += 1;
if (specified == 0) {
return load(loader, "application", parseOptions, resolveOptions);
} else if (specified > 1) {
throw new ConfigException.Generic("You set more than one of config.file='" + file
+ "', config.url='" + url + "', config.resource='" + resource
+ "'; don't know which one to use!");
} else {
// the override file/url/resource MUST be present or it's an error
ConfigParseOptions overrideOptions = parseOptions.setAllowMissing(false);
if (resource != null) {
if (resource.startsWith("/"))
resource = resource.substring(1);
// this deliberately does not parseResourcesAnySyntax; if
// people want that they can use an include statement.
Config parsedResources = parseResources(loader, resource, overrideOptions);
return load(loader, parsedResources, resolveOptions);
} else if (file != null) {
Config parsedFile = parseFile(new File(file), overrideOptions);
return load(loader, parsedFile, resolveOptions);
} else {
try {
Config parsedURL = parseURL(new URL(url), overrideOptions);
return load(loader, parsedURL, resolveOptions);
} catch (MalformedURLException e) {
throw new ConfigException.Generic("Bad URL in config.url system property: '"
+ url + "': " + e.getMessage(), e);
}
}
}
}
|
diff --git a/org.intrace/src/org/intrace/agent/ClassTransformer.java b/org.intrace/src/org/intrace/agent/ClassTransformer.java
index b98f466..cf86bbf 100644
--- a/org.intrace/src/org/intrace/agent/ClassTransformer.java
+++ b/org.intrace/src/org/intrace/agent/ClassTransformer.java
@@ -1,473 +1,473 @@
package org.intrace.agent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import org.intrace.output.AgentHelper;
import org.objectweb.asm.ClassReader;
/**
* Uses ASM2 to transform class files to add Trace instrumentation.
*/
public class ClassTransformer implements ClassFileTransformer
{
/**
* Map of modified class names to their original bytes
*/
private final Set<String> modifiedClasses = new ConcurrentSkipListSet<String>();
/**
* Instrumentation interface.
*/
private final Instrumentation inst;
/**
* Settings for this Transformer
*/
private final AgentSettings settings;
/**
* cTor
*
* @param xiInst
* @param xiEnableTracing
* @param xiClassRegex
* @param xiWriteModifiedClassfiles
* @param xiVerboseMode
* @param xiEnableTraceJars
*/
public ClassTransformer(Instrumentation xiInst, AgentSettings xiArgs)
{
inst = xiInst;
settings = xiArgs;
if (settings.isVerboseMode())
{
System.out.println(settings.toString());
}
}
/**
* Generate and return instrumented class bytes.
*
* @param xiClassName
* @param classfileBuffer
* @return Instrumented class bytes
*/
private byte[] getInstrumentedClassBytes(String xiClassName,
byte[] classfileBuffer)
{
try
{
ClassReader cr = new ClassReader(classfileBuffer);
ClassAnalysis analysis = new ClassAnalysis();
cr.accept(analysis, 0);
InstrumentedClassWriter writer = new InstrumentedClassWriter(xiClassName,
cr, analysis);
cr.accept(writer, 0);
return writer.toByteArray();
}
catch (Throwable th)
{
System.err.println("Caught Throwable when trying to instrument: "
+ xiClassName);
th.printStackTrace();
return null;
}
}
/**
* Retransform all modified classes.
* <p>
* Iterates over all loaded classes and retransforms those which we know we
* have modified.
*
* @param xiInst
*/
private void retransformModifiedClasses()
{
Class<?>[] loadedClasses = inst.getAllLoadedClasses();
for (Class<?> loadedClass : loadedClasses)
{
try
{
if (modifiedClasses.contains(loadedClass.getName()))
{
if (settings.isVerboseMode())
{
System.out.println("Retransform class: " + loadedClass.getName());
}
inst.retransformClasses(loadedClass);
}
}
catch (Throwable e)
{
// Write exception to stdout
System.err.println("Caught exception when modifying Class: "
+ loadedClass.getCanonicalName());
e.printStackTrace();
}
}
}
/**
* Determine whether a given className is eligible for modification. Any of
* the following conditions will make a class ineligible for instrumentation.
* <ul>
* <li>Class name which begins with "org.intrace"
* <li>Class name which begins with "org.objectweb.asm"
* <li>The class has already been modified
* <li>Class name ends with "Test"
* <li>Class name doesn't match the regex
* <li>Class is in a JAR and JAR instrumention is disabled
* </ul>
*
* @param className
* @param protectionDomain
* @return True if the Class with name className should be instrumented.
*/
private boolean isToBeConsideredForInstrumentation(
String className,
ProtectionDomain protectionDomain)
{
// Don't modify anything if tracing is disabled
if (!settings.isInstrumentationEnabled())
{
return false;
}
// Don't modify self
if (className.startsWith("org.intrace")
|| className.contains("objectweb.asm"))
{
if (settings.isVerboseMode())
{
System.out
.println("Ignoring class in org.intrace or objectweb.asm package: "
+ className);
}
return false;
}
// Don't modify a class which is already modified
if (modifiedClasses.contains(className))
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class already modified: " + className);
}
return false;
}
// Don't modify classes which match the exclude regex
if ((settings.getExcludeClassRegex() == null)
- || !settings.getExcludeClassRegex().matcher(className).matches())
+ || settings.getExcludeClassRegex().matcher(className).matches())
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class matching the active exclude regex: "
+ className);
}
return false;
}
// Don't modify classes which fail to match the regex
if ((settings.getClassRegex() == null)
|| !settings.getClassRegex().matcher(className).matches())
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class not matching the active regex: "
+ className);
}
return false;
}
// Don't modify a class for which we don't know the protection domain
if (protectionDomain == null)
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class with no protectionDomain: "
+ className);
}
return false;
}
// Don't modify a class from a JAR file unless this is allowed
CodeSource codeSource = protectionDomain.getCodeSource();
if (!settings.allowJarsToBeTraced() && (codeSource != null)
&& codeSource.getLocation().getPath().endsWith(".jar"))
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class in a JAR: " + className);
}
return false;
}
// All checks passed - class can be instrumented
return true;
}
/**
* java.lang.instrument Entry Point
* <p>
* Optionally transform a class file to add instrumentation.
* {@link ClassTransformer#isToBeConsideredForInstrumentation(String, ProtectionDomain)}
* determines whether a class is eligible for instrumentation.
*/
@Override
public byte[] transform(ClassLoader loader, String internalClassName,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] originalClassfile)
throws IllegalClassFormatException
{
String className = internalClassName.replace('/', '.');
if (isToBeConsideredForInstrumentation(className, protectionDomain))
{
if (settings.isVerboseMode())
{
System.out.println("!! Instrumenting class: " + className);
}
if (settings.saveTracedClassfiles())
{
writeClassBytes(originalClassfile, internalClassName + "_src.class");
}
byte[] newBytes;
try
{
newBytes = getInstrumentedClassBytes(className, originalClassfile);
}
catch (RuntimeException th)
{
// Ensure the JVM doesn't silently swallow an unchecked exception
th.printStackTrace();
throw th;
}
catch (Error th)
{
// Ensure the JVM doesn't silently swallow an unchecked exception
th.printStackTrace();
throw th;
}
if (settings.saveTracedClassfiles())
{
writeClassBytes(newBytes, internalClassName + "_gen.class");
}
modifiedClasses.add(className);
return newBytes;
}
else
{
modifiedClasses.remove(className);
return null;
}
}
private void writeClassBytes(byte[] newBytes, String className)
{
File classOut = new File("./genbin/" + className);
File parentDir = classOut.getParentFile();
boolean dirExists = parentDir.exists();
if (!dirExists)
{
dirExists = parentDir.mkdirs();
}
if (dirExists)
{
try
{
OutputStream out = new FileOutputStream(classOut);
try
{
out.write(newBytes);
out.flush();
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
out.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
}
else
{
System.out.println("Can't create directory " + parentDir
+ " for saving traced classfiles.");
}
}
/**
* Consider loaded classes for transformation. Any of the following reasons
* would prevent a loaded class from being eligible for instrumentation.
* <ul>
* <li>Class is an annotation
* <li>Class is synthetic
* <li>Class is not modifiable
* <li>Class is rejected by
* {@link ClassTransformer#isToBeConsideredForInstrumentation(String, ProtectionDomain)}
* </ul>
*/
public void instrumentLoadedClasses()
{
Class<?>[] loadedClasses = inst.getAllLoadedClasses();
for (Class<?> loadedClass : loadedClasses)
{
if (loadedClass.isAnnotation())
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring annotation class: "
+ loadedClass.getCanonicalName());
}
}
else if (loadedClass.isSynthetic())
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring synthetic class: "
+ loadedClass.getCanonicalName());
}
}
else if (!inst.isModifiableClass(loadedClass))
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring unmodifiable class: "
+ loadedClass.getCanonicalName());
}
}
else if (isToBeConsideredForInstrumentation(
loadedClass.getName(),
loadedClass
.getProtectionDomain()))
{
try
{
// System.out.println("ReTransform: " + loadedClass.getName());
inst.retransformClasses(loadedClass);
}
catch (Throwable e)
{
// Write exception to stdout
System.out.println(loadedClass.getName());
e.printStackTrace();
}
}
}
}
/**
* Toggle whether instrumentation is enabled
*
* @param xiTracingEnabled
*/
public void setInstrumentationEnabled(boolean xiInstrumentationEnabled)
{
if (xiInstrumentationEnabled)
{
instrumentLoadedClasses();
}
else if (!xiInstrumentationEnabled)
{
retransformModifiedClasses();
}
}
/**
* @return The currently active settings.
*/
public Map<String, String> getSettings()
{
return settings.getSettingsMap();
}
/**
* Handle a message and return a response.
*
* @param message
* @return Response or null if there is no response.
*/
public List<String> getResponse(String message)
{
List<String> responses = new ArrayList<String>();
AgentSettings oldSettings = new AgentSettings(settings);
settings.parseArgs(message);
if (settings.isVerboseMode()
&& (oldSettings.isVerboseMode() != settings.isVerboseMode()))
{
System.out.println(settings.toString());
}
else if (oldSettings.isInstrumentationEnabled() != settings
.isInstrumentationEnabled())
{
System.out.println("## Settings Changed");
setInstrumentationEnabled(settings.isInstrumentationEnabled());
}
else if (!oldSettings.getClassRegex().pattern()
.equals(settings.getClassRegex().pattern()))
{
System.out.println("## Settings Changed");
retransformModifiedClasses();
instrumentLoadedClasses();
}
else if (oldSettings.allowJarsToBeTraced() != settings
.allowJarsToBeTraced())
{
System.out.println("## Settings Changed");
retransformModifiedClasses();
instrumentLoadedClasses();
}
else if (oldSettings.saveTracedClassfiles() != settings
.saveTracedClassfiles())
{
System.out.println("## Settings Changed");
retransformModifiedClasses();
instrumentLoadedClasses();
}
else if (message.equals("[listmodifiedclasses"))
{
responses.add(modifiedClasses.toString());
}
responses.addAll(AgentHelper.getResponses(message));
return responses;
}
}
| true | true | private boolean isToBeConsideredForInstrumentation(
String className,
ProtectionDomain protectionDomain)
{
// Don't modify anything if tracing is disabled
if (!settings.isInstrumentationEnabled())
{
return false;
}
// Don't modify self
if (className.startsWith("org.intrace")
|| className.contains("objectweb.asm"))
{
if (settings.isVerboseMode())
{
System.out
.println("Ignoring class in org.intrace or objectweb.asm package: "
+ className);
}
return false;
}
// Don't modify a class which is already modified
if (modifiedClasses.contains(className))
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class already modified: " + className);
}
return false;
}
// Don't modify classes which match the exclude regex
if ((settings.getExcludeClassRegex() == null)
|| !settings.getExcludeClassRegex().matcher(className).matches())
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class matching the active exclude regex: "
+ className);
}
return false;
}
// Don't modify classes which fail to match the regex
if ((settings.getClassRegex() == null)
|| !settings.getClassRegex().matcher(className).matches())
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class not matching the active regex: "
+ className);
}
return false;
}
// Don't modify a class for which we don't know the protection domain
if (protectionDomain == null)
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class with no protectionDomain: "
+ className);
}
return false;
}
// Don't modify a class from a JAR file unless this is allowed
CodeSource codeSource = protectionDomain.getCodeSource();
if (!settings.allowJarsToBeTraced() && (codeSource != null)
&& codeSource.getLocation().getPath().endsWith(".jar"))
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class in a JAR: " + className);
}
return false;
}
// All checks passed - class can be instrumented
return true;
}
| private boolean isToBeConsideredForInstrumentation(
String className,
ProtectionDomain protectionDomain)
{
// Don't modify anything if tracing is disabled
if (!settings.isInstrumentationEnabled())
{
return false;
}
// Don't modify self
if (className.startsWith("org.intrace")
|| className.contains("objectweb.asm"))
{
if (settings.isVerboseMode())
{
System.out
.println("Ignoring class in org.intrace or objectweb.asm package: "
+ className);
}
return false;
}
// Don't modify a class which is already modified
if (modifiedClasses.contains(className))
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class already modified: " + className);
}
return false;
}
// Don't modify classes which match the exclude regex
if ((settings.getExcludeClassRegex() == null)
|| settings.getExcludeClassRegex().matcher(className).matches())
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class matching the active exclude regex: "
+ className);
}
return false;
}
// Don't modify classes which fail to match the regex
if ((settings.getClassRegex() == null)
|| !settings.getClassRegex().matcher(className).matches())
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class not matching the active regex: "
+ className);
}
return false;
}
// Don't modify a class for which we don't know the protection domain
if (protectionDomain == null)
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class with no protectionDomain: "
+ className);
}
return false;
}
// Don't modify a class from a JAR file unless this is allowed
CodeSource codeSource = protectionDomain.getCodeSource();
if (!settings.allowJarsToBeTraced() && (codeSource != null)
&& codeSource.getLocation().getPath().endsWith(".jar"))
{
if (settings.isVerboseMode())
{
System.out.println("Ignoring class in a JAR: " + className);
}
return false;
}
// All checks passed - class can be instrumented
return true;
}
|
diff --git a/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/index/DbDuplicationsIndex.java b/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/index/DbDuplicationsIndex.java
index 9cff050f2a..6f11397f0b 100644
--- a/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/index/DbDuplicationsIndex.java
+++ b/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/index/DbDuplicationsIndex.java
@@ -1,144 +1,144 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.cpd.index;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import org.hibernate.ejb.HibernateQuery;
import org.hibernate.transform.Transformers;
import org.sonar.api.database.DatabaseSession;
import org.sonar.api.database.model.Snapshot;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
import org.sonar.batch.index.ResourcePersister;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.ByteArray;
import org.sonar.jpa.entity.DuplicationBlock;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class DbDuplicationsIndex {
private final Map<ByteArray, Collection<Block>> cache = Maps.newHashMap();
private final DatabaseSession session;
private final ResourcePersister resourcePersister;
private final int currentProjectSnapshotId;
private final Integer lastSnapshotId;
public DbDuplicationsIndex(DatabaseSession session, ResourcePersister resourcePersister, Project currentProject) {
this.session = session;
this.resourcePersister = resourcePersister;
Snapshot currentSnapshot = resourcePersister.getSnapshotOrFail(currentProject);
Snapshot lastSnapshot = resourcePersister.getLastSnapshot(currentSnapshot, false);
this.currentProjectSnapshotId = currentSnapshot.getId();
this.lastSnapshotId = lastSnapshot == null ? null : lastSnapshot.getId();
}
/**
* For tests.
*/
DbDuplicationsIndex(DatabaseSession session, ResourcePersister resourcePersister, Integer currentProjectSnapshotId, Integer prevSnapshotId) {
this.session = session;
this.resourcePersister = resourcePersister;
this.currentProjectSnapshotId = currentProjectSnapshotId;
this.lastSnapshotId = prevSnapshotId;
}
int getSnapshotIdFor(Resource resource) {
return resourcePersister.getSnapshotOrFail(resource).getId();
}
public void prepareCache(Resource resource) {
int resourceSnapshotId = getSnapshotIdFor(resource);
// Order of columns is important - see code below!
String sql = "SELECT to_blocks.hash, res.kee, to_blocks.index_in_file, to_blocks.start_line, to_blocks.end_line" +
" FROM duplications_index to_blocks, duplications_index from_blocks, snapshots snapshot, projects res" +
" WHERE from_blocks.snapshot_id = :resource_snapshot_id" +
" AND to_blocks.hash = from_blocks.hash" +
" AND to_blocks.snapshot_id = snapshot.id" +
" AND snapshot.islast = :is_last" +
" AND snapshot.project_id = res.id";
if (lastSnapshotId != null) {
// Filter for blocks from previous snapshot of current project
sql += " AND to_blocks.project_snapshot_id != :last_project_snapshot_id";
}
Query query = session.getEntityManager().createNativeQuery(sql)
.setParameter("resource_snapshot_id", resourceSnapshotId)
.setParameter("is_last", Boolean.TRUE);
if (lastSnapshotId != null) {
query.setParameter("last_project_snapshot_id", lastSnapshotId);
}
// Ugly hack for mapping results of custom SQL query into plain list (MyBatis is coming soon)
((HibernateQuery) query).getHibernateQuery().setResultTransformer(Transformers.TO_LIST);
List<List<Object>> blocks = query.getResultList();
cache.clear();
for (List<Object> dbBlock : blocks) {
String hash = (String) dbBlock.get(0);
String resourceKey = (String) dbBlock.get(1);
- int indexInFile = (Integer) dbBlock.get(2);
- int startLine = (Integer) dbBlock.get(3);
- int endLine = (Integer) dbBlock.get(4);
+ int indexInFile = ((Number) dbBlock.get(2)).intValue();
+ int startLine = ((Number) dbBlock.get(3)).intValue();
+ int endLine = ((Number) dbBlock.get(4)).intValue();
Block block = new Block(resourceKey, new ByteArray(hash), indexInFile, startLine, endLine);
// Group blocks by hash
Collection<Block> sameHash = cache.get(block.getBlockHash());
if (sameHash == null) {
sameHash = Lists.newArrayList();
cache.put(block.getBlockHash(), sameHash);
}
sameHash.add(block);
}
}
public Collection<Block> getByHash(ByteArray hash) {
Collection<Block> result = cache.get(hash);
if (result != null) {
return result;
} else {
return Collections.emptyList();
}
}
public void insert(Resource resource, Collection<Block> blocks) {
int resourceSnapshotId = getSnapshotIdFor(resource);
for (Block block : blocks) {
DuplicationBlock dbBlock = new DuplicationBlock(
currentProjectSnapshotId,
resourceSnapshotId,
block.getBlockHash().toString(),
block.getIndexInFile(),
block.getFirstLineNumber(),
block.getLastLineNumber());
session.save(dbBlock);
}
session.commit();
}
}
| true | true | public void prepareCache(Resource resource) {
int resourceSnapshotId = getSnapshotIdFor(resource);
// Order of columns is important - see code below!
String sql = "SELECT to_blocks.hash, res.kee, to_blocks.index_in_file, to_blocks.start_line, to_blocks.end_line" +
" FROM duplications_index to_blocks, duplications_index from_blocks, snapshots snapshot, projects res" +
" WHERE from_blocks.snapshot_id = :resource_snapshot_id" +
" AND to_blocks.hash = from_blocks.hash" +
" AND to_blocks.snapshot_id = snapshot.id" +
" AND snapshot.islast = :is_last" +
" AND snapshot.project_id = res.id";
if (lastSnapshotId != null) {
// Filter for blocks from previous snapshot of current project
sql += " AND to_blocks.project_snapshot_id != :last_project_snapshot_id";
}
Query query = session.getEntityManager().createNativeQuery(sql)
.setParameter("resource_snapshot_id", resourceSnapshotId)
.setParameter("is_last", Boolean.TRUE);
if (lastSnapshotId != null) {
query.setParameter("last_project_snapshot_id", lastSnapshotId);
}
// Ugly hack for mapping results of custom SQL query into plain list (MyBatis is coming soon)
((HibernateQuery) query).getHibernateQuery().setResultTransformer(Transformers.TO_LIST);
List<List<Object>> blocks = query.getResultList();
cache.clear();
for (List<Object> dbBlock : blocks) {
String hash = (String) dbBlock.get(0);
String resourceKey = (String) dbBlock.get(1);
int indexInFile = (Integer) dbBlock.get(2);
int startLine = (Integer) dbBlock.get(3);
int endLine = (Integer) dbBlock.get(4);
Block block = new Block(resourceKey, new ByteArray(hash), indexInFile, startLine, endLine);
// Group blocks by hash
Collection<Block> sameHash = cache.get(block.getBlockHash());
if (sameHash == null) {
sameHash = Lists.newArrayList();
cache.put(block.getBlockHash(), sameHash);
}
sameHash.add(block);
}
}
| public void prepareCache(Resource resource) {
int resourceSnapshotId = getSnapshotIdFor(resource);
// Order of columns is important - see code below!
String sql = "SELECT to_blocks.hash, res.kee, to_blocks.index_in_file, to_blocks.start_line, to_blocks.end_line" +
" FROM duplications_index to_blocks, duplications_index from_blocks, snapshots snapshot, projects res" +
" WHERE from_blocks.snapshot_id = :resource_snapshot_id" +
" AND to_blocks.hash = from_blocks.hash" +
" AND to_blocks.snapshot_id = snapshot.id" +
" AND snapshot.islast = :is_last" +
" AND snapshot.project_id = res.id";
if (lastSnapshotId != null) {
// Filter for blocks from previous snapshot of current project
sql += " AND to_blocks.project_snapshot_id != :last_project_snapshot_id";
}
Query query = session.getEntityManager().createNativeQuery(sql)
.setParameter("resource_snapshot_id", resourceSnapshotId)
.setParameter("is_last", Boolean.TRUE);
if (lastSnapshotId != null) {
query.setParameter("last_project_snapshot_id", lastSnapshotId);
}
// Ugly hack for mapping results of custom SQL query into plain list (MyBatis is coming soon)
((HibernateQuery) query).getHibernateQuery().setResultTransformer(Transformers.TO_LIST);
List<List<Object>> blocks = query.getResultList();
cache.clear();
for (List<Object> dbBlock : blocks) {
String hash = (String) dbBlock.get(0);
String resourceKey = (String) dbBlock.get(1);
int indexInFile = ((Number) dbBlock.get(2)).intValue();
int startLine = ((Number) dbBlock.get(3)).intValue();
int endLine = ((Number) dbBlock.get(4)).intValue();
Block block = new Block(resourceKey, new ByteArray(hash), indexInFile, startLine, endLine);
// Group blocks by hash
Collection<Block> sameHash = cache.get(block.getBlockHash());
if (sameHash == null) {
sameHash = Lists.newArrayList();
cache.put(block.getBlockHash(), sameHash);
}
sameHash.add(block);
}
}
|
diff --git a/srcj/com/sun/electric/tool/routing/SimpleWirer.java b/srcj/com/sun/electric/tool/routing/SimpleWirer.java
index 6f3c1ea81..cdea445c2 100644
--- a/srcj/com/sun/electric/tool/routing/SimpleWirer.java
+++ b/srcj/com/sun/electric/tool/routing/SimpleWirer.java
@@ -1,231 +1,231 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: SimpleWirer.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.routing;
import com.sun.electric.database.geometry.GenMath;
import com.sun.electric.database.geometry.PolyMerge;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.SizeOffset;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.tool.user.User;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* A Simple wiring tool for the user to draw wires.
*/
public class SimpleWirer extends InteractiveRouter {
/* ----------------------- Router Methods ------------------------------------- */
public String toString() { return "SimpleWirer"; }
protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE,
Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute,
boolean contactsOnEndObj, boolean extendArcHead, boolean extendArcTail) {
RouteElementPort startRE = route.getEnd();
// find port protos of startRE and endRE, and find connecting arc type
PortProto startPort = startRE.getPortProto();
PortProto endPort = endRE.getPortProto();
ArcProto useArc = getArcToUse(startPort, endPort);
// first, find location of corner of L if routing will be an L shape
Point2D cornerLoc = null;
// see if it fits the angle increment so that a single arc can be drawn
boolean singleArc = false;
if (useArc != null)
{
- int inc = useArc.getAngleIncrement();
+ int inc = 10*useArc.getAngleIncrement();
if (inc == 0) singleArc = true; else
{
int ang = GenMath.figureAngle(startLoc, endLoc);
if ((ang % inc) == 0) singleArc = true;
}
} else
{
// no arc specified: allow direct if manhattan
if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()) singleArc = true;
}
if (singleArc)
{
// single arc
if (contactsOnEndObj)
cornerLoc = endLoc;
else
cornerLoc = startLoc;
} else
{
Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY());
Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY());
// find which pin to use
int clickedQuad = findQuadrant(endLoc, clicked);
int pin1Quad = findQuadrant(endLoc, pin1);
int pin2Quad = findQuadrant(endLoc, pin2);
int oppositeQuad = (clickedQuad + 2) % 4;
// presume pin1 by default
cornerLoc = pin1;
if (pin2Quad == clickedQuad)
{
cornerLoc = pin2; // same quad as pin2, use pin2
} else if (pin1Quad == clickedQuad)
{
cornerLoc = pin1; // same quad as pin1, use pin1
} else if (pin1Quad == oppositeQuad)
{
cornerLoc = pin2; // near to pin2 quad, use pin2
}
if (stayInside != null && useArc != null)
{
// make sure the bend stays inside of the merge area
double pinSize = useArc.getDefaultLambdaBaseWidth();
Layer pinLayer = useArc.getLayerIterator().next();
Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize);
Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize);
if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else
if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2;
}
}
// never use universal arcs unless the user has selected them
if (useArc == null) {
// use universal if selected
if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc)
useArc = Generic.tech.universal_arc;
else {
route.add(endRE);
route.setEnd(endRE);
vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc, stayInside);
return true;
}
}
route.add(endRE);
route.setEnd(endRE);
// startRE and endRE can be connected with an arc. If one of them is a bisectArcPin,
// and can be replaced by the other, just replace it and we're done.
if (route.replaceBisectPin(startRE, endRE)) {
route.remove(startRE);
return true;
} else if (route.replaceBisectPin(endRE, startRE)) {
route.remove(endRE);
route.setEnd(startRE);
return true;
}
// find arc width to use
double width = getArcWidthToUse(startRE, useArc);
double width2 = getArcWidthToUse(endRE, useArc);
if (width2 > width) width = width2;
// see if we should only draw a single arc
if (singleArc) {
// draw single
RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE,
startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(arcRE);
return true;
}
// this router only draws horizontal and vertical arcs
// if either X or Y coords are the same, create a single arc
// boolean newV = DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY());
// boolean oldV = (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY());
// if (newV != oldV)
// System.out.println("Precision problem in SimpleWireer");
if (DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY()))
{
// single arc
RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE,
startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(arcRE);
} else {
// otherwise, create new pin and two arcs for corner
// make new pin of arc type
PrimitiveNode pn = useArc.findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset();
double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset();
RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc,
defwidth, defheight);
RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE,
startLoc, cornerLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE,
cornerLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(pinRE);
route.add(arcRE1);
route.add(arcRE2);
}
return true;
}
/**
* Determines what route quadrant pt is compared to refPoint.
* A route can be drawn vertically or horizontally so this
* method will return a number between 0 and 3, inclusive,
* where quadrants are defined based on the angle relationship
* of refPoint to pt. Imagine a circle with <i>refPoint</i> as
* the center and <i>pt</i> a point on the circumference of the
* circle. Then theta is the angle described by the arc refPoint->pt,
* and quadrants are defined as:
* <code>
* <p>quadrant : angle (theta)
* <p>0 : -45 degrees to 45 degrees
* <p>1 : 45 degress to 135 degrees
* <p>2 : 135 degrees to 225 degrees
* <p>3 : 225 degrees to 315 degrees (-45 degrees)
*
* @param refPoint reference point
* @param pt variable point
* @return which quadrant <i>pt</i> is in.
*/
protected static int findQuadrant(Point2D refPoint, Point2D pt) {
// find angle
double angle = Math.atan((pt.getY()-refPoint.getY())/(pt.getX()-refPoint.getX()));
if (pt.getX() < refPoint.getX()) angle += Math.PI;
if ((angle > -Math.PI/4) && (angle <= Math.PI/4))
return 0;
else if ((angle > Math.PI/4) && (angle <= Math.PI*3/4))
return 1;
else if ((angle > Math.PI*3/4) &&(angle <= Math.PI*5/4))
return 2;
else
return 3;
}
}
| true | true | protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE,
Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute,
boolean contactsOnEndObj, boolean extendArcHead, boolean extendArcTail) {
RouteElementPort startRE = route.getEnd();
// find port protos of startRE and endRE, and find connecting arc type
PortProto startPort = startRE.getPortProto();
PortProto endPort = endRE.getPortProto();
ArcProto useArc = getArcToUse(startPort, endPort);
// first, find location of corner of L if routing will be an L shape
Point2D cornerLoc = null;
// see if it fits the angle increment so that a single arc can be drawn
boolean singleArc = false;
if (useArc != null)
{
int inc = useArc.getAngleIncrement();
if (inc == 0) singleArc = true; else
{
int ang = GenMath.figureAngle(startLoc, endLoc);
if ((ang % inc) == 0) singleArc = true;
}
} else
{
// no arc specified: allow direct if manhattan
if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()) singleArc = true;
}
if (singleArc)
{
// single arc
if (contactsOnEndObj)
cornerLoc = endLoc;
else
cornerLoc = startLoc;
} else
{
Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY());
Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY());
// find which pin to use
int clickedQuad = findQuadrant(endLoc, clicked);
int pin1Quad = findQuadrant(endLoc, pin1);
int pin2Quad = findQuadrant(endLoc, pin2);
int oppositeQuad = (clickedQuad + 2) % 4;
// presume pin1 by default
cornerLoc = pin1;
if (pin2Quad == clickedQuad)
{
cornerLoc = pin2; // same quad as pin2, use pin2
} else if (pin1Quad == clickedQuad)
{
cornerLoc = pin1; // same quad as pin1, use pin1
} else if (pin1Quad == oppositeQuad)
{
cornerLoc = pin2; // near to pin2 quad, use pin2
}
if (stayInside != null && useArc != null)
{
// make sure the bend stays inside of the merge area
double pinSize = useArc.getDefaultLambdaBaseWidth();
Layer pinLayer = useArc.getLayerIterator().next();
Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize);
Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize);
if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else
if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2;
}
}
// never use universal arcs unless the user has selected them
if (useArc == null) {
// use universal if selected
if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc)
useArc = Generic.tech.universal_arc;
else {
route.add(endRE);
route.setEnd(endRE);
vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc, stayInside);
return true;
}
}
route.add(endRE);
route.setEnd(endRE);
// startRE and endRE can be connected with an arc. If one of them is a bisectArcPin,
// and can be replaced by the other, just replace it and we're done.
if (route.replaceBisectPin(startRE, endRE)) {
route.remove(startRE);
return true;
} else if (route.replaceBisectPin(endRE, startRE)) {
route.remove(endRE);
route.setEnd(startRE);
return true;
}
// find arc width to use
double width = getArcWidthToUse(startRE, useArc);
double width2 = getArcWidthToUse(endRE, useArc);
if (width2 > width) width = width2;
// see if we should only draw a single arc
if (singleArc) {
// draw single
RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE,
startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(arcRE);
return true;
}
// this router only draws horizontal and vertical arcs
// if either X or Y coords are the same, create a single arc
// boolean newV = DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY());
// boolean oldV = (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY());
// if (newV != oldV)
// System.out.println("Precision problem in SimpleWireer");
if (DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY()))
{
// single arc
RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE,
startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(arcRE);
} else {
// otherwise, create new pin and two arcs for corner
// make new pin of arc type
PrimitiveNode pn = useArc.findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset();
double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset();
RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc,
defwidth, defheight);
RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE,
startLoc, cornerLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE,
cornerLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(pinRE);
route.add(arcRE1);
route.add(arcRE2);
}
return true;
}
| protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE,
Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute,
boolean contactsOnEndObj, boolean extendArcHead, boolean extendArcTail) {
RouteElementPort startRE = route.getEnd();
// find port protos of startRE and endRE, and find connecting arc type
PortProto startPort = startRE.getPortProto();
PortProto endPort = endRE.getPortProto();
ArcProto useArc = getArcToUse(startPort, endPort);
// first, find location of corner of L if routing will be an L shape
Point2D cornerLoc = null;
// see if it fits the angle increment so that a single arc can be drawn
boolean singleArc = false;
if (useArc != null)
{
int inc = 10*useArc.getAngleIncrement();
if (inc == 0) singleArc = true; else
{
int ang = GenMath.figureAngle(startLoc, endLoc);
if ((ang % inc) == 0) singleArc = true;
}
} else
{
// no arc specified: allow direct if manhattan
if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()) singleArc = true;
}
if (singleArc)
{
// single arc
if (contactsOnEndObj)
cornerLoc = endLoc;
else
cornerLoc = startLoc;
} else
{
Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY());
Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY());
// find which pin to use
int clickedQuad = findQuadrant(endLoc, clicked);
int pin1Quad = findQuadrant(endLoc, pin1);
int pin2Quad = findQuadrant(endLoc, pin2);
int oppositeQuad = (clickedQuad + 2) % 4;
// presume pin1 by default
cornerLoc = pin1;
if (pin2Quad == clickedQuad)
{
cornerLoc = pin2; // same quad as pin2, use pin2
} else if (pin1Quad == clickedQuad)
{
cornerLoc = pin1; // same quad as pin1, use pin1
} else if (pin1Quad == oppositeQuad)
{
cornerLoc = pin2; // near to pin2 quad, use pin2
}
if (stayInside != null && useArc != null)
{
// make sure the bend stays inside of the merge area
double pinSize = useArc.getDefaultLambdaBaseWidth();
Layer pinLayer = useArc.getLayerIterator().next();
Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize);
Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize);
if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else
if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2;
}
}
// never use universal arcs unless the user has selected them
if (useArc == null) {
// use universal if selected
if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc)
useArc = Generic.tech.universal_arc;
else {
route.add(endRE);
route.setEnd(endRE);
vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc, stayInside);
return true;
}
}
route.add(endRE);
route.setEnd(endRE);
// startRE and endRE can be connected with an arc. If one of them is a bisectArcPin,
// and can be replaced by the other, just replace it and we're done.
if (route.replaceBisectPin(startRE, endRE)) {
route.remove(startRE);
return true;
} else if (route.replaceBisectPin(endRE, startRE)) {
route.remove(endRE);
route.setEnd(startRE);
return true;
}
// find arc width to use
double width = getArcWidthToUse(startRE, useArc);
double width2 = getArcWidthToUse(endRE, useArc);
if (width2 > width) width = width2;
// see if we should only draw a single arc
if (singleArc) {
// draw single
RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE,
startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(arcRE);
return true;
}
// this router only draws horizontal and vertical arcs
// if either X or Y coords are the same, create a single arc
// boolean newV = DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY());
// boolean oldV = (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY());
// if (newV != oldV)
// System.out.println("Precision problem in SimpleWireer");
if (DBMath.areEquals(startLoc.getX(), endLoc.getX()) || DBMath.areEquals(startLoc.getY(), endLoc.getY()))
{
// single arc
RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE,
startLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(arcRE);
} else {
// otherwise, create new pin and two arcs for corner
// make new pin of arc type
PrimitiveNode pn = useArc.findOverridablePinProto();
SizeOffset so = pn.getProtoSizeOffset();
double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset();
double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset();
RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc,
defwidth, defheight);
RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE,
startLoc, cornerLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE,
cornerLoc, endLoc, null, null, null, extendArcHead, extendArcTail, stayInside);
route.add(pinRE);
route.add(arcRE1);
route.add(arcRE2);
}
return true;
}
|
diff --git a/src/com/hyperactivity/android_app/network/ServerLink.java b/src/com/hyperactivity/android_app/network/ServerLink.java
index 451d540..1364647 100644
--- a/src/com/hyperactivity/android_app/network/ServerLink.java
+++ b/src/com/hyperactivity/android_app/network/ServerLink.java
@@ -1,268 +1,268 @@
package com.hyperactivity.android_app.network;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.hyperactivity.android_app.Constants;
import com.hyperactivity.android_app.activities.MainActivity;
import com.hyperactivity.android_app.core.Engine;
import com.hyperactivity.android_app.forum.ForumEventCallback;
import com.hyperactivity.android_app.forum.models.*;
import com.hyperactivity.android_app.forum.models.Thread;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
/*
//TODO: enable the fb stuff
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
*/
public class ServerLink {
Engine engine;
public ServerLink(Engine engine) {
this.engine = engine;
}
//---------------------------- ACCOUNT ----------------------------
public void login(Session facebookSession, GraphUser facebookUser, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
String email = "TODO";
int facebookID = Integer.parseInt(facebookUser.getId());
String token = facebookSession.getAccessToken();
// params.put(Constants.Transfer.EMAIL, email);
params.put(Constants.Transfer.TOKEN, token);
sendRequest(Constants.Methods.LOGIN, facebookID, token, params, callback, true);
}
public void register(Session facebookSession, GraphUser facebookUser, String username, NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
int facebookID = Integer.parseInt(facebookUser.getId());
String token = facebookSession.getAccessToken();
params.put(Constants.Transfer.TOKEN, token);
params.put(Constants.Transfer.USERNAME, username);
sendRequest(Constants.Methods.REGISTER, facebookID, token, params, callback, true);
}
public void getAccount(int accountID, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.ACCOUNT_ID, accountID);
sendRequest(Constants.Methods.GET_ACCOUNT, params, callback, lockWithLoadingScreen);
}
public void updateAccount(String description, boolean showBirthDate, Bitmap avatar, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.DESCRIPTION, description);
params.put(Constants.Transfer.SHOW_BIRTHDATE, showBirthDate);
//TODO: Also send avatar.
sendRequest(Constants.Methods.UPDATE_PROFILE, params, callback, lockWithLoadingScreen);
}
public void loadAvatars(final Class callbackMethodType, final List<Account> accounts, final ForumEventCallback callback) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(callbackMethodType.equals(Thread.class)){
callback.threadsLoaded();
}else if(callbackMethodType.equals(Reply.class)){
callback.repliesLoaded();
}
}
@Override
protected Void doInBackground(Void... voids) {
for(Account account: accounts){
- String imageURL = "http://graph.facebook.com/"+account.getFacebookId()+"/picture?type=square";
+ String imageURL = "http://graph.facebook.com/"+account.getFacebookId()+"/picture?width=100&height=100";
try {
account.setProfilePicture(BitmapFactory.decodeStream((InputStream) new URL(imageURL).getContent()));
} catch (IOException e) {
Log.d(Constants.Log.TAG, "Loading Picture FAILED");
e.printStackTrace();
}
}
return null;
}
}.execute();
}
//---------------------------- CATEGORY ----------------------------
public void getForumContent(String type, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.TYPE, type);
sendRequest(Constants.Methods.GET_FORUM_CONTENT, params, callback, lockWithLoadingScreen);
}
public void getCategoryContent(int categoryID, String type, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.CATEGORY_ID, categoryID);
params.put(Constants.Transfer.TYPE, type);
sendRequest(Constants.Methods.GET_CATEGORY_CONTENT, params, callback, lockWithLoadingScreen);
}
public void createCategory(String type, String headline, int colorCode, boolean lockWithLoadinScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.TYPE, type);
params.put(Constants.Transfer.HEADLINE, headline);
params.put(Constants.Transfer.COLOR_CODE, colorCode);
sendRequest(Constants.Methods.CREATE_CATEGORY, params, callback, lockWithLoadinScreen);
}
public void modifyCategory(int categoryID, String type, String headline, int colorCode, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.CATEGORY_ID, categoryID);
params.put(Constants.Transfer.TYPE, type);
params.put(Constants.Transfer.HEADLINE, headline);
params.put(Constants.Transfer.COLOR_CODE, colorCode);
sendRequest(Constants.Methods.MODIFY_CATEGORY, params, callback, lockWithLoadingScreen);
}
public void deleteCategory(int categoryID, String type, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.CATEGORY_ID, categoryID);
params.put(Constants.Transfer.TYPE, type);
sendRequest(Constants.Methods.DELETE_CATEGORY, params, callback, lockWithLoadingScreen);
}
//---------------------------- THREAD ----------------------------
public void getLatestThreads(int limit, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.LIMIT, limit);
sendRequest(Constants.Methods.GET_LATEST_THREADS, params, callback, lockWithLoadingScreen);
}
public void getThreadContent(int threadID, int sortType, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.THREAD_ID, threadID);
params.put(Constants.Transfer.SORT_TYPE, sortType);
sendRequest(Constants.Methods.GET_THREAD_CONTENT, params, callback, lockWithLoadingScreen);
}
public void createThread(int categoryID, String headline, String text, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.CATEGORY_ID, categoryID);
params.put(Constants.Transfer.HEADLINE, headline);
params.put(Constants.Transfer.TEXT, text);
sendRequest(Constants.Methods.CREATE_THREAD, params, callback, lockWithLoadingScreen);
}
public void modifyThread(int threadID, String headline, String text, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.THREAD_ID, threadID);
params.put(Constants.Transfer.HEADLINE, headline);
params.put(Constants.Transfer.TEXT, text);
sendRequest(Constants.Methods.MODIFY_THREAD, params, callback, lockWithLoadingScreen);
}
public void deleteThread(int threadID, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.THREAD_ID, threadID);
sendRequest(Constants.Methods.DELETE_THREAD, params, callback, lockWithLoadingScreen);
}
//---------------------------- REPLIES ----------------------------
public void createReply(int threadID, String text, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.THREAD_ID, threadID);
params.put(Constants.Transfer.TEXT, text);
sendRequest(Constants.Methods.CREATE_REPLY, params, callback, lockWithLoadingScreen);
}
public void modifyReply(int replyID, String text, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.REPLY_ID, replyID);
params.put(Constants.Transfer.TEXT, text);
sendRequest(Constants.Methods.MODIFY_REPLY, params, callback, lockWithLoadingScreen);
}
public void deleteReply(int replyID, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.REPLY_ID, replyID);
sendRequest(Constants.Methods.DELETE_REPLY, params, callback, lockWithLoadingScreen);
}
public void thumbUp(int replyID, boolean lockWithLoadingScreen, final NetworkCallback callback) {
java.util.Map<String, Object> params = new HashMap<String, Object>();
params.put(Constants.Transfer.REPLY_ID, replyID);
sendRequest(Constants.Transfer.THUMB_UP, params, callback, lockWithLoadingScreen);
}
//---------------------------- HELPER METHODS ----------------------------
private void sendRequest(String method, java.util.Map<String, Object> params, final NetworkCallback activityCallback, boolean lockWithLoadingScreen) {
sendRequest(method, engine.getClientInfo().getAccount().getId(), engine.getClientInfo().getFacebookToken(), params, activityCallback, lockWithLoadingScreen);
}
private void sendRequest(String method, int id, String facebookToken, java.util.Map<String, Object> params, final NetworkCallback activityCallback, boolean lockWithLoadingScreen) {
if(facebookToken != null){
params.put(Constants.Transfer.TOKEN, facebookToken);
}
final JSONRPC2Request reqOut = new JSONRPC2Request(method, params, id);
sendRequest(reqOut, activityCallback, lockWithLoadingScreen);
}
private void sendRequest(JSONRPC2Request request, final NetworkCallback activityCallback, boolean lockWithLoadingScreen) {
try {
AsyncTask asyncTask = new NetworkAsyncTask(activityCallback, lockWithLoadingScreen);
asyncTask.execute(request);
} catch (Exception e) {
Log.e(Constants.Log.TAG, "exception: ", e);
}
}
/*
TODO: implement fb stuff
private Response getFacebookUserInfo() {
Session session = Session.getActiveSession();
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
}
});
return request.executeAndWait();
}
*/
}
| true | true | public void loadAvatars(final Class callbackMethodType, final List<Account> accounts, final ForumEventCallback callback) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(callbackMethodType.equals(Thread.class)){
callback.threadsLoaded();
}else if(callbackMethodType.equals(Reply.class)){
callback.repliesLoaded();
}
}
@Override
protected Void doInBackground(Void... voids) {
for(Account account: accounts){
String imageURL = "http://graph.facebook.com/"+account.getFacebookId()+"/picture?type=square";
try {
account.setProfilePicture(BitmapFactory.decodeStream((InputStream) new URL(imageURL).getContent()));
} catch (IOException e) {
Log.d(Constants.Log.TAG, "Loading Picture FAILED");
e.printStackTrace();
}
}
return null;
}
}.execute();
}
| public void loadAvatars(final Class callbackMethodType, final List<Account> accounts, final ForumEventCallback callback) {
new AsyncTask<Void, Void, Void>() {
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(callbackMethodType.equals(Thread.class)){
callback.threadsLoaded();
}else if(callbackMethodType.equals(Reply.class)){
callback.repliesLoaded();
}
}
@Override
protected Void doInBackground(Void... voids) {
for(Account account: accounts){
String imageURL = "http://graph.facebook.com/"+account.getFacebookId()+"/picture?width=100&height=100";
try {
account.setProfilePicture(BitmapFactory.decodeStream((InputStream) new URL(imageURL).getContent()));
} catch (IOException e) {
Log.d(Constants.Log.TAG, "Loading Picture FAILED");
e.printStackTrace();
}
}
return null;
}
}.execute();
}
|
diff --git a/Hog/src/util/ast/AbstractSyntaxTree.java b/Hog/src/util/ast/AbstractSyntaxTree.java
index e3f5be8..a311929 100644
--- a/Hog/src/util/ast/AbstractSyntaxTree.java
+++ b/Hog/src/util/ast/AbstractSyntaxTree.java
@@ -1,86 +1,86 @@
package util.ast;
import java.util.Iterator;
import util.ast.node.Node;
/**
* Abstract class for specifying common behavior for ASTs.
*
* @author sam
*
*/
public abstract class AbstractSyntaxTree {
protected Node root;
protected AbstractSyntaxTree(Node root) {
this.root = root;
}
public Iterator<Node> preOrderTraversal() {
return TreeTraversalBuilder.buildTraversalIterator(root,
TreeTraversalBuilder.traversalOrder.PREORDER);
}
public Iterator<Node> postOrderTraversal() {
return TreeTraversalBuilder.buildTraversalIterator(root,
TreeTraversalBuilder.traversalOrder.POSTORDER);
}
public String toLatex() {
if (root.getChildren() == null || root.getChildren().size() == 0) {
return "[.{" + root.getName() + "} ]";
}
StringBuilder sb = new StringBuilder();
sb.append("\\documentclass{article}\n");
sb.append("\\usepackage{graphicx, pdflscape}\n");
sb.append("\\usepackage{qtree}\n");
sb.append("\\begin{document}\n");
sb.append("\\begin{landscape}\n");
sb.append("\\thispagestyle{empty}\n");
sb.append("\\hspace*{-0.1\\linewidth}\\resizebox{1.2\\linewidth}{!}{%\n");
sb.append("\\Tree[.{" + root.getName() + "}");
for (Node child : root.getChildren()) {
sb.append(toLatexAux(child));
}
- sb.append(" ]\n");
+ sb.append(" ]\n}\n");
sb.append("\\end{landscape}\n");
sb.append("\\end{document}\n");
- return sb.toString().replaceAll("<", "\\$<\\$").replaceAll(">", "\\$>\\$").replaceAll("_", "\\_");
+ return sb.toString().replaceAll("<", "\\$<\\$").replaceAll(">", "\\$>\\$").replaceAll("_", "-");
}
private String toLatexAux(Node node) {
// base case
if (node.getChildren() == null || node.getChildren().size() == 0) {
return " [.{" + node.getName() + "} ]";
}
StringBuilder sb = new StringBuilder();
sb.append(" [.{" + node.getName() + "}");
for (Node child : node.getChildren()) {
sb.append(toLatexAux(child));
}
sb.append(" ]");
return sb.toString();
}
}
| false | true | public String toLatex() {
if (root.getChildren() == null || root.getChildren().size() == 0) {
return "[.{" + root.getName() + "} ]";
}
StringBuilder sb = new StringBuilder();
sb.append("\\documentclass{article}\n");
sb.append("\\usepackage{graphicx, pdflscape}\n");
sb.append("\\usepackage{qtree}\n");
sb.append("\\begin{document}\n");
sb.append("\\begin{landscape}\n");
sb.append("\\thispagestyle{empty}\n");
sb.append("\\hspace*{-0.1\\linewidth}\\resizebox{1.2\\linewidth}{!}{%\n");
sb.append("\\Tree[.{" + root.getName() + "}");
for (Node child : root.getChildren()) {
sb.append(toLatexAux(child));
}
sb.append(" ]\n");
sb.append("\\end{landscape}\n");
sb.append("\\end{document}\n");
return sb.toString().replaceAll("<", "\\$<\\$").replaceAll(">", "\\$>\\$").replaceAll("_", "\\_");
}
| public String toLatex() {
if (root.getChildren() == null || root.getChildren().size() == 0) {
return "[.{" + root.getName() + "} ]";
}
StringBuilder sb = new StringBuilder();
sb.append("\\documentclass{article}\n");
sb.append("\\usepackage{graphicx, pdflscape}\n");
sb.append("\\usepackage{qtree}\n");
sb.append("\\begin{document}\n");
sb.append("\\begin{landscape}\n");
sb.append("\\thispagestyle{empty}\n");
sb.append("\\hspace*{-0.1\\linewidth}\\resizebox{1.2\\linewidth}{!}{%\n");
sb.append("\\Tree[.{" + root.getName() + "}");
for (Node child : root.getChildren()) {
sb.append(toLatexAux(child));
}
sb.append(" ]\n}\n");
sb.append("\\end{landscape}\n");
sb.append("\\end{document}\n");
return sb.toString().replaceAll("<", "\\$<\\$").replaceAll(">", "\\$>\\$").replaceAll("_", "-");
}
|
diff --git a/src/main/java/be/Balor/Manager/Commands/Player/SpyMsg.java b/src/main/java/be/Balor/Manager/Commands/Player/SpyMsg.java
index 677a93a5..ab4da9e9 100644
--- a/src/main/java/be/Balor/Manager/Commands/Player/SpyMsg.java
+++ b/src/main/java/be/Balor/Manager/Commands/Player/SpyMsg.java
@@ -1,77 +1,77 @@
/************************************************************************
* This file is part of AdminCmd.
*
* AdminCmd 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.
*
* AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
package be.Balor.Manager.Commands.Player;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import be.Balor.Manager.Commands.CommandArgs;
import be.Balor.Manager.Commands.CoreCommand;
import be.Balor.Player.ACPlayer;
import be.Balor.Tools.Type;
import be.Balor.Tools.Utils;
import be.Balor.bukkit.AdminCmd.ACHelper;
/**
* @author Balor (aka Antoine Aflalo)
*
*/
public class SpyMsg extends CoreCommand {
/**
*
*/
public SpyMsg() {
permNode = "admincmd.player.spymsg";
cmdName = "bal_spymsg";
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.ACCommands#execute(org.bukkit.command.CommandSender,
* java.lang.String[])
*/
@Override
public void execute(CommandSender sender, CommandArgs args) {
if (Utils.isPlayer(sender)) {
ACPlayer acp = ACPlayer.getPlayer(((Player) sender).getName());
if (acp.hasPower(Type.SPYMSG)) {
acp.removePower(Type.SPYMSG);
- ACHelper.getInstance().removeSpy(acp.getHandler());
+ ACHelper.getInstance().removeSpy((Player) sender);
Utils.sI18n(sender, "spymsgDisabled");
} else {
acp.setPower(Type.SPYMSG);
- ACHelper.getInstance().addSpy(acp.getHandler());
+ ACHelper.getInstance().addSpy((Player) sender);
Utils.sI18n(sender, "spymsgEnabled");
}
}
}
/*
* (non-Javadoc)
*
* @see be.Balor.Manager.ACCommands#argsCheck(java.lang.String[])
*/
@Override
public boolean argsCheck(String... args) {
return true;
}
}
| false | true | public void execute(CommandSender sender, CommandArgs args) {
if (Utils.isPlayer(sender)) {
ACPlayer acp = ACPlayer.getPlayer(((Player) sender).getName());
if (acp.hasPower(Type.SPYMSG)) {
acp.removePower(Type.SPYMSG);
ACHelper.getInstance().removeSpy(acp.getHandler());
Utils.sI18n(sender, "spymsgDisabled");
} else {
acp.setPower(Type.SPYMSG);
ACHelper.getInstance().addSpy(acp.getHandler());
Utils.sI18n(sender, "spymsgEnabled");
}
}
}
| public void execute(CommandSender sender, CommandArgs args) {
if (Utils.isPlayer(sender)) {
ACPlayer acp = ACPlayer.getPlayer(((Player) sender).getName());
if (acp.hasPower(Type.SPYMSG)) {
acp.removePower(Type.SPYMSG);
ACHelper.getInstance().removeSpy((Player) sender);
Utils.sI18n(sender, "spymsgDisabled");
} else {
acp.setPower(Type.SPYMSG);
ACHelper.getInstance().addSpy((Player) sender);
Utils.sI18n(sender, "spymsgEnabled");
}
}
}
|
diff --git a/src/com/dmdirc/parser/IRCParser.java b/src/com/dmdirc/parser/IRCParser.java
index 2c01d4348..8f5bce27d 100644
--- a/src/com/dmdirc/parser/IRCParser.java
+++ b/src/com/dmdirc/parser/IRCParser.java
@@ -1,2052 +1,2052 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* SVN: $Id$
*/
package com.dmdirc.parser;
import com.dmdirc.parser.callbacks.CallbackManager;
import com.dmdirc.parser.callbacks.CallbackOnConnectError;
import com.dmdirc.parser.callbacks.CallbackOnDataIn;
import com.dmdirc.parser.callbacks.CallbackOnDataOut;
import com.dmdirc.parser.callbacks.CallbackOnDebugInfo;
import com.dmdirc.parser.callbacks.CallbackOnErrorInfo;
import com.dmdirc.parser.callbacks.CallbackOnServerError;
import com.dmdirc.parser.callbacks.CallbackOnSocketClosed;
import com.dmdirc.parser.callbacks.CallbackOnPingFailed;
import com.dmdirc.parser.callbacks.CallbackOnPingSent;
import com.dmdirc.parser.callbacks.CallbackOnPingSuccess;
import com.dmdirc.parser.callbacks.CallbackOnPost005;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Map;
import java.util.Timer;
import java.util.Queue;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* IRC Parser.
*
* @author Shane Mc Cormack
* @version $Id$
*/
public class IRCParser implements Runnable {
/** Max length an outgoing line should be (NOT including \r\n). */
public static final int MAX_LINELENGTH = 510;
/** General Debug Information. */
public static final int DEBUG_INFO = 1;
/** Socket Debug Information. */
public static final int DEBUG_SOCKET = 2;
/** Processing Manager Debug Information. */
public static final int DEBUG_PROCESSOR = 4;
/** List Mode Queue Debug Information. */
public static final int DEBUG_LMQ = 8;
// public static final int DEBUG_SOMETHING = 16; //Next thingy
/** Socket is not created yet. */
public static final byte STATE_NULL = 0;
/** Socket is closed. */
public static final byte STATE_CLOSED = 1;
/** Socket is Open. */
public static final byte STATE_OPEN = 2;
/** Attempt to update user host all the time, not just on Who/Add/NickChange. */
static final boolean ALWAYS_UPDATECLIENT = true;
/** Byte used to show that a non-boolean mode is a list (b). */
static final byte MODE_LIST = 1;
/** Byte used to show that a non-boolean mode is not a list, and requires a parameter to set (lk). */
static final byte MODE_SET = 2;
/** Byte used to show that a non-boolean mode is not a list, and requires a parameter to unset (k). */
static final byte MODE_UNSET = 4;
/**
* This is what the user wants settings to be.
* Nickname here is *not* always accurate.<br><br>
* ClientInfo variable tParser.getMyself() should be used for accurate info.
*/
public MyInfo me = new MyInfo();
/** Server Info requested by user. */
public ServerInfo server = new ServerInfo();
/** Timer for server ping. */
private Timer pingTimer = null;
/** Length of time to wait between ping stuff. */
private long pingTimerLength = 10000;
/** Is a ping needed? */
private volatile Boolean pingNeeded = false;
/** Time last ping was sent at. */
private long pingTime;
/** Current Server Lag. */
private long serverLag;
/** Last value sent as a ping argument. */
private String lastPingValue = "";
/**
* Count down to next ping.
* The timer fires every 10 seconds, this value is decreased every time the
* timer fires.<br>
* Once it reaches 0, we send a ping, and reset it to 6, this means we ping
* the server every minute.
*
* @see setPingCountDownLength
*/
private byte pingCountDown;
/**
* Amount of times the timer has to fire for inactivity before sending a ping.
*
* @see setPingCountDownLength
*/
private byte pingCountDownLength = 6;
/** Name the server calls itself. */
String sServerName;
/** Network name. This is "" if no network name is provided */
String sNetworkName;
/** This is what we think the nickname should be. */
String sThinkNickname;
/** When using inbuilt pre-001 NickInUse handler, have we tried our AltNick. */
boolean triedAlt;
/** Have we recieved the 001. */
boolean got001;
/** Have we fired post005? */
boolean post005;
/** Has the thread started execution yet, (Prevents run() being called multiple times). */
boolean hasBegan;
/** Hashtable storing known prefix modes (ohv). */
final Map<Character, Long> hPrefixModes = new Hashtable<Character, Long>();
/**
* Hashtable maping known prefix modes (ohv) to prefixes (@%+) - Both ways.
* Prefix map contains 2 pairs for each mode. (eg @ => o and o => @)
*/
final Map<Character, Character> hPrefixMap = new Hashtable<Character, Character>();
/** Integer representing the next avaliable integer value of a prefix mode. */
long nNextKeyPrefix = 1;
/** Hashtable storing known user modes (owxis etc). */
final Map<Character, Long> hUserModes = new Hashtable<Character, Long>();
/** Integer representing the next avaliable integer value of a User mode. */
long nNextKeyUser = 1;
/**
* Hashtable storing known boolean chan modes (cntmi etc).
* Valid Boolean Modes are stored as Hashtable.pub('m',1); where 'm' is the mode and 1 is a numeric value.<br><br>
* Numeric values are powers of 2. This allows up to 32 modes at present (expandable to 64)<br><br>
* ChannelInfo/ChannelClientInfo etc provide methods to view the modes in a human way.<br><br>
* <br>
* Channel modes discovered but not listed in 005 are stored as boolean modes automatically (and a ERROR_WARNING Error is called)
*/
final Map<Character, Long> hChanModesBool = new Hashtable<Character, Long>();
/** Integer representing the next avaliable integer value of a Boolean mode. */
long nNextKeyCMBool = 1;
/**
* Hashtable storing known non-boolean chan modes (klbeI etc).
* Non Boolean Modes (for Channels) are stored together in this hashtable, the value param
* is used to show the type of variable. (List (1), Param just for set (2), Param for Set and Unset (2+4=6))<br><br>
* <br>
* see MODE_LIST<br>
* see MODE_SET<br>
* see MODE_UNSET<br>
*/
final Map<Character, Byte> hChanModesOther = new Hashtable<Character, Byte>();
/** The last line of input recieved from the server */
String lastLine = "";
/** Should the lastline (where given) be appended to the "data" part of any onErrorInfo call? */
boolean addLastLine = false;
/**
* Channel Prefixes (ie # + etc).
* The "value" for these is always true.
*/
final Map<Character, Boolean> hChanPrefix = new Hashtable<Character, Boolean>();
/** Hashtable storing all known clients based on nickname (in lowercase). */
private final Map<String, ClientInfo> hClientList = new Hashtable<String, ClientInfo>();
/** Hashtable storing all known channels based on chanel name (inc prefix - in lowercase). */
private final Map<String, ChannelInfo> hChannelList = new Hashtable<String, ChannelInfo>();
/** Reference to the ClientInfo object that references ourself. */
private ClientInfo cMyself = new ClientInfo(this, "myself").setFake(true);
/** Hashtable storing all information gathered from 005. */
final Map<String, String> h005Info = new Hashtable<String, String>();
/** Ignore List. */
RegexStringList myIgnoreList = new RegexStringList();
/** Reference to the callback Manager. */
CallbackManager myCallbackManager = new CallbackManager(this);
/** Reference to the Processing Manager. */
ProcessingManager myProcessingManager = new ProcessingManager(this);
/** Should we automatically disconnect on fatal errors?. */
private boolean disconnectOnFatal = true;
/** Current Socket State. */
protected byte currentSocketState;
/** This is the socket used for reading from/writing to the IRC server. */
private Socket socket;
/** Used for writing to the server. */
private PrintWriter out;
/** Used for reading from the server. */
private BufferedReader in;
/** This is the default TrustManager for SSL Sockets, it trusts all ssl certs. */
private final TrustManager[] trustAllCerts = {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() { return null; }
@Override
public void checkClientTrusted(final X509Certificate[] certs, final String authType) { }
@Override
public void checkServerTrusted(final X509Certificate[] certs, final String authType) { }
},
};
/** Should fake (channel)clients be created for callbacks where they do not exist? */
boolean createFake = false;
/** Should channels automatically request list modes? */
boolean autoListMode = true;
/** Should part/quit/kick callbacks be fired before removing the user internally? */
boolean removeAfterCallback = true;
/** This is the TrustManager used for SSL Sockets. */
private TrustManager[] myTrustManager = trustAllCerts;
/** This is the IP we want to bind to. */
private String bindIP = "";
/**
* Default constructor, ServerInfo and MyInfo need to be added separately (using IRC.me and IRC.server).
*/
public IRCParser() { this(null, null); }
/**
* Constructor with ServerInfo, MyInfo needs to be added separately (using IRC.me).
*
* @param serverDetails Server information.
*/
public IRCParser(final ServerInfo serverDetails) { this(null, serverDetails); }
/**
* Constructor with MyInfo, ServerInfo needs to be added separately (using IRC.server).
*
* @param myDetails Client information.
*/
public IRCParser(final MyInfo myDetails) { this(myDetails, null); }
/**
* Constructor with ServerInfo and MyInfo.
*
* @param serverDetails Server information.
* @param myDetails Client information.
*/
public IRCParser(final MyInfo myDetails, final ServerInfo serverDetails) {
if (myDetails != null) { this.me = myDetails; }
if (serverDetails != null) { this.server = serverDetails; }
resetState();
}
/**
* Get the current Value of bindIP.
*
* @return Value of bindIP ("" for default IP)
*/
public String getBindIP() { return bindIP; }
/**
* Set the current Value of bindIP.
*
* @param newValue New value to set bindIP
*/
public void setBindIP(final String newValue) { bindIP = newValue; }
/**
* Get the current Value of createFake.
*
* @return Value of createFake (true if fake clients will be added for callbacks, else false)
*/
public boolean getCreateFake() { return createFake; }
/**
* Set the current Value of createFake.
*
* @param newValue New value to set createFake
*/
public void setCreateFake(final boolean newValue) { createFake = newValue; }
/**
* Get the current Value of autoListMode.
*
* @return Value of autoListMode (true if channels automatically ask for list modes on join, else false)
*/
public boolean getAutoListMode() { return autoListMode; }
/**
* Set the current Value of autoListMode.
*
* @param newValue New value to set autoListMode
*/
public void setAutoListMode(final boolean newValue) { autoListMode = newValue; }
/**
* Get the current Value of removeAfterCallback.
*
* @return Value of removeAfterCallback (true if kick/part/quit callbacks are fired before internal removal)
*/
public boolean getRemoveAfterCallback() { return removeAfterCallback; }
/**
* Get the current Value of removeAfterCallback.
*
* @param newValue New value to set removeAfterCallback
*/
public void setRemoveAfterCallback(final boolean newValue) { removeAfterCallback = newValue; }
/**
* Get the current Value of addLastLine.
*
* @return Value of addLastLine (true if lastLine info will be automatically
* added to the errorInfo data line). This should be true if lastLine
* isn't handled any other way.
*/
public boolean getAddLastLine() { return addLastLine; }
/**
* Get the current Value of addLastLine.
* This returns "this" and thus can be used in the construction line.
*
* @param newValue New value to set addLastLine
*/
public void setAddLastLine(final boolean newValue) { addLastLine = newValue; }
/**
* Get the current socket State.
*
* @return Current SocketState (STATE_NULL, STATE_CLOSED or STATE_OPEN)
*/
public byte getSocketState() { return currentSocketState; }
/**
* Get a reference to the Processing Manager.
*
* @return Reference to the CallbackManager
*/
public ProcessingManager getProcessingManager() { return myProcessingManager; }
/**
* Get a reference to the CallbackManager.
*
* @return Reference to the CallbackManager
*/
public CallbackManager getCallbackManager() { return myCallbackManager; }
/**
* Get a reference to the default TrustManager for SSL Sockets.
*
* @return a reference to trustAllCerts
*/
public TrustManager[] getDefaultTrustManager() { return trustAllCerts; }
/**
* Get a reference to the current TrustManager for SSL Sockets.
*
* @return a reference to myTrustManager;
*/
public TrustManager[] getTrustManager() { return myTrustManager; }
/**
* Replace the current TrustManager for SSL Sockets with a new one.
*
* @param newTrustManager Replacement TrustManager for SSL Sockets.
*/
public void setTrustManager(final TrustManager[] newTrustManager) { myTrustManager = newTrustManager; }
/**
* Get a reference to the ignorelist.
*
* @return a reference to the ignorelist
*/
public RegexStringList getIgnoreList() { return myIgnoreList; }
/**
* Replaces the current ignorelist with a new one.
*
* @param ignoreList Replacement ignorelist
*/
public void setIgnoreList(final RegexStringList ignoreList) { myIgnoreList = ignoreList; }
//---------------------------------------------------------------------------
// Start Callbacks
//---------------------------------------------------------------------------
/**
* Callback to all objects implementing the ServerError Callback.
*
* @see com.dmdirc.parser.callbacks.interfaces.IServerError
* @param message The error message
* @return true if a method was called, false otherwise
*/
protected boolean callServerError(final String message) {
return ((CallbackOnServerError) myCallbackManager.getCallbackType("OnServerError")).call(message);
}
/**
* Callback to all objects implementing the DataIn Callback.
*
* @see com.dmdirc.parser.callbacks.interfaces.IDataIn
* @param data Incomming Line.
* @return true if a method was called, false otherwise
*/
protected boolean callDataIn(final String data) {
return ((CallbackOnDataIn) myCallbackManager.getCallbackType("OnDataIn")).call(data);
}
/**
* Callback to all objects implementing the DataOut Callback.
*
* @param data Outgoing Data
* @param fromParser True if parser sent the data, false if sent using .sendLine
* @return true if a method was called, false otherwise
* @see com.dmdirc.parser.callbacks.interfaces.IDataOut
*/
protected boolean callDataOut(final String data, final boolean fromParser) {
return ((CallbackOnDataOut) myCallbackManager.getCallbackType("OnDataOut")).call(data, fromParser);
}
/**
* Callback to all objects implementing the DebugInfo Callback.
*
* @see com.dmdirc.parser.callbacks.interfaces.IDebugInfo
* @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc)
* @param data Debugging Information as a format string
* @param args Formatting String Options
* @return true if a method was called, false otherwise
*/
protected boolean callDebugInfo(final int level, final String data, final Object... args) {
return callDebugInfo(level, String.format(data, args));
}
/**
* Callback to all objects implementing the DebugInfo Callback.
*
* @see com.dmdirc.parser.callbacks.interfaces.IDebugInfo
* @param level Debugging Level (DEBUG_INFO, DEBUG_SOCKET etc)
* @param data Debugging Information
* @return true if a method was called, false otherwise
*/
protected boolean callDebugInfo(final int level, final String data) {
return ((CallbackOnDebugInfo) myCallbackManager.getCallbackType("OnDebugInfo")).call(level, data);
}
/**
* Callback to all objects implementing the IErrorInfo Interface.
*
* @see com.dmdirc.parser.callbacks.interfaces.IErrorInfo
* @param errorInfo ParserError object representing the error.
* @return true if a method was called, false otherwise
*/
protected boolean callErrorInfo(final ParserError errorInfo) {
return ((CallbackOnErrorInfo) myCallbackManager.getCallbackType("OnErrorInfo")).call(errorInfo);
}
/**
* Callback to all objects implementing the IConnectError Interface.
*
* @see com.dmdirc.parser.callbacks.interfaces.IConnectError
* @param errorInfo ParserError object representing the error.
* @return true if a method was called, false otherwise
*/
protected boolean callConnectError(final ParserError errorInfo) {
return ((CallbackOnConnectError) myCallbackManager.getCallbackType("OnConnectError")).call(errorInfo);
}
/**
* Callback to all objects implementing the SocketClosed Callback.
*
* @see com.dmdirc.parser.callbacks.interfaces.ISocketClosed
* @return true if a method was called, false otherwise
*/
protected boolean callSocketClosed() {
return ((CallbackOnSocketClosed) myCallbackManager.getCallbackType("OnSocketClosed")).call();
}
/**
* Callback to all objects implementing the PingFailed Callback.
*
* @see com.dmdirc.parser.callbacks.interfaces.IPingFailed
* @return true if a method was called, false otherwise
*/
protected boolean callPingFailed() {
return ((CallbackOnPingFailed) myCallbackManager.getCallbackType("OnPingFailed")).call();
}
/**
* Callback to all objects implementing the PingSent Callback.
*
* @see com.dmdirc.parser.callbacks.interfaces.IPingSent
* @return true if a method was called, false otherwise
*/
protected boolean callPingSent() {
return ((CallbackOnPingSent) myCallbackManager.getCallbackType("OnPingSent")).call();
}
/**
* Callback to all objects implementing the PingSuccess Callback.
*
* @see com.dmdirc.parser.callbacks.interfaces.IPingSuccess
* @return true if a method was called, false otherwise
*/
protected boolean callPingSuccess() {
return ((CallbackOnPingSuccess) myCallbackManager.getCallbackType("OnPingSuccess")).call();
}
/**
* Callback to all objects implementing the Post005 Callback.
*
* @return true if any callbacks were called.
* @see IPost005
*/
protected synchronized boolean callPost005() {
if (post005) { return false; }
post005 = true;
return ((CallbackOnPost005) getCallbackManager().getCallbackType("OnPost005")).call();
}
//---------------------------------------------------------------------------
// End Callbacks
//---------------------------------------------------------------------------
/** Reset internal state (use before connect). */
private void resetState() {
// Reset General State info
triedAlt = false;
got001 = false;
post005 = false;
// Clear the hash tables
hChannelList.clear();
hClientList.clear();
h005Info.clear();
hPrefixModes.clear();
hPrefixMap.clear();
hChanModesOther.clear();
hChanModesBool.clear();
hUserModes.clear();
hChanPrefix.clear();
// Reset the mode indexes
nNextKeyPrefix = 1;
nNextKeyCMBool = 1;
nNextKeyUser = 1;
sServerName = "";
sNetworkName = "";
lastLine = "";
cMyself = new ClientInfo(this, "myself").setFake(true);
if (pingTimer != null) {
pingTimer.cancel();
pingTimer = null;
}
currentSocketState = STATE_CLOSED;
// Char Mapping
updateCharArrays((byte)4);
}
/**
* Called after other error callbacks.
* CallbackOnErrorInfo automatically calls this *AFTER* any registered callbacks
* for it are called.
*
* @param errorInfo ParserError object representing the error.
* @param called True/False depending on the the success of other callbacks.
*/
public void onPostErrorInfo(final ParserError errorInfo, final boolean called) {
if (errorInfo.isFatal() && disconnectOnFatal) {
disconnect("Fatal Parser Error");
}
}
/**
* Get the current Value of disconnectOnFatal.
*
* @return Value of disconnectOnFatal (true if the parser automatically disconnects on fatal errors, else false)
*/
public boolean getDisconnectOnFatal() { return disconnectOnFatal; }
/**
* Set the current Value of disconnectOnFatal.
*
* @param newValue New value to set disconnectOnFatal
*/
public void setDisconnectOnFatal(final boolean newValue) { disconnectOnFatal = newValue; }
/**
* Connect to IRC.
*
* @throws IOException if the socket can not be connected
* @throws UnknownHostException if the hostname can not be resolved
* @throws NoSuchAlgorithmException if SSL is not available
* @throws KeyManagementException if the trustManager is invalid
*/
private void connect() throws UnknownHostException, IOException, NoSuchAlgorithmException, KeyManagementException {
resetState();
callDebugInfo(DEBUG_SOCKET, "Connecting to " + server.getHost() + ":" + server.getPort());
if (server.getPort() > 65535 || server.getPort() <= 0) {
throw new IOException("Server port ("+server.getPort()+") is invalid.");
}
if (server.getUseSocks()) {
callDebugInfo(DEBUG_SOCKET, "Using Proxy");
if (bindIP != null && !bindIP.isEmpty()) {
callDebugInfo(DEBUG_SOCKET, "IP Binding is not possible when using a proxy.");
}
if (server.getProxyPort() > 65535 || server.getProxyPort() <= 0) {
throw new IOException("Proxy port ("+server.getProxyPort()+") is invalid.");
}
final Proxy.Type proxyType = Proxy.Type.SOCKS;
socket = new Socket(new Proxy(proxyType, new InetSocketAddress(server.getProxyHost(), server.getProxyPort())));
if (server.getProxyUser() != null && !server.getProxyUser().isEmpty()) {
- IRCAuthenticator.getIRCAuthenticator().add(server);
+ IRCAuthenticator.getIRCAuthenticator().addAuthentication(server);
}
socket.connect(new InetSocketAddress(server.getHost(), server.getPort()));
} else {
callDebugInfo(DEBUG_SOCKET, "Not using Proxy");
if (!server.getSSL()) {
if (bindIP == null || bindIP.isEmpty()) {
socket = new Socket(server.getHost(), server.getPort());
} else {
callDebugInfo(DEBUG_SOCKET, "Binding to IP: "+bindIP);
try {
socket = new Socket(server.getHost(), server.getPort(), InetAddress.getByName(bindIP), 0);
} catch (IOException e) {
callDebugInfo(DEBUG_SOCKET, "Binding failed: "+e.getMessage());
socket = new Socket(server.getHost(), server.getPort());
}
}
}
}
if (server.getSSL()) {
callDebugInfo(DEBUG_SOCKET, "Server is SSL.");
if (myTrustManager == null) { myTrustManager = trustAllCerts; }
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, myTrustManager, new java.security.SecureRandom());
final SSLSocketFactory socketFactory = sc.getSocketFactory();
if (server.getUseSocks()) {
socket = socketFactory.createSocket(socket, server.getHost(), server.getPort(), false);
} else {
if (bindIP == null || bindIP.isEmpty()) {
socket = socketFactory.createSocket(server.getHost(), server.getPort());
} else {
callDebugInfo(DEBUG_SOCKET, "Binding to IP: "+bindIP);
try {
socket = socketFactory.createSocket(server.getHost(), server.getPort(), InetAddress.getByName(bindIP), 0);
} catch (UnknownHostException e) {
callDebugInfo(DEBUG_SOCKET, "Bind failed: "+e.getMessage());
socket = socketFactory.createSocket(server.getHost(), server.getPort());
}
}
}
}
callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket output stream PrintWriter");
out = new PrintWriter(socket.getOutputStream(), true);
currentSocketState = STATE_OPEN;
callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket input stream BufferedReader");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
callDebugInfo(DEBUG_SOCKET, "\t-> Socket Opened");
}
/**
* Send server connection strings (NICK/USER/PASS).
*/
protected void sendConnectionStrings() {
if (!server.getPassword().isEmpty()) {
sendString("PASS " + server.getPassword());
}
setNickname(me.getNickname());
String localhost;
try {
localhost = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException uhe) {
localhost = "*";
}
sendString("USER " + getIRCStringConverter().toLowerCase(me.getUsername()) + " "+localhost+" "+server.getHost()+" :" + me.getRealname());
}
/**
* Handle an onConnect error.
*
* @param e Exception to handle
*/
private void handleConnectException(final Exception e) {
callDebugInfo(DEBUG_SOCKET, "Error Connecting (" + e.getMessage() + "), Aborted");
final ParserError ei = new ParserError(ParserError.ERROR_ERROR, "Error connecting to server");
ei.setException(e);
callConnectError(ei);
}
/**
* Begin execution.
* Connect to server, and start parsing incomming lines
*/
@Override
public void run() {
callDebugInfo(DEBUG_INFO, "Begin Thread Execution");
if (hasBegan) { return; } else { hasBegan = true; }
try {
connect();
} catch (UnknownHostException e) {
handleConnectException(e);
return;
} catch (IOException e) {
handleConnectException(e);
return;
} catch (NoSuchAlgorithmException e) {
handleConnectException(e);
return;
} catch (KeyManagementException e) {
handleConnectException(e);
return;
}
callDebugInfo(DEBUG_SOCKET, "Socket Connected");
sendConnectionStrings();
while (true) {
try {
lastLine = in.readLine(); // Blocking :/
if (lastLine == null) {
if (currentSocketState != STATE_CLOSED) {
currentSocketState = STATE_CLOSED;
callSocketClosed();
}
resetState();
break;
} else {
processLine(lastLine);
}
} catch (IOException e) {
if (currentSocketState != STATE_CLOSED) {
currentSocketState = STATE_CLOSED;
callSocketClosed();
}
resetState();
break;
}
}
callDebugInfo(DEBUG_INFO, "End Thread Execution");
}
/**
* Get the current local port number.
*
* @return 0 if not connected, else the current local port number
*/
public int getLocalPort() {
if (currentSocketState == STATE_OPEN) {
return socket.getLocalPort();
} else {
return 0;
}
}
/** Close socket on destroy. */
@Override
protected void finalize() throws Throwable {
try { socket.close(); }
catch (IOException e) {
callDebugInfo(DEBUG_SOCKET, "Could not close socket");
}
super.finalize();
}
/**
* Get the trailing parameter for a line.
* The parameter is everything after the first occurance of " :" ot the last token in the line after a space.
*
* @param line Line to get parameter for
* @return Parameter of the line
*/
public static String getParam(final String line) {
String[] params = null;
params = line.split(" :", 2);
return params[params.length - 1];
}
/**
* Tokenise a line.
* splits by " " up to the first " :" everything after this is a single token
*
* @param line Line to tokenise
* @return Array of tokens
*/
public static String[] tokeniseLine(final String line) {
if (line == null) {
return new String[]{"", }; // Return empty string[]
}
final int lastarg = line.indexOf(" :");
String[] tokens;
if (lastarg > -1) {
final String[] temp = line.substring(0, lastarg).split(" ");
tokens = new String[temp.length + 1];
System.arraycopy(temp, 0, tokens, 0, temp.length);
tokens[temp.length] = line.substring(lastarg + 2);
} else {
tokens = line.split(" ");
}
return tokens;
}
/**
* Get the ClientInfo object for a person.
*
* @param sHost Who can be any valid identifier for a client as long as it contains a nickname (?:)nick(?!ident)(?@host)
* @return ClientInfo Object for the client, or null
*/
public ClientInfo getClientInfo(final String sHost) {
final String sWho = getIRCStringConverter().toLowerCase(ClientInfo.parseHost(sHost));
if (hClientList.containsKey(sWho)) { return hClientList.get(sWho); }
else { return null; }
}
/**
* Get the ClientInfo object for a person, or create a fake client info object.
*
* @param sHost Who can be any valid identifier for a client as long as it contains a nickname (?:)nick(?!ident)(?@host)
* @return ClientInfo Object for the client.
*/
public ClientInfo getClientInfoOrFake(final String sHost) {
final String sWho = getIRCStringConverter().toLowerCase(ClientInfo.parseHost(sHost));
if (hClientList.containsKey(sWho)) { return hClientList.get(sWho); }
else { return new ClientInfo(this, sHost).setFake(true); }
}
/**
* Get the ChannelInfo object for a channel.
*
* @param sWhat This is the name of the channel.
* @return ChannelInfo Object for the channel, or null
*/
public ChannelInfo getChannelInfo(String sWhat) {
synchronized (hChannelList) {
sWhat = getIRCStringConverter().toLowerCase(sWhat);
if (hChannelList.containsKey(sWhat)) { return hChannelList.get(sWhat); } else { return null; }
}
}
/**
* Send a line to the server.
*
* @param line Line to send (\r\n termination is added automatically)
*/
public void sendLine(final String line) { doSendString(line, false); }
/**
* Send a line to the server and add proper line ending.
*
* @param line Line to send (\r\n termination is added automatically)
*/
protected void sendString(final String line) { doSendString(line, true); }
/**
* Send a line to the server and add proper line ending.
*
* @param line Line to send (\r\n termination is added automatically)
* @param fromParser is this line from the parser? (used for callDataOut)
*/
protected void doSendString(final String line, final boolean fromParser) {
if (out == null) { return; }
callDataOut(line, fromParser);
out.printf("%s\r\n", line);
final String[] newLine = tokeniseLine(line);
if (newLine[0].equalsIgnoreCase("away") && newLine.length > 1) {
cMyself.setAwayReason(newLine[newLine.length-1]);
} else if (newLine[0].equalsIgnoreCase("mode") && newLine.length == 3) {
// This makes sure we don't add the same item to the LMQ twice, even if its requested twice,
// as the ircd will only reply once.
final LinkedList<Character> foundModes = new LinkedList<Character>();
final ChannelInfo channel = getChannelInfo(newLine[1]);
if (channel != null) {
final Queue<Character> listModeQueue = channel.getListModeQueue();
for (int i = 0; i < newLine[2].length() ; ++i) {
final Character mode = newLine[2].charAt(i);
callDebugInfo(DEBUG_LMQ, "Intercepted mode request for "+channel+" for mode "+mode);
if (hChanModesOther.containsKey(mode) && hChanModesOther.get(mode) == MODE_LIST) {
if (foundModes.contains(mode)) {
callDebugInfo(DEBUG_LMQ, "Already added to LMQ");
} else {
listModeQueue.offer(mode);
foundModes.offer(mode);
callDebugInfo(DEBUG_LMQ, "Added to LMQ");
}
}
}
}
}
}
/**
* Get the network name given in 005.
*
* @return network name from 005
*/
public String getNetworkName() {
return sNetworkName;
}
/**
* Get the server name given in 001.
*
* @return server name from 001
*/
public String getServerName() {
return sServerName;
}
/**
* Get the last line of input recieved from the server.
*
* @return the last line of input recieved from the server.
*/
public String getLastLine() {
return lastLine;
}
/**
* Process a line and call relevent methods for handling.
*
* @param line IRC Line to process
*/
protected void processLine(final String line) {
callDataIn(line);
final String[] token = tokeniseLine(line);
int nParam;
setPingNeeded(false);
// pingCountDown = pingCountDownLength;
if (token.length < 2) {
return;
}
try {
final String sParam = token[1];
if (token[0].equalsIgnoreCase("PING") || token[1].equalsIgnoreCase("PING")) {
sendString("PONG :" + sParam);
} else if (token[0].equalsIgnoreCase("PONG") || token[1].equalsIgnoreCase("PONG")) {
if (!lastPingValue.isEmpty() && lastPingValue.equals(token[token.length-1])) {
lastPingValue = "";
serverLag = System.currentTimeMillis() - pingTime;
callPingSuccess();
}
} else if (token[0].equalsIgnoreCase("ERROR")) {
final StringBuilder errorMessage = new StringBuilder();
for (int i = 1; i < token.length; ++i) { errorMessage.append(token[i]); }
callServerError(errorMessage.toString());
} else {
if (got001) {
// Freenode sends a random notice in a stupid place, others might do aswell
// These shouldn't cause post005 to be fired, so handle them here.
if (token[0].equalsIgnoreCase("NOTICE")) {
try { myProcessingManager.process("Notice Auth", token); } catch (ProcessorNotFoundException e) { }
return;
}
if (!post005) {
try { nParam = Integer.parseInt(token[1]); } catch (NumberFormatException e) { nParam = -1; }
if (nParam < 0 || nParam > 5) {
callPost005();
}
}
// After 001 we potentially care about everything!
try { myProcessingManager.process(sParam, token); }
catch (ProcessorNotFoundException e) { }
} else {
// Before 001 we don't care about much.
try { nParam = Integer.parseInt(token[1]); } catch (NumberFormatException e) { nParam = -1; }
switch (nParam) {
case 1: // 001 - Welcome to IRC
case 464: // Password Required
case 433: // Nick In Use
try { myProcessingManager.process(sParam, token); } catch (ProcessorNotFoundException e) { }
break;
default: // Unknown - Send to Notice Auth
// Some networks send a CTCP during the auth process, handle it
if (token.length > 3 && !token[3].isEmpty() && token[3].charAt(0) == (char)1 && token[3].charAt(token[3].length()-1) == (char)1) {
try { myProcessingManager.process(sParam, token); } catch (ProcessorNotFoundException e) { }
break;
}
// Otherwise, send to Notice Auth
try { myProcessingManager.process("Notice Auth", token); } catch (ProcessorNotFoundException e) { }
break;
}
}
}
} catch (Exception e) {
final ParserError ei = new ParserError(ParserError.ERROR_FATAL, "Fatal Exception in Parser.", lastLine);
ei.setException(e);
callErrorInfo(ei);
}
}
/** The IRCStringConverter for this parser */
private IRCStringConverter stringConverter = null;
/**
* Get the IRCStringConverter used by this parser.
*
* @return the IRCStringConverter used by this parser. (will create a default
* one if none exists already);
*/
public IRCStringConverter getIRCStringConverter() {
if (stringConverter == null) {
stringConverter = new IRCStringConverter((byte)4);
}
return stringConverter;
}
/**
* Update the character arrays.
*
* @param limit Number of post-alphabetical characters to convert
* 0 = ascii encoding
* 3 = strict-rfc1459 encoding
* 4 = rfc1459 encoding
*/
protected void updateCharArrays(final byte limit) {
stringConverter = new IRCStringConverter(limit);
}
/**
* Get the known boolean chanmodes in 005 order.
* Modes are returned in the order that the ircd specifies the modes in 005
* with any newly-found modes (mode being set that wasn't specified in 005)
* being added at the end.
*
* @return All the currently known boolean modes
*/
public String getBoolChanModes005() {
// This code isn't the nicest, as Hashtable's don't lend themselves to being
// ordered.
// Order isn't really important, and this code only takes 3 lines of we
// don't care about it but ordered guarentees that on a specific ircd this
// method will ALWAYs return the same value.
final char[] modes = new char[hChanModesBool.size()];
long nTemp;
double pos;
for (char cTemp : hChanModesBool.keySet()) {
nTemp = hChanModesBool.get(cTemp);
// nTemp should never be less than 0
if (nTemp > 0) {
pos = Math.log(nTemp) / Math.log(2);
modes[(int)pos] = cTemp;
}
/* // Is there an easier way to find out the power of 2 value for a number?
// ie 1024 = 10, 512 = 9 ?
for (int i = 0; i < modes.length; i++) {
if (Math.pow(2, i) == (double) nTemp) {
modes[i] = cTemp;
break;
}
}*/
}
return new String(modes);
}
/**
* Process CHANMODES from 005.
*/
public void parseChanModes() {
final StringBuilder sDefaultModes = new StringBuilder("b,k,l,");
String[] bits = null;
String modeStr;
if (h005Info.containsKey("USERCHANMODES")) {
if (getIRCD(true).equalsIgnoreCase("dancer")) {
sDefaultModes.insert(0, "dqeI");
} else if (getIRCD(true).equalsIgnoreCase("austirc")) {
sDefaultModes.insert(0, "e");
}
modeStr = h005Info.get("USERCHANMODES");
char mode;
for (int i = 0; i < modeStr.length(); ++i) {
mode = modeStr.charAt(i);
if (!hPrefixModes.containsKey(mode) && sDefaultModes.indexOf(Character.toString(mode)) < 0) {
sDefaultModes.append(mode);
}
}
} else {
sDefaultModes.append("imnpstrc");
}
if (h005Info.containsKey("CHANMODES")) {
modeStr = h005Info.get("CHANMODES");
} else {
modeStr = sDefaultModes.toString();
h005Info.put("CHANMODES", modeStr);
}
bits = modeStr.split(",", 5);
if (bits.length < 4) {
modeStr = sDefaultModes.toString();
callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "CHANMODES String not valid. Using default string of \"" + modeStr + "\""));
h005Info.put("CHANMODES", modeStr);
bits = modeStr.split(",", 5);
}
// resetState
hChanModesOther.clear();
hChanModesBool.clear();
nNextKeyCMBool = 1;
// List modes.
for (int i = 0; i < bits[0].length(); ++i) {
final Character cMode = bits[0].charAt(i);
callDebugInfo(DEBUG_INFO, "Found List Mode: %c", cMode);
if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode, MODE_LIST); }
}
// Param for Set and Unset.
final Byte nBoth = MODE_SET + MODE_UNSET;
for (int i = 0; i < bits[1].length(); ++i) {
final Character cMode = bits[1].charAt(i);
callDebugInfo(DEBUG_INFO, "Found Set/Unset Mode: %c", cMode);
if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode, nBoth); }
}
// Param just for Set
for (int i = 0; i < bits[2].length(); ++i) {
final Character cMode = bits[2].charAt(i);
callDebugInfo(DEBUG_INFO, "Found Set Only Mode: %c", cMode);
if (!hChanModesOther.containsKey(cMode)) { hChanModesOther.put(cMode, MODE_SET); }
}
// Boolean Mode
for (int i = 0; i < bits[3].length(); ++i) {
final Character cMode = bits[3].charAt(i);
callDebugInfo(DEBUG_INFO, "Found Boolean Mode: %c [%d]", cMode, nNextKeyCMBool);
if (!hChanModesBool.containsKey(cMode)) {
hChanModesBool.put(cMode, nNextKeyCMBool);
nNextKeyCMBool = nNextKeyCMBool * 2;
}
}
}
/**
* Get the known prefixmodes in priority order.
*
* @return All the currently known usermodes
*/
public String getPrefixModes() {
if (h005Info.containsKey("PREFIXSTRING")) {
return h005Info.get("PREFIXSTRING");
} else {
return "";
}
}
/**
* Get the known boolean chanmodes in alphabetical order.
* Modes are returned in alphabetic order
*
* @return All the currently known boolean modes
*/
public String getBoolChanModes() {
final char[] modes = new char[hChanModesBool.size()];
int i = 0;
for (char mode : hChanModesBool.keySet()) {
modes[i++] = mode;
}
// Alphabetically sort the array
Arrays.sort(modes);
return new String(modes);
}
/**
* Get the known List chanmodes.
* Modes are returned in alphabetical order
*
* @return All the currently known List modes
*/
public String getListChanModes() {
return getOtherModeString(MODE_LIST);
}
/**
* Get the known Set-Only chanmodes.
* Modes are returned in alphabetical order
*
* @return All the currently known Set-Only modes
*/
public String getSetOnlyChanModes() {
return getOtherModeString(MODE_SET);
}
/**
* Get the known Set-Unset chanmodes.
* Modes are returned in alphabetical order
*
* @return All the currently known Set-Unset modes
*/
public String getSetUnsetChanModes() {
return getOtherModeString((byte) (MODE_SET + MODE_UNSET));
}
/**
* Get modes from hChanModesOther that have a specific value.
* Modes are returned in alphabetical order
*
* @param nValue Value mode must have to be included
* @return All the currently known Set-Unset modes
*/
protected String getOtherModeString(final byte nValue) {
final char[] modes = new char[hChanModesOther.size()];
Byte nTemp;
int i = 0;
for (char cTemp : hChanModesOther.keySet()) {
nTemp = hChanModesOther.get(cTemp);
if (nTemp == nValue) { modes[i++] = cTemp; }
}
// Alphabetically sort the array
Arrays.sort(modes);
return new String(modes).trim();
}
/**
* Get the known usermodes.
* Modes are returned in the order specified by the ircd.
*
* @return All the currently known usermodes (returns "" if usermodes are unknown)
*/
public String getUserModeString() {
if (h005Info.containsKey("USERMODES")) {
return h005Info.get("USERMODES");
} else {
return "";
}
}
/**
* Process USERMODES from 004.
*/
protected void parseUserModes() {
final String sDefaultModes = "nwdoi";
String modeStr;
if (h005Info.containsKey("USERMODES")) {
modeStr = h005Info.get("USERMODES");
} else {
modeStr = sDefaultModes;
h005Info.put("USERMODES", sDefaultModes);
}
// resetState
hUserModes.clear();
nNextKeyUser = 1;
// Boolean Mode
for (int i = 0; i < modeStr.length(); ++i) {
final Character cMode = modeStr.charAt(i);
callDebugInfo(DEBUG_INFO, "Found User Mode: %c [%d]", cMode, nNextKeyUser);
if (!hUserModes.containsKey(cMode)) {
hUserModes.put(cMode, nNextKeyUser);
nNextKeyUser = nNextKeyUser * 2;
}
}
}
/**
* Process CHANTYPES from 005.
*/
protected void parseChanPrefix() {
final String sDefaultModes = "#&";
String modeStr;
if (h005Info.containsKey("CHANTYPES")) {
modeStr = h005Info.get("CHANTYPES");
} else {
modeStr = sDefaultModes;
h005Info.put("CHANTYPES", sDefaultModes);
}
// resetState
hChanPrefix.clear();
// Boolean Mode
for (int i = 0; i < modeStr.length(); ++i) {
final Character cMode = modeStr.charAt(i);
callDebugInfo(DEBUG_INFO, "Found Chan Prefix: %c", cMode);
if (!hChanPrefix.containsKey(cMode)) { hChanPrefix.put(cMode, true); }
}
}
/**
* Process PREFIX from 005.
*/
public void parsePrefixModes() {
final String sDefaultModes = "(ohv)@%+";
String[] bits;
String modeStr;
if (h005Info.containsKey("PREFIX")) {
modeStr = h005Info.get("PREFIX");
} else {
modeStr = sDefaultModes;
}
if (modeStr.substring(0, 1).equals("(")) {
modeStr = modeStr.substring(1);
} else {
modeStr = sDefaultModes.substring(1);
h005Info.put("PREFIX", sDefaultModes);
}
bits = modeStr.split("\\)", 2);
if (bits.length != 2 || bits[0].length() != bits[1].length()) {
modeStr = sDefaultModes;
callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "PREFIX String not valid. Using default string of \"" + modeStr + "\""));
h005Info.put("PREFIX", modeStr);
modeStr = modeStr.substring(1);
bits = modeStr.split("\\)", 2);
}
// resetState
hPrefixModes.clear();
hPrefixMap.clear();
nNextKeyPrefix = 1;
for (int i = bits[0].length() - 1; i > -1; --i) {
final Character cMode = bits[0].charAt(i);
final Character cPrefix = bits[1].charAt(i);
callDebugInfo(DEBUG_INFO, "Found Prefix Mode: %c => %c [%d]", cMode, cPrefix, nNextKeyPrefix);
if (!hPrefixModes.containsKey(cMode)) {
hPrefixModes.put(cMode, nNextKeyPrefix);
hPrefixMap.put(cMode, cPrefix);
hPrefixMap.put(cPrefix, cMode);
nNextKeyPrefix = nNextKeyPrefix * 2;
}
}
h005Info.put("PREFIXSTRING", bits[0]);
}
/**
* Check if server is ready.
*
* @return true if 001 has been recieved, false otherwise.
*/
public boolean isReady() { return got001; }
/**
* Join a Channel.
*
* @param sChannelName Name of channel to join
*/
public void joinChannel(final String sChannelName) {
joinChannel(sChannelName, "", true);
}
/**
* Join a Channel.
*
* @param sChannelName Name of channel to join
* @param autoPrefix Automatically prepend the first channel prefix defined
* in 005 if sChannelName is an invalid channel.
* **This only applies to the first channel if given a list**
*/
public void joinChannel(final String sChannelName, final boolean autoPrefix) {
joinChannel(sChannelName, "", autoPrefix);
}
/**
* Join a Channel with a key.
*
* @param sChannelName Name of channel to join
* @param sKey Key to use to try and join the channel
*/
public void joinChannel(final String sChannelName, final String sKey) {
joinChannel(sChannelName, sKey, true);
}
/**
* Join a Channel with a key.
*
* @param sChannelName Name of channel to join
* @param sKey Key to use to try and join the channel
* @param autoPrefix Automatically prepend the first channel prefix defined
* in 005 if sChannelName is an invalid channel.
* **This only applies to the first channel if given a list**
*/
public void joinChannel(final String sChannelName, final String sKey, final boolean autoPrefix) {
final String channelName;
if (isValidChannelName(sChannelName)) {
channelName = sChannelName;
} else {
if (autoPrefix) {
if (h005Info.containsKey("CHANTYPES")) {
final String chantypes = h005Info.get("CHANTYPES");
if (chantypes.isEmpty()) {
channelName = "#" + sChannelName;
} else {
channelName = chantypes.charAt(0) + sChannelName;
}
} else {
return;
}
} else {
return;
}
}
if (sKey.isEmpty()) {
sendString("JOIN " + channelName);
} else {
sendString("JOIN " + channelName + " " + sKey);
}
}
/**
* Leave a Channel.
*
* @param sChannelName Name of channel to part
* @param sReason Reason for leaving (Nothing sent if sReason is "")
*/
public void partChannel(final String sChannelName, final String sReason) {
if (getChannelInfo(sChannelName) == null) { return; }
if (sReason.isEmpty()) {
sendString("PART " + sChannelName);
} else {
sendString("PART " + sChannelName + " :" + sReason);
}
}
/**
* Set Nickname.
*
* @param sNewNickName New nickname wanted.
*/
public void setNickname(final String sNewNickName) {
if (getSocketState() == STATE_OPEN) {
if (!cMyself.isFake() && cMyself.getNickname().equals(sNewNickName)) {
return;
}
sendString("NICK " + sNewNickName);
} else {
me.setNickname(sNewNickName);
}
sThinkNickname = sNewNickName;
}
/**
* Get the max length a message can be.
*
* @param sType Type of message (ie PRIVMSG)
* @param sTarget Target for message (eg #DMDirc)
* @return Max Length message should be.
*/
public int getMaxLength(final String sType, final String sTarget) {
// If my host is "nick!user@host" and we are sending "#Channel"
// a "PRIVMSG" this will find the length of ":nick!user@host PRIVMSG #channel :"
// and subtract it from the MAX_LINELENGTH. This should be sufficient in most cases.
// Lint = the 2 ":" at the start and end and the 3 separating " "s
int length = 0;
if (sType != null) { length = length + sType.length(); }
if (sTarget != null) { length = length + sTarget.length(); }
return getMaxLength(length);
}
/**
* Get the max length a message can be.
*
* @param nLength Length of stuff. (Ie "PRIVMSG"+"#Channel")
* @return Max Length message should be.
*/
public int getMaxLength(final int nLength) {
final int lineLint = 5;
if (cMyself.isFake()) {
callErrorInfo(new ParserError(ParserError.ERROR_ERROR + ParserError.ERROR_USER, "getMaxLength() called, but I don't know who I am?", lastLine));
return MAX_LINELENGTH - nLength - lineLint;
} else {
return MAX_LINELENGTH - cMyself.toString().length() - nLength - lineLint;
}
}
/**
* Get the max number of list modes.
*
* @param mode The mode to know the max number for
* @return The max number of list modes for the given mode.
* - returns 0 if MAXLIST does not contain the mode, unless MAXBANS is
* set, then this is returned instead.
* - returns -1 if:
* - MAXLIST or MAXBANS were not in 005
* - Values for MAXLIST or MAXBANS were invalid (non integer, empty)
*/
public int getMaxListModes(final char mode) {
// MAXLIST=bdeI:50
// MAXLIST=b:60,e:60,I:60
// MAXBANS=30
int result = -2;
callDebugInfo(DEBUG_INFO, "Looking for maxlistmodes for: "+mode);
// Try in MAXLIST
if (h005Info.get("MAXLIST") != null) {
if (h005Info.get("MAXBANS") == null) {
result = 0;
}
final String maxlist = h005Info.get("MAXLIST");
callDebugInfo(DEBUG_INFO, "Found maxlist ("+maxlist+")");
final String[] bits = maxlist.split(",");
for (String bit : bits) {
final String[] parts = bit.split(":", 2);
callDebugInfo(DEBUG_INFO, "Bit: "+bit+" | parts.length = "+parts.length+" ("+parts[0]+" -> "+parts[0].indexOf(mode)+")");
if (parts.length == 2 && parts[0].indexOf(mode) > -1) {
callDebugInfo(DEBUG_INFO, "parts[0] = '"+parts[0]+"' | parts[1] = '"+parts[1]+"'");
try {
result = Integer.parseInt(parts[1]);
break;
} catch (NumberFormatException nfe) { result = -1; }
}
}
}
// If not in max list, try MAXBANS
if (result == -2 && h005Info.get("MAXBANS") != null) {
callDebugInfo(DEBUG_INFO, "Trying max bans");
try {
result = Integer.parseInt(h005Info.get("MAXBANS"));
} catch (NumberFormatException nfe) { result = -1; }
} else if (result == -2) {
result = -1;
callDebugInfo(DEBUG_INFO, "Failed");
callErrorInfo(new ParserError(ParserError.ERROR_ERROR, "Unable to discover max list modes."));
}
callDebugInfo(DEBUG_INFO, "Result: "+result);
return result;
}
/**
* Send a private message to a target.
*
* @param sTarget Target
* @param sMessage Message to send
*/
public void sendMessage(final String sTarget, final String sMessage) {
if (sTarget == null || sMessage == null) { return; }
if (sTarget.isEmpty()/* || sMessage.isEmpty()*/) { return; }
sendString("PRIVMSG " + sTarget + " :" + sMessage);
}
/**
* Send a notice message to a target.
*
* @param sTarget Target
* @param sMessage Message to send
*/
public void sendNotice(final String sTarget, final String sMessage) {
if (sTarget == null || sMessage == null) { return; }
if (sTarget.isEmpty()/* || sMessage.isEmpty()*/) { return; }
sendString("NOTICE " + sTarget + " :" + sMessage);
}
/**
* Send a Action to a target.
*
* @param sTarget Target
* @param sMessage Action to send
*/
public void sendAction(final String sTarget, final String sMessage) {
sendCTCP(sTarget, "ACTION", sMessage);
}
/**
* Send a CTCP to a target.
*
* @param sTarget Target
* @param sType Type of CTCP
* @param sMessage Optional Additional Parameters
*/
public void sendCTCP(final String sTarget, final String sType, final String sMessage) {
if (sTarget == null || sMessage == null) { return; }
if (sTarget.isEmpty() || sType.isEmpty()) { return; }
final char char1 = (char) 1;
sendString("PRIVMSG " + sTarget + " :" + char1 + sType.toUpperCase() + " " + sMessage + char1);
}
/**
* Send a CTCPReply to a target.
*
* @param sTarget Target
* @param sType Type of CTCP
* @param sMessage Optional Additional Parameters
*/
public void sendCTCPReply(final String sTarget, final String sType, final String sMessage) {
if (sTarget == null || sMessage == null) { return; }
if (sTarget.isEmpty() || sType.isEmpty()) { return; }
final char char1 = (char) 1;
sendString("NOTICE " + sTarget + " :" + char1 + sType.toUpperCase() + " " + sMessage + char1);
}
/**
* Quit IRC.
* This method will wait for the server to close the socket.
*
* @param sReason Reason for quitting.
*/
public void quit(final String sReason) {
if (sReason.isEmpty()) {
sendString("QUIT");
} else {
sendString("QUIT :" + sReason);
}
}
/**
* Disconnect from server.
* This method will quit and automatically close the socket without waiting for
* the server.
*
* @param sReason Reason for quitting.
*/
public void disconnect(final String sReason) {
if (currentSocketState == STATE_OPEN && got001) { quit(sReason); }
try {
if (socket != null) { socket.close(); }
} catch (IOException e) {
/* Do Nothing */
} finally {
if (currentSocketState != STATE_CLOSED) {
currentSocketState = STATE_CLOSED;
callSocketClosed();
}
resetState();
}
}
/**
* Check if a channel name is valid.
*
* @param sChannelName Channel name to test
* @return true if name is valid on the current connection, false otherwise.
* - Before channel prefixes are known (005/noMOTD/MOTDEnd), this checks
* that the first character is either #, &, ! or +
* - Assumes that any channel that is already known is valid, even if
* 005 disagrees.
*/
public boolean isValidChannelName(final String sChannelName) {
// Check sChannelName is not empty or null
if (sChannelName == null || sChannelName.isEmpty()) { return false; }
// Check its not ourself (PM recieved before 005)
if (getIRCStringConverter().equalsIgnoreCase(getMyNickname(), sChannelName)) { return false; }
// Check if we are already on this channel
if (getChannelInfo(sChannelName) != null) { return true; }
// Check if we know of any valid chan prefixes
if (hChanPrefix.isEmpty()) {
// We don't. Lets check against RFC2811-Specified channel types
final char first = sChannelName.charAt(0);
return first == '#' || first == '&' || first == '!' || first == '+';
}
// Otherwise return true if:
// Channel equals "0"
// first character of the channel name is a valid channel prefix.
return hChanPrefix.containsKey(sChannelName.charAt(0)) || sChannelName.equals("0");
}
/**
* Check if a given chanmode is user settable.
*
* @param mode Mode to test
* @return true if mode is settable by users, false if servers only
*/
public boolean isUserSettable(final Character mode) {
String validmodes;
if (h005Info.containsKey("USERCHANMODES")) {
validmodes = h005Info.get("USERCHANMODES");
} else {
validmodes = "bklimnpstrc";
}
return validmodes.matches(".*" + mode + ".*");
}
/**
* Get the 005 info.
*
* @return 005Info hashtable.
*/
public Map<String, String> get005() { return h005Info; }
/**
* Get the name of the ircd.
*
* @param getType if this is false the string from 004 is returned. Else a guess of the type (ircu, hybrid, ircnet)
* @return IRCD Version or Type
*/
public String getIRCD(final boolean getType) {
if (h005Info.containsKey("004IRCD")) {
final String version = h005Info.get("004IRCD");
if (getType) {
// This ilst is vaugly based on http://searchirc.com/ircd-versions,
// but keeping groups of ircd's together (ie hybrid-based, ircu-based)
if (version.matches("(?i).*unreal.*")) { return "unreal"; }
else if (version.matches("(?i).*bahamut.*")) { return "bahamut"; }
else if (version.matches("(?i).*nefarious.*")) { return "nefarious"; }
else if (version.matches("(?i).*asuka.*")) { return "asuka"; }
else if (version.matches("(?i).*snircd.*")) { return "snircd"; }
else if (version.matches("(?i).*beware.*")) { return "bircd"; }
else if (version.matches("(?i).*u2\\.[0-9]+\\.H\\..*")) { return "irchispano"; }
else if (version.matches("(?i).*u2\\.[0-9]+\\..*")) { return "ircu"; }
else if (version.matches("(?i).*ircu.*")) { return "ircu"; }
else if (version.matches("(?i).*plexus.*")) { return "plexus"; }
else if (version.matches("(?i).*ircd.hybrid.*")) { return "hybrid7"; }
else if (version.matches("(?i).*hybrid.*")) { return "hybrid"; }
else if (version.matches("(?i).*charybdis.*")) { return "charybdis"; }
else if (version.matches("(?i).*inspircd.*")) { return "inspircd"; }
else if (version.matches("(?i).*ultimateircd.*")) { return "ultimateircd"; }
else if (version.matches("(?i).*critenircd.*")) { return "critenircd"; }
else if (version.matches("(?i).*fqircd.*")) { return "fqircd"; }
else if (version.matches("(?i).*conferenceroom.*")) { return "conferenceroom"; }
else if (version.matches("(?i).*hyperion.*")) { return "hyperion"; }
else if (version.matches("(?i).*dancer.*")) { return "dancer"; }
else if (version.matches("(?i).*austhex.*")) { return "austhex"; }
else if (version.matches("(?i).*austirc.*")) { return "austirc"; }
else if (version.matches("(?i).*ratbox.*")) { return "ratbox"; }
else {
// Stupid networks/ircds go here...
if (sNetworkName.equalsIgnoreCase("ircnet")) { return "ircnet"; }
else if (sNetworkName.equalsIgnoreCase("starchat")) { return "starchat"; }
else if (sNetworkName.equalsIgnoreCase("bitlbee")) { return "bitlbee"; }
else if (h005Info.containsKey("003IRCD") && h005Info.get("003IRCD").matches("(?i).*bitlbee.*")) { return "bitlbee"; } // Older bitlbee
else { return "generic"; }
}
} else {
return version;
}
} else {
if (getType) { return "generic"; }
else { return ""; }
}
}
/**
* Get the time used for the ping Timer.
*
* @return current time used.
* @see setPingCountDownLength
*/
public long getPingTimerLength() { return pingTimerLength; }
/**
* Set the time used for the ping Timer.
* This will also reset the pingTimer.
*
* @param newValue New value to use.
* @see setPingCountDownLength
*/
public void setPingTimerLength(final long newValue) {
pingTimerLength = newValue;
startPingTimer();
}
/**
* Get the time used for the pingCountdown.
*
* @return current time used.
* @see setPingCountDownLength
*/
public byte getPingCountDownLength() { return pingCountDownLength; }
/**
* Set the time used for the ping countdown.
* The pingTimer fires every pingTimerLength/1000 seconds, whenever a line of data
* is received, the "waiting for ping" flag is set to false, if the line is
* a "PONG", then onPingSuccess is also called.
*
* When waiting for a ping reply, onPingFailed() is called every time the
* timer is fired.
*
* When not waiting for a ping reply, the pingCountDown is decreased by 1
* every time the timer fires, when it reaches 0 is is reset to
* pingCountDownLength and a PING is sent to the server.
*
* To ping the server after 30 seconds of inactivity you could use:
* pingTimerLength = 5000, pingCountDown = 6
* or
* pingTimerLength = 10000, pingCountDown = 3
*
* @param newValue New value to use.
* @see pingCountDown
* @see pingTimerLength
* @see pingTimerTask
*/
public void setPingCountDownLength(final byte newValue) {
pingCountDownLength = newValue;
}
/**
* Start the pingTimer.
*/
protected void startPingTimer() {
setPingNeeded(false);
if (pingTimer != null) { pingTimer.cancel(); }
pingTimer = new Timer("IRCParser pingTimer");
pingTimer.schedule(new PingTimer(this, pingTimer), 0, pingTimerLength);
pingCountDown = 1;
}
/**
* This is called when the ping Timer has been executed.
* As the timer is restarted on every incomming message, this will only be
* called when there has been no incomming line for 10 seconds.
*
* @param timer The timer that called this.
*/
protected void pingTimerTask(final Timer timer) {
if (pingTimer == null || !pingTimer.equals(timer)) { return; }
if (getPingNeeded()) {
if (!callPingFailed()) {
pingTimer.cancel();
disconnect("Server not responding.");
}
} else {
--pingCountDown;
if (pingCountDown < 1) {
pingTime = System.currentTimeMillis();
setPingNeeded(true);
pingCountDown = pingCountDownLength;
callPingSent();
lastPingValue = String.valueOf(System.currentTimeMillis());
sendLine("PING " + lastPingValue);
}
}
}
/**
* Get the current server lag.
*
* @return Last time between sending a PING and recieving a PONG
*/
public long getServerLag() {
return serverLag;
}
/**
* Get the current server lag.
*
* @param actualTime if True the value returned will be the actual time the ping was sent
* else it will be the amount of time sinse the last ping was sent.
* @return Time last ping was sent
*/
public long getPingTime(final boolean actualTime) {
if (actualTime) { return pingTime; }
else { return System.currentTimeMillis() - pingTime; }
}
/**
* Set if a ping is needed or not.
*
* @param newStatus new value to set pingNeeded to.
*/
private void setPingNeeded(final boolean newStatus) {
synchronized (pingNeeded) {
pingNeeded = newStatus;
}
}
/**
* Get if a ping is needed or not.
*
* @return value of pingNeeded.
*/
private boolean getPingNeeded() {
synchronized (pingNeeded) {
return pingNeeded;
}
}
/**
* Get a reference to the cMyself object.
*
* @return cMyself reference
*/
public synchronized ClientInfo getMyself() { return cMyself; }
/**
* Get the current nickname.
* If after 001 this returns the exact same as getMyself.getNickname();
* Before 001 it returns the nickname that the parser Thinks it has.
*
* @return Current nickname.
*/
public String getMyNickname() {
if (cMyself.isFake()) {
return sThinkNickname;
} else {
return cMyself.getNickname();
}
}
/**
* Get the current username (Specified in MyInfo on construction).
* Get the username given in MyInfo
*
* @return My username.
*/
public String getMyUsername() {
return me.getUsername();
}
/**
* Add a client to the ClientList.
*
* @param client Client to add
*/
public void addClient(final ClientInfo client) {
hClientList.put(getIRCStringConverter().toLowerCase(client.getNickname()),client);
}
/**
* Remove a client from the ClientList.
* This WILL NOT allow cMyself to be removed from the list.
*
* @param client Client to remove
*/
public void removeClient(final ClientInfo client) {
if (client != cMyself) {
forceRemoveClient(client);
}
}
/**
* Remove a client from the ClientList.
. * This WILL allow cMyself to be removed from the list
*
* @param client Client to remove
*/
protected void forceRemoveClient(final ClientInfo client) {
hClientList.remove(getIRCStringConverter().toLowerCase(client.getNickname()));
}
/**
* Get the number of known clients.
*
* @return Count of known clients
*/
public int knownClients() {
return hClientList.size();
}
/**
* Get the known clients as a collection.
*
* @return Known clients as a collection
*/
public Collection<ClientInfo> getClients() {
return hClientList.values();
}
/**
* Clear the client list.
*/
public void clearClients() {
hClientList.clear();
addClient(getMyself());
}
/**
* Add a channel to the ChannelList.
*
* @param channel Channel to add
*/
public void addChannel(final ChannelInfo channel) {
synchronized (hChannelList) {
hChannelList.put(getIRCStringConverter().toLowerCase(channel.getName()), channel);
}
}
/**
* Remove a channel from the ChannelList.
*
* @param channel Channel to remove
*/
public void removeChannel(final ChannelInfo channel) {
synchronized (hChannelList) {
hChannelList.remove(getIRCStringConverter().toLowerCase(channel.getName()));
}
}
/**
* Get the number of known channel.
*
* @return Count of known channel
*/
public int knownChannels() {
synchronized (hChannelList) {
return hChannelList.size();
}
}
/**
* Get the known channels as a collection.
*
* @return Known channels as a collection
*/
public Collection<ChannelInfo> getChannels() {
synchronized (hChannelList) {
return hChannelList.values();
}
}
/**
* Clear the channel list.
*/
public void clearChannels() {
synchronized (hChannelList) {
hChannelList.clear();
}
}
}
| true | true | private void connect() throws UnknownHostException, IOException, NoSuchAlgorithmException, KeyManagementException {
resetState();
callDebugInfo(DEBUG_SOCKET, "Connecting to " + server.getHost() + ":" + server.getPort());
if (server.getPort() > 65535 || server.getPort() <= 0) {
throw new IOException("Server port ("+server.getPort()+") is invalid.");
}
if (server.getUseSocks()) {
callDebugInfo(DEBUG_SOCKET, "Using Proxy");
if (bindIP != null && !bindIP.isEmpty()) {
callDebugInfo(DEBUG_SOCKET, "IP Binding is not possible when using a proxy.");
}
if (server.getProxyPort() > 65535 || server.getProxyPort() <= 0) {
throw new IOException("Proxy port ("+server.getProxyPort()+") is invalid.");
}
final Proxy.Type proxyType = Proxy.Type.SOCKS;
socket = new Socket(new Proxy(proxyType, new InetSocketAddress(server.getProxyHost(), server.getProxyPort())));
if (server.getProxyUser() != null && !server.getProxyUser().isEmpty()) {
IRCAuthenticator.getIRCAuthenticator().add(server);
}
socket.connect(new InetSocketAddress(server.getHost(), server.getPort()));
} else {
callDebugInfo(DEBUG_SOCKET, "Not using Proxy");
if (!server.getSSL()) {
if (bindIP == null || bindIP.isEmpty()) {
socket = new Socket(server.getHost(), server.getPort());
} else {
callDebugInfo(DEBUG_SOCKET, "Binding to IP: "+bindIP);
try {
socket = new Socket(server.getHost(), server.getPort(), InetAddress.getByName(bindIP), 0);
} catch (IOException e) {
callDebugInfo(DEBUG_SOCKET, "Binding failed: "+e.getMessage());
socket = new Socket(server.getHost(), server.getPort());
}
}
}
}
if (server.getSSL()) {
callDebugInfo(DEBUG_SOCKET, "Server is SSL.");
if (myTrustManager == null) { myTrustManager = trustAllCerts; }
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, myTrustManager, new java.security.SecureRandom());
final SSLSocketFactory socketFactory = sc.getSocketFactory();
if (server.getUseSocks()) {
socket = socketFactory.createSocket(socket, server.getHost(), server.getPort(), false);
} else {
if (bindIP == null || bindIP.isEmpty()) {
socket = socketFactory.createSocket(server.getHost(), server.getPort());
} else {
callDebugInfo(DEBUG_SOCKET, "Binding to IP: "+bindIP);
try {
socket = socketFactory.createSocket(server.getHost(), server.getPort(), InetAddress.getByName(bindIP), 0);
} catch (UnknownHostException e) {
callDebugInfo(DEBUG_SOCKET, "Bind failed: "+e.getMessage());
socket = socketFactory.createSocket(server.getHost(), server.getPort());
}
}
}
}
callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket output stream PrintWriter");
out = new PrintWriter(socket.getOutputStream(), true);
currentSocketState = STATE_OPEN;
callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket input stream BufferedReader");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
callDebugInfo(DEBUG_SOCKET, "\t-> Socket Opened");
}
| private void connect() throws UnknownHostException, IOException, NoSuchAlgorithmException, KeyManagementException {
resetState();
callDebugInfo(DEBUG_SOCKET, "Connecting to " + server.getHost() + ":" + server.getPort());
if (server.getPort() > 65535 || server.getPort() <= 0) {
throw new IOException("Server port ("+server.getPort()+") is invalid.");
}
if (server.getUseSocks()) {
callDebugInfo(DEBUG_SOCKET, "Using Proxy");
if (bindIP != null && !bindIP.isEmpty()) {
callDebugInfo(DEBUG_SOCKET, "IP Binding is not possible when using a proxy.");
}
if (server.getProxyPort() > 65535 || server.getProxyPort() <= 0) {
throw new IOException("Proxy port ("+server.getProxyPort()+") is invalid.");
}
final Proxy.Type proxyType = Proxy.Type.SOCKS;
socket = new Socket(new Proxy(proxyType, new InetSocketAddress(server.getProxyHost(), server.getProxyPort())));
if (server.getProxyUser() != null && !server.getProxyUser().isEmpty()) {
IRCAuthenticator.getIRCAuthenticator().addAuthentication(server);
}
socket.connect(new InetSocketAddress(server.getHost(), server.getPort()));
} else {
callDebugInfo(DEBUG_SOCKET, "Not using Proxy");
if (!server.getSSL()) {
if (bindIP == null || bindIP.isEmpty()) {
socket = new Socket(server.getHost(), server.getPort());
} else {
callDebugInfo(DEBUG_SOCKET, "Binding to IP: "+bindIP);
try {
socket = new Socket(server.getHost(), server.getPort(), InetAddress.getByName(bindIP), 0);
} catch (IOException e) {
callDebugInfo(DEBUG_SOCKET, "Binding failed: "+e.getMessage());
socket = new Socket(server.getHost(), server.getPort());
}
}
}
}
if (server.getSSL()) {
callDebugInfo(DEBUG_SOCKET, "Server is SSL.");
if (myTrustManager == null) { myTrustManager = trustAllCerts; }
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, myTrustManager, new java.security.SecureRandom());
final SSLSocketFactory socketFactory = sc.getSocketFactory();
if (server.getUseSocks()) {
socket = socketFactory.createSocket(socket, server.getHost(), server.getPort(), false);
} else {
if (bindIP == null || bindIP.isEmpty()) {
socket = socketFactory.createSocket(server.getHost(), server.getPort());
} else {
callDebugInfo(DEBUG_SOCKET, "Binding to IP: "+bindIP);
try {
socket = socketFactory.createSocket(server.getHost(), server.getPort(), InetAddress.getByName(bindIP), 0);
} catch (UnknownHostException e) {
callDebugInfo(DEBUG_SOCKET, "Bind failed: "+e.getMessage());
socket = socketFactory.createSocket(server.getHost(), server.getPort());
}
}
}
}
callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket output stream PrintWriter");
out = new PrintWriter(socket.getOutputStream(), true);
currentSocketState = STATE_OPEN;
callDebugInfo(DEBUG_SOCKET, "\t-> Opening socket input stream BufferedReader");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
callDebugInfo(DEBUG_SOCKET, "\t-> Socket Opened");
}
|
diff --git a/src/ibis/satin/impl/Stats.java b/src/ibis/satin/impl/Stats.java
index 01939753..156a5033 100644
--- a/src/ibis/satin/impl/Stats.java
+++ b/src/ibis/satin/impl/Stats.java
@@ -1,725 +1,726 @@
/* $Id$ */
package ibis.satin.impl;
import ibis.util.Timer;
public abstract class Stats extends SharedObjects {
protected StatsMessage createStats() {
StatsMessage s = new StatsMessage();
s.spawns = spawns;
s.jobsExecuted = jobsExecuted;
s.syncs = syncs;
s.aborts = aborts;
s.abortMessages = abortMessages;
s.abortedJobs = abortedJobs;
s.stealAttempts = stealAttempts;
s.stealSuccess = stealSuccess;
s.tupleMsgs = tupleMsgs;
s.tupleBytes = tupleBytes;
s.stolenJobs = stolenJobs;
s.stealRequests = stealRequests;
s.interClusterMessages = interClusterMessages;
s.intraClusterMessages = intraClusterMessages;
s.interClusterBytes = interClusterBytes;
s.intraClusterBytes = intraClusterBytes;
s.stealTime = stealTimer.totalTimeVal();
s.handleStealTime = handleStealTimer.totalTimeVal();
s.abortTime = abortTimer.totalTimeVal();
s.idleTime = idleTimer.totalTimeVal();
s.idleCount = idleTimer.nrTimes();
s.pollTime = pollTimer.totalTimeVal();
s.pollCount = pollTimer.nrTimes();
s.tupleTime = tupleTimer.totalTimeVal();
s.handleTupleTime = handleTupleTimer.totalTimeVal();
s.tupleWaitTime = tupleOrderingWaitTimer.totalTimeVal();
s.tupleWaitCount = tupleOrderingWaitTimer.nrTimes();
s.invocationRecordWriteTime = invocationRecordWriteTimer.totalTimeVal();
s.invocationRecordWriteCount = invocationRecordWriteTimer.nrTimes();
s.invocationRecordReadTime = invocationRecordReadTimer.totalTimeVal();
s.invocationRecordReadCount = invocationRecordReadTimer.nrTimes();
s.returnRecordWriteTime = returnRecordWriteTimer.totalTimeVal();
s.returnRecordWriteCount = returnRecordWriteTimer.nrTimes();
s.returnRecordReadTime = returnRecordReadTimer.totalTimeVal();
s.returnRecordReadCount = returnRecordReadTimer.nrTimes();
s.returnRecordBytes = returnRecordBytes;
//fault tolerance
if (FAULT_TOLERANCE) {
s.tableResultUpdates = globalResultTable.numResultUpdates;
s.tableLockUpdates = globalResultTable.numLockUpdates;
s.tableUpdateMessages = globalResultTable.numUpdateMessages;
s.tableLookups = globalResultTable.numLookups;
s.tableSuccessfulLookups = globalResultTable.numLookupsSucceded;
s.tableRemoteLookups = globalResultTable.numRemoteLookups;
s.killedOrphans = killedOrphans;
s.restartedJobs = restartedJobs;
s.tableLookupTime = lookupTimer.totalTimeVal();
s.tableUpdateTime = updateTimer.totalTimeVal();
s.tableHandleUpdateTime = handleUpdateTimer.totalTimeVal();
s.tableHandleLookupTime = handleLookupTimer.totalTimeVal();
s.tableSerializationTime = tableSerializationTimer.totalTimeVal();
s.tableDeserializationTime = tableDeserializationTimer
.totalTimeVal();
s.tableCheckTime = redoTimer.totalTimeVal();
s.crashHandlingTime = crashTimer.totalTimeVal();
s.addReplicaTime = addReplicaTimer.totalTimeVal();
}
if (SHARED_OBJECTS) {
s.soInvocations = soInvocations;
s.soInvocationsBytes = soInvocationsBytes;
s.soTransfers = soTransfers;
s.soTransfersBytes = soTransfersBytes;
s.handleSOInvocationsTime = handleSOInvocationsTimer.totalTimeVal();
s.broadcastSOInvocationsTime = broadcastSOInvocationsTimer
.totalTimeVal();
s.soTransferTime = soTransferTimer.totalTimeVal();
s.soSerializationTime = soSerializationTimer.totalTimeVal();
s.soDeserializationTime = soDeserializationTimer.totalTimeVal() + soBroadcastDeserializationTimer.totalTimeVal();
s.soRealMessageCount = soRealMessageCount;
}
return s;
}
private double perStats(double tm, long cnt) {
if (cnt == 0) {
return 0.0;
}
return tm / cnt;
}
protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
- out.println("SATIN: SHARED_OBJECTS: nr invocations "
- + nf.format(totalStats.soInvocations) + ", bytes "
- + nf.format(totalStats.soInvocationsBytes) + ", messages "
- + nf.format(totalStats.soRealMessageCount)
- + ", object transfers " + nf.format(totalStats.soTransfers)
- + ", bytes " + nf.format(totalStats.soTransfersBytes));
+ out.println("SATIN: SO_INVOCATIONS: "
+ + nf.format(totalStats.soInvocations) + " invocations "
+ + nf.format(totalStats.soInvocationsBytes) + " bytes, "
+ + nf.format(totalStats.soRealMessageCount) + " messages");
+ out.println("SATIN: SO_TRANSFERS: "
+ + nf.format(totalStats.soTransfers) + " transfers "
+ + nf.format(totalStats.soTransfersBytes) + " bytes ");
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
protected void printDetailedStats() {
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
if (SPAWN_STATS) {
out.println("SATIN '" + ident + "': SPAWN_STATS: spawns = "
+ spawns + " executed = " + jobsExecuted + " syncs = " + syncs);
if (ABORTS) {
out.println("SATIN '" + ident + "': ABORT_STATS 1: aborts = "
+ aborts + " abort msgs = " + abortMessages
+ " aborted jobs = " + abortedJobs);
}
}
if (TUPLE_STATS) {
out.println("SATIN '" + ident
+ "': TUPLE_STATS 1: tuple bcast msgs: " + tupleMsgs
+ ", bytes = " + nf.format(tupleBytes));
}
if (STEAL_STATS) {
out.println("SATIN '" + ident + "': INTRA_STATS: messages = "
+ intraClusterMessages + ", bytes = "
+ nf.format(intraClusterBytes));
out.println("SATIN '" + ident + "': INTER_STATS: messages = "
+ interClusterMessages + ", bytes = "
+ nf.format(interClusterBytes));
out.println("SATIN '" + ident + "': STEAL_STATS 1: attempts = "
+ stealAttempts + " success = " + stealSuccess + " ("
+ (perStats((double) stealSuccess, stealAttempts) * 100.0)
+ " %)");
out.println("SATIN '" + ident + "': STEAL_STATS 2: requests = "
+ stealRequests + " jobs stolen = " + stolenJobs);
if (STEAL_TIMING) {
out.println("SATIN '" + ident + "': STEAL_STATS 3: attempts = "
+ stealTimer.nrTimes() + " total time = "
+ stealTimer.totalTime() + " avg time = "
+ stealTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 4: handleSteals = "
+ handleStealTimer.nrTimes() + " total time = "
+ handleStealTimer.totalTime() + " avg time = "
+ handleStealTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 5: invocationRecordWrites = "
+ invocationRecordWriteTimer.nrTimes() + " total time = "
+ invocationRecordWriteTimer.totalTime() + " avg time = "
+ invocationRecordWriteTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 6: invocationRecordReads = "
+ invocationRecordReadTimer.nrTimes() + " total time = "
+ invocationRecordReadTimer.totalTime() + " avg time = "
+ invocationRecordReadTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 7: returnRecordWrites = "
+ returnRecordWriteTimer.nrTimes() + " total time = "
+ returnRecordWriteTimer.totalTime() + " avg time = "
+ returnRecordWriteTimer.averageTime());
out.println("SATIN '" + ident
+ "': STEAL_STATS 8: returnRecordReads = "
+ returnRecordReadTimer.nrTimes() + " total time = "
+ returnRecordReadTimer.totalTime() + " avg time = "
+ returnRecordReadTimer.averageTime());
}
if (ABORTS && ABORT_TIMING) {
out.println("SATIN '" + ident + "': ABORT_STATS 2: aborts = "
+ abortTimer.nrTimes() + " total time = "
+ abortTimer.totalTime() + " avg time = "
+ abortTimer.averageTime());
}
if (IDLE_TIMING) {
out.println("SATIN '" + ident + "': IDLE_STATS: idle count = "
+ idleTimer.nrTimes() + " total time = "
+ idleTimer.totalTime() + " avg time = "
+ idleTimer.averageTime());
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN '" + ident + "': POLL_STATS: poll count = "
+ pollTimer.nrTimes() + " total time = "
+ pollTimer.totalTime() + " avg time = "
+ pollTimer.averageTime());
}
if (STEAL_TIMING && IDLE_TIMING) {
out.println("SATIN '"
+ ident
+ "': COMM_STATS: software comm time = "
+ Timer.format(stealTimer.totalTimeVal()
+ handleStealTimer.totalTimeVal()
- idleTimer.totalTimeVal()));
}
if (TUPLE_TIMING) {
out.println("SATIN '" + ident + "': TUPLE_STATS 2: bcasts = "
+ tupleTimer.nrTimes() + " total time = "
+ tupleTimer.totalTime() + " avg time = "
+ tupleTimer.averageTime());
out.println("SATIN '" + ident + "': TUPLE_STATS 3: waits = "
+ tupleOrderingWaitTimer.nrTimes() + " total time = "
+ tupleOrderingWaitTimer.totalTime() + " avg time = "
+ tupleOrderingWaitTimer.averageTime());
}
algorithm.printStats(out);
}
if (FAULT_TOLERANCE) {
if (GRT_STATS) {
out.println("SATIN '" + ident + "': "
+ globalResultTable.numResultUpdates
+ " result updates of the table.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numLockUpdates
+ " lock updates of the table.");
out
.println("SATIN '" + ident + "': "
+ globalResultTable.numUpdateMessages
+ " update messages.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numLookupsSucceded
+ " lookups succeded, of which:");
out.println("SATIN '" + ident + "': "
+ globalResultTable.numRemoteLookups + " remote lookups.");
out.println("SATIN '" + ident + "': "
+ globalResultTable.maxNumEntries + " entries maximally.");
}
if (GRT_TIMING) {
out.println("SATIN '" + ident + "': " + lookupTimer.totalTime()
+ " spent in lookups");
out.println("SATIN '" + ident + "': "
+ lookupTimer.averageTime() + " per lookup");
out.println("SATIN '" + ident + "': " + updateTimer.totalTime()
+ " spent in updates");
out.println("SATIN '" + ident + "': "
+ updateTimer.averageTime() + " per update");
out.println("SATIN '" + ident + "': "
+ handleUpdateTimer.totalTime()
+ " spent in handling updates");
out.println("SATIN '" + ident + "': "
+ handleUpdateTimer.averageTime() + " per update handle");
out.println("SATIN '" + ident + "': "
+ handleLookupTimer.totalTime()
+ " spent in handling lookups");
out.println("SATIN '" + ident + "': "
+ handleLookupTimer.averageTime() + " per lookup handle");
}
if (CRASH_TIMING) {
out.println("SATIN '" + ident + "': " + crashTimer.totalTime()
+ " spent in handling crashes");
}
if (TABLE_CHECK_TIMING) {
out.println("SATIN '" + ident + "': " + redoTimer.totalTime()
+ " spent in redoing");
}
if (FT_STATS) {
out.println("SATIN '" + ident + "': " + killedOrphans
+ " orphans killed");
out.println("SATIN '" + ident + "': " + restartedJobs
+ " jobs restarted");
}
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN '" + ident.name() + "': " + soInvocations
+ " shared object invocations sent.");
out.println("SATIN '" + ident.name() + "': " + soTransfers
+ " shared objects transfered.");
}
}
}
| true | true | protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN: SHARED_OBJECTS: nr invocations "
+ nf.format(totalStats.soInvocations) + ", bytes "
+ nf.format(totalStats.soInvocationsBytes) + ", messages "
+ nf.format(totalStats.soRealMessageCount)
+ ", object transfers " + nf.format(totalStats.soTransfers)
+ ", bytes " + nf.format(totalStats.soTransfersBytes));
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
| protected void printStats() {
int size;
synchronized (this) {
// size = victims.size();
// No, this is one too few. (Ceriel)
size = victims.size() + 1;
}
// add my own stats
StatsMessage me = createStats();
totalStats.add(me);
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
// pf.setMaximumIntegerDigits(3);
// pf.setMinimumIntegerDigits(3);
// for percentages
java.text.NumberFormat pf = java.text.NumberFormat.getInstance();
pf.setMaximumFractionDigits(3);
pf.setMinimumFractionDigits(3);
pf.setGroupingUsed(false);
out.println("-------------------------------SATIN STATISTICS------"
+ "--------------------------");
if (SPAWN_STATS) {
out.println("SATIN: SPAWN: " + nf.format(totalStats.spawns)
+ " spawns, " + nf.format(totalStats.jobsExecuted)
+ " executed, " + nf.format(totalStats.syncs) + " syncs");
if (ABORTS) {
out.println("SATIN: ABORT: "
+ nf.format(totalStats.aborts) + " aborts, "
+ nf.format(totalStats.abortMessages) + " abort msgs, "
+ nf.format(totalStats.abortedJobs) + " aborted jobs");
}
}
if (TUPLE_STATS) {
out.println("SATIN: TUPLE_SPACE: "
+ nf.format(totalStats.tupleMsgs) + " bcasts, "
+ nf.format(totalStats.tupleBytes) + " bytes");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL: poll count = "
+ nf.format(totalStats.pollCount));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE: idle count = "
+ nf.format(totalStats.idleCount));
}
if (STEAL_STATS) {
out.println("SATIN: STEAL: "
+ nf.format(totalStats.stealAttempts)
+ " attempts, "
+ nf.format(totalStats.stealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.stealSuccess,
totalStats.stealAttempts) * 100.0) + " %)");
if (totalStats.asyncStealAttempts != 0) {
out.println("SATIN: ASYNCSTEAL: "
+ nf.format(totalStats.asyncStealAttempts)
+ " attempts, "
+ nf.format(totalStats.asyncStealSuccess)
+ " successes ("
+ pf.format(perStats((double) totalStats.asyncStealSuccess,
totalStats.asyncStealAttempts) * 100.0) + " %)");
}
out.println("SATIN: MESSAGES: intra "
+ nf.format(totalStats.intraClusterMessages) + " msgs, "
+ nf.format(totalStats.intraClusterBytes) + " bytes; inter "
+ nf.format(totalStats.interClusterMessages) + " msgs, "
+ nf.format(totalStats.interClusterBytes) + " bytes");
}
if (FAULT_TOLERANCE && GRT_STATS) {
out.println("SATIN: GLOBAL_RESULT_TABLE: result updates "
+ nf.format(totalStats.tableResultUpdates)
+ ",update messages "
+ nf.format(totalStats.tableUpdateMessages) + ", lock updates "
+ nf.format(totalStats.tableLockUpdates) + ",lookups "
+ nf.format(totalStats.tableLookups) + ",successful "
+ nf.format(totalStats.tableSuccessfulLookups) + ",remote "
+ nf.format(totalStats.tableRemoteLookups));
}
if (FAULT_TOLERANCE && FT_STATS) {
out.println("SATIN: FAULT_TOLERANCE: killed orphans "
+ nf.format(totalStats.killedOrphans));
out.println("SATIN: FAULT_TOLERANCE: restarted jobs "
+ nf.format(totalStats.restartedJobs));
}
if (SHARED_OBJECTS && SO_STATS) {
out.println("SATIN: SO_INVOCATIONS: "
+ nf.format(totalStats.soInvocations) + " invocations "
+ nf.format(totalStats.soInvocationsBytes) + " bytes, "
+ nf.format(totalStats.soRealMessageCount) + " messages");
out.println("SATIN: SO_TRANSFERS: "
+ nf.format(totalStats.soTransfers) + " transfers "
+ nf.format(totalStats.soTransfersBytes) + " bytes ");
}
out.println("-------------------------------SATIN TOTAL TIMES"
+ "-------------------------------");
if (STEAL_TIMING) {
out.println("SATIN: STEAL_TIME: total "
+ Timer.format(totalStats.stealTime)
+ " time/req "
+ Timer.format(perStats(totalStats.stealTime,
totalStats.stealAttempts)));
out.println("SATIN: HANDLE_STEAL_TIME: total "
+ Timer.format(totalStats.handleStealTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.handleStealTime,
totalStats.stealAttempts)));
out.println("SATIN: INV SERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.invocationRecordWriteTime,
totalStats.stealSuccess)));
out.println("SATIN: INV DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.invocationRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.invocationRecordReadTime,
totalStats.stealSuccess)));
out.println("SATIN: RET SERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordWriteTime)
+ " time/write "
+ Timer.format(perStats(totalStats.returnRecordWriteTime,
totalStats.returnRecordWriteCount)));
out.println("SATIN: RET DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.returnRecordReadTime)
+ " time/read "
+ Timer.format(perStats(totalStats.returnRecordReadTime,
totalStats.returnRecordReadCount)));
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: total "
+ Timer.format(totalStats.abortTime)
+ " time/abort "
+ Timer
.format(perStats(totalStats.abortTime, totalStats.aborts)));
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: total "
+ Timer.format(totalStats.tupleTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleTime,
totalStats.tupleMsgs)));
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: total "
+ Timer.format(totalStats.tupleWaitTime)
+ " time/bcast "
+ Timer.format(perStats(totalStats.tupleWaitTime,
totalStats.tupleWaitCount)));
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: total "
+ Timer.format(totalStats.pollTime)
+ " time/poll "
+ Timer.format(perStats(totalStats.pollTime,
totalStats.pollCount)));
}
if (IDLE_TIMING) {
out.println("SATIN: IDLE_TIME: total "
+ Timer.format(totalStats.idleTime)
+ " time/idle "
+ Timer.format(perStats(totalStats.idleTime,
totalStats.idleCount)));
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out
.println("SATIN: GRT_UPDATE_TIME: total "
+ Timer.format(totalStats.tableUpdateTime)
+ " time/update "
+ Timer
.format(perStats(
totalStats.tableUpdateTime,
(totalStats.tableResultUpdates + totalStats.tableLockUpdates))));
out.println("SATIN: GRT_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableLookupTime)
+ " time/lookup "
+ Timer.format(perStats(totalStats.tableLookupTime,
totalStats.tableLookups)));
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: total "
+ Timer.format(totalStats.tableHandleUpdateTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleUpdateTime,
totalStats.tableResultUpdates * (size - 1))));
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: total "
+ Timer.format(totalStats.tableHandleLookupTime)
+ " time/handle "
+ Timer.format(perStats(totalStats.tableHandleLookupTime,
totalStats.tableRemoteLookups)));
out.println("SATIN: GRT_SERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableSerializationTime));
out.println("SATIN: GRT_DESERIALIZATION_TIME: total "
+ Timer.format(totalStats.tableDeserializationTime));
out.println("SATIN: GRT_CHECK_TIME: total "
+ Timer.format(totalStats.tableCheckTime)
+ " time/check "
+ Timer.format(perStats(totalStats.tableCheckTime,
totalStats.tableLookups)));
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: total "
+ Timer.format(totalStats.crashHandlingTime));
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: total "
+ Timer.format(totalStats.addReplicaTime));
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: total "
+ Timer.format(totalStats.broadcastSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.broadcastSOInvocationsTime,
totalStats.soInvocations)));
out.println("SATIN: HANDLE_SO_INVOCATIONS: total "
+ Timer.format(totalStats.handleSOInvocationsTime)
+ " time/inv "
+ Timer.format(perStats(totalStats.handleSOInvocationsTime,
totalStats.soInvocations * (size - 1))));
out.println("SATIN: SO_TRANSFERS: total "
+ Timer.format(totalStats.soTransferTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soTransferTime,
totalStats.soTransfers)));
out.println("SATIN: SO_SERIALIZATION: total "
+ Timer.format(totalStats.soSerializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soSerializationTime,
totalStats.soTransfers)));
out.println("SATIN: SO_DESERIALIZATION: total "
+ Timer.format(totalStats.soDeserializationTime)
+ " time/transf "
+ Timer.format(perStats(totalStats.soDeserializationTime,
totalStats.soTransfers)));
}
out.println("-------------------------------SATIN RUN TIME "
+ "BREAKDOWN------------------------");
out.println("SATIN: TOTAL_RUN_TIME: "
+ Timer.format(totalTimer.totalTimeVal()));
double lbTime = (totalStats.stealTime + totalStats.handleStealTime
- totalStats.invocationRecordReadTime - totalStats.invocationRecordWriteTime)
/ size;
if (lbTime < 0.0) {
lbTime = 0.0;
}
double lbPerc = lbTime / totalTimer.totalTimeVal() * 100.0;
double serTime = (totalStats.invocationRecordWriteTime
+ totalStats.invocationRecordReadTime
+ totalStats.returnRecordWriteTime + totalStats.returnRecordReadTime)
/ size;
double serPerc = serTime / totalTimer.totalTimeVal() * 100.0;
double abortTime = totalStats.abortTime / size;
double abortPerc = abortTime / totalTimer.totalTimeVal() * 100.0;
double tupleTime = totalStats.tupleTime / size;
double tuplePerc = tupleTime / totalTimer.totalTimeVal() * 100.0;
double handleTupleTime = totalStats.handleTupleTime / size;
double handleTuplePerc = handleTupleTime / totalTimer.totalTimeVal()
* 100.0;
double tupleWaitTime = totalStats.tupleWaitTime / size;
double tupleWaitPerc = tupleWaitTime / totalTimer.totalTimeVal()
* 100.0;
double pollTime = totalStats.pollTime / size;
double pollPerc = pollTime / totalTimer.totalTimeVal() * 100.0;
double tableUpdateTime = totalStats.tableUpdateTime / size;
double tableUpdatePerc = tableUpdateTime / totalTimer.totalTimeVal()
* 100.0;
double tableLookupTime = totalStats.tableLookupTime / size;
double tableLookupPerc = tableLookupTime / totalTimer.totalTimeVal()
* 100.0;
double tableHandleUpdateTime = totalStats.tableHandleUpdateTime / size;
double tableHandleUpdatePerc = tableHandleUpdateTime
/ totalTimer.totalTimeVal() * 100.0;
double tableHandleLookupTime = totalStats.tableHandleLookupTime / size;
double tableHandleLookupPerc = tableHandleLookupTime
/ totalTimer.totalTimeVal() * 100.0;
double tableSerializationTime = totalStats.tableSerializationTime
/ size;
double tableSerializationPerc = tableSerializationTime
/ totalTimer.totalTimeVal() * 100;
double tableDeserializationTime = totalStats.tableDeserializationTime
/ size;
double tableDeserializationPerc = tableDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double crashHandlingTime = totalStats.crashHandlingTime / size;
double crashHandlingPerc = crashHandlingTime
/ totalTimer.totalTimeVal() * 100.0;
double addReplicaTime = totalStats.addReplicaTime / size;
double addReplicaPerc = addReplicaTime / totalTimer.totalTimeVal()
* 100.0;
double broadcastSOInvocationsTime = totalStats.broadcastSOInvocationsTime
/ size;
double broadcastSOInvocationsPerc = broadcastSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double handleSOInvocationsTime = totalStats.handleSOInvocationsTime
/ size;
double handleSOInvocationsPerc = handleSOInvocationsTime
/ totalTimer.totalTimeVal() * 100;
double soTransferTime = totalStats.soTransferTime / size;
double soTransferPerc = soTransferTime / totalTimer.totalTimeVal()
* 100;
double soSerializationTime = totalStats.soSerializationTime / size;
double soSerializationPerc = soSerializationTime
/ totalTimer.totalTimeVal() * 100;
double soDeserializationTime = totalStats.soDeserializationTime / size;
double soDeserializationPerc = soDeserializationTime
/ totalTimer.totalTimeVal() * 100;
double totalOverhead = abortTime
+ tupleTime
+ handleTupleTime
+ tupleWaitTime
+ pollTime
+ tableUpdateTime
+ tableLookupTime
+ tableHandleUpdateTime
+ tableHandleLookupTime
+ handleSOInvocationsTime
+ broadcastSOInvocationsTime
+ soTransferTime
+ (totalStats.stealTime + totalStats.handleStealTime
+ totalStats.returnRecordReadTime + totalStats.returnRecordWriteTime)
/ size;
double totalPerc = totalOverhead / totalTimer.totalTimeVal() * 100.0;
double appTime = totalTimer.totalTimeVal() - totalOverhead;
if (appTime < 0.0) {
appTime = 0.0;
}
double appPerc = appTime / totalTimer.totalTimeVal() * 100.0;
if (STEAL_TIMING) {
out.println("SATIN: LOAD_BALANCING_TIME: avg. per machine "
+ Timer.format(lbTime) + " (" + (lbPerc < 10 ? " " : "")
+ pf.format(lbPerc) + " %)");
out.println("SATIN: (DE)SERIALIZATION_TIME: avg. per machine "
+ Timer.format(serTime) + " (" + (serPerc < 10 ? " " : "")
+ pf.format(serPerc) + " %)");
}
if (ABORT_TIMING) {
out.println("SATIN: ABORT_TIME: avg. per machine "
+ Timer.format(abortTime) + " (" + (abortPerc < 10 ? " " : "")
+ pf.format(abortPerc) + " %)");
}
if (TUPLE_TIMING) {
out.println("SATIN: TUPLE_SPACE_BCAST_TIME: avg. per machine "
+ Timer.format(tupleTime) + " (" + (tuplePerc < 10 ? " " : "")
+ pf.format(tuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_HANDLE_TIME: avg. per machine "
+ Timer.format(handleTupleTime) + " ("
+ (handleTuplePerc < 10 ? " " : "")
+ pf.format(handleTuplePerc) + " %)");
out.println("SATIN: TUPLE_SPACE_WAIT_TIME: avg. per machine "
+ Timer.format(tupleWaitTime) + " ("
+ (tupleWaitPerc < 10 ? " " : "") + pf.format(tupleWaitPerc)
+ " %)");
}
if (POLL_FREQ != 0 && POLL_TIMING) {
out.println("SATIN: POLL_TIME: avg. per machine "
+ Timer.format(pollTime) + " (" + (pollPerc < 10 ? " " : "")
+ pf.format(pollPerc) + " %)");
}
if (FAULT_TOLERANCE && GRT_TIMING) {
out.println("SATIN: GRT_UPDATE_TIME: avg. per machine "
+ Timer.format(tableUpdateTime) + " ("
+ pf.format(tableUpdatePerc) + " %)");
out.println("SATIN: GRT_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableLookupTime) + " ("
+ pf.format(tableLookupPerc) + " %)");
out.println("SATIN: GRT_HANDLE_UPDATE_TIME: avg. per machine "
+ Timer.format(tableHandleUpdateTime) + " ("
+ pf.format(tableHandleUpdatePerc) + " %)");
out.println("SATIN: GRT_HANDLE_LOOKUP_TIME: avg. per machine "
+ Timer.format(tableHandleLookupTime) + " ("
+ pf.format(tableHandleLookupPerc) + " %)");
out.println("SATIN: GRT_SERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableSerializationTime) + " ("
+ pf.format(tableSerializationPerc) + " %)");
out.println("SATIN: GRT_DESERIALIZATION_TIME: avg. per machine "
+ Timer.format(tableDeserializationTime) + " ("
+ pf.format(tableDeserializationPerc) + " %)");
}
if (FAULT_TOLERANCE && CRASH_TIMING) {
out.println("SATIN: CRASH_HANDLING_TIME: avg. per machine "
+ Timer.format(crashHandlingTime) + " ("
+ pf.format(crashHandlingPerc) + " %)");
}
if (FAULT_TOLERANCE && ADD_REPLICA_TIMING) {
out.println("SATIN: ADD_REPLICA_TIME: avg. per machine "
+ Timer.format(addReplicaTime) + " ("
+ pf.format(addReplicaPerc) + " %)");
}
if (SHARED_OBJECTS && SO_TIMING) {
out.println("SATIN: BROADCAST_SO_INVOCATIONS: avg. per machine "
+ Timer.format(broadcastSOInvocationsTime) + " ( "
+ pf.format(broadcastSOInvocationsPerc) + " %)");
out.println("SATIN: HANDLE_SO_INVOCATIONS: avg. per machine "
+ Timer.format(handleSOInvocationsTime) + " ( "
+ pf.format(handleSOInvocationsPerc) + " %)");
out.println("SATIN: SO_TRANSFERS: avg. per machine "
+ Timer.format(soTransferTime) + " ( "
+ pf.format(soTransferPerc) + " %)");
out.println("SATIN: SO_SERIALIZATION: avg. per machine "
+ Timer.format(soSerializationTime) + " ( "
+ pf.format(soSerializationPerc) + " %)");
out.println("SATIN: SO_DESERIALIZATION: avg. per machine "
+ Timer.format(soDeserializationTime) + " ( "
+ pf.format(soDeserializationPerc) + " %)");
}
out.println("\nSATIN: TOTAL_PARALLEL_OVERHEAD: avg. per machine "
+ Timer.format(totalOverhead) + " (" + (totalPerc < 10 ? " " : "")
+ pf.format(totalPerc) + " %)");
out.println("SATIN: USEFUL_APP_TIME: avg. per machine "
+ Timer.format(appTime) + " (" + (appPerc < 10 ? " " : "")
+ pf.format(appPerc) + " %)");
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/ProxyServiceDeserializer.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/ProxyServiceDeserializer.java
index 8caa4bc1b..7caf84f82 100755
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/ProxyServiceDeserializer.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/custom/deserializer/ProxyServiceDeserializer.java
@@ -1,246 +1,246 @@
/*
* Copyright 2012 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.deserializer;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.synapse.core.axis2.ProxyService;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.endpoints.IndirectEndpoint;
import org.apache.synapse.mediators.base.SequenceMediator;
import org.apache.synapse.util.PolicyInfo;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.EndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.MediatorFlow;
import org.wso2.developerstudio.eclipse.gmf.esb.ProxyServiceParameter;
import org.wso2.developerstudio.eclipse.gmf.esb.ProxyServicePolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.ProxyWSDLResource;
import org.wso2.developerstudio.eclipse.gmf.esb.ProxyWsdlType;
import org.wso2.developerstudio.eclipse.gmf.esb.RegistryKeyProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.SequenceType;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes;
import static org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage.Literals.*;
public class ProxyServiceDeserializer extends AbstractEsbNodeDeserializer<ProxyService,org.wso2.developerstudio.eclipse.gmf.esb.ProxyService> {
@Override
public org.wso2.developerstudio.eclipse.gmf.esb.ProxyService createNode(IGraphicalEditPart editPart,ProxyService object) {
org.wso2.developerstudio.eclipse.gmf.esb.ProxyService proxy = (org.wso2.developerstudio.eclipse.gmf.esb.ProxyService) DeserializerUtils
.createNode(editPart, EsbElementTypes.ProxyService_3001);
setElementToEdit(proxy);
refreshEditPartMap();
executeSetValueCommand(PROXY_SERVICE__NAME,object.getName());
boolean hasPublishWsdl=true;
if(object.getWsdlURI()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.SOURCE_URL);
executeSetValueCommand(PROXY_SERVICE__WSDL_URL, object.getWsdlURI().toString());
}else if(object.getWSDLKey()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.REGISTRY_KEY);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(object.getWSDLKey());
executeSetValueCommand(PROXY_SERVICE__WSDL_KEY, keyProperty);
}else if(object.getInLineWSDL()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.INLINE);
executeSetValueCommand(PROXY_SERVICE__WSDL_XML, object.getInLineWSDL());
}else{
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.NONE);
hasPublishWsdl=false;
}
Endpoint targetInLineEndpoint = object.getTargetInLineEndpoint();
if(targetInLineEndpoint!=null){
setHasInlineEndPoint(true);
} else if(StringUtils.isNotBlank(object.getTargetEndpoint())){
setHasInlineEndPoint(true);
}
if(hasPublishWsdl && object.getResourceMap()!=null){
Map<String, String> resourcesMap = object.getResourceMap().getResources();
EList<ProxyWSDLResource> wsdlResourceList= new BasicEList<ProxyWSDLResource>();
for (Entry<String, String> entry : resourcesMap.entrySet()) {
ProxyWSDLResource resource= EsbFactory.eINSTANCE.createProxyWSDLResource();
resource.getKey().setKeyValue(entry.getValue());
resource.setLocation(entry.getKey());
wsdlResourceList.add(resource);
}
executeSetValueCommand(PROXY_SERVICE__WSDL_RESOURCES, wsdlResourceList);
}
- if(object.getTransports().size()>0){
+ if(object.getTransports()!=null && object.getTransports().size()>0){
executeSetValueCommand(PROXY_SERVICE__TRANSPORTS,DeserializerUtils.join(object.getTransports(), ","));
}
if(object.getServiceGroup()!=null){
executeSetValueCommand(PROXY_SERVICE__SERVICE_GROUP,object.getServiceGroup());
}
if(object.getPinnedServers().size()>0){
executeSetValueCommand(PROXY_SERVICE__PINNED_SERVERS,DeserializerUtils.join(object.getPinnedServers(), ","));
}
executeSetValueCommand(PROXY_SERVICE__SECURITY_ENABLED, object.isWsSecEnabled());
executeSetValueCommand(PROXY_SERVICE__RELIABLE_MESSAGING_ENABLED, object.isWsRMEnabled());
EList<ProxyServiceParameter> parameters = new BasicEList<ProxyServiceParameter>();
for (Map.Entry<String, Object> entry : object.getParameterMap().entrySet()) {
ProxyServiceParameter parameter = EsbFactory.eINSTANCE.createProxyServiceParameter();
parameter.setName(entry.getKey());
parameter.setValue(entry.getValue().toString());
parameters.add(parameter);
}
if(parameters.size()>0){
executeSetValueCommand(PROXY_SERVICE__SERVICE_PARAMETERS,parameters);
}
EList<ProxyServicePolicy> policies = new BasicEList<ProxyServicePolicy>();
for (PolicyInfo entry : object.getPolicies()) {
ProxyServicePolicy policy = EsbFactory.eINSTANCE.createProxyServicePolicy();
policy.getPolicyKey().setKeyValue(entry.getPolicyKey());
policies.add(policy);
}
if(policies.size()>0){
executeSetValueCommand(PROXY_SERVICE__SERVICE_POLICIES,policies);
}
addRootInputConnector(proxy.getInputConnector());
MediatorFlow mediatorFlow = proxy.getContainer().getSequenceAndEndpointContainer().getMediatorFlow();
SequenceMediator inSequence = object.getTargetInLineInSequence();
GraphicalEditPart compartment = (GraphicalEditPart)((getEditpart(mediatorFlow)).getChildren().get(0));
setRootCompartment(compartment);
if(inSequence!=null){
deserializeSequence(compartment, inSequence, proxy.getOutputConnector());
} else{
String inSequenceName = object.getTargetInSequence();
if(inSequenceName!=null){
if(inSequenceName.startsWith("/") || inSequenceName.startsWith("conf:") || inSequenceName.startsWith("gov:")){
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_TYPE, SequenceType.REGISTRY_REFERENCE);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(inSequenceName);
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_KEY, keyProperty);
} else{
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE);
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_NAME, inSequenceName);
}
}
}
/*if(object.getTargetInLineEndpoint() == null){
String endpointName = object.getTargetEndpoint();
if(StringUtils.isNotBlank(endpointName)){
if(endpointName.startsWith("/") || endpointName.startsWith("conf:") || endpointName.startsWith("gov:")){
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_TYPE, SequenceType.REGISTRY_REFERENCE);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(endpointName);
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_KEY, keyProperty);
} else{
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_TYPE, SequenceType.NAMED_REFERENCE);
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_NAME, endpointName);
}
}
}*/
if (hasInlineEndPoint()) {
if (object.getTargetEndpoint() != null) {
IndirectEndpoint indirectEndpoint = new IndirectEndpoint();
indirectEndpoint.setKey(object.getTargetEndpoint());
targetInLineEndpoint = indirectEndpoint;
}
@SuppressWarnings("rawtypes")
IEsbNodeDeserializer deserializer = EsbDeserializerRegistry.getInstance()
.getDeserializer(targetInLineEndpoint);
if (deserializer != null) {
@SuppressWarnings("unchecked")
EndPoint endPointModel = (EndPoint) deserializer.createNode(
getRootCompartment(), targetInLineEndpoint);
executeSetValueCommand(endPointModel, END_POINT__IN_LINE, true);
getConnectionFlow(proxy.getOutputConnector()).add(endPointModel);
}
}
setHasInlineEndPoint(false);
setRootCompartment(null);
setAddedAddressingEndPoint(false);
SequenceMediator outSequence = object.getTargetInLineOutSequence();
if(outSequence!=null){
setRootCompartment(compartment);
deserializeSequence(compartment, outSequence, proxy.getInputConnector());
setRootCompartment(null);
} else{
String outSequenceName = object.getTargetOutSequence();
if(outSequenceName!=null){
if(outSequenceName.startsWith("/") || outSequenceName.startsWith("conf:") || outSequenceName.startsWith("gov:")){
executeSetValueCommand(PROXY_SERVICE__OUT_SEQUENCE_TYPE, SequenceType.REGISTRY_REFERENCE);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(outSequenceName);
executeSetValueCommand(PROXY_SERVICE__OUT_SEQUENCE_KEY, keyProperty);
} else{
executeSetValueCommand(PROXY_SERVICE__OUT_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE);
executeSetValueCommand(PROXY_SERVICE__OUT_SEQUENCE_NAME, outSequenceName);
}
}
deserializeSequence(compartment, new SequenceMediator(), proxy.getInputConnector());
}
SequenceMediator faultSequence = object.getTargetInLineFaultSequence();
MediatorFlow faultmediatorFlow = proxy.getContainer().getFaultContainer().getMediatorFlow();
GraphicalEditPart faultCompartment = (GraphicalEditPart)((getEditpart(faultmediatorFlow)).getChildren().get(0));
if(faultSequence!=null){
setRootCompartment(compartment);
deserializeSequence(faultCompartment, faultSequence, proxy.getFaultInputConnector());
setRootCompartment(null);
} else{
String faultSequenceName = object.getTargetFaultSequence();
if(faultSequenceName!=null){
if(faultSequenceName.startsWith("/") || faultSequenceName.startsWith("conf:") || faultSequenceName.startsWith("gov:")){
executeSetValueCommand(PROXY_SERVICE__FAULT_SEQUENCE_TYPE, SequenceType.REGISTRY_REFERENCE);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(faultSequenceName);
executeSetValueCommand(PROXY_SERVICE__FAULT_SEQUENCE_KEY, keyProperty);
} else{
executeSetValueCommand(PROXY_SERVICE__FAULT_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE);
executeSetValueCommand(PROXY_SERVICE__FAULT_SEQUENCE_NAME, faultSequenceName);
}
}
deserializeSequence(faultCompartment, new SequenceMediator(), proxy.getFaultInputConnector());
}
addPairMediatorFlow(proxy.getOutputConnector(),proxy.getInputConnector());
//TODO : deserialize other properties
return proxy;
}
}
| true | true | public org.wso2.developerstudio.eclipse.gmf.esb.ProxyService createNode(IGraphicalEditPart editPart,ProxyService object) {
org.wso2.developerstudio.eclipse.gmf.esb.ProxyService proxy = (org.wso2.developerstudio.eclipse.gmf.esb.ProxyService) DeserializerUtils
.createNode(editPart, EsbElementTypes.ProxyService_3001);
setElementToEdit(proxy);
refreshEditPartMap();
executeSetValueCommand(PROXY_SERVICE__NAME,object.getName());
boolean hasPublishWsdl=true;
if(object.getWsdlURI()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.SOURCE_URL);
executeSetValueCommand(PROXY_SERVICE__WSDL_URL, object.getWsdlURI().toString());
}else if(object.getWSDLKey()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.REGISTRY_KEY);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(object.getWSDLKey());
executeSetValueCommand(PROXY_SERVICE__WSDL_KEY, keyProperty);
}else if(object.getInLineWSDL()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.INLINE);
executeSetValueCommand(PROXY_SERVICE__WSDL_XML, object.getInLineWSDL());
}else{
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.NONE);
hasPublishWsdl=false;
}
Endpoint targetInLineEndpoint = object.getTargetInLineEndpoint();
if(targetInLineEndpoint!=null){
setHasInlineEndPoint(true);
} else if(StringUtils.isNotBlank(object.getTargetEndpoint())){
setHasInlineEndPoint(true);
}
if(hasPublishWsdl && object.getResourceMap()!=null){
Map<String, String> resourcesMap = object.getResourceMap().getResources();
EList<ProxyWSDLResource> wsdlResourceList= new BasicEList<ProxyWSDLResource>();
for (Entry<String, String> entry : resourcesMap.entrySet()) {
ProxyWSDLResource resource= EsbFactory.eINSTANCE.createProxyWSDLResource();
resource.getKey().setKeyValue(entry.getValue());
resource.setLocation(entry.getKey());
wsdlResourceList.add(resource);
}
executeSetValueCommand(PROXY_SERVICE__WSDL_RESOURCES, wsdlResourceList);
}
if(object.getTransports().size()>0){
executeSetValueCommand(PROXY_SERVICE__TRANSPORTS,DeserializerUtils.join(object.getTransports(), ","));
}
if(object.getServiceGroup()!=null){
executeSetValueCommand(PROXY_SERVICE__SERVICE_GROUP,object.getServiceGroup());
}
if(object.getPinnedServers().size()>0){
executeSetValueCommand(PROXY_SERVICE__PINNED_SERVERS,DeserializerUtils.join(object.getPinnedServers(), ","));
}
executeSetValueCommand(PROXY_SERVICE__SECURITY_ENABLED, object.isWsSecEnabled());
executeSetValueCommand(PROXY_SERVICE__RELIABLE_MESSAGING_ENABLED, object.isWsRMEnabled());
EList<ProxyServiceParameter> parameters = new BasicEList<ProxyServiceParameter>();
for (Map.Entry<String, Object> entry : object.getParameterMap().entrySet()) {
ProxyServiceParameter parameter = EsbFactory.eINSTANCE.createProxyServiceParameter();
parameter.setName(entry.getKey());
parameter.setValue(entry.getValue().toString());
parameters.add(parameter);
}
if(parameters.size()>0){
executeSetValueCommand(PROXY_SERVICE__SERVICE_PARAMETERS,parameters);
}
EList<ProxyServicePolicy> policies = new BasicEList<ProxyServicePolicy>();
for (PolicyInfo entry : object.getPolicies()) {
ProxyServicePolicy policy = EsbFactory.eINSTANCE.createProxyServicePolicy();
policy.getPolicyKey().setKeyValue(entry.getPolicyKey());
policies.add(policy);
}
if(policies.size()>0){
executeSetValueCommand(PROXY_SERVICE__SERVICE_POLICIES,policies);
}
addRootInputConnector(proxy.getInputConnector());
MediatorFlow mediatorFlow = proxy.getContainer().getSequenceAndEndpointContainer().getMediatorFlow();
SequenceMediator inSequence = object.getTargetInLineInSequence();
GraphicalEditPart compartment = (GraphicalEditPart)((getEditpart(mediatorFlow)).getChildren().get(0));
setRootCompartment(compartment);
if(inSequence!=null){
deserializeSequence(compartment, inSequence, proxy.getOutputConnector());
} else{
String inSequenceName = object.getTargetInSequence();
if(inSequenceName!=null){
if(inSequenceName.startsWith("/") || inSequenceName.startsWith("conf:") || inSequenceName.startsWith("gov:")){
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_TYPE, SequenceType.REGISTRY_REFERENCE);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(inSequenceName);
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_KEY, keyProperty);
} else{
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE);
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_NAME, inSequenceName);
}
}
}
/*if(object.getTargetInLineEndpoint() == null){
String endpointName = object.getTargetEndpoint();
if(StringUtils.isNotBlank(endpointName)){
if(endpointName.startsWith("/") || endpointName.startsWith("conf:") || endpointName.startsWith("gov:")){
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_TYPE, SequenceType.REGISTRY_REFERENCE);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(endpointName);
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_KEY, keyProperty);
} else{
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_TYPE, SequenceType.NAMED_REFERENCE);
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_NAME, endpointName);
}
}
}*/
| public org.wso2.developerstudio.eclipse.gmf.esb.ProxyService createNode(IGraphicalEditPart editPart,ProxyService object) {
org.wso2.developerstudio.eclipse.gmf.esb.ProxyService proxy = (org.wso2.developerstudio.eclipse.gmf.esb.ProxyService) DeserializerUtils
.createNode(editPart, EsbElementTypes.ProxyService_3001);
setElementToEdit(proxy);
refreshEditPartMap();
executeSetValueCommand(PROXY_SERVICE__NAME,object.getName());
boolean hasPublishWsdl=true;
if(object.getWsdlURI()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.SOURCE_URL);
executeSetValueCommand(PROXY_SERVICE__WSDL_URL, object.getWsdlURI().toString());
}else if(object.getWSDLKey()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.REGISTRY_KEY);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(object.getWSDLKey());
executeSetValueCommand(PROXY_SERVICE__WSDL_KEY, keyProperty);
}else if(object.getInLineWSDL()!=null){
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.INLINE);
executeSetValueCommand(PROXY_SERVICE__WSDL_XML, object.getInLineWSDL());
}else{
executeSetValueCommand(PROXY_SERVICE__WSDL_TYPE, ProxyWsdlType.NONE);
hasPublishWsdl=false;
}
Endpoint targetInLineEndpoint = object.getTargetInLineEndpoint();
if(targetInLineEndpoint!=null){
setHasInlineEndPoint(true);
} else if(StringUtils.isNotBlank(object.getTargetEndpoint())){
setHasInlineEndPoint(true);
}
if(hasPublishWsdl && object.getResourceMap()!=null){
Map<String, String> resourcesMap = object.getResourceMap().getResources();
EList<ProxyWSDLResource> wsdlResourceList= new BasicEList<ProxyWSDLResource>();
for (Entry<String, String> entry : resourcesMap.entrySet()) {
ProxyWSDLResource resource= EsbFactory.eINSTANCE.createProxyWSDLResource();
resource.getKey().setKeyValue(entry.getValue());
resource.setLocation(entry.getKey());
wsdlResourceList.add(resource);
}
executeSetValueCommand(PROXY_SERVICE__WSDL_RESOURCES, wsdlResourceList);
}
if(object.getTransports()!=null && object.getTransports().size()>0){
executeSetValueCommand(PROXY_SERVICE__TRANSPORTS,DeserializerUtils.join(object.getTransports(), ","));
}
if(object.getServiceGroup()!=null){
executeSetValueCommand(PROXY_SERVICE__SERVICE_GROUP,object.getServiceGroup());
}
if(object.getPinnedServers().size()>0){
executeSetValueCommand(PROXY_SERVICE__PINNED_SERVERS,DeserializerUtils.join(object.getPinnedServers(), ","));
}
executeSetValueCommand(PROXY_SERVICE__SECURITY_ENABLED, object.isWsSecEnabled());
executeSetValueCommand(PROXY_SERVICE__RELIABLE_MESSAGING_ENABLED, object.isWsRMEnabled());
EList<ProxyServiceParameter> parameters = new BasicEList<ProxyServiceParameter>();
for (Map.Entry<String, Object> entry : object.getParameterMap().entrySet()) {
ProxyServiceParameter parameter = EsbFactory.eINSTANCE.createProxyServiceParameter();
parameter.setName(entry.getKey());
parameter.setValue(entry.getValue().toString());
parameters.add(parameter);
}
if(parameters.size()>0){
executeSetValueCommand(PROXY_SERVICE__SERVICE_PARAMETERS,parameters);
}
EList<ProxyServicePolicy> policies = new BasicEList<ProxyServicePolicy>();
for (PolicyInfo entry : object.getPolicies()) {
ProxyServicePolicy policy = EsbFactory.eINSTANCE.createProxyServicePolicy();
policy.getPolicyKey().setKeyValue(entry.getPolicyKey());
policies.add(policy);
}
if(policies.size()>0){
executeSetValueCommand(PROXY_SERVICE__SERVICE_POLICIES,policies);
}
addRootInputConnector(proxy.getInputConnector());
MediatorFlow mediatorFlow = proxy.getContainer().getSequenceAndEndpointContainer().getMediatorFlow();
SequenceMediator inSequence = object.getTargetInLineInSequence();
GraphicalEditPart compartment = (GraphicalEditPart)((getEditpart(mediatorFlow)).getChildren().get(0));
setRootCompartment(compartment);
if(inSequence!=null){
deserializeSequence(compartment, inSequence, proxy.getOutputConnector());
} else{
String inSequenceName = object.getTargetInSequence();
if(inSequenceName!=null){
if(inSequenceName.startsWith("/") || inSequenceName.startsWith("conf:") || inSequenceName.startsWith("gov:")){
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_TYPE, SequenceType.REGISTRY_REFERENCE);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(inSequenceName);
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_KEY, keyProperty);
} else{
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_TYPE, SequenceType.NAMED_REFERENCE);
executeSetValueCommand(PROXY_SERVICE__IN_SEQUENCE_NAME, inSequenceName);
}
}
}
/*if(object.getTargetInLineEndpoint() == null){
String endpointName = object.getTargetEndpoint();
if(StringUtils.isNotBlank(endpointName)){
if(endpointName.startsWith("/") || endpointName.startsWith("conf:") || endpointName.startsWith("gov:")){
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_TYPE, SequenceType.REGISTRY_REFERENCE);
RegistryKeyProperty keyProperty = EsbFactory.eINSTANCE.createRegistryKeyProperty();
keyProperty.setKeyValue(endpointName);
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_KEY, keyProperty);
} else{
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_TYPE, SequenceType.NAMED_REFERENCE);
executeSetValueCommand(PROXY_SERVICE__ENDPOINT_NAME, endpointName);
}
}
}*/
|
diff --git a/cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/SummaryContentViewControllerTest.java b/cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/SummaryContentViewControllerTest.java
index 40adccef4..7e9e4e510 100644
--- a/cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/SummaryContentViewControllerTest.java
+++ b/cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/SummaryContentViewControllerTest.java
@@ -1,30 +1,30 @@
package gov.nih.nci.cagrid.portal.portlet;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.ModelAndView;
/**
* User: kherm
*
* @author kherm [email protected]
*/
public class SummaryContentViewControllerTest {
protected MockRenderRequest request = new MockRenderRequest();
protected MockRenderResponse response = new MockRenderResponse();
@Test
public void handleRenderRequestInternal() throws Exception {
SummaryContentViewController controller = new SummaryContentViewController();
ModelAndView mav = controller.handleRenderRequest(request, response);
assertNotNull(response.getContentAsString());
- assertTrue(mav.getModel().size() > 0);
+// assertTrue(mav.getModel().size() > 0);
}
}
| true | true | public void handleRenderRequestInternal() throws Exception {
SummaryContentViewController controller = new SummaryContentViewController();
ModelAndView mav = controller.handleRenderRequest(request, response);
assertNotNull(response.getContentAsString());
assertTrue(mav.getModel().size() > 0);
}
| public void handleRenderRequestInternal() throws Exception {
SummaryContentViewController controller = new SummaryContentViewController();
ModelAndView mav = controller.handleRenderRequest(request, response);
assertNotNull(response.getContentAsString());
// assertTrue(mav.getModel().size() > 0);
}
|
diff --git a/src/com/redhat/qe/sm/cli/tests/PofilterTranslationTests.java b/src/com/redhat/qe/sm/cli/tests/PofilterTranslationTests.java
index 4e1ac225..87be9e43 100644
--- a/src/com/redhat/qe/sm/cli/tests/PofilterTranslationTests.java
+++ b/src/com/redhat/qe/sm/cli/tests/PofilterTranslationTests.java
@@ -1,597 +1,597 @@
package com.redhat.qe.sm.cli.tests;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.redhat.qe.Assert;
import com.redhat.qe.auto.bugzilla.BlockedByBzBug;
import com.redhat.qe.auto.testng.TestNGUtils;
import com.redhat.qe.sm.base.SubscriptionManagerCLITestScript;
import com.redhat.qe.sm.data.Translation;
import com.redhat.qe.tools.RemoteFileTasks;
import com.redhat.qe.tools.SSHCommandResult;
import com.redhat.qe.tools.SSHCommandRunner;
//import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;
/**
* @author fsharath
* @author jsefler
* @References
* Engineering Localization Services: https://home.corp.redhat.com/node/53593
* http://git.fedorahosted.org/git/?p=subscription-manager.git;a=blob;f=po/pt.po;h=0854212f4fab348a25f0542625df343653a4a097;hb=RHEL6.3
* Here is the raw rhsm.po file for LANG=pt
* http://git.fedorahosted.org/git/?p=subscription-manager.git;a=blob;f=po/pt.po;hb=RHEL6.3
*
* https://engineering.redhat.com/trac/LocalizationServices
* https://engineering.redhat.com/trac/LocalizationServices/wiki/L10nRHEL6LanguageSupportCriteria
*
* https://translate.zanata.org/zanata/project/view/subscription-manager/iter/0.99.X/stats
*
* https://fedora.transifex.net/projects/p/fedora/
*
* http://translate.sourceforge.net/wiki/
* http://translate.sourceforge.net/wiki/toolkit/index
* http://translate.sourceforge.net/wiki/toolkit/pofilter
* http://translate.sourceforge.net/wiki/toolkit/pofilter_tests
* http://translate.sourceforge.net/wiki/toolkit/installation
*
* https://github.com/translate/translate
*
* Translation Bug Reporting Process
* https://engineering.redhat.com/trac/LocalizationServices/wiki/L10nBugReportingProcess
*
* Contacts:
* hi_IN: [email protected]
* or_IN: Manoj Giri <[email protected]> <[email protected]>
*
**/
@Test(groups={"PofilterTranslationTests"})
public class PofilterTranslationTests extends SubscriptionManagerCLITestScript {
// Test Methods ***********************************************************************
@Test( description="run pofilter translate tests on subscription manager translation files",
dataProvider="getSubscriptionManagerTranslationFilePofilterTestData",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void subscriptionManagerPofilter_Test(Object bugzilla, String pofilterTest, File translationFile) {
pofilter_Test(client, pofilterTest, translationFile);
}
@Test( description="run pofilter translate tests on candlepin translation files",
dataProvider="getCandlepinTranslationFilePofilterTestData",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void candlepinPofilter_Test(Object bugzilla, String pofilterTest, File translationFile) {
pofilter_Test(server, pofilterTest, translationFile);
}
// Candidates for an automated Test:
// Configuration Methods ***********************************************************************
@BeforeClass(groups={"setup"})
public void setupBeforeClass() {
// for debugging purposes, load a reduced list of pofilterTests
if (!getProperty("sm.debug.pofilterTests", "").equals("")) pofilterTests = Arrays.asList(getProperty("sm.debug.pofilterTests", "").trim().split(" *, *"));
}
// Protected Methods ***********************************************************************
// see http://translate.sourceforge.net/wiki/toolkit/pofilter_tests
// Critical -- can break a program
// accelerators, escapes, newlines, nplurals, printf, tabs, variables, xmltags, dialogsizes
// Functional -- may confuse the user
// acronyms, blank, emails, filepaths, functions, gconf, kdecomments, long, musttranslatewords, notranslatewords, numbers, options, purepunc, sentencecount, short, spellcheck, urls, unchanged
// Cosmetic -- make it look better
// brackets, doublequoting, doublespacing, doublewords, endpunc, endwhitespace, puncspacing, simplecaps, simpleplurals, startcaps, singlequoting, startpunc, startwhitespace, validchars
// Extraction -- useful mainly for extracting certain types of string
// compendiumconflicts, credits, hassuggestion, isfuzzy, isreview, untranslated
protected List<String> pofilterTests = Arrays.asList(
// Critical -- can break a program
"accelerators", "escapes", "newlines", /*nplurals,*/ "printf", "tabs", "variables", "xmltags", /*dialogsizes,*/
// Functional -- may confuse the user
/*acronyms,*/ "blank", "emails", "filepaths", /*functions,*/ "gconf", /*kdecomments,*/ "long", /*musttranslatewords,*/ "notranslatewords", /*numbers,*/ "options", /*purepunc,*/ /*sentencecount,*/ "short", /*spellcheck,*/ "urls", "unchanged",
// Cosmetic -- make it look better
/*brackets, doublequoting, doublespacing,*/ "doublewords", /*endpunc, endwhitespace, puncspacing, simplecaps, simpleplurals, startcaps, singlequoting, startpunc, startwhitespace, validchars */
// Extraction -- useful mainly for extracting certain types of string
/*compendiumconflicts, credits, hassuggestion, isfuzzy, isreview,*/ "untranslated");
protected void pofilter_Test(SSHCommandRunner sshCommandRunner, String pofilterTest, File translationFile) {
log.info("For an explanation of pofilter test '"+pofilterTest+"', see: http://translate.sourceforge.net/wiki/toolkit/pofilter_tests");
File translationPoFile = new File(translationFile.getPath().replaceFirst(".mo$", ".po"));
List<String> ignorableMsgIds = new ArrayList<String>();
// if pofilter test -> notranslatewords, create a file with words that don't have to be translated to native language
final String notranslateFile = "/tmp/notranslatefile";
if (pofilterTest.equals("notranslatewords")) {
// The words that need not be translated can be added this list
List<String> notranslateWords = Arrays.asList("Red Hat","subscription-manager","python-rhsm");
// remove former notranslate file
sshCommandRunner.runCommandAndWait("rm -f "+notranslateFile);
// echo all of the notranslateWords to the notranslateFile
for(String str : notranslateWords) {
String echoCommand = "echo \""+str+"\" >> "+notranslateFile;
sshCommandRunner.runCommandAndWait(echoCommand);
}
Assert.assertTrue(RemoteFileTasks.testExists(sshCommandRunner, notranslateFile),"The pofilter notranslate file '"+notranslateFile+"' has been created on the client.");
}
// execute the pofilter test
String pofilterCommand = "pofilter --gnome -t "+pofilterTest;
if (pofilterTest.equals("notranslatewords")) pofilterCommand += " --notranslatefile="+notranslateFile;
SSHCommandResult pofilterResult = sshCommandRunner.runCommandAndWait(pofilterCommand+" "+translationPoFile);
Assert.assertEquals(pofilterResult.getExitCode(), new Integer(0), "Successfully executed the pofilter tests.");
// convert the pofilter test results into a list of failed Translation objects for simplified handling of special cases
List<Translation> pofilterFailedTranslations = Translation.parse(pofilterResult.getStdout());
// remove the first translation which contains only meta data
if (!pofilterFailedTranslations.isEmpty() && pofilterFailedTranslations.get(0).msgid.equals("")) pofilterFailedTranslations.remove(0);
// ignore the following special cases of acceptable results for each of the pofilterTests..........
if (pofilterTest.equals("accelerators")) {
if (translationFile.getPath().contains("/hi/")) ignorableMsgIds = Arrays.asList("proxy url in the form of proxy_hostname:proxy_port");
if (translationFile.getPath().contains("/ru/")) ignorableMsgIds = Arrays.asList("proxy url in the form of proxy_hostname:proxy_port","%%prog %s [OPTIONS] CERT_FILE");
}
if (pofilterTest.equals("newlines")) {
ignorableMsgIds = Arrays.asList(
"Optional language to use for email notification when subscription redemption is complete. Examples: en-us, de-de",
"\n"+"Unable to register.\n"+"For further assistance, please contact Red Hat Global Support Services.",
"Tip: Forgot your login or password? Look it up at http://red.ht/lost_password",
"Unable to perform refresh due to the following exception: %s",
""+"This migration script requires the system to be registered to RHN Classic.\n"+"However this system appears to be registered to '%s'.\n"+"Exiting.",
"The tool you are using is attempting to re-register using RHN Certificate-Based technology. Red Hat recommends (except in a few cases) that customers only register with RHN once.",
// bug 825397 ""+"Redeeming the subscription may take a few minutes.\n"+"Please provide an email address to receive notification\n"+"when the redemption is complete.", // the Subscription Redemption dialog actually expands to accommodate the message, therefore we could ignore it // bug 825397 should fix this
// bug 825388 ""+"We have detected that you have multiple service level\n"+"agreements on various products. Please select how you\n"+"want them assigned.", // bug 825388 or 825397 should fix this
"\n"+"This machine appears to be already registered to Certificate-based RHN. Exiting.",
"\n"+"This machine appears to be already registered to Red Hat Subscription Management. Exiting.");
}
if (pofilterTest.equals("xmltags")) {
Boolean match = false;
for(Translation pofilterFailedTranslation : pofilterFailedTranslations) {
// Parsing mgID and msgStr for XMLTags
Pattern xmlTags = Pattern.compile("<.+?>");
Matcher tagsMsgID = xmlTags.matcher(pofilterFailedTranslation.msgid);
Matcher tagsMsgStr = xmlTags.matcher(pofilterFailedTranslation.msgstr);
// Populating a msgID tags into a list
ArrayList<String> msgIDTags = new ArrayList<String>();
while(tagsMsgID.find()) {
msgIDTags.add(tagsMsgID.group());
}
// Sorting an list of msgID tags
ArrayList<String> msgIDTagsSort = new ArrayList<String>(msgIDTags);
Collections.sort(msgIDTagsSort);
// Populating a msgStr tags into a list
ArrayList<String> msgStrTags = new ArrayList<String>();
while(tagsMsgStr.find()) {
msgStrTags.add(tagsMsgStr.group());
}
// Sorting an list of msgStr tags
ArrayList<String> msgStrTagsSort = new ArrayList<String>(msgStrTags);
Collections.sort(msgStrTagsSort);
// Verifying whether XMLtags are opened and closed appropriately
// If the above condition holds, then check for XML Tag ordering
if(msgIDTagsSort.equals(msgStrTagsSort) && msgIDTagsSort.size() == msgStrTagsSort.size()) {
int size = msgIDTags.size(),count=0;
// Stack to hold XML tags
Stack<String> stackMsgIDTags = new Stack<String>();
Stack<String> stackMsgStrTags = new Stack<String>();
// Temporary stack to hold popped elements
Stack<String> tempStackMsgIDTags = new Stack<String>();
Stack<String> tempStackMsgStrTags = new Stack<String>();
while(count< size) {
// If it's not a close tag push into stack
if(!msgIDTags.get(count).contains("/")) stackMsgIDTags.push(msgIDTags.get(count));
else {
if(checkTags(stackMsgIDTags,tempStackMsgIDTags,msgIDTags.get(count))) match = true;
else {
// If an open XMLtag doesn't have an appropriate close tag exit loop
match = false;
break;
}
}
// If it's not a close tag push into stack
if(!msgStrTags.get(count).contains("/")) stackMsgStrTags.push(msgStrTags.get(count));
else {
if(checkTags(stackMsgStrTags,tempStackMsgStrTags,msgStrTags.get(count))) match = true;
else {
// If an open XMLtag doesn't have an appropriate close tag exit loop
match = false;
break;
}
}
// Incrementing count to point to the next element
count++;
}
}
if(match) ignorableMsgIds.add(pofilterFailedTranslation.msgid);
}
}
if (pofilterTest.equals("filepaths")) {
for(Translation pofilterFailedTranslation : pofilterFailedTranslations) {
// Parsing mgID and msgStr for FilePaths ending ' ' (space)
Pattern filePath = Pattern.compile("/.*?( |$)", Pattern.MULTILINE);
Matcher filePathMsgID = filePath.matcher(pofilterFailedTranslation.msgid);
Matcher filePathMsgStr = filePath.matcher(pofilterFailedTranslation.msgstr);
ArrayList<String> filePathsInID = new ArrayList<String>();
ArrayList<String> filePathsInStr = new ArrayList<String>();
// Reading the filePaths into a list
while(filePathMsgID.find()) {
filePathsInID.add(filePathMsgID.group());
}
while(filePathMsgStr.find()) {
filePathsInStr.add(filePathMsgStr.group());
}
// If the lists are equal in size, then compare the contents of msdID->filePath and msgStr->filePath
//if(filePathsInID.size() == filePathsInStr.size()) {
for(int i=0;i<filePathsInID.size();i++) {
// If the msgID->filePath ends with '.', remove '.' and compare with msgStr->filePath
if(filePathsInID.get(i).trim().startsWith("//")) {
ignorableMsgIds.add(pofilterFailedTranslation.msgid);
continue;
}
//contains("//")) ignoreMsgIDs.add(pofilterFailedTranslation.msgid);
if(filePathsInID.get(i).trim().charAt(filePathsInID.get(i).trim().length()-1) == '.') {
String filePathID = filePathsInID.get(i).trim().substring(0, filePathsInID.get(i).trim().length()-1);
if(filePathID.equals(filePathsInStr.get(i).trim())) ignorableMsgIds.add(pofilterFailedTranslation.msgid);
}
/*else {
if(filePathsInID.get(i).trim().equals(filePathsInStr.get(i).trim())) ignoreMsgIDs.add(pofilterFailedTranslation.msgid);
}*/
}
//}
}
}
// TODO remove or comment this ignore case once the msgID is corrected
// error: msgid "Error: you must register or specify --username and password to list service levels"
// rectified: msgid "Error: you must register or specify --username and --password to list service levels"
if (pofilterTest.equals("options")) {
ignorableMsgIds = Arrays.asList("Error: you must register or specify --username and password to list service levels");
}
if (pofilterTest.equals("short")) {
ignorableMsgIds = Arrays.asList("No","Yes","Key","Value","N/A","None","Number");
}
if (pofilterTest.equals("doublewords")) {
// common doublewords in the translation to ignore for all langs
ignorableMsgIds.addAll(Arrays.asList("Subscription Subscriptions Box","Subscription Subscriptions Label"));
// doublewords in the translation to ignore for specific langs
if((translationFile.getPath().contains("/pa/"))) ignorableMsgIds.addAll(Arrays.asList("Server URL can not be None"));
if((translationFile.getPath().contains("/hi/"))) ignorableMsgIds.addAll(Arrays.asList("Server URL can not be None")); // more info in bug 861095
if((translationFile.getPath().contains("/fr/"))) ignorableMsgIds.addAll(Arrays.asList("The Subscription Management Service you register with will provide your system with updates and allow additional management.")); // msgstr "Le service de gestion des abonnements « Subscription Management » avec lequel vous vous enregistrez fournira à votre système des mises à jour et permettra une gestion supplémentaire."
if((translationFile.getPath().contains("/or/"))) ignorableMsgIds.addAll(Arrays.asList("Run the initial checks immediately, with no delay.","Run the initial checks immediatly, with no delay."));
}
if (pofilterTest.equals("unchanged")) {
// common unchanged translations to ignore for all langs
ignorableMsgIds.addAll(Arrays.asList("registration_dialog_action_area","server_label","server_entry","proxy_button","hostname[:port][/prefix]","default_button","choose_server_label","<b>SKU:</b>","%prog [options]","%prog [OPTIONS]","%%prog %s [OPTIONS]","%%prog %s [OPTIONS] CERT_FILE"/*SEE BUG 845304*/,"<b>HTTP Proxy</b>","<b>python-rhsm version:</b> %s","<b>python-rhsm Version:</b> %s","close_button","facts_view","register_button","register_dialog_main_vbox","registration_dialog_action_area\n","prod 1, prod2, prod 3, prod 4, prod 5, prod 6, prod 7, prod 8","%s of %s","floating-point","integer","long integer","Copyright (c) 2012 Red Hat, Inc.","RHN Classic","env_select_vbox_label","environment_treeview","no_subs_label","org_selection_label","org_selection_scrolledwindow","owner_treeview","progress_label","subscription-manager: %s","python-rhsm: %s","register_details_label","register_progressbar","system_instructions_label","system_name_label","connectionStatusLabel",""+"\n"+"This software is licensed to you under the GNU General Public License, version 2 (GPLv2). There is NO WARRANTY for this software, express or implied, including the implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 along with this software; if not, see:\n"+"\n"+"http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt\n"+"\n"+"Red Hat trademarks are not licensed under GPLv2. No permission is granted to use or replicate Red Hat trademarks that are incorporated in this software or its documentation.\n","progress_label","Red Hat Subscription Manager", "Red Hat Subscription Validity Applet"));
// unchanged translations to ignore for specific langs
if (translationFile.getPath().contains("/bn_IN/")) ignorableMsgIds.addAll(Arrays.asList("Red Hat Subscription Validity Applet","Subscription Validity Applet"));
if (translationFile.getPath().contains("/ta_IN/")) ignorableMsgIds.addAll(Arrays.asList("Org: ","org id: %s","Repo Id: \\t%s","Repo Url: \\t%s"));
if (translationFile.getPath().contains("/pt_BR/")) ignorableMsgIds.addAll(Arrays.asList("Org: ","org id: %s","<b>subscription management service version:</b> %s","Status","Status: \\t%s","Login:","Virtual","_Help","hostname[:port][/prefix]","virtual"));
if (translationFile.getPath().contains("/de_DE/")) ignorableMsgIds.addAll(Arrays.asList("Subscription Manager","Red Hat account: ","Account","<b>Account:</b>","Account: \\t%s","<b>Subscription Management Service Version:</b> %s","<b>subscription management service version:</b> %s","Login:","Name","Name: \\t%s","Status","Status: \\t%s","Version","Version: \\t%s","_System","long integer","name: %s","label","Label","Name: %s","Release: %s","integer","Tags","Org: "));
if (translationFile.getPath().contains("/es_ES/")) ignorableMsgIds.addAll(Arrays.asList("Org: ","Serial","No","%s: error: %s"));
if (translationFile.getPath().contains("/te/")) ignorableMsgIds.addAll(Arrays.asList("page 2"));
if (translationFile.getPath().contains("/pa/")) ignorableMsgIds.addAll(Arrays.asList("<b>python-rhsm version:</b> %s"));
if (translationFile.getPath().contains("/fr/")) ignorableMsgIds.addAll(Arrays.asList("Options","options","Type","Arch","Version","page 2"));
if (translationFile.getPath().contains("/it/")) ignorableMsgIds.addAll(Arrays.asList("Org: ","Account","<b>Account:</b>","Account: \\t%s","<b>Arch:</b>","Arch: \\t%s","Arch","Login:","No","Password:","Release: %s","Password: "));
}
if (pofilterTest.equals("urls")) {
if(translationFile.getPath().contains("/zh_CN/")) ignorableMsgIds.addAll(Arrays.asList("Server URL has an invalid scheme. http:// and https:// are supported"));
}
// pluck out the ignorable pofilter test results
for (String msgid : ignorableMsgIds) {
Translation ignoreTranslation = Translation.findFirstInstanceWithMatchingFieldFromList("msgid", msgid, pofilterFailedTranslations);
if (ignoreTranslation!=null) {
log.info("Ignoring result of pofiliter test '"+pofilterTest+"' for msgid: "+ignoreTranslation.msgid);
pofilterFailedTranslations.remove(ignoreTranslation);
}
}
// for convenience reading the logs, log warnings for the failed pofilter test results (when some of the failed test are being ignored)
if (!ignorableMsgIds.isEmpty()) for (Translation pofilterFailedTranslation : pofilterFailedTranslations) {
log.warning("Failed result of pofiliter test '"+pofilterTest+"' for translation: "+pofilterFailedTranslation);
}
// assert that there are no failed pofilter translation test results remaining after the ignorable pofilter test results have been plucked out
Assert.assertEquals(pofilterFailedTranslations.size(),0, "Discounting the ignored test results, the number of failed pofilter '"+pofilterTest+"' tests for translation file '"+translationFile+"'.");
}
/**
* @param str
* @return the tag character (Eg: <b> or </b> return_val = 'b')
*/
protected char parseElement(String str){
return str.charAt(str.length()-2);
}
/**
* @param tags
* @param temp
* @param tagElement
* @return whether every open tag has an appropriate close tag in order
*/
protected Boolean checkTags(Stack<String> tags, Stack<String> temp, String tagElement) {
// If there are no open tags in the stack -> return
if(tags.empty()) return false;
String popElement = tags.pop();
// If openTag in stack = closeTag -> return
if(!popElement.contains("/") && parseElement(popElement) == parseElement(tagElement)) return true;
else {
// Continue popping elements from stack and push to temp until appropriate open tag is found
while(popElement.contains("/") || parseElement(popElement) != parseElement(tagElement)) {
temp.push(popElement);
// If stack = empty and no match, push back the popped elements -> return
if(tags.empty()) {
while(!temp.empty()) {
tags.push(temp.pop());
}
return false;
}
popElement = tags.pop();
}
// If a match is found, push back the popped elements -> return
while(!temp.empty()) tags.push(temp.pop());
}
return true;
}
// Data Providers ***********************************************************************
@DataProvider(name="getSubscriptionManagerTranslationFilePofilterTestData")
public Object[][] getSubscriptionManagerTranslationFilePofilterTestDataAs2dArray() {
return TestNGUtils.convertListOfListsTo2dArray(getSubscriptionManagerTranslationFilePofilterTestDataAsListOfLists());
}
protected List<List<Object>> getSubscriptionManagerTranslationFilePofilterTestDataAsListOfLists() {
List<List<Object>> ll = new ArrayList<List<Object>>();
// Client side
Map<File,List<Translation>> translationFileMapForSubscriptionManager = buildTranslationFileMapForSubscriptionManager();
for (File translationFile : translationFileMapForSubscriptionManager.keySet()) {
for (String pofilterTest : pofilterTests) {
Set<String> bugIds = new HashSet<String>();
// Bug 825362 [es_ES] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825362");
// Bug 825367 [zh_CN] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("825367");
// Bug 860084 - [ja_JP] two accelerators for msgid "Configure Pro_xy"
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/ja/")) bugIds.add("860084");
// Bug 825397 Many translated languages fail the pofilter newlines test
if (pofilterTest.equals("newlines") && !(translationFile.getPath().contains("/zh_CN/")||translationFile.getPath().contains("/ru/")||translationFile.getPath().contains("/ja/"))) bugIds.add("825397");
// Bug 825393 [ml_IN][es_ES] translations should not use character ¶ for a new line.
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/ml/")) bugIds.add("825393");
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825393");
// Bug 827059 [kn] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/kn/")) bugIds.add("827059");
// Bug 827079 [es-ES] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/es_ES/")) bugIds.add("827079");
// Bug 827085 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/hi/")) bugIds.add("827085");
// Bug 827089 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/te/")) bugIds.add("827089");
// Bug 827113 Many Translated languages fail the pofilter tabs test
if (pofilterTest.equals("tabs") && !(translationFile.getPath().contains("/pa/")||translationFile.getPath().contains("/mr/")||translationFile.getPath().contains("/de_DE/")||translationFile.getPath().contains("/bn_IN/"))) bugIds.add("825397");
// Bug 827161 [bn_IN] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("827161");
// Bug 827208 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/or/")) bugIds.add("827208");
// Bug 827214 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("827214");
// Bug 828368 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828368");
// Bug 828365 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828365");
// Bug 828372 - [es_ES] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828372");
// Bug 828416 - [ru] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ru/")) bugIds.add("828416");
// Bug 843113 - [ta_IN] failed pofilter xmltags test for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("843113");
// Bug 828566 [bn-IN] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828566");
// Bug 828567 [as] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/as/")) bugIds.add("828567");
// Bug 828576 - [ta_IN] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828576");
// Bug 828579 - [ml] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ml/")) bugIds.add("828579");
// Bug 828580 - [mr] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/mr/")) bugIds.add("828580");
// Bug 828583 - [ko] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ko/")) bugIds.add("828583");
// Bug 828810 - [kn] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/kn/")) bugIds.add("828810");
// Bug 828816 - [es_ES] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828816");
// Bug 828821 - [hi] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/hi/")) bugIds.add("828821");
// Bug 828867 - [te] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/te/")) bugIds.add("828867");
// Bug 828903 - [bn_IN] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828903");
// Bug 828930 - [as] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/as/")) bugIds.add("828930");
// Bug 828948 - [or] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/or/")) bugIds.add("828948");
// Bug 828954 - [ta_IN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828954");
// Bug 828958 - [pt_BR] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828958");
// Bug 828961 - [gu] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/gu/")) bugIds.add("828961");
// Bug 828965 - [hi] failed pofilter options test for subscription-manager trasnlations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/hi/")) bugIds.add("828965");
// Bug 828966 - [zh_CN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("828966");
// Bug 828969 - [te] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/te/")) bugIds.add("828969");
// Bug 842898 - [it] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/it/")) bugIds.add("842898");
// Bug 828985 - [ml] failed pofilter urls test for subscription manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/ml/")) bugIds.add("828985");
// Bug 828989 - [pt_BR] failed pofilter urls test for subscription-manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828989");
// Bug 860088 - [de_DE] translation for a url should not be altered
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/de_DE/")) bugIds.add("860088");
// Bug 845304 - translation of the word "[OPTIONS]" has reverted
if (pofilterTest.equals("unchanged")) bugIds.add("845304");
// Bug 829459 - [bn_IN] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("829459");
// Bug 829470 - [or] failed pofilter unchanged options for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/or/")) bugIds.add("829470");
// Bug 829471 - [ta_IN] failed pofilter unchanged optioon test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("829471");
// Bug 829476 - [ml] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ml/")) bugIds.add("829476");
// Bug 829479 - [pt_BR] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) {bugIds.add("829479"); bugIds.add("828958");}
// Bug 829482 - [zh_TW] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_TW/")) bugIds.add("829482");
// Bug 829483 - [de_DE] failed pofilter unchanged options test for suubscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/de_DE/")) bugIds.add("829483");
// Bug 829486 - [fr] failed pofilter unchanged options test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/fr/")) bugIds.add("829486");
// Bug 829488 - [es_ES] failed pofilter unchanged option tests for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("829488");
// Bug 829491 - [it] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/it/")) bugIds.add("829491");
// Bug 829492 - [hi] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/hi/")) bugIds.add("829492");
// Bug 829494 - [zh_CN] failed pofilter unchanged option for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("829494");
// Bug 829495 - [pa] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pa/")) bugIds.add("829495");
// Bug 840914 - [te] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/te/")) bugIds.add("840914");
// Bug 840644 - [ta_IN] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("840644");
// Bug 855087 - [mr] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/mr/")) bugIds.add("855087");
// Bug 855085 - [as] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/as/")) bugIds.add("855085");
// Bug 855081 - [pt_BR] untranslated msgid "Arch"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("855081");
- // Bug 864095 - [fr_FR] unchanged translation for msgid "System Engine Username: "
- if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/fr/")) bugIds.add("864095");
+ // Bug 864095 - [it_IT] unchanged translation for msgid "System Engine Username: "
+ if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/it/")) bugIds.add("864095");
// Bug 864092 - [es_ES] unchanged translation for msgid "Configure Proxy"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("864092");
// Bug 841011 - [kn] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/kn/")) bugIds.add("841011");
// Bug 861095 - [hi_IN] duplicate words appear in two msgid translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/hi/")) bugIds.add("861095");
BlockedByBzBug blockedByBzBug = new BlockedByBzBug(bugIds.toArray(new String[]{}));
ll.add(Arrays.asList(new Object[] {blockedByBzBug, pofilterTest, translationFile}));
}
}
return ll;
}
@DataProvider(name="getCandlepinTranslationFilePofilterTestData")
public Object[][] getCandlepinTranslationFilePofilterTestDataAs2dArray() {
return TestNGUtils.convertListOfListsTo2dArray(getCandlepinTranslationFilePofilterTestDataAsListOfLists());
}
protected List<List<Object>> getCandlepinTranslationFilePofilterTestDataAsListOfLists() {
List<List<Object>> ll = new ArrayList<List<Object>>();
// Server side
Map<File,List<Translation>> translationFileMapForCandlepin = buildTranslationFileMapForCandlepin();
for (File translationFile : translationFileMapForCandlepin.keySet()) {
for (String pofilterTest : pofilterTests) {
BlockedByBzBug bugzilla = null;
// Bug 842450 - [ja_JP] failed pofilter newlines option test for candlepin translations
if (pofilterTest.equals("newlines") && translationFile.getName().equals("ja.po")) bugzilla = new BlockedByBzBug("842450");
if (pofilterTest.equals("tabs") && translationFile.getName().equals("ja.po")) bugzilla = new BlockedByBzBug("842450");
// Bug 842784 - [ALL LANG] failed pofilter untranslated option test for candlepin translations
if (pofilterTest.equals("untranslated")) bugzilla = new BlockedByBzBug("842784");
// Bug 865561 - [pa_IN] the pofilter escapes test is failing on msgid "Consumer Type with id {0} could not be found."
if (pofilterTest.equals("escapes")) bugzilla = new BlockedByBzBug("865561");
ll.add(Arrays.asList(new Object[] {bugzilla, pofilterTest, translationFile}));
}
}
return ll;
}
}
| true | true | protected List<List<Object>> getSubscriptionManagerTranslationFilePofilterTestDataAsListOfLists() {
List<List<Object>> ll = new ArrayList<List<Object>>();
// Client side
Map<File,List<Translation>> translationFileMapForSubscriptionManager = buildTranslationFileMapForSubscriptionManager();
for (File translationFile : translationFileMapForSubscriptionManager.keySet()) {
for (String pofilterTest : pofilterTests) {
Set<String> bugIds = new HashSet<String>();
// Bug 825362 [es_ES] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825362");
// Bug 825367 [zh_CN] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("825367");
// Bug 860084 - [ja_JP] two accelerators for msgid "Configure Pro_xy"
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/ja/")) bugIds.add("860084");
// Bug 825397 Many translated languages fail the pofilter newlines test
if (pofilterTest.equals("newlines") && !(translationFile.getPath().contains("/zh_CN/")||translationFile.getPath().contains("/ru/")||translationFile.getPath().contains("/ja/"))) bugIds.add("825397");
// Bug 825393 [ml_IN][es_ES] translations should not use character ¶ for a new line.
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/ml/")) bugIds.add("825393");
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825393");
// Bug 827059 [kn] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/kn/")) bugIds.add("827059");
// Bug 827079 [es-ES] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/es_ES/")) bugIds.add("827079");
// Bug 827085 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/hi/")) bugIds.add("827085");
// Bug 827089 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/te/")) bugIds.add("827089");
// Bug 827113 Many Translated languages fail the pofilter tabs test
if (pofilterTest.equals("tabs") && !(translationFile.getPath().contains("/pa/")||translationFile.getPath().contains("/mr/")||translationFile.getPath().contains("/de_DE/")||translationFile.getPath().contains("/bn_IN/"))) bugIds.add("825397");
// Bug 827161 [bn_IN] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("827161");
// Bug 827208 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/or/")) bugIds.add("827208");
// Bug 827214 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("827214");
// Bug 828368 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828368");
// Bug 828365 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828365");
// Bug 828372 - [es_ES] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828372");
// Bug 828416 - [ru] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ru/")) bugIds.add("828416");
// Bug 843113 - [ta_IN] failed pofilter xmltags test for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("843113");
// Bug 828566 [bn-IN] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828566");
// Bug 828567 [as] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/as/")) bugIds.add("828567");
// Bug 828576 - [ta_IN] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828576");
// Bug 828579 - [ml] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ml/")) bugIds.add("828579");
// Bug 828580 - [mr] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/mr/")) bugIds.add("828580");
// Bug 828583 - [ko] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ko/")) bugIds.add("828583");
// Bug 828810 - [kn] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/kn/")) bugIds.add("828810");
// Bug 828816 - [es_ES] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828816");
// Bug 828821 - [hi] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/hi/")) bugIds.add("828821");
// Bug 828867 - [te] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/te/")) bugIds.add("828867");
// Bug 828903 - [bn_IN] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828903");
// Bug 828930 - [as] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/as/")) bugIds.add("828930");
// Bug 828948 - [or] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/or/")) bugIds.add("828948");
// Bug 828954 - [ta_IN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828954");
// Bug 828958 - [pt_BR] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828958");
// Bug 828961 - [gu] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/gu/")) bugIds.add("828961");
// Bug 828965 - [hi] failed pofilter options test for subscription-manager trasnlations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/hi/")) bugIds.add("828965");
// Bug 828966 - [zh_CN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("828966");
// Bug 828969 - [te] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/te/")) bugIds.add("828969");
// Bug 842898 - [it] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/it/")) bugIds.add("842898");
// Bug 828985 - [ml] failed pofilter urls test for subscription manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/ml/")) bugIds.add("828985");
// Bug 828989 - [pt_BR] failed pofilter urls test for subscription-manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828989");
// Bug 860088 - [de_DE] translation for a url should not be altered
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/de_DE/")) bugIds.add("860088");
// Bug 845304 - translation of the word "[OPTIONS]" has reverted
if (pofilterTest.equals("unchanged")) bugIds.add("845304");
// Bug 829459 - [bn_IN] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("829459");
// Bug 829470 - [or] failed pofilter unchanged options for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/or/")) bugIds.add("829470");
// Bug 829471 - [ta_IN] failed pofilter unchanged optioon test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("829471");
// Bug 829476 - [ml] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ml/")) bugIds.add("829476");
// Bug 829479 - [pt_BR] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) {bugIds.add("829479"); bugIds.add("828958");}
// Bug 829482 - [zh_TW] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_TW/")) bugIds.add("829482");
// Bug 829483 - [de_DE] failed pofilter unchanged options test for suubscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/de_DE/")) bugIds.add("829483");
// Bug 829486 - [fr] failed pofilter unchanged options test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/fr/")) bugIds.add("829486");
// Bug 829488 - [es_ES] failed pofilter unchanged option tests for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("829488");
// Bug 829491 - [it] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/it/")) bugIds.add("829491");
// Bug 829492 - [hi] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/hi/")) bugIds.add("829492");
// Bug 829494 - [zh_CN] failed pofilter unchanged option for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("829494");
// Bug 829495 - [pa] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pa/")) bugIds.add("829495");
// Bug 840914 - [te] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/te/")) bugIds.add("840914");
// Bug 840644 - [ta_IN] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("840644");
// Bug 855087 - [mr] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/mr/")) bugIds.add("855087");
// Bug 855085 - [as] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/as/")) bugIds.add("855085");
// Bug 855081 - [pt_BR] untranslated msgid "Arch"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("855081");
// Bug 864095 - [fr_FR] unchanged translation for msgid "System Engine Username: "
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/fr/")) bugIds.add("864095");
// Bug 864092 - [es_ES] unchanged translation for msgid "Configure Proxy"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("864092");
// Bug 841011 - [kn] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/kn/")) bugIds.add("841011");
// Bug 861095 - [hi_IN] duplicate words appear in two msgid translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/hi/")) bugIds.add("861095");
BlockedByBzBug blockedByBzBug = new BlockedByBzBug(bugIds.toArray(new String[]{}));
ll.add(Arrays.asList(new Object[] {blockedByBzBug, pofilterTest, translationFile}));
}
}
| protected List<List<Object>> getSubscriptionManagerTranslationFilePofilterTestDataAsListOfLists() {
List<List<Object>> ll = new ArrayList<List<Object>>();
// Client side
Map<File,List<Translation>> translationFileMapForSubscriptionManager = buildTranslationFileMapForSubscriptionManager();
for (File translationFile : translationFileMapForSubscriptionManager.keySet()) {
for (String pofilterTest : pofilterTests) {
Set<String> bugIds = new HashSet<String>();
// Bug 825362 [es_ES] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825362");
// Bug 825367 [zh_CN] failed pofilter accelerator tests for subscription-manager translations
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("825367");
// Bug 860084 - [ja_JP] two accelerators for msgid "Configure Pro_xy"
if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/ja/")) bugIds.add("860084");
// Bug 825397 Many translated languages fail the pofilter newlines test
if (pofilterTest.equals("newlines") && !(translationFile.getPath().contains("/zh_CN/")||translationFile.getPath().contains("/ru/")||translationFile.getPath().contains("/ja/"))) bugIds.add("825397");
// Bug 825393 [ml_IN][es_ES] translations should not use character ¶ for a new line.
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/ml/")) bugIds.add("825393");
if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/es_ES/")) bugIds.add("825393");
// Bug 827059 [kn] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/kn/")) bugIds.add("827059");
// Bug 827079 [es-ES] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/es_ES/")) bugIds.add("827079");
// Bug 827085 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/hi/")) bugIds.add("827085");
// Bug 827089 [hi] translation fails for printf test
if (pofilterTest.equals("printf") && translationFile.getPath().contains("/te/")) bugIds.add("827089");
// Bug 827113 Many Translated languages fail the pofilter tabs test
if (pofilterTest.equals("tabs") && !(translationFile.getPath().contains("/pa/")||translationFile.getPath().contains("/mr/")||translationFile.getPath().contains("/de_DE/")||translationFile.getPath().contains("/bn_IN/"))) bugIds.add("825397");
// Bug 827161 [bn_IN] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("827161");
// Bug 827208 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/or/")) bugIds.add("827208");
// Bug 827214 [or] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("827214");
// Bug 828368 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828368");
// Bug 828365 - [kn] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/kn/")) bugIds.add("828365");
// Bug 828372 - [es_ES] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828372");
// Bug 828416 - [ru] failed pofilter xmltags tests for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ru/")) bugIds.add("828416");
// Bug 843113 - [ta_IN] failed pofilter xmltags test for subscription-manager translations
if (pofilterTest.equals("xmltags") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("843113");
// Bug 828566 [bn-IN] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828566");
// Bug 828567 [as] cosmetic bug for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/as/")) bugIds.add("828567");
// Bug 828576 - [ta_IN] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828576");
// Bug 828579 - [ml] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ml/")) bugIds.add("828579");
// Bug 828580 - [mr] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/mr/")) bugIds.add("828580");
// Bug 828583 - [ko] failed pofilter filepaths tests for subscription-manager translations
if (pofilterTest.equals("filepaths") && translationFile.getPath().contains("/ko/")) bugIds.add("828583");
// Bug 828810 - [kn] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/kn/")) bugIds.add("828810");
// Bug 828816 - [es_ES] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/es_ES/")) bugIds.add("828816");
// Bug 828821 - [hi] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/hi/")) bugIds.add("828821");
// Bug 828867 - [te] failed pofilter varialbes tests for subscription-manager translations
if (pofilterTest.equals("variables") && translationFile.getPath().contains("/te/")) bugIds.add("828867");
// Bug 828903 - [bn_IN] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("828903");
// Bug 828930 - [as] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/as/")) bugIds.add("828930");
// Bug 828948 - [or] failed pofilter options tests for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/or/")) bugIds.add("828948");
// Bug 828954 - [ta_IN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("828954");
// Bug 828958 - [pt_BR] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828958");
// Bug 828961 - [gu] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/gu/")) bugIds.add("828961");
// Bug 828965 - [hi] failed pofilter options test for subscription-manager trasnlations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/hi/")) bugIds.add("828965");
// Bug 828966 - [zh_CN] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("828966");
// Bug 828969 - [te] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/te/")) bugIds.add("828969");
// Bug 842898 - [it] failed pofilter options test for subscription-manager translations
if (pofilterTest.equals("options") && translationFile.getPath().contains("/it/")) bugIds.add("842898");
// Bug 828985 - [ml] failed pofilter urls test for subscription manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/ml/")) bugIds.add("828985");
// Bug 828989 - [pt_BR] failed pofilter urls test for subscription-manager translations
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("828989");
// Bug 860088 - [de_DE] translation for a url should not be altered
if (pofilterTest.equals("urls") && translationFile.getPath().contains("/de_DE/")) bugIds.add("860088");
// Bug 845304 - translation of the word "[OPTIONS]" has reverted
if (pofilterTest.equals("unchanged")) bugIds.add("845304");
// Bug 829459 - [bn_IN] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/bn_IN/")) bugIds.add("829459");
// Bug 829470 - [or] failed pofilter unchanged options for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/or/")) bugIds.add("829470");
// Bug 829471 - [ta_IN] failed pofilter unchanged optioon test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("829471");
// Bug 829476 - [ml] failed pofilter unchanged option test for subscription-manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ml/")) bugIds.add("829476");
// Bug 829479 - [pt_BR] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) {bugIds.add("829479"); bugIds.add("828958");}
// Bug 829482 - [zh_TW] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_TW/")) bugIds.add("829482");
// Bug 829483 - [de_DE] failed pofilter unchanged options test for suubscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/de_DE/")) bugIds.add("829483");
// Bug 829486 - [fr] failed pofilter unchanged options test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/fr/")) bugIds.add("829486");
// Bug 829488 - [es_ES] failed pofilter unchanged option tests for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("829488");
// Bug 829491 - [it] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/it/")) bugIds.add("829491");
// Bug 829492 - [hi] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/hi/")) bugIds.add("829492");
// Bug 829494 - [zh_CN] failed pofilter unchanged option for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/zh_CN/")) bugIds.add("829494");
// Bug 829495 - [pa] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pa/")) bugIds.add("829495");
// Bug 840914 - [te] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/te/")) bugIds.add("840914");
// Bug 840644 - [ta_IN] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/ta_IN/")) bugIds.add("840644");
// Bug 855087 - [mr] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/mr/")) bugIds.add("855087");
// Bug 855085 - [as] missing translation for the word "OPTIONS"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/as/")) bugIds.add("855085");
// Bug 855081 - [pt_BR] untranslated msgid "Arch"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/pt_BR/")) bugIds.add("855081");
// Bug 864095 - [it_IT] unchanged translation for msgid "System Engine Username: "
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/it/")) bugIds.add("864095");
// Bug 864092 - [es_ES] unchanged translation for msgid "Configure Proxy"
if (pofilterTest.equals("unchanged") && translationFile.getPath().contains("/es_ES/")) bugIds.add("864092");
// Bug 841011 - [kn] failed pofilter unchanged option test for subscription manager translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/kn/")) bugIds.add("841011");
// Bug 861095 - [hi_IN] duplicate words appear in two msgid translations
if (pofilterTest.equals("doublewords") && translationFile.getPath().contains("/hi/")) bugIds.add("861095");
BlockedByBzBug blockedByBzBug = new BlockedByBzBug(bugIds.toArray(new String[]{}));
ll.add(Arrays.asList(new Object[] {blockedByBzBug, pofilterTest, translationFile}));
}
}
|
diff --git a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/home/AddressHome.java b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/home/AddressHome.java
index bfc9b582..f75ddef0 100644
--- a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/home/AddressHome.java
+++ b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/home/AddressHome.java
@@ -1,72 +1,72 @@
/**
*
*/
package gr.sch.ira.minoas.seam.components.home;
import gr.sch.ira.minoas.model.core.Address;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
/**
* @author <a href="mailto:[email protected]">Filippos Slavik</a>
* @version $Id$
*/
@Name("addressHome")
@Scope(ScopeType.CONVERSATION)
public class AddressHome extends MinoasEntityHome<Address> {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @see org.jboss.seam.framework.Home#createInstance()
*/
@Override
protected Address createInstance() {
Address instance = new Address();
return instance;
}
/**
* @see org.jboss.seam.framework.Home#getInstance()
*/
@Override
@Factory(value = "address", scope = ScopeType.PAGE)
public Address getInstance() {
// TODO Auto-generated method stub
return (Address) super.getInstance();
}
/**
* @see gr.sch.ira.minoas.seam.components.home.MinoasEntityHome#persist()
*/
@Override
@Transactional
public String persist() {
return super.persist();
}
@Transactional
public String revert() {
- info("principal #0 is reverting updates to adress #1", getPrincipalName(), getInstance());
+ info("principal #0 is reverting updates to address #1", getPrincipalName(), getInstance());
getEntityManager().refresh(getInstance());
return "reverted";
}
/**
* @see gr.sch.ira.minoas.seam.components.home.MinoasEntityHome#update()
*/
@Override
@Transactional
public String update() {
return super.update();
}
}
| true | true | public String revert() {
info("principal #0 is reverting updates to adress #1", getPrincipalName(), getInstance());
getEntityManager().refresh(getInstance());
return "reverted";
}
| public String revert() {
info("principal #0 is reverting updates to address #1", getPrincipalName(), getInstance());
getEntityManager().refresh(getInstance());
return "reverted";
}
|
diff --git a/src/java/net/sf/jabref/imports/ScifinderImporter.java b/src/java/net/sf/jabref/imports/ScifinderImporter.java
index c314af089..08e70260d 100644
--- a/src/java/net/sf/jabref/imports/ScifinderImporter.java
+++ b/src/java/net/sf/jabref/imports/ScifinderImporter.java
@@ -1,125 +1,136 @@
package net.sf.jabref.imports;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import net.sf.jabref.BibtexEntry;
import net.sf.jabref.Globals;
import net.sf.jabref.AuthorList;
import net.sf.jabref.BibtexFields;
/**
* Imports a Biblioscape Tag File. The format is described on
* http://www.biblioscape.com/manual_bsp/Biblioscape_Tag_File.htm Several
* Biblioscape field types are ignored. Others are only included in the BibTeX
* field "comment".
*/
public class ScifinderImporter extends ImportFormat {
/**
* Return the name of this import format.
*/
public String getFormatName() {
return "Scifinder";
}
/*
* (non-Javadoc)
* @see net.sf.jabref.imports.ImportFormat#getCLIId()
*/
public String getCLIId() {
return "scifinder";
}
/**
* Check whether the source is in the correct format for this importer.
*/
public boolean isRecognizedFormat(InputStream stream) throws IOException {
BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream));
String str;
int i=0;
while (((str = in.readLine()) != null) && (i < 50)) {
if (str.trim().equals("START_RECORD"))
return true;
i++;
}
return false;
}
/**
* Parse the entries in the source, and return a List of BibtexEntry
* objects.
*/
public List<BibtexEntry> importEntries(InputStream stream) throws IOException {
ArrayList<BibtexEntry> bibitems = new ArrayList<BibtexEntry>();
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream));
String str;
String number = "";
String country = "";
String kindcode = "";
while ((str = in.readLine()) != null){
sb.append(str);
}
String[] entries = sb.toString().split("START_RECORD");
HashMap<String, String> hm = new HashMap<String, String>();
for (int i = 1; i < entries.length; i++){
String[] fields = entries[i].split("FIELD ");
+ String journal = null;
String Type = "";
hm.clear(); // reset
for (int j = 0; j < fields.length; j++)
if (fields[j].indexOf(":") >= 0){
String tmp[] = new String[2];
tmp[0] = fields[j].substring(0, fields[j].indexOf(":"));
tmp[1] = fields[j].substring(fields[j].indexOf(":") + 1).trim();
if (tmp.length > 1){//==2
if (tmp[0].equals("Author")) hm.put("author", AuthorList.fixAuthor_lastNameFirst(tmp[1].replaceAll(";", " and ")));
else if (tmp[0].equals("Title")) hm.put("title", tmp[1]);
- else if (tmp[0].equals("Journal Title")) hm.put("journal", tmp[1]);
+ else if (tmp[0].equals("Journal Title")) {
+ journal = tmp[1];
+ }
else if (tmp[0].equals("Volume")) hm.put("volume", tmp[1]);
else if (tmp[0].equals("Page")) hm.put("pages", tmp[1]);
else if (tmp[0].equals("Publication Year")) hm.put("year", tmp[1]);
else if (tmp[0].equals("Abstract")) hm.put("abstract", tmp[1]);
else if (tmp[0].equals("Supplementary Terms")) hm.put("keywords",
tmp[1]);
- else if (tmp[0].equals("Inventor Name")) hm.put("author", AuthorList.fixAuthor_lastNameFirst(tmp[1].replaceAll(";", " and ")));
+ else if (tmp[0].equals("Inventor Name") && (tmp[1].trim().length() > 0)) hm.put("author", AuthorList.fixAuthor_lastNameFirst(tmp[1].replaceAll(";", " and ")));
else if (tmp[0].equals("Patent Assignee")) hm.put("institution", tmp[1]);
else if (tmp[0].equals("Patent Kind Code")) kindcode = " " + tmp[1];
else if (tmp[0].equals("Patent Country")) country = tmp[1] + " ";
else if (tmp[0].equals("Patent Number")) number = tmp[1];
else if (tmp[0].equals("Priority Application Date")) hm.put("number", country + number + kindcode);
else if (tmp[0].equals("Document Type")) {
if (tmp[1].startsWith("Journal") || tmp[1].startsWith("Review"))
Type = "article";
else if (tmp[1].equals("Dissertation"))
Type = "phdthesis";
else if (tmp[1].equals("Patent"))
Type = "patent";
+ else if (tmp[1].startsWith("Conference"))
+ Type = "conference";
else
Type = tmp[1];
}
}
}
BibtexEntry b = new BibtexEntry(BibtexFields.DEFAULT_BIBTEXENTRY_ID, Globals
.getEntryType(Type)); // id assumes an existing database so don't
// create one here
b.setField(hm);
+ if (journal != null) {
+ if (Type.equals("conference"))
+ b.setField("booktitle", journal);
+ else
+ b.setField("journal", journal);
+ }
bibitems.add(b);
}
return bibitems;
}
}
| false | true | public List<BibtexEntry> importEntries(InputStream stream) throws IOException {
ArrayList<BibtexEntry> bibitems = new ArrayList<BibtexEntry>();
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream));
String str;
String number = "";
String country = "";
String kindcode = "";
while ((str = in.readLine()) != null){
sb.append(str);
}
String[] entries = sb.toString().split("START_RECORD");
HashMap<String, String> hm = new HashMap<String, String>();
for (int i = 1; i < entries.length; i++){
String[] fields = entries[i].split("FIELD ");
String Type = "";
hm.clear(); // reset
for (int j = 0; j < fields.length; j++)
if (fields[j].indexOf(":") >= 0){
String tmp[] = new String[2];
tmp[0] = fields[j].substring(0, fields[j].indexOf(":"));
tmp[1] = fields[j].substring(fields[j].indexOf(":") + 1).trim();
if (tmp.length > 1){//==2
if (tmp[0].equals("Author")) hm.put("author", AuthorList.fixAuthor_lastNameFirst(tmp[1].replaceAll(";", " and ")));
else if (tmp[0].equals("Title")) hm.put("title", tmp[1]);
else if (tmp[0].equals("Journal Title")) hm.put("journal", tmp[1]);
else if (tmp[0].equals("Volume")) hm.put("volume", tmp[1]);
else if (tmp[0].equals("Page")) hm.put("pages", tmp[1]);
else if (tmp[0].equals("Publication Year")) hm.put("year", tmp[1]);
else if (tmp[0].equals("Abstract")) hm.put("abstract", tmp[1]);
else if (tmp[0].equals("Supplementary Terms")) hm.put("keywords",
tmp[1]);
else if (tmp[0].equals("Inventor Name")) hm.put("author", AuthorList.fixAuthor_lastNameFirst(tmp[1].replaceAll(";", " and ")));
else if (tmp[0].equals("Patent Assignee")) hm.put("institution", tmp[1]);
else if (tmp[0].equals("Patent Kind Code")) kindcode = " " + tmp[1];
else if (tmp[0].equals("Patent Country")) country = tmp[1] + " ";
else if (tmp[0].equals("Patent Number")) number = tmp[1];
else if (tmp[0].equals("Priority Application Date")) hm.put("number", country + number + kindcode);
else if (tmp[0].equals("Document Type")) {
if (tmp[1].startsWith("Journal") || tmp[1].startsWith("Review"))
Type = "article";
else if (tmp[1].equals("Dissertation"))
Type = "phdthesis";
else if (tmp[1].equals("Patent"))
Type = "patent";
else
Type = tmp[1];
}
}
}
BibtexEntry b = new BibtexEntry(BibtexFields.DEFAULT_BIBTEXENTRY_ID, Globals
.getEntryType(Type)); // id assumes an existing database so don't
// create one here
b.setField(hm);
bibitems.add(b);
}
return bibitems;
}
| public List<BibtexEntry> importEntries(InputStream stream) throws IOException {
ArrayList<BibtexEntry> bibitems = new ArrayList<BibtexEntry>();
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(ImportFormatReader.getReaderDefaultEncoding(stream));
String str;
String number = "";
String country = "";
String kindcode = "";
while ((str = in.readLine()) != null){
sb.append(str);
}
String[] entries = sb.toString().split("START_RECORD");
HashMap<String, String> hm = new HashMap<String, String>();
for (int i = 1; i < entries.length; i++){
String[] fields = entries[i].split("FIELD ");
String journal = null;
String Type = "";
hm.clear(); // reset
for (int j = 0; j < fields.length; j++)
if (fields[j].indexOf(":") >= 0){
String tmp[] = new String[2];
tmp[0] = fields[j].substring(0, fields[j].indexOf(":"));
tmp[1] = fields[j].substring(fields[j].indexOf(":") + 1).trim();
if (tmp.length > 1){//==2
if (tmp[0].equals("Author")) hm.put("author", AuthorList.fixAuthor_lastNameFirst(tmp[1].replaceAll(";", " and ")));
else if (tmp[0].equals("Title")) hm.put("title", tmp[1]);
else if (tmp[0].equals("Journal Title")) {
journal = tmp[1];
}
else if (tmp[0].equals("Volume")) hm.put("volume", tmp[1]);
else if (tmp[0].equals("Page")) hm.put("pages", tmp[1]);
else if (tmp[0].equals("Publication Year")) hm.put("year", tmp[1]);
else if (tmp[0].equals("Abstract")) hm.put("abstract", tmp[1]);
else if (tmp[0].equals("Supplementary Terms")) hm.put("keywords",
tmp[1]);
else if (tmp[0].equals("Inventor Name") && (tmp[1].trim().length() > 0)) hm.put("author", AuthorList.fixAuthor_lastNameFirst(tmp[1].replaceAll(";", " and ")));
else if (tmp[0].equals("Patent Assignee")) hm.put("institution", tmp[1]);
else if (tmp[0].equals("Patent Kind Code")) kindcode = " " + tmp[1];
else if (tmp[0].equals("Patent Country")) country = tmp[1] + " ";
else if (tmp[0].equals("Patent Number")) number = tmp[1];
else if (tmp[0].equals("Priority Application Date")) hm.put("number", country + number + kindcode);
else if (tmp[0].equals("Document Type")) {
if (tmp[1].startsWith("Journal") || tmp[1].startsWith("Review"))
Type = "article";
else if (tmp[1].equals("Dissertation"))
Type = "phdthesis";
else if (tmp[1].equals("Patent"))
Type = "patent";
else if (tmp[1].startsWith("Conference"))
Type = "conference";
else
Type = tmp[1];
}
}
}
BibtexEntry b = new BibtexEntry(BibtexFields.DEFAULT_BIBTEXENTRY_ID, Globals
.getEntryType(Type)); // id assumes an existing database so don't
// create one here
b.setField(hm);
if (journal != null) {
if (Type.equals("conference"))
b.setField("booktitle", journal);
else
b.setField("journal", journal);
}
bibitems.add(b);
}
return bibitems;
}
|
diff --git a/src/main/java/dk/statsbiblioteket/newspaper/metadatachecker/ModsXPathEventHandler.java b/src/main/java/dk/statsbiblioteket/newspaper/metadatachecker/ModsXPathEventHandler.java
index 862f4b2..b9957be 100644
--- a/src/main/java/dk/statsbiblioteket/newspaper/metadatachecker/ModsXPathEventHandler.java
+++ b/src/main/java/dk/statsbiblioteket/newspaper/metadatachecker/ModsXPathEventHandler.java
@@ -1,307 +1,307 @@
package dk.statsbiblioteket.newspaper.metadatachecker;
import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.AttributeParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.NodeBeginsParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.DefaultTreeEventHandler;
import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO;
import dk.statsbiblioteket.newspaper.mfpakintegration.database.NewspaperBatchOptions;
import dk.statsbiblioteket.util.xml.DOM;
import dk.statsbiblioteket.util.xml.XPathSelector;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static dk.statsbiblioteket.util.Strings.getStackTrace;
/**
* This class uses xpath to validate metadata requirements for mods files that do no otherwise fit into the schematron
* paradigm. This includes checking for consistency of the existence of brik files with the displayName attribute
* in the mods file.
*/
public class ModsXPathEventHandler extends DefaultTreeEventHandler {
public static final String EDITION_REGEX = "^[0-9]{4}.*-[0-9]{2}$";
private ResultCollector resultCollector;
private MfPakDAO mfPakDAO;
private Batch batch;
private List<String> briksInThisEdition;
private Document batchXmlStructure;
private static final XPathSelector BATCH_XPATH_SELECTOR = DOM.createXPathSelector();
private static final XPathSelector MODS_XPATH_SELECTOR = DOM.createXPathSelector("mods", "http://www.loc.gov/mods/v3");
/**
* Constructor for this class.
* @param resultCollector the result collector to collect errors in
* @param mfPakDAO a DAO object from which one can read relevant external properties of a batch.
* @param batch a batch object representing the batch being analysed.
* @param batchXmlStructure the complete structure of this batch as XML.
*/
public ModsXPathEventHandler(ResultCollector resultCollector, MfPakDAO mfPakDAO, Batch batch, Document batchXmlStructure) {
this.resultCollector = resultCollector;
this.mfPakDAO = mfPakDAO;
this.batch = batch;
this.batchXmlStructure = batchXmlStructure;
briksInThisEdition = new ArrayList<>();
}
/**
* Whenever we reach the start of an edition node, this method reinitializes briksInThisEdition
* with a list of brik-files in this edition node.
* @param event the node-begins event.
*/
@Override
public void handleNodeBegin(NodeBeginsParsingEvent event) {
String shortName = getLastTokenInPath(event.getName());
if (shortName.matches(EDITION_REGEX)) {
briksInThisEdition = new ArrayList<String>();
String xpathForBriks = "//node[@name='" + event.getName() + "']/node[ends-with(@shortName, 'brik')]/@shortName";
NodeList nodeList = BATCH_XPATH_SELECTOR.selectNodeList(batchXmlStructure, xpathForBriks);
for (int nodeNumber = 0; nodeNumber < nodeList.getLength(); nodeNumber++ ) {
Node node = nodeList.item(nodeNumber);
briksInThisEdition.add(node.getNodeValue().replace("-brik", ""));
}
}
}
@Override
public void handleAttribute(AttributeParsingEvent event) {
if (event.getName().endsWith("mods.xml")) {
try {
doValidate(event);
} catch (Exception e) { //Fault Barrier
resultCollector.addFailure(
event.getName(),
"exception",
getClass().getSimpleName(),
"Error processing page-MODS metadata: " + e.toString(),
getStackTrace(e)
);
}
}
}
private void doValidate(AttributeParsingEvent event) {
Document modsDocument;
try {
modsDocument = DOM.streamToDOM(event.getData());
if (modsDocument == null) {
resultCollector.addFailure(
event.getName(),
"exception",
getClass().getSimpleName(),
"Could not parse xml");
return;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
validate2C1(event, modsDocument);
validate2C4(event, modsDocument);
validate2C5(event, modsDocument);
validate2C11(event, modsDocument);
validate2C10(event, modsDocument);
}
/**
* Checks that section titles are absent if option B7 is not chosen, and vice versa.
* @param event the event corresponding to the mods file being checked.
* @param modsDocument the xml representation of the file.
*/
private void validate2C1(AttributeParsingEvent event, Document modsDocument) {
NewspaperBatchOptions batchOptions = null;
try {
batchOptions = mfPakDAO.getBatchOptions(batch.getBatchID());
} catch (SQLException e) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Couldn't read batch options from mfpak.",
getStackTrace(e)
);
}
if (batchOptions == null) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Couldn't read batch options from mfpak. Got null value.",
batch.getBatchID()
);
return;
} else if (!batchOptions.isOptionB7()) {
String sectionLabelXpath = "mods:mods/mods:part/mods:detail[@type='sectionLabel']";
NodeList nodes = MODS_XPATH_SELECTOR.selectNodeList(modsDocument, sectionLabelXpath);
if (nodes == null || nodes.getLength() == 0) {
return;
} else {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Found section entitled " + nodes.item(0).getTextContent() + " for the page "
+ event.getName() + " although Option B7 (Section Titles) was not chosen for the batch " + batch.getBatchID(),
sectionLabelXpath );
}
} else {
String sectionLabelXpath = "mods:mods/mods:part/mods:detail[@type='sectionLabel']";
NodeList nodes = MODS_XPATH_SELECTOR.selectNodeList(modsDocument, sectionLabelXpath);
if (nodes == null || nodes.getLength() == 0) {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
- "2C-1: Dit not find section entitled " + nodes.item(0).getTextContent() + " for the page "
- + event.getName() + " although Option B7 (Section Titles) was chosen for the batch " + batch.getBatchID(),
+ "2C-1: Dit not find section for the page " + event.getName()
+ + " although Option B7 (Section Titles) was chosen for the batch " + batch.getBatchID(),
sectionLabelXpath );
} else {
return;
}
}
}
/**
* Valid against the requirement that the displayLabel attribute implies the existence of a corresponding briks
* file and it's absence implies absence of brik file.
* @param event
* @param modsDocument
*/
private void validate2C10(AttributeParsingEvent event, Document modsDocument) {
String display = "mods:mods/mods:relatedItem/mods:note[@type='noteAboutReproduction' and @displayLabel]";
String name = getLastTokenInPath(event.getName());
name = getBrikName(name);
boolean brikExists = briksInThisEdition.contains(name);
NodeList nodes = MODS_XPATH_SELECTOR.selectNodeList(modsDocument, display);
boolean brikShouldExist = nodes != null && nodes.getLength() > 0 ;
if (brikExists && !brikShouldExist) {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-10: Found symbol " + name + " but there is no displayName attribute in the" +
" corresponding page " + event.getName(),
display
);
}
if (!brikExists && brikShouldExist) {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-10: Did not find symbol " + name + " although it is implied by existence of " +
"displayname in corresponding page " + event.getName(),
display
);
}
}
/**
* Transform the name of this mods file to the expected name of the brik object.
* This means
* i) remove the .mods.xml ending
* ii) remove the multi-page suffix so
* adresseavisen1759-1795-06-15-02-0005B.mods.xml -> adresseavisen1759-1795-06-15-02-0005
* adresseavisen1759-1795-06-15-02-0004.mods.xml -> adresseavisen1759-1795-06-15-02-0004
* @param modsFileName the name of this mods file.
* @return the name of the matching brik (symbol) file.
*/
private String getBrikName(String modsFileName) {
modsFileName = modsFileName.replace(".mods.xml", "");
char lastChar = modsFileName.charAt(modsFileName.length() -1);
if (String.valueOf(lastChar).matches("[A-Z]")) {
modsFileName = modsFileName.substring(0, modsFileName.length() -1);
}
return modsFileName;
}
/**
* Validate consistency of newspaper title against teh database.
* @param event
* @param modsDocument
*/
private void validate2C11(AttributeParsingEvent event, Document modsDocument) {
//2C-11
final String xpath2C11 = "mods:mods/mods:relatedItem/mods:titleInfo[@type='uniform' and @authority='Statens Avissamling']/mods:title";
String avisId = null;
try {
avisId = mfPakDAO.getNewspaperID(batch.getBatchID());
String modsAvisId = MODS_XPATH_SELECTOR.selectString(modsDocument, xpath2C11);
if (modsAvisId == null || avisId == null || !modsAvisId.equals(avisId)) {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-11: avisId mismatch. Document gives " + modsAvisId + " but mfpak gives " + avisId,
xpath2C11
);
}
} catch (SQLException e) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-11: Couldn't read avisId from mfpak.",
getStackTrace(e)
);
}
}
/**
* Validate consistency of sequence number in mods file against the name of the file.
* @param event
* @param modsDocument
*/
private void validate2C5(AttributeParsingEvent event, Document modsDocument) {
//2C-5
final String xpath2C5 = "mods:mods/mods:relatedItem[@type='original']/mods:identifier[@type='reel sequence number']";
String sequenceNumber = MODS_XPATH_SELECTOR.selectString(modsDocument, xpath2C5);
String namePattern = ".*-[0]*" + sequenceNumber + ".mods.xml";
if (sequenceNumber == null || !(event.getName().matches(namePattern))) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-5: " + sequenceNumber + " not found in file name. Should match " + namePattern + ".",
xpath2C5
);
}
}
/**
* Validate that the reel number matches the expected pattern for reels in this batch.
* @param event
* @param modsDocument
*/
private void validate2C4(AttributeParsingEvent event, Document modsDocument) {
//2C-4
final String xpath2C4 = "mods:mods/mods:relatedItem[@type='original']/mods:identifier[@type='reel number']";
String reelNumber = MODS_XPATH_SELECTOR.selectString(modsDocument, xpath2C4);
String reelNumberPatternString = "^" + batch.getBatchID() + "-" + "[0-9]+$";
if (reelNumber == null || !reelNumber.matches(reelNumberPatternString)) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-4: reel number " + reelNumber + " does not match expected pattern '" + reelNumberPatternString + "'",
xpath2C4
);
}
}
/**
* We use a constant "/" as file separator in DOMS, not the system-dependent file-separator, so this
* method finds the last token in a path assuming that "/" is the file separator.
* @param name
* @return
*/
private static String getLastTokenInPath(String name) {
String [] nameSplit = name.split("/");
return nameSplit[nameSplit.length -1];
}
}
| true | true | private void validate2C1(AttributeParsingEvent event, Document modsDocument) {
NewspaperBatchOptions batchOptions = null;
try {
batchOptions = mfPakDAO.getBatchOptions(batch.getBatchID());
} catch (SQLException e) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Couldn't read batch options from mfpak.",
getStackTrace(e)
);
}
if (batchOptions == null) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Couldn't read batch options from mfpak. Got null value.",
batch.getBatchID()
);
return;
} else if (!batchOptions.isOptionB7()) {
String sectionLabelXpath = "mods:mods/mods:part/mods:detail[@type='sectionLabel']";
NodeList nodes = MODS_XPATH_SELECTOR.selectNodeList(modsDocument, sectionLabelXpath);
if (nodes == null || nodes.getLength() == 0) {
return;
} else {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Found section entitled " + nodes.item(0).getTextContent() + " for the page "
+ event.getName() + " although Option B7 (Section Titles) was not chosen for the batch " + batch.getBatchID(),
sectionLabelXpath );
}
} else {
String sectionLabelXpath = "mods:mods/mods:part/mods:detail[@type='sectionLabel']";
NodeList nodes = MODS_XPATH_SELECTOR.selectNodeList(modsDocument, sectionLabelXpath);
if (nodes == null || nodes.getLength() == 0) {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Dit not find section entitled " + nodes.item(0).getTextContent() + " for the page "
+ event.getName() + " although Option B7 (Section Titles) was chosen for the batch " + batch.getBatchID(),
sectionLabelXpath );
} else {
return;
}
}
}
| private void validate2C1(AttributeParsingEvent event, Document modsDocument) {
NewspaperBatchOptions batchOptions = null;
try {
batchOptions = mfPakDAO.getBatchOptions(batch.getBatchID());
} catch (SQLException e) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Couldn't read batch options from mfpak.",
getStackTrace(e)
);
}
if (batchOptions == null) {
resultCollector.addFailure(event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Couldn't read batch options from mfpak. Got null value.",
batch.getBatchID()
);
return;
} else if (!batchOptions.isOptionB7()) {
String sectionLabelXpath = "mods:mods/mods:part/mods:detail[@type='sectionLabel']";
NodeList nodes = MODS_XPATH_SELECTOR.selectNodeList(modsDocument, sectionLabelXpath);
if (nodes == null || nodes.getLength() == 0) {
return;
} else {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Found section entitled " + nodes.item(0).getTextContent() + " for the page "
+ event.getName() + " although Option B7 (Section Titles) was not chosen for the batch " + batch.getBatchID(),
sectionLabelXpath );
}
} else {
String sectionLabelXpath = "mods:mods/mods:part/mods:detail[@type='sectionLabel']";
NodeList nodes = MODS_XPATH_SELECTOR.selectNodeList(modsDocument, sectionLabelXpath);
if (nodes == null || nodes.getLength() == 0) {
resultCollector.addFailure(
event.getName(),
"metadata",
getClass().getSimpleName(),
"2C-1: Dit not find section for the page " + event.getName()
+ " although Option B7 (Section Titles) was chosen for the batch " + batch.getBatchID(),
sectionLabelXpath );
} else {
return;
}
}
}
|
diff --git a/src/com/dmdirc/ParserFactory.java b/src/com/dmdirc/ParserFactory.java
index 77bee4f69..7dec1d054 100644
--- a/src/com/dmdirc/ParserFactory.java
+++ b/src/com/dmdirc/ParserFactory.java
@@ -1,70 +1,68 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.parser.interfaces.Parser;
import com.dmdirc.parser.irc.IRCParser;
import com.dmdirc.parser.irc.MyInfo;
import com.dmdirc.parser.irc.ServerInfo;
import com.dmdirc.util.IrcAddress;
/**
* Provides a method to retrieve a parser.
*
* @since 0.6
* @author chris
*/
public class ParserFactory {
/**
* Retrieves a parser instance.
*
* @param myInfo The client information to use
* @param address The address of the server to connect to
* @return An appropriately configured parser
* @since 0.6.3m2
*/
public Parser getParser(final MyInfo myInfo, final IrcAddress address) {
// TODO: Hacky Hack McHack
final ServerInfo info = new ServerInfo(address.getServer(), address.getPort(6667),
address.getPassword());
info.setSSL(address.isSSL());
- if ("irc".equals(address.getProtocol())) {
- return new IRCParser(myInfo, info);
- } else if ("irc-test".equals(address.getProtocol())) {
+ if ("irc-test".equals(address.getProtocol())) {
try {
return (Parser) Class.forName("com.dmdirc.harness.parser.TestParser")
.getConstructor(MyInfo.class, ServerInfo.class)
.newInstance(myInfo, info);
} catch (Exception ex) {
Logger.userError(ErrorLevel.UNKNOWN, "Unable to create parser", ex);
}
}
- return null;
+ return new IRCParser(myInfo, info);
}
}
| false | true | public Parser getParser(final MyInfo myInfo, final IrcAddress address) {
// TODO: Hacky Hack McHack
final ServerInfo info = new ServerInfo(address.getServer(), address.getPort(6667),
address.getPassword());
info.setSSL(address.isSSL());
if ("irc".equals(address.getProtocol())) {
return new IRCParser(myInfo, info);
} else if ("irc-test".equals(address.getProtocol())) {
try {
return (Parser) Class.forName("com.dmdirc.harness.parser.TestParser")
.getConstructor(MyInfo.class, ServerInfo.class)
.newInstance(myInfo, info);
} catch (Exception ex) {
Logger.userError(ErrorLevel.UNKNOWN, "Unable to create parser", ex);
}
}
return null;
}
| public Parser getParser(final MyInfo myInfo, final IrcAddress address) {
// TODO: Hacky Hack McHack
final ServerInfo info = new ServerInfo(address.getServer(), address.getPort(6667),
address.getPassword());
info.setSSL(address.isSSL());
if ("irc-test".equals(address.getProtocol())) {
try {
return (Parser) Class.forName("com.dmdirc.harness.parser.TestParser")
.getConstructor(MyInfo.class, ServerInfo.class)
.newInstance(myInfo, info);
} catch (Exception ex) {
Logger.userError(ErrorLevel.UNKNOWN, "Unable to create parser", ex);
}
}
return new IRCParser(myInfo, info);
}
|
diff --git a/src/main/org/jboss/messaging/core/remoting/impl/netty/NettyConnection.java b/src/main/org/jboss/messaging/core/remoting/impl/netty/NettyConnection.java
index 23357dc84..6091e01cb 100644
--- a/src/main/org/jboss/messaging/core/remoting/impl/netty/NettyConnection.java
+++ b/src/main/org/jboss/messaging/core/remoting/impl/netty/NettyConnection.java
@@ -1,120 +1,125 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.messaging.core.remoting.impl.netty;
import org.jboss.messaging.core.remoting.MessagingBuffer;
import org.jboss.messaging.core.remoting.spi.Connection;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.handler.ssl.SslHandler;
/**
* @author <a href="mailto:[email protected]">Jeff Mesnil</a>
* @author <a href="mailto:[email protected]">Andy Taylor</a>
* @author <a href="mailto:[email protected]">Tim Fox</a>
* buhnaflagilibrn
* @version <tt>$Revision$</tt>
*/
public class NettyConnection implements Connection
{
// Constants -----------------------------------------------------
// Attributes ----------------------------------------------------
private final Channel channel;
private boolean closed;
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
public NettyConnection(final Channel channel)
{
this.channel = channel;
}
// Public --------------------------------------------------------
// Connection implementation ----------------------------
public synchronized void close()
{
if (closed)
{
return;
}
SslHandler sslHandler = (SslHandler) channel.getPipeline().get("ssl");
if (sslHandler != null)
{
try
{
sslHandler.close(channel).addListener(ChannelFutureListener.CLOSE);
}
catch (Throwable t)
{
// ignore
}
} else {
channel.close();
}
- if (channel.getParent() == null) {
- // A client channel - wait until everything is cleaned up.
- // TODO Do not spin - use signal.
- MessagingChannelHandler handler = (MessagingChannelHandler) channel.getPipeline().get("handler");
- while (handler.active) {
- Thread.yield();
- }
- }
+// This block has been disabled because this method can be called from
+// the Netty I/O thread.
+// TODO Netty should be improved to provide a way to determine
+// if the current code is running in the I/O thread.
+//
+// if (channel.getParent() == null) {
+// // A client channel - wait until everything is cleaned up.
+// // TODO Do not spin - use signal.
+// MessagingChannelHandler handler = (MessagingChannelHandler) channel.getPipeline().get("handler");
+// while (handler.active) {
+// Thread.yield();
+// }
+// }
closed = true;
}
public MessagingBuffer createBuffer(int size)
{
return new ChannelBufferWrapper(size);
}
public Object getID()
{
return channel.getId();
}
public void write(final MessagingBuffer buffer)
{
channel.write(buffer.getUnderlyingBuffer());
}
// Public --------------------------------------------------------
// Package protected ---------------------------------------------
// Protected -----------------------------------------------------
// Private -------------------------------------------------------
// Inner classes -------------------------------------------------
}
| true | true | public synchronized void close()
{
if (closed)
{
return;
}
SslHandler sslHandler = (SslHandler) channel.getPipeline().get("ssl");
if (sslHandler != null)
{
try
{
sslHandler.close(channel).addListener(ChannelFutureListener.CLOSE);
}
catch (Throwable t)
{
// ignore
}
} else {
channel.close();
}
if (channel.getParent() == null) {
// A client channel - wait until everything is cleaned up.
// TODO Do not spin - use signal.
MessagingChannelHandler handler = (MessagingChannelHandler) channel.getPipeline().get("handler");
while (handler.active) {
Thread.yield();
}
}
closed = true;
}
| public synchronized void close()
{
if (closed)
{
return;
}
SslHandler sslHandler = (SslHandler) channel.getPipeline().get("ssl");
if (sslHandler != null)
{
try
{
sslHandler.close(channel).addListener(ChannelFutureListener.CLOSE);
}
catch (Throwable t)
{
// ignore
}
} else {
channel.close();
}
// This block has been disabled because this method can be called from
// the Netty I/O thread.
// TODO Netty should be improved to provide a way to determine
// if the current code is running in the I/O thread.
//
// if (channel.getParent() == null) {
// // A client channel - wait until everything is cleaned up.
// // TODO Do not spin - use signal.
// MessagingChannelHandler handler = (MessagingChannelHandler) channel.getPipeline().get("handler");
// while (handler.active) {
// Thread.yield();
// }
// }
closed = true;
}
|
diff --git a/src/org/apache/fop/fo/flow/TableBody.java b/src/org/apache/fop/fo/flow/TableBody.java
index e601bce59..2c40b66a4 100644
--- a/src/org/apache/fop/fo/flow/TableBody.java
+++ b/src/org/apache/fop/fo/flow/TableBody.java
@@ -1,262 +1,263 @@
/*-- $Id$ --
*
* Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
* For details on use and redistribution please refer to the
* LICENSE file included with these sources."
*/
package org.apache.fop.fo.flow;
// FOP
import org.apache.fop.fo.*;
import org.apache.fop.fo.properties.*;
import org.apache.fop.datatypes.*;
import org.apache.fop.layout.*;
import org.apache.fop.apps.FOPException;
// Java
import java.util.Vector;
import java.util.Enumeration;
public class TableBody extends FObj {
public static class Maker extends FObj.Maker {
public FObj make(FObj parent,
PropertyList propertyList) throws FOPException {
return new TableBody(parent, propertyList);
}
}
public static FObj.Maker maker() {
return new TableBody.Maker();
}
int spaceBefore;
int spaceAfter;
ColorType backgroundColor;
String id;
Vector columns;
AreaContainer areaContainer;
public TableBody(FObj parent, PropertyList propertyList) {
super(parent, propertyList);
this.name = "fo:table-body";
}
public void setColumns(Vector columns) {
this.columns = columns;
}
public void setYPosition(int value) {
areaContainer.setYPosition(value);
}
public int getYPosition() {
return areaContainer.getCurrentYPosition();
}
public int getHeight() {
return areaContainer.getHeight() + spaceBefore + spaceAfter;
}
public Status layout(Area area) throws FOPException {
if (this.marker == BREAK_AFTER) {
return new Status(Status.OK);
}
if (this.marker == START) {
this.spaceBefore = this.properties.get(
"space-before.optimum").getLength().mvalue();
this.spaceAfter = this.properties.get(
"space-after.optimum").getLength().mvalue();
this.backgroundColor = this.properties.get(
"background-color").getColorType();
this.id = this.properties.get("id").getString();
area.getIDReferences().createID(id);
if (area instanceof BlockArea) {
area.end();
}
//if (this.isInListBody) {
//startIndent += bodyIndent + distanceBetweenStarts;
//}
this.marker = 0;
}
if ((spaceBefore != 0) && (this.marker == 0)) {
area.increaseHeight(spaceBefore);
}
if (marker == 0) {
// configure id
area.getIDReferences().configureID(id, area);
}
int spaceLeft = area.spaceLeft();
/* Note: the parent FO must be a Table. The parent Area is the Block
* type area created by the Table, which is also a reference area.
* The content "width" (IPD) of the TableBody is the same as that
* of the containing table area, and its relative position is 0,0.
* Strictly speaking (CR), this FO should generate no areas!
*/
this.areaContainer = new AreaContainer(
propMgr.getFontState(area.getFontInfo()), 0,
area.getContentHeight(), area.getContentWidth(), // IPD
area.spaceLeft() , Position.RELATIVE);
areaContainer.foCreator = this; // G Seshadri
areaContainer.setPage(area.getPage());
areaContainer.setBackgroundColor(backgroundColor);
areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
areaContainer.start();
areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
areaContainer.setIDReferences(area.getIDReferences());
Vector keepWith = new Vector();
int numChildren = this.children.size();
TableRow lastRow = null;
boolean endKeepGroup = true;
for (int i = this.marker; i < numChildren; i++) {
Object child = children.elementAt(i);
if (!(child instanceof TableRow)) {
throw new FOPException("Currently only Table Rows are supported in table body, header and footer");
}
TableRow row = (TableRow) child;
row.setColumns(columns);
row.doSetup(areaContainer);
if (row.getKeepWithPrevious().getType() !=
KeepValue.KEEP_WITH_AUTO && lastRow != null &&
keepWith.indexOf(lastRow) == -1) {
keepWith.addElement(lastRow);
} else {
if (endKeepGroup && keepWith.size() > 0) {
keepWith = new Vector();
}
}
Status status;
if ((status = row.layout(areaContainer)).isIncomplete()) {
if (status.isPageBreak()) {
this.marker = i;
area.addChild(areaContainer);
//areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(
areaContainer.getAbsoluteHeight());
if (i == numChildren - 1) {
this.marker = BREAK_AFTER;
if (spaceAfter != 0) {
area.increaseHeight(spaceAfter);
}
}
return status;
}
if (keepWith.size() > 0) { // && status.getCode() == Status.AREA_FULL_NONE
row.removeLayout(areaContainer);
for (Enumeration e = keepWith.elements();
e.hasMoreElements();) {
TableRow tr = (TableRow) e.nextElement();
tr.removeLayout(areaContainer);
i--;
}
if (i == 0) {
resetMarker();
return new Status(Status.AREA_FULL_NONE);
}
}
this.marker = i;
if ((i != 0) &&
(status.getCode() == Status.AREA_FULL_NONE)) {
status = new Status(Status.AREA_FULL_SOME);
}
// if (i < widows && numChildren >= widows) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// if (numChildren <= orphans) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// if (numChildren - i < orphans && numChildren >= orphans) {
// for (int count = i;
// count > numChildren - orphans - 1; count--) {
// row = (TableRow) children.elementAt(count);
// row.removeLayout(areaContainer);
// i--;
// }
// if (i < widows && numChildren >= widows) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// this.marker = i;
// area.addChild(areaContainer);
// //areaContainer.end();
// area.increaseHeight(areaContainer.getHeight());
// area.setAbsoluteHeight(
// areaContainer.getAbsoluteHeight());
// return new Status(Status.AREA_FULL_SOME);
// }
if (!((i == 0) &&
(areaContainer.getContentHeight() <= 0))) {
area.addChild(areaContainer);
//areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(
areaContainer.getAbsoluteHeight());
}
return status;
} else if (status.getCode() == Status.KEEP_WITH_NEXT) {
keepWith.addElement(row);
endKeepGroup = false;
} else {
endKeepGroup = true;
}
lastRow = row;
area.setMaxHeight(area.getMaxHeight() - spaceLeft +
this.areaContainer.getMaxHeight());
spaceLeft = area.spaceLeft();
}
area.addChild(areaContainer);
areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (spaceAfter != 0) {
area.increaseHeight(spaceAfter);
+ area.setMaxHeight(area.getMaxHeight() - spaceAfter);
}
if (area instanceof BlockArea) {
area.start();
}
return new Status(Status.OK);
}
public void removeLayout(Area area) {
if (areaContainer != null) {
area.removeChild(areaContainer);
}
if (spaceBefore != 0) {
area.increaseHeight(-spaceBefore);
}
if (spaceAfter != 0) {
area.increaseHeight(-spaceAfter);
}
this.resetMarker();
this.removeID(area.getIDReferences());
}
}
| true | true | public Status layout(Area area) throws FOPException {
if (this.marker == BREAK_AFTER) {
return new Status(Status.OK);
}
if (this.marker == START) {
this.spaceBefore = this.properties.get(
"space-before.optimum").getLength().mvalue();
this.spaceAfter = this.properties.get(
"space-after.optimum").getLength().mvalue();
this.backgroundColor = this.properties.get(
"background-color").getColorType();
this.id = this.properties.get("id").getString();
area.getIDReferences().createID(id);
if (area instanceof BlockArea) {
area.end();
}
//if (this.isInListBody) {
//startIndent += bodyIndent + distanceBetweenStarts;
//}
this.marker = 0;
}
if ((spaceBefore != 0) && (this.marker == 0)) {
area.increaseHeight(spaceBefore);
}
if (marker == 0) {
// configure id
area.getIDReferences().configureID(id, area);
}
int spaceLeft = area.spaceLeft();
/* Note: the parent FO must be a Table. The parent Area is the Block
* type area created by the Table, which is also a reference area.
* The content "width" (IPD) of the TableBody is the same as that
* of the containing table area, and its relative position is 0,0.
* Strictly speaking (CR), this FO should generate no areas!
*/
this.areaContainer = new AreaContainer(
propMgr.getFontState(area.getFontInfo()), 0,
area.getContentHeight(), area.getContentWidth(), // IPD
area.spaceLeft() , Position.RELATIVE);
areaContainer.foCreator = this; // G Seshadri
areaContainer.setPage(area.getPage());
areaContainer.setBackgroundColor(backgroundColor);
areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
areaContainer.start();
areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
areaContainer.setIDReferences(area.getIDReferences());
Vector keepWith = new Vector();
int numChildren = this.children.size();
TableRow lastRow = null;
boolean endKeepGroup = true;
for (int i = this.marker; i < numChildren; i++) {
Object child = children.elementAt(i);
if (!(child instanceof TableRow)) {
throw new FOPException("Currently only Table Rows are supported in table body, header and footer");
}
TableRow row = (TableRow) child;
row.setColumns(columns);
row.doSetup(areaContainer);
if (row.getKeepWithPrevious().getType() !=
KeepValue.KEEP_WITH_AUTO && lastRow != null &&
keepWith.indexOf(lastRow) == -1) {
keepWith.addElement(lastRow);
} else {
if (endKeepGroup && keepWith.size() > 0) {
keepWith = new Vector();
}
}
Status status;
if ((status = row.layout(areaContainer)).isIncomplete()) {
if (status.isPageBreak()) {
this.marker = i;
area.addChild(areaContainer);
//areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(
areaContainer.getAbsoluteHeight());
if (i == numChildren - 1) {
this.marker = BREAK_AFTER;
if (spaceAfter != 0) {
area.increaseHeight(spaceAfter);
}
}
return status;
}
if (keepWith.size() > 0) { // && status.getCode() == Status.AREA_FULL_NONE
row.removeLayout(areaContainer);
for (Enumeration e = keepWith.elements();
e.hasMoreElements();) {
TableRow tr = (TableRow) e.nextElement();
tr.removeLayout(areaContainer);
i--;
}
if (i == 0) {
resetMarker();
return new Status(Status.AREA_FULL_NONE);
}
}
this.marker = i;
if ((i != 0) &&
(status.getCode() == Status.AREA_FULL_NONE)) {
status = new Status(Status.AREA_FULL_SOME);
}
// if (i < widows && numChildren >= widows) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// if (numChildren <= orphans) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// if (numChildren - i < orphans && numChildren >= orphans) {
// for (int count = i;
// count > numChildren - orphans - 1; count--) {
// row = (TableRow) children.elementAt(count);
// row.removeLayout(areaContainer);
// i--;
// }
// if (i < widows && numChildren >= widows) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// this.marker = i;
// area.addChild(areaContainer);
// //areaContainer.end();
// area.increaseHeight(areaContainer.getHeight());
// area.setAbsoluteHeight(
// areaContainer.getAbsoluteHeight());
// return new Status(Status.AREA_FULL_SOME);
// }
if (!((i == 0) &&
(areaContainer.getContentHeight() <= 0))) {
area.addChild(areaContainer);
//areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(
areaContainer.getAbsoluteHeight());
}
return status;
} else if (status.getCode() == Status.KEEP_WITH_NEXT) {
keepWith.addElement(row);
endKeepGroup = false;
} else {
endKeepGroup = true;
}
lastRow = row;
area.setMaxHeight(area.getMaxHeight() - spaceLeft +
this.areaContainer.getMaxHeight());
spaceLeft = area.spaceLeft();
}
area.addChild(areaContainer);
areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (spaceAfter != 0) {
area.increaseHeight(spaceAfter);
}
if (area instanceof BlockArea) {
area.start();
}
return new Status(Status.OK);
}
| public Status layout(Area area) throws FOPException {
if (this.marker == BREAK_AFTER) {
return new Status(Status.OK);
}
if (this.marker == START) {
this.spaceBefore = this.properties.get(
"space-before.optimum").getLength().mvalue();
this.spaceAfter = this.properties.get(
"space-after.optimum").getLength().mvalue();
this.backgroundColor = this.properties.get(
"background-color").getColorType();
this.id = this.properties.get("id").getString();
area.getIDReferences().createID(id);
if (area instanceof BlockArea) {
area.end();
}
//if (this.isInListBody) {
//startIndent += bodyIndent + distanceBetweenStarts;
//}
this.marker = 0;
}
if ((spaceBefore != 0) && (this.marker == 0)) {
area.increaseHeight(spaceBefore);
}
if (marker == 0) {
// configure id
area.getIDReferences().configureID(id, area);
}
int spaceLeft = area.spaceLeft();
/* Note: the parent FO must be a Table. The parent Area is the Block
* type area created by the Table, which is also a reference area.
* The content "width" (IPD) of the TableBody is the same as that
* of the containing table area, and its relative position is 0,0.
* Strictly speaking (CR), this FO should generate no areas!
*/
this.areaContainer = new AreaContainer(
propMgr.getFontState(area.getFontInfo()), 0,
area.getContentHeight(), area.getContentWidth(), // IPD
area.spaceLeft() , Position.RELATIVE);
areaContainer.foCreator = this; // G Seshadri
areaContainer.setPage(area.getPage());
areaContainer.setBackgroundColor(backgroundColor);
areaContainer.setBorderAndPadding(propMgr.getBorderAndPadding());
areaContainer.start();
areaContainer.setAbsoluteHeight(area.getAbsoluteHeight());
areaContainer.setIDReferences(area.getIDReferences());
Vector keepWith = new Vector();
int numChildren = this.children.size();
TableRow lastRow = null;
boolean endKeepGroup = true;
for (int i = this.marker; i < numChildren; i++) {
Object child = children.elementAt(i);
if (!(child instanceof TableRow)) {
throw new FOPException("Currently only Table Rows are supported in table body, header and footer");
}
TableRow row = (TableRow) child;
row.setColumns(columns);
row.doSetup(areaContainer);
if (row.getKeepWithPrevious().getType() !=
KeepValue.KEEP_WITH_AUTO && lastRow != null &&
keepWith.indexOf(lastRow) == -1) {
keepWith.addElement(lastRow);
} else {
if (endKeepGroup && keepWith.size() > 0) {
keepWith = new Vector();
}
}
Status status;
if ((status = row.layout(areaContainer)).isIncomplete()) {
if (status.isPageBreak()) {
this.marker = i;
area.addChild(areaContainer);
//areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(
areaContainer.getAbsoluteHeight());
if (i == numChildren - 1) {
this.marker = BREAK_AFTER;
if (spaceAfter != 0) {
area.increaseHeight(spaceAfter);
}
}
return status;
}
if (keepWith.size() > 0) { // && status.getCode() == Status.AREA_FULL_NONE
row.removeLayout(areaContainer);
for (Enumeration e = keepWith.elements();
e.hasMoreElements();) {
TableRow tr = (TableRow) e.nextElement();
tr.removeLayout(areaContainer);
i--;
}
if (i == 0) {
resetMarker();
return new Status(Status.AREA_FULL_NONE);
}
}
this.marker = i;
if ((i != 0) &&
(status.getCode() == Status.AREA_FULL_NONE)) {
status = new Status(Status.AREA_FULL_SOME);
}
// if (i < widows && numChildren >= widows) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// if (numChildren <= orphans) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// if (numChildren - i < orphans && numChildren >= orphans) {
// for (int count = i;
// count > numChildren - orphans - 1; count--) {
// row = (TableRow) children.elementAt(count);
// row.removeLayout(areaContainer);
// i--;
// }
// if (i < widows && numChildren >= widows) {
// resetMarker();
// return new Status(Status.AREA_FULL_NONE);
// }
// this.marker = i;
// area.addChild(areaContainer);
// //areaContainer.end();
// area.increaseHeight(areaContainer.getHeight());
// area.setAbsoluteHeight(
// areaContainer.getAbsoluteHeight());
// return new Status(Status.AREA_FULL_SOME);
// }
if (!((i == 0) &&
(areaContainer.getContentHeight() <= 0))) {
area.addChild(areaContainer);
//areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(
areaContainer.getAbsoluteHeight());
}
return status;
} else if (status.getCode() == Status.KEEP_WITH_NEXT) {
keepWith.addElement(row);
endKeepGroup = false;
} else {
endKeepGroup = true;
}
lastRow = row;
area.setMaxHeight(area.getMaxHeight() - spaceLeft +
this.areaContainer.getMaxHeight());
spaceLeft = area.spaceLeft();
}
area.addChild(areaContainer);
areaContainer.end();
area.increaseHeight(areaContainer.getHeight());
area.setAbsoluteHeight(areaContainer.getAbsoluteHeight());
if (spaceAfter != 0) {
area.increaseHeight(spaceAfter);
area.setMaxHeight(area.getMaxHeight() - spaceAfter);
}
if (area instanceof BlockArea) {
area.start();
}
return new Status(Status.OK);
}
|
diff --git a/grails-app/services/org/chai/kevin/importer/ImporterService.java b/grails-app/services/org/chai/kevin/importer/ImporterService.java
index 77de2e97..5270a862 100644
--- a/grails-app/services/org/chai/kevin/importer/ImporterService.java
+++ b/grails-app/services/org/chai/kevin/importer/ImporterService.java
@@ -1,289 +1,290 @@
/**
* Copyright (c) 2011, Clinton Health Access Initiative.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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.chai.kevin.importer;
import java.io.IOException;
import java.io.Reader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.chai.kevin.LocationService;
import org.chai.kevin.data.DataService;
import org.chai.kevin.data.Enum;
import org.chai.kevin.data.EnumOption;
import org.chai.kevin.data.RawDataElement;
import org.chai.kevin.data.Type;
import org.chai.kevin.data.Type.Sanitizer;
import org.chai.kevin.location.DataLocationEntity;
import org.chai.kevin.util.Utils;
import org.chai.kevin.value.RawDataElementValue;
import org.chai.kevin.value.Value;
import org.chai.kevin.value.ValueService;
import org.hisp.dhis.period.Period;
import org.supercsv.io.CsvMapReader;
import org.supercsv.io.ICsvMapReader;
import org.supercsv.prefs.CsvPreference;
/**
* @author Jean Kahigiso M.
*
*/
public class ImporterService {
private static final Log log = LogFactory.getLog(ImporterService.class);
private LocationService locationService;
private ValueService valueService;
private DataService dataService;
private static final String CODE_HEADER = "code";
public void importFile(RawDataElement rawDataElement, Reader reader, Period period,ImporterErrorManager manager) throws IOException{
ICsvMapReader readFileAsMap = new CsvMapReader(reader, CsvPreference.EXCEL_PREFERENCE);
try{
final String[] headers = readFileAsMap.getCSVHeader(true);
String code=null;
Map<String,Integer> positions = new HashMap<String,Integer>();
Map<String,String> values = readFileAsMap.read(headers);
Map<String,Type> types = new HashMap<String,Type>();
for (String header : headers) {
try {
if(!header.equals(CODE_HEADER))
types.put("[_]."+header,rawDataElement.getType().getType("[_]."+header));
} catch(IllegalArgumentException e){
if(log.isWarnEnabled()) log.warn("Column type not found for header"+header, e);
manager.getErrors().add(new ImporterError(readFileAsMap.getLineNumber(),header,"error.message.unknowm.column.type"));
}
}
Value value = null;
DataLocationEntity dataEntity=null;
RawDataElementValue rawDataElementValue= null;
manager.setNumberOfSavedRows(0);
manager.setNumberOfUnsavedRows(0);
manager.setNumberOfRowsSavedWithError(0);
ImportSanitizer sanitizer = new ImportSanitizer(manager.getErrors(), types);
while (values != null) {
Map <String,Object> map = new HashMap<String,Object>();
Set<String> attributes = new HashSet<String>();
sanitizer.setLineNumber(readFileAsMap.getLineNumber());
sanitizer.setNumberOfErrorInRows(0);
if(!values.get(CODE_HEADER).equals(code)){
// The location changes, we need to update the code, location, position, rawDataElementValue
// 1 update the code
code = values.get(CODE_HEADER);
// 2 update the position
if (positions.get(code) == null) positions.put(code, 0);
// 3 update the location
dataEntity = locationService.findCalculationEntityByCode(code, DataLocationEntity.class);
if(dataEntity==null){
manager.getErrors().add(new ImporterError(readFileAsMap.getLineNumber(),CODE_HEADER,"error.message.unknown.location"));
}else{
// 4 update the rawDataElementValue
rawDataElementValue = valueService.getDataElementValue(rawDataElement, dataEntity, period);
if(rawDataElementValue != null) value = rawDataElementValue.getValue();
else{
value = new Value("");
rawDataElementValue= new RawDataElementValue(rawDataElement,dataEntity,period,value);
}
}
}
for (String header : headers){
if (!header.equals(CODE_HEADER)){
map.put("[" + positions.get(code) + "]."+ header, values.get(header));
}
}
map.put("", getLineNumberString(positions.get(code)));
positions.put(code, positions.get(code) + 1);
if (dataEntity == null)
manager.incrementNumberOfUnsavedRows();
else {
if(log.isDebugEnabled()) log.debug("Marging with data from map of header and data "+map+" Value before marge"+value);
value = rawDataElement.getType().mergeValueFromMap(value, map, "",attributes, sanitizer);
if(log.isDebugEnabled()) log.debug("Value after marge "+value);
rawDataElementValue.setValue(value);
valueService.save(rawDataElementValue);
- manager.incrementNumberOfRowsSavedWithError(sanitizer.getNumberOfErrorInRows());
+ if(sanitizer.getNumberOfErrorInRows()>0)
+ manager.incrementNumberOfRowsSavedWithError(1);
manager.incrementNumberOfSavedRows();
}
values = readFileAsMap.read(headers);
}
}catch(IOException ioe){
// TODO Please through something meaningful
throw ioe;
}finally {
readFileAsMap.close();
}
}
private class ImportSanitizer implements Sanitizer {
private final List<ImporterError> errors;
private final Map<String,Type> types;
public ImportSanitizer(List<ImporterError> errors, Map<String,Type> types) {
this.errors = errors;
this.types = types;
}
private Integer lineNumber;
private Integer numberOfErrorInRows;
public void setLineNumber(Integer lineNumber) {
this.lineNumber = lineNumber;
}
public Integer getNumberOfErrorInRows() {
return numberOfErrorInRows;
}
public void setNumberOfErrorInRows(Integer numberOfErrorInRows) {
this.numberOfErrorInRows = numberOfErrorInRows;
}
@Override
public Object sanitizeValue(Object value, Type type, String prefix,String genericPrefix) {
switch (type.getType()) {
case ENUM:
return validateImportEnum(genericPrefix, value);
case BOOL:
return validateImportBool(genericPrefix, value);
case NUMBER:
return validateImportNumber(genericPrefix, value);
case TEXT:
return validateImportString(genericPrefix, value);
case STRING:
return validateImportString(genericPrefix, value);
case DATE:
return validateImportDate(genericPrefix, value);
default:
errors.add(new ImporterError(lineNumber, prefix, "error.message.unknown.type"));
return null;
}
}
private String validateImportEnum(String header, Object value) {
Enum enumValue = new Enum();
List<EnumOption> enumOptions = new ArrayList<EnumOption>();
enumValue = dataService.findEnumByCode(types.get(header).getEnumCode());
if (enumValue != null) {
enumOptions = enumValue.getEnumOptions();
for (EnumOption enumOption : enumOptions)
if (enumOption.getValue().equals(value))
return enumOption.getValue();
}
this.setNumberOfErrorInRows(this.getNumberOfErrorInRows()+1);
errors.add(new ImporterError(lineNumber, header,"error.message.enume"));
return null;
}
private Boolean validateImportBool(String header, Object value){
if (((String) value).equals("0") || ((String) value).equals("1"))
if (((String) value).equals("1"))
return true;
else
return false;
this.setNumberOfErrorInRows(this.getNumberOfErrorInRows() + 1);
errors.add(new ImporterError(lineNumber, header,
"error.message.boolean"));
return null;
}
private Number validateImportNumber(String header, Object value) {
try {
return Double.parseDouble((String) value);
} catch (NumberFormatException e) {
if (log.isDebugEnabled()) log.debug("Value in this cell [Line: " + lineNumber+ ",Column: " + header + "] has to be a Number"+ value, e);
}
this.setNumberOfErrorInRows(this.getNumberOfErrorInRows()+1);
errors.add(new ImporterError(lineNumber, header,"error.message.number"));
return null;
}
private String validateImportString(String header, Object value){
if(value instanceof String || value.equals(""))
return (String) value;
this.setNumberOfErrorInRows(this.getNumberOfErrorInRows()+1);
errors.add(new ImporterError(lineNumber, header, "error.message.string.text"));
return null;
}
private Date validateImportDate(String header, Object value){
if(value instanceof String)
try {
return Utils.parseDate((String)value);
} catch (ParseException e) {
if (log.isDebugEnabled()) log.debug("Value in this cell [Line: " + lineNumber+ ",Column: " + header + "] has to be a Date (dd-MM-yyyy)"+ value, e);
}
this.setNumberOfErrorInRows(this.getNumberOfErrorInRows()+1);
errors.add(new ImporterError(lineNumber, header, "error.message.date"));
return null;
}
}
public void setLocationService(LocationService locationService) {
this.locationService = locationService;
}
public void setValueService(ValueService valueService) {
this.valueService = valueService;
}
public void setDataService(DataService dataService) {
this.dataService = dataService;
}
private static List<String> getLineNumberString(Integer lineNumber) {
List<String> result = new ArrayList<String>();
for (int i = 0; i <= lineNumber; i++) {
result.add("["+i+"]");
}
return result;
}
}
| true | true | public void importFile(RawDataElement rawDataElement, Reader reader, Period period,ImporterErrorManager manager) throws IOException{
ICsvMapReader readFileAsMap = new CsvMapReader(reader, CsvPreference.EXCEL_PREFERENCE);
try{
final String[] headers = readFileAsMap.getCSVHeader(true);
String code=null;
Map<String,Integer> positions = new HashMap<String,Integer>();
Map<String,String> values = readFileAsMap.read(headers);
Map<String,Type> types = new HashMap<String,Type>();
for (String header : headers) {
try {
if(!header.equals(CODE_HEADER))
types.put("[_]."+header,rawDataElement.getType().getType("[_]."+header));
} catch(IllegalArgumentException e){
if(log.isWarnEnabled()) log.warn("Column type not found for header"+header, e);
manager.getErrors().add(new ImporterError(readFileAsMap.getLineNumber(),header,"error.message.unknowm.column.type"));
}
}
Value value = null;
DataLocationEntity dataEntity=null;
RawDataElementValue rawDataElementValue= null;
manager.setNumberOfSavedRows(0);
manager.setNumberOfUnsavedRows(0);
manager.setNumberOfRowsSavedWithError(0);
ImportSanitizer sanitizer = new ImportSanitizer(manager.getErrors(), types);
while (values != null) {
Map <String,Object> map = new HashMap<String,Object>();
Set<String> attributes = new HashSet<String>();
sanitizer.setLineNumber(readFileAsMap.getLineNumber());
sanitizer.setNumberOfErrorInRows(0);
if(!values.get(CODE_HEADER).equals(code)){
// The location changes, we need to update the code, location, position, rawDataElementValue
// 1 update the code
code = values.get(CODE_HEADER);
// 2 update the position
if (positions.get(code) == null) positions.put(code, 0);
// 3 update the location
dataEntity = locationService.findCalculationEntityByCode(code, DataLocationEntity.class);
if(dataEntity==null){
manager.getErrors().add(new ImporterError(readFileAsMap.getLineNumber(),CODE_HEADER,"error.message.unknown.location"));
}else{
// 4 update the rawDataElementValue
rawDataElementValue = valueService.getDataElementValue(rawDataElement, dataEntity, period);
if(rawDataElementValue != null) value = rawDataElementValue.getValue();
else{
value = new Value("");
rawDataElementValue= new RawDataElementValue(rawDataElement,dataEntity,period,value);
}
}
}
for (String header : headers){
if (!header.equals(CODE_HEADER)){
map.put("[" + positions.get(code) + "]."+ header, values.get(header));
}
}
map.put("", getLineNumberString(positions.get(code)));
positions.put(code, positions.get(code) + 1);
if (dataEntity == null)
manager.incrementNumberOfUnsavedRows();
else {
if(log.isDebugEnabled()) log.debug("Marging with data from map of header and data "+map+" Value before marge"+value);
value = rawDataElement.getType().mergeValueFromMap(value, map, "",attributes, sanitizer);
if(log.isDebugEnabled()) log.debug("Value after marge "+value);
rawDataElementValue.setValue(value);
valueService.save(rawDataElementValue);
manager.incrementNumberOfRowsSavedWithError(sanitizer.getNumberOfErrorInRows());
manager.incrementNumberOfSavedRows();
}
values = readFileAsMap.read(headers);
}
}catch(IOException ioe){
// TODO Please through something meaningful
throw ioe;
}finally {
readFileAsMap.close();
}
}
| public void importFile(RawDataElement rawDataElement, Reader reader, Period period,ImporterErrorManager manager) throws IOException{
ICsvMapReader readFileAsMap = new CsvMapReader(reader, CsvPreference.EXCEL_PREFERENCE);
try{
final String[] headers = readFileAsMap.getCSVHeader(true);
String code=null;
Map<String,Integer> positions = new HashMap<String,Integer>();
Map<String,String> values = readFileAsMap.read(headers);
Map<String,Type> types = new HashMap<String,Type>();
for (String header : headers) {
try {
if(!header.equals(CODE_HEADER))
types.put("[_]."+header,rawDataElement.getType().getType("[_]."+header));
} catch(IllegalArgumentException e){
if(log.isWarnEnabled()) log.warn("Column type not found for header"+header, e);
manager.getErrors().add(new ImporterError(readFileAsMap.getLineNumber(),header,"error.message.unknowm.column.type"));
}
}
Value value = null;
DataLocationEntity dataEntity=null;
RawDataElementValue rawDataElementValue= null;
manager.setNumberOfSavedRows(0);
manager.setNumberOfUnsavedRows(0);
manager.setNumberOfRowsSavedWithError(0);
ImportSanitizer sanitizer = new ImportSanitizer(manager.getErrors(), types);
while (values != null) {
Map <String,Object> map = new HashMap<String,Object>();
Set<String> attributes = new HashSet<String>();
sanitizer.setLineNumber(readFileAsMap.getLineNumber());
sanitizer.setNumberOfErrorInRows(0);
if(!values.get(CODE_HEADER).equals(code)){
// The location changes, we need to update the code, location, position, rawDataElementValue
// 1 update the code
code = values.get(CODE_HEADER);
// 2 update the position
if (positions.get(code) == null) positions.put(code, 0);
// 3 update the location
dataEntity = locationService.findCalculationEntityByCode(code, DataLocationEntity.class);
if(dataEntity==null){
manager.getErrors().add(new ImporterError(readFileAsMap.getLineNumber(),CODE_HEADER,"error.message.unknown.location"));
}else{
// 4 update the rawDataElementValue
rawDataElementValue = valueService.getDataElementValue(rawDataElement, dataEntity, period);
if(rawDataElementValue != null) value = rawDataElementValue.getValue();
else{
value = new Value("");
rawDataElementValue= new RawDataElementValue(rawDataElement,dataEntity,period,value);
}
}
}
for (String header : headers){
if (!header.equals(CODE_HEADER)){
map.put("[" + positions.get(code) + "]."+ header, values.get(header));
}
}
map.put("", getLineNumberString(positions.get(code)));
positions.put(code, positions.get(code) + 1);
if (dataEntity == null)
manager.incrementNumberOfUnsavedRows();
else {
if(log.isDebugEnabled()) log.debug("Marging with data from map of header and data "+map+" Value before marge"+value);
value = rawDataElement.getType().mergeValueFromMap(value, map, "",attributes, sanitizer);
if(log.isDebugEnabled()) log.debug("Value after marge "+value);
rawDataElementValue.setValue(value);
valueService.save(rawDataElementValue);
if(sanitizer.getNumberOfErrorInRows()>0)
manager.incrementNumberOfRowsSavedWithError(1);
manager.incrementNumberOfSavedRows();
}
values = readFileAsMap.read(headers);
}
}catch(IOException ioe){
// TODO Please through something meaningful
throw ioe;
}finally {
readFileAsMap.close();
}
}
|
diff --git a/plugins/org.chromium.sdk/src/org/chromium/sdk/internal/SessionManager.java b/plugins/org.chromium.sdk/src/org/chromium/sdk/internal/SessionManager.java
index 738e89e0..e5e51bf7 100644
--- a/plugins/org.chromium.sdk/src/org/chromium/sdk/internal/SessionManager.java
+++ b/plugins/org.chromium.sdk/src/org/chromium/sdk/internal/SessionManager.java
@@ -1,205 +1,205 @@
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.sdk.internal;
import java.util.ArrayList;
import java.util.List;
/**
* Manager that switches on and off some resource for a shared multiuser access.
* The nature of actual resource should be defined in subclass of
* {@link SessionManager}. Time period when resource is on is called "session".
* Switch on operation (aka session creation) must be an atomic operation.
* Switch off (aka session closing) may be lengthy asynchronous operation.
* <p>
* If no user needs it, manager switches the resource off. On the first demand
* resource gets switched on (and new session gets created). After the last user
* has released the resource, the session finishes either instantly or
* some time later. In the latter case resource becomes temporary unavailable.
* The manager does not operate resource in any other sense than switching it
* on and off.
* <p>
* Every user first acquires the resource by calling {@link #connect()} method.
* It gets ticket which points to the corresponding session. Method
* {@link Ticket#dismiss()} must be called when resource is no more needed.
* @param <SESSION> user class that represents a session; must
* extend {@link SessionBase}
* @param <EX> exception that is allowed to be thrown when resource is being switched
* on and the new session is starting; {@link RuntimeException}
* is a good default parameter value
*/
public abstract class SessionManager<SESSION extends SessionManager.SessionBase<SESSION>,
EX extends Exception> {
// Holds current session; all access must be synchronized on "this".
private SESSION currentSession = null;
/**
* Ticket to resource use. Every client gets its own copy. All tickets must
* be dismissed in order for resource to be switched off.
* @param <SESSION> is be the same type as of manager that issued this ticket
*/
public interface Ticket<SESSION> {
/**
* Each valid ticket points to session of the resource. The actual type
* {@code SESSION} is provided by user (as a type parameter of enclosing
* SessionManager). The actual resource should be accessible from
* {@code SESSION}.
* @return non-null current session
* @throws IllegalStateException if ticket is no longer valid
*/
SESSION getSession();
/**
* Releases resource and makes ticket invalid. Switches the resource
* off if it was a last ticket.
* @throws IllegalStateException if ticket is no more valid
*/
void dismiss();
}
/**
* Registers user request for resource and switches the resource on if required.
* @return new ticket which symbolize use of resource until
* {@link Ticket#dismiss()} is called
* @throws EX if new session was being created and failed
*/
public Ticket<SESSION> connect() throws EX {
synchronized (this) {
if (currentSession == null) {
currentSession = newSessionObject();
if (currentSession.manager != this) {
throw new IllegalArgumentException("Wrong manager was set in session");
}
}
return currentSession.newTicket();
}
}
/**
* User-provided constructor of a new session. It should switch the resource on
* whatever it actually means.
* @return new instance of resource use session
* @throws EX if switching resource on or creating a new session failed
*/
protected abstract SESSION newSessionObject() throws EX;
/**
* Base class for user session. It should be subclassed and it is parameterized by
* this subclass. Object construction should have semantics of switching resource
* on. It gets constructed via user-defined {@link SessionManager#newSessionObject()}.
* Subclass should honestly pass instance of {@link SessionManager} to the base
* class. User also should implement {@link #lastTicketDismissed()} and helper
* {@link #getThisAsSession()}.
* @param <SESSION> the very user class which extends {@link SessionBase};
* {@link #getThisAsSession()} should compile as "return this;"
*/
public static abstract class SessionBase<SESSION extends SessionBase<SESSION>> {
private final SessionManager<?, ?> manager;
private boolean isConnectionStopped = false;
SessionBase(SessionManager<SESSION, ?> manager) {
this.manager = manager;
}
/**
* Must be simply "return this;"
*/
protected abstract SESSION getThisAsSession();
/**
* User-provided behavior when no more valid tickets left. Resource should
* be switched off whatever it actually means and the session closed.
* There are 3 options here:
* <ol>
* <li>Method is finished with {@link #closeSession()} call. Method
* {@link SessionManager#connect()} does not interrupt its service and simply
* creates new session the next call.
* <li>Method is finished with {@link #stopNewConnections()} call. Connection
* process is put on hold after this and {@link SessionManager#connect()} starts
* to throw {@link IllegalStateException}. Later {@link #closeSession()} must
* be called possibly asynchronously. After this the resource is available again
* and a new session may be created.
* <li>Do not call any of methods listed above. This probably works but is
* not specified here.
* </ol>
*/
protected abstract void lastTicketDismissed();
/**
* See {@link #lastTicketDismissed()}. This method is supposed to be called
* from there, but not necessarily.
*/
protected void stopNewConnections() {
synchronized (manager) {
isConnectionStopped = true;
}
}
/**
* See {@link #lastTicketDismissed()}. This method is supposed to be called
* from there, but not necessarily.
*/
protected void closeSession() {
synchronized (manager) {
isConnectionStopped = true;
- if (tickets.isEmpty()) {
+ if (!tickets.isEmpty()) {
throw new IllegalStateException("Some tickets are still valid");
}
if (manager.currentSession != null) {
throw new IllegalStateException("Session is not active");
}
manager.currentSession = null;
}
}
/**
* Creates new ticket that is to be dismissed later.
* Internal method. However user may use it or even make it public.
*/
protected Ticket<SESSION> newTicket() {
synchronized (manager) {
if (isConnectionStopped) {
throw new IllegalStateException("Connection has been stopped");
}
TicketImpl ticketImpl = new TicketImpl();
tickets.add(ticketImpl);
return ticketImpl;
}
}
private final List<TicketImpl> tickets = new ArrayList<TicketImpl>();
private class TicketImpl implements Ticket<SESSION> {
private volatile boolean isDismissed = false;
public void dismiss() {
synchronized (manager) {
boolean res = tickets.remove(this);
if (!res) {
throw new IllegalStateException("Ticket is already dismissed");
}
if (tickets.isEmpty()) {
lastTicketDismissed();
}
isDismissed = true;
}
}
public SESSION getSession() {
if (isDismissed) {
throw new IllegalStateException("Ticket is dismissed");
}
return getThisAsSession();
}
}
}
/**
* This method is completely unsynchronized. Is should be used for
* single-threaded tests only.
*/
public SESSION getCurrentSessionForTest() {
return currentSession;
}
}
| true | true | protected void closeSession() {
synchronized (manager) {
isConnectionStopped = true;
if (tickets.isEmpty()) {
throw new IllegalStateException("Some tickets are still valid");
}
if (manager.currentSession != null) {
throw new IllegalStateException("Session is not active");
}
manager.currentSession = null;
}
}
| protected void closeSession() {
synchronized (manager) {
isConnectionStopped = true;
if (!tickets.isEmpty()) {
throw new IllegalStateException("Some tickets are still valid");
}
if (manager.currentSession != null) {
throw new IllegalStateException("Session is not active");
}
manager.currentSession = null;
}
}
|
diff --git a/AddBinary/Solution.java b/AddBinary/Solution.java
index 478a0a6..75eb45f 100644
--- a/AddBinary/Solution.java
+++ b/AddBinary/Solution.java
@@ -1,33 +1,38 @@
public class Solution {
public String addBinary(String a, String b) {
if(a == null)
return b;
if(b == null)
return a;
char [] src = a.toCharArray();
char [] dest = b.toCharArray();
int srcLen = a.length();
int destLen = b.length();
int maxSize = (srcLen > destLen)?(srcLen):(destLen);
char [] sum = new char[maxSize+1];
+ //remember to reset!!!
int carry = 0;
int i = 0;
for(; i<maxSize || carry != 0; ++i){
int tmp = carry;
+ carry = 0;
+ //remember to convert from int to char
if(i < srcLen)
- tmp +=src[srcLen-1-i];
+ tmp +=src[srcLen-1-i]-'0';
if(i < destLen)
- tmp +=dest[destLen-1-i];
- if(tmp >1)
+ tmp +=dest[destLen-1-i]-'0';
+ if(tmp >1) {
carry = 1;
- sum[i]= tmp - 0 + '0';
+ tmp -=2;
+ }
+ sum[i]= (char)(tmp - 0 + '0');
}
--i;
for(int j = 0; j<i; j++,i--){
char tmp = sum[j];
sum[j] = sum[i];
sum[i] = tmp;
}
return new String(sum);
}
}
| false | true | public String addBinary(String a, String b) {
if(a == null)
return b;
if(b == null)
return a;
char [] src = a.toCharArray();
char [] dest = b.toCharArray();
int srcLen = a.length();
int destLen = b.length();
int maxSize = (srcLen > destLen)?(srcLen):(destLen);
char [] sum = new char[maxSize+1];
int carry = 0;
int i = 0;
for(; i<maxSize || carry != 0; ++i){
int tmp = carry;
if(i < srcLen)
tmp +=src[srcLen-1-i];
if(i < destLen)
tmp +=dest[destLen-1-i];
if(tmp >1)
carry = 1;
sum[i]= tmp - 0 + '0';
}
--i;
for(int j = 0; j<i; j++,i--){
char tmp = sum[j];
sum[j] = sum[i];
sum[i] = tmp;
}
return new String(sum);
}
| public String addBinary(String a, String b) {
if(a == null)
return b;
if(b == null)
return a;
char [] src = a.toCharArray();
char [] dest = b.toCharArray();
int srcLen = a.length();
int destLen = b.length();
int maxSize = (srcLen > destLen)?(srcLen):(destLen);
char [] sum = new char[maxSize+1];
//remember to reset!!!
int carry = 0;
int i = 0;
for(; i<maxSize || carry != 0; ++i){
int tmp = carry;
carry = 0;
//remember to convert from int to char
if(i < srcLen)
tmp +=src[srcLen-1-i]-'0';
if(i < destLen)
tmp +=dest[destLen-1-i]-'0';
if(tmp >1) {
carry = 1;
tmp -=2;
}
sum[i]= (char)(tmp - 0 + '0');
}
--i;
for(int j = 0; j<i; j++,i--){
char tmp = sum[j];
sum[j] = sum[i];
sum[i] = tmp;
}
return new String(sum);
}
|
diff --git a/src/info/pishen/gameoflife/MainGUI.java b/src/info/pishen/gameoflife/MainGUI.java
index ed076a1..0c60d8f 100644
--- a/src/info/pishen/gameoflife/MainGUI.java
+++ b/src/info/pishen/gameoflife/MainGUI.java
@@ -1,327 +1,333 @@
package info.pishen.gameoflife;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.JSlider;
import java.awt.FlowLayout;
import javax.swing.JLabel;
public class MainGUI extends JFrame {
private static Logger log = Logger.getLogger(MainGUI.class.getName());
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel mainPanel, contentPanel;
private JButton runPauseButton;
private JScrollBar hScrollBar, vScrollBar;
//private int contentWidth, contentHeight;
private int cellSize = 10;
private final int MIN_CELL_SIZE = 2, MAX_CELL_SIZE = 20;
private boolean isRunning = false;
private boolean updateValue;
private CellGrid cellGrid;
private ParallelGenerator generator;
private JSlider threadNumSlider;
private JButton zoomIn;
private JButton zoomOut;
private JLabel threadNumLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
log.info("starting...");
log.info("processors: " + Runtime.getRuntime().availableProcessors());
CellGrid cellGrid = new CellGrid(2000, 2000);
MainGUI frame = new MainGUI(cellGrid, new ParallelGenerator(cellGrid));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainGUI(CellGrid cellGridArg, ParallelGenerator generatorArg) {
this.cellGrid = cellGridArg;
this.generator = generatorArg;
cellGrid.setMainGUI(this);
//contentWidth = cellGrid.getColNum() * cellSize;
//contentHeight = cellGrid.getRowNum() * cellSize;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 500);
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BorderLayout(0, 0));
setContentPane(mainPanel);
JPanel buttomPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) buttomPanel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
mainPanel.add(buttomPanel, BorderLayout.SOUTH);
runPauseButton = new JButton("Run");
runPauseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(isRunning){
isRunning = false;
runPauseButton.setText("Run");
runPauseButton.setEnabled(false);
//pause
generator.pause(MainGUI.this);
}else{
isRunning = true;
runPauseButton.setText("Pause");
//run
generator.run();
}
}
});
buttomPanel.add(runPauseButton);
threadNumSlider = new JSlider();
threadNumSlider.setMinimum(1);
threadNumSlider.setMaximum(Runtime.getRuntime().availableProcessors());
threadNumSlider.setValue(1);
threadNumSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
threadNumLabel.setText("" + threadNumSlider.getValue());
//change number of threads
generator.setParallel(threadNumSlider.getValue());
}
});
zoomIn = new JButton("+");
zoomIn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cellSize++;
zoomOut.setEnabled(true);
if(cellSize == MAX_CELL_SIZE){
zoomIn.setEnabled(false);
}
updateScale();
}
});
buttomPanel.add(zoomIn);
zoomOut = new JButton("-");
zoomOut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cellSize--;
zoomIn.setEnabled(true);
if(cellSize == MIN_CELL_SIZE){
zoomOut.setEnabled(false);
}
updateScale();
}
});
buttomPanel.add(zoomOut);
buttomPanel.add(threadNumSlider);
threadNumLabel = new JLabel("1");
buttomPanel.add(threadNumLabel);
JPanel customScrollPanel = new JPanel();
mainPanel.add(customScrollPanel, BorderLayout.CENTER);
GridBagLayout gbl_customScrollPanel = new GridBagLayout();
customScrollPanel.setLayout(gbl_customScrollPanel);
contentPanel = new ContentPanel();
contentPanel.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX() + hScrollBar.getValue();
int y = e.getY() + vScrollBar.getValue();
+ if(isRunning || runPauseButton.isEnabled() == false){
+ return;
+ }
if(x >= 0 && x < hScrollBar.getMaximum() && y >= 0 && y < vScrollBar.getMaximum()){
int i = y / cellSize, j = x / cellSize;
updateValue = !cellGrid.getValue(i, j);
cellGrid.updateGrid(i, j, updateValue);
contentPanel.repaint();
}
}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {}
});
contentPanel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getX() + hScrollBar.getValue();
int y = e.getY() + vScrollBar.getValue();
+ if(isRunning || runPauseButton.isEnabled() == false){
+ return;
+ }
if(x >= 0 && x < hScrollBar.getMaximum() && y >= 0 && y < vScrollBar.getMaximum()){
int i = y / cellSize, j = x / cellSize;
cellGrid.updateGrid(i, j, updateValue);
contentPanel.repaint();
}
}
});
GridBagConstraints gbc_contentPanel = new GridBagConstraints();
gbc_contentPanel.weighty = 1.0;
gbc_contentPanel.weightx = 1.0;
gbc_contentPanel.insets = new Insets(0, 0, 0, 0);
gbc_contentPanel.fill = GridBagConstraints.BOTH;
gbc_contentPanel.gridx = 0;
gbc_contentPanel.gridy = 0;
customScrollPanel.add(contentPanel, gbc_contentPanel);
hScrollBar = new JScrollBar();
hScrollBar.setOrientation(JScrollBar.HORIZONTAL);
hScrollBar.setMaximum(cellGrid.getColNum() * cellSize);
hScrollBar.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
contentPanel.repaint();
}
});
hScrollBar.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentResized(ComponentEvent e) {
hScrollBar.setValue(Math.min(hScrollBar.getValue(), hScrollBar.getMaximum() - hScrollBar.getWidth()));
hScrollBar.setVisibleAmount(hScrollBar.getWidth());
}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
});
GridBagConstraints gbc_hScrollBar = new GridBagConstraints();
gbc_hScrollBar.insets = new Insets(0, 0, 0, 0);
gbc_hScrollBar.fill = GridBagConstraints.HORIZONTAL;
gbc_hScrollBar.gridx = 0;
gbc_hScrollBar.gridy = 1;
customScrollPanel.add(hScrollBar, gbc_hScrollBar);
vScrollBar = new JScrollBar();
vScrollBar.setMaximum(cellGrid.getRowNum() * cellSize);
vScrollBar.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
contentPanel.repaint();
}
});
vScrollBar.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentResized(ComponentEvent e) {
vScrollBar.setValue(Math.min(vScrollBar.getValue(), vScrollBar.getMaximum() - vScrollBar.getHeight()));
vScrollBar.setVisibleAmount(vScrollBar.getHeight());
}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
});
GridBagConstraints gbc_vScrollBar = new GridBagConstraints();
gbc_vScrollBar.fill = GridBagConstraints.VERTICAL;
gbc_vScrollBar.gridx = 1;
gbc_vScrollBar.gridy = 0;
customScrollPanel.add(vScrollBar, gbc_vScrollBar);
}
private void updateScale(){
hScrollBar.setMaximum(cellGrid.getColNum() * cellSize);
vScrollBar.setMaximum(cellGrid.getRowNum() * cellSize);
contentPanel.repaint();
}
public void repaintGrid(){
EventQueue.invokeLater(new Runnable(){
@Override
public void run() {
contentPanel.repaint();
}
});
}
public void enableRun(){
runPauseButton.setEnabled(true);
}
private class ContentPanel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int xLeft = 0 - (hScrollBar.getValue() % cellSize);
int yTop = 0 - (vScrollBar.getValue() % cellSize);
int jLeft = hScrollBar.getValue() / cellSize;
int iTop = vScrollBar.getValue() / cellSize;
int jRight = Math.min(jLeft + hScrollBar.getVisibleAmount() / cellSize + 1, cellGrid.getColNum() - 1);
int iBottom = Math.min(iTop + vScrollBar.getVisibleAmount() / cellSize + 1, cellGrid.getRowNum() - 1);
boolean[][] partialGrid = cellGrid.getPartialGrid(iTop, jLeft, iBottom, jRight);
for(int x = xLeft, j = 0; j < partialGrid[0].length; x += cellSize, j++){
for(int y = yTop, i = 0; i < partialGrid.length; y += cellSize, i++){
g.drawRect(x, y, cellSize, cellSize);
if(partialGrid[i][j] == true){
g.fillRect(x, y, cellSize, cellSize);
}
}
}
}
}
}
| false | true | public MainGUI(CellGrid cellGridArg, ParallelGenerator generatorArg) {
this.cellGrid = cellGridArg;
this.generator = generatorArg;
cellGrid.setMainGUI(this);
//contentWidth = cellGrid.getColNum() * cellSize;
//contentHeight = cellGrid.getRowNum() * cellSize;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 500);
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BorderLayout(0, 0));
setContentPane(mainPanel);
JPanel buttomPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) buttomPanel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
mainPanel.add(buttomPanel, BorderLayout.SOUTH);
runPauseButton = new JButton("Run");
runPauseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(isRunning){
isRunning = false;
runPauseButton.setText("Run");
runPauseButton.setEnabled(false);
//pause
generator.pause(MainGUI.this);
}else{
isRunning = true;
runPauseButton.setText("Pause");
//run
generator.run();
}
}
});
buttomPanel.add(runPauseButton);
threadNumSlider = new JSlider();
threadNumSlider.setMinimum(1);
threadNumSlider.setMaximum(Runtime.getRuntime().availableProcessors());
threadNumSlider.setValue(1);
threadNumSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
threadNumLabel.setText("" + threadNumSlider.getValue());
//change number of threads
generator.setParallel(threadNumSlider.getValue());
}
});
zoomIn = new JButton("+");
zoomIn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cellSize++;
zoomOut.setEnabled(true);
if(cellSize == MAX_CELL_SIZE){
zoomIn.setEnabled(false);
}
updateScale();
}
});
buttomPanel.add(zoomIn);
zoomOut = new JButton("-");
zoomOut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cellSize--;
zoomIn.setEnabled(true);
if(cellSize == MIN_CELL_SIZE){
zoomOut.setEnabled(false);
}
updateScale();
}
});
buttomPanel.add(zoomOut);
buttomPanel.add(threadNumSlider);
threadNumLabel = new JLabel("1");
buttomPanel.add(threadNumLabel);
JPanel customScrollPanel = new JPanel();
mainPanel.add(customScrollPanel, BorderLayout.CENTER);
GridBagLayout gbl_customScrollPanel = new GridBagLayout();
customScrollPanel.setLayout(gbl_customScrollPanel);
contentPanel = new ContentPanel();
contentPanel.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX() + hScrollBar.getValue();
int y = e.getY() + vScrollBar.getValue();
if(x >= 0 && x < hScrollBar.getMaximum() && y >= 0 && y < vScrollBar.getMaximum()){
int i = y / cellSize, j = x / cellSize;
updateValue = !cellGrid.getValue(i, j);
cellGrid.updateGrid(i, j, updateValue);
contentPanel.repaint();
}
}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {}
});
contentPanel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getX() + hScrollBar.getValue();
int y = e.getY() + vScrollBar.getValue();
if(x >= 0 && x < hScrollBar.getMaximum() && y >= 0 && y < vScrollBar.getMaximum()){
int i = y / cellSize, j = x / cellSize;
cellGrid.updateGrid(i, j, updateValue);
contentPanel.repaint();
}
}
});
GridBagConstraints gbc_contentPanel = new GridBagConstraints();
gbc_contentPanel.weighty = 1.0;
gbc_contentPanel.weightx = 1.0;
gbc_contentPanel.insets = new Insets(0, 0, 0, 0);
gbc_contentPanel.fill = GridBagConstraints.BOTH;
gbc_contentPanel.gridx = 0;
gbc_contentPanel.gridy = 0;
customScrollPanel.add(contentPanel, gbc_contentPanel);
hScrollBar = new JScrollBar();
hScrollBar.setOrientation(JScrollBar.HORIZONTAL);
hScrollBar.setMaximum(cellGrid.getColNum() * cellSize);
hScrollBar.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
contentPanel.repaint();
}
});
hScrollBar.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentResized(ComponentEvent e) {
hScrollBar.setValue(Math.min(hScrollBar.getValue(), hScrollBar.getMaximum() - hScrollBar.getWidth()));
hScrollBar.setVisibleAmount(hScrollBar.getWidth());
}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
});
GridBagConstraints gbc_hScrollBar = new GridBagConstraints();
gbc_hScrollBar.insets = new Insets(0, 0, 0, 0);
gbc_hScrollBar.fill = GridBagConstraints.HORIZONTAL;
gbc_hScrollBar.gridx = 0;
gbc_hScrollBar.gridy = 1;
customScrollPanel.add(hScrollBar, gbc_hScrollBar);
vScrollBar = new JScrollBar();
vScrollBar.setMaximum(cellGrid.getRowNum() * cellSize);
vScrollBar.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
contentPanel.repaint();
}
});
vScrollBar.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentResized(ComponentEvent e) {
vScrollBar.setValue(Math.min(vScrollBar.getValue(), vScrollBar.getMaximum() - vScrollBar.getHeight()));
vScrollBar.setVisibleAmount(vScrollBar.getHeight());
}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
});
GridBagConstraints gbc_vScrollBar = new GridBagConstraints();
gbc_vScrollBar.fill = GridBagConstraints.VERTICAL;
gbc_vScrollBar.gridx = 1;
gbc_vScrollBar.gridy = 0;
customScrollPanel.add(vScrollBar, gbc_vScrollBar);
}
| public MainGUI(CellGrid cellGridArg, ParallelGenerator generatorArg) {
this.cellGrid = cellGridArg;
this.generator = generatorArg;
cellGrid.setMainGUI(this);
//contentWidth = cellGrid.getColNum() * cellSize;
//contentHeight = cellGrid.getRowNum() * cellSize;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 500);
mainPanel = new JPanel();
mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BorderLayout(0, 0));
setContentPane(mainPanel);
JPanel buttomPanel = new JPanel();
FlowLayout flowLayout = (FlowLayout) buttomPanel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
mainPanel.add(buttomPanel, BorderLayout.SOUTH);
runPauseButton = new JButton("Run");
runPauseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(isRunning){
isRunning = false;
runPauseButton.setText("Run");
runPauseButton.setEnabled(false);
//pause
generator.pause(MainGUI.this);
}else{
isRunning = true;
runPauseButton.setText("Pause");
//run
generator.run();
}
}
});
buttomPanel.add(runPauseButton);
threadNumSlider = new JSlider();
threadNumSlider.setMinimum(1);
threadNumSlider.setMaximum(Runtime.getRuntime().availableProcessors());
threadNumSlider.setValue(1);
threadNumSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
threadNumLabel.setText("" + threadNumSlider.getValue());
//change number of threads
generator.setParallel(threadNumSlider.getValue());
}
});
zoomIn = new JButton("+");
zoomIn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cellSize++;
zoomOut.setEnabled(true);
if(cellSize == MAX_CELL_SIZE){
zoomIn.setEnabled(false);
}
updateScale();
}
});
buttomPanel.add(zoomIn);
zoomOut = new JButton("-");
zoomOut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cellSize--;
zoomIn.setEnabled(true);
if(cellSize == MIN_CELL_SIZE){
zoomOut.setEnabled(false);
}
updateScale();
}
});
buttomPanel.add(zoomOut);
buttomPanel.add(threadNumSlider);
threadNumLabel = new JLabel("1");
buttomPanel.add(threadNumLabel);
JPanel customScrollPanel = new JPanel();
mainPanel.add(customScrollPanel, BorderLayout.CENTER);
GridBagLayout gbl_customScrollPanel = new GridBagLayout();
customScrollPanel.setLayout(gbl_customScrollPanel);
contentPanel = new ContentPanel();
contentPanel.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX() + hScrollBar.getValue();
int y = e.getY() + vScrollBar.getValue();
if(isRunning || runPauseButton.isEnabled() == false){
return;
}
if(x >= 0 && x < hScrollBar.getMaximum() && y >= 0 && y < vScrollBar.getMaximum()){
int i = y / cellSize, j = x / cellSize;
updateValue = !cellGrid.getValue(i, j);
cellGrid.updateGrid(i, j, updateValue);
contentPanel.repaint();
}
}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {}
});
contentPanel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getX() + hScrollBar.getValue();
int y = e.getY() + vScrollBar.getValue();
if(isRunning || runPauseButton.isEnabled() == false){
return;
}
if(x >= 0 && x < hScrollBar.getMaximum() && y >= 0 && y < vScrollBar.getMaximum()){
int i = y / cellSize, j = x / cellSize;
cellGrid.updateGrid(i, j, updateValue);
contentPanel.repaint();
}
}
});
GridBagConstraints gbc_contentPanel = new GridBagConstraints();
gbc_contentPanel.weighty = 1.0;
gbc_contentPanel.weightx = 1.0;
gbc_contentPanel.insets = new Insets(0, 0, 0, 0);
gbc_contentPanel.fill = GridBagConstraints.BOTH;
gbc_contentPanel.gridx = 0;
gbc_contentPanel.gridy = 0;
customScrollPanel.add(contentPanel, gbc_contentPanel);
hScrollBar = new JScrollBar();
hScrollBar.setOrientation(JScrollBar.HORIZONTAL);
hScrollBar.setMaximum(cellGrid.getColNum() * cellSize);
hScrollBar.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
contentPanel.repaint();
}
});
hScrollBar.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentResized(ComponentEvent e) {
hScrollBar.setValue(Math.min(hScrollBar.getValue(), hScrollBar.getMaximum() - hScrollBar.getWidth()));
hScrollBar.setVisibleAmount(hScrollBar.getWidth());
}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
});
GridBagConstraints gbc_hScrollBar = new GridBagConstraints();
gbc_hScrollBar.insets = new Insets(0, 0, 0, 0);
gbc_hScrollBar.fill = GridBagConstraints.HORIZONTAL;
gbc_hScrollBar.gridx = 0;
gbc_hScrollBar.gridy = 1;
customScrollPanel.add(hScrollBar, gbc_hScrollBar);
vScrollBar = new JScrollBar();
vScrollBar.setMaximum(cellGrid.getRowNum() * cellSize);
vScrollBar.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
contentPanel.repaint();
}
});
vScrollBar.addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentResized(ComponentEvent e) {
vScrollBar.setValue(Math.min(vScrollBar.getValue(), vScrollBar.getMaximum() - vScrollBar.getHeight()));
vScrollBar.setVisibleAmount(vScrollBar.getHeight());
}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
});
GridBagConstraints gbc_vScrollBar = new GridBagConstraints();
gbc_vScrollBar.fill = GridBagConstraints.VERTICAL;
gbc_vScrollBar.gridx = 1;
gbc_vScrollBar.gridy = 0;
customScrollPanel.add(vScrollBar, gbc_vScrollBar);
}
|
diff --git a/src/org/rascalmpl/interpreter/staticErrors/ArgumentsMismatchError.java b/src/org/rascalmpl/interpreter/staticErrors/ArgumentsMismatchError.java
index d56db13251..58b9fcad4e 100644
--- a/src/org/rascalmpl/interpreter/staticErrors/ArgumentsMismatchError.java
+++ b/src/org/rascalmpl/interpreter/staticErrors/ArgumentsMismatchError.java
@@ -1,77 +1,69 @@
/*******************************************************************************
* Copyright (c) 2009-2011 CWI
* 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* * Jurgen J. Vinju - [email protected] - CWI
*******************************************************************************/
package org.rascalmpl.interpreter.staticErrors;
import java.util.List;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.rascalmpl.ast.AbstractAST;
import org.rascalmpl.ast.FunctionDeclaration;
import org.rascalmpl.interpreter.result.AbstractFunction;
import org.rascalmpl.interpreter.result.RascalFunction;
public class ArgumentsMismatchError extends StaticError {
private static final long serialVersionUID = -641438732779898646L;
public ArgumentsMismatchError(String name,
List<AbstractFunction> candidates, Type[] argTypes,
AbstractAST ast) {
super(computeMessage(name, candidates, argTypes), ast);
}
private static String computeMessage(String name,
List<AbstractFunction> candidates, Type[] argTypes) {
StringBuilder b = new StringBuilder();
b.append("The called signature: " + name);
b.append('(');
argumentTypes(TypeFactory.getInstance().tupleType(argTypes), b);
b.append(')');
if (candidates.size() == 1) {
b.append(",\ndoes not match the declared signature:");
}
else {
b.append(",\ndoes not match any of the declared (overloaded) signature patterns:\n");
}
for (AbstractFunction c : candidates) {
b.append('\t');
- b.append(c.getName());
- b.append('(');
- if (c instanceof RascalFunction) {
- b.append(((FunctionDeclaration) ((RascalFunction) c).getAst()).getSignature().getParameters().getFormals());
- }
- else {
- argumentTypes(c.getFunctionType().getArgumentTypes(), b);
- }
- b.append(')');
+ b.append(c.toString());
b.append('\n');
}
return b.toString();
}
private static void argumentTypes(Type argTypes, StringBuilder b) {
int i = 0;
for (Type arg : argTypes) {
if (i != 0) b.append(", ");
b.append(arg);
if (argTypes.hasFieldNames()) {
b.append(' ');
b.append(argTypes.getFieldName(i));
}
i++;
}
}
}
| true | true | private static String computeMessage(String name,
List<AbstractFunction> candidates, Type[] argTypes) {
StringBuilder b = new StringBuilder();
b.append("The called signature: " + name);
b.append('(');
argumentTypes(TypeFactory.getInstance().tupleType(argTypes), b);
b.append(')');
if (candidates.size() == 1) {
b.append(",\ndoes not match the declared signature:");
}
else {
b.append(",\ndoes not match any of the declared (overloaded) signature patterns:\n");
}
for (AbstractFunction c : candidates) {
b.append('\t');
b.append(c.getName());
b.append('(');
if (c instanceof RascalFunction) {
b.append(((FunctionDeclaration) ((RascalFunction) c).getAst()).getSignature().getParameters().getFormals());
}
else {
argumentTypes(c.getFunctionType().getArgumentTypes(), b);
}
b.append(')');
b.append('\n');
}
return b.toString();
}
| private static String computeMessage(String name,
List<AbstractFunction> candidates, Type[] argTypes) {
StringBuilder b = new StringBuilder();
b.append("The called signature: " + name);
b.append('(');
argumentTypes(TypeFactory.getInstance().tupleType(argTypes), b);
b.append(')');
if (candidates.size() == 1) {
b.append(",\ndoes not match the declared signature:");
}
else {
b.append(",\ndoes not match any of the declared (overloaded) signature patterns:\n");
}
for (AbstractFunction c : candidates) {
b.append('\t');
b.append(c.toString());
b.append('\n');
}
return b.toString();
}
|
diff --git a/src/impl/java/org/wyona/yarep/impl/AbstractNode.java b/src/impl/java/org/wyona/yarep/impl/AbstractNode.java
index e06ada9..42d4434 100644
--- a/src/impl/java/org/wyona/yarep/impl/AbstractNode.java
+++ b/src/impl/java/org/wyona/yarep/impl/AbstractNode.java
@@ -1,364 +1,364 @@
package org.wyona.yarep.impl;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.apache.log4j.Category;
import org.wyona.commons.io.PathUtil;
import org.wyona.yarep.core.NoSuchNodeException;
import org.wyona.yarep.core.NoSuchPropertyException;
import org.wyona.yarep.core.NoSuchRevisionException;
import org.wyona.yarep.core.Node;
import org.wyona.yarep.core.NodeStateException;
import org.wyona.yarep.core.NodeType;
import org.wyona.yarep.core.Property;
import org.wyona.yarep.core.PropertyType;
import org.wyona.yarep.core.Repository;
import org.wyona.yarep.core.RepositoryException;
import org.wyona.yarep.core.Revision;
/**
* This class represents a repository node and implements some basic functionality which may be
* shared among different implementations.
*/
public abstract class AbstractNode implements Node {
private static Category log = Category.getInstance(AbstractNode.class);
protected Repository repository;
protected String path;
protected String name;
protected String uuid;
protected HashMap properties;
protected LinkedHashMap revisions;
// system properties:
public static final String PROPERTY_TYPE = "yarep_type";
//public static final String PROPERTY_CONTENT = "yarep_content";
public static final String PROPERTY_SIZE = "yarep_size";
public static final String PROPERTY_LAST_MODIFIED = "yarep_lastModifed";
public static final String PROPERTY_MIME_TYPE = "yarep_mimeType";
public static final String PROPERTY_ENCODING = "yarep_encoding";
public static final String PROPERTY_IS_CHECKED_OUT = "yarep_isCheckedOut";
public static final String PROPERTY_CHECKOUT_USER_ID = "yarep_checkoutUserID";
public static final String PROPERTY_CHECKOUT_DATE = "yarep_checkoutDate";
public static final String PROPERTY_CHECKIN_DATE = "yarep_checkinDate";
/**
* Constructor
* @throws RepositoryException
*/
public AbstractNode(Repository repository, String path, String uuid) throws RepositoryException {
this.repository = repository;
this.path = path;
this.name = PathUtil.getName(path);
this.uuid = uuid;
// TODO: Make sure that no backslashes are being used
if (path.indexOf("\\") >= 0) {
- RepositoryException e = new RepositoryException();
+ RepositoryException e = new RepositoryException("path contains backslashes: " + path);
log.error(e.getMessage(), e);
throw e;
}
}
/**
* @see org.wyona.yarep.core.Node#getName()
*/
public String getName() throws RepositoryException {
return this.name;
}
/**
* @see org.wyona.yarep.core.Node#getParent()
*/
public Node getParent() throws RepositoryException {
if (getPath().equals("") || getPath().equals("/")) return null;
String parentPath = PathUtil.getParent(path);
return this.repository.getNode(parentPath);
}
/**
* @see org.wyona.yarep.core.Node#getPath()
*/
public String getPath() throws RepositoryException {
return this.path;
}
/**
* @see org.wyona.yarep.core.Node#getUUID()
*/
public String getUUID() throws RepositoryException {
return this.uuid;
}
/**
* @see org.wyona.yarep.core.Node#getType()
*/
public int getType() throws RepositoryException {
return NodeType.getType(getProperty(PROPERTY_TYPE).getString());
}
/**
* @see org.wyona.yarep.core.Node#isResource()
*/
public boolean isResource() throws RepositoryException {
return getType() == NodeType.RESOURCE;
}
/**
* @see org.wyona.yarep.core.Node#isCollection()
*/
public boolean isCollection() throws RepositoryException {
//log.debug("Node Type: " + getType() + ", Path: " + getPath());
return getType() == NodeType.COLLECTION;
}
/**
* @see org.wyona.yarep.core.Node#getNode(java.lang.String)
*/
public Node getNode(String name) throws NoSuchNodeException, RepositoryException {
String childPath = getPath() + "/" + name;
return this.repository.getNode(childPath);
}
/**
* @see org.wyona.yarep.core.Node#hasNode(java.lang.String)
*/
public boolean hasNode(String name) throws RepositoryException {
String childPath = getPath() + "/" + name;
return this.repository.existsNode(childPath);
}
/**
* @see org.wyona.yarep.core.Node#getProperty(java.lang.String)
*/
public Property getProperty(String name) throws RepositoryException {
return (Property)this.properties.get(name);
}
/**
* @see org.wyona.yarep.core.Node#getProperties()
*/
public Property[] getProperties() throws RepositoryException {
return (Property[])this.properties.values().toArray(new Property[this.properties.size()]);
}
/**
* @see org.wyona.yarep.core.Node#hasProperty(java.lang.String)
*/
public boolean hasProperty(String name) throws RepositoryException {
return this.properties.containsKey(name);
}
//public boolean hasProperties() throws RepositoryException;
/**
* @see org.wyona.yarep.core.Node#setProperty(java.lang.String, boolean)
*/
public Property setProperty(String name, boolean value) throws RepositoryException {
Property property = new DefaultProperty(name, PropertyType.BOOLEAN, this);
property.setValue(value);
setProperty(property);
return property;
}
/**
* @see org.wyona.yarep.core.Node#setProperty(java.lang.String, java.util.Date)
*/
public Property setProperty(String name, Date value) throws RepositoryException {
Property property = new DefaultProperty(name, PropertyType.DATE, this);
property.setValue(value);
setProperty(property);
return property;
}
/**
* @see org.wyona.yarep.core.Node#setProperty(java.lang.String, double)
*/
public Property setProperty(String name, double value) throws RepositoryException {
Property property = new DefaultProperty(name, PropertyType.DOUBLE, this);
property.setValue(value);
setProperty(property);
return property;
}
//public Property setProperty(String name, InputStream value) throws RepositoryException;
/**
* @see org.wyona.yarep.core.Node#setProperty(java.lang.String, long)
*/
public Property setProperty(String name, long value) throws RepositoryException {
Property property = new DefaultProperty(name, PropertyType.LONG, this);
property.setValue(value);
setProperty(property);
return property;
}
/**
* @see org.wyona.yarep.core.Node#setProperty(java.lang.String, java.lang.String)
*/
public Property setProperty(String name, String value) throws RepositoryException {
Property property = new DefaultProperty(name, PropertyType.STRING, this);
property.setValue(value);
setProperty(property);
return property;
}
/**
* @see org.wyona.yarep.core.Node#isCheckedOut()
*/
public boolean isCheckedOut() throws RepositoryException {
if (!hasProperty(PROPERTY_IS_CHECKED_OUT)) {
return false;
}
return getProperty(PROPERTY_IS_CHECKED_OUT).getBoolean();
}
/**
* @see org.wyona.yarep.core.Node#getCheckoutUserID()
*/
public String getCheckoutUserID() throws NodeStateException, RepositoryException {
if (!isCheckedOut()) {
throw new NodeStateException("Node is not checked out: " + getPath());
}
return getProperty(PROPERTY_CHECKOUT_USER_ID).getString();
}
/**
* @see org.wyona.yarep.core.Node#getCheckoutDate()
*/
public Date getCheckoutDate() throws NodeStateException, RepositoryException {
if (!isCheckedOut()) {
throw new NodeStateException("Node is not checked out: " + getPath());
}
return getProperty(PROPERTY_CHECKOUT_DATE).getDate();
}
/**
* @see org.wyona.yarep.core.Node#getCheckinDate()
*/
public Date getCheckinDate() throws NodeStateException, RepositoryException {
if (isCheckedOut()) {
throw new NodeStateException("Node is not checked in: " + getPath());
}
return getProperty(PROPERTY_CHECKIN_DATE).getDate();
}
/**
* @see org.wyona.yarep.core.Node#getRevisions()
*/
public Revision[] getRevisions() throws RepositoryException {
Collection values = this.revisions.values();
return (Revision[])values.toArray(new Revision[values.size()]);
}
/**
* @see org.wyona.yarep.core.Node#getRevision(java.lang.String)
*/
public Revision getRevision(String revisionName) throws NoSuchRevisionException, RepositoryException {
if (!this.revisions.containsKey(revisionName)) {
throw new NoSuchRevisionException("Node " + getPath() + " has no revision with name: " + revisionName);
}
return (Revision)this.revisions.get(revisionName);
}
/**
* @see org.wyona.yarep.core.Node#getRevisionByTag(java.lang.String)
*/
public Revision getRevisionByTag(String tag) throws NoSuchRevisionException, RepositoryException {
Iterator iter = this.revisions.values().iterator();
while (iter.hasNext()) {
Revision revision = (Revision)iter.next();
if (revision.hasTag() && revision.getTag().equals(tag)) {
return revision;
}
}
// revision not found:
throw new NoSuchRevisionException("Node " + getPath() + " has no revision with tag: " + tag);
}
/**
* @see org.wyona.yarep.core.Node#hasRevisionWithTag(java.lang.String)
*/
public boolean hasRevisionWithTag(String tag) throws RepositoryException {
Iterator iter = this.revisions.values().iterator();
while (iter.hasNext()) {
Revision revision = (Revision)iter.next();
if (revision.hasTag() && revision.getTag().equals(tag)) {
return true;
}
}
// revision not found:
return false;
}
/**
* @see org.wyona.yarep.core.Node#getLastModified()
*/
public long getLastModified() throws RepositoryException {
Property lastModified = getProperty(PROPERTY_LAST_MODIFIED);
if (lastModified != null) {
return lastModified.getLong();
} else {
return 0;
}
}
/**
* @see org.wyona.yarep.core.Node#getSize()
*/
public long getSize() throws RepositoryException {
Property size = getProperty(PROPERTY_SIZE);
if (size != null) {
return size.getLong();
} else {
return 0;
}
}
/**
* @see org.wyona.yarep.core.Node#getMimeType()
*/
public String getMimeType() throws RepositoryException {
Property mimeType = getProperty(PROPERTY_MIME_TYPE);
if (mimeType != null) {
return mimeType.getString();
} else {
return null;
}
}
/**
* @see org.wyona.yarep.core.Node#setMimeType(java.lang.String)
*/
public void setMimeType(String mimeType) throws RepositoryException {
setProperty(PROPERTY_MIME_TYPE, mimeType);
}
/**
* @see org.wyona.yarep.core.Node#getEncoding()
*/
public String getEncoding() throws RepositoryException {
Property encoding = getProperty(PROPERTY_ENCODING);
if (encoding != null) {
return encoding.getString();
} else {
return null;
}
}
/**
* @see org.wyona.yarep.core.Node#setEncoding(java.lang.String)
*/
public void setEncoding(String encoding) throws RepositoryException {
setProperty(PROPERTY_ENCODING, encoding);
}
}
| true | true | public AbstractNode(Repository repository, String path, String uuid) throws RepositoryException {
this.repository = repository;
this.path = path;
this.name = PathUtil.getName(path);
this.uuid = uuid;
// TODO: Make sure that no backslashes are being used
if (path.indexOf("\\") >= 0) {
RepositoryException e = new RepositoryException();
log.error(e.getMessage(), e);
throw e;
}
}
| public AbstractNode(Repository repository, String path, String uuid) throws RepositoryException {
this.repository = repository;
this.path = path;
this.name = PathUtil.getName(path);
this.uuid = uuid;
// TODO: Make sure that no backslashes are being used
if (path.indexOf("\\") >= 0) {
RepositoryException e = new RepositoryException("path contains backslashes: " + path);
log.error(e.getMessage(), e);
throw e;
}
}
|
diff --git a/common/infinitealloys/item/ItemInternetWand.java b/common/infinitealloys/item/ItemInternetWand.java
index 23ad438..2c5bd00 100644
--- a/common/infinitealloys/item/ItemInternetWand.java
+++ b/common/infinitealloys/item/ItemInternetWand.java
@@ -1,89 +1,89 @@
package infinitealloys.item;
import infinitealloys.core.InfiniteAlloys;
import infinitealloys.util.Consts;
import infinitealloys.util.MachineHelper;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemInternetWand extends ItemIA {
public ItemInternetWand(int id) {
super(id, "internetwand");
}
@Override
public boolean getShareTag() {
return true;
}
@Override
public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer player) {
if(itemstack.hasTagCompound())
itemstack.getTagCompound().removeTag("CoordsCurrent");
player.openGui(InfiniteAlloys.instance, Consts.WAND_GUI, world, (int)player.posX, (int)player.posY, (int)player.posZ);
return itemstack;
}
/** Is the machine that is at (x, y, z) OK to be added to this wand?
*
* @param x the machine's x coord
* @param y the machine's y coord
* @param z the machine's z coord
* @return true if there is space for the machine, the machine is a valid client, and it does not already exist in the wand */
public boolean isMachineValid(World world, ItemStack itemstack, int x, int y, int z) {
// If the item does not already have a tag compound, create a new one
NBTTagCompound tagCompound = itemstack.getTagCompound();
if(tagCompound == null)
itemstack.setTagCompound(tagCompound = new NBTTagCompound());
// If the wand is not full and the machine is a valid remote client
if(!tagCompound.hasKey("Coords" + (Consts.WAND_SIZE - 1)) && MachineHelper.isClient(world, x, y, z)) {
for(int i = 0; i < Consts.WAND_SIZE; i++) { // Iterate over each coord that the wand contains
if(tagCompound.hasKey("Coords" + i)) {
// If the wand already contains this machine, return false
int[] a = tagCompound.getIntArray("Coords" + i);
- if(a[1] == x && a[2] == y && a[3] == z)
+ if(a[0] == x && a[1] == y && a[2] == z)
return false;
}
}
return true; // If the machine is not already in the wand, then it is valid
}
return false;
}
/** Checks if the machine at x, y, z, can be added to the wand at itemstack, then adds it if it can */
public void addMachine(World world, ItemStack itemstack, int x, int y, int z) {
if(itemstack.getItem() instanceof ItemInternetWand && isMachineValid(world, itemstack, x, y, z)) {
NBTTagCompound tagCompound = itemstack.getTagCompound();
for(int i = 0; i < Consts.WAND_SIZE; i++) {
if(!tagCompound.hasKey("Coords" + i)) {
tagCompound.setIntArray("Coords" + i, new int[] { x, y, z });
break;
}
}
}
}
/** Removes the machine with the given index from the wand */
public void removeMachine(ItemStack itemstack, int index) {
if(itemstack.getItem() instanceof ItemInternetWand && itemstack.hasTagCompound()) { // If this is a wand and has stored data
NBTTagCompound tagCompound = itemstack.getTagCompound();
tagCompound.removeTag("Coords" + index); // Remove the tag at index
for(int i = index + 1; i < Consts.WAND_SIZE; i++) { // Iterate over each coord below the one that was removed
if(tagCompound.hasKey("Coords" + i)) { // If this key exists
tagCompound.setIntArray("Coords" + (i - 1), tagCompound.getIntArray("Coords" + i)); // Move this coord up one spot to fill the hole
tagCompound.removeTag("Coords" + i);
}
else
break; // If the tag doesn't exist, break because we have reached the end of the list
}
}
}
}
| true | true | public boolean isMachineValid(World world, ItemStack itemstack, int x, int y, int z) {
// If the item does not already have a tag compound, create a new one
NBTTagCompound tagCompound = itemstack.getTagCompound();
if(tagCompound == null)
itemstack.setTagCompound(tagCompound = new NBTTagCompound());
// If the wand is not full and the machine is a valid remote client
if(!tagCompound.hasKey("Coords" + (Consts.WAND_SIZE - 1)) && MachineHelper.isClient(world, x, y, z)) {
for(int i = 0; i < Consts.WAND_SIZE; i++) { // Iterate over each coord that the wand contains
if(tagCompound.hasKey("Coords" + i)) {
// If the wand already contains this machine, return false
int[] a = tagCompound.getIntArray("Coords" + i);
if(a[1] == x && a[2] == y && a[3] == z)
return false;
}
}
return true; // If the machine is not already in the wand, then it is valid
}
return false;
}
| public boolean isMachineValid(World world, ItemStack itemstack, int x, int y, int z) {
// If the item does not already have a tag compound, create a new one
NBTTagCompound tagCompound = itemstack.getTagCompound();
if(tagCompound == null)
itemstack.setTagCompound(tagCompound = new NBTTagCompound());
// If the wand is not full and the machine is a valid remote client
if(!tagCompound.hasKey("Coords" + (Consts.WAND_SIZE - 1)) && MachineHelper.isClient(world, x, y, z)) {
for(int i = 0; i < Consts.WAND_SIZE; i++) { // Iterate over each coord that the wand contains
if(tagCompound.hasKey("Coords" + i)) {
// If the wand already contains this machine, return false
int[] a = tagCompound.getIntArray("Coords" + i);
if(a[0] == x && a[1] == y && a[2] == z)
return false;
}
}
return true; // If the machine is not already in the wand, then it is valid
}
return false;
}
|
diff --git a/RACT-JACKAGT-AOPD10/src/rmit/ai/clima/jackagt/PathNode.java b/RACT-JACKAGT-AOPD10/src/rmit/ai/clima/jackagt/PathNode.java
index ea2f017..4a8883f 100644
--- a/RACT-JACKAGT-AOPD10/src/rmit/ai/clima/jackagt/PathNode.java
+++ b/RACT-JACKAGT-AOPD10/src/rmit/ai/clima/jackagt/PathNode.java
@@ -1,36 +1,36 @@
package rmit.ai.clima.jackagt;
import rmit.ai.clima.gui.grid.*;
public class PathNode implements Comparable
{
public boolean obstacle;
public boolean visited;
public GridPoint pos;
public String dir;
public int g;
public int h;
public int f;
public PathNode ()
{
visited = false;
obstacle = false;
- pos = new GridPoint();
+ pos = new GridPoint(0,0);
dir = "";
g = 0;
h = 0;
f = 0;
}
public boolean equals (Object o)
{
PathNode other = (PathNode)o;
return (f == other.f);
}
public int compareTo (Object o)
{
PathNode other = (PathNode)o;
return other.f - f;
}
}
| true | true | public PathNode ()
{
visited = false;
obstacle = false;
pos = new GridPoint();
dir = "";
g = 0;
h = 0;
f = 0;
}
| public PathNode ()
{
visited = false;
obstacle = false;
pos = new GridPoint(0,0);
dir = "";
g = 0;
h = 0;
f = 0;
}
|
diff --git a/common/src/test/java/de/consistec/syncframework/common/conflict/ConflictTypeTest.java b/common/src/test/java/de/consistec/syncframework/common/conflict/ConflictTypeTest.java
index 55a81de..0b0045b 100755
--- a/common/src/test/java/de/consistec/syncframework/common/conflict/ConflictTypeTest.java
+++ b/common/src/test/java/de/consistec/syncframework/common/conflict/ConflictTypeTest.java
@@ -1,172 +1,172 @@
package de.consistec.syncframework.common.conflict;
import static de.consistec.syncframework.common.conflict.ConflictType.CLIENT_ADD_SERVER_ADD_OR_SERVER_MOD;
import static de.consistec.syncframework.common.conflict.ConflictType.CLIENT_ADD_SERVER_DEL;
import static de.consistec.syncframework.common.conflict.ConflictType.CLIENT_DEL_SERVER_ADD_OR_SERVER_MOD;
import static de.consistec.syncframework.common.conflict.ConflictType.CLIENT_DEL_SERVER_DEL;
import static de.consistec.syncframework.common.conflict.ConflictType.CLIENT_MOD_SERVER_ADD_OR_SERVER_MOD;
import static de.consistec.syncframework.common.conflict.ConflictType.CLIENT_MOD_SERVER_DEL;
import static de.consistec.syncframework.common.util.CollectionsUtil.newHashMap;
import static org.junit.Assert.assertTrue;
import de.consistec.syncframework.common.TestBase;
import de.consistec.syncframework.common.client.ConflictHandlingData;
import de.consistec.syncframework.common.data.Change;
import de.consistec.syncframework.common.data.MDEntry;
import java.util.Date;
import java.util.Map;
import org.junit.Test;
/**
* Tests of {@link de.consistec.syncframework.common.conflict.ConflictType.Resolver Resolver} instance of
* {@link de.consistec.syncframework.common.conflict.ConflictType ConflictType} enumeration.
*
* @author Markus Backes
* @company Consistec Engineering and Consulting GmbH
* @date 20.07.12 15:09
* @since 0.0.1-SNAPSHOT
*/
public class ConflictTypeTest extends TestBase {
private static final String TEST_STRING = "testString";
private static final String TEST_TABLE_NAME = "testTablename";
private static final String TEST_COLUMN1 = "column1";
private static final String TEST_COLUMN2 = "column2";
private static final String TEST_COLUMN3 = "column3";
private static final String TEST_COLUMN4 = "column4";
private static final String TEST_COLUMN5 = "column5";
private static final String TEST_MDV = "6767e648767786786dsffdsa786dfsaf";
private enum CHANGE_CREATION_TYPE {
ADD, MOD, DEL;
}
private Change createChange(CHANGE_CREATION_TYPE creationType, boolean isClient, int revision) {
MDEntry entry = null;
Map<String, Object> rowData = newHashMap();
String testString = !isClient ? TEST_STRING : TEST_STRING + "_updateClient";
switch (creationType) {
case ADD:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
case MOD:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
case DEL:
- entry = new MDEntry(1, isClient, 1, TEST_TABLE_NAME, null);
+ entry = new MDEntry(1, false, 1, TEST_TABLE_NAME, null);
// no rowData, they were deleted
break;
default:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
}
Change change = new Change(entry, rowData);
return change;
}
@Test
public void testIsDelAddConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.DEL, true, 1);
Change serverChange = createChange(CHANGE_CREATION_TYPE.ADD, false, 0);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_DEL_SERVER_ADD_OR_SERVER_MOD.isTheCase(data));
}
@Test
public void testIsDelModConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.DEL, true, 1);
Change serverChange = createChange(CHANGE_CREATION_TYPE.MOD, false, 1);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_DEL_SERVER_ADD_OR_SERVER_MOD.isTheCase(data));
}
@Test
public void testIsDelDelConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.DEL, true, 1);
Change serverChange = createChange(CHANGE_CREATION_TYPE.DEL, false, 1);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_DEL_SERVER_DEL.isTheCase(data));
}
@Test
public void testIsAddAddConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.ADD, true, 0);
Change serverChange = createChange(CHANGE_CREATION_TYPE.ADD, false, 0);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_ADD_SERVER_ADD_OR_SERVER_MOD.isTheCase(data));
}
@Test
public void testIsAddModConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.ADD, true, 0);
Change serverChange = createChange(CHANGE_CREATION_TYPE.MOD, false, 1);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_ADD_SERVER_ADD_OR_SERVER_MOD.isTheCase(data));
}
@Test
public void testIsAddDelConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.ADD, true, 0);
Change serverChange = createChange(CHANGE_CREATION_TYPE.DEL, false, 1);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_ADD_SERVER_DEL.isTheCase(data));
}
@Test
public void testIsModAddConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.MOD, true, 1);
Change serverChange = createChange(CHANGE_CREATION_TYPE.ADD, false, 0);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_MOD_SERVER_ADD_OR_SERVER_MOD.isTheCase(data));
}
@Test
public void testIsModModConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.MOD, true, 1);
Change serverChange = createChange(CHANGE_CREATION_TYPE.MOD, false, 1);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_MOD_SERVER_ADD_OR_SERVER_MOD.isTheCase(data));
}
@Test
public void testIsModDelConflict() {
Change clientChange = createChange(CHANGE_CREATION_TYPE.MOD, true, 1);
Change serverChange = createChange(CHANGE_CREATION_TYPE.DEL, false, 1);
ConflictHandlingData data = new ConflictHandlingData(clientChange, serverChange);
assertTrue(CLIENT_MOD_SERVER_DEL.isTheCase(data));
}
}
| true | true | private Change createChange(CHANGE_CREATION_TYPE creationType, boolean isClient, int revision) {
MDEntry entry = null;
Map<String, Object> rowData = newHashMap();
String testString = !isClient ? TEST_STRING : TEST_STRING + "_updateClient";
switch (creationType) {
case ADD:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
case MOD:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
case DEL:
entry = new MDEntry(1, isClient, 1, TEST_TABLE_NAME, null);
// no rowData, they were deleted
break;
default:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
}
Change change = new Change(entry, rowData);
return change;
}
| private Change createChange(CHANGE_CREATION_TYPE creationType, boolean isClient, int revision) {
MDEntry entry = null;
Map<String, Object> rowData = newHashMap();
String testString = !isClient ? TEST_STRING : TEST_STRING + "_updateClient";
switch (creationType) {
case ADD:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
case MOD:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
case DEL:
entry = new MDEntry(1, false, 1, TEST_TABLE_NAME, null);
// no rowData, they were deleted
break;
default:
entry = new MDEntry(1, true, revision, TEST_TABLE_NAME, TEST_MDV);
rowData.put(TEST_COLUMN1, 1);
rowData.put(TEST_COLUMN2, testString);
rowData.put(TEST_COLUMN3, true);
rowData.put(TEST_COLUMN4, new Date(System.currentTimeMillis()));
rowData.put(TEST_COLUMN5, 4.5);
break;
}
Change change = new Change(entry, rowData);
return change;
}
|
diff --git a/src/com/redhat/ceylon/ant/LazyHelper.java b/src/com/redhat/ceylon/ant/LazyHelper.java
index e2692d3d0..1b971d4e6 100644
--- a/src/com/redhat/ceylon/ant/LazyHelper.java
+++ b/src/com/redhat/ceylon/ant/LazyHelper.java
@@ -1,235 +1,234 @@
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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 distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package com.redhat.ceylon.ant;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.tools.ant.Project;
/**
* Encapsulates file modification time logic for figuring out whether a tool
* execution is actually required: Are any sources newer than the output.
* @author tom
*/
abstract class LazyHelper {
private final Lazy task;
public LazyHelper(Lazy task) {
this.task = task;
}
long newestSourceFile(List<File> srcs, File moduleDir) {
long newest = Long.MIN_VALUE;
for (File src : srcs) {
File srcModuleDir = new File(src, moduleDir.getPath());
newest = newestSourceFile(newest, srcModuleDir);
task.log("Newest file in " + srcModuleDir + " " + new Date(newest), Project.MSG_DEBUG);
}
return newest;
}
long newestSourceFile(long mtime, File file) {
if (file.isDirectory()) {
for (File child : file.listFiles()) {
mtime = Math.max(mtime, newestSourceFile(mtime, child));
}
} else {
long lastModified = file.lastModified();
task.log(file + " last modified " + new Date(lastModified), Project.MSG_DEBUG);
mtime = Math.max(mtime, lastModified);
}
return mtime;
}
long oldestOutputArtifact(long mtime, File file) {
if (file.isDirectory()) {
for (File child : file.listFiles()) {
mtime = Math.min(mtime, oldestOutputArtifact(mtime, child));
}
} else if (getArtifactFilter().accept(file)) {
if (file.getName().toLowerCase().endsWith(".car")) {
long oldest = oldestFileInCar(file);
task.log(file + " oldest entry " + new Date(oldest), Project.MSG_DEBUG);
mtime = Math.min(mtime, oldest);
} else {
long lastModified = file.lastModified();
task.log(file + " last modified " + new Date(lastModified), Project.MSG_DEBUG);
mtime = Math.min(mtime, lastModified);
}
}
return mtime;
}
private long oldestFileInCar(File file) {
long mtime = Long.MAX_VALUE;
JarFile jarFile = null;
try {
jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()){
JarEntry entry = entries.nextElement();
if (entry.getTime() < mtime) {
mtime = entry.getTime();
}
}
} catch (IOException ex) {
// Maybe something's wrong with the CAR so let's return MIN_VALUE
mtime = Long.MIN_VALUE;
} finally {
if (jarFile != null) {
try {
jarFile.close();
} catch (IOException e) {
// Ignore
}
}
}
return mtime;
}
/**
* Filters out all the modules which appear to not require
* compilation based on comparison of file modification times
* @return true if everything was filtered out
*/
protected boolean filterModules(Collection<Module> modules) {
if (task.getNoMtimeCheck() || isOutputRepositoryURL()) {
return false;
}
Iterator<Module> iterator = modules.iterator();
while (iterator.hasNext()) {
Module m = iterator.next();
Module module = findModule(m.getName());
if (module.getVersion() == null) {
task.log("Unable to determine version (and hence timestamp) of " + module, Project.MSG_VERBOSE);
continue;
}
long newest = newestSourceFile(task.getSrc(), module.toDir());
File outModuleDir = getArtifactDir(module);
long oldest = oldestOutputArtifact(Long.MAX_VALUE, outModuleDir);
task.log("Oldest file in " + outModuleDir + " " + new Date(oldest), Project.MSG_DEBUG);
if (newest != Long.MIN_VALUE
&& oldest != Long.MAX_VALUE
&& newest < oldest) {
task.log("No need to compile " + module + ", it's up to date");
iterator.remove();
}
}
return modules.size() == 0;
}
private boolean isOutputRepositoryURL() {
String out = task.getOut();
if(out == null || out.isEmpty())
return false;
try{
new URL(out);
return true;
}catch(MalformedURLException x){
return false;
}
}
/**
* Filters out all the source files which appear to not require
* compilation based on comparison of file modification times
* @return true if everything was filtered out
*/
protected boolean filterFiles(List<File> files) {
if (task.getNoMtimeCheck() || isOutputRepositoryURL()) {
return false;
}
- long newestFile = Long.MIN_VALUE;
Iterator<File> iter = files.iterator();
while (iter.hasNext()) {
File file = iter.next();
Module module = inferModule(file);
if (module == null) {
task.log("Unable to determine module of " + file, Project.MSG_VERBOSE);
continue;
}
if (module.getVersion() == null) {
task.log("Unable to determine version (and hence timestamp) of " + module.getName(), Project.MSG_VERBOSE);
continue;
}
File outModuleDir = getArtifactDir(module);
long oldest = oldestOutputArtifact(Long.MAX_VALUE, outModuleDir);
task.log("Oldest file in " + outModuleDir + " " + new Date(oldest), Project.MSG_DEBUG);
- newestFile = Math.max(newestFile, file.lastModified());
+ long newestFile = file.lastModified();
task.log("File " + file + " last modified " + new Date(newestFile), Project.MSG_DEBUG);
if (newestFile != Long.MIN_VALUE
&& oldest != Long.MAX_VALUE
&& newestFile < oldest) {
task.log("No need to compile " + file + ", it's up to date");
iter.remove();
}
}
return files.size() == 0;
}
protected abstract File getArtifactDir(Module module);
protected abstract FileFilter getArtifactFilter();
private Module findModule(String moduleName) {
for (File src : task.getSrc()) {
ModuleDescriptorReader mdr = new ModuleDescriptorReader(moduleName, src);
if (mdr.getModuleVersion() != null) {
return new Module(mdr.getModuleName(), mdr.getModuleVersion());
}
}
return null;
}
private Module inferModule(File file) {
if (file.exists()) {
for (File src : task.getSrc()) {
if (file.getAbsolutePath().startsWith(src.getAbsolutePath())) {
while (!file.equals(src)) {
File moduleDescriptor = file.isDirectory() ? new File(file, "module.ceylon") : file;
if (moduleDescriptor.exists()
&& moduleDescriptor.getName().equals("module.ceylon")) {
String moduleName = moduleDescriptor.getParentFile().getAbsolutePath().substring(src.getAbsolutePath().length()+1).replace(File.separator, ".");
ModuleDescriptorReader mdr = new ModuleDescriptorReader(moduleName, src);
return new Module(mdr.getModuleName(), mdr.getModuleVersion());
}
file = file.getParentFile();
}
}
}
}
return null;
}
}
| false | true | protected boolean filterFiles(List<File> files) {
if (task.getNoMtimeCheck() || isOutputRepositoryURL()) {
return false;
}
long newestFile = Long.MIN_VALUE;
Iterator<File> iter = files.iterator();
while (iter.hasNext()) {
File file = iter.next();
Module module = inferModule(file);
if (module == null) {
task.log("Unable to determine module of " + file, Project.MSG_VERBOSE);
continue;
}
if (module.getVersion() == null) {
task.log("Unable to determine version (and hence timestamp) of " + module.getName(), Project.MSG_VERBOSE);
continue;
}
File outModuleDir = getArtifactDir(module);
long oldest = oldestOutputArtifact(Long.MAX_VALUE, outModuleDir);
task.log("Oldest file in " + outModuleDir + " " + new Date(oldest), Project.MSG_DEBUG);
newestFile = Math.max(newestFile, file.lastModified());
task.log("File " + file + " last modified " + new Date(newestFile), Project.MSG_DEBUG);
if (newestFile != Long.MIN_VALUE
&& oldest != Long.MAX_VALUE
&& newestFile < oldest) {
task.log("No need to compile " + file + ", it's up to date");
iter.remove();
}
}
return files.size() == 0;
}
| protected boolean filterFiles(List<File> files) {
if (task.getNoMtimeCheck() || isOutputRepositoryURL()) {
return false;
}
Iterator<File> iter = files.iterator();
while (iter.hasNext()) {
File file = iter.next();
Module module = inferModule(file);
if (module == null) {
task.log("Unable to determine module of " + file, Project.MSG_VERBOSE);
continue;
}
if (module.getVersion() == null) {
task.log("Unable to determine version (and hence timestamp) of " + module.getName(), Project.MSG_VERBOSE);
continue;
}
File outModuleDir = getArtifactDir(module);
long oldest = oldestOutputArtifact(Long.MAX_VALUE, outModuleDir);
task.log("Oldest file in " + outModuleDir + " " + new Date(oldest), Project.MSG_DEBUG);
long newestFile = file.lastModified();
task.log("File " + file + " last modified " + new Date(newestFile), Project.MSG_DEBUG);
if (newestFile != Long.MIN_VALUE
&& oldest != Long.MAX_VALUE
&& newestFile < oldest) {
task.log("No need to compile " + file + ", it's up to date");
iter.remove();
}
}
return files.size() == 0;
}
|
diff --git a/sdk/src/main/java/net/siegmar/billomat4j/sdk/service/impl/BillomatConfiguration.java b/sdk/src/main/java/net/siegmar/billomat4j/sdk/service/impl/BillomatConfiguration.java
index 548d7c0..f5c85c2 100644
--- a/sdk/src/main/java/net/siegmar/billomat4j/sdk/service/impl/BillomatConfiguration.java
+++ b/sdk/src/main/java/net/siegmar/billomat4j/sdk/service/impl/BillomatConfiguration.java
@@ -1,144 +1,145 @@
/*
* Copyright 2012 Oliver Siegmar <[email protected]>
*
* This file is part of Billomat4J.
*
* Billomat4J 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.
*
* Billomat4J 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Billomat4J. If not, see <http://www.gnu.org/licenses/>.
*/
package net.siegmar.billomat4j.sdk.service.impl;
import net.siegmar.billomat4j.sdk.domain.types.PaymentType;
import net.siegmar.billomat4j.sdk.json.CustomBooleanDeserializer;
import net.siegmar.billomat4j.sdk.json.PaymentTypesDeserializer;
import net.siegmar.billomat4j.sdk.json.PaymentTypesSerializer;
import net.siegmar.billomat4j.sdk.json.Views;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class BillomatConfiguration {
private String billomatId;
private String apiKey;
private boolean secure = true;
private boolean ignoreUnknownProperties = true;
private RequestHelper requestHelper;
private ObjectReader objectReader;
private ObjectWriter objectWriter;
public String getBillomatId() {
return billomatId;
}
public void setBillomatId(final String billomatId) {
this.billomatId = billomatId;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(final String apiKey) {
this.apiKey = apiKey;
}
public boolean isSecure() {
return secure;
}
/**
* Sets secure mode (HTTPS instead of HTTP). This is enabled by default.
*
* @param secure
* {@code true} for HTTPS, {@code false} for HTTP
*/
public void setSecure(final boolean secure) {
this.secure = secure;
}
public boolean isIgnoreUnknownProperties() {
return ignoreUnknownProperties;
}
/**
* Defines if unmappable API response should be ignores. This is the default.
*
* @param ignoreUnknownProperties
* {@code true} for ignore unknown response attributes
*/
public void setIgnoreUnknownProperties(final boolean ignoreUnknownProperties) {
this.ignoreUnknownProperties = ignoreUnknownProperties;
}
RequestHelper getRequestHelper() {
return requestHelper;
}
ObjectReader getObjectReader() {
return objectReader;
}
ObjectWriter getObjectWriter() {
return objectWriter;
}
synchronized void init() {
if (requestHelper != null) {
return;
}
requestHelper = new RequestHelper(this);
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.registerModule(
new SimpleModule("CustomBooleanDeserializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addDeserializer(Boolean.class, new CustomBooleanDeserializer()));
objectMapper.registerModule(
new SimpleModule("PaymentTypesDeserializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addDeserializer(PaymentType[].class, new PaymentTypesDeserializer()));
objectMapper.registerModule(
new SimpleModule("PaymentTypesSerializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addSerializer(PaymentType[].class, new PaymentTypesSerializer()));
objectReader = objectMapper.reader()
.with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
+ .with(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
.with(DeserializationFeature.UNWRAP_ROOT_VALUE);
if (isIgnoreUnknownProperties()) {
objectReader = objectReader.without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
objectWriter = objectMapper.writer()
.withView(Views.Default.class)
.with(SerializationFeature.WRAP_ROOT_VALUE)
.without(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS)
.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}
| true | true | synchronized void init() {
if (requestHelper != null) {
return;
}
requestHelper = new RequestHelper(this);
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.registerModule(
new SimpleModule("CustomBooleanDeserializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addDeserializer(Boolean.class, new CustomBooleanDeserializer()));
objectMapper.registerModule(
new SimpleModule("PaymentTypesDeserializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addDeserializer(PaymentType[].class, new PaymentTypesDeserializer()));
objectMapper.registerModule(
new SimpleModule("PaymentTypesSerializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addSerializer(PaymentType[].class, new PaymentTypesSerializer()));
objectReader = objectMapper.reader()
.with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.with(DeserializationFeature.UNWRAP_ROOT_VALUE);
if (isIgnoreUnknownProperties()) {
objectReader = objectReader.without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
objectWriter = objectMapper.writer()
.withView(Views.Default.class)
.with(SerializationFeature.WRAP_ROOT_VALUE)
.without(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS)
.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
| synchronized void init() {
if (requestHelper != null) {
return;
}
requestHelper = new RequestHelper(this);
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.registerModule(
new SimpleModule("CustomBooleanDeserializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addDeserializer(Boolean.class, new CustomBooleanDeserializer()));
objectMapper.registerModule(
new SimpleModule("PaymentTypesDeserializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addDeserializer(PaymentType[].class, new PaymentTypesDeserializer()));
objectMapper.registerModule(
new SimpleModule("PaymentTypesSerializer",
new Version(1, 0, 0, null, "net.siegmar", "billomat4j"))
.addSerializer(PaymentType[].class, new PaymentTypesSerializer()));
objectReader = objectMapper.reader()
.with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
.with(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
.with(DeserializationFeature.UNWRAP_ROOT_VALUE);
if (isIgnoreUnknownProperties()) {
objectReader = objectReader.without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
objectWriter = objectMapper.writer()
.withView(Views.Default.class)
.with(SerializationFeature.WRAP_ROOT_VALUE)
.without(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS)
.without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
|
diff --git a/FairytellerSwing/src/test/java/com/fairyteller/swing/SampleBranchingWorkflowMain.java b/FairytellerSwing/src/test/java/com/fairyteller/swing/SampleBranchingWorkflowMain.java
index eaa9e6f..c6ed702 100644
--- a/FairytellerSwing/src/test/java/com/fairyteller/swing/SampleBranchingWorkflowMain.java
+++ b/FairytellerSwing/src/test/java/com/fairyteller/swing/SampleBranchingWorkflowMain.java
@@ -1,188 +1,188 @@
package com.fairyteller.swing;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import com.fairyteller.swing.concurrent.workflow.DefaultSwingUiHandler;
import com.fairyteller.utilities.concurrent.workflow.AbstractWorkflowRunnable;
import com.fairyteller.utilities.concurrent.workflow.DefaultBranchingWorkflowElement;
import com.fairyteller.utilities.concurrent.workflow.MainRunnable;
import com.fairyteller.utilities.concurrent.workflow.UIHandler;
import com.fairyteller.utilities.concurrent.workflow.UIRunnable;
import com.fairyteller.utilities.concurrent.workflow.Workflow;
import com.fairyteller.utilities.concurrent.workflow.WorkflowFactory;
import com.fairyteller.utilities.concurrent.workflow.WorkflowService;
public class SampleBranchingWorkflowMain {
public static void main(String[] args) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("counter", 0);
final Object[] arguments = new Object[1];
arguments[0] = context;
final JPanel myComponent = new JPanel(new FlowLayout());
FrameHelper.createMainFrame("test Workflow", myComponent, true);
UIRunnable firstStartUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
myComponent.add(new JLabel("First task started..."));
myComponent.revalidate();
}
};
MainRunnable firstMainRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
try {
int counter = ((Integer) ((Map<String, Object>)getArguments()[0]).get("counter"));
setProceed(true);
//Thread.sleep(1000);
setSuccess(counter % 2 == 0);
((Map<String, Object>)getArguments()[0]).put("counter", counter+1);
((Map<String, Object>)getArguments()[0]).put("date", Calendar.getInstance().getTime());
} catch (Exception e) {
setProceed(false);
}
}
};
UIRunnable firstFinishUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
int counter = ((Integer) ((Map<String, Object>)getArguments()[0]).get("counter"));
Date date = ((Date) ((Map<String, Object>)getArguments()[0]).get("date"));
if (counter % 2 == 0)
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": First task completed! ("
+ counter + ")"));
else
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": First task completed again! ("
+ counter + ")"));
myComponent.add(new JLabel(date.toString()+": current date in the arguments"));
myComponent.revalidate();
}
};
UIRunnable secondStartUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
Date date = ((Date) ((Map<String, Object>)getArguments()[0]).get("date"));
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": Second task started..."));
myComponent.add(new JLabel(date.toString()+": current date in the arguments"));
myComponent.revalidate();
}
};
MainRunnable secondMainRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
try {
setProceed(true);
setSuccess(true);
} catch (Exception e) {
setProceed(false);
}
}
};
UIRunnable secondFinishUIRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
if (isSuccess()) {
myComponent.add(new JLabel("Second task completed!"));
} else {
myComponent.add(new JLabel("Second task failed!"));
}
myComponent.revalidate();
}
};
UIRunnable timeoutUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
myComponent.add(new JLabel("Timeout :("));
myComponent.revalidate();
}
};
final UIHandler handler = new DefaultSwingUiHandler();
DefaultBranchingWorkflowElement[] welements = new DefaultBranchingWorkflowElement[] {
new DefaultBranchingWorkflowElement(0, "first", firstStartUiRunnable,
firstMainRunnable, firstFinishUiRunnable, 3000,
handler, timeoutUiRunnable),
new DefaultBranchingWorkflowElement(1, "second", secondStartUiRunnable,
secondMainRunnable, secondFinishUIRunnable, 3000,
handler, timeoutUiRunnable) };
welements[0].setNextStateYes(0);
welements[0].setNextStateNo(1);
welements[1].setStateFinal(true);
final Workflow workflow = WorkflowFactory
.createBranchingWorkflow(welements);
final WorkflowService service = new WorkflowService();
Action processWorkflowAction = new AbstractAction(
"Process the workflow") {
private static final long serialVersionUID = 3949757251884123525L;
@Override
public void actionPerformed(ActionEvent e) {
this.setEnabled(false);
new SwingWorker<String, Object>() {
@Override
protected String doInBackground() throws Exception {
service.start(workflow, arguments);
return "done";
}
@Override
protected void done() {
try {
get();
setEnabled(true);
} catch (InterruptedException e) {
JOptionPane.showMessageDialog(myComponent,
- "probl�me!");
+ "problème!");
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.execute();
}
};
myComponent.add(new JButton(processWorkflowAction));
myComponent.revalidate();
}
}
| true | true | public static void main(String[] args) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("counter", 0);
final Object[] arguments = new Object[1];
arguments[0] = context;
final JPanel myComponent = new JPanel(new FlowLayout());
FrameHelper.createMainFrame("test Workflow", myComponent, true);
UIRunnable firstStartUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
myComponent.add(new JLabel("First task started..."));
myComponent.revalidate();
}
};
MainRunnable firstMainRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
try {
int counter = ((Integer) ((Map<String, Object>)getArguments()[0]).get("counter"));
setProceed(true);
//Thread.sleep(1000);
setSuccess(counter % 2 == 0);
((Map<String, Object>)getArguments()[0]).put("counter", counter+1);
((Map<String, Object>)getArguments()[0]).put("date", Calendar.getInstance().getTime());
} catch (Exception e) {
setProceed(false);
}
}
};
UIRunnable firstFinishUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
int counter = ((Integer) ((Map<String, Object>)getArguments()[0]).get("counter"));
Date date = ((Date) ((Map<String, Object>)getArguments()[0]).get("date"));
if (counter % 2 == 0)
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": First task completed! ("
+ counter + ")"));
else
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": First task completed again! ("
+ counter + ")"));
myComponent.add(new JLabel(date.toString()+": current date in the arguments"));
myComponent.revalidate();
}
};
UIRunnable secondStartUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
Date date = ((Date) ((Map<String, Object>)getArguments()[0]).get("date"));
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": Second task started..."));
myComponent.add(new JLabel(date.toString()+": current date in the arguments"));
myComponent.revalidate();
}
};
MainRunnable secondMainRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
try {
setProceed(true);
setSuccess(true);
} catch (Exception e) {
setProceed(false);
}
}
};
UIRunnable secondFinishUIRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
if (isSuccess()) {
myComponent.add(new JLabel("Second task completed!"));
} else {
myComponent.add(new JLabel("Second task failed!"));
}
myComponent.revalidate();
}
};
UIRunnable timeoutUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
myComponent.add(new JLabel("Timeout :("));
myComponent.revalidate();
}
};
final UIHandler handler = new DefaultSwingUiHandler();
DefaultBranchingWorkflowElement[] welements = new DefaultBranchingWorkflowElement[] {
new DefaultBranchingWorkflowElement(0, "first", firstStartUiRunnable,
firstMainRunnable, firstFinishUiRunnable, 3000,
handler, timeoutUiRunnable),
new DefaultBranchingWorkflowElement(1, "second", secondStartUiRunnable,
secondMainRunnable, secondFinishUIRunnable, 3000,
handler, timeoutUiRunnable) };
welements[0].setNextStateYes(0);
welements[0].setNextStateNo(1);
welements[1].setStateFinal(true);
final Workflow workflow = WorkflowFactory
.createBranchingWorkflow(welements);
final WorkflowService service = new WorkflowService();
Action processWorkflowAction = new AbstractAction(
"Process the workflow") {
private static final long serialVersionUID = 3949757251884123525L;
@Override
public void actionPerformed(ActionEvent e) {
this.setEnabled(false);
new SwingWorker<String, Object>() {
@Override
protected String doInBackground() throws Exception {
service.start(workflow, arguments);
return "done";
}
@Override
protected void done() {
try {
get();
setEnabled(true);
} catch (InterruptedException e) {
JOptionPane.showMessageDialog(myComponent,
"probl�me!");
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.execute();
}
};
myComponent.add(new JButton(processWorkflowAction));
myComponent.revalidate();
}
| public static void main(String[] args) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("counter", 0);
final Object[] arguments = new Object[1];
arguments[0] = context;
final JPanel myComponent = new JPanel(new FlowLayout());
FrameHelper.createMainFrame("test Workflow", myComponent, true);
UIRunnable firstStartUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
myComponent.add(new JLabel("First task started..."));
myComponent.revalidate();
}
};
MainRunnable firstMainRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
try {
int counter = ((Integer) ((Map<String, Object>)getArguments()[0]).get("counter"));
setProceed(true);
//Thread.sleep(1000);
setSuccess(counter % 2 == 0);
((Map<String, Object>)getArguments()[0]).put("counter", counter+1);
((Map<String, Object>)getArguments()[0]).put("date", Calendar.getInstance().getTime());
} catch (Exception e) {
setProceed(false);
}
}
};
UIRunnable firstFinishUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
int counter = ((Integer) ((Map<String, Object>)getArguments()[0]).get("counter"));
Date date = ((Date) ((Map<String, Object>)getArguments()[0]).get("date"));
if (counter % 2 == 0)
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": First task completed! ("
+ counter + ")"));
else
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": First task completed again! ("
+ counter + ")"));
myComponent.add(new JLabel(date.toString()+": current date in the arguments"));
myComponent.revalidate();
}
};
UIRunnable secondStartUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
Date date = ((Date) ((Map<String, Object>)getArguments()[0]).get("date"));
myComponent.add(new JLabel(Calendar.getInstance().getTime().toString()+": Second task started..."));
myComponent.add(new JLabel(date.toString()+": current date in the arguments"));
myComponent.revalidate();
}
};
MainRunnable secondMainRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
try {
setProceed(true);
setSuccess(true);
} catch (Exception e) {
setProceed(false);
}
}
};
UIRunnable secondFinishUIRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
if (isSuccess()) {
myComponent.add(new JLabel("Second task completed!"));
} else {
myComponent.add(new JLabel("Second task failed!"));
}
myComponent.revalidate();
}
};
UIRunnable timeoutUiRunnable = new AbstractWorkflowRunnable() {
@Override
public void run() {
myComponent.add(new JLabel("Timeout :("));
myComponent.revalidate();
}
};
final UIHandler handler = new DefaultSwingUiHandler();
DefaultBranchingWorkflowElement[] welements = new DefaultBranchingWorkflowElement[] {
new DefaultBranchingWorkflowElement(0, "first", firstStartUiRunnable,
firstMainRunnable, firstFinishUiRunnable, 3000,
handler, timeoutUiRunnable),
new DefaultBranchingWorkflowElement(1, "second", secondStartUiRunnable,
secondMainRunnable, secondFinishUIRunnable, 3000,
handler, timeoutUiRunnable) };
welements[0].setNextStateYes(0);
welements[0].setNextStateNo(1);
welements[1].setStateFinal(true);
final Workflow workflow = WorkflowFactory
.createBranchingWorkflow(welements);
final WorkflowService service = new WorkflowService();
Action processWorkflowAction = new AbstractAction(
"Process the workflow") {
private static final long serialVersionUID = 3949757251884123525L;
@Override
public void actionPerformed(ActionEvent e) {
this.setEnabled(false);
new SwingWorker<String, Object>() {
@Override
protected String doInBackground() throws Exception {
service.start(workflow, arguments);
return "done";
}
@Override
protected void done() {
try {
get();
setEnabled(true);
} catch (InterruptedException e) {
JOptionPane.showMessageDialog(myComponent,
"problème!");
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.execute();
}
};
myComponent.add(new JButton(processWorkflowAction));
myComponent.revalidate();
}
|
diff --git a/src/org/xbmc/android/remote/XbmcBroadcastReceiver.java b/src/org/xbmc/android/remote/XbmcBroadcastReceiver.java
index 86a7bd9..e718362 100644
--- a/src/org/xbmc/android/remote/XbmcBroadcastReceiver.java
+++ b/src/org/xbmc/android/remote/XbmcBroadcastReceiver.java
@@ -1,116 +1,123 @@
package org.xbmc.android.remote;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.xbmc.android.util.ConnectionManager;
import org.xbmc.android.util.SmsMmsMessage;
import org.xbmc.android.util.SmsPopupUtils;
import org.xbmc.eventclient.ButtonCodes;
import org.xbmc.eventclient.EventClient;
import org.xbmc.eventclient.Packet;
import org.xbmc.httpapi.HttpClient;
import org.xbmc.httpapi.client.ControlClient.ICurrentlyPlaying;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
public class XbmcBroadcastReceiver extends BroadcastReceiver {
/**
* The Action fired by the Android-System when a SMS was received.
*/
private static final String SMS_RECVEICED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
private static final int PLAY_STATE_NONE = -1;
private static final int PLAY_STATE_PAUSED = 0;
private static int PLAY_STATE = PLAY_STATE_NONE;
public XbmcBroadcastReceiver() {
// TODO Auto-generated constructor stub
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
EventClient client = ConnectionManager.getEventClient();
HttpClient http = ConnectionManager.getHttpClient();
SharedPreferences prefs = context.getSharedPreferences("XBMCRemotePrefsFile", Context.MODE_WORLD_WRITEABLE);
// currently no new connection to the event server is opened
if(client != null) {
try {
if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)
&& prefs.getBoolean("settings_show_call", true)) {
String extra = intent.getStringExtra(android.telephony.TelephonyManager.EXTRA_STATE);
if(extra.equals(android.telephony.TelephonyManager.EXTRA_STATE_RINGING)) {
// someone is calling, we get all infos and pause the playback
- String number = intent.getStringExtra(android.telephony.TelephonyManager.EXTRA_INCOMING_NUMBER);
- String id = SmsPopupUtils.getPersonIdFromPhoneNumber(context, number);
- String callername = SmsPopupUtils.getPersonName(context, id, number);
+ String number = null;
+ String id = null;
+ String callername = null;
+ number = intent.getStringExtra(android.telephony.TelephonyManager.EXTRA_INCOMING_NUMBER);
+ if(number != null){
+ id = SmsPopupUtils.getPersonIdFromPhoneNumber(context, number);
+ callername = SmsPopupUtils.getPersonName(context, id, number);
+ }
+ else
+ callername = "Unknown Number";
// Bitmap isn't supported by the event server, so we have to compress it
Bitmap pic;
if(id != null)
pic = Contacts.People.loadContactPhoto(context,
Uri.withAppendedPath(Contacts.People.CONTENT_URI, id), R.drawable.icon, null);
else
pic = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
ByteArrayOutputStream os = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.PNG, 0, os);
// if xbmc is playing something, we pause it. without the check paused playback would resume
final ICurrentlyPlaying cp = http.control.getCurrentlyPlaying();
if (http != null && http.isConnected() && http.info != null && cp != null ){
if (cp.isPlaying()){
client.sendButton("R1", ButtonCodes.REMOTE_PAUSE, true, true, true, (short)0, (byte)0);
client.sendButton("R1", ButtonCodes.REMOTE_PAUSE, false, false, true, (short)0, (byte)0);
PLAY_STATE = PLAY_STATE_PAUSED;
}
}
client.sendNotification(callername,"calling", Packet.ICON_PNG, os.toByteArray());
}
if(extra.equals(android.telephony.TelephonyManager.EXTRA_STATE_IDLE))
{
// phone state changed to idle, so if we paused the playback before, we resume it now
if(PLAY_STATE == PLAY_STATE_PAUSED) {
client.sendButton("R1", ButtonCodes.REMOTE_PLAY, true, true, true, (short)0, (byte)0);
client.sendButton("R1", ButtonCodes.REMOTE_PLAY, false, false, true, (short)0, (byte)0);
}
PLAY_STATE = PLAY_STATE_NONE;
}
}else if(action.equals(SMS_RECVEICED_ACTION) && prefs.getBoolean("setting_show_sms", true)) {
// sms received. extract msg, contact and pic and show it on the tv
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMmsMessage msg = SmsMmsMessage.getSmsfromPDUs(context, (Object[])bundle.get("pdus"));
Bitmap pic = msg.getContactPhoto();
if(pic != null) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.PNG, 0, os);
client.sendNotification("SMS Received from "+msg.getContactName(), msg.getMessageBody(),
Packet.ICON_PNG, os.toByteArray());
} else {
client.sendNotification("SMS Received from "+msg.getContactName(), msg.getMessageBody());
}
}
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
EventClient client = ConnectionManager.getEventClient();
HttpClient http = ConnectionManager.getHttpClient();
SharedPreferences prefs = context.getSharedPreferences("XBMCRemotePrefsFile", Context.MODE_WORLD_WRITEABLE);
// currently no new connection to the event server is opened
if(client != null) {
try {
if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)
&& prefs.getBoolean("settings_show_call", true)) {
String extra = intent.getStringExtra(android.telephony.TelephonyManager.EXTRA_STATE);
if(extra.equals(android.telephony.TelephonyManager.EXTRA_STATE_RINGING)) {
// someone is calling, we get all infos and pause the playback
String number = intent.getStringExtra(android.telephony.TelephonyManager.EXTRA_INCOMING_NUMBER);
String id = SmsPopupUtils.getPersonIdFromPhoneNumber(context, number);
String callername = SmsPopupUtils.getPersonName(context, id, number);
// Bitmap isn't supported by the event server, so we have to compress it
Bitmap pic;
if(id != null)
pic = Contacts.People.loadContactPhoto(context,
Uri.withAppendedPath(Contacts.People.CONTENT_URI, id), R.drawable.icon, null);
else
pic = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
ByteArrayOutputStream os = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.PNG, 0, os);
// if xbmc is playing something, we pause it. without the check paused playback would resume
final ICurrentlyPlaying cp = http.control.getCurrentlyPlaying();
if (http != null && http.isConnected() && http.info != null && cp != null ){
if (cp.isPlaying()){
client.sendButton("R1", ButtonCodes.REMOTE_PAUSE, true, true, true, (short)0, (byte)0);
client.sendButton("R1", ButtonCodes.REMOTE_PAUSE, false, false, true, (short)0, (byte)0);
PLAY_STATE = PLAY_STATE_PAUSED;
}
}
client.sendNotification(callername,"calling", Packet.ICON_PNG, os.toByteArray());
}
if(extra.equals(android.telephony.TelephonyManager.EXTRA_STATE_IDLE))
{
// phone state changed to idle, so if we paused the playback before, we resume it now
if(PLAY_STATE == PLAY_STATE_PAUSED) {
client.sendButton("R1", ButtonCodes.REMOTE_PLAY, true, true, true, (short)0, (byte)0);
client.sendButton("R1", ButtonCodes.REMOTE_PLAY, false, false, true, (short)0, (byte)0);
}
PLAY_STATE = PLAY_STATE_NONE;
}
}else if(action.equals(SMS_RECVEICED_ACTION) && prefs.getBoolean("setting_show_sms", true)) {
// sms received. extract msg, contact and pic and show it on the tv
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMmsMessage msg = SmsMmsMessage.getSmsfromPDUs(context, (Object[])bundle.get("pdus"));
Bitmap pic = msg.getContactPhoto();
if(pic != null) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.PNG, 0, os);
client.sendNotification("SMS Received from "+msg.getContactName(), msg.getMessageBody(),
Packet.ICON_PNG, os.toByteArray());
} else {
client.sendNotification("SMS Received from "+msg.getContactName(), msg.getMessageBody());
}
}
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
EventClient client = ConnectionManager.getEventClient();
HttpClient http = ConnectionManager.getHttpClient();
SharedPreferences prefs = context.getSharedPreferences("XBMCRemotePrefsFile", Context.MODE_WORLD_WRITEABLE);
// currently no new connection to the event server is opened
if(client != null) {
try {
if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)
&& prefs.getBoolean("settings_show_call", true)) {
String extra = intent.getStringExtra(android.telephony.TelephonyManager.EXTRA_STATE);
if(extra.equals(android.telephony.TelephonyManager.EXTRA_STATE_RINGING)) {
// someone is calling, we get all infos and pause the playback
String number = null;
String id = null;
String callername = null;
number = intent.getStringExtra(android.telephony.TelephonyManager.EXTRA_INCOMING_NUMBER);
if(number != null){
id = SmsPopupUtils.getPersonIdFromPhoneNumber(context, number);
callername = SmsPopupUtils.getPersonName(context, id, number);
}
else
callername = "Unknown Number";
// Bitmap isn't supported by the event server, so we have to compress it
Bitmap pic;
if(id != null)
pic = Contacts.People.loadContactPhoto(context,
Uri.withAppendedPath(Contacts.People.CONTENT_URI, id), R.drawable.icon, null);
else
pic = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
ByteArrayOutputStream os = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.PNG, 0, os);
// if xbmc is playing something, we pause it. without the check paused playback would resume
final ICurrentlyPlaying cp = http.control.getCurrentlyPlaying();
if (http != null && http.isConnected() && http.info != null && cp != null ){
if (cp.isPlaying()){
client.sendButton("R1", ButtonCodes.REMOTE_PAUSE, true, true, true, (short)0, (byte)0);
client.sendButton("R1", ButtonCodes.REMOTE_PAUSE, false, false, true, (short)0, (byte)0);
PLAY_STATE = PLAY_STATE_PAUSED;
}
}
client.sendNotification(callername,"calling", Packet.ICON_PNG, os.toByteArray());
}
if(extra.equals(android.telephony.TelephonyManager.EXTRA_STATE_IDLE))
{
// phone state changed to idle, so if we paused the playback before, we resume it now
if(PLAY_STATE == PLAY_STATE_PAUSED) {
client.sendButton("R1", ButtonCodes.REMOTE_PLAY, true, true, true, (short)0, (byte)0);
client.sendButton("R1", ButtonCodes.REMOTE_PLAY, false, false, true, (short)0, (byte)0);
}
PLAY_STATE = PLAY_STATE_NONE;
}
}else if(action.equals(SMS_RECVEICED_ACTION) && prefs.getBoolean("setting_show_sms", true)) {
// sms received. extract msg, contact and pic and show it on the tv
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMmsMessage msg = SmsMmsMessage.getSmsfromPDUs(context, (Object[])bundle.get("pdus"));
Bitmap pic = msg.getContactPhoto();
if(pic != null) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.PNG, 0, os);
client.sendNotification("SMS Received from "+msg.getContactName(), msg.getMessageBody(),
Packet.ICON_PNG, os.toByteArray());
} else {
client.sendNotification("SMS Received from "+msg.getContactName(), msg.getMessageBody());
}
}
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
diff --git a/test/edu/harvard/cs262/grading/test/TestGradeCompilerService.java b/test/edu/harvard/cs262/grading/test/TestGradeCompilerService.java
index 2c423a5..e54fb5e 100644
--- a/test/edu/harvard/cs262/grading/test/TestGradeCompilerService.java
+++ b/test/edu/harvard/cs262/grading/test/TestGradeCompilerService.java
@@ -1,137 +1,148 @@
package edu.harvard.cs262.grading.test;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.harvard.cs262.grading.server.services.Assignment;
import edu.harvard.cs262.grading.server.services.AssignmentImpl;
import edu.harvard.cs262.grading.server.services.Grade;
import edu.harvard.cs262.grading.server.services.GradeCompilerService;
import edu.harvard.cs262.grading.server.services.GradeCompilerServiceServer;
import edu.harvard.cs262.grading.server.services.GradeStorageService;
import edu.harvard.cs262.grading.server.services.InvalidGraderForStudentException;
import edu.harvard.cs262.grading.server.services.MongoGradeStorageService;
import edu.harvard.cs262.grading.server.services.MongoSubmissionStorageService;
import edu.harvard.cs262.grading.server.services.ScoreImpl;
import edu.harvard.cs262.grading.server.services.SharderServiceServer;
import edu.harvard.cs262.grading.server.services.Student;
import edu.harvard.cs262.grading.server.services.StudentImpl;
import edu.harvard.cs262.grading.server.services.Submission;
import edu.harvard.cs262.grading.server.services.SubmissionReceiverService;
import edu.harvard.cs262.grading.server.services.SubmissionReceiverServiceServer;
import edu.harvard.cs262.grading.server.services.SubmissionStorageService;
import static org.junit.Assert.*;
public class TestGradeCompilerService {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testGradeStorage() throws Exception {
// instantiate the storage services locally
GradeStorageService gradeStorage = new MongoGradeStorageService();
gradeStorage.init();
SubmissionStorageService submissionStorage = new MongoSubmissionStorageService();
submissionStorage.init();
// create students
Student[] students =
{new StudentImpl(100,"[email protected]","Kenny","Yu"),
new StudentImpl(101,"[email protected]","Jim","Danz"),
new StudentImpl(102,"[email protected]","Willie","Yao"),
new StudentImpl(103,"[email protected]","Tony","Ho"),
new StudentImpl(104,"[email protected]","Stefan","Muller")};
// create assignments
Assignment assignment = new AssignmentImpl(66,"hw");
// instantiate a sandboxed submission receiver service
SubmissionReceiverService receiver = new SubmissionReceiverServiceServer(submissionStorage);
// Kenny and Jim submit
Submission submission1 = receiver.submit(students[0], assignment, (new String("cheese")).getBytes());
Submission submission2 = receiver.submit(students[1], assignment, (new String("cheddar")).getBytes());
// instantiate a sandboxed sharder service
SharderServiceServer sharder = new SharderServiceServer();
sharder.init(true);
+ // generate a sharding
Map<Student, Set<Student>> gradermap = new HashMap<Student, Set<Student>>();
- HashSet<Student> willieGradees = new HashSet<Student>();
+ Set<Student> kennyGradees = new HashSet<Student>();
+ kennyGradees.add(students[1]);
+ Set<Student> willieGradees = new HashSet<Student>();
willieGradees.add(students[0]);
willieGradees.add(students[1]);
+ gradermap.put(students[2], willieGradees);
+ Set<Student> tonyGradees = new HashSet<Student>();
+ tonyGradees.add(students[0]);
+ tonyGradees.add(students[1]);
+ gradermap.put(students[3], tonyGradees);
+ Set<Student> stefanGradees = new HashSet<Student>();
+ stefanGradees.add(students[0]);
+ gradermap.put(students[4], stefanGradees);
sharder.putShard(assignment, gradermap);
// instantiate a sandboxed grade compiler service
GradeCompilerService service = new GradeCompilerServiceServer(gradeStorage, submissionStorage, sharder);
// Willie and Tony grade both Kenny and Jim
// Stefan grades Kenny
// Kenny grades Jim
Grade grade1 = service.storeGrade(students[2], submission1, new ScoreImpl(50,100), "good");
Grade grade2 = service.storeGrade(students[2], submission2, new ScoreImpl(60,100), "better");
Grade grade3 = service.storeGrade(students[3], submission1, new ScoreImpl(70,100), "okay");
Grade grade4 = service.storeGrade(students[3], submission2, new ScoreImpl(80,100), "mediocre");
Grade grade5 = service.storeGrade(students[4], submission1, new ScoreImpl(90,100), "awesome");
Grade grade6 = service.storeGrade(students[0], submission2, new ScoreImpl(100,100), "perfect");
try {
service.storeGrade(students[0], submission1, new ScoreImpl(100,100), "impossible");
fail("student should not be allowed to grade him/herself");
} catch (InvalidGraderForStudentException e) {
assertTrue(true);
}
// assert the graders are correctly mapped
Set<Student> kennyGraders = service.getGraders(submission1);
assertEquals(3,kennyGraders.size());
assertTrue(kennyGraders.contains(students[2]));
assertTrue(kennyGraders.contains(students[3]));
assertTrue(kennyGraders.contains(students[4]));
Set<Student> jimGraders = service.getGraders(submission2);
assertEquals(3,jimGraders.size());
assertTrue(jimGraders.contains(students[0]));
assertTrue(jimGraders.contains(students[2]));
assertTrue(jimGraders.contains(students[3]));
// assert the grades were successfully submitted
Map<Submission, List<Grade>> grades = service.getCompiledGrades(assignment);
List<Grade> kennyGrades = grades.get(submission1);
assertEquals(3,kennyGrades.size());
assertTrue(kennyGrades.contains(grade1));
assertTrue(kennyGrades.contains(grade3));
assertTrue(kennyGrades.contains(grade5));
List<Grade> jimGrades = grades.get(submission2);
assertEquals(3,jimGrades.size());
assertTrue(jimGrades.contains(grade2));
assertTrue(jimGrades.contains(grade4));
assertTrue(jimGrades.contains(grade6));
}
}
| false | true | public void testGradeStorage() throws Exception {
// instantiate the storage services locally
GradeStorageService gradeStorage = new MongoGradeStorageService();
gradeStorage.init();
SubmissionStorageService submissionStorage = new MongoSubmissionStorageService();
submissionStorage.init();
// create students
Student[] students =
{new StudentImpl(100,"[email protected]","Kenny","Yu"),
new StudentImpl(101,"[email protected]","Jim","Danz"),
new StudentImpl(102,"[email protected]","Willie","Yao"),
new StudentImpl(103,"[email protected]","Tony","Ho"),
new StudentImpl(104,"[email protected]","Stefan","Muller")};
// create assignments
Assignment assignment = new AssignmentImpl(66,"hw");
// instantiate a sandboxed submission receiver service
SubmissionReceiverService receiver = new SubmissionReceiverServiceServer(submissionStorage);
// Kenny and Jim submit
Submission submission1 = receiver.submit(students[0], assignment, (new String("cheese")).getBytes());
Submission submission2 = receiver.submit(students[1], assignment, (new String("cheddar")).getBytes());
// instantiate a sandboxed sharder service
SharderServiceServer sharder = new SharderServiceServer();
sharder.init(true);
Map<Student, Set<Student>> gradermap = new HashMap<Student, Set<Student>>();
HashSet<Student> willieGradees = new HashSet<Student>();
willieGradees.add(students[0]);
willieGradees.add(students[1]);
sharder.putShard(assignment, gradermap);
// instantiate a sandboxed grade compiler service
GradeCompilerService service = new GradeCompilerServiceServer(gradeStorage, submissionStorage, sharder);
// Willie and Tony grade both Kenny and Jim
// Stefan grades Kenny
// Kenny grades Jim
Grade grade1 = service.storeGrade(students[2], submission1, new ScoreImpl(50,100), "good");
Grade grade2 = service.storeGrade(students[2], submission2, new ScoreImpl(60,100), "better");
Grade grade3 = service.storeGrade(students[3], submission1, new ScoreImpl(70,100), "okay");
Grade grade4 = service.storeGrade(students[3], submission2, new ScoreImpl(80,100), "mediocre");
Grade grade5 = service.storeGrade(students[4], submission1, new ScoreImpl(90,100), "awesome");
Grade grade6 = service.storeGrade(students[0], submission2, new ScoreImpl(100,100), "perfect");
try {
service.storeGrade(students[0], submission1, new ScoreImpl(100,100), "impossible");
fail("student should not be allowed to grade him/herself");
} catch (InvalidGraderForStudentException e) {
assertTrue(true);
}
// assert the graders are correctly mapped
Set<Student> kennyGraders = service.getGraders(submission1);
assertEquals(3,kennyGraders.size());
assertTrue(kennyGraders.contains(students[2]));
assertTrue(kennyGraders.contains(students[3]));
assertTrue(kennyGraders.contains(students[4]));
Set<Student> jimGraders = service.getGraders(submission2);
assertEquals(3,jimGraders.size());
assertTrue(jimGraders.contains(students[0]));
assertTrue(jimGraders.contains(students[2]));
assertTrue(jimGraders.contains(students[3]));
// assert the grades were successfully submitted
Map<Submission, List<Grade>> grades = service.getCompiledGrades(assignment);
List<Grade> kennyGrades = grades.get(submission1);
assertEquals(3,kennyGrades.size());
assertTrue(kennyGrades.contains(grade1));
assertTrue(kennyGrades.contains(grade3));
assertTrue(kennyGrades.contains(grade5));
List<Grade> jimGrades = grades.get(submission2);
assertEquals(3,jimGrades.size());
assertTrue(jimGrades.contains(grade2));
assertTrue(jimGrades.contains(grade4));
assertTrue(jimGrades.contains(grade6));
}
| public void testGradeStorage() throws Exception {
// instantiate the storage services locally
GradeStorageService gradeStorage = new MongoGradeStorageService();
gradeStorage.init();
SubmissionStorageService submissionStorage = new MongoSubmissionStorageService();
submissionStorage.init();
// create students
Student[] students =
{new StudentImpl(100,"[email protected]","Kenny","Yu"),
new StudentImpl(101,"[email protected]","Jim","Danz"),
new StudentImpl(102,"[email protected]","Willie","Yao"),
new StudentImpl(103,"[email protected]","Tony","Ho"),
new StudentImpl(104,"[email protected]","Stefan","Muller")};
// create assignments
Assignment assignment = new AssignmentImpl(66,"hw");
// instantiate a sandboxed submission receiver service
SubmissionReceiverService receiver = new SubmissionReceiverServiceServer(submissionStorage);
// Kenny and Jim submit
Submission submission1 = receiver.submit(students[0], assignment, (new String("cheese")).getBytes());
Submission submission2 = receiver.submit(students[1], assignment, (new String("cheddar")).getBytes());
// instantiate a sandboxed sharder service
SharderServiceServer sharder = new SharderServiceServer();
sharder.init(true);
// generate a sharding
Map<Student, Set<Student>> gradermap = new HashMap<Student, Set<Student>>();
Set<Student> kennyGradees = new HashSet<Student>();
kennyGradees.add(students[1]);
Set<Student> willieGradees = new HashSet<Student>();
willieGradees.add(students[0]);
willieGradees.add(students[1]);
gradermap.put(students[2], willieGradees);
Set<Student> tonyGradees = new HashSet<Student>();
tonyGradees.add(students[0]);
tonyGradees.add(students[1]);
gradermap.put(students[3], tonyGradees);
Set<Student> stefanGradees = new HashSet<Student>();
stefanGradees.add(students[0]);
gradermap.put(students[4], stefanGradees);
sharder.putShard(assignment, gradermap);
// instantiate a sandboxed grade compiler service
GradeCompilerService service = new GradeCompilerServiceServer(gradeStorage, submissionStorage, sharder);
// Willie and Tony grade both Kenny and Jim
// Stefan grades Kenny
// Kenny grades Jim
Grade grade1 = service.storeGrade(students[2], submission1, new ScoreImpl(50,100), "good");
Grade grade2 = service.storeGrade(students[2], submission2, new ScoreImpl(60,100), "better");
Grade grade3 = service.storeGrade(students[3], submission1, new ScoreImpl(70,100), "okay");
Grade grade4 = service.storeGrade(students[3], submission2, new ScoreImpl(80,100), "mediocre");
Grade grade5 = service.storeGrade(students[4], submission1, new ScoreImpl(90,100), "awesome");
Grade grade6 = service.storeGrade(students[0], submission2, new ScoreImpl(100,100), "perfect");
try {
service.storeGrade(students[0], submission1, new ScoreImpl(100,100), "impossible");
fail("student should not be allowed to grade him/herself");
} catch (InvalidGraderForStudentException e) {
assertTrue(true);
}
// assert the graders are correctly mapped
Set<Student> kennyGraders = service.getGraders(submission1);
assertEquals(3,kennyGraders.size());
assertTrue(kennyGraders.contains(students[2]));
assertTrue(kennyGraders.contains(students[3]));
assertTrue(kennyGraders.contains(students[4]));
Set<Student> jimGraders = service.getGraders(submission2);
assertEquals(3,jimGraders.size());
assertTrue(jimGraders.contains(students[0]));
assertTrue(jimGraders.contains(students[2]));
assertTrue(jimGraders.contains(students[3]));
// assert the grades were successfully submitted
Map<Submission, List<Grade>> grades = service.getCompiledGrades(assignment);
List<Grade> kennyGrades = grades.get(submission1);
assertEquals(3,kennyGrades.size());
assertTrue(kennyGrades.contains(grade1));
assertTrue(kennyGrades.contains(grade3));
assertTrue(kennyGrades.contains(grade5));
List<Grade> jimGrades = grades.get(submission2);
assertEquals(3,jimGrades.size());
assertTrue(jimGrades.contains(grade2));
assertTrue(jimGrades.contains(grade4));
assertTrue(jimGrades.contains(grade6));
}
|
diff --git a/src/java/fedora/server/storage/replication/DefaultDOReplicator.java b/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
index b459e7375..4ace81fc2 100755
--- a/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
+++ b/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
@@ -1,2158 +1,2162 @@
package fedora.server.storage.replication;
import java.util.*;
import java.sql.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;
import fedora.server.errors.*;
import fedora.server.storage.*;
import fedora.server.storage.types.*;
import fedora.server.utilities.SQLUtility;
import fedora.server.Module;
import fedora.server.Server;
import fedora.server.storage.ConnectionPoolManager;
import fedora.server.errors.ModuleInitializationException;
/**
*
* <p><b>Title:</b> DefaultDOReplicator.java</p>
* <p><b>Description:</b> A Module that replicates digital object information
* to the dissemination database.</p>
*
* <p>Converts data read from the object reader interfaces and creates or
* updates the corresponding database rows in the dissemination database.</p>
*
* -----------------------------------------------------------------------------
*
* <p><b>License and Copyright: </b>The contents of this file are subject to the
* Mozilla Public License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p>
*
* <p>Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.</p>
*
* <p>The entire file consists of original code. Copyright © 2002, 2003 by The
* Rector and Visitors of the University of Virginia and Cornell University.
* All rights reserved.</p>
*
* -----------------------------------------------------------------------------
*
* @author Paul Charlton, [email protected]
* @version $Id$
*/
public class DefaultDOReplicator
extends Module
implements DOReplicator {
private ConnectionPool m_pool;
private RowInsertion m_ri;
private DBIDLookup m_dl;
// sdp - local.fedora.server conversion
private Pattern hostPattern = null;
private Pattern hostPortPattern = null;
private Pattern serializedLocalURLPattern = null;
/**
* Server instance to work with in this module.
*/
private Server server;
/** Port number on which the Fedora server is running; determined from
* fedora.fcfg config file.
*/
private static String fedoraServerPort = null;
/** Hostname of the Fedora server determined from
* fedora.fcfg config file, or (fallback) by hostIP.getHostName()
*/
private static String fedoraServerHost = null;
/** The IP address of the local host; determined dynamically. */
private static InetAddress hostIP = null;
public DefaultDOReplicator(Map moduleParameters, Server server, String role)
throws ModuleInitializationException {
super(moduleParameters, server, role);
}
public void initModule() {
}
public void postInitModule()
throws ModuleInitializationException {
try {
ConnectionPoolManager mgr=(ConnectionPoolManager)
getServer().getModule(
"fedora.server.storage.ConnectionPoolManager");
m_pool=mgr.getPool();
// sdp: insert new
hostIP = null;
fedoraServerPort = getServer().getParameter("fedoraServerPort");
getServer().logFinest("fedoraServerPort: " + fedoraServerPort);
hostIP = InetAddress.getLocalHost();
fedoraServerHost = getServer().getParameter("fedoraServerHost");
if (fedoraServerHost==null || fedoraServerHost.equals("")) {
fedoraServerHost=hostIP.getHostName();
}
hostPattern = Pattern.compile("http://"+fedoraServerHost+"/");
hostPortPattern = Pattern.compile("http://"+fedoraServerHost+":"+fedoraServerPort+"/");
serializedLocalURLPattern = Pattern.compile("http://local.fedora.server/");
//System.out.println("Replicator: hostPattern is " + hostPattern.pattern());
//System.out.println("Replicator: hostPortPattern is " + hostPortPattern.pattern());
//
} catch (ServerException se) {
throw new ModuleInitializationException(
"Error getting default pool: " + se.getMessage(),
getRole());
} catch (UnknownHostException se) {
throw new ModuleInitializationException(
"Error determining hostIP address: " + se.getMessage(),
getRole());
}
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* @ids=select doDbID from do where doPID='demo:5'
* if @ids.size=0, return false
* else:
* foreach $id in @ids
* ds=reader.getDatastream(id, null)
* update dsBind set dsLabel='mylabel', dsLocation='' where dsID='$id'
*
* // currentVersionId?
*
* @param reader a digital object reader.
* @return true is successful update; false oterhwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
results.close();
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
ArrayList updates=new ArrayList();
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID+";");
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
if (dissDbIDs.size()==0) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "has no disseminators; components dont need updating.");
return false;
}
results.close();
Iterator dissIter = dissDbIDs.iterator();
// Iterate over disseminators to check if any have been modified
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
logFinest("Iterating, dissDbID: "+dissDbID);
// get disseminator info for this disseminator
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bmech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bmech WHERE bmech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
// compare the latest version of the disseminator with what's in the db...
// replace what's in db if they are different
Disseminator diss=reader.GetDisseminator(dissID, null);
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
+ if (!diss.dissLabel.equals(dissLabel))
+ logFinest("dissLabel changed from '" + dissLabel + "' to '" + diss.dissLabel + "'");
+ if (!diss.dissState.equals(dissState))
+ logFinest("dissState changed from '" + dissState + "' to '" + diss.dissState + "'");
// we might need to set the bMechDbID to the id for the new one,
// if the mechanism changed
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
- logFinest("Since the BMech changed, the diss table's bMechDbID will be changed.");
+ logFinest("bMechPID changed from '" + bMechPID + "' to '" + diss.bMechID + "'");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
}
// update the diss table with all new, correct values
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
- + "', dissID='" + diss.dissID + "', "
+ + "dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID);
}
// compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID+";");
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
String newDSBindMapID=diss.dsBindMapID;
if (!newDSBindMapID.equals(origDSBindMapID)) {
// dsBindingMap was modified so remove existing bindingMap
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE dsBindMapDbID=" + origDSBindMapDbID + ";");
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID + ";");
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
// now add back new dsBindMap for this disseminator
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
// only update bindingMap that was modified
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
logFinest("augmentedlength: "+allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length;
++j) {
logFinest("j: "+j);
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].
datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
"A");
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
return true;
}
private boolean addNewComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean failed=false;
try {
String doPID = reader.GetObjectPID();
connection=m_pool.getConnection();
connection.setAutoCommit(false);
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE "
+ "doPID='" + doPID + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.addNewComponents: Object is "
+ "new; components will be added as part of new object replication.");
return false;
}
int doDbID=results.getInt("doDbID");
results.close();
Disseminator[] dissArray = reader.GetDisseminators(null, null);
HashSet newDisseminators = new HashSet();
for (int j=0; j< dissArray.length; j++)
{
// Find disseminators that are NEW within an existing object
// (disseminator does not already exist in the database)
results=logAndExecuteQuery(st, "SELECT diss.dissDbID"
+ " FROM dodissassoc, diss"
+ " WHERE dodissassoc.doDbID=" + doDbID + " AND diss.dissID='" + dissArray[j].dissID + "'"
+ " AND dodissassoc.dissDbID=diss.dissDbID");
while (!results.next()) {
// the disseminator does NOT exist in the database; it is NEW.
newDisseminators.add(dissArray[j]);
}
}
addDisseminators(doPID, (Disseminator[])newDisseminators.toArray(new Disseminator[0]), reader, connection);
connection.commit();
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
// TODO: make sure this makes sense here
if (connection!=null) {
try {
if (failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
return true;
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* Currently bdef components cannot be updated, so this will
* simply return true if the bDef has already been replicated.
*
* @param reader a behavior definitionobject reader.
* @return true if bdef update successful; false otherwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(BDefReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
try {
connection=m_pool.getConnection();
st=connection.createStatement();
results=logAndExecuteQuery(st, "SELECT bDefDbID FROM bDef WHERE "
+ "bDefPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
return true;
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* Currently bmech components cannot be updated, so this will
* simply return true if the bMech has already been replicated.
*
* @param reader a behavior mechanism object reader.
* @return true if bmech update successful; false otherwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(BMechReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
try {
connection=m_pool.getConnection();
st=connection.createStatement();
results=logAndExecuteQuery(st, "SELECT bMechDbID FROM bMech WHERE "
+ "bMechPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
return true;
}
/**
* Replicates a Fedora behavior definition object.
*
* @param bDefReader behavior definition reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(BDefReader bDefReader)
throws ReplicationException, SQLException {
if (!updateComponents(bDefReader)) {
Connection connection=null;
try {
MethodDef behaviorDefs[];
String bDefDBID;
String bDefPID;
String bDefLabel;
String methDBID;
String methodName;
String parmRequired;
String[] parmDomainValues;
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Behavior Definition row
bDefPID = bDefReader.GetObjectPID();
bDefLabel = bDefReader.GetObjectLabel();
insertBehaviorDefinitionRow(connection, bDefPID, bDefLabel, bDefReader.GetObjectState());
// Insert method rows
bDefDBID = lookupBehaviorDefinitionDBID(connection, bDefPID);
if (bDefDBID == null) {
throw new ReplicationException(
"BehaviorDefinition row doesn't exist for PID: "
+ bDefPID);
}
behaviorDefs = bDefReader.getAbstractMethods(null);
for (int i=0; i<behaviorDefs.length; ++i) {
insertMethodRow(connection, bDefDBID,
behaviorDefs[i].methodName,
behaviorDefs[i].methodLabel);
// Insert method parm rows
methDBID = lookupMethodDBID(connection, bDefDBID,
behaviorDefs[i].methodName);
for (int j=0; j<behaviorDefs[i].methodParms.length; j++)
{
MethodParmDef[] methodParmDefs =
new MethodParmDef[behaviorDefs[i].methodParms.length];
methodParmDefs = behaviorDefs[i].methodParms;
parmRequired =
methodParmDefs[j].parmRequired ? "true" : "false";
parmDomainValues = methodParmDefs[j].parmDomainValues;
StringBuffer sb = new StringBuffer();
if (parmDomainValues != null && parmDomainValues.length > 0)
{
for (int k=0; k<parmDomainValues.length; k++)
{
if (k < parmDomainValues.length-1)
{
sb.append(parmDomainValues[k]+",");
} else
{
sb.append(parmDomainValues[k]);
}
}
} else
{
sb.append("null");
}
insertMethodParmRow(connection, methDBID, bDefDBID,
methodParmDefs[j].parmName,
methodParmDefs[j].parmDefaultValue,
sb.toString(),
parmRequired,
methodParmDefs[j].parmLabel,
methodParmDefs[j].parmType);
}
}
connection.commit();
} catch (ReplicationException re) {
throw re;
} catch (ServerException se) {
throw new ReplicationException("Replication exception caused by "
+ "ServerException - " + se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
/**
* Replicates a Fedora behavior mechanism object.
*
* @param bMechReader behavior mechanism reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(BMechReader bMechReader)
throws ReplicationException, SQLException {
if (!updateComponents(bMechReader)) {
Connection connection=null;
try {
BMechDSBindSpec dsBindSpec;
MethodDefOperationBind behaviorBindings[];
MethodDefOperationBind behaviorBindingsEntry;
String bDefDBID;
String bDefPID;
String bMechDBID;
String bMechPID;
String bMechLabel;
String dsBindingKeyDBID;
String methodDBID;
String ordinality_flag;
String cardinality;
String[] parmDomainValues;
String parmRequired;
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Behavior Mechanism row
dsBindSpec = bMechReader.getServiceDSInputSpec(null);
bDefPID = dsBindSpec.bDefPID;
bDefDBID = lookupBehaviorDefinitionDBID(connection, bDefPID);
if (bDefDBID == null) {
throw new ReplicationException("BehaviorDefinition row doesn't "
+ "exist for PID: " + bDefPID);
}
bMechPID = bMechReader.GetObjectPID();
bMechLabel = bMechReader.GetObjectLabel();
insertBehaviorMechanismRow(connection, bDefDBID, bMechPID,
bMechLabel, bMechReader.GetObjectState());
// Insert dsBindSpec rows
bMechDBID = lookupBehaviorMechanismDBID(connection, bMechPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row doesn't "
+ "exist for PID: " + bDefPID);
}
for (int i=0; i<dsBindSpec.dsBindRules.length; ++i) {
// Convert from type boolean to type String
ordinality_flag =
dsBindSpec.dsBindRules[i].ordinality ? "true" : "false";
// Convert from type int to type String
cardinality = Integer.toString(
dsBindSpec.dsBindRules[i].maxNumBindings);
insertDataStreamBindingSpecRow(connection,
bMechDBID, dsBindSpec.dsBindRules[i].bindingKeyName,
ordinality_flag, cardinality,
dsBindSpec.dsBindRules[i].bindingLabel);
// Insert dsMIME rows
dsBindingKeyDBID =
lookupDataStreamBindingSpecDBID(connection,
bMechDBID, dsBindSpec.dsBindRules[i].bindingKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"dsBindSpec row doesn't exist for "
+ "bMechDBID: " + bMechDBID
+ ", binding key name: "
+ dsBindSpec.dsBindRules[i].bindingKeyName);
}
for (int j=0;
j<dsBindSpec.dsBindRules[i].bindingMIMETypes.length;
++j) {
insertDataStreamMIMERow(connection,
dsBindingKeyDBID,
dsBindSpec.dsBindRules[i].bindingMIMETypes[j]);
}
}
// Insert mechImpl rows
behaviorBindings = bMechReader.getServiceMethodBindings(null);
for (int i=0; i<behaviorBindings.length; ++i) {
behaviorBindingsEntry =
(MethodDefOperationBind)behaviorBindings[i];
if (!behaviorBindingsEntry.protocolType.equals("HTTP")) {
// For the time being, ignore bindings other than HTTP.
continue;
}
// Insert mechDefParm rows
methodDBID = lookupMethodDBID(connection, bDefDBID,
behaviorBindingsEntry.methodName);
if (methodDBID == null) {
throw new ReplicationException("Method row doesn't "
+ "exist for method name: "
+ behaviorBindingsEntry.methodName);
}
for (int j=0; j<behaviorBindings[i].methodParms.length; j++)
{
MethodParmDef[] methodParmDefs =
new MethodParmDef[behaviorBindings[i].methodParms.length];
methodParmDefs = behaviorBindings[i].methodParms;
//if (methodParmDefs[j].parmType.equalsIgnoreCase("fedora:defaultInputType"))
if (methodParmDefs[j].parmType.equalsIgnoreCase(MethodParmDef.DEFAULT_INPUT))
{
parmRequired =
methodParmDefs[j].parmRequired ? "true" : "false";
parmDomainValues = methodParmDefs[j].parmDomainValues;
StringBuffer sb = new StringBuffer();
if (parmDomainValues != null && parmDomainValues.length > 0)
{
for (int k=0; k<parmDomainValues.length; k++)
{
if (k < parmDomainValues.length-1)
{
sb.append(parmDomainValues[k]+",");
} else
{
sb.append(parmDomainValues[k]);
}
}
} else
{
if (sb.length() == 0) sb.append("null");
}
insertMechDefaultMethodParmRow(connection, methodDBID, bMechDBID,
methodParmDefs[j].parmName,
methodParmDefs[j].parmDefaultValue,
sb.toString(),
parmRequired,
methodParmDefs[j].parmLabel,
methodParmDefs[j].parmType);
}
}
for (int j=0; j<dsBindSpec.dsBindRules.length; ++j) {
dsBindingKeyDBID =
lookupDataStreamBindingSpecDBID(connection,
bMechDBID,
dsBindSpec.dsBindRules[j].bindingKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"dsBindSpec "
+ "row doesn't exist for bMechDBID: "
+ bMechDBID + ", binding key name: "
+ dsBindSpec.dsBindRules[j].bindingKeyName);
}
for (int k=0; k<behaviorBindingsEntry.dsBindingKeys.length;
k++)
{
// A row is added to the mechImpl table for each
// method with a different BindingKeyName. In cases where
// a single method may have multiple binding keys,
// multiple rows are added for each different
// BindingKeyName for that method.
if (behaviorBindingsEntry.dsBindingKeys[k].
equalsIgnoreCase(
dsBindSpec.dsBindRules[j].bindingKeyName))
{
insertMechanismImplRow(connection, bMechDBID,
bDefDBID, methodDBID, dsBindingKeyDBID,
"http", "text/html",
// sdp - local.fedora.server conversion
encodeLocalURL(behaviorBindingsEntry.serviceBindingAddress),
encodeLocalURL(behaviorBindingsEntry.operationLocation), "1");
}
}
}
}
connection.commit();
} catch (ReplicationException re) {
re.printStackTrace();
throw re;
} catch (ServerException se) {
se.printStackTrace();
throw new ReplicationException(
"Replication exception caused by ServerException - "
+ se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
/**
* Replicates a Fedora data object.
*
* @param doReader data object reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(DOReader doReader)
throws ReplicationException, SQLException {
// do updates if the object already existed
boolean componentsUpdated=updateComponents(doReader);
// and do adds if the object already existed
boolean componentsAdded=addNewComponents(doReader);
// ...if neither returned true, assume the object never existed
if (!componentsUpdated && !componentsAdded) {
Connection connection=null;
try
{
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
int rc;
doPID = doReader.GetObjectPID();
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Digital Object row
doPID = doReader.GetObjectPID();
doLabel = doReader.GetObjectLabel();
insertDigitalObjectRow(connection, doPID, doLabel, doReader.GetObjectState());
doDBID = lookupDigitalObjectDBID(connection, doPID);
if (doDBID == null) {
throw new ReplicationException("do row doesn't "
+ "exist for PID: " + doPID);
}
// add disseminator components (which include associated datastream components)
disseminators = doReader.GetDisseminators(null, null);
addDisseminators(doPID, disseminators, doReader, connection);
connection.commit();
} catch (ReplicationException re) {
re.printStackTrace();
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + re.getClass().getName()
+ " \". The cause was \" " + re.getMessage() + " \"");
} catch (ServerException se) {
se.printStackTrace();
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
private ResultSet logAndExecuteQuery(Statement statement, String sql)
throws SQLException {
logFinest("Executing query: " + sql);
return statement.executeQuery(sql);
}
private int logAndExecuteUpdate(Statement statement, String sql)
throws SQLException {
logFinest("Executing update: " + sql);
return statement.executeUpdate(sql);
}
/**
* Gets a string suitable for a SQL WHERE clause, of the form
* <b>x=y1 or x=y2 or x=y3</b>...etc, where x is the value from the
* column, and y1 is composed of the integer values from the given set.
* <p></p>
* If the set doesn't contain any items, returns a condition that
* always evaluates to false, <b>1=2</b>.
*
* @param column value of the column.
* @param integers set of integers.
* @return string suitable for SQL WHERE clause.
*/
private String inIntegerSetWhereConditionString(String column,
Set integers) {
StringBuffer out=new StringBuffer();
Iterator iter=integers.iterator();
int n=0;
while (iter.hasNext()) {
if (n>0) {
out.append(" OR ");
}
out.append(column);
out.append('=');
int i=((Integer) iter.next()).intValue();
out.append(i);
n++;
}
if (n>0) {
return out.toString();
} else {
return "1=2";
}
}
/**
* Deletes all rows pertinent to the given behavior definition object,
* if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $bDefDbID=SELECT bDefDbID FROM bDef WHERE bDefPID=$PID
* DELETE FROM bDef,method,parm
* WHERE bDefDbID=$bDefDbID
* </pre></ul>
*
* @param connection a database connection.
* @param pid the idenitifer of a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteBehaviorDefinition(Connection connection, String pid)
throws SQLException {
logFinest("Entered DefaultDOReplicator.deleteBehaviorDefinition");
Statement st=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("Checking BehaviorDefinition table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT bDefDbID FROM "
+ "bDef WHERE bDefPID='" + pid + "'");
if (!results.next()) {
// must not be a bdef...exit early
logFinest(pid + " wasn't found in BehaviorDefinition table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("bDefDbID");
logFinest(pid + " was found in BehaviorDefinition table (DBID="
+ dbid + ")");
//
// WRITE
//
int rowCount;
logFinest("Attempting row deletion from BehaviorDefinition "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM bDef "
+ "WHERE bDefDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from method table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM method WHERE "
+ "bDefDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from parm table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM parm WHERE "
+ "bDefDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null) st.close();
logFinest("Exiting DefaultDOReplicator.deleteBehaviorDefinition");
}
}
/**
* Deletes all rows pertinent to the given behavior mechanism object,
* if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $bMechDbID=SELECT bMechDbID
* FROM bMech WHERE bMechPID=$PID
* bMech
* @BKEYIDS=SELECT dsBindKeyDbID
* FROM dsBindSpec
* WHERE bMechDbID=$bMechDbID
* dsMIME WHERE dsBindKeyDbID in @BKEYIDS
* mechImpl
* </pre></ul>
*
* @param connection a database connection.
* @param pid the identifier of a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteBehaviorMechanism(Connection connection, String pid)
throws SQLException {
logFinest("Entered DefaultDOReplicator.deleteBehaviorMechanism");
Statement st=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("Checking bMech table for " + pid + "...");
//results=logAndExecuteQuery(st, "SELECT bMechDbID, SMType_DBID "
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech WHERE bMechPID='" + pid + "'");
if (!results.next()) {
// must not be a bmech...exit early
logFinest(pid + " wasn't found in bMech table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("bMechDbID");
//int smtype_dbid=results.getInt("bMechDbID");
results.close();
logFinest(pid + " was found in bMech table (DBID="
// + dbid + ", SMTYPE_DBID=" + smtype_dbid + ")");
+ dbid);
logFinest("Getting dsBindKeyDbID(s) from dsBindSpec "
+ "table...");
HashSet dsBindingKeyIds=new HashSet();
results=logAndExecuteQuery(st, "SELECT dsBindKeyDbID from "
+ "dsBindSpec WHERE bMechDbID=" + dbid);
while (results.next()) {
dsBindingKeyIds.add(new Integer(
results.getInt("dsBindKeyDbID")));
}
results.close();
logFinest("Found " + dsBindingKeyIds.size()
+ " dsBindKeyDbID(s).");
//
// WRITE
//
int rowCount;
logFinest("Attempting row deletion from bMech table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM bMech "
+ "WHERE bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBindSpec "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "dsBindSpec WHERE bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsMIME table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsMIME WHERE "
+ inIntegerSetWhereConditionString("dsBindKeyDbID",
dsBindingKeyIds));
logFinest("Deleted " + rowCount + " row(s).");
//logFinest("Attempting row deletion from StructMapType table...");
//rowCount=logAndExecuteUpdate(st, "DELETE FROM StructMapType WHERE "
// + "SMType_DBID=" + smtype_dbid);
//logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBindMap table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE "
+ "bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from mechImpl table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM mechImpl WHERE "
+ "bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from mechDefParm table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM mechDefParm "
+ "WHERE bMechDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null)st.close();
logFinest("Exiting DefaultDOReplicator.deleteBehaviorMechanism");
}
}
/**
* Deletes all rows pertinent to the given digital object (treated as a
* regular data object) if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $doDbID=SELECT doDbID FROM do where doPID=$PID
* @DISSIDS=SELECT dissDbID
* FROM doDissAssoc WHERE doDbID=$doDbID
* @BMAPIDS=SELECT dsBindMapDbID
* FROM dsBind WHERE doDbID=$doDbID
* do
* doDissAssoc where $doDbID=doDbID
* dsBind WHERE $doDbID=doDbID
* diss WHERE dissDbID in @DISSIDS
* dsBindMap WHERE dsBindMapDbID in @BMAPIDS
* </pre></ul>
*
* @param connection a databae connection.
* @param pid the identifier for a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteDigitalObject(Connection connection, String pid)
throws SQLException {
logFinest("Entered DefaultDOReplicator.deleteDigitalObject");
Statement st=null;
Statement st2=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("Checking do table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT doDbID FROM "
+ "do WHERE doPID='" + pid + "'");
if (!results.next()) {
// must not be a digitalobject...exit early
logFinest(pid + " wasn't found in do table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("doDbID");
results.close();
logFinest(pid + " was found in do table (DBID="
+ dbid + ")");
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table...");
HashSet dissIds=new HashSet();
HashSet dissIdsInUse = new HashSet();
results=logAndExecuteQuery(st, "SELECT dissDbID from "
+ "doDissAssoc WHERE doDbID=" + dbid);
while (results.next()) {
dissIds.add(new Integer(results.getInt("dissDbID")));
}
results.close();
HashSet bMechIds = new HashSet();
logFinest("Getting dissDbID(s) from doDissAssoc "
+ "table unique to this object...");
Iterator iterator = dissIds.iterator();
while (iterator.hasNext())
{
Integer id = (Integer)iterator.next();
logFinest("Getting occurrences of dissDbID(s) in "
+ "doDissAssoc table...");
results=logAndExecuteQuery(st, "SELECT COUNT(*) from "
+ "doDissAssoc WHERE dissDbID=" + id);
while (results.next())
{
Integer i1 = new Integer(results.getInt("COUNT(*)"));
if ( i1.intValue() > 1 )
{
//dissIds.remove(id);
// A dissDbID that occurs more than once indicates that the
// disseminator is used by other objects. In this case, we
// do not want to remove the disseminator from the diss
// table so keep track of this dissDbID.
dissIdsInUse.add(id);
} else
{
ResultSet rs = null;
logFinest("Getting associated bMechDbID(s) that are unique "
+ "for this object in diss table...");
st2 = connection.createStatement();
rs=logAndExecuteQuery(st2, "SELECT bMechDbID from "
+ "diss WHERE dissDbID=" + id);
while (rs.next())
{
bMechIds.add(new Integer(rs.getInt("bMechDbID")));
}
rs.close();
st2.close();
}
}
results.close();
}
iterator = dissIdsInUse.iterator();
// Remove disseminator ids of those disseminators that were in
// use by one or more other objects to prevent them from being
// removed from the disseminator table in following code section.
while (iterator.hasNext() )
{
Integer id = (Integer)iterator.next();
dissIds.remove(id);
}
logFinest("Found " + dissIds.size() + " dissDbID(s).");
logFinest("Getting bMechDbIDs matching dsBindMapDbID(s) from dsBind "
+ "table...");
logFinest("Getting dsBindMapDbID(s) from dsBind "
+ "table...");
//HashSet bmapIds=new HashSet();
//results=logAndExecuteQuery(st, "SELECT dsBindMapDbID FROM "
// + "dsBind WHERE doDbID=" + dbid);
//while (results.next()) {
// bmapIds.add(new Integer(results.getInt("dsBindMapDbID")));
//}
//results.close();
//logFinest("Found " + bmapIds.size() + " dsBindMapDbID(s).");
//
// WRITE
//
int rowCount;
logFinest("Attempting row deletion from do table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM do "
+ "WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from doDissAssoc "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "doDissAssoc WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBind table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind "
+ "WHERE doDbID=" + dbid);
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from diss table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE "
+ inIntegerSetWhereConditionString("dissDbID", dissIds));
logFinest("Deleted " + rowCount + " row(s).");
logFinest("Attempting row deletion from dsBindMap "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap "
+ "WHERE " + inIntegerSetWhereConditionString(
// "dsBindMapDbID", bmapIds));
"bMechDbID", bMechIds));
logFinest("Deleted " + rowCount + " row(s).");
} finally {
if (results != null) results.close();
if (st!=null) st.close();
if (st2!=null) st2.close();
logFinest("Exiting DefaultDOReplicator.deleteDigitalObject");
}
}
/**
* Removes a digital object from the dissemination database.
* <p></p>
* If the object is a behavior definition or mechanism, it's deleted
* as such, and then an attempt is made to delete it as a regular
* digital object as well.
* <p></p>
* Note that this does not do cascading check object dependencies at
* all. It is expected at this point that when this is called, any
* referencial integrity issues have been ironed out or checked as
* appropriate.
* <p></p>
* All deletions happen in a transaction. If any database errors occur,
* the change is rolled back.
*
* @param pid The pid of the object to delete.
* @throws ReplicationException If the request couldn't be fulfilled for
* any reason.
*/
public void delete(String pid)
throws ReplicationException {
logFinest("Entered DefaultDOReplicator.delete");
Connection connection=null;
try {
connection = m_pool.getConnection();
connection.setAutoCommit(false);
deleteBehaviorDefinition(connection, pid);
deleteBehaviorMechanism(connection, pid);
deleteDigitalObject(connection, pid);
connection.commit();
} catch (SQLException sqle) {
throw new ReplicationException("Error while replicator was trying "
+ "to delete " + pid + ". " + sqle.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
connection.setAutoCommit(true);
m_pool.free(connection);
} catch (SQLException sqle) {}
}
logFinest("Exiting DefaultDOReplicator.delete");
}
}
/**
*
* Inserts a Behavior Definition row.
*
* @param connection JDBC DBMS connection
* @param bDefPID Behavior definition PID
* @param bDefLabel Behavior definition label
*
* @exception SQLException JDBC, SQL error
*/
public void insertBehaviorDefinitionRow(Connection connection, String bDefPID, String bDefLabel, String bDefState) throws SQLException {
String insertionStatement = "INSERT INTO bDef (bDefPID, bDefLabel, bDefState) VALUES ('" + bDefPID + "', '" + SQLUtility.aposEscape(bDefLabel) + "', '" + bDefState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a Behavior Mechanism row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param bMechPID Behavior mechanism DBID
* @param bMechLabel Behavior mechanism label
*
* @throws SQLException JDBC, SQL error
*/
public void insertBehaviorMechanismRow(Connection connection, String bDefDbID, String bMechPID, String bMechLabel, String bMechState) throws SQLException {
String insertionStatement = "INSERT INTO bMech (bDefDbID, bMechPID, bMechLabel, bMechState) VALUES ('" + bDefDbID + "', '" + bMechPID + "', '" + SQLUtility.aposEscape(bMechLabel) + "', '" + bMechState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a DataStreamBindingRow row.
*
* @param connection JDBC DBMS connection
* @param doDbID Digital object DBID
* @param dsBindKeyDbID Datastream binding key DBID
* @param dsBindMapDbID Binding map DBID
* @param dsBindKeySeq Datastream binding key sequence number
* @param dsID Datastream ID
* @param dsLabel Datastream label
* @param dsMIME Datastream mime type
* @param dsLocation Datastream location
* @param dsControlGroupType Datastream type
* @param dsCurrentVersionID Datastream current version ID
* @param policyDbID Policy DBID
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingRow(Connection connection, String doDbID, String dsBindKeyDbID, String dsBindMapDbID, String dsBindKeySeq, String dsID, String dsLabel, String dsMIME, String dsLocation, String dsControlGroupType, String dsCurrentVersionID, String policyDbID, String dsState) throws SQLException {
String insertionStatement = "INSERT INTO dsBind (doDbID, dsBindKeyDbID, dsBindMapDbID, dsBindKeySeq, dsID, dsLabel, dsMIME, dsLocation, dsControlGroupType, dsCurrentVersionID, policyDbID, dsState) VALUES ('" + doDbID + "', '" + dsBindKeyDbID + "', '" + dsBindMapDbID + "', '" + dsBindKeySeq + "', '" + dsID + "', '" + SQLUtility.aposEscape(dsLabel) + "', '" + dsMIME + "', '" + dsLocation + "', '" + dsControlGroupType + "', '" + dsCurrentVersionID + "', '" + policyDbID + "', '" + dsState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsBindMap row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param dsBindMapID Datastream binding map ID
* @param dsBindMapLabel Datastream binding map label
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingMapRow(Connection connection, String bMechDbID, String dsBindMapID, String dsBindMapLabel) throws SQLException {
String insertionStatement = "INSERT INTO dsBindMap (bMechDbID, dsBindMapID, dsBindMapLabel) VALUES ('" + bMechDbID + "', '" + dsBindMapID + "', '" + SQLUtility.aposEscape(dsBindMapLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsBindSpec row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param dsBindSpecName Datastream binding spec name
* @param dsBindSpecOrdinality Datastream binding spec ordinality flag
* @param dsBindSpecCardinality Datastream binding cardinality
* @param dsBindSpecLabel Datastream binding spec lable
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingSpecRow(Connection connection, String bMechDbID, String dsBindSpecName, String dsBindSpecOrdinality, String dsBindSpecCardinality, String dsBindSpecLabel) throws SQLException {
String insertionStatement = "INSERT INTO dsBindSpec (bMechDbID, dsBindSpecName, dsBindSpecOrdinality, dsBindSpecCardinality, dsBindSpecLabel) VALUES ('" + bMechDbID + "', '" + SQLUtility.aposEscape(dsBindSpecName) + "', '" + dsBindSpecOrdinality + "', '" + dsBindSpecCardinality + "', '" + SQLUtility.aposEscape(dsBindSpecLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsMIME row.
*
* @param connection JDBC DBMS connection
* @param dsBindKeyDbID Datastream binding key DBID
* @param dsMIMEName Datastream MIME type name
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamMIMERow(Connection connection, String dsBindKeyDbID, String dsMIMEName) throws SQLException {
String insertionStatement = "INSERT INTO dsMIME (dsBindKeyDbID, dsMIMEName) VALUES ('" + dsBindKeyDbID + "', '" + dsMIMEName + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a do row.
*
* @param connection JDBC DBMS connection
* @param doPID DigitalObject PID
* @param doLabel DigitalObject label
*
* @exception SQLException JDBC, SQL error
*/
public void insertDigitalObjectRow(Connection connection, String doPID, String doLabel, String doState) throws SQLException {
String insertionStatement = "INSERT INTO do (doPID, doLabel, doState) VALUES ('" + doPID + "', '" + SQLUtility.aposEscape(doLabel) + "', '" + doState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a doDissAssoc row.
*
* @param connection JDBC DBMS connection
* @param doDbID DigitalObject DBID
* @param dissDbID Disseminator DBID
*
* @exception SQLException JDBC, SQL error
*/
public void insertDigitalObjectDissAssocRow(Connection connection, String doDbID, String dissDbID) throws SQLException {
String insertionStatement = "INSERT INTO doDissAssoc (doDbID, dissDbID) VALUES ('" + doDbID + "', '" + dissDbID + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a Disseminator row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param bMechDbID Behavior mechanism DBID
* @param dissID Disseminator ID
* @param dissLabel Disseminator label
*
* @exception SQLException JDBC, SQL error
*/
public void insertDisseminatorRow(Connection connection, String bDefDbID, String bMechDbID, String dissID, String dissLabel, String dissState) throws SQLException {
String insertionStatement = "INSERT INTO diss (bDefDbID, bMechDbID, dissID, dissLabel, dissState) VALUES ('" + bDefDbID + "', '" + bMechDbID + "', '" + dissID + "', '" + SQLUtility.aposEscape(dissLabel) + "', '" + dissState +"')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a mechImpl row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param bDefDbID Behavior definition DBID
* @param methodDbID Method DBID
* @param dsBindKeyDbID Datastream binding key DBID
* @param protocolType Mechanism implementation protocol type
* @param returnType Mechanism implementation return type
* @param addressLocation Mechanism implementation address location
* @param operationLocation Mechanism implementation operation location
* @param policyDbID Policy DBID
*
* @exception SQLException JDBC, SQL error
*/
public void insertMechanismImplRow(Connection connection, String bMechDbID, String bDefDbID, String methodDbID, String dsBindKeyDbID, String protocolType, String returnType, String addressLocation, String operationLocation, String policyDbID) throws SQLException {
String insertionStatement = "INSERT INTO mechImpl (bMechDbID, bDefDbID, methodDbID, dsBindKeyDbID, protocolType, returnType, addressLocation, operationLocation, policyDbID) VALUES ('" + bMechDbID + "', '" + bDefDbID + "', '" + methodDbID + "', '" + dsBindKeyDbID + "', '" + protocolType + "', '" + returnType + "', '" + addressLocation + "', '" + operationLocation + "', '" + policyDbID + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a method row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param methodName Behavior definition label
* @param methodLabel Behavior definition label
*
* @exception SQLException JDBC, SQL error
*/
public void insertMethodRow(Connection connection, String bDefDbID, String methodName, String methodLabel) throws SQLException {
String insertionStatement = "INSERT INTO method (bDefDbID, methodName, methodLabel) VALUES ('" + bDefDbID + "', '" + SQLUtility.aposEscape(methodName) + "', '" + SQLUtility.aposEscape(methodLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* @param connection An SQL Connection.
* @param methDBID The method database ID.
* @param bdefDBID The behavior Definition object database ID.
* @param parmName the parameter name.
* @param parmDefaultValue A default value for the parameter.
* @param parmDomainValues A list of possible values for the parameter.
* @param parmRequiredFlag A boolean flag indicating whether the
* parameter is required or not.
* @param parmLabel The parameter label.
* @param parmType The parameter type.
* @throws SQLException JDBC, SQL error
*/
public void insertMethodParmRow(Connection connection, String methDBID,
String bdefDBID, String parmName, String parmDefaultValue,
String parmDomainValues, String parmRequiredFlag,
String parmLabel, String parmType)
throws SQLException {
String insertionStatement = "INSERT INTO parm "
+ "(methodDbID, bDefDbID, parmName, parmDefaultValue, "
+ "parmDomainValues, parmRequiredFlag, parmLabel, "
+ "parmType) VALUES ('"
+ methDBID + "', '" + bdefDBID + "', '"
+ SQLUtility.aposEscape(parmName) + "', '" + SQLUtility.aposEscape(parmDefaultValue) + "', '"
+ SQLUtility.aposEscape(parmDomainValues) + "', '"
+ parmRequiredFlag + "', '" + SQLUtility.aposEscape(parmLabel) + "', '"
+ parmType + "')";
insertGen(connection, insertionStatement);
}
/**
*
* @param connection An SQL Connection.
* @param methDBID The method database ID.
* @param bmechDBID The behavior Mechanism object database ID.
* @param parmName the parameter name.
* @param parmDefaultValue A default value for the parameter.
* @param parmRequiredFlag A boolean flag indicating whether the
* parameter is required or not.
* @param parmDomainValues A list of possible values for the parameter.
* @param parmLabel The parameter label.
* @param parmType The parameter type.
* @throws SQLException JDBC, SQL error
*/
public void insertMechDefaultMethodParmRow(Connection connection, String methDBID,
String bmechDBID, String parmName, String parmDefaultValue,
String parmDomainValues, String parmRequiredFlag,
String parmLabel, String parmType)
throws SQLException {
String insertionStatement = "INSERT INTO mechDefParm "
+ "(methodDbID, bMechDbID, defParmName, defParmDefaultValue, "
+ "defParmDomainValues, defParmRequiredFlag, defParmLabel, "
+ "defParmType) VALUES ('"
+ methDBID + "', '" + bmechDBID + "', '"
+ SQLUtility.aposEscape(parmName) + "', '" + SQLUtility.aposEscape(parmDefaultValue) + "', '"
+ SQLUtility.aposEscape(parmDomainValues) + "', '"
+ parmRequiredFlag + "', '" + SQLUtility.aposEscape(parmLabel) + "', '"
+ parmType + "')";
insertGen(connection, insertionStatement);
}
/**
*
* General JDBC row insertion method.
*
* @param connection JDBC DBMS connection
* @param insertionStatement SQL row insertion statement
*
* @exception SQLException JDBC, SQL error
*/
public void insertGen(Connection connection, String insertionStatement) throws SQLException {
int rowCount = 0;
Statement statement = null;
statement = connection.createStatement();
logFinest("Doing DB Insert: " + insertionStatement);
rowCount = statement.executeUpdate(insertionStatement);
statement.close();
}
/**
*
* Looks up a BehaviorDefinition DBID.
*
* @param connection JDBC DBMS connection
* @param bDefPID Behavior definition PID
*
* @return The DBID of the specified Behavior Definition row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupBehaviorDefinitionDBID(Connection connection, String bDefPID) throws StorageDeviceException {
return lookupDBID1(connection, "bDefDbID", "bDef", "bDefPID", bDefPID);
}
/**
*
* Looks up a BehaviorMechanism DBID.
*
* @param connection JDBC DBMS connection
* @param bMechPID Behavior mechanism PID
*
* @return The DBID of the specified Behavior Mechanism row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupBehaviorMechanismDBID(Connection connection, String bMechPID) throws StorageDeviceException {
return lookupDBID1(connection, "bMechDbID", "bMech", "bMechPID", bMechPID);
}
/**
*
* Looks up a dsBindMap DBID.
*
* @param connection JDBC DBMS connection
* @param bMechDBID Behavior mechanism DBID
* @param dsBindingMapID Data stream binding map ID
*
* @return The DBID of the specified dsBindMap row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDataStreamBindingMapDBID(Connection connection, String bMechDBID, String dsBindingMapID) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "dsBindMapDbID", "dsBindMap", "bMechDbID", bMechDBID, "dsBindMapID", dsBindingMapID);
}
/**
*
* Looks up a dsBindSpec DBID.
*
* @param connection JDBC DBMS connection
* @param bMechDBID Behavior mechanism DBID
* @param dsBindingSpecName Data stream binding spec name
*
* @return The DBID of the specified dsBindSpec row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDataStreamBindingSpecDBID(Connection connection, String bMechDBID, String dsBindingSpecName) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "dsBindKeyDbID", "dsBindSpec", "bMechDbID", bMechDBID, "dsBindSpecName", dsBindingSpecName);
}
/**
*
* Looks up a do DBID.
*
* @param connection JDBC DBMS connection
* @param doPID Data object PID
*
* @return The DBID of the specified DigitalObject row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDigitalObjectDBID(Connection connection, String doPID) throws StorageDeviceException {
return lookupDBID1(connection, "doDbID", "do", "doPID", doPID);
}
/**
*
* Looks up a Disseminator DBID.
*
* @param connection JDBC DBMS connection
* @param bDefDBID Behavior definition DBID
* @param bMechDBID Behavior mechanism DBID
* @param dissID Disseminator ID
*
* @return The DBID of the specified Disseminator row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDisseminatorDBID(Connection connection, String bDefDBID, String bMechDBID, String dissID) throws StorageDeviceException {
Statement statement = null;
ResultSet rs = null;
String query = null;
String ID = null;
try
{
query = "SELECT dissDbID FROM diss WHERE ";
query += "bDefDbID = " + bDefDBID + " AND ";
query += "bMechDbID = " + bMechDBID + " AND ";
query += "dissID = '" + dissID + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
}
}
return ID;
}
/**
*
* Looks up a method DBID.
*
* @param connection JDBC DBMS connection
* @param bDefDBID Behavior definition DBID
* @param methName Method name
*
* @return The DBID of the specified method row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupMethodDBID(Connection connection, String bDefDBID, String methName) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "methodDbID", "method", "bDefDbID", bDefDBID, "methodName", methName);
}
/**
*
* General JDBC lookup method with 1 lookup column value.
*
* @param connection JDBC DBMS connection
* @param DBIDName DBID column name
* @param tableName Table name
* @param lookupColumnName Lookup column name
* @param lookupColumnValue Lookup column value
*
* @return The DBID of the specified row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDBID1(Connection connection, String DBIDName, String tableName, String lookupColumnName, String lookupColumnValue) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName + " = '" + lookupColumnValue + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
}
}
return ID;
}
/**
*
* General JDBC lookup method with 2 lookup column values.
*
* @param connection JDBC DBMS connection
* @param DBIDName DBID Column name
* @param tableName Table name
* @param lookupColumnName1 First lookup column name
* @param lookupColumnValue1 First lookup column value
* @param lookupColumnName2 Second lookup column name
* @param lookupColumnValue2 Second lookup column value
*
* @return The DBID of the specified row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDBID2(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName1 + " = '" + lookupColumnValue1 + "' AND ";
query += lookupColumnName2 + " = '" + lookupColumnValue2 + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
}
}
return ID;
}
public String lookupDBID2FirstNum(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName1 + " =" + lookupColumnValue1 + " AND ";
query += lookupColumnName2 + " = '" + lookupColumnValue2 + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
}
}
return ID;
}
private String encodeLocalURL(String locationString)
{
// Replace any occurences of the host:port of the local Fedora
// server with the internal serialization string "local.fedora.server."
// This will make sure that local URLs (self-referential to the
// local server) will be recognizable if the server host and
// port configuration changes after an object is stored in the
// repository.
if (fedoraServerPort.equalsIgnoreCase("80") &&
hostPattern.matcher(locationString).find())
{
//System.out.println("port is 80 and host-only pattern found - convert to l.f.s");
return hostPattern.matcher(
locationString).replaceAll("http://local.fedora.server/");
}
else
{
//System.out.println("looking for hostPort pattern to convert to l.f.s");
return hostPortPattern.matcher(
locationString).replaceAll("http://local.fedora.server/");
}
}
private String unencodeLocalURL(String storedLocationString)
{
// Replace any occurrences of the internal serialization string
// "local.fedora.server" with the current host and port of the
// local Fedora server. This translates local URLs (self-referential
// to the local server) back into resolvable URLs that reflect
// the currently configured host and port for the server.
if (fedoraServerPort.equalsIgnoreCase("80"))
{
return serializedLocalURLPattern.matcher(
storedLocationString).replaceAll(fedoraServerHost);
}
else
{
return serializedLocalURLPattern.matcher(
storedLocationString).replaceAll(
fedoraServerHost+":"+fedoraServerPort);
}
}
private void addDisseminators(String doPID, Disseminator[] disseminators, DOReader doReader, Connection connection)
throws ReplicationException, SQLException, ServerException
{
DSBindingMapAugmented[] allBindingMaps;
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doLabel;
String dsBindingKeyDBID;
int rc;
doDBID = lookupDigitalObjectDBID(connection, doPID);
for (int i=0; i<disseminators.length; ++i) {
bDefDBID = lookupBehaviorDefinitionDBID(connection,
disseminators[i].bDefID);
if (bDefDBID == null) {
throw new ReplicationException("BehaviorDefinition row "
+ "doesn't exist for PID: "
+ disseminators[i].bDefID);
}
bMechDBID = lookupBehaviorMechanismDBID(connection,
disseminators[i].bMechID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ disseminators[i].bMechID);
}
// Insert Disseminator row if it doesn't exist.
dissDBID = lookupDisseminatorDBID(connection, bDefDBID,
bMechDBID, disseminators[i].dissID);
if (dissDBID == null) {
// Disseminator row doesn't exist, add it.
insertDisseminatorRow(connection, bDefDBID, bMechDBID,
disseminators[i].dissID, disseminators[i].dissLabel, disseminators[i].dissState);
dissDBID = lookupDisseminatorDBID(connection, bDefDBID,
bMechDBID, disseminators[i].dissID);
if (dissDBID == null) {
throw new ReplicationException("diss row "
+ "doesn't exist for PID: "
+ disseminators[i].dissID);
}
}
// Insert doDissAssoc row
insertDigitalObjectDissAssocRow(connection, doDBID,
dissDBID);
}
allBindingMaps = doReader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length;
++j) {
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
insertDataStreamBindingRow(connection, doDBID,
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].
datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
"A");
}
}
return;
}
}
| false | true | private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
results.close();
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
ArrayList updates=new ArrayList();
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID+";");
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
if (dissDbIDs.size()==0) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "has no disseminators; components dont need updating.");
return false;
}
results.close();
Iterator dissIter = dissDbIDs.iterator();
// Iterate over disseminators to check if any have been modified
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
logFinest("Iterating, dissDbID: "+dissDbID);
// get disseminator info for this disseminator
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bmech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bmech WHERE bmech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
// compare the latest version of the disseminator with what's in the db...
// replace what's in db if they are different
Disseminator diss=reader.GetDisseminator(dissID, null);
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
// we might need to set the bMechDbID to the id for the new one,
// if the mechanism changed
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
logFinest("Since the BMech changed, the diss table's bMechDbID will be changed.");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
}
// update the diss table with all new, correct values
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
+ "', dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID);
}
// compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID+";");
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
String newDSBindMapID=diss.dsBindMapID;
if (!newDSBindMapID.equals(origDSBindMapID)) {
// dsBindingMap was modified so remove existing bindingMap
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE dsBindMapDbID=" + origDSBindMapDbID + ";");
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID + ";");
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
// now add back new dsBindMap for this disseminator
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
// only update bindingMap that was modified
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
logFinest("augmentedlength: "+allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length;
++j) {
logFinest("j: "+j);
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].
datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
"A");
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
return true;
}
| private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
results.close();
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
ArrayList updates=new ArrayList();
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID+";");
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
if (dissDbIDs.size()==0) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "has no disseminators; components dont need updating.");
return false;
}
results.close();
Iterator dissIter = dissDbIDs.iterator();
// Iterate over disseminators to check if any have been modified
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
logFinest("Iterating, dissDbID: "+dissDbID);
// get disseminator info for this disseminator
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bmech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bmech WHERE bmech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
// compare the latest version of the disseminator with what's in the db...
// replace what's in db if they are different
Disseminator diss=reader.GetDisseminator(dissID, null);
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
if (!diss.dissLabel.equals(dissLabel))
logFinest("dissLabel changed from '" + dissLabel + "' to '" + diss.dissLabel + "'");
if (!diss.dissState.equals(dissState))
logFinest("dissState changed from '" + dissState + "' to '" + diss.dissState + "'");
// we might need to set the bMechDbID to the id for the new one,
// if the mechanism changed
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
logFinest("bMechPID changed from '" + bMechPID + "' to '" + diss.bMechID + "'");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
}
// update the diss table with all new, correct values
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
+ "dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID);
}
// compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID+";");
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
String newDSBindMapID=diss.dsBindMapID;
if (!newDSBindMapID.equals(origDSBindMapID)) {
// dsBindingMap was modified so remove existing bindingMap
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE dsBindMapDbID=" + origDSBindMapDbID + ";");
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID + ";");
logFinest("deleted "+rowCount+" rows from dsBindMapDbID");
// now add back new dsBindMap for this disseminator
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
// only update bindingMap that was modified
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
logFinest("augmentedlength: "+allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length;
++j) {
logFinest("j: "+j);
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].
datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
"A");
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
m_pool.free(connection);
}
}
}
}
return true;
}
|
diff --git a/src/main/java/net/pterodactylus/sone/text/FreenetLinkParser.java b/src/main/java/net/pterodactylus/sone/text/FreenetLinkParser.java
index f36b6df8..906571b5 100644
--- a/src/main/java/net/pterodactylus/sone/text/FreenetLinkParser.java
+++ b/src/main/java/net/pterodactylus/sone/text/FreenetLinkParser.java
@@ -1,174 +1,174 @@
/*
* Sone - FreenetLinkParser.java - Copyright © 2010 David Roden
*
* 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 net.pterodactylus.sone.text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.pterodactylus.util.logging.Logging;
import net.pterodactylus.util.template.TemplateFactory;
/**
* {@link Parser} implementation that can recognize Freenet URIs.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class FreenetLinkParser implements Parser {
/** The logger. */
private static final Logger logger = Logging.getLogger(FreenetLinkParser.class);
/** Pattern to detect whitespace. */
private static final Pattern whitespacePattern = Pattern.compile("[\u0020\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u200c\u200d\u202f\u205f\u2060\u2800\u3000]");
/**
* Enumeration for all recognized link types.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
private enum LinkType {
/** Link is a KSK. */
KSK,
/** Link is a CHK. */
CHK,
/** Link is an SSK. */
SSK,
/** Link is a USK. */
USK
}
/** The template factory. */
private final TemplateFactory templateFactory;
/**
* Creates a new freenet link parser.
*
* @param templateFactory
* The template factory
*/
public FreenetLinkParser(TemplateFactory templateFactory) {
this.templateFactory = templateFactory;
}
//
// PART METHODS
//
/**
* {@inheritDoc}
*/
@Override
public Part parse(Reader source) throws IOException {
PartContainer parts = new PartContainer();
BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.trim() + "\n";
while (line.length() > 0) {
int nextKsk = line.indexOf("KSK@");
int nextChk = line.indexOf("CHK@");
int nextSsk = line.indexOf("SSK@");
int nextUsk = line.indexOf("USK@");
if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1)) {
parts.add(createPlainTextPart(line));
break;
}
int next = Integer.MAX_VALUE;
LinkType linkType = null;
if ((nextKsk > -1) && (nextKsk < next)) {
next = nextKsk;
linkType = LinkType.KSK;
}
if ((nextChk > -1) && (nextChk < next)) {
next = nextChk;
linkType = LinkType.CHK;
}
if ((nextSsk > -1) && (nextSsk < next)) {
next = nextSsk;
linkType = LinkType.SSK;
}
if ((nextUsk > -1) && (nextUsk < next)) {
next = nextUsk;
linkType = LinkType.USK;
}
if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
next -= 8;
line = line.substring(0, next) + line.substring(next + 8);
}
Matcher matcher = whitespacePattern.matcher(line);
int nextSpace = matcher.find(next) ? matcher.start() : line.length();
if (nextSpace > (next + 4)) {
parts.add(createPlainTextPart(line.substring(0, next)));
String link = line.substring(next, nextSpace);
String name = link;
- logger.log(Level.FINER, "Found link: " + link);
+ logger.log(Level.FINER, "Found link: %s", link);
logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk });
if (((linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (link.length() > 98) && (link.charAt(47) == ',') && (link.charAt(91) == ',') && (link.charAt(99) == '/')) {
name = link.substring(0, 47) + "…" + link.substring(99);
}
parts.add(createLinkPart(link, name));
line = line.substring(nextSpace);
} else {
parts.add(createPlainTextPart(line.substring(0, next + 4)));
line = line.substring(next + 4);
}
}
}
return parts;
}
//
// PRIVATE METHODS
//
/**
* Creates a new plain text part based on a template.
*
* @param text
* The text to display
* @return The part that displays the given text
*/
private Part createPlainTextPart(String text) {
return new TemplatePart(templateFactory.createTemplate(new StringReader("<% text|html>"))).set("text", text);
}
/**
* Creates a new link part based on a template.
*
* @param link
* The target of the link
* @param name
* The name of the link
* @return The part that displays the link
*/
private Part createLinkPart(String link, String name) {
return new TemplatePart(templateFactory.createTemplate(new StringReader("<a href=\"/<% link|html>\"><% name|html></a>"))).set("link", link).set("name", name);
}
}
| true | true | public Part parse(Reader source) throws IOException {
PartContainer parts = new PartContainer();
BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.trim() + "\n";
while (line.length() > 0) {
int nextKsk = line.indexOf("KSK@");
int nextChk = line.indexOf("CHK@");
int nextSsk = line.indexOf("SSK@");
int nextUsk = line.indexOf("USK@");
if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1)) {
parts.add(createPlainTextPart(line));
break;
}
int next = Integer.MAX_VALUE;
LinkType linkType = null;
if ((nextKsk > -1) && (nextKsk < next)) {
next = nextKsk;
linkType = LinkType.KSK;
}
if ((nextChk > -1) && (nextChk < next)) {
next = nextChk;
linkType = LinkType.CHK;
}
if ((nextSsk > -1) && (nextSsk < next)) {
next = nextSsk;
linkType = LinkType.SSK;
}
if ((nextUsk > -1) && (nextUsk < next)) {
next = nextUsk;
linkType = LinkType.USK;
}
if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
next -= 8;
line = line.substring(0, next) + line.substring(next + 8);
}
Matcher matcher = whitespacePattern.matcher(line);
int nextSpace = matcher.find(next) ? matcher.start() : line.length();
if (nextSpace > (next + 4)) {
parts.add(createPlainTextPart(line.substring(0, next)));
String link = line.substring(next, nextSpace);
String name = link;
logger.log(Level.FINER, "Found link: " + link);
logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk });
if (((linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (link.length() > 98) && (link.charAt(47) == ',') && (link.charAt(91) == ',') && (link.charAt(99) == '/')) {
name = link.substring(0, 47) + "…" + link.substring(99);
}
parts.add(createLinkPart(link, name));
line = line.substring(nextSpace);
} else {
parts.add(createPlainTextPart(line.substring(0, next + 4)));
line = line.substring(next + 4);
}
}
}
return parts;
}
| public Part parse(Reader source) throws IOException {
PartContainer parts = new PartContainer();
BufferedReader bufferedReader = (source instanceof BufferedReader) ? (BufferedReader) source : new BufferedReader(source);
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.trim() + "\n";
while (line.length() > 0) {
int nextKsk = line.indexOf("KSK@");
int nextChk = line.indexOf("CHK@");
int nextSsk = line.indexOf("SSK@");
int nextUsk = line.indexOf("USK@");
if ((nextKsk == -1) && (nextChk == -1) && (nextSsk == -1) && (nextUsk == -1)) {
parts.add(createPlainTextPart(line));
break;
}
int next = Integer.MAX_VALUE;
LinkType linkType = null;
if ((nextKsk > -1) && (nextKsk < next)) {
next = nextKsk;
linkType = LinkType.KSK;
}
if ((nextChk > -1) && (nextChk < next)) {
next = nextChk;
linkType = LinkType.CHK;
}
if ((nextSsk > -1) && (nextSsk < next)) {
next = nextSsk;
linkType = LinkType.SSK;
}
if ((nextUsk > -1) && (nextUsk < next)) {
next = nextUsk;
linkType = LinkType.USK;
}
if ((next >= 8) && (line.substring(next - 8, next).equals("freenet:"))) {
next -= 8;
line = line.substring(0, next) + line.substring(next + 8);
}
Matcher matcher = whitespacePattern.matcher(line);
int nextSpace = matcher.find(next) ? matcher.start() : line.length();
if (nextSpace > (next + 4)) {
parts.add(createPlainTextPart(line.substring(0, next)));
String link = line.substring(next, nextSpace);
String name = link;
logger.log(Level.FINER, "Found link: %s", link);
logger.log(Level.FINEST, "Next: %d, CHK: %d, SSK: %d, USK: %d", new Object[] { next, nextChk, nextSsk, nextUsk });
if (((linkType == LinkType.CHK) || (linkType == LinkType.SSK) || (linkType == LinkType.USK)) && (link.length() > 98) && (link.charAt(47) == ',') && (link.charAt(91) == ',') && (link.charAt(99) == '/')) {
name = link.substring(0, 47) + "…" + link.substring(99);
}
parts.add(createLinkPart(link, name));
line = line.substring(nextSpace);
} else {
parts.add(createPlainTextPart(line.substring(0, next + 4)));
line = line.substring(next + 4);
}
}
}
return parts;
}
|
diff --git a/src/com/wolvencraft/prison/mines/cmd/TriggerCommand.java b/src/com/wolvencraft/prison/mines/cmd/TriggerCommand.java
index 06fb99d..c9866d0 100644
--- a/src/com/wolvencraft/prison/mines/cmd/TriggerCommand.java
+++ b/src/com/wolvencraft/prison/mines/cmd/TriggerCommand.java
@@ -1,86 +1,88 @@
package com.wolvencraft.prison.mines.cmd;
import org.bukkit.ChatColor;
import com.wolvencraft.prison.mines.PrisonMine;
import com.wolvencraft.prison.mines.mine.Mine;
import com.wolvencraft.prison.mines.util.Message;
import com.wolvencraft.prison.mines.util.Util;
public class TriggerCommand implements BaseCommand {
@Override
public boolean run(String[] args) {
if(args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase("help"))) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_ARGUMENTS); return false; }
Mine curMine = PrisonMine.getCurMine();
if(curMine == null) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_MINENOTSELECTED); return false; }
if(args[1].equalsIgnoreCase("time")) {
if(args.length == 2) {
if(curMine.getAutomaticReset()) {
curMine.setAutomaticReset(false);
Message.sendFormattedMine("Time trigger is " + ChatColor.RED + "off");
}
else {
curMine.setAutomaticReset(true);
Message.sendFormattedMine("Time trigger is " + ChatColor.GREEN + "on");
}
} else {
if(!curMine.getAutomaticReset()) {
curMine.setAutomaticReset(true);
Message.sendFormattedMine("Time trigger is " + ChatColor.GREEN + "on");
}
int time = Util.parseTime(args[2]);
if(time <= 0) { Message.sendFormattedError("Invalid time provided"); return false; }
curMine.setResetPeriod(time);
String parsedTime = Util.parseSeconds(time);
Message.sendFormattedMine("Mine will now reset every " + ChatColor.GOLD + parsedTime + ChatColor.WHITE + " minute(s)");
}
} else if(args[1].equalsIgnoreCase("composition")) {
if(args.length == 2) {
if(curMine.getCompositionReset()) {
curMine.setCompositionReset(false);
Message.sendFormattedMine("Composition trigger is " + ChatColor.RED + "off");
}
else {
curMine.setCompositionReset(true);
Message.sendFormattedMine("Composition trigger is " + ChatColor.GREEN + "on");
}
} else {
if(!curMine.getCompositionReset()) {
curMine.setCompositionReset(true);
Message.sendFormattedMine("Composition trigger is " + ChatColor.GREEN + "on");
}
String percentString = args[2];
if(percentString.endsWith("%")) percentString.substring(0, percentString.length() - 1);
- double percent = Double.parseDouble(percentString) / 100;
+ double percent = 0;
+ try {percent = Double.parseDouble(percentString) / 100; }
+ catch (NumberFormatException nfe) { Message.sendFormattedError("Invalid percent value provided"); return false; }
if(percent <= 0 || percent > 100) { Message.sendFormattedError("Invalid percent value provided"); return false; }
curMine.setCompositionPercent(percent);
Message.sendFormattedMine("Mine will reset once it is " + ChatColor.GOLD + percentString + "%" + ChatColor.WHITE + " empty");
}
} else { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_COMMAND); return false; }
return curMine.saveFile();
}
@Override
public void getHelp() {
Message.formatHeader(20, "Trigger");
Message.formatHelp("trigger", "time", "Toggles the timer on and off");
Message.formatHelp("trigger", "time <time>", "Sets the timer to the specified value");
Message.formatHelp("trigger", "composition", "Toggles the composition trigger");
Message.formatHelp("trigger", "composition <percent>", "Sets the composition percent");
}
@Override
public void getHelpLine() { Message.formatHelp("trigger help", "", "Shows the reset trigger help page", "prison.mine.edit"); }
}
| true | true | public boolean run(String[] args) {
if(args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase("help"))) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_ARGUMENTS); return false; }
Mine curMine = PrisonMine.getCurMine();
if(curMine == null) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_MINENOTSELECTED); return false; }
if(args[1].equalsIgnoreCase("time")) {
if(args.length == 2) {
if(curMine.getAutomaticReset()) {
curMine.setAutomaticReset(false);
Message.sendFormattedMine("Time trigger is " + ChatColor.RED + "off");
}
else {
curMine.setAutomaticReset(true);
Message.sendFormattedMine("Time trigger is " + ChatColor.GREEN + "on");
}
} else {
if(!curMine.getAutomaticReset()) {
curMine.setAutomaticReset(true);
Message.sendFormattedMine("Time trigger is " + ChatColor.GREEN + "on");
}
int time = Util.parseTime(args[2]);
if(time <= 0) { Message.sendFormattedError("Invalid time provided"); return false; }
curMine.setResetPeriod(time);
String parsedTime = Util.parseSeconds(time);
Message.sendFormattedMine("Mine will now reset every " + ChatColor.GOLD + parsedTime + ChatColor.WHITE + " minute(s)");
}
} else if(args[1].equalsIgnoreCase("composition")) {
if(args.length == 2) {
if(curMine.getCompositionReset()) {
curMine.setCompositionReset(false);
Message.sendFormattedMine("Composition trigger is " + ChatColor.RED + "off");
}
else {
curMine.setCompositionReset(true);
Message.sendFormattedMine("Composition trigger is " + ChatColor.GREEN + "on");
}
} else {
if(!curMine.getCompositionReset()) {
curMine.setCompositionReset(true);
Message.sendFormattedMine("Composition trigger is " + ChatColor.GREEN + "on");
}
String percentString = args[2];
if(percentString.endsWith("%")) percentString.substring(0, percentString.length() - 1);
double percent = Double.parseDouble(percentString) / 100;
if(percent <= 0 || percent > 100) { Message.sendFormattedError("Invalid percent value provided"); return false; }
curMine.setCompositionPercent(percent);
Message.sendFormattedMine("Mine will reset once it is " + ChatColor.GOLD + percentString + "%" + ChatColor.WHITE + " empty");
}
} else { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_COMMAND); return false; }
return curMine.saveFile();
}
| public boolean run(String[] args) {
if(args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase("help"))) { getHelp(); return true; }
if(args.length > 3) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_ARGUMENTS); return false; }
Mine curMine = PrisonMine.getCurMine();
if(curMine == null) { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_MINENOTSELECTED); return false; }
if(args[1].equalsIgnoreCase("time")) {
if(args.length == 2) {
if(curMine.getAutomaticReset()) {
curMine.setAutomaticReset(false);
Message.sendFormattedMine("Time trigger is " + ChatColor.RED + "off");
}
else {
curMine.setAutomaticReset(true);
Message.sendFormattedMine("Time trigger is " + ChatColor.GREEN + "on");
}
} else {
if(!curMine.getAutomaticReset()) {
curMine.setAutomaticReset(true);
Message.sendFormattedMine("Time trigger is " + ChatColor.GREEN + "on");
}
int time = Util.parseTime(args[2]);
if(time <= 0) { Message.sendFormattedError("Invalid time provided"); return false; }
curMine.setResetPeriod(time);
String parsedTime = Util.parseSeconds(time);
Message.sendFormattedMine("Mine will now reset every " + ChatColor.GOLD + parsedTime + ChatColor.WHITE + " minute(s)");
}
} else if(args[1].equalsIgnoreCase("composition")) {
if(args.length == 2) {
if(curMine.getCompositionReset()) {
curMine.setCompositionReset(false);
Message.sendFormattedMine("Composition trigger is " + ChatColor.RED + "off");
}
else {
curMine.setCompositionReset(true);
Message.sendFormattedMine("Composition trigger is " + ChatColor.GREEN + "on");
}
} else {
if(!curMine.getCompositionReset()) {
curMine.setCompositionReset(true);
Message.sendFormattedMine("Composition trigger is " + ChatColor.GREEN + "on");
}
String percentString = args[2];
if(percentString.endsWith("%")) percentString.substring(0, percentString.length() - 1);
double percent = 0;
try {percent = Double.parseDouble(percentString) / 100; }
catch (NumberFormatException nfe) { Message.sendFormattedError("Invalid percent value provided"); return false; }
if(percent <= 0 || percent > 100) { Message.sendFormattedError("Invalid percent value provided"); return false; }
curMine.setCompositionPercent(percent);
Message.sendFormattedMine("Mine will reset once it is " + ChatColor.GOLD + percentString + "%" + ChatColor.WHITE + " empty");
}
} else { Message.sendFormattedError(PrisonMine.getLanguage().ERROR_COMMAND); return false; }
return curMine.saveFile();
}
|
diff --git a/src/main/java/net/nexisonline/spade/Interpolator.java b/src/main/java/net/nexisonline/spade/Interpolator.java
index 393d294..2675159 100644
--- a/src/main/java/net/nexisonline/spade/Interpolator.java
+++ b/src/main/java/net/nexisonline/spade/Interpolator.java
@@ -1,66 +1,66 @@
package net.nexisonline.spade;
public class Interpolator {
private static int arrayindex(int x, int y, int z) {
return x << 11 | z << 7 | y;
}
/**
* Linear Interpolator
* @author PrettyPony <[email protected]>
*/
public static byte[] LinearExpand(byte[] abyte) {
// Generate the xy and yz planes of blocks by interpolation
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
if (y != 15)
{
- abyte[arrayindex(x , y + 1, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y + 3, z)], 0.25f);
- abyte[arrayindex(x, y + 2, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y + 3, z)], 0.85f);
+ abyte[arrayindex(x , y + 1, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y + 3, z)], 0.02f);
+ abyte[arrayindex(x, y + 2, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y + 3, z)], 0.98f);
}
}
}
}
// Generate the xz plane of blocks by interpolation
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z += 3)
{
if (x == 0 && z > 0)
{
abyte[arrayindex(x, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.25f);
abyte[arrayindex(x, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.85f);
}
else if (x > 0 && z > 0)
{
abyte[arrayindex(x - 1, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.25f);
abyte[arrayindex(x - 2, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.85f);
abyte[arrayindex(x, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.25f);
abyte[arrayindex(x - 1, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.25f);
abyte[arrayindex(x - 2, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.85f);
abyte[arrayindex(x, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.85f);
abyte[arrayindex(x - 1, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.25f);
abyte[arrayindex(x - 2, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.85f);
}
else if (x > 0 && z == 0)
{
abyte[arrayindex(x - 1, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.25f);
abyte[arrayindex(x - 2, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.85f);
}
}
}
}
return abyte;
}
private static byte lerp(byte a, byte b, float f) {
return (byte) (a+(b-a)*f);
}
}
| true | true | public static byte[] LinearExpand(byte[] abyte) {
// Generate the xy and yz planes of blocks by interpolation
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
if (y != 15)
{
abyte[arrayindex(x , y + 1, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y + 3, z)], 0.25f);
abyte[arrayindex(x, y + 2, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y + 3, z)], 0.85f);
}
}
}
}
// Generate the xz plane of blocks by interpolation
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z += 3)
{
if (x == 0 && z > 0)
{
abyte[arrayindex(x, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.25f);
abyte[arrayindex(x, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.85f);
}
else if (x > 0 && z > 0)
{
abyte[arrayindex(x - 1, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.25f);
abyte[arrayindex(x - 2, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.85f);
abyte[arrayindex(x, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.25f);
abyte[arrayindex(x - 1, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.25f);
abyte[arrayindex(x - 2, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.85f);
abyte[arrayindex(x, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.85f);
abyte[arrayindex(x - 1, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.25f);
abyte[arrayindex(x - 2, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.85f);
}
else if (x > 0 && z == 0)
{
abyte[arrayindex(x - 1, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.25f);
abyte[arrayindex(x - 2, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.85f);
}
}
}
}
return abyte;
}
| public static byte[] LinearExpand(byte[] abyte) {
// Generate the xy and yz planes of blocks by interpolation
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
if (y != 15)
{
abyte[arrayindex(x , y + 1, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y + 3, z)], 0.02f);
abyte[arrayindex(x, y + 2, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y + 3, z)], 0.98f);
}
}
}
}
// Generate the xz plane of blocks by interpolation
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z += 3)
{
if (x == 0 && z > 0)
{
abyte[arrayindex(x, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.25f);
abyte[arrayindex(x, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.85f);
}
else if (x > 0 && z > 0)
{
abyte[arrayindex(x - 1, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.25f);
abyte[arrayindex(x - 2, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.85f);
abyte[arrayindex(x, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.25f);
abyte[arrayindex(x - 1, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.25f);
abyte[arrayindex(x - 2, y, z - 1)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.85f);
abyte[arrayindex(x, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x, y, z - 3)], 0.85f);
abyte[arrayindex(x - 1, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.25f);
abyte[arrayindex(x - 2, y, z - 2)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z - 3)], 0.85f);
}
else if (x > 0 && z == 0)
{
abyte[arrayindex(x - 1, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.25f);
abyte[arrayindex(x - 2, y, z)] = lerp(abyte[arrayindex(x, y, z)], abyte[arrayindex(x - 3, y, z)], 0.85f);
}
}
}
}
return abyte;
}
|
diff --git a/runtime/org.eclipse.emf.texo.server/src/org/eclipse/emf/texo/server/web/WebServiceHandler.java b/runtime/org.eclipse.emf.texo.server/src/org/eclipse/emf/texo/server/web/WebServiceHandler.java
index 125574e3..0527ecdd 100644
--- a/runtime/org.eclipse.emf.texo.server/src/org/eclipse/emf/texo/server/web/WebServiceHandler.java
+++ b/runtime/org.eclipse.emf.texo.server/src/org/eclipse/emf/texo/server/web/WebServiceHandler.java
@@ -1,376 +1,376 @@
/**
* <copyright>
*
* Copyright (c) 2011 Springsite BV (The Netherlands) and others
* 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://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Martin Taal - Initial API and implementation
*
* </copyright>
*
* $Id: WebServiceHandler.java,v 1.8 2011/09/14 15:35:48 mtaal Exp $
*/
package org.eclipse.emf.texo.server.web;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.emf.texo.component.ComponentProvider;
import org.eclipse.emf.texo.component.TexoComponent;
import org.eclipse.emf.texo.server.service.DeleteModelOperation;
import org.eclipse.emf.texo.server.service.ModelOperation;
import org.eclipse.emf.texo.server.service.RetrieveModelOperation;
import org.eclipse.emf.texo.server.service.ServiceContext;
import org.eclipse.emf.texo.server.service.ServiceUtils;
import org.eclipse.emf.texo.server.service.UpdateInsertModelOperation;
import org.eclipse.emf.texo.server.store.EntityManagerObjectStore;
import org.eclipse.emf.texo.server.store.EntityManagerProvider;
/**
* The base implementation of a CRUD Rest WS. It is the basis of the XML and JSON CRUD REST functions.
*
* It is controlled by one servlet instance. One instance can be called by multiple requests, so it should not hold
* state.
*
* This class make use of the {@link ModelOperation} and the {@link ServiceContext} classes to execute the operation and
* compute the result. The {@link ServiceContext} results are processed through a {@link ServiceContextResultProcessor},
* you can set the class to use for the {@link ServiceContextResultProcessor} to for example process the resulting XML
* through a XSLT script.
*
* @author <a href="[email protected]">Martin Taal</a>
*/
public abstract class WebServiceHandler implements TexoComponent {
private String uri = null;
private ServiceContextResultProcessor serviceContextResultProcessor = ComponentProvider.getInstance().newInstance(
ServiceContextResultProcessor.class);
public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
final ServiceContext serviceContext = createServiceContext(req);
try {
final DeleteModelOperation operation = ComponentProvider.getInstance().newInstance(DeleteModelOperation.class);
operation.setServiceContext(serviceContext);
operation.execute();
setResultInResponse(serviceContext, resp);
operation.close();
} finally {
releaseEntityManager((EntityManager) serviceContext.getObjectStore().getDelegate());
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
final ServiceContext serviceContext = createServiceContext(req);
try {
final RetrieveModelOperation retrieveModelOperation = ComponentProvider.getInstance().newInstance(
RetrieveModelOperation.class);
retrieveModelOperation.setServiceContext(serviceContext);
retrieveModelOperation.execute();
setResultInResponse(serviceContext, resp);
retrieveModelOperation.close();
} finally {
releaseEntityManager((EntityManager) serviceContext.getObjectStore().getDelegate());
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServiceContext serviceContext = createServiceContext(req);
if (serviceContext.isErrorOccured()) {
setResultInResponse(serviceContext, resp);
return;
}
try {
final UpdateInsertModelOperation operation = ComponentProvider.getInstance().newInstance(
UpdateInsertModelOperation.class);
operation.setServiceContext(serviceContext);
operation.execute();
setResultInResponse(serviceContext, resp);
operation.close();
} finally {
releaseEntityManager((EntityManager) serviceContext.getObjectStore().getDelegate());
}
}
/**
* This implementation calls the {@link WebServiceHandler#doPost(HttpServletRequest, HttpServletResponse)} method.
*/
public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doPost(req, resp);
}
/**
* Create a web service specific implementation of the {@link ServiceContext}. Calls {@link #createServiceContext()}
* and then copies information from the {@link HttpServletRequest} to the service context. Is called once for each
* request.
*/
protected ServiceContext createServiceContext(HttpServletRequest request) {
final String requestUrl = request.getRequestURL().toString();
EntityManager entityManager = null;
ServiceContext serviceContext = null;
try {
serviceContext = createServiceContext();
- entityManager = EntityManagerProvider.getInstance().createEntityManager();
+ entityManager = createEntityManager();
serviceContext.setRequestURI(requestUrl);
serviceContext.setServiceRequestURI(request.getPathInfo());
final EntityManagerObjectStore emObjectStore = ComponentProvider.getInstance().newInstance(
EntityManagerObjectStore.class);
emObjectStore.setEntityManager(entityManager);
// find the uri on the basis of the request uri
String objectStoreUri = getUri() == null ? request.getContextPath() : getUri();
if (getUri() == null) {
final int contextIndex = requestUrl.indexOf(request.getContextPath() + "/"); //$NON-NLS-1$
objectStoreUri = requestUrl.substring(0, contextIndex) + request.getContextPath() + request.getServletPath();
} else {
objectStoreUri = getUri();
}
emObjectStore.setUri(objectStoreUri);
final Map<String, Object> params = new HashMap<String, Object>();
for (Enumeration<String> enumeration = request.getParameterNames(); enumeration.hasMoreElements();) {
final String name = enumeration.nextElement();
final String[] vals = request.getParameterValues(name);
if (vals.length == 1) {
params.put(name, vals[0]);
} else {
params.put(name, vals);
}
}
serviceContext.setObjectStore(emObjectStore);
serviceContext.setRequestParameters(params);
serviceContext.setRequestContent(ServiceUtils.toString(request.getInputStream(), request.getCharacterEncoding()));
return serviceContext;
} catch (Throwable t) {
if (entityManager != null) {
releaseEntityManager(entityManager);
}
if (serviceContext != null) {
serviceContext.createErrorResult(t);
return serviceContext;
}
throw new IllegalStateException(t);
}
}
/**
* Calls the {@link ServiceContext#getResponseContent()} and {@link ServiceContext#getResponseCode()} and the
* {@link ServiceContext#getResponseContentType()}.
*
* The {@link ServiceContextResultProcessor} is used to post process the results of these methods before writing them
* to the {@link HttpServletResponse}.
*/
protected void setResultInResponse(ServiceContext serviceContext, HttpServletResponse resp) throws IOException {
serviceContextResultProcessor.startOfRequest();
serviceContextResultProcessor.setServiceContext(serviceContext);
final String result = serviceContextResultProcessor.getResponseContent();
// must be done before writing and closing the writer
resp.setContentType(serviceContextResultProcessor.getResponseContentType());
resp.setStatus(serviceContextResultProcessor.getResponseCode());
resp.getWriter().write(result);
resp.getWriter().close();
serviceContextResultProcessor.endOfRequest();
}
/**
* Create a web service specific service context.
*/
protected abstract ServiceContext createServiceContext();
/**
* This method is called once at the beginning of the processing of a request. It should return a new instance of the
* entity manager normally.
*
* As a default calls {@link EntityManagerProvider#createEntityManager()}.
*
* Can be overridden for specific logic to get the entity manager. In that case also override the
* {@link #releaseEntityManager(EntityManager)}.
*/
protected EntityManager createEntityManager() {
return EntityManagerProvider.getInstance().createEntityManager();
}
/**
* Is called once at the end of the processing of a request.
*
* As a default calls {@link EntityManagerProvider#releaseEntityManager(EntityManager)}.
*/
protected void releaseEntityManager(EntityManager entityManager) {
EntityManagerProvider.getInstance().releaseEntityManager(entityManager);
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
/**
* Can be used to let the response be processed before it is written to the {@link HttpServletResponse}.
*
* This owning {@link WebServiceHandler} has one instance of this class which is re-used in different methods. Note
* the {@link WebServiceHandler} is not thread-safe and should only be used in one request/thread and then discarded.
* The same applies to the {@link ServiceContextResultProcessor}. The {@link ServiceContextResultProcessor} is
* notified of the start of the request and the end of the request processing.
*
* The ServletContextResultWrapper can also override the status code and the response type.
*
* @author mtaal
*/
public static class ServiceContextResultProcessor implements TexoComponent {
private ServiceContext serviceContext;
/**
* Calls the {@link ServiceContext#getResponseContent()} and returns the result.
*/
public String getResponseContent() {
return serviceContext.getResponseContent();
}
/**
* Calls the {@link ServiceContext#getResponseCode()} and returns the result.
*/
public int getResponseCode() {
return serviceContext.getResponseCode();
}
/**
* Calls the {@link ServiceContext#getResponseContentType()} and returns the result.
*/
public String getResponseContentType() {
return serviceContext.getResponseContentType();
}
public ServiceContext getServiceContext() {
return serviceContext;
}
public void setServiceContext(ServiceContext serviceContext) {
this.serviceContext = serviceContext;
}
/**
* Is called at the beginning of the request.
*/
public void startOfRequest() {
}
/**
* Is called at the end of the request.
*/
public void endOfRequest() {
}
}
/**
* A subclass of the {@link ServletContextResultWrapper} which processes the result through a XSLT template.
*
* @author mtaal
*/
public static class XSLTServiceContextResultProcessor extends ServiceContextResultProcessor {
private boolean errorOccured = false;
private String templateClassPathLocation = null;
private Map<String, Object> parameters = new HashMap<String, Object>();
@Override
public String getResponseContent() {
try {
return applyTemplate(getServiceContext().getResponseContent(), getTemplateClassPathLocation());
} catch (Exception e) {
errorOccured = true;
throw new IllegalStateException(e);
}
}
@Override
public int getResponseCode() {
if (errorOccured) {
return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
return getServiceContext().getResponseCode();
}
public void addParameter(String name, Object value) {
parameters.put(name, value);
}
private String applyTemplate(String xml, String template) {
try {
final InputStream is = this.getClass().getResourceAsStream(template);
final TransformerFactory factory = TransformerFactory.newInstance();
final Transformer transformer = factory.newTransformer(new StreamSource(is));
for (String key : parameters.keySet()) {
transformer.setParameter(key, parameters.get(key));
}
final StringWriter sw = new StringWriter();
final StreamResult response = new StreamResult(sw);
transformer.transform(new StreamSource(new StringReader(xml)), response);
return sw.toString();
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}
public String getTemplateClassPathLocation() {
return templateClassPathLocation;
}
public void setTemplateClassPathLocation(String templateClassPathLocation) {
this.templateClassPathLocation = templateClassPathLocation;
}
}
public ServiceContextResultProcessor getServiceContextResultProcessor() {
return serviceContextResultProcessor;
}
public void setServiceContextResultProcessor(ServiceContextResultProcessor serviceContextResultProcessor) {
this.serviceContextResultProcessor = serviceContextResultProcessor;
}
}
| true | true | protected ServiceContext createServiceContext(HttpServletRequest request) {
final String requestUrl = request.getRequestURL().toString();
EntityManager entityManager = null;
ServiceContext serviceContext = null;
try {
serviceContext = createServiceContext();
entityManager = EntityManagerProvider.getInstance().createEntityManager();
serviceContext.setRequestURI(requestUrl);
serviceContext.setServiceRequestURI(request.getPathInfo());
final EntityManagerObjectStore emObjectStore = ComponentProvider.getInstance().newInstance(
EntityManagerObjectStore.class);
emObjectStore.setEntityManager(entityManager);
// find the uri on the basis of the request uri
String objectStoreUri = getUri() == null ? request.getContextPath() : getUri();
if (getUri() == null) {
final int contextIndex = requestUrl.indexOf(request.getContextPath() + "/"); //$NON-NLS-1$
objectStoreUri = requestUrl.substring(0, contextIndex) + request.getContextPath() + request.getServletPath();
} else {
objectStoreUri = getUri();
}
emObjectStore.setUri(objectStoreUri);
final Map<String, Object> params = new HashMap<String, Object>();
for (Enumeration<String> enumeration = request.getParameterNames(); enumeration.hasMoreElements();) {
final String name = enumeration.nextElement();
final String[] vals = request.getParameterValues(name);
if (vals.length == 1) {
params.put(name, vals[0]);
} else {
params.put(name, vals);
}
}
serviceContext.setObjectStore(emObjectStore);
serviceContext.setRequestParameters(params);
serviceContext.setRequestContent(ServiceUtils.toString(request.getInputStream(), request.getCharacterEncoding()));
return serviceContext;
} catch (Throwable t) {
if (entityManager != null) {
releaseEntityManager(entityManager);
}
if (serviceContext != null) {
serviceContext.createErrorResult(t);
return serviceContext;
}
throw new IllegalStateException(t);
}
}
| protected ServiceContext createServiceContext(HttpServletRequest request) {
final String requestUrl = request.getRequestURL().toString();
EntityManager entityManager = null;
ServiceContext serviceContext = null;
try {
serviceContext = createServiceContext();
entityManager = createEntityManager();
serviceContext.setRequestURI(requestUrl);
serviceContext.setServiceRequestURI(request.getPathInfo());
final EntityManagerObjectStore emObjectStore = ComponentProvider.getInstance().newInstance(
EntityManagerObjectStore.class);
emObjectStore.setEntityManager(entityManager);
// find the uri on the basis of the request uri
String objectStoreUri = getUri() == null ? request.getContextPath() : getUri();
if (getUri() == null) {
final int contextIndex = requestUrl.indexOf(request.getContextPath() + "/"); //$NON-NLS-1$
objectStoreUri = requestUrl.substring(0, contextIndex) + request.getContextPath() + request.getServletPath();
} else {
objectStoreUri = getUri();
}
emObjectStore.setUri(objectStoreUri);
final Map<String, Object> params = new HashMap<String, Object>();
for (Enumeration<String> enumeration = request.getParameterNames(); enumeration.hasMoreElements();) {
final String name = enumeration.nextElement();
final String[] vals = request.getParameterValues(name);
if (vals.length == 1) {
params.put(name, vals[0]);
} else {
params.put(name, vals);
}
}
serviceContext.setObjectStore(emObjectStore);
serviceContext.setRequestParameters(params);
serviceContext.setRequestContent(ServiceUtils.toString(request.getInputStream(), request.getCharacterEncoding()));
return serviceContext;
} catch (Throwable t) {
if (entityManager != null) {
releaseEntityManager(entityManager);
}
if (serviceContext != null) {
serviceContext.createErrorResult(t);
return serviceContext;
}
throw new IllegalStateException(t);
}
}
|
diff --git a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ViewRequisition.java b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ViewRequisition.java
index ab60e4df8f..8ae2da3f0e 100644
--- a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ViewRequisition.java
+++ b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ViewRequisition.java
@@ -1,114 +1,115 @@
/*
* Copyright © 2013 VillageReach. All Rights Reserved. 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.openlmis.functional;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.pageobjects.*;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class ViewRequisition extends TestCaseHelper {
@BeforeMethod(groups = {"functional"})
public void setUp() throws Exception {
super.setup();
}
@Test(groups = {"functional"}, dataProvider = "Data-Provider-Function-Positive")
public void testViewRequisition(String program, String userSIC, String password) throws Exception {
setupTestDataToInitiateRnR(program, userSIC);
dbWrapper.assignRight("store in-charge", "APPROVE_REQUISITION");
dbWrapper.assignRight("store in-charge", "CONVERT_TO_ORDER");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
HomePage homePage1 = initiateRnRPage.clickHome();
ViewRequisitionPage viewRequisitionPage = homePage1.navigateViewRequisition();
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
dbWrapper.insertValuesInRequisition();
dbWrapper.updateRequisitionStatus("SUBMITTED");
viewRequisitionPage.enterViewSearchCriteria();
viewRequisitionPage.clickSearch();
viewRequisitionPage.verifyNoRequisitionFound();
dbWrapper.updateRequisitionStatus("AUTHORIZED");
viewRequisitionPage.clickSearch();
viewRequisitionPage.clickRnRList();
HomePage homePageAuthorized = viewRequisitionPage.verifyFieldsPreApproval("12.50", "1");
ViewRequisitionPage viewRequisitionPageAuthorized = homePageAuthorized.navigateViewRequisition();
viewRequisitionPageAuthorized.enterViewSearchCriteria();
viewRequisitionPageAuthorized.clickSearch();
viewRequisitionPageAuthorized.verifyStatus("AUTHORIZED");
viewRequisitionPageAuthorized.clickRnRList();
HomePage homePageInApproval = viewRequisitionPageAuthorized.verifyFieldsPreApproval("12.50", "1");
dbWrapper.updateRequisitionStatus("IN_APPROVAL");
ViewRequisitionPage viewRequisitionPageInApproval = homePageInApproval.navigateViewRequisition();
viewRequisitionPageInApproval.enterViewSearchCriteria();
viewRequisitionPageInApproval.clickSearch();
viewRequisitionPageInApproval.verifyStatus("IN_APPROVAL");
ApprovePage approvePageTopSNUser = homePageInApproval.navigateToApprove();
approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCostViewRequisition("20");
approvePageTopSNUser.addComments("Dummy Comments");
approvePageTopSNUser.approveRequisition();
+ approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
ViewRequisitionPage viewRequisitionPageApproved = homePageInApproval.navigateViewRequisition();
viewRequisitionPageApproved.enterViewSearchCriteria();
viewRequisitionPageApproved.clickSearch();
viewRequisitionPageApproved.verifyStatus("APPROVED");
viewRequisitionPageApproved.clickRnRList();
viewRequisitionPageApproved.verifyComment("Dummy Comments", userSIC,1);
viewRequisitionPageApproved.verifyCommentBoxNotPresent();
HomePage homePageApproved = viewRequisitionPageApproved.verifyFieldsPostApproval("25.00", "1");
dbWrapper.updateRequisition("F10");
OrderPage orderPage = homePageApproved.navigateConvertToOrder();
orderPage.convertToOrder();
ViewRequisitionPage viewRequisitionPageOrdered = homePageApproved.navigateViewRequisition();
viewRequisitionPageOrdered.enterViewSearchCriteria();
viewRequisitionPageOrdered.clickSearch();
viewRequisitionPageOrdered.verifyStatus("ORDERED");
viewRequisitionPageOrdered.clickRnRList();
viewRequisitionPageOrdered.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageOrdered.verifyApprovedQuantityFieldPresent();
}
@AfterMethod(groups = {"functional"})
public void tearDown() throws Exception {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
@DataProvider(name = "Data-Provider-Function-Positive")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"HIV", "storeincharge", "Admin123"}
};
}
}
| true | true | public void testViewRequisition(String program, String userSIC, String password) throws Exception {
setupTestDataToInitiateRnR(program, userSIC);
dbWrapper.assignRight("store in-charge", "APPROVE_REQUISITION");
dbWrapper.assignRight("store in-charge", "CONVERT_TO_ORDER");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
HomePage homePage1 = initiateRnRPage.clickHome();
ViewRequisitionPage viewRequisitionPage = homePage1.navigateViewRequisition();
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
dbWrapper.insertValuesInRequisition();
dbWrapper.updateRequisitionStatus("SUBMITTED");
viewRequisitionPage.enterViewSearchCriteria();
viewRequisitionPage.clickSearch();
viewRequisitionPage.verifyNoRequisitionFound();
dbWrapper.updateRequisitionStatus("AUTHORIZED");
viewRequisitionPage.clickSearch();
viewRequisitionPage.clickRnRList();
HomePage homePageAuthorized = viewRequisitionPage.verifyFieldsPreApproval("12.50", "1");
ViewRequisitionPage viewRequisitionPageAuthorized = homePageAuthorized.navigateViewRequisition();
viewRequisitionPageAuthorized.enterViewSearchCriteria();
viewRequisitionPageAuthorized.clickSearch();
viewRequisitionPageAuthorized.verifyStatus("AUTHORIZED");
viewRequisitionPageAuthorized.clickRnRList();
HomePage homePageInApproval = viewRequisitionPageAuthorized.verifyFieldsPreApproval("12.50", "1");
dbWrapper.updateRequisitionStatus("IN_APPROVAL");
ViewRequisitionPage viewRequisitionPageInApproval = homePageInApproval.navigateViewRequisition();
viewRequisitionPageInApproval.enterViewSearchCriteria();
viewRequisitionPageInApproval.clickSearch();
viewRequisitionPageInApproval.verifyStatus("IN_APPROVAL");
ApprovePage approvePageTopSNUser = homePageInApproval.navigateToApprove();
approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCostViewRequisition("20");
approvePageTopSNUser.addComments("Dummy Comments");
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
ViewRequisitionPage viewRequisitionPageApproved = homePageInApproval.navigateViewRequisition();
viewRequisitionPageApproved.enterViewSearchCriteria();
viewRequisitionPageApproved.clickSearch();
viewRequisitionPageApproved.verifyStatus("APPROVED");
viewRequisitionPageApproved.clickRnRList();
viewRequisitionPageApproved.verifyComment("Dummy Comments", userSIC,1);
viewRequisitionPageApproved.verifyCommentBoxNotPresent();
HomePage homePageApproved = viewRequisitionPageApproved.verifyFieldsPostApproval("25.00", "1");
dbWrapper.updateRequisition("F10");
OrderPage orderPage = homePageApproved.navigateConvertToOrder();
orderPage.convertToOrder();
ViewRequisitionPage viewRequisitionPageOrdered = homePageApproved.navigateViewRequisition();
viewRequisitionPageOrdered.enterViewSearchCriteria();
viewRequisitionPageOrdered.clickSearch();
viewRequisitionPageOrdered.verifyStatus("ORDERED");
viewRequisitionPageOrdered.clickRnRList();
viewRequisitionPageOrdered.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageOrdered.verifyApprovedQuantityFieldPresent();
}
| public void testViewRequisition(String program, String userSIC, String password) throws Exception {
setupTestDataToInitiateRnR(program, userSIC);
dbWrapper.assignRight("store in-charge", "APPROVE_REQUISITION");
dbWrapper.assignRight("store in-charge", "CONVERT_TO_ORDER");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateAndInitiateRnr(program);
InitiateRnRPage initiateRnRPage = homePage.clickProceed();
HomePage homePage1 = initiateRnRPage.clickHome();
ViewRequisitionPage viewRequisitionPage = homePage1.navigateViewRequisition();
viewRequisitionPage.verifyElementsOnViewRequisitionScreen();
dbWrapper.insertValuesInRequisition();
dbWrapper.updateRequisitionStatus("SUBMITTED");
viewRequisitionPage.enterViewSearchCriteria();
viewRequisitionPage.clickSearch();
viewRequisitionPage.verifyNoRequisitionFound();
dbWrapper.updateRequisitionStatus("AUTHORIZED");
viewRequisitionPage.clickSearch();
viewRequisitionPage.clickRnRList();
HomePage homePageAuthorized = viewRequisitionPage.verifyFieldsPreApproval("12.50", "1");
ViewRequisitionPage viewRequisitionPageAuthorized = homePageAuthorized.navigateViewRequisition();
viewRequisitionPageAuthorized.enterViewSearchCriteria();
viewRequisitionPageAuthorized.clickSearch();
viewRequisitionPageAuthorized.verifyStatus("AUTHORIZED");
viewRequisitionPageAuthorized.clickRnRList();
HomePage homePageInApproval = viewRequisitionPageAuthorized.verifyFieldsPreApproval("12.50", "1");
dbWrapper.updateRequisitionStatus("IN_APPROVAL");
ViewRequisitionPage viewRequisitionPageInApproval = homePageInApproval.navigateViewRequisition();
viewRequisitionPageInApproval.enterViewSearchCriteria();
viewRequisitionPageInApproval.clickSearch();
viewRequisitionPageInApproval.verifyStatus("IN_APPROVAL");
ApprovePage approvePageTopSNUser = homePageInApproval.navigateToApprove();
approvePageTopSNUser.verifyAndClickRequisitionPresentForApproval();
approvePageTopSNUser.editApproveQuantityAndVerifyTotalCostViewRequisition("20");
approvePageTopSNUser.addComments("Dummy Comments");
approvePageTopSNUser.approveRequisition();
approvePageTopSNUser.clickOk();
approvePageTopSNUser.verifyNoRequisitionPendingMessage();
ViewRequisitionPage viewRequisitionPageApproved = homePageInApproval.navigateViewRequisition();
viewRequisitionPageApproved.enterViewSearchCriteria();
viewRequisitionPageApproved.clickSearch();
viewRequisitionPageApproved.verifyStatus("APPROVED");
viewRequisitionPageApproved.clickRnRList();
viewRequisitionPageApproved.verifyComment("Dummy Comments", userSIC,1);
viewRequisitionPageApproved.verifyCommentBoxNotPresent();
HomePage homePageApproved = viewRequisitionPageApproved.verifyFieldsPostApproval("25.00", "1");
dbWrapper.updateRequisition("F10");
OrderPage orderPage = homePageApproved.navigateConvertToOrder();
orderPage.convertToOrder();
ViewRequisitionPage viewRequisitionPageOrdered = homePageApproved.navigateViewRequisition();
viewRequisitionPageOrdered.enterViewSearchCriteria();
viewRequisitionPageOrdered.clickSearch();
viewRequisitionPageOrdered.verifyStatus("ORDERED");
viewRequisitionPageOrdered.clickRnRList();
viewRequisitionPageOrdered.verifyFieldsPostApproval("25.00", "1");
viewRequisitionPageOrdered.verifyApprovedQuantityFieldPresent();
}
|
diff --git a/src/org/jetbrains/plugins/clojure/editor/braceHighlighter/ClojureBraceHighlighter.java b/src/org/jetbrains/plugins/clojure/editor/braceHighlighter/ClojureBraceHighlighter.java
index ffec6e9..bbd7876 100644
--- a/src/org/jetbrains/plugins/clojure/editor/braceHighlighter/ClojureBraceHighlighter.java
+++ b/src/org/jetbrains/plugins/clojure/editor/braceHighlighter/ClojureBraceHighlighter.java
@@ -1,115 +1,117 @@
package org.jetbrains.plugins.clojure.editor.braceHighlighter;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.event.EditorEventMulticaster;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.ex.EditorEventMulticasterEx;
import com.intellij.openapi.editor.ex.FocusChangeListener;
import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.util.Alarm;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.clojure.settings.ClojureProjectSettings;
/**
* @author ilyas
*/
public class ClojureBraceHighlighter extends AbstractProjectComponent {
private final Alarm myAlarm = new Alarm();
static Key<Boolean> MUST_BE_REHIGHLIGHTED = new Key<Boolean>("EDITOR_IS_REHIGHLIGHTED");
@NotNull
@Override
public String getComponentName() {
return "ClojureBraceHighlighter";
}
protected ClojureBraceHighlighter(Project project) {
super(project);
}
public void projectOpened() {
StartupManager.getInstance(myProject).registerPostStartupActivity(new DumbAwareRunnable() {
public void run() {
doInit();
}
});
}
private void doInit() {
final EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
DocumentListener documentListener = new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
myAlarm.cancelAllRequests();
Editor[] editors = EditorFactory.getInstance().getEditors(e.getDocument(), myProject);
for (Editor editor : editors) {
- updateBraces(editor, myAlarm, e);
+ if (editor.getProject() != null) {
+ updateBraces(editor, myAlarm, e);
+ }
}
}
};
eventMulticaster.addDocumentListener(documentListener, myProject);
final FocusChangeListener myFocusChangeListener = new FocusChangeListener() {
public void focusGained(Editor editor) {
updateBraces(editor, myAlarm, null);
}
public void focusLost(Editor editor) {
// do nothing
}
};
((EditorEventMulticasterEx) eventMulticaster).addFocusChangeListner(myFocusChangeListener);
myProject.getMessageBus().connect(myProject).subscribe(
FileEditorManagerListener.FILE_EDITOR_MANAGER,
new FileEditorManagerAdapter() {
public void selectionChanged(FileEditorManagerEvent e) {
myAlarm.cancelAllRequests();
}
});
}
static void updateBraces(@NotNull final Editor editor, @NotNull final Alarm alarm, final DocumentEvent e) {
final Project project = editor.getProject();
if (!ClojureProjectSettings.getInstance(project).coloredParentheses) {
final Boolean data = editor.getUserData(MUST_BE_REHIGHLIGHTED);
if (data == null || data) {
EditorFactory.getInstance().refreshAllEditors();
FileStatusManager.getInstance(project).fileStatusesChanged();
DaemonCodeAnalyzer.getInstance(project).settingsChanged();
}
editor.putUserData(MUST_BE_REHIGHLIGHTED, false);
return;
}
editor.putUserData(MUST_BE_REHIGHLIGHTED, true);
final Document document = editor.getDocument();
if (document instanceof DocumentEx && ((DocumentEx) document).isInBulkUpdate()) return;
ClojureBraceHighlightingHandler.lookForInjectedAndHighlightInOtherThread(editor, alarm, new Processor<ClojureBraceHighlightingHandler>() {
public boolean process(final ClojureBraceHighlightingHandler handler) {
handler.updateBraces(e);
return false;
}
});
}
}
| true | true | private void doInit() {
final EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
DocumentListener documentListener = new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
myAlarm.cancelAllRequests();
Editor[] editors = EditorFactory.getInstance().getEditors(e.getDocument(), myProject);
for (Editor editor : editors) {
updateBraces(editor, myAlarm, e);
}
}
};
eventMulticaster.addDocumentListener(documentListener, myProject);
final FocusChangeListener myFocusChangeListener = new FocusChangeListener() {
public void focusGained(Editor editor) {
updateBraces(editor, myAlarm, null);
}
public void focusLost(Editor editor) {
// do nothing
}
};
((EditorEventMulticasterEx) eventMulticaster).addFocusChangeListner(myFocusChangeListener);
myProject.getMessageBus().connect(myProject).subscribe(
FileEditorManagerListener.FILE_EDITOR_MANAGER,
new FileEditorManagerAdapter() {
public void selectionChanged(FileEditorManagerEvent e) {
myAlarm.cancelAllRequests();
}
});
}
| private void doInit() {
final EditorEventMulticaster eventMulticaster = EditorFactory.getInstance().getEventMulticaster();
DocumentListener documentListener = new DocumentAdapter() {
public void documentChanged(DocumentEvent e) {
myAlarm.cancelAllRequests();
Editor[] editors = EditorFactory.getInstance().getEditors(e.getDocument(), myProject);
for (Editor editor : editors) {
if (editor.getProject() != null) {
updateBraces(editor, myAlarm, e);
}
}
}
};
eventMulticaster.addDocumentListener(documentListener, myProject);
final FocusChangeListener myFocusChangeListener = new FocusChangeListener() {
public void focusGained(Editor editor) {
updateBraces(editor, myAlarm, null);
}
public void focusLost(Editor editor) {
// do nothing
}
};
((EditorEventMulticasterEx) eventMulticaster).addFocusChangeListner(myFocusChangeListener);
myProject.getMessageBus().connect(myProject).subscribe(
FileEditorManagerListener.FILE_EDITOR_MANAGER,
new FileEditorManagerAdapter() {
public void selectionChanged(FileEditorManagerEvent e) {
myAlarm.cancelAllRequests();
}
});
}
|
diff --git a/src/Player.java b/src/Player.java
index 92a2481..1ed32ba 100644
--- a/src/Player.java
+++ b/src/Player.java
@@ -1,1400 +1,1403 @@
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minecraft.server.MinecraftServer;
/**
* Player.java - Interface for eo so mods don't have to update often.
*
* @author James
*/
public class Player extends HumanEntity implements MessageReceiver {
private static final Logger log = Logger.getLogger("Minecraft");
private int id = -1;
private String prefix = "";
private String[] commands = new String[] { "" };
private ArrayList<String> groups = new ArrayList<String>();
private String[] ips = new String[] { "" };
private boolean ignoreRestrictions = false;
private boolean admin = false;
private boolean canModifyWorld = false;
private boolean muted = false;
private PlayerInventory inventory;
private List<String> onlyOneUseKits = new ArrayList<String>();
private Pattern badChatPattern = Pattern.compile("[^ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[\\\\\\]^_'abcdefghijklmnopqrstuvwxyz{|}~\u2302\u00C7\u00FC\u00E9\u00E2\u00E4\u00E0\u00E5\u00E7\u00EA\u00EB\u00E8\u00EF\u00EE\u00EC\u00C4\u00C5\u00C9\u00E6\u00C6\u00F4\u00F6\u00F2\u00FB\u00F9\u00FF\u00D6\u00DC\u00F8\u00A3\u00D8\u00D7\u0192\u00E1\u00ED\u00F3\u00FA\u00F1\u00D1\u00AA\u00BA\u00BF\u00AE\u00AC\u00BD\u00BC\u00A1\u00AB\u00BB]");
/**
* Creates an empty player. Add the player by calling {@link #setUser(es)}
*/
public Player() {
}
public Player(OEntityPlayerMP player) {
setUser(player);
}
/**
* Returns the entity we're wrapping.
*
* @return
*/
public OEntityPlayerMP getEntity() {
return (OEntityPlayerMP) entity;
}
/**
* Returns if the player is still connected
*
* @return
*/
public boolean isConnected() {
return !getEntity().a.c;
}
/**
* Kicks player with the specified reason
*
* @param reason
*/
public void kick(String reason) {
getEntity().a.a(reason);
}
/**
* Sends player a notification
*
* @param message
*/
public void notify(String message) {
if (message.length() > 0)
sendMessage(Colors.Rose + message);
}
/**
* Sends a message to the player
*
* @param message
*/
public void sendMessage(String message) {
getEntity().a.msg(message);
}
/**
* Gives an item to the player
*
* @param item
*/
public void giveItem(Item item) {
inventory.addItem(item);
inventory.update();
}
/**
* Makes player send message.
*
* @param message
*/
public void chat(String message) {
if (message.length() > 100) {
kick("Chat message too long");
return;
}
message = message.trim();
Matcher m = badChatPattern.matcher(message);
if (m.find()) {
kick("Illegal characters '" + m.group() + "' hex: " + Integer.toHexString(message.charAt(m.start())) + " in chat");
return;
}
if (message.startsWith("/"))
command(message);
else {
if (isMuted()) {
sendMessage(Colors.Rose + "You are currently muted.");
return;
}
if ((Boolean) etc.getLoader().callHook(PluginLoader.Hook.CHAT, new Object[] { this, message }))
return;
String chat = "<" + getColor() + getName() + Colors.White + "> " + message;
log.log(Level.INFO, "<" + getName() + "> " + message);
etc.getServer().messageAll(chat);
}
}
/**
* Makes player use command.
*
* @param command
*
*/
public void command(String command) {
try {
if (etc.getInstance().isLogging())
log.info("Command used by " + getName() + " " + command);
String[] split = command.split(" ");
String cmd = split[0];
if ((Boolean) etc.getLoader().callHook(PluginLoader.Hook.COMMAND, new Object[] { this, split }))
return; // No need to go on, commands were parsed.
if (!canUseCommand(cmd) && !cmd.startsWith("/#")) {
if (etc.getInstance().showUnknownCommand())
sendMessage(Colors.Rose + "Unknown command.");
return;
}
// Remove '/' before checking.
if (ServerConsoleCommands.parseServerConsoleCommand(this, cmd.substring(1), split)) {
// Command parsed successfully...
} else if (cmd.equalsIgnoreCase("/help")) {
// Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().getCommands().entrySet())
if (canUseCommand(entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getDataSource().hasKits())
continue;
if (entry.getKey().equals("/listwarps") && !etc.getDataSource().hasWarps())
continue;
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
sendMessage(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2)
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0)
amount = (amount - 1) * 7;
else
amount = 0;
for (int i = amount; i < amount + 7; i++)
if (availableCommands.size() > i)
sendMessage(Colors.Rose + availableCommands.get(i));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Not a valid page number.");
}
else
for (int i = 0; i < 7; i++)
if (availableCommands.size() > i)
sendMessage(Colors.Rose + availableCommands.get(i));
} else if (cmd.equalsIgnoreCase("/mute")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (player.toggleMute())
sendMessage(Colors.Rose + "player was muted");
else
sendMessage(Colors.Rose + "player was unmuted");
} else
sendMessage(Colors.Rose + "Can't find player " + split[1]);
} else if ((cmd.equalsIgnoreCase("/msg") || cmd.equalsIgnoreCase("/tell")) || cmd.equalsIgnoreCase("/m")) {
if (split.length < 3) {
sendMessage(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (isMuted()) {
sendMessage(Colors.Rose + "You are currently muted.");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (player.getName().equals(getName())) {
sendMessage(Colors.Rose + "You can't message yourself!");
return;
}
player.sendMessage("(MSG) " + getColor() + "<" + getName() + "> " + Colors.White + etc.combineSplit(2, split, " "));
sendMessage("(MSG) " + getColor() + "<" + getName() + "> " + Colors.White + etc.combineSplit(2, split, " "));
} else
sendMessage(Colors.Rose + "Couldn't find player " + split[1]);
} else if (cmd.equalsIgnoreCase("/kit") && etc.getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
sendMessage(Colors.Rose + "Available kits" + Colors.White + ": " + etc.getDataSource().getKitNames(this));
return;
}
Player toGive = this;
if (split.length > 2 && canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[2]);
Kit kit = etc.getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!isInGroup(kit.Group) && !kit.Group.equals(""))
sendMessage(Colors.Rose + "That kit does not exist.");
else if (onlyOneUseKits.contains(kit.Name))
sendMessage(Colors.Rose + "You can only get this kit once per login.");
else if (MinecraftServer.b.containsKey(getName() + " " + kit.Name))
sendMessage(Colors.Rose + "You can't get this kit again for a while.");
else {
if (!canIgnoreRestrictions())
if (kit.Delay >= 0)
MinecraftServer.b.put(getName() + " " + kit.Name, kit.Delay);
else
onlyOneUseKits.add(kit.Name);
log.info(getName() + " got a kit!");
toGive.sendMessage(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet())
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getDataSource().getItem(entry.getKey());
}
toGive.giveItem(itemId, kit.IDs.get(entry.getKey()));
} catch (Exception e1) {
log.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
sendMessage(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
} else
sendMessage(Colors.Rose + "That kit does not exist.");
} else
sendMessage(Colors.Rose + "That user does not exist.");
} else if (cmd.equalsIgnoreCase("/tp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (getName().equalsIgnoreCase(player.getName())) {
sendMessage(Colors.Rose + "You're already here!");
return;
}
log.info(getName() + " teleported to " + player.getName());
teleportTo(player);
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if ((cmd.equalsIgnoreCase("/tphere") || cmd.equalsIgnoreCase("/s"))) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (getName().equalsIgnoreCase(player.getName())) {
sendMessage(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
log.info(getName() + " teleported " + player.getName() + " to their self.");
player.teleportTo(this);
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/playerlist") || cmd.equalsIgnoreCase("/who"))
sendMessage(Colors.Rose + "Player list (" + etc.getMCServer().f.b.size() + "/" + etc.getInstance().getPlayerLimit() + "): " + Colors.White + etc.getMCServer().f.c());
else if (cmd.equalsIgnoreCase("/item") || cmd.equalsIgnoreCase("/i") || cmd.equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (canIgnoreRestrictions())
sendMessage(Colors.Rose + "Correct usage is: /item [itemid] <amount> <damage> <player> (optional)");
else
sendMessage(Colors.Rose + "Correct usage is: /item [itemid] <amount> <damage>");
return;
}
Player toGive = this;
int itemId = 0, amount = 1, damage = 0;
try {
if (split.length > 1)
try {
itemId = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
itemId = etc.getDataSource().getItem(split[1]);
}
if (split.length > 2) {
amount = Integer.parseInt(split[2]);
if (amount <= 0 && !isAdmin())
amount = 1;
if (amount > 64 && !canIgnoreRestrictions())
amount = 64;
if (amount > 1024)
amount = 1024; // 16 stacks worth. More than enough.
}
if (split.length == 4) {
int temp = -1;
try {
temp = Integer.parseInt(split[3]);
} catch (NumberFormatException n) {
if (canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[3]);
}
if (temp > -1 && temp < 50)
damage = temp;
} else if (split.length == 5) {
damage = Integer.parseInt(split[3]);
if (damage < 0 && damage > 49)
damage = 0;
if (canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[4]);
}
} catch (NumberFormatException localNumberFormatException) {
sendMessage(Colors.Rose + "Improper ID and/or amount.");
return;
}
if (toGive != null) {
boolean allowedItem = false;
if (!etc.getInstance().getAllowedItems().isEmpty() && etc.getInstance().getAllowedItems().contains(itemId))
allowedItem = true;
else
allowedItem = true;
if (!etc.getInstance().getDisallowedItems().isEmpty() && etc.getInstance().getDisallowedItems().contains(itemId))
allowedItem = false;
if (Item.isValidItem(itemId)) {
if (allowedItem || canIgnoreRestrictions()) {
Item i = new Item(itemId, amount, -1, damage);
log.log(Level.INFO, "Giving " + toGive.getName() + " some " + i.toString());
// toGive.giveItem(itemId, amount);
Inventory inv = toGive.getInventory();
ArrayList<Item> list = new ArrayList<Item>();
for(Item it : inv.getContents())
if(it != null && it.getItemId() == i.getItemId() && it.getDamage() == i.getDamage())
list.add(it);
for(Item it : list){
if(it.getAmount() < 64){
if(amount >= 64 - it.getAmount()){
amount -= 64 - it.getAmount();
it.setAmount(64);
toGive.giveItem(it);
}else{
it.setAmount(it.getAmount() + amount);
amount = 0;
toGive.giveItem(it);
}
}
}
if(amount != 0){
i.setAmount(64);
while (amount > 64) {
amount -= 64;
toGive.giveItem(i);
i.setSlot(-1);
}
i.setAmount(amount);
toGive.giveItem(i);
}
if (toGive.getName().equalsIgnoreCase(getName()))
sendMessage(Colors.Rose + "There you go " + getName() + ".");
else {
sendMessage(Colors.Rose + "Gift given! :D");
toGive.sendMessage(Colors.Rose + "Enjoy your gift! :D");
}
} else if (!allowedItem && !canIgnoreRestrictions())
sendMessage(Colors.Rose + "You are not allowed to spawn that item.");
} else
sendMessage(Colors.Rose + "No item with ID " + split[1]);
} else
sendMessage(Colors.Rose + "Can't find user " + split[3]);
} else if (cmd.equalsIgnoreCase("/cloth") || cmd.equalsIgnoreCase("/dye")) {
if (split.length < 3) {
sendMessage(Colors.Rose + "Correct usage is: "+cmd+" [amount] [color]");
return;
}
try {
int amount = Integer.parseInt(split[1]);
if (amount <= 0 && !isAdmin())
amount = 1;
if (amount > 64 && !canIgnoreRestrictions())
amount = 64;
if (amount > 1024)
amount = 1024; // 16 stacks worth. More than enough.
String color = split[2];
if (split.length > 3)
color += " " + split[3];
Cloth.Color c = Cloth.Color.getColor(color.toLowerCase());
if (c == null) {
sendMessage(Colors.Rose + "Invalid color name!");
return;
}
Item i = c.getItem();
- if(cmd.equalsIgnoreCase("/dye"))
+ if(cmd.equalsIgnoreCase("/dye")){
i.setType(Item.Type.InkSack);
+ //some1 had fun inverting this i guess .....
+ i.setDamage(15 - i.getDamage());
+ }
i.setAmount(amount);
log.log(Level.INFO, "Giving " + getName() + " some " + i.toString());
Inventory inv = getInventory();
ArrayList<Item> list = new ArrayList<Item>();
for(Item it : inv.getContents())
if(it != null && it.getItemId() == i.getItemId() && it.getDamage() == i.getDamage())
list.add(it);
for(Item it : list){
if(it.getAmount() < 64){
if(amount >= 64 - it.getAmount()){
amount -= 64 - it.getAmount();
it.setAmount(64);
giveItem(it);
}else{
it.setAmount(it.getAmount() + amount);
amount = 0;
giveItem(it);
}
}
}
if(amount != 0){
i.setAmount(64);
while (amount > 64) {
amount -= 64;
giveItem(i);
i.setSlot(-1);
}
i.setAmount(amount);
giveItem(i);
}
sendMessage(Colors.Rose + "There you go " + getName() + ".");
} catch (NumberFormatException localNumberFormatException) {
sendMessage(Colors.Rose + "Improper ID and/or amount.");
}
} else if (cmd.equalsIgnoreCase("/tempban")) {
// /tempban MINUTES HOURS DAYS
if (split.length == 1)
return;
int minutes = 0, hours = 0, days = 0;
if (split.length >= 2)
minutes = Integer.parseInt(split[1]);
if (split.length >= 3)
hours = Integer.parseInt(split[2]);
if (split.length >= 4)
days = Integer.parseInt(split[3]);
Date date = new Date();
// date.
} else if (cmd.equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2)
if (split[1].equalsIgnoreCase("ips"))
type = 1;
if (type == 0)
sendMessage(Colors.Blue + "Ban list:" + Colors.White + " " + etc.getMCServer().f.getBans());
else
sendMessage(Colors.Blue + "IP Ban list:" + Colors.White + " " + etc.getMCServer().f.getIpBans());
} else if (cmd.equalsIgnoreCase("/banip")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
etc.getMCServer().f.c(player.getIP());
etc.getLoader().callHook(PluginLoader.Hook.IPBAN, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
log.log(Level.INFO, "IP Banning " + player.getName() + " (IP: " + player.getIP() + ")");
sendMessage(Colors.Rose + "IP Banning " + player.getName() + " (IP: " + player.getIP() + ")");
if (split.length > 2)
player.kick("IP Banned by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("IP Banned by " + getName() + ".");
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/ban")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
etc.getServer().ban(player.getName());
etc.getLoader().callHook(PluginLoader.Hook.BAN, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
if (split.length > 2)
player.kick("Banned by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("Banned by " + getName() + ".");
log.log(Level.INFO, "Banning " + player.getName());
sendMessage(Colors.Rose + "Banning " + player.getName());
} else {
// sendMessage(Colors.Rose + "Can't find user " + split[1] +
// ".");
etc.getServer().ban(split[1]);
log.log(Level.INFO, "Banning " + split[1]);
sendMessage(Colors.Rose + "Banning " + split[1]);
}
} else if (cmd.equalsIgnoreCase("/unban")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
etc.getServer().unban(split[1]);
sendMessage(Colors.Rose + "Unbanned " + split[1]);
} else if (cmd.equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
etc.getMCServer().f.d(split[1]);
sendMessage(Colors.Rose + "Unbanned " + split[1]);
} else if (cmd.equalsIgnoreCase("/kick")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't kick that user.");
return;
}
etc.getLoader().callHook(PluginLoader.Hook.KICK, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
if (split.length > 2)
player.kick("Kicked by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("Kicked by " + getName() + ".");
log.log(Level.INFO, "Kicking " + player.getName());
sendMessage(Colors.Rose + "Kicking " + player.getName());
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/me")) {
if (isMuted()) {
sendMessage(Colors.Rose + "You are currently muted.");
return;
}
if (split.length == 1)
return;
String paramString2 = "* " + getColor() + getName() + Colors.White + " " + command.substring(command.indexOf(" ")).trim();
log.info("* " + getName() + " " + command.substring(command.indexOf(" ")).trim());
etc.getServer().messageAll(paramString2);
} else if (cmd.equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Warp home = new Warp();
home.Location = getLocation();
home.Group = ""; // no group neccessary, lol.
home.Name = getName();
etc.getInstance().changeHome(home);
sendMessage(Colors.Rose + "Your home has been set.");
} else if (cmd.equalsIgnoreCase("/spawn"))
teleportTo(etc.getServer().getSpawnLocation());
else if (cmd.equalsIgnoreCase("/setspawn")) {
etc.getMCServer().e.m = (int) Math.ceil(getX());
etc.getMCServer().e.o = (int) Math.ceil(getZ());
// Too lazy to actually update this considering it's not even
// used anyways.
// this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis
// really matters since it tries to get the highest point iirc.
log.info("Spawn position changed.");
sendMessage(Colors.Rose + "You have set the spawn to your current position.");
} else if (cmd.equalsIgnoreCase("/home")) {
Warp home = null;
if (split.length > 1 && isAdmin())
home = etc.getDataSource().getHome(split[1]);
else
home = etc.getDataSource().getHome(getName());
if (home != null)
teleportTo(home.Location);
else if (split.length > 1 && isAdmin())
sendMessage(Colors.Rose + "That player home does not exist");
else
teleportTo(etc.getServer().getSpawnLocation());
} else if (cmd.equalsIgnoreCase("/warp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
Player toWarp = this;
Warp warp = null;
if (split.length == 3 && canIgnoreRestrictions()) {
warp = etc.getDataSource().getWarp(split[1]);
toWarp = etc.getServer().matchPlayer(split[2]);
} else
warp = etc.getDataSource().getWarp(split[1]);
if (toWarp != null) {
if (warp != null) {
if (!isInGroup(warp.Group) && !warp.Group.equals(""))
sendMessage(Colors.Rose + "Warp not found.");
else {
toWarp.teleportTo(warp.Location);
toWarp.sendMessage(Colors.Rose + "Woosh!");
}
} else
sendMessage(Colors.Rose + "Warp not found");
} else
sendMessage(Colors.Rose + "Player not found.");
} else if (cmd.equalsIgnoreCase("/listwarps") && etc.getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
sendMessage(Colors.Rose + "Available warps: " + Colors.White + etc.getDataSource().getWarpNames(this));
return;
}
} else if (cmd.equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (canIgnoreRestrictions())
sendMessage(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
else
sendMessage(Colors.Rose + "Correct usage is: /setwarp [warpname]");
return;
}
if (split[1].contains(":")) {
sendMessage("You can't set a warp with \":\" in its name");
return;
}
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = getLocation();
if (split.length == 3)
warp.Group = split[2];
else
warp.Group = "";
etc.getInstance().setWarp(warp);
sendMessage(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/removewarp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /removewarp [warpname]");
return;
}
Warp warp = etc.getDataSource().getWarp(split[1]);
if (warp != null) {
etc.getDataSource().removeWarp(warp);
sendMessage(Colors.Blue + "Warp removed.");
} else
sendMessage(Colors.Rose + "That warp does not exist");
} else if (cmd.equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(getName() + " lighter")) {
log.info(getName() + " failed to iron!");
sendMessage(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!canIgnoreRestrictions())
MinecraftServer.b.put(getName() + " lighter", Integer.valueOf(6000));
log.info(getName() + " created a lighter!");
giveItem(259, 1);
}
} else if ((command.startsWith("/#")) && (etc.getMCServer().f.g(getName()))) {
String str = command.substring(2);
log.info(getName() + " issued server command: " + str);
etc.getMCServer().a(str, getEntity().a);
} else if (cmd.equalsIgnoreCase("/time")) {
if (split.length == 2) {
if (split[1].equalsIgnoreCase("day"))
etc.getServer().setRelativeTime(0);
else if (split[1].equalsIgnoreCase("night"))
etc.getServer().setRelativeTime(13000);
else if (split[1].equalsIgnoreCase("check"))
sendMessage(Colors.Rose + "The time is " + etc.getServer().getRelativeTime() + "! (RAW: " + etc.getServer().getTime() + ")");
else
try {
etc.getServer().setRelativeTime(Long.parseLong(split[1]));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Please enter numbers, not letters.");
}
} else if (split.length == 3) {
if (split[1].equalsIgnoreCase("raw"))
try {
etc.getServer().setTime(Long.parseLong(split[2]));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Please enter numbers, not letters.");
}
} else {
sendMessage(Colors.Rose + "Correct usage is: /time [time|'day|night|check|raw'] (rawtime)");
return;
}
} else if (cmd.equalsIgnoreCase("/getpos")) {
sendMessage("Pos X: " + getX() + " Y: " + getY() + " Z: " + getZ());
sendMessage("Rotation: " + getRotation() + " Pitch: " + getPitch());
double degreeRotation = ((getRotation() - 90) % 360);
if (degreeRotation < 0)
degreeRotation += 360.0;
sendMessage("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (cmd.equalsIgnoreCase("/compass")) {
double degreeRotation = ((getRotation() - 90) % 360);
if (degreeRotation < 0)
degreeRotation += 360.0;
sendMessage(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (cmd.equalsIgnoreCase("/motd"))
for (String str : etc.getInstance().getMotd())
sendMessage(str);
else if (cmd.equalsIgnoreCase("/spawnmob")) {
if (split.length == 1) {
sendMessage(Colors.Rose + "Correct usage is: /spawnmob [name] <amount>");
return;
}
if (!Mob.isValid(split[1])) {
sendMessage(Colors.Rose + "Invalid mob. Name has to start with a capital like so: Pig");
return;
}
if (split.length == 2) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn();
} else if (split.length == 3)
try {
int mobnumber = Integer.parseInt(split[2]);
for (int i = 0; i < mobnumber; i++) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn();
}
} catch (NumberFormatException nfe) {
if (!Mob.isValid(split[2])) {
sendMessage(Colors.Rose + "Invalid mob name or number of mobs.");
sendMessage(Colors.Rose + "Mob names have to start with a capital like so: Pig");
} else {
Mob mob = new Mob(split[1], getLocation());
mob.spawn(new Mob(split[2]));
}
}
else if (split.length == 4)
try {
int mobnumber = Integer.parseInt(split[3]);
if (!Mob.isValid(split[2]))
sendMessage(Colors.Rose + "Invalid rider. Name has to start with a capital like so: Pig");
else
for (int i = 0; i < mobnumber; i++) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn(new Mob(split[2]));
}
} catch (NumberFormatException nfe) {
sendMessage(Colors.Rose + "Invalid number of mobs.");
}
} else if (cmd.equalsIgnoreCase("/clearinventory")) {
Player target = this;
if (split.length >= 2 && isAdmin())
target = etc.getServer().matchPlayer(split[1]);
if (target != null) {
Inventory inv = target.getInventory();
inv.clearContents();
inv.update();
if (!target.getName().equals(getName()))
sendMessage(Colors.Rose + "Cleared " + target.getName() + "'s inventory.");
} else
sendMessage(Colors.Rose + "Target not found");
} else if (cmd.equals("/mspawn")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "You must specify what to change the mob spawner to.");
return;
}
if (!Mob.isValid(split[1])) {
sendMessage(Colors.Rose + "Invalid mob specified.");
return;
}
HitBlox hb = new HitBlox(this);
Block block = hb.getTargetBlock();
if (block.getType() == 52) { // mob spawner
MobSpawner ms = (MobSpawner) etc.getServer().getComplexBlock(block.getX(), block.getY(), block.getZ());
if (ms != null)
ms.setSpawn(split[1]);
} else
sendMessage(Colors.Rose + "You are not targeting a mob spawner.");
} else {
log.info(getName() + " tried command " + command);
if (etc.getInstance().showUnknownCommand())
sendMessage(Colors.Rose + "Unknown command");
}
} catch (Throwable ex) { // Might as well try and catch big exceptions
// before the server crashes from a stack
// overflow or something
log.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (isAdmin())
sendMessage(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
/**
* Gives an item to the player
*
* @param itemId
* @param amount
*/
public void giveItem(int itemId, int amount) {
inventory.giveItem(itemId, amount);
inventory.update();
}
/**
* Gives the player this item by dropping it in front of them
*
* @param item
*/
public void giveItemDrop(Item item) {
giveItemDrop(item.getItemId(), item.getAmount());
}
/**
* Gives the player this item by dropping it in front of them
*
* @param itemId
* @param amount
*/
public void giveItemDrop(int itemId, int amount) {
OEntityPlayerMP player = getEntity();
if (amount == -1)
player.a(new OItemStack(itemId, 255, 0));
else {
int temp = amount;
do {
if (temp - 64 >= 64)
player.a(new OItemStack(itemId, 64, 0));
else
player.a(new OItemStack(itemId, temp, 0));
temp -= 64;
} while (temp > 0);
}
}
/**
* Returns true if this player can use the specified command
*
* @param command
* @return
*/
public boolean canUseCommand(String command) {
for (String str : commands)
if (str.equalsIgnoreCase(command))
return true;
for (String str : groups) {
Group g = etc.getDataSource().getGroup(str);
if (g != null)
if (recursiveUseCommand(g, command))
return true;
}
if (hasNoGroups()) {
Group def = etc.getInstance().getDefaultGroup();
if (def != null)
if (recursiveUseCommand(def, command))
return true;
}
return false;
}
private boolean recursiveUseCommand(Group g, String command) {
for (String str : g.Commands)
if (str.equalsIgnoreCase(command) || str.equals("*"))
return true;
if (g.InheritedGroups != null)
for (String str : g.InheritedGroups) {
Group g2 = etc.getDataSource().getGroup(str);
if (g2 != null)
if (recursiveUseCommand(g2, command))
return true;
}
return false;
}
/**
* Checks to see if this player is in the specified group
*
* @param group
* @return
*/
public boolean isInGroup(String group) {
if (group != null)
if (etc.getInstance().getDefaultGroup() != null)
if (group.equalsIgnoreCase(etc.getInstance().getDefaultGroup().Name))
return true;
for (String str : groups)
if (recursiveUserInGroup(etc.getDataSource().getGroup(str), group))
return true;
return false;
}
private boolean recursiveUserInGroup(Group g, String group) {
if (g == null || group == null)
return false;
if (g.Name.equalsIgnoreCase(group))
return true;
if (g.InheritedGroups != null)
for (String str : g.InheritedGroups) {
if (g.Name.equalsIgnoreCase(str))
return true;
Group g2 = etc.getDataSource().getGroup(str);
if (g2 != null)
if (recursiveUserInGroup(g2, group))
return true;
}
return false;
}
/**
* Returns true if this player has control over the other player
*
* @param player
* @return true if player has control
*/
public boolean hasControlOver(Player player) {
boolean isInGroup = false;
if (player.hasNoGroups())
return true;
for (String str : player.getGroups()) {
if (isInGroup(str))
isInGroup = true;
else
continue;
break;
}
return isInGroup;
}
/**
* Returns the player's current location
*
* @return
*/
public Location getLocation() {
Location loc = new Location();
loc.x = getX();
loc.y = getY();
loc.z = getZ();
loc.rotX = getRotation();
loc.rotY = getPitch();
return loc;
}
/**
* Returns the IP of this player
*
* @return
*/
public String getIP() {
return getEntity().a.b.b().toString().split(":")[0].substring(1);
}
/**
* Returns true if this player is an admin.
*
* @return
*/
public boolean isAdmin() {
if (admin)
return true;
for (String str : groups) {
Group group = etc.getDataSource().getGroup(str);
if (group != null)
if (group.Administrator)
return true;
}
return false;
}
/**
* Don't use this! Use isAdmin
*
* @return
*/
public boolean getAdmin() {
return admin;
}
/**
* Sets whether or not this player is an administrator
*
* @param admin
*/
public void setAdmin(boolean admin) {
this.admin = admin;
}
/**
* Returns false if this player can not modify terrain, edit chests, etc.
*
* @return
*/
public boolean canBuild() {
if (canModifyWorld)
return true;
for (String str : groups) {
Group group = etc.getDataSource().getGroup(str);
if (group != null)
if (group.CanModifyWorld)
return true;
}
if (hasNoGroups())
if (etc.getInstance().getDefaultGroup().CanModifyWorld)
return true;
return false;
}
/**
* Don't use this, use canBuild()
*
* @return
*/
public boolean canModifyWorld() {
return canModifyWorld;
}
/**
* Sets whether or not this player can modify the world terrain
*
* @param canModifyWorld
*/
public void setCanModifyWorld(boolean canModifyWorld) {
this.canModifyWorld = canModifyWorld;
}
/**
* Set allowed commands
*
* @return
*/
public String[] getCommands() {
return commands;
}
/**
* Sets this player's allowed commands
*
* @param commands
*/
public void setCommands(String[] commands) {
this.commands = commands;
}
/**
* Returns this player's groups
*
* @return
*/
public String[] getGroups() {
String[] strGroups = new String[groups.size()];
groups.toArray(strGroups);
return strGroups;
}
/**
* Sets this player's groups
*
* @param groups
*/
public void setGroups(String[] groups) {
this.groups.clear();
for (String s : groups)
if (s.length() > 0)
this.groups.add(s);
}
/**
* Adds the player to the specified group
*
* @param group
* group to add player to
*/
public void addGroup(String group) {
groups.add(group);
}
/**
* Removes specified group from list of groups
*
* @param group
* group to remove
*/
public void removeGroup(String group) {
groups.remove(group);
}
/**
* Returns the sql ID.
*
* @return
*/
public int getSqlId() {
return id;
}
/**
* Sets the sql ID. Don't touch this.
*
* @param id
*/
public void setSqlId(int id) {
this.id = id;
}
/**
* If the user can ignore restrictions this will return true. Things like
* item amounts and such are unlimited, etc.
*
* @return
*/
public boolean canIgnoreRestrictions() {
if (admin || ignoreRestrictions)
return true;
for (String str : groups) {
Group group = etc.getDataSource().getGroup(str);
if (group != null)
if (group.Administrator || group.IgnoreRestrictions)
return true;
}
return false;
}
/**
* Don't use. Use canIgnoreRestrictions()
*
* @return
*/
public boolean ignoreRestrictions() {
return ignoreRestrictions;
}
/**
* Sets ignore restrictions
*
* @param ignoreRestrictions
*/
public void setIgnoreRestrictions(boolean ignoreRestrictions) {
this.ignoreRestrictions = ignoreRestrictions;
}
/**
* Returns allowed IPs
*
* @return
*/
public String[] getIps() {
return ips;
}
/**
* Sets allowed IPs
*
* @param ips
*/
public void setIps(String[] ips) {
this.ips = ips;
}
/**
* Returns the correct color/prefix for this player
*
* @return
*/
public String getColor() {
if (prefix != null)
if (!prefix.equals(""))
return "§" + prefix;
if (groups.size() > 0) {
Group group = etc.getDataSource().getGroup(groups.get(0));
if (group != null)
return "§" + group.Prefix;
}
Group def = etc.getInstance().getDefaultGroup();
return def != null ? "§" + def.Prefix : "";
}
/**
* Returns the prefix. NOTE: Don't use this, use getColor() instead.
*
* @return
*/
public String getPrefix() {
return prefix;
}
/**
* Sets the prefix
*
* @param prefix
*/
public void setPrefix(String prefix) {
this.prefix = prefix;
}
/**
* Gets the actual user class.
*
* @return
*/
public OEntityPlayerMP getUser() {
return getEntity();
}
/**
* Sets the user. Don't use this.
*
* @param er
*/
public void setUser(OEntityPlayerMP player) {
entity = player;
inventory = new PlayerInventory(this);
}
public void teleportTo(double x, double y, double z, float rotation, float pitch) {
OEntityPlayerMP player = getEntity();
// If player is in vehicle - eject them before they are teleported.
if (player.k != null)
player.e(player.k);
player.a.a(x, y, z, rotation, pitch);
}
/**
* Returns true if the player is muted
*
* @return
*/
public boolean isMuted() {
return muted;
}
/**
* Toggles mute
*
* @return
*/
public boolean toggleMute() {
muted = !muted;
return muted;
}
/**
* Checks to see if this player is in any groups
*
* @return true if this player is in any group
*/
public boolean hasNoGroups() {
if (groups.isEmpty())
return true;
if (groups.size() == 1)
return groups.get(0).equals("");
return false;
}
/**
* Returns item id in player's hand
*
* @return
*/
public int getItemInHand() {
return getEntity().a.getItemInHand();
}
/**
* Returns this player's inventory
*
* @return inventory
*/
public Inventory getInventory() {
return inventory;
}
/**
* Returns whether or not this Player is currently sneaking (crouching)
*
* @return true if sneaking
*/
public boolean getSneaking() {
return getEntity().am;
}
/**
* Force this Player to be sneaking or not
*
* @param sneaking
* true if sneaking
*/
public void setSneaking(boolean sneaking) {
getEntity().am = sneaking;
}
/**
* Returns a String representation of this Player
*
* @return String representation of this Player
*/
@Override
public String toString() {
return String.format("Player[id=%d, name=%s]", id, getName());
}
/**
* Tests the given object to see if it equals this object
*
* @param obj
* the object to test
* @return true if the two objects match
*/
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Player other = (Player) obj;
return getName().equals(other.getName());
}
/**
* Returns a unique hashcode for this Player
*
* @return hashcode
*/
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + id;
return hash;
}
}
| false | true | public void command(String command) {
try {
if (etc.getInstance().isLogging())
log.info("Command used by " + getName() + " " + command);
String[] split = command.split(" ");
String cmd = split[0];
if ((Boolean) etc.getLoader().callHook(PluginLoader.Hook.COMMAND, new Object[] { this, split }))
return; // No need to go on, commands were parsed.
if (!canUseCommand(cmd) && !cmd.startsWith("/#")) {
if (etc.getInstance().showUnknownCommand())
sendMessage(Colors.Rose + "Unknown command.");
return;
}
// Remove '/' before checking.
if (ServerConsoleCommands.parseServerConsoleCommand(this, cmd.substring(1), split)) {
// Command parsed successfully...
} else if (cmd.equalsIgnoreCase("/help")) {
// Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().getCommands().entrySet())
if (canUseCommand(entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getDataSource().hasKits())
continue;
if (entry.getKey().equals("/listwarps") && !etc.getDataSource().hasWarps())
continue;
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
sendMessage(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2)
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0)
amount = (amount - 1) * 7;
else
amount = 0;
for (int i = amount; i < amount + 7; i++)
if (availableCommands.size() > i)
sendMessage(Colors.Rose + availableCommands.get(i));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Not a valid page number.");
}
else
for (int i = 0; i < 7; i++)
if (availableCommands.size() > i)
sendMessage(Colors.Rose + availableCommands.get(i));
} else if (cmd.equalsIgnoreCase("/mute")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (player.toggleMute())
sendMessage(Colors.Rose + "player was muted");
else
sendMessage(Colors.Rose + "player was unmuted");
} else
sendMessage(Colors.Rose + "Can't find player " + split[1]);
} else if ((cmd.equalsIgnoreCase("/msg") || cmd.equalsIgnoreCase("/tell")) || cmd.equalsIgnoreCase("/m")) {
if (split.length < 3) {
sendMessage(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (isMuted()) {
sendMessage(Colors.Rose + "You are currently muted.");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (player.getName().equals(getName())) {
sendMessage(Colors.Rose + "You can't message yourself!");
return;
}
player.sendMessage("(MSG) " + getColor() + "<" + getName() + "> " + Colors.White + etc.combineSplit(2, split, " "));
sendMessage("(MSG) " + getColor() + "<" + getName() + "> " + Colors.White + etc.combineSplit(2, split, " "));
} else
sendMessage(Colors.Rose + "Couldn't find player " + split[1]);
} else if (cmd.equalsIgnoreCase("/kit") && etc.getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
sendMessage(Colors.Rose + "Available kits" + Colors.White + ": " + etc.getDataSource().getKitNames(this));
return;
}
Player toGive = this;
if (split.length > 2 && canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[2]);
Kit kit = etc.getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!isInGroup(kit.Group) && !kit.Group.equals(""))
sendMessage(Colors.Rose + "That kit does not exist.");
else if (onlyOneUseKits.contains(kit.Name))
sendMessage(Colors.Rose + "You can only get this kit once per login.");
else if (MinecraftServer.b.containsKey(getName() + " " + kit.Name))
sendMessage(Colors.Rose + "You can't get this kit again for a while.");
else {
if (!canIgnoreRestrictions())
if (kit.Delay >= 0)
MinecraftServer.b.put(getName() + " " + kit.Name, kit.Delay);
else
onlyOneUseKits.add(kit.Name);
log.info(getName() + " got a kit!");
toGive.sendMessage(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet())
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getDataSource().getItem(entry.getKey());
}
toGive.giveItem(itemId, kit.IDs.get(entry.getKey()));
} catch (Exception e1) {
log.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
sendMessage(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
} else
sendMessage(Colors.Rose + "That kit does not exist.");
} else
sendMessage(Colors.Rose + "That user does not exist.");
} else if (cmd.equalsIgnoreCase("/tp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (getName().equalsIgnoreCase(player.getName())) {
sendMessage(Colors.Rose + "You're already here!");
return;
}
log.info(getName() + " teleported to " + player.getName());
teleportTo(player);
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if ((cmd.equalsIgnoreCase("/tphere") || cmd.equalsIgnoreCase("/s"))) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (getName().equalsIgnoreCase(player.getName())) {
sendMessage(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
log.info(getName() + " teleported " + player.getName() + " to their self.");
player.teleportTo(this);
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/playerlist") || cmd.equalsIgnoreCase("/who"))
sendMessage(Colors.Rose + "Player list (" + etc.getMCServer().f.b.size() + "/" + etc.getInstance().getPlayerLimit() + "): " + Colors.White + etc.getMCServer().f.c());
else if (cmd.equalsIgnoreCase("/item") || cmd.equalsIgnoreCase("/i") || cmd.equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (canIgnoreRestrictions())
sendMessage(Colors.Rose + "Correct usage is: /item [itemid] <amount> <damage> <player> (optional)");
else
sendMessage(Colors.Rose + "Correct usage is: /item [itemid] <amount> <damage>");
return;
}
Player toGive = this;
int itemId = 0, amount = 1, damage = 0;
try {
if (split.length > 1)
try {
itemId = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
itemId = etc.getDataSource().getItem(split[1]);
}
if (split.length > 2) {
amount = Integer.parseInt(split[2]);
if (amount <= 0 && !isAdmin())
amount = 1;
if (amount > 64 && !canIgnoreRestrictions())
amount = 64;
if (amount > 1024)
amount = 1024; // 16 stacks worth. More than enough.
}
if (split.length == 4) {
int temp = -1;
try {
temp = Integer.parseInt(split[3]);
} catch (NumberFormatException n) {
if (canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[3]);
}
if (temp > -1 && temp < 50)
damage = temp;
} else if (split.length == 5) {
damage = Integer.parseInt(split[3]);
if (damage < 0 && damage > 49)
damage = 0;
if (canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[4]);
}
} catch (NumberFormatException localNumberFormatException) {
sendMessage(Colors.Rose + "Improper ID and/or amount.");
return;
}
if (toGive != null) {
boolean allowedItem = false;
if (!etc.getInstance().getAllowedItems().isEmpty() && etc.getInstance().getAllowedItems().contains(itemId))
allowedItem = true;
else
allowedItem = true;
if (!etc.getInstance().getDisallowedItems().isEmpty() && etc.getInstance().getDisallowedItems().contains(itemId))
allowedItem = false;
if (Item.isValidItem(itemId)) {
if (allowedItem || canIgnoreRestrictions()) {
Item i = new Item(itemId, amount, -1, damage);
log.log(Level.INFO, "Giving " + toGive.getName() + " some " + i.toString());
// toGive.giveItem(itemId, amount);
Inventory inv = toGive.getInventory();
ArrayList<Item> list = new ArrayList<Item>();
for(Item it : inv.getContents())
if(it != null && it.getItemId() == i.getItemId() && it.getDamage() == i.getDamage())
list.add(it);
for(Item it : list){
if(it.getAmount() < 64){
if(amount >= 64 - it.getAmount()){
amount -= 64 - it.getAmount();
it.setAmount(64);
toGive.giveItem(it);
}else{
it.setAmount(it.getAmount() + amount);
amount = 0;
toGive.giveItem(it);
}
}
}
if(amount != 0){
i.setAmount(64);
while (amount > 64) {
amount -= 64;
toGive.giveItem(i);
i.setSlot(-1);
}
i.setAmount(amount);
toGive.giveItem(i);
}
if (toGive.getName().equalsIgnoreCase(getName()))
sendMessage(Colors.Rose + "There you go " + getName() + ".");
else {
sendMessage(Colors.Rose + "Gift given! :D");
toGive.sendMessage(Colors.Rose + "Enjoy your gift! :D");
}
} else if (!allowedItem && !canIgnoreRestrictions())
sendMessage(Colors.Rose + "You are not allowed to spawn that item.");
} else
sendMessage(Colors.Rose + "No item with ID " + split[1]);
} else
sendMessage(Colors.Rose + "Can't find user " + split[3]);
} else if (cmd.equalsIgnoreCase("/cloth") || cmd.equalsIgnoreCase("/dye")) {
if (split.length < 3) {
sendMessage(Colors.Rose + "Correct usage is: "+cmd+" [amount] [color]");
return;
}
try {
int amount = Integer.parseInt(split[1]);
if (amount <= 0 && !isAdmin())
amount = 1;
if (amount > 64 && !canIgnoreRestrictions())
amount = 64;
if (amount > 1024)
amount = 1024; // 16 stacks worth. More than enough.
String color = split[2];
if (split.length > 3)
color += " " + split[3];
Cloth.Color c = Cloth.Color.getColor(color.toLowerCase());
if (c == null) {
sendMessage(Colors.Rose + "Invalid color name!");
return;
}
Item i = c.getItem();
if(cmd.equalsIgnoreCase("/dye"))
i.setType(Item.Type.InkSack);
i.setAmount(amount);
log.log(Level.INFO, "Giving " + getName() + " some " + i.toString());
Inventory inv = getInventory();
ArrayList<Item> list = new ArrayList<Item>();
for(Item it : inv.getContents())
if(it != null && it.getItemId() == i.getItemId() && it.getDamage() == i.getDamage())
list.add(it);
for(Item it : list){
if(it.getAmount() < 64){
if(amount >= 64 - it.getAmount()){
amount -= 64 - it.getAmount();
it.setAmount(64);
giveItem(it);
}else{
it.setAmount(it.getAmount() + amount);
amount = 0;
giveItem(it);
}
}
}
if(amount != 0){
i.setAmount(64);
while (amount > 64) {
amount -= 64;
giveItem(i);
i.setSlot(-1);
}
i.setAmount(amount);
giveItem(i);
}
sendMessage(Colors.Rose + "There you go " + getName() + ".");
} catch (NumberFormatException localNumberFormatException) {
sendMessage(Colors.Rose + "Improper ID and/or amount.");
}
} else if (cmd.equalsIgnoreCase("/tempban")) {
// /tempban MINUTES HOURS DAYS
if (split.length == 1)
return;
int minutes = 0, hours = 0, days = 0;
if (split.length >= 2)
minutes = Integer.parseInt(split[1]);
if (split.length >= 3)
hours = Integer.parseInt(split[2]);
if (split.length >= 4)
days = Integer.parseInt(split[3]);
Date date = new Date();
// date.
} else if (cmd.equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2)
if (split[1].equalsIgnoreCase("ips"))
type = 1;
if (type == 0)
sendMessage(Colors.Blue + "Ban list:" + Colors.White + " " + etc.getMCServer().f.getBans());
else
sendMessage(Colors.Blue + "IP Ban list:" + Colors.White + " " + etc.getMCServer().f.getIpBans());
} else if (cmd.equalsIgnoreCase("/banip")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
etc.getMCServer().f.c(player.getIP());
etc.getLoader().callHook(PluginLoader.Hook.IPBAN, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
log.log(Level.INFO, "IP Banning " + player.getName() + " (IP: " + player.getIP() + ")");
sendMessage(Colors.Rose + "IP Banning " + player.getName() + " (IP: " + player.getIP() + ")");
if (split.length > 2)
player.kick("IP Banned by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("IP Banned by " + getName() + ".");
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/ban")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
etc.getServer().ban(player.getName());
etc.getLoader().callHook(PluginLoader.Hook.BAN, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
if (split.length > 2)
player.kick("Banned by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("Banned by " + getName() + ".");
log.log(Level.INFO, "Banning " + player.getName());
sendMessage(Colors.Rose + "Banning " + player.getName());
} else {
// sendMessage(Colors.Rose + "Can't find user " + split[1] +
// ".");
etc.getServer().ban(split[1]);
log.log(Level.INFO, "Banning " + split[1]);
sendMessage(Colors.Rose + "Banning " + split[1]);
}
} else if (cmd.equalsIgnoreCase("/unban")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
etc.getServer().unban(split[1]);
sendMessage(Colors.Rose + "Unbanned " + split[1]);
} else if (cmd.equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
etc.getMCServer().f.d(split[1]);
sendMessage(Colors.Rose + "Unbanned " + split[1]);
} else if (cmd.equalsIgnoreCase("/kick")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't kick that user.");
return;
}
etc.getLoader().callHook(PluginLoader.Hook.KICK, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
if (split.length > 2)
player.kick("Kicked by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("Kicked by " + getName() + ".");
log.log(Level.INFO, "Kicking " + player.getName());
sendMessage(Colors.Rose + "Kicking " + player.getName());
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/me")) {
if (isMuted()) {
sendMessage(Colors.Rose + "You are currently muted.");
return;
}
if (split.length == 1)
return;
String paramString2 = "* " + getColor() + getName() + Colors.White + " " + command.substring(command.indexOf(" ")).trim();
log.info("* " + getName() + " " + command.substring(command.indexOf(" ")).trim());
etc.getServer().messageAll(paramString2);
} else if (cmd.equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Warp home = new Warp();
home.Location = getLocation();
home.Group = ""; // no group neccessary, lol.
home.Name = getName();
etc.getInstance().changeHome(home);
sendMessage(Colors.Rose + "Your home has been set.");
} else if (cmd.equalsIgnoreCase("/spawn"))
teleportTo(etc.getServer().getSpawnLocation());
else if (cmd.equalsIgnoreCase("/setspawn")) {
etc.getMCServer().e.m = (int) Math.ceil(getX());
etc.getMCServer().e.o = (int) Math.ceil(getZ());
// Too lazy to actually update this considering it's not even
// used anyways.
// this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis
// really matters since it tries to get the highest point iirc.
log.info("Spawn position changed.");
sendMessage(Colors.Rose + "You have set the spawn to your current position.");
} else if (cmd.equalsIgnoreCase("/home")) {
Warp home = null;
if (split.length > 1 && isAdmin())
home = etc.getDataSource().getHome(split[1]);
else
home = etc.getDataSource().getHome(getName());
if (home != null)
teleportTo(home.Location);
else if (split.length > 1 && isAdmin())
sendMessage(Colors.Rose + "That player home does not exist");
else
teleportTo(etc.getServer().getSpawnLocation());
} else if (cmd.equalsIgnoreCase("/warp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
Player toWarp = this;
Warp warp = null;
if (split.length == 3 && canIgnoreRestrictions()) {
warp = etc.getDataSource().getWarp(split[1]);
toWarp = etc.getServer().matchPlayer(split[2]);
} else
warp = etc.getDataSource().getWarp(split[1]);
if (toWarp != null) {
if (warp != null) {
if (!isInGroup(warp.Group) && !warp.Group.equals(""))
sendMessage(Colors.Rose + "Warp not found.");
else {
toWarp.teleportTo(warp.Location);
toWarp.sendMessage(Colors.Rose + "Woosh!");
}
} else
sendMessage(Colors.Rose + "Warp not found");
} else
sendMessage(Colors.Rose + "Player not found.");
} else if (cmd.equalsIgnoreCase("/listwarps") && etc.getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
sendMessage(Colors.Rose + "Available warps: " + Colors.White + etc.getDataSource().getWarpNames(this));
return;
}
} else if (cmd.equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (canIgnoreRestrictions())
sendMessage(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
else
sendMessage(Colors.Rose + "Correct usage is: /setwarp [warpname]");
return;
}
if (split[1].contains(":")) {
sendMessage("You can't set a warp with \":\" in its name");
return;
}
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = getLocation();
if (split.length == 3)
warp.Group = split[2];
else
warp.Group = "";
etc.getInstance().setWarp(warp);
sendMessage(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/removewarp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /removewarp [warpname]");
return;
}
Warp warp = etc.getDataSource().getWarp(split[1]);
if (warp != null) {
etc.getDataSource().removeWarp(warp);
sendMessage(Colors.Blue + "Warp removed.");
} else
sendMessage(Colors.Rose + "That warp does not exist");
} else if (cmd.equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(getName() + " lighter")) {
log.info(getName() + " failed to iron!");
sendMessage(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!canIgnoreRestrictions())
MinecraftServer.b.put(getName() + " lighter", Integer.valueOf(6000));
log.info(getName() + " created a lighter!");
giveItem(259, 1);
}
} else if ((command.startsWith("/#")) && (etc.getMCServer().f.g(getName()))) {
String str = command.substring(2);
log.info(getName() + " issued server command: " + str);
etc.getMCServer().a(str, getEntity().a);
} else if (cmd.equalsIgnoreCase("/time")) {
if (split.length == 2) {
if (split[1].equalsIgnoreCase("day"))
etc.getServer().setRelativeTime(0);
else if (split[1].equalsIgnoreCase("night"))
etc.getServer().setRelativeTime(13000);
else if (split[1].equalsIgnoreCase("check"))
sendMessage(Colors.Rose + "The time is " + etc.getServer().getRelativeTime() + "! (RAW: " + etc.getServer().getTime() + ")");
else
try {
etc.getServer().setRelativeTime(Long.parseLong(split[1]));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Please enter numbers, not letters.");
}
} else if (split.length == 3) {
if (split[1].equalsIgnoreCase("raw"))
try {
etc.getServer().setTime(Long.parseLong(split[2]));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Please enter numbers, not letters.");
}
} else {
sendMessage(Colors.Rose + "Correct usage is: /time [time|'day|night|check|raw'] (rawtime)");
return;
}
} else if (cmd.equalsIgnoreCase("/getpos")) {
sendMessage("Pos X: " + getX() + " Y: " + getY() + " Z: " + getZ());
sendMessage("Rotation: " + getRotation() + " Pitch: " + getPitch());
double degreeRotation = ((getRotation() - 90) % 360);
if (degreeRotation < 0)
degreeRotation += 360.0;
sendMessage("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (cmd.equalsIgnoreCase("/compass")) {
double degreeRotation = ((getRotation() - 90) % 360);
if (degreeRotation < 0)
degreeRotation += 360.0;
sendMessage(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (cmd.equalsIgnoreCase("/motd"))
for (String str : etc.getInstance().getMotd())
sendMessage(str);
else if (cmd.equalsIgnoreCase("/spawnmob")) {
if (split.length == 1) {
sendMessage(Colors.Rose + "Correct usage is: /spawnmob [name] <amount>");
return;
}
if (!Mob.isValid(split[1])) {
sendMessage(Colors.Rose + "Invalid mob. Name has to start with a capital like so: Pig");
return;
}
if (split.length == 2) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn();
} else if (split.length == 3)
try {
int mobnumber = Integer.parseInt(split[2]);
for (int i = 0; i < mobnumber; i++) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn();
}
} catch (NumberFormatException nfe) {
if (!Mob.isValid(split[2])) {
sendMessage(Colors.Rose + "Invalid mob name or number of mobs.");
sendMessage(Colors.Rose + "Mob names have to start with a capital like so: Pig");
} else {
Mob mob = new Mob(split[1], getLocation());
mob.spawn(new Mob(split[2]));
}
}
else if (split.length == 4)
try {
int mobnumber = Integer.parseInt(split[3]);
if (!Mob.isValid(split[2]))
sendMessage(Colors.Rose + "Invalid rider. Name has to start with a capital like so: Pig");
else
for (int i = 0; i < mobnumber; i++) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn(new Mob(split[2]));
}
} catch (NumberFormatException nfe) {
sendMessage(Colors.Rose + "Invalid number of mobs.");
}
} else if (cmd.equalsIgnoreCase("/clearinventory")) {
Player target = this;
if (split.length >= 2 && isAdmin())
target = etc.getServer().matchPlayer(split[1]);
if (target != null) {
Inventory inv = target.getInventory();
inv.clearContents();
inv.update();
if (!target.getName().equals(getName()))
sendMessage(Colors.Rose + "Cleared " + target.getName() + "'s inventory.");
} else
sendMessage(Colors.Rose + "Target not found");
} else if (cmd.equals("/mspawn")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "You must specify what to change the mob spawner to.");
return;
}
if (!Mob.isValid(split[1])) {
sendMessage(Colors.Rose + "Invalid mob specified.");
return;
}
HitBlox hb = new HitBlox(this);
Block block = hb.getTargetBlock();
if (block.getType() == 52) { // mob spawner
MobSpawner ms = (MobSpawner) etc.getServer().getComplexBlock(block.getX(), block.getY(), block.getZ());
if (ms != null)
ms.setSpawn(split[1]);
} else
sendMessage(Colors.Rose + "You are not targeting a mob spawner.");
} else {
log.info(getName() + " tried command " + command);
if (etc.getInstance().showUnknownCommand())
sendMessage(Colors.Rose + "Unknown command");
}
} catch (Throwable ex) { // Might as well try and catch big exceptions
// before the server crashes from a stack
// overflow or something
log.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (isAdmin())
sendMessage(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
| public void command(String command) {
try {
if (etc.getInstance().isLogging())
log.info("Command used by " + getName() + " " + command);
String[] split = command.split(" ");
String cmd = split[0];
if ((Boolean) etc.getLoader().callHook(PluginLoader.Hook.COMMAND, new Object[] { this, split }))
return; // No need to go on, commands were parsed.
if (!canUseCommand(cmd) && !cmd.startsWith("/#")) {
if (etc.getInstance().showUnknownCommand())
sendMessage(Colors.Rose + "Unknown command.");
return;
}
// Remove '/' before checking.
if (ServerConsoleCommands.parseServerConsoleCommand(this, cmd.substring(1), split)) {
// Command parsed successfully...
} else if (cmd.equalsIgnoreCase("/help")) {
// Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().getCommands().entrySet())
if (canUseCommand(entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getDataSource().hasKits())
continue;
if (entry.getKey().equals("/listwarps") && !etc.getDataSource().hasWarps())
continue;
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
sendMessage(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2)
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0)
amount = (amount - 1) * 7;
else
amount = 0;
for (int i = amount; i < amount + 7; i++)
if (availableCommands.size() > i)
sendMessage(Colors.Rose + availableCommands.get(i));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Not a valid page number.");
}
else
for (int i = 0; i < 7; i++)
if (availableCommands.size() > i)
sendMessage(Colors.Rose + availableCommands.get(i));
} else if (cmd.equalsIgnoreCase("/mute")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (player.toggleMute())
sendMessage(Colors.Rose + "player was muted");
else
sendMessage(Colors.Rose + "player was unmuted");
} else
sendMessage(Colors.Rose + "Can't find player " + split[1]);
} else if ((cmd.equalsIgnoreCase("/msg") || cmd.equalsIgnoreCase("/tell")) || cmd.equalsIgnoreCase("/m")) {
if (split.length < 3) {
sendMessage(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (isMuted()) {
sendMessage(Colors.Rose + "You are currently muted.");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (player.getName().equals(getName())) {
sendMessage(Colors.Rose + "You can't message yourself!");
return;
}
player.sendMessage("(MSG) " + getColor() + "<" + getName() + "> " + Colors.White + etc.combineSplit(2, split, " "));
sendMessage("(MSG) " + getColor() + "<" + getName() + "> " + Colors.White + etc.combineSplit(2, split, " "));
} else
sendMessage(Colors.Rose + "Couldn't find player " + split[1]);
} else if (cmd.equalsIgnoreCase("/kit") && etc.getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
sendMessage(Colors.Rose + "Available kits" + Colors.White + ": " + etc.getDataSource().getKitNames(this));
return;
}
Player toGive = this;
if (split.length > 2 && canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[2]);
Kit kit = etc.getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!isInGroup(kit.Group) && !kit.Group.equals(""))
sendMessage(Colors.Rose + "That kit does not exist.");
else if (onlyOneUseKits.contains(kit.Name))
sendMessage(Colors.Rose + "You can only get this kit once per login.");
else if (MinecraftServer.b.containsKey(getName() + " " + kit.Name))
sendMessage(Colors.Rose + "You can't get this kit again for a while.");
else {
if (!canIgnoreRestrictions())
if (kit.Delay >= 0)
MinecraftServer.b.put(getName() + " " + kit.Name, kit.Delay);
else
onlyOneUseKits.add(kit.Name);
log.info(getName() + " got a kit!");
toGive.sendMessage(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet())
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getDataSource().getItem(entry.getKey());
}
toGive.giveItem(itemId, kit.IDs.get(entry.getKey()));
} catch (Exception e1) {
log.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
sendMessage(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
} else
sendMessage(Colors.Rose + "That kit does not exist.");
} else
sendMessage(Colors.Rose + "That user does not exist.");
} else if (cmd.equalsIgnoreCase("/tp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (getName().equalsIgnoreCase(player.getName())) {
sendMessage(Colors.Rose + "You're already here!");
return;
}
log.info(getName() + " teleported to " + player.getName());
teleportTo(player);
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if ((cmd.equalsIgnoreCase("/tphere") || cmd.equalsIgnoreCase("/s"))) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (getName().equalsIgnoreCase(player.getName())) {
sendMessage(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
log.info(getName() + " teleported " + player.getName() + " to their self.");
player.teleportTo(this);
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/playerlist") || cmd.equalsIgnoreCase("/who"))
sendMessage(Colors.Rose + "Player list (" + etc.getMCServer().f.b.size() + "/" + etc.getInstance().getPlayerLimit() + "): " + Colors.White + etc.getMCServer().f.c());
else if (cmd.equalsIgnoreCase("/item") || cmd.equalsIgnoreCase("/i") || cmd.equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (canIgnoreRestrictions())
sendMessage(Colors.Rose + "Correct usage is: /item [itemid] <amount> <damage> <player> (optional)");
else
sendMessage(Colors.Rose + "Correct usage is: /item [itemid] <amount> <damage>");
return;
}
Player toGive = this;
int itemId = 0, amount = 1, damage = 0;
try {
if (split.length > 1)
try {
itemId = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
itemId = etc.getDataSource().getItem(split[1]);
}
if (split.length > 2) {
amount = Integer.parseInt(split[2]);
if (amount <= 0 && !isAdmin())
amount = 1;
if (amount > 64 && !canIgnoreRestrictions())
amount = 64;
if (amount > 1024)
amount = 1024; // 16 stacks worth. More than enough.
}
if (split.length == 4) {
int temp = -1;
try {
temp = Integer.parseInt(split[3]);
} catch (NumberFormatException n) {
if (canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[3]);
}
if (temp > -1 && temp < 50)
damage = temp;
} else if (split.length == 5) {
damage = Integer.parseInt(split[3]);
if (damage < 0 && damage > 49)
damage = 0;
if (canIgnoreRestrictions())
toGive = etc.getServer().matchPlayer(split[4]);
}
} catch (NumberFormatException localNumberFormatException) {
sendMessage(Colors.Rose + "Improper ID and/or amount.");
return;
}
if (toGive != null) {
boolean allowedItem = false;
if (!etc.getInstance().getAllowedItems().isEmpty() && etc.getInstance().getAllowedItems().contains(itemId))
allowedItem = true;
else
allowedItem = true;
if (!etc.getInstance().getDisallowedItems().isEmpty() && etc.getInstance().getDisallowedItems().contains(itemId))
allowedItem = false;
if (Item.isValidItem(itemId)) {
if (allowedItem || canIgnoreRestrictions()) {
Item i = new Item(itemId, amount, -1, damage);
log.log(Level.INFO, "Giving " + toGive.getName() + " some " + i.toString());
// toGive.giveItem(itemId, amount);
Inventory inv = toGive.getInventory();
ArrayList<Item> list = new ArrayList<Item>();
for(Item it : inv.getContents())
if(it != null && it.getItemId() == i.getItemId() && it.getDamage() == i.getDamage())
list.add(it);
for(Item it : list){
if(it.getAmount() < 64){
if(amount >= 64 - it.getAmount()){
amount -= 64 - it.getAmount();
it.setAmount(64);
toGive.giveItem(it);
}else{
it.setAmount(it.getAmount() + amount);
amount = 0;
toGive.giveItem(it);
}
}
}
if(amount != 0){
i.setAmount(64);
while (amount > 64) {
amount -= 64;
toGive.giveItem(i);
i.setSlot(-1);
}
i.setAmount(amount);
toGive.giveItem(i);
}
if (toGive.getName().equalsIgnoreCase(getName()))
sendMessage(Colors.Rose + "There you go " + getName() + ".");
else {
sendMessage(Colors.Rose + "Gift given! :D");
toGive.sendMessage(Colors.Rose + "Enjoy your gift! :D");
}
} else if (!allowedItem && !canIgnoreRestrictions())
sendMessage(Colors.Rose + "You are not allowed to spawn that item.");
} else
sendMessage(Colors.Rose + "No item with ID " + split[1]);
} else
sendMessage(Colors.Rose + "Can't find user " + split[3]);
} else if (cmd.equalsIgnoreCase("/cloth") || cmd.equalsIgnoreCase("/dye")) {
if (split.length < 3) {
sendMessage(Colors.Rose + "Correct usage is: "+cmd+" [amount] [color]");
return;
}
try {
int amount = Integer.parseInt(split[1]);
if (amount <= 0 && !isAdmin())
amount = 1;
if (amount > 64 && !canIgnoreRestrictions())
amount = 64;
if (amount > 1024)
amount = 1024; // 16 stacks worth. More than enough.
String color = split[2];
if (split.length > 3)
color += " " + split[3];
Cloth.Color c = Cloth.Color.getColor(color.toLowerCase());
if (c == null) {
sendMessage(Colors.Rose + "Invalid color name!");
return;
}
Item i = c.getItem();
if(cmd.equalsIgnoreCase("/dye")){
i.setType(Item.Type.InkSack);
//some1 had fun inverting this i guess .....
i.setDamage(15 - i.getDamage());
}
i.setAmount(amount);
log.log(Level.INFO, "Giving " + getName() + " some " + i.toString());
Inventory inv = getInventory();
ArrayList<Item> list = new ArrayList<Item>();
for(Item it : inv.getContents())
if(it != null && it.getItemId() == i.getItemId() && it.getDamage() == i.getDamage())
list.add(it);
for(Item it : list){
if(it.getAmount() < 64){
if(amount >= 64 - it.getAmount()){
amount -= 64 - it.getAmount();
it.setAmount(64);
giveItem(it);
}else{
it.setAmount(it.getAmount() + amount);
amount = 0;
giveItem(it);
}
}
}
if(amount != 0){
i.setAmount(64);
while (amount > 64) {
amount -= 64;
giveItem(i);
i.setSlot(-1);
}
i.setAmount(amount);
giveItem(i);
}
sendMessage(Colors.Rose + "There you go " + getName() + ".");
} catch (NumberFormatException localNumberFormatException) {
sendMessage(Colors.Rose + "Improper ID and/or amount.");
}
} else if (cmd.equalsIgnoreCase("/tempban")) {
// /tempban MINUTES HOURS DAYS
if (split.length == 1)
return;
int minutes = 0, hours = 0, days = 0;
if (split.length >= 2)
minutes = Integer.parseInt(split[1]);
if (split.length >= 3)
hours = Integer.parseInt(split[2]);
if (split.length >= 4)
days = Integer.parseInt(split[3]);
Date date = new Date();
// date.
} else if (cmd.equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2)
if (split[1].equalsIgnoreCase("ips"))
type = 1;
if (type == 0)
sendMessage(Colors.Blue + "Ban list:" + Colors.White + " " + etc.getMCServer().f.getBans());
else
sendMessage(Colors.Blue + "IP Ban list:" + Colors.White + " " + etc.getMCServer().f.getIpBans());
} else if (cmd.equalsIgnoreCase("/banip")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
etc.getMCServer().f.c(player.getIP());
etc.getLoader().callHook(PluginLoader.Hook.IPBAN, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
log.log(Level.INFO, "IP Banning " + player.getName() + " (IP: " + player.getIP() + ")");
sendMessage(Colors.Rose + "IP Banning " + player.getName() + " (IP: " + player.getIP() + ")");
if (split.length > 2)
player.kick("IP Banned by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("IP Banned by " + getName() + ".");
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/ban")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
etc.getServer().ban(player.getName());
etc.getLoader().callHook(PluginLoader.Hook.BAN, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
if (split.length > 2)
player.kick("Banned by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("Banned by " + getName() + ".");
log.log(Level.INFO, "Banning " + player.getName());
sendMessage(Colors.Rose + "Banning " + player.getName());
} else {
// sendMessage(Colors.Rose + "Can't find user " + split[1] +
// ".");
etc.getServer().ban(split[1]);
log.log(Level.INFO, "Banning " + split[1]);
sendMessage(Colors.Rose + "Banning " + split[1]);
}
} else if (cmd.equalsIgnoreCase("/unban")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
etc.getServer().unban(split[1]);
sendMessage(Colors.Rose + "Unbanned " + split[1]);
} else if (cmd.equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
etc.getMCServer().f.d(split[1]);
sendMessage(Colors.Rose + "Unbanned " + split[1]);
} else if (cmd.equalsIgnoreCase("/kick")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
Player player = etc.getServer().matchPlayer(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
sendMessage(Colors.Rose + "You can't kick that user.");
return;
}
etc.getLoader().callHook(PluginLoader.Hook.KICK, new Object[] { this, player, split.length >= 3 ? etc.combineSplit(2, split, " ") : "" });
if (split.length > 2)
player.kick("Kicked by " + getName() + ": " + etc.combineSplit(2, split, " "));
else
player.kick("Kicked by " + getName() + ".");
log.log(Level.INFO, "Kicking " + player.getName());
sendMessage(Colors.Rose + "Kicking " + player.getName());
} else
sendMessage(Colors.Rose + "Can't find user " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/me")) {
if (isMuted()) {
sendMessage(Colors.Rose + "You are currently muted.");
return;
}
if (split.length == 1)
return;
String paramString2 = "* " + getColor() + getName() + Colors.White + " " + command.substring(command.indexOf(" ")).trim();
log.info("* " + getName() + " " + command.substring(command.indexOf(" ")).trim());
etc.getServer().messageAll(paramString2);
} else if (cmd.equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Warp home = new Warp();
home.Location = getLocation();
home.Group = ""; // no group neccessary, lol.
home.Name = getName();
etc.getInstance().changeHome(home);
sendMessage(Colors.Rose + "Your home has been set.");
} else if (cmd.equalsIgnoreCase("/spawn"))
teleportTo(etc.getServer().getSpawnLocation());
else if (cmd.equalsIgnoreCase("/setspawn")) {
etc.getMCServer().e.m = (int) Math.ceil(getX());
etc.getMCServer().e.o = (int) Math.ceil(getZ());
// Too lazy to actually update this considering it's not even
// used anyways.
// this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis
// really matters since it tries to get the highest point iirc.
log.info("Spawn position changed.");
sendMessage(Colors.Rose + "You have set the spawn to your current position.");
} else if (cmd.equalsIgnoreCase("/home")) {
Warp home = null;
if (split.length > 1 && isAdmin())
home = etc.getDataSource().getHome(split[1]);
else
home = etc.getDataSource().getHome(getName());
if (home != null)
teleportTo(home.Location);
else if (split.length > 1 && isAdmin())
sendMessage(Colors.Rose + "That player home does not exist");
else
teleportTo(etc.getServer().getSpawnLocation());
} else if (cmd.equalsIgnoreCase("/warp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
Player toWarp = this;
Warp warp = null;
if (split.length == 3 && canIgnoreRestrictions()) {
warp = etc.getDataSource().getWarp(split[1]);
toWarp = etc.getServer().matchPlayer(split[2]);
} else
warp = etc.getDataSource().getWarp(split[1]);
if (toWarp != null) {
if (warp != null) {
if (!isInGroup(warp.Group) && !warp.Group.equals(""))
sendMessage(Colors.Rose + "Warp not found.");
else {
toWarp.teleportTo(warp.Location);
toWarp.sendMessage(Colors.Rose + "Woosh!");
}
} else
sendMessage(Colors.Rose + "Warp not found");
} else
sendMessage(Colors.Rose + "Player not found.");
} else if (cmd.equalsIgnoreCase("/listwarps") && etc.getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
sendMessage(Colors.Rose + "Available warps: " + Colors.White + etc.getDataSource().getWarpNames(this));
return;
}
} else if (cmd.equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (canIgnoreRestrictions())
sendMessage(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
else
sendMessage(Colors.Rose + "Correct usage is: /setwarp [warpname]");
return;
}
if (split[1].contains(":")) {
sendMessage("You can't set a warp with \":\" in its name");
return;
}
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = getLocation();
if (split.length == 3)
warp.Group = split[2];
else
warp.Group = "";
etc.getInstance().setWarp(warp);
sendMessage(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (cmd.equalsIgnoreCase("/removewarp")) {
if (split.length < 2) {
sendMessage(Colors.Rose + "Correct usage is: /removewarp [warpname]");
return;
}
Warp warp = etc.getDataSource().getWarp(split[1]);
if (warp != null) {
etc.getDataSource().removeWarp(warp);
sendMessage(Colors.Blue + "Warp removed.");
} else
sendMessage(Colors.Rose + "That warp does not exist");
} else if (cmd.equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(getName() + " lighter")) {
log.info(getName() + " failed to iron!");
sendMessage(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!canIgnoreRestrictions())
MinecraftServer.b.put(getName() + " lighter", Integer.valueOf(6000));
log.info(getName() + " created a lighter!");
giveItem(259, 1);
}
} else if ((command.startsWith("/#")) && (etc.getMCServer().f.g(getName()))) {
String str = command.substring(2);
log.info(getName() + " issued server command: " + str);
etc.getMCServer().a(str, getEntity().a);
} else if (cmd.equalsIgnoreCase("/time")) {
if (split.length == 2) {
if (split[1].equalsIgnoreCase("day"))
etc.getServer().setRelativeTime(0);
else if (split[1].equalsIgnoreCase("night"))
etc.getServer().setRelativeTime(13000);
else if (split[1].equalsIgnoreCase("check"))
sendMessage(Colors.Rose + "The time is " + etc.getServer().getRelativeTime() + "! (RAW: " + etc.getServer().getTime() + ")");
else
try {
etc.getServer().setRelativeTime(Long.parseLong(split[1]));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Please enter numbers, not letters.");
}
} else if (split.length == 3) {
if (split[1].equalsIgnoreCase("raw"))
try {
etc.getServer().setTime(Long.parseLong(split[2]));
} catch (NumberFormatException ex) {
sendMessage(Colors.Rose + "Please enter numbers, not letters.");
}
} else {
sendMessage(Colors.Rose + "Correct usage is: /time [time|'day|night|check|raw'] (rawtime)");
return;
}
} else if (cmd.equalsIgnoreCase("/getpos")) {
sendMessage("Pos X: " + getX() + " Y: " + getY() + " Z: " + getZ());
sendMessage("Rotation: " + getRotation() + " Pitch: " + getPitch());
double degreeRotation = ((getRotation() - 90) % 360);
if (degreeRotation < 0)
degreeRotation += 360.0;
sendMessage("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (cmd.equalsIgnoreCase("/compass")) {
double degreeRotation = ((getRotation() - 90) % 360);
if (degreeRotation < 0)
degreeRotation += 360.0;
sendMessage(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (cmd.equalsIgnoreCase("/motd"))
for (String str : etc.getInstance().getMotd())
sendMessage(str);
else if (cmd.equalsIgnoreCase("/spawnmob")) {
if (split.length == 1) {
sendMessage(Colors.Rose + "Correct usage is: /spawnmob [name] <amount>");
return;
}
if (!Mob.isValid(split[1])) {
sendMessage(Colors.Rose + "Invalid mob. Name has to start with a capital like so: Pig");
return;
}
if (split.length == 2) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn();
} else if (split.length == 3)
try {
int mobnumber = Integer.parseInt(split[2]);
for (int i = 0; i < mobnumber; i++) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn();
}
} catch (NumberFormatException nfe) {
if (!Mob.isValid(split[2])) {
sendMessage(Colors.Rose + "Invalid mob name or number of mobs.");
sendMessage(Colors.Rose + "Mob names have to start with a capital like so: Pig");
} else {
Mob mob = new Mob(split[1], getLocation());
mob.spawn(new Mob(split[2]));
}
}
else if (split.length == 4)
try {
int mobnumber = Integer.parseInt(split[3]);
if (!Mob.isValid(split[2]))
sendMessage(Colors.Rose + "Invalid rider. Name has to start with a capital like so: Pig");
else
for (int i = 0; i < mobnumber; i++) {
Mob mob = new Mob(split[1], getLocation());
mob.spawn(new Mob(split[2]));
}
} catch (NumberFormatException nfe) {
sendMessage(Colors.Rose + "Invalid number of mobs.");
}
} else if (cmd.equalsIgnoreCase("/clearinventory")) {
Player target = this;
if (split.length >= 2 && isAdmin())
target = etc.getServer().matchPlayer(split[1]);
if (target != null) {
Inventory inv = target.getInventory();
inv.clearContents();
inv.update();
if (!target.getName().equals(getName()))
sendMessage(Colors.Rose + "Cleared " + target.getName() + "'s inventory.");
} else
sendMessage(Colors.Rose + "Target not found");
} else if (cmd.equals("/mspawn")) {
if (split.length != 2) {
sendMessage(Colors.Rose + "You must specify what to change the mob spawner to.");
return;
}
if (!Mob.isValid(split[1])) {
sendMessage(Colors.Rose + "Invalid mob specified.");
return;
}
HitBlox hb = new HitBlox(this);
Block block = hb.getTargetBlock();
if (block.getType() == 52) { // mob spawner
MobSpawner ms = (MobSpawner) etc.getServer().getComplexBlock(block.getX(), block.getY(), block.getZ());
if (ms != null)
ms.setSpawn(split[1]);
} else
sendMessage(Colors.Rose + "You are not targeting a mob spawner.");
} else {
log.info(getName() + " tried command " + command);
if (etc.getInstance().showUnknownCommand())
sendMessage(Colors.Rose + "Unknown command");
}
} catch (Throwable ex) { // Might as well try and catch big exceptions
// before the server crashes from a stack
// overflow or something
log.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (isAdmin())
sendMessage(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
|
diff --git a/src/me/furt/CraftEssence/commands/GameModeCommand.java b/src/me/furt/CraftEssence/commands/GameModeCommand.java
index cc76f0d..b3e2c8b 100644
--- a/src/me/furt/CraftEssence/commands/GameModeCommand.java
+++ b/src/me/furt/CraftEssence/commands/GameModeCommand.java
@@ -1,75 +1,75 @@
package me.furt.CraftEssence.commands;
import me.furt.CraftEssence.CraftEssence;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class GameModeCommand implements CommandExecutor {
private final CraftEssence plugin;
public GameModeCommand(CraftEssence instance) {
this.plugin = instance;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (!plugin.hasPerm(sender, "gamemode", false)) {
sender.sendMessage(ChatColor.YELLOW
+ "You do not have permission to use /" + label);
return true;
}
Player player = (Player) sender;
if (args.length == 1) {
- if (args[0].equalsIgnoreCase("survival") || (args[1].equalsIgnoreCase("0"))) {
+ if (args[0].equalsIgnoreCase("survival") || (args[0].equalsIgnoreCase("0"))) {
player.setGameMode(GameMode.SURVIVAL);
player.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Survival.");
- } else if (args[0].equalsIgnoreCase("creative") || (args[1].equalsIgnoreCase("1"))) {
+ } else if (args[0].equalsIgnoreCase("creative") || (args[0].equalsIgnoreCase("1"))) {
player.setGameMode(GameMode.CREATIVE);
player.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Creative.");
} else {
player.sendMessage(CraftEssence.premessage + "Gamemode "
+ args[0] + " not found.");
}
return true;
} else if (args.length == 2) {
Player p = plugin.getServer().getPlayer(args[0]);
if (p == null) {
player.sendMessage(CraftEssence.premessage
+ "Player not found.");
return true;
}
if (args[1].equalsIgnoreCase("survival") || (args[1].equalsIgnoreCase("0"))) {
p.setGameMode(GameMode.SURVIVAL);
p.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Survival.");
player.sendMessage(CraftEssence.premessage + args[0]
+ "'s gamemode is now set to Survival.");
} else if (args[1].equalsIgnoreCase("creative") || (args[1].equalsIgnoreCase("1"))) {
p.setGameMode(GameMode.CREATIVE);
p.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Creative.");
player.sendMessage(CraftEssence.premessage + args[0]
+ "'s gamemode is now set to Creative.");
} else {
player.sendMessage(CraftEssence.premessage + "Gamemode "
+ args[1] + " not found.");
}
return true;
} else {
sender.sendMessage(CraftEssence.premessage
+ "Please select a gamemode: survival or creative");
return true;
}
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (!plugin.hasPerm(sender, "gamemode", false)) {
sender.sendMessage(ChatColor.YELLOW
+ "You do not have permission to use /" + label);
return true;
}
Player player = (Player) sender;
if (args.length == 1) {
if (args[0].equalsIgnoreCase("survival") || (args[1].equalsIgnoreCase("0"))) {
player.setGameMode(GameMode.SURVIVAL);
player.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Survival.");
} else if (args[0].equalsIgnoreCase("creative") || (args[1].equalsIgnoreCase("1"))) {
player.setGameMode(GameMode.CREATIVE);
player.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Creative.");
} else {
player.sendMessage(CraftEssence.premessage + "Gamemode "
+ args[0] + " not found.");
}
return true;
} else if (args.length == 2) {
Player p = plugin.getServer().getPlayer(args[0]);
if (p == null) {
player.sendMessage(CraftEssence.premessage
+ "Player not found.");
return true;
}
if (args[1].equalsIgnoreCase("survival") || (args[1].equalsIgnoreCase("0"))) {
p.setGameMode(GameMode.SURVIVAL);
p.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Survival.");
player.sendMessage(CraftEssence.premessage + args[0]
+ "'s gamemode is now set to Survival.");
} else if (args[1].equalsIgnoreCase("creative") || (args[1].equalsIgnoreCase("1"))) {
p.setGameMode(GameMode.CREATIVE);
p.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Creative.");
player.sendMessage(CraftEssence.premessage + args[0]
+ "'s gamemode is now set to Creative.");
} else {
player.sendMessage(CraftEssence.premessage + "Gamemode "
+ args[1] + " not found.");
}
return true;
} else {
sender.sendMessage(CraftEssence.premessage
+ "Please select a gamemode: survival or creative");
return true;
}
}
| public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (!plugin.hasPerm(sender, "gamemode", false)) {
sender.sendMessage(ChatColor.YELLOW
+ "You do not have permission to use /" + label);
return true;
}
Player player = (Player) sender;
if (args.length == 1) {
if (args[0].equalsIgnoreCase("survival") || (args[0].equalsIgnoreCase("0"))) {
player.setGameMode(GameMode.SURVIVAL);
player.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Survival.");
} else if (args[0].equalsIgnoreCase("creative") || (args[0].equalsIgnoreCase("1"))) {
player.setGameMode(GameMode.CREATIVE);
player.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Creative.");
} else {
player.sendMessage(CraftEssence.premessage + "Gamemode "
+ args[0] + " not found.");
}
return true;
} else if (args.length == 2) {
Player p = plugin.getServer().getPlayer(args[0]);
if (p == null) {
player.sendMessage(CraftEssence.premessage
+ "Player not found.");
return true;
}
if (args[1].equalsIgnoreCase("survival") || (args[1].equalsIgnoreCase("0"))) {
p.setGameMode(GameMode.SURVIVAL);
p.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Survival.");
player.sendMessage(CraftEssence.premessage + args[0]
+ "'s gamemode is now set to Survival.");
} else if (args[1].equalsIgnoreCase("creative") || (args[1].equalsIgnoreCase("1"))) {
p.setGameMode(GameMode.CREATIVE);
p.sendMessage(CraftEssence.premessage
+ "Your gamemode is now set to Creative.");
player.sendMessage(CraftEssence.premessage + args[0]
+ "'s gamemode is now set to Creative.");
} else {
player.sendMessage(CraftEssence.premessage + "Gamemode "
+ args[1] + " not found.");
}
return true;
} else {
sender.sendMessage(CraftEssence.premessage
+ "Please select a gamemode: survival or creative");
return true;
}
}
|
diff --git a/client/StorySplash.java b/client/StorySplash.java
index af9bc59..5276417 100644
--- a/client/StorySplash.java
+++ b/client/StorySplash.java
@@ -1,52 +1,52 @@
package client;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
* Splash screen for game
* @author wheelemaxw
*
*/
public class StorySplash extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L; //to stop warnings
private final String storyText = "You awaken in a strange dungeon with no memory of how you got there. \n" +
"All you know is that its kind of dark in here and that something does not " +
"seem quite right. " +
"\n \n" +
"There is a man in the distance, maybe he will know more about " +
"what is going on"+
"\n \n \n \n Click to Play";
public StorySplash(){
this.setTitle("Run,Escape");
JTextArea textf = new JTextArea();
JButton b = new JButton("Click to Play");
b.setActionCommand("play");
this.add(b, BorderLayout.SOUTH);
b.addActionListener(this);
- String text = storyText;
- textf.append(text);
+ textf.setEditable(false);
+ textf.setText(storyText);
this.add(textf, BorderLayout.NORTH);
this.pack();
this.setAlwaysOnTop(true);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("play")) {
this.dispose();
}
}
}
| true | true | public StorySplash(){
this.setTitle("Run,Escape");
JTextArea textf = new JTextArea();
JButton b = new JButton("Click to Play");
b.setActionCommand("play");
this.add(b, BorderLayout.SOUTH);
b.addActionListener(this);
String text = storyText;
textf.append(text);
this.add(textf, BorderLayout.NORTH);
this.pack();
this.setAlwaysOnTop(true);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
| public StorySplash(){
this.setTitle("Run,Escape");
JTextArea textf = new JTextArea();
JButton b = new JButton("Click to Play");
b.setActionCommand("play");
this.add(b, BorderLayout.SOUTH);
b.addActionListener(this);
textf.setEditable(false);
textf.setText(storyText);
this.add(textf, BorderLayout.NORTH);
this.pack();
this.setAlwaysOnTop(true);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
|
diff --git a/src/test/java/com/persistit/Bug1010079Test.java b/src/test/java/com/persistit/Bug1010079Test.java
index 0dd42fb4..7e1ce383 100644
--- a/src/test/java/com/persistit/Bug1010079Test.java
+++ b/src/test/java/com/persistit/Bug1010079Test.java
@@ -1,107 +1,108 @@
/**
* Copyright © 2012 Akiban Technologies, Inc. All rights reserved.
*
* 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, version 3 (only) 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 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/>.
*
* This program may also be available under different license terms. For more
* information, see www.akiban.com or contact [email protected].
*/
package com.persistit;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* https://bugs.launchpad.net/akiban-persistit/+bug/1010079
*
* Various symptoms found while running stress test mixture_txn_1, including
* CorruptVolumeException, CorruptValueException, and several different asserts.
* These all stem from new code introduced in
* lp:~pbeaman/akiban-persistit/fix_1006576_long_record_pruning. This bug is
* related to 1005206 and 1006576. Diagnosis:
*
* New code added to prune LongRecord MVVs operates on a copy of the original
* buffer and then atomically refreshes the original buffer from the copy. That
* operation fails to invalidate the FastIndex of the original buffer in the
* event a key is removed due to a LongRecord MVV becoming a primordial
* anti-value.
*
* In addition, pruneLongMvvValues uses a Value object obtained from a
* ThreadLocal. However, this same Value is already in use by
* Exchange#storeInternal.
*
* @author peter
*
*/
public class Bug1010079Test extends MVCCTestBase {
@Test
public void induceCorruption() throws Exception {
/*
* 1. Create a page with a long record MVV.
*
* 2. Read the value to set up the LevelCache
*
* 3. Abort the transaction so that long record MVV will become an
* AntiValue
*
* 4. Prune the Buffer to liberate the long record chain.
*
+ * 5. Store a value in the page (not yet certain why this is needed to
+ * induce the bug, but it is.)
*
- *
- * 6. Attempt the read the first value back in.
+ * 6. Attempt to the read the first value back in.
*
* Theory of bug is that the read attempt will not see a generation
* change, will use the LevelCache, and will attempt to read a long
* record from a page that has now become a data page.
*/
/*
* Disable background pruning
*/
_persistit.getCleanupManager().setPollInterval(-1);
/*
* Bump the generation number -- perhaps unnecessary
*/
for (int i = 0; i < 10; i++) {
ex1.to(i).store();
ex1.remove();
}
/*
* Store a single Long MVV
*/
trx1.begin();
storeLongMVV(ex1, 1);
ex1.fetch();
trx1.rollback();
trx1.end();
_persistit.getTransactionIndex().updateActiveTransactionCache();
ex1.prune();
ex1.getValue().put(RED_FOX);
ex1.to(0).store();
/*
* This method throws a CorruptVolumeException
*/
ex1.to(1).fetch();
assertTrue("Value should have been removed by rollback", !ex1.getValue().isDefined());
}
}
| false | true | public void induceCorruption() throws Exception {
/*
* 1. Create a page with a long record MVV.
*
* 2. Read the value to set up the LevelCache
*
* 3. Abort the transaction so that long record MVV will become an
* AntiValue
*
* 4. Prune the Buffer to liberate the long record chain.
*
*
*
* 6. Attempt the read the first value back in.
*
* Theory of bug is that the read attempt will not see a generation
* change, will use the LevelCache, and will attempt to read a long
* record from a page that has now become a data page.
*/
/*
* Disable background pruning
*/
_persistit.getCleanupManager().setPollInterval(-1);
/*
* Bump the generation number -- perhaps unnecessary
*/
for (int i = 0; i < 10; i++) {
ex1.to(i).store();
ex1.remove();
}
/*
* Store a single Long MVV
*/
trx1.begin();
storeLongMVV(ex1, 1);
ex1.fetch();
trx1.rollback();
trx1.end();
_persistit.getTransactionIndex().updateActiveTransactionCache();
ex1.prune();
ex1.getValue().put(RED_FOX);
ex1.to(0).store();
/*
* This method throws a CorruptVolumeException
*/
ex1.to(1).fetch();
assertTrue("Value should have been removed by rollback", !ex1.getValue().isDefined());
}
| public void induceCorruption() throws Exception {
/*
* 1. Create a page with a long record MVV.
*
* 2. Read the value to set up the LevelCache
*
* 3. Abort the transaction so that long record MVV will become an
* AntiValue
*
* 4. Prune the Buffer to liberate the long record chain.
*
* 5. Store a value in the page (not yet certain why this is needed to
* induce the bug, but it is.)
*
* 6. Attempt to the read the first value back in.
*
* Theory of bug is that the read attempt will not see a generation
* change, will use the LevelCache, and will attempt to read a long
* record from a page that has now become a data page.
*/
/*
* Disable background pruning
*/
_persistit.getCleanupManager().setPollInterval(-1);
/*
* Bump the generation number -- perhaps unnecessary
*/
for (int i = 0; i < 10; i++) {
ex1.to(i).store();
ex1.remove();
}
/*
* Store a single Long MVV
*/
trx1.begin();
storeLongMVV(ex1, 1);
ex1.fetch();
trx1.rollback();
trx1.end();
_persistit.getTransactionIndex().updateActiveTransactionCache();
ex1.prune();
ex1.getValue().put(RED_FOX);
ex1.to(0).store();
/*
* This method throws a CorruptVolumeException
*/
ex1.to(1).fetch();
assertTrue("Value should have been removed by rollback", !ex1.getValue().isDefined());
}
|
diff --git a/src/org/pentaho/platform/dataaccess/datasource/wizard/models/DatasourceDTOUtil.java b/src/org/pentaho/platform/dataaccess/datasource/wizard/models/DatasourceDTOUtil.java
index 48e82091..0c8c1bba 100644
--- a/src/org/pentaho/platform/dataaccess/datasource/wizard/models/DatasourceDTOUtil.java
+++ b/src/org/pentaho/platform/dataaccess/datasource/wizard/models/DatasourceDTOUtil.java
@@ -1,27 +1,29 @@
package org.pentaho.platform.dataaccess.datasource.wizard.models;
/**
* User: nbaker
* Date: Aug 13, 2010
*/
public class DatasourceDTOUtil {
public static DatasourceDTO generateDTO(DatasourceModel model){
DatasourceDTO dto = new DatasourceDTO();
dto.setDatasourceName(model.getDatasourceName());
dto.setCsvModelInfo(model.getModelInfo());
dto.setDatasourceType(model.getDatasourceType());
dto.setQuery(model.getQuery());
- dto.setConnectionName(model.getSelectedRelationalConnection().getName());
+ if(model.getSelectedRelationalConnection() != null){
+ dto.setConnectionName(model.getSelectedRelationalConnection().getName());
+ }
return dto;
}
public static void populateModel(DatasourceDTO dto, DatasourceModel model){
model.setDatasourceName(dto.getDatasourceName());
model.setModelInfo(dto.getCsvModelInfo());
model.setDatasourceType(dto.getDatasourceType());
model.setQuery(dto.getQuery());
model.setSelectedRelationalConnection(model.getGuiStateModel().getConnectionByName(dto.getConnectionName()));
}
}
| true | true | public static DatasourceDTO generateDTO(DatasourceModel model){
DatasourceDTO dto = new DatasourceDTO();
dto.setDatasourceName(model.getDatasourceName());
dto.setCsvModelInfo(model.getModelInfo());
dto.setDatasourceType(model.getDatasourceType());
dto.setQuery(model.getQuery());
dto.setConnectionName(model.getSelectedRelationalConnection().getName());
return dto;
}
| public static DatasourceDTO generateDTO(DatasourceModel model){
DatasourceDTO dto = new DatasourceDTO();
dto.setDatasourceName(model.getDatasourceName());
dto.setCsvModelInfo(model.getModelInfo());
dto.setDatasourceType(model.getDatasourceType());
dto.setQuery(model.getQuery());
if(model.getSelectedRelationalConnection() != null){
dto.setConnectionName(model.getSelectedRelationalConnection().getName());
}
return dto;
}
|
diff --git a/src/com/grademaster/servlets/IndexServlet.java b/src/com/grademaster/servlets/IndexServlet.java
index 1da1b0e..4bc73be 100644
--- a/src/com/grademaster/servlets/IndexServlet.java
+++ b/src/com/grademaster/servlets/IndexServlet.java
@@ -1,41 +1,41 @@
package com.grademaster.servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.grademaster.Globals;
import com.grademaster.data.objects.User;
import com.grademaster.logging.ErrorLevel;
import com.grademaster.logging.Logger;
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = -9088365072065846961L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
Logger log = Globals.getLogger();
log.log("Login servlet running...",ErrorLevel.INFO);
log.log("Login servlet is not complete yet.",ErrorLevel.WARNING);
boolean loggedIn = (Boolean) req.getSession(true).getAttribute("loggedIn");
- if (loggedIn==true) {
+ if (loggedIn==true && req.getAttribute("user")!=null) {
String redirect="index_misc.jsp";
String accountType = ((User) req.getSession(true).getAttribute("user")).getUserType();
if (accountType!=null && accountType=="teacher") {
redirect = "teacher_index.jsp";
} else if (accountType!=null && accountType=="student") {
redirect = "student_index.jsp";
}
log.log("Index dispatched to: " + redirect);
RequestDispatcher view = req.getRequestDispatcher(redirect);
view.forward(req, res);
} else {
res.sendRedirect("login.do");
}
}
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
Logger log = Globals.getLogger();
log.log("Login servlet running...",ErrorLevel.INFO);
log.log("Login servlet is not complete yet.",ErrorLevel.WARNING);
boolean loggedIn = (Boolean) req.getSession(true).getAttribute("loggedIn");
if (loggedIn==true) {
String redirect="index_misc.jsp";
String accountType = ((User) req.getSession(true).getAttribute("user")).getUserType();
if (accountType!=null && accountType=="teacher") {
redirect = "teacher_index.jsp";
} else if (accountType!=null && accountType=="student") {
redirect = "student_index.jsp";
}
log.log("Index dispatched to: " + redirect);
RequestDispatcher view = req.getRequestDispatcher(redirect);
view.forward(req, res);
} else {
res.sendRedirect("login.do");
}
}
| public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
Logger log = Globals.getLogger();
log.log("Login servlet running...",ErrorLevel.INFO);
log.log("Login servlet is not complete yet.",ErrorLevel.WARNING);
boolean loggedIn = (Boolean) req.getSession(true).getAttribute("loggedIn");
if (loggedIn==true && req.getAttribute("user")!=null) {
String redirect="index_misc.jsp";
String accountType = ((User) req.getSession(true).getAttribute("user")).getUserType();
if (accountType!=null && accountType=="teacher") {
redirect = "teacher_index.jsp";
} else if (accountType!=null && accountType=="student") {
redirect = "student_index.jsp";
}
log.log("Index dispatched to: " + redirect);
RequestDispatcher view = req.getRequestDispatcher(redirect);
view.forward(req, res);
} else {
res.sendRedirect("login.do");
}
}
|
diff --git a/proxy/src/main/java/org/fedoraproject/candlepin/resource/ConsumerResource.java b/proxy/src/main/java/org/fedoraproject/candlepin/resource/ConsumerResource.java
index 06598d9ea..2f4fbb0a7 100644
--- a/proxy/src/main/java/org/fedoraproject/candlepin/resource/ConsumerResource.java
+++ b/proxy/src/main/java/org/fedoraproject/candlepin/resource/ConsumerResource.java
@@ -1,975 +1,975 @@
/**
* Copyright (c) 2009 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.fedoraproject.candlepin.resource;
import org.fedoraproject.candlepin.audit.Event;
import org.fedoraproject.candlepin.audit.EventAdapter;
import org.fedoraproject.candlepin.audit.EventFactory;
import org.fedoraproject.candlepin.audit.EventSink;
import org.fedoraproject.candlepin.auth.Access;
import org.fedoraproject.candlepin.auth.Principal;
import org.fedoraproject.candlepin.auth.SystemPrincipal;
import org.fedoraproject.candlepin.auth.UserPrincipal;
import org.fedoraproject.candlepin.controller.PoolManager;
import org.fedoraproject.candlepin.exceptions.BadRequestException;
import org.fedoraproject.candlepin.exceptions.CandlepinException;
import org.fedoraproject.candlepin.exceptions.ForbiddenException;
import org.fedoraproject.candlepin.exceptions.IseException;
import org.fedoraproject.candlepin.exceptions.NotFoundException;
import org.fedoraproject.candlepin.model.CertificateSerialDto;
import org.fedoraproject.candlepin.model.Consumer;
import org.fedoraproject.candlepin.model.ConsumerCurator;
import org.fedoraproject.candlepin.model.ConsumerType;
import org.fedoraproject.candlepin.model.ConsumerType.ConsumerTypeEnum;
import org.fedoraproject.candlepin.model.ConsumerTypeCurator;
import org.fedoraproject.candlepin.model.Entitlement;
import org.fedoraproject.candlepin.model.EntitlementCertificate;
import org.fedoraproject.candlepin.model.EntitlementCurator;
import org.fedoraproject.candlepin.model.EventCurator;
import org.fedoraproject.candlepin.model.IdentityCertificate;
import org.fedoraproject.candlepin.model.Owner;
import org.fedoraproject.candlepin.model.OwnerCurator;
import org.fedoraproject.candlepin.model.Pool;
import org.fedoraproject.candlepin.model.Product;
import org.fedoraproject.candlepin.model.Subscription;
import org.fedoraproject.candlepin.model.User;
import org.fedoraproject.candlepin.policy.EntitlementRefusedException;
import org.fedoraproject.candlepin.policy.js.consumer.ConsumerDeleteHelper;
import org.fedoraproject.candlepin.policy.js.consumer.ConsumerRules;
import org.fedoraproject.candlepin.service.EntitlementCertServiceAdapter;
import org.fedoraproject.candlepin.service.IdentityCertServiceAdapter;
import org.fedoraproject.candlepin.service.ProductServiceAdapter;
import org.fedoraproject.candlepin.service.SubscriptionServiceAdapter;
import org.fedoraproject.candlepin.service.UserServiceAdapter;
import org.fedoraproject.candlepin.sync.ExportCreationException;
import org.fedoraproject.candlepin.sync.Exporter;
import org.fedoraproject.candlepin.util.Util;
import com.google.inject.Inject;
import com.wideplay.warp.persist.Transactional;
import org.apache.log4j.Logger;
import org.jboss.resteasy.annotations.providers.jaxb.Wrapped;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.xnap.commons.i18n.I18n;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.fedoraproject.candlepin.auth.interceptor.SecurityHole;
import org.fedoraproject.candlepin.auth.interceptor.Verify;
/**
* API Gateway for Consumers
*/
@Path("/consumers")
public class ConsumerResource {
private static final Pattern CONSUMER_NAME_PATTERN = Pattern
.compile("[\\#\\?\\'\\`\\!@{}()\\[\\]\\?&\\w-\\.]+");
private static Logger log = Logger.getLogger(ConsumerResource.class);
private ConsumerCurator consumerCurator;
private ConsumerTypeCurator consumerTypeCurator;
private ProductServiceAdapter productAdapter;
private SubscriptionServiceAdapter subAdapter;
private EntitlementCurator entitlementCurator;
private IdentityCertServiceAdapter identityCertService;
private EntitlementCertServiceAdapter entCertService;
private UserServiceAdapter userService;
private I18n i18n;
private EventSink sink;
private EventFactory eventFactory;
private EventCurator eventCurator;
private EventAdapter eventAdapter;
private static final int FEED_LIMIT = 1000;
private Exporter exporter;
private PoolManager poolManager;
private ConsumerRules consumerRules;
private ConsumerDeleteHelper consumerDeleteHelper;
private OwnerCurator ownerCurator;
@Inject
public ConsumerResource(ConsumerCurator consumerCurator,
ConsumerTypeCurator consumerTypeCurator,
ProductServiceAdapter productAdapter,
SubscriptionServiceAdapter subAdapter,
EntitlementCurator entitlementCurator,
IdentityCertServiceAdapter identityCertService,
EntitlementCertServiceAdapter entCertServiceAdapter, I18n i18n,
EventSink sink, EventFactory eventFactory, EventCurator eventCurator,
EventAdapter eventAdapter, UserServiceAdapter userService,
Exporter exporter, PoolManager poolManager,
ConsumerRules consumerRules, ConsumerDeleteHelper consumerDeleteHelper,
OwnerCurator ownerCurator) {
this.consumerCurator = consumerCurator;
this.consumerTypeCurator = consumerTypeCurator;
this.productAdapter = productAdapter;
this.subAdapter = subAdapter;
this.entitlementCurator = entitlementCurator;
this.identityCertService = identityCertService;
this.entCertService = entCertServiceAdapter;
this.i18n = i18n;
this.sink = sink;
this.eventFactory = eventFactory;
this.eventCurator = eventCurator;
this.userService = userService;
this.exporter = exporter;
this.poolManager = poolManager;
this.consumerRules = consumerRules;
this.consumerDeleteHelper = consumerDeleteHelper;
this.ownerCurator = ownerCurator;
this.eventAdapter = eventAdapter;
}
/**
* List available Consumers
*
* @return list of available consumers.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Wrapped(element = "consumers")
public List<Consumer> list(@QueryParam("username") String userName,
@QueryParam("type") String typeLabel,
@QueryParam("owner") String ownerKey) {
ConsumerType type = null;
if (typeLabel != null) {
type = lookupConsumerType(typeLabel);
}
Owner owner = null;
if (ownerKey != null) {
owner = ownerCurator.lookupByKey(ownerKey);
if (owner == null) {
throw new NotFoundException(i18n.tr(
"owner with key: {0} was not found.", ownerKey));
}
}
// We don't look up the user and warn if it doesn't exist here to not
// give away usernames
return consumerCurator.listByUsernameAndType(userName, type, owner);
}
/**
* Return the consumer identified by the given uuid.
*
* @param uuid uuid of the consumer sought.
* @return the consumer identified by the given uuid.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{consumer_uuid}")
public Consumer getConsumer(@PathParam("consumer_uuid") @Verify(Consumer.class) String uuid) {
Consumer consumer = verifyAndLookupConsumer(uuid);
if (consumer != null) {
// enrich with subscription data
consumer.setCanActivate(subAdapter
.canActivateSubscription(consumer));
}
return consumer;
}
/**
* Create a Consumer.
*
* NOTE: Opening this method up to everyone, as we have nothing we can reliably verify
* in the method signature. Instead we have to figure out what owner this consumer is
* destined for (due to backward compatability with existing clients which do not
* specify an owner during registration), and then check the access to the specified
* owner in the method itself.
*
* @param consumer Consumer metadata
* @return newly created Consumer
* @throws BadRequestException generic exception type for web services We
* are calling this "registerConsumer" in the api discussions
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@SecurityHole
public Consumer create(Consumer consumer, @Context Principal principal,
@QueryParam("username") String userName, @QueryParam("owner") String ownerKey)
throws BadRequestException {
// API:registerConsumer
if (!isConsumerNameValid(consumer.getName())) {
throw new BadRequestException(
i18n.tr("System name cannot contain most special characters."));
}
if (consumer.getName().indexOf('#') == 0) {
// this is a bouncycastle restriction
throw new BadRequestException(
i18n.tr("System name cannot begin with # character"));
}
// If no owner was specified, try to assume based on which owners the principal
// has admin rights for. If more than one, we have to error out.
if (ownerKey == null) {
// check for this cast?
List<String> ownerKeys = ((UserPrincipal) principal).getOwnerKeys();
if (ownerKeys.size() != 1) {
throw new BadRequestException(
i18n.tr("Must specify owner for new consumer."));
}
ownerKey = ownerKeys.get(0);
}
ConsumerType type = lookupConsumerType(consumer.getType().getLabel());
User user = getCurrentUsername(principal);
if (userName != null) {
user = userService.findByLogin(userName);
}
setupOwners((UserPrincipal) principal);
// TODO: Refactor out type specific checks?
if (type.isType(ConsumerTypeEnum.PERSON) && user != null) {
Consumer existing = consumerCurator.findByUser(user);
if (existing != null &&
existing.getType().isType(ConsumerTypeEnum.PERSON)) {
// TODO: This is not the correct error code for this situation!
throw new BadRequestException(i18n.tr(
"User {0} has already registered a personal consumer",
user.getUsername()));
}
consumer.setName(user.getUsername());
}
Owner owner = ownerCurator.lookupByKey(ownerKey);
if (owner == null) {
throw new BadRequestException(i18n.tr("Owner {0} does not exist", ownerKey));
}
if (!principal.canAccess(owner, Access.ALL)) {
throw new ForbiddenException(i18n.tr("User {0} cannot access owner {1}",
principal.getPrincipalName(), owner.getKey()));
}
// When registering person consumers we need to be sure the username
// has some association with the owner the consumer is destined for:
- if (!user.getOwners().contains(owner)) {
+ if (!user.getOwners().contains(owner) && !user.isSuperAdmin()) {
throw new ForbiddenException(i18n.tr("User {0} has no roles for owner {1}",
user.getUsername(), owner.getKey()));
}
consumer.setUsername(user.getUsername());
consumer.setOwner(owner);
consumer.setType(type);
consumer.setCanActivate(subAdapter.canActivateSubscription(consumer));
if (log.isDebugEnabled()) {
log.debug("Got consumerTypeLabel of: " + type.getLabel());
log.debug("got metadata: ");
log.debug(consumer.getFacts());
for (String key : consumer.getFacts().keySet()) {
log.debug(" " + key + " = " + consumer.getFact(key));
}
}
try {
consumer = consumerCurator.create(consumer);
IdentityCertificate idCert = generateIdCert(consumer, false);
consumer.setIdCert(idCert);
sink.emitConsumerCreated(consumer);
return consumer;
}
catch (CandlepinException ce) {
// If it is one of ours, rethrow it.
throw ce;
}
catch (Exception e) {
log.error("Problem creating consumer:", e);
e.printStackTrace();
throw new BadRequestException(i18n.tr(
"Problem creating consumer {0}", consumer));
}
}
private boolean isConsumerNameValid(String name) {
if (name == null) {
return false;
}
return CONSUMER_NAME_PATTERN.matcher(name).matches();
}
/*
* During registration of new consumers we support an edge case where the user
* service may have authenticated a username/password for an owner which we have
* not yet created in the Candlepin database. If we detect this during
* registration we need to create the new owners, and adjust
* the principal that was created during authentication to carry it.
*/
// TODO: Reevaluate if this is still an issue with the new membership scheme!
private void setupOwners(UserPrincipal principal) {
for (Owner owner : principal.getOwners()) {
Owner existingOwner = ownerCurator.lookupByKey(owner.getKey());
if (existingOwner == null) {
log.info("Principal carries permission for owner that does not exist.");
log.info("Creating new owner: " + owner.getKey());
// Need elevated privileges to create a new owner:
Principal systemPrincipal = new SystemPrincipal();
ResteasyProviderFactory.pushContext(Principal.class,
systemPrincipal);
existingOwner = ownerCurator.create(owner);
poolManager.refreshPools(existingOwner);
//p.setOwner(existingOwner);
ResteasyProviderFactory.popContextData(Principal.class);
// Restore the old principal having elevated privileges earlier:
ResteasyProviderFactory.pushContext(Principal.class, principal);
}
}
}
private ConsumerType lookupConsumerType(String label) {
ConsumerType type = consumerTypeCurator.lookupByLabel(label);
if (type == null) {
throw new BadRequestException(i18n.tr("No such consumer type: {0}",
label));
}
return type;
}
private User getCurrentUsername(Principal principal) {
if (principal instanceof UserPrincipal) {
UserPrincipal user = (UserPrincipal) principal;
return userService.findByLogin(user.getUsername());
}
return null;
}
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Path("{consumer_uuid}")
@Transactional
public void updateConsumer(@PathParam("consumer_uuid") String uuid,
Consumer consumer, @Context Principal principal) {
Consumer toUpdate = verifyAndLookupConsumer(uuid);
log.debug("Updating");
if (!toUpdate.factsAreEqual(consumer)) {
log.debug("Facts are not equal, updating them");
Event event = eventFactory.consumerModified(toUpdate, consumer);
// TODO: Just updating the facts for now
toUpdate.setFacts(consumer.getFacts());
sink.sendEvent(event);
}
}
/**
* delete the consumer.
*
* @param uuid uuid of the consumer to delete.
*/
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("{consumer_uuid}")
@Transactional
public void deleteConsumer(@PathParam("consumer_uuid") @Verify(Consumer.class) String uuid,
@Context Principal principal) {
log.debug("deleting consumer_uuid" + uuid);
Consumer toDelete = verifyAndLookupConsumer(uuid);
try {
this.poolManager.revokeAllEntitlements(toDelete);
}
catch (ForbiddenException e) {
String msg = e.message().getDisplayMessage();
throw new ForbiddenException(i18n.tr(
"Cannot unregister {0} consumer {1} because: {2}", toDelete
.getType().getLabel(), toDelete.getName(), msg), e);
}
consumerRules.onConsumerDelete(consumerDeleteHelper, toDelete);
Event event = eventFactory.consumerDeleted(toDelete);
consumerCurator.delete(toDelete);
identityCertService.deleteIdentityCert(toDelete);
sink.sendEvent(event);
}
/**
* Return the entitlement certificate for the given consumer.
*
* @param consumerUuid UUID of the consumer
* @return list of the client certificates for the given consumer.
*/
@GET
@Path("{consumer_uuid}/certificates")
@Produces(MediaType.APPLICATION_JSON)
public List<EntitlementCertificate> getEntitlementCertificates(
@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid,
@QueryParam("serials") String serials) {
log.debug("Getting client certificates for consumer: " + consumerUuid);
Consumer consumer = verifyAndLookupConsumer(consumerUuid);
Set<Long> serialSet = new HashSet<Long>();
if (serials != null) {
log.debug("Requested serials: " + serials);
for (String s : serials.split(",")) {
log.debug(" " + s);
serialSet.add(Long.valueOf(s));
}
}
List<EntitlementCertificate> returnCerts = new LinkedList<EntitlementCertificate>();
List<EntitlementCertificate> allCerts = entCertService
.listForConsumer(consumer);
for (EntitlementCertificate cert : allCerts) {
if (serialSet.isEmpty() ||
serialSet.contains(cert.getSerial().getId())) {
returnCerts.add(cert);
}
}
return returnCerts;
}
/**
* Return the client certificate metadata for the given consumer. This is a
* small subset of data clients can use to determine which certificates they
* need to update/fetch.
*
* @param consumerUuid UUID of the consumer
* @return list of the client certificate metadata for the given consumer.
*/
@GET
@Path("{consumer_uuid}/certificates/serials")
@Produces(MediaType.APPLICATION_JSON)
@Wrapped(element = "serials")
public List<CertificateSerialDto> getEntitlementCertificateSerials(
@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid) {
log.debug("Getting client certificate serials for consumer: " +
consumerUuid);
Consumer consumer = verifyAndLookupConsumer(consumerUuid);
List<CertificateSerialDto> allCerts = new LinkedList<CertificateSerialDto>();
for (EntitlementCertificate cert : entCertService
.listForConsumer(consumer)) {
allCerts.add(new CertificateSerialDto(cert.getSerial().getId()));
}
return allCerts;
}
/**
* Entitles the given Consumer to the given Product. Will seek out pools
* which provide access to this product, either directly or as a child, and
* select the best one based on a call to the rules engine.
*
* @param productId Product ID.
* @return Entitlement object.
*/
// TODO: Bleh, very duplicated methods here:
private List<Entitlement> bindByProducts(String[] productIds,
Consumer consumer, Integer quantity) {
// Attempt to create entitlements:
try {
List<Entitlement> entitlements = poolManager.entitleByProducts(
consumer, productIds, quantity);
log.debug("Created entitlements: " + entitlements);
return entitlements;
}
catch (EntitlementRefusedException e) {
// Could be multiple errors, but we'll just report the first one for
// now:
// TODO: Convert resource key to user friendly string?
// See below for more TODOS
String productId = "XXX FIXME";
String msg;
String error = e.getResult().getErrors().get(0).getResourceKey();
if (error.equals("rulefailed.consumer.already.has.product")) {
msg = i18n
.tr("This consumer is already subscribed to the product ''{0}''",
productId);
}
else if (error.equals("rulefailed.no.entitlements.available")) {
msg = i18n
.tr("No free entitlements are available for the product ''{0}''",
productId);
}
else if (error.equals("rulefailed.consumer.type.mismatch")) {
msg = i18n
.tr("Consumers of this type are not allowed to the product ''{0}''",
productId);
}
else if (error.equals("rulefailed.virt.only")) {
msg = i18n.tr(
"Only virtual systems can consume the product ''{0}''",
productId);
}
else {
msg = i18n.tr(
"Unable to entitle consumer to the product ''{0}'': {1}",
productId, error);
}
throw new ForbiddenException(msg);
}
}
private Entitlement createEntitlementByPool(Consumer consumer, Pool pool,
Integer quantity) {
// Attempt to create an entitlement:
try {
Entitlement e = poolManager.entitleByPool(consumer, pool, quantity);
log.debug("Created entitlement: " + e);
return e;
}
catch (EntitlementRefusedException e) {
// Could be multiple errors, but we'll just report the first one for
// now:
// TODO: multiple checks here for the errors will get ugly, but the
// returned
// string is dependent on the caller (ie pool vs product)
String msg;
String error = e.getResult().getErrors().get(0).getResourceKey();
if (error.equals("rulefailed.consumer.already.has.product")) {
msg = i18n.tr(
"This consumer is already subscribed to the product matching pool " +
"with id ''{0}''", pool.getId().toString());
}
else if (error.equals("rulefailed.no.entitlements.available")) {
msg = i18n
.tr("No free entitlements are available for the pool with id ''{0}''",
pool.getId().toString());
}
else if (error.equals("rulefailed.consumer.type.mismatch")) {
msg = i18n.tr(
"Consumers of this type are not allowed to subscribe to the pool " +
"with id ''{0}''", pool.getId().toString());
}
else {
msg = i18n
.tr("Unable to entitle consumer to the pool with id ''{0}'': {1}",
pool.getId().toString(), error);
}
throw new ForbiddenException(msg);
}
}
/**
* Grants entitlements based on a registration token.
*
* @param registrationToken registration token.
* @param consumer Consumer to bind
* @return token
*/
private List<Entitlement> bindByToken(String registrationToken,
Consumer consumer, Integer quantity, String email, String emailLocale) {
List<Subscription> subs = subAdapter.getSubscriptionForToken(
consumer.getOwner(), registrationToken, email, emailLocale);
if ((subs == null) || (subs.isEmpty())) {
log.debug("token: " + registrationToken);
throw new BadRequestException(i18n.tr("No such token: {0}",
registrationToken));
}
List<Entitlement> entitlementList = new LinkedList<Entitlement>();
for (Subscription sub : subs) {
// Make sure we have created/updated a pool for this subscription:
Pool pool = poolManager.lookupBySubscriptionId(sub.getId());
if (pool == null) {
// WARNING: Assumption here that a bind by token subscription
// will only link up to one pool, or at least that we'll try to
// bind
// to the *first* one it created:
pool = poolManager.createPoolsForSubscription(sub).get(0);
}
else {
poolManager.updatePoolForSubscription(pool, sub);
}
entitlementList.add(createEntitlementByPool(consumer, pool,
quantity));
}
return entitlementList;
}
private List<Entitlement> bindByPool(String poolId, Consumer consumer,
Integer quantity) {
Pool pool = poolManager.find(poolId);
List<Entitlement> entitlementList = new LinkedList<Entitlement>();
if (log.isDebugEnabled() && pool != null) {
log.debug("pool: id[" + pool.getId() + "], consumed[" +
pool.getConsumed() + "], qty [" + pool.getQuantity() + "]");
}
if (pool == null) {
throw new BadRequestException(i18n.tr(
"No such entitlement pool: {0}", poolId));
}
// Attempt to create an entitlement:
entitlementList.add(createEntitlementByPool(consumer, pool, quantity));
return entitlementList;
}
/**
* Request an entitlement.
*
* @param consumerUuid Consumer identifier to be entitled
* @param poolIdString Entitlement pool id.
* @param email TODO
* @param emailLocale TODO
* @return Entitlement.
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{consumer_uuid}/entitlements")
public List<Entitlement> bind(
@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid,
@QueryParam("pool") String poolIdString,
@QueryParam("token") String token,
@QueryParam("product") String[] productIds,
@QueryParam("quantity") @DefaultValue("1") Integer quantity,
@QueryParam("email") String email,
@QueryParam("email_locale") String emailLocale) {
// Check that only one query param was set:
if ((poolIdString != null && token != null) ||
(poolIdString != null && productIds != null && productIds.length > 0) ||
(token != null && productIds != null && productIds.length > 0)) {
throw new BadRequestException(
i18n.tr("Cannot bind by multiple parameters."));
}
// Verify consumer exists:
Consumer consumer = verifyAndLookupConsumer(consumerUuid);
List<Entitlement> entitlements = null;
try {
if (!subAdapter.hasUnacceptedSubscriptionTerms(consumer.getOwner())) {
if (token != null) {
entitlements = bindByToken(token, consumer, quantity,
email, emailLocale);
}
else if (productIds != null && productIds.length > 0) {
entitlements = bindByProducts(productIds, consumer,
quantity);
}
else {
String poolId = Util.assertNotNull(poolIdString,
i18n.tr("Pool ID must be provided"));
entitlements = bindByPool(poolId, consumer, quantity);
}
}
}
catch (CandlepinException e) {
log.debug(e.getMessage());
throw e;
}
// Trigger events:
for (Entitlement e : entitlements) {
Event event = eventFactory.entitlementCreated(e);
sink.sendEvent(event);
}
return entitlements;
}
private Consumer verifyAndLookupConsumer(String consumerUuid) {
Consumer consumer = consumerCurator.findByUuid(consumerUuid);
if (consumer == null) {
throw new NotFoundException(i18n.tr("No such consumer: {0}",
consumerUuid));
}
return consumer;
}
private Entitlement verifyAndLookupEntitlement(String entitlementId) {
Entitlement entitlement = entitlementCurator.find(entitlementId);
if (entitlement == null) {
throw new NotFoundException(i18n.tr("No such entitlement: {0}",
entitlementId));
}
return entitlement;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{consumer_uuid}/entitlements")
public List<Entitlement> listEntitlements(
@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid,
@QueryParam("product") String productId) {
Consumer consumer = verifyAndLookupConsumer(consumerUuid);
if (productId != null) {
Product p = productAdapter.getProductById(productId);
if (p == null) {
throw new BadRequestException(i18n.tr("No such product: {0}",
productId));
}
return entitlementCurator.listByConsumerAndProduct(consumer,
productId);
}
return entitlementCurator.listByConsumer(consumer);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{consumer_uuid}/owner")
public Owner getOwner(@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid) {
Consumer consumer = verifyAndLookupConsumer(consumerUuid);
return consumer.getOwner();
}
/**
* Unbind all entitlements.
*
* @param consumerUuid Unique id for the Consumer.
*/
@DELETE
@Path("/{consumer_uuid}/entitlements")
public void unbindAll(@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid) {
// FIXME: just a stub, needs CertifcateService (and/or a
// CertificateCurator) to lookup by serialNumber
Consumer consumer = verifyAndLookupConsumer(consumerUuid);
if (consumer == null) {
throw new NotFoundException(i18n.tr("Consumer with ID " +
consumerUuid + " could not be found."));
}
poolManager.revokeAllEntitlements(consumer);
// Need to parse off the value of subscriptionNumberArgs, probably
// use comma separated see IntergerList in sparklines example in
// jersey examples find all entitlements for this consumer and
// subscription numbers delete all of those (and/or return them to
// entitlement pool)
}
/**
* Remove an entitlement by ID.
*
* @param dbid the entitlement to delete.
*/
@DELETE
@Path("/{consumer_uuid}/entitlements/{dbid}")
public void unbind(@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid,
@PathParam("dbid") String dbid, @Context Principal principal) {
verifyAndLookupConsumer(consumerUuid);
Entitlement toDelete = entitlementCurator.find(dbid);
if (toDelete != null) {
poolManager.revokeEntitlement(toDelete);
return;
}
throw new NotFoundException(i18n.tr(
"Entitlement with ID '{0}' could not be found.", dbid));
}
@DELETE
@Path("/{consumer_uuid}/certificates/{serial}")
public void unbindBySerial(@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid,
@PathParam("serial") Long serial) {
verifyAndLookupConsumer(consumerUuid);
Entitlement toDelete = entitlementCurator
.findByCertificateSerial(serial);
if (toDelete != null) {
poolManager.revokeEntitlement(toDelete);
return;
}
throw new NotFoundException(
i18n.tr(
"Entitlement Certificate with serial number {0} could not be found.",
serial.toString())); // prevent serial number formatting.
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{consumer_uuid}/events")
public List<Event> getConsumerEvents(
@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid) {
Consumer consumer = verifyAndLookupConsumer(consumerUuid);
List<Event> events = this.eventCurator.listMostRecent(FEED_LIMIT,
consumer);
if (events != null) {
eventAdapter.addMessageText(events);
}
return events;
}
@PUT
@Path("/{consumer_uuid}/certificates")
public void regenerateEntitlementCertificates(
@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid,
@QueryParam("entitlement") String entitlementId) {
if (entitlementId != null) {
Entitlement e = verifyAndLookupEntitlement(entitlementId);
poolManager.regenerateCertificatesOf(e);
}
else {
Consumer c = verifyAndLookupConsumer(consumerUuid);
poolManager.regenerateEntitlementCertificates(c);
}
}
@GET
@Produces("application/zip")
@Path("{consumer_uuid}/export")
public File exportData(@Context HttpServletResponse response,
@PathParam("consumer_uuid") String consumerUuid) {
Consumer consumer = verifyAndLookupConsumer(consumerUuid);
if (!consumer.getType().isType(ConsumerTypeEnum.CANDLEPIN)) {
throw new ForbiddenException(
i18n.tr(
"Consumer {0} cannot be exported, as it's of wrong consumer type.",
consumerUuid));
}
File archive;
try {
archive = exporter.getExport(consumer);
response.addHeader("Content-Disposition", "attachment; filename=" +
archive.getName());
sink.sendEvent(eventFactory.exportCreated(consumer));
return archive;
}
catch (ExportCreationException e) {
throw new IseException(i18n.tr("Unable to create export archive"),
e);
}
}
/**
* Return the consumer identified by the given uuid.
*
* @param uuid uuid of the consumer sought.
* @return the consumer identified by the given uuid.
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{consumer_uuid}")
public Consumer regenerateIdentityCertificates(
@PathParam("consumer_uuid") @Verify(Consumer.class) String uuid) {
Consumer c = verifyAndLookupConsumer(uuid);
try {
IdentityCertificate ic = generateIdCert(c, true);
c.setIdCert(ic);
consumerCurator.update(c);
Event consumerModified = this.eventFactory.consumerModified(c);
this.sink.sendEvent(consumerModified);
return c;
}
catch (Exception e) {
log.error("Problem regenerating id cert for consumer:", e);
throw new BadRequestException(i18n.tr(
"Problem regenerating id cert for consumer {0}", c));
}
}
/**
* Generates the identity certificate for the given consumer and user.
* Throws RuntimeException if there is a problem with generating the
* certificate.
*
* @param c Consumer whose certificate needs to be generated.
* @param regen if true, forces a regen of the certificate.
* @return The identity certificate for the given consumer.
* @throws IOException thrown if there's a problem generating the cert.
* @throws GeneralSecurityException thrown incase of security error.
*/
private IdentityCertificate generateIdCert(Consumer c, boolean regen)
throws GeneralSecurityException, IOException {
IdentityCertificate idCert = null;
if (regen) {
idCert = identityCertService.regenerateIdentityCert(c);
}
else {
idCert = identityCertService.generateIdentityCert(c);
}
if (log.isDebugEnabled()) {
log.debug("Generated identity cert: " + idCert);
log.debug("Created consumer: " + c);
}
if (idCert == null) {
throw new RuntimeException("Error generating identity certificate.");
}
return idCert;
}
}
| true | true | public Consumer create(Consumer consumer, @Context Principal principal,
@QueryParam("username") String userName, @QueryParam("owner") String ownerKey)
throws BadRequestException {
// API:registerConsumer
if (!isConsumerNameValid(consumer.getName())) {
throw new BadRequestException(
i18n.tr("System name cannot contain most special characters."));
}
if (consumer.getName().indexOf('#') == 0) {
// this is a bouncycastle restriction
throw new BadRequestException(
i18n.tr("System name cannot begin with # character"));
}
// If no owner was specified, try to assume based on which owners the principal
// has admin rights for. If more than one, we have to error out.
if (ownerKey == null) {
// check for this cast?
List<String> ownerKeys = ((UserPrincipal) principal).getOwnerKeys();
if (ownerKeys.size() != 1) {
throw new BadRequestException(
i18n.tr("Must specify owner for new consumer."));
}
ownerKey = ownerKeys.get(0);
}
ConsumerType type = lookupConsumerType(consumer.getType().getLabel());
User user = getCurrentUsername(principal);
if (userName != null) {
user = userService.findByLogin(userName);
}
setupOwners((UserPrincipal) principal);
// TODO: Refactor out type specific checks?
if (type.isType(ConsumerTypeEnum.PERSON) && user != null) {
Consumer existing = consumerCurator.findByUser(user);
if (existing != null &&
existing.getType().isType(ConsumerTypeEnum.PERSON)) {
// TODO: This is not the correct error code for this situation!
throw new BadRequestException(i18n.tr(
"User {0} has already registered a personal consumer",
user.getUsername()));
}
consumer.setName(user.getUsername());
}
Owner owner = ownerCurator.lookupByKey(ownerKey);
if (owner == null) {
throw new BadRequestException(i18n.tr("Owner {0} does not exist", ownerKey));
}
if (!principal.canAccess(owner, Access.ALL)) {
throw new ForbiddenException(i18n.tr("User {0} cannot access owner {1}",
principal.getPrincipalName(), owner.getKey()));
}
// When registering person consumers we need to be sure the username
// has some association with the owner the consumer is destined for:
if (!user.getOwners().contains(owner)) {
throw new ForbiddenException(i18n.tr("User {0} has no roles for owner {1}",
user.getUsername(), owner.getKey()));
}
consumer.setUsername(user.getUsername());
consumer.setOwner(owner);
consumer.setType(type);
consumer.setCanActivate(subAdapter.canActivateSubscription(consumer));
if (log.isDebugEnabled()) {
log.debug("Got consumerTypeLabel of: " + type.getLabel());
log.debug("got metadata: ");
log.debug(consumer.getFacts());
for (String key : consumer.getFacts().keySet()) {
log.debug(" " + key + " = " + consumer.getFact(key));
}
}
try {
consumer = consumerCurator.create(consumer);
IdentityCertificate idCert = generateIdCert(consumer, false);
consumer.setIdCert(idCert);
sink.emitConsumerCreated(consumer);
return consumer;
}
catch (CandlepinException ce) {
// If it is one of ours, rethrow it.
throw ce;
}
catch (Exception e) {
log.error("Problem creating consumer:", e);
e.printStackTrace();
throw new BadRequestException(i18n.tr(
"Problem creating consumer {0}", consumer));
}
}
| public Consumer create(Consumer consumer, @Context Principal principal,
@QueryParam("username") String userName, @QueryParam("owner") String ownerKey)
throws BadRequestException {
// API:registerConsumer
if (!isConsumerNameValid(consumer.getName())) {
throw new BadRequestException(
i18n.tr("System name cannot contain most special characters."));
}
if (consumer.getName().indexOf('#') == 0) {
// this is a bouncycastle restriction
throw new BadRequestException(
i18n.tr("System name cannot begin with # character"));
}
// If no owner was specified, try to assume based on which owners the principal
// has admin rights for. If more than one, we have to error out.
if (ownerKey == null) {
// check for this cast?
List<String> ownerKeys = ((UserPrincipal) principal).getOwnerKeys();
if (ownerKeys.size() != 1) {
throw new BadRequestException(
i18n.tr("Must specify owner for new consumer."));
}
ownerKey = ownerKeys.get(0);
}
ConsumerType type = lookupConsumerType(consumer.getType().getLabel());
User user = getCurrentUsername(principal);
if (userName != null) {
user = userService.findByLogin(userName);
}
setupOwners((UserPrincipal) principal);
// TODO: Refactor out type specific checks?
if (type.isType(ConsumerTypeEnum.PERSON) && user != null) {
Consumer existing = consumerCurator.findByUser(user);
if (existing != null &&
existing.getType().isType(ConsumerTypeEnum.PERSON)) {
// TODO: This is not the correct error code for this situation!
throw new BadRequestException(i18n.tr(
"User {0} has already registered a personal consumer",
user.getUsername()));
}
consumer.setName(user.getUsername());
}
Owner owner = ownerCurator.lookupByKey(ownerKey);
if (owner == null) {
throw new BadRequestException(i18n.tr("Owner {0} does not exist", ownerKey));
}
if (!principal.canAccess(owner, Access.ALL)) {
throw new ForbiddenException(i18n.tr("User {0} cannot access owner {1}",
principal.getPrincipalName(), owner.getKey()));
}
// When registering person consumers we need to be sure the username
// has some association with the owner the consumer is destined for:
if (!user.getOwners().contains(owner) && !user.isSuperAdmin()) {
throw new ForbiddenException(i18n.tr("User {0} has no roles for owner {1}",
user.getUsername(), owner.getKey()));
}
consumer.setUsername(user.getUsername());
consumer.setOwner(owner);
consumer.setType(type);
consumer.setCanActivate(subAdapter.canActivateSubscription(consumer));
if (log.isDebugEnabled()) {
log.debug("Got consumerTypeLabel of: " + type.getLabel());
log.debug("got metadata: ");
log.debug(consumer.getFacts());
for (String key : consumer.getFacts().keySet()) {
log.debug(" " + key + " = " + consumer.getFact(key));
}
}
try {
consumer = consumerCurator.create(consumer);
IdentityCertificate idCert = generateIdCert(consumer, false);
consumer.setIdCert(idCert);
sink.emitConsumerCreated(consumer);
return consumer;
}
catch (CandlepinException ce) {
// If it is one of ours, rethrow it.
throw ce;
}
catch (Exception e) {
log.error("Problem creating consumer:", e);
e.printStackTrace();
throw new BadRequestException(i18n.tr(
"Problem creating consumer {0}", consumer));
}
}
|
diff --git a/src/com/android/launcher2/CheckLongPressHelper.java b/src/com/android/launcher2/CheckLongPressHelper.java
index 3ccda263..5c3752ad 100644
--- a/src/com/android/launcher2/CheckLongPressHelper.java
+++ b/src/com/android/launcher2/CheckLongPressHelper.java
@@ -1,61 +1,62 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* 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.android.launcher2;
import android.view.View;
public class CheckLongPressHelper {
private View mView;
private boolean mHasPerformedLongPress;
private CheckForLongPress mPendingCheckForLongPress;
class CheckForLongPress implements Runnable {
public void run() {
if ((mView.getParent() != null) && mView.hasWindowFocus()
&& !mHasPerformedLongPress) {
if (mView.performLongClick()) {
+ mView.setPressed(false);
mHasPerformedLongPress = true;
}
}
}
}
public CheckLongPressHelper(View v) {
mView = v;
}
public void postCheckForLongPress() {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mView.postDelayed(mPendingCheckForLongPress, LauncherApplication.getLongPressTimeout());
}
public void cancelLongPress() {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress != null) {
mView.removeCallbacks(mPendingCheckForLongPress);
mPendingCheckForLongPress = null;
}
}
public boolean hasPerformedLongPress() {
return mHasPerformedLongPress;
}
}
| true | true | public void run() {
if ((mView.getParent() != null) && mView.hasWindowFocus()
&& !mHasPerformedLongPress) {
if (mView.performLongClick()) {
mHasPerformedLongPress = true;
}
}
}
| public void run() {
if ((mView.getParent() != null) && mView.hasWindowFocus()
&& !mHasPerformedLongPress) {
if (mView.performLongClick()) {
mView.setPressed(false);
mHasPerformedLongPress = true;
}
}
}
|
diff --git a/java_training/JPL/ch17/ex17_04/ResourceManager.java b/java_training/JPL/ch17/ex17_04/ResourceManager.java
index d6e022f..277cb01 100644
--- a/java_training/JPL/ch17/ex17_04/ResourceManager.java
+++ b/java_training/JPL/ch17/ex17_04/ResourceManager.java
@@ -1,78 +1,80 @@
package ch17.ex17_04;
import java.awt.RenderingHints.Key;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.HashMap;
import java.util.Map;
public final class ResourceManager {
final ReferenceQueue<Object> queue;
final Map<Reference<?>, Resource> refs;
final Thread reaper;
boolean shutdown = false;
public ResourceManager(){
queue = new ReferenceQueue<Object>();
refs = new HashMap<Reference<?>, Resource>();
reaper = new ReaperThread();
reaper.start();
}
public synchronized void shutdown(){
if(!shutdown){
shutdown = true;
}
}
public synchronized Resource getResource(Object key){
if(shutdown)
throw new IllegalStateException();
Resource res = new ResourceImple(key);
Reference<?> ref = new PhantomReference<Object>(key, queue);
refs.put(ref, res);
return res;
}
class ReaperThread extends Thread {
public void run(){
while(true){
// try{
- Reference<?> ref = queue.poll();
- if(ref==null && shutdown==true){
- break;
- }else if(ref==null){
+ //Reference<?> ref = queue.poll();
+ if(refs.size()==0 && shutdown==true){
+ return;
+ }else if(refs.size()==0){
continue;
}
Resource res = null;
- synchronized(ResourceManager.this){
- res = refs.get(ref);
- refs.remove(ref);
+ Reference<?> ref = queue.poll();
+ if(ref!=null){
+ synchronized(ResourceManager.this){
+ res = refs.remove(ref);
+ }
+ res.release();
+ System.out.println("##remove ref::"+ref.toString()+" res::"+res.toString());
+ ref.clear();
}
- res.release();
- ref.clear();
- System.out.println("##remove ref::"+ref.toString()+" res::"+res.toString());
// }
}
}
}
public static void main(String[] args) {
ResourceManager manager = new ResourceManager();
Object key = new Object();
Resource res = manager.getResource(key);
res.use(key, new Object());
Resource res2 = manager.getResource(key);
res2.use(key, new Object());
//stop repear thread
System.out.println("shutdown");
manager.shutdown();
//add key's ref to queue
key = null;
Runtime.getRuntime().gc();
}
}
| false | true | public void run(){
while(true){
// try{
Reference<?> ref = queue.poll();
if(ref==null && shutdown==true){
break;
}else if(ref==null){
continue;
}
Resource res = null;
synchronized(ResourceManager.this){
res = refs.get(ref);
refs.remove(ref);
}
res.release();
ref.clear();
System.out.println("##remove ref::"+ref.toString()+" res::"+res.toString());
// }
}
}
| public void run(){
while(true){
// try{
//Reference<?> ref = queue.poll();
if(refs.size()==0 && shutdown==true){
return;
}else if(refs.size()==0){
continue;
}
Resource res = null;
Reference<?> ref = queue.poll();
if(ref!=null){
synchronized(ResourceManager.this){
res = refs.remove(ref);
}
res.release();
System.out.println("##remove ref::"+ref.toString()+" res::"+res.toString());
ref.clear();
}
// }
}
}
|
diff --git a/src/main/tools/java/fi/csc/chipster/tools/LocalNGSPreprocess.java b/src/main/tools/java/fi/csc/chipster/tools/LocalNGSPreprocess.java
index 7747c4829..fe61df09e 100644
--- a/src/main/tools/java/fi/csc/chipster/tools/LocalNGSPreprocess.java
+++ b/src/main/tools/java/fi/csc/chipster/tools/LocalNGSPreprocess.java
@@ -1,94 +1,94 @@
package fi.csc.chipster.tools;
import java.io.File;
import fi.csc.chipster.tools.gbrowser.SamBamUtils;
import fi.csc.microarray.client.Session;
import fi.csc.microarray.client.operation.Operation;
import fi.csc.microarray.client.tasks.Task;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.ElandParser;
import fi.csc.microarray.client.visualisation.methods.gbrowser.fileFormat.TsvParser;
import fi.csc.microarray.databeans.DataBean;
import fi.csc.microarray.databeans.DataManager;
public class LocalNGSPreprocess implements Runnable {
private static TsvParser[] parsers = {
new ElandParser()
};
private Task task;
public LocalNGSPreprocess(Task task) {
this.task = task;
}
public static String getSADL() {
StringBuffer fileFormats = new StringBuffer();
for (int i = 0; i < parsers.length; i++) {
fileFormats.append(parsers[i].getName() + ": " + parsers[i].getName());
if (i < parsers.length - 1) {
fileFormats.append(", ");
}
}
return "TOOL \"Preprocess\" / LocalNGSPreprocess.java: \"NGS Preprocess\" (Sort primarily using chromosome and secondarily using start " +
"location of the feature. File format is used to find columns containing " +
"chromosome and start location. )" + "\n" +
"INPUT input{...}.txt: \"Input NGS data\" TYPE GENERIC" + "\n" +
"OUTPUT ngs-preprocess.txt: \"Preprocessed NGS data\"" + "\n" +
"OUTPUT phenodata.tsv: \"Phenodata\"";
}
public void run() {
DataManager dataManager = Session.getSession().getDataManager();
try {
for (DataBean inputDataBean : task.getInputs()) {
File inputFile = dataManager.getLocalFile(inputDataBean);
String outputName;
String indexOutputName;
String extension = "";
int fileExtensionStartPosition = inputFile.getName().lastIndexOf(".");
if (fileExtensionStartPosition != -1) {
outputName = inputFile.getName().substring(0, fileExtensionStartPosition) + "-preprocessed";
- extension = inputFile.getName().substring(fileExtensionStartPosition);
+ extension = inputFile.getName().substring(fileExtensionStartPosition + 1);
} else {
outputName = inputFile.getName() + "-preprocessed";
}
outputName = outputName + ".bam";
indexOutputName = outputName + ".bai";
File outputFile = dataManager.createNewRepositoryFile(outputName);
File indexOutputFile = dataManager.createNewRepositoryFile(indexOutputName);
// Run preprocessing
if (SamBamUtils.isSamBamExtension(extension)) {
SamBamUtils.preprocessSamBam(inputFile, outputFile, indexOutputFile);
} else {
// Assume ELAND format
SamBamUtils.preprocessEland(inputFile, outputFile, indexOutputFile);
}
// create outputs in the client
DataBean outputBean = dataManager.createDataBean(outputName, outputFile);
DataBean indexOutputBean = dataManager.createDataBean(indexOutputName, indexOutputFile);
// create new operation instance, without any inputs FIXME parameters are lost, sucks
outputBean.setOperation(new Operation(Session.getSession().getApplication().getOperationDefinition(task.getOperationID()), new DataBean[] {}));
indexOutputBean.setOperation(new Operation(Session.getSession().getApplication().getOperationDefinition(task.getOperationID()), new DataBean[] {}));
dataManager.getRootFolder().addChild(outputBean);
dataManager.getRootFolder().addChild(indexOutputBean);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| true | true | public void run() {
DataManager dataManager = Session.getSession().getDataManager();
try {
for (DataBean inputDataBean : task.getInputs()) {
File inputFile = dataManager.getLocalFile(inputDataBean);
String outputName;
String indexOutputName;
String extension = "";
int fileExtensionStartPosition = inputFile.getName().lastIndexOf(".");
if (fileExtensionStartPosition != -1) {
outputName = inputFile.getName().substring(0, fileExtensionStartPosition) + "-preprocessed";
extension = inputFile.getName().substring(fileExtensionStartPosition);
} else {
outputName = inputFile.getName() + "-preprocessed";
}
outputName = outputName + ".bam";
indexOutputName = outputName + ".bai";
File outputFile = dataManager.createNewRepositoryFile(outputName);
File indexOutputFile = dataManager.createNewRepositoryFile(indexOutputName);
// Run preprocessing
if (SamBamUtils.isSamBamExtension(extension)) {
SamBamUtils.preprocessSamBam(inputFile, outputFile, indexOutputFile);
} else {
// Assume ELAND format
SamBamUtils.preprocessEland(inputFile, outputFile, indexOutputFile);
}
// create outputs in the client
DataBean outputBean = dataManager.createDataBean(outputName, outputFile);
DataBean indexOutputBean = dataManager.createDataBean(indexOutputName, indexOutputFile);
// create new operation instance, without any inputs FIXME parameters are lost, sucks
outputBean.setOperation(new Operation(Session.getSession().getApplication().getOperationDefinition(task.getOperationID()), new DataBean[] {}));
indexOutputBean.setOperation(new Operation(Session.getSession().getApplication().getOperationDefinition(task.getOperationID()), new DataBean[] {}));
dataManager.getRootFolder().addChild(outputBean);
dataManager.getRootFolder().addChild(indexOutputBean);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
| public void run() {
DataManager dataManager = Session.getSession().getDataManager();
try {
for (DataBean inputDataBean : task.getInputs()) {
File inputFile = dataManager.getLocalFile(inputDataBean);
String outputName;
String indexOutputName;
String extension = "";
int fileExtensionStartPosition = inputFile.getName().lastIndexOf(".");
if (fileExtensionStartPosition != -1) {
outputName = inputFile.getName().substring(0, fileExtensionStartPosition) + "-preprocessed";
extension = inputFile.getName().substring(fileExtensionStartPosition + 1);
} else {
outputName = inputFile.getName() + "-preprocessed";
}
outputName = outputName + ".bam";
indexOutputName = outputName + ".bai";
File outputFile = dataManager.createNewRepositoryFile(outputName);
File indexOutputFile = dataManager.createNewRepositoryFile(indexOutputName);
// Run preprocessing
if (SamBamUtils.isSamBamExtension(extension)) {
SamBamUtils.preprocessSamBam(inputFile, outputFile, indexOutputFile);
} else {
// Assume ELAND format
SamBamUtils.preprocessEland(inputFile, outputFile, indexOutputFile);
}
// create outputs in the client
DataBean outputBean = dataManager.createDataBean(outputName, outputFile);
DataBean indexOutputBean = dataManager.createDataBean(indexOutputName, indexOutputFile);
// create new operation instance, without any inputs FIXME parameters are lost, sucks
outputBean.setOperation(new Operation(Session.getSession().getApplication().getOperationDefinition(task.getOperationID()), new DataBean[] {}));
indexOutputBean.setOperation(new Operation(Session.getSession().getApplication().getOperationDefinition(task.getOperationID()), new DataBean[] {}));
dataManager.getRootFolder().addChild(outputBean);
dataManager.getRootFolder().addChild(indexOutputBean);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
diff --git a/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java b/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
index 32c4007..c71235f 100644
--- a/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
+++ b/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/GameSystem.java
@@ -1,274 +1,277 @@
/*
* Copyright © 2013, Pierre Marijon <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders X 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.geekygoblin.nedetlesmaki.game.systems;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.Iterator;
import com.artemis.Entity;
import com.artemis.ComponentMapper;
import com.artemis.annotations.Mapper;
import com.artemis.systems.VoidEntitySystem;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Pushable;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Pusher;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Position;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Movable;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.BlockOnPlate;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.StopOnPlate;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Square;
import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Plate;
import org.geekygoblin.nedetlesmaki.game.manager.EntityIndexManager;
import org.geekygoblin.nedetlesmaki.game.utils.PosOperation;
import org.geekygoblin.nedetlesmaki.game.utils.Mouvement;
import org.geekygoblin.nedetlesmaki.game.constants.AnimationType;
import org.geekygoblin.nedetlesmaki.game.Game;
/**
*
* @author natir
*/
@Singleton
public class GameSystem extends VoidEntitySystem {
private EntityIndexManager index;
@Mapper
ComponentMapper<Pushable> pushableMapper;
@Mapper
ComponentMapper<Pusher> pusherMapper;
@Mapper
ComponentMapper<Position> positionMapper;
@Mapper
ComponentMapper<Movable> movableMapper;
@Mapper
ComponentMapper<Plate> plateMapper;
@Mapper
ComponentMapper<BlockOnPlate> blockOnPlateMapper;
@Mapper
ComponentMapper<StopOnPlate> stopOnPlateMapper;
@Inject
public GameSystem(EntityIndexManager index) {
this.index = index;
}
@Override
protected void processSystem() {
}
public ArrayList<Mouvement> moveEntity(Entity e, Position dirP) {
/*Check if move possible*/
Position oldP = this.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList<Mouvement>();
for (int i = 0; i != this.getMovable(e); i++) {
Position newP = PosOperation.sum(oldP, dirP);
if (this.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
}
} else {
if (this.isPusherEntity(e)) {
- Entity nextE = index.getEntity(newP.getX(), newP.getY()).get(0);
- if (this.isPushableEntity(nextE)) {
- mouv.addAll(this.moveEntity(nextE, dirP));
- mouv.add(runValideMove(oldP, newP, e));
+ ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class);
+ if(!aNextE.isEmpty()) {
+ Entity nextE = aNextE.get(0);
+ if (this.isPushableEntity(nextE)) {
+ mouv.addAll(this.moveEntity(nextE, dirP));
+ mouv.add(runValideMove(oldP, newP, e));
+ }
}
}
return mouv;
}
}
return mouv;
}
private Mouvement runValideMove(Position oldP, Position newP, Entity e) {
if (index.moveEntity(oldP.getX(), oldP.getY(), newP.getX(), newP.getY())) {
Position diff = PosOperation.deduction(newP, oldP);
Mouvement m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.no);
if (e == ((Game) this.world).getNed()) {
if (diff.getX() > 0) {
m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.ned_right);
} else if (diff.getX() < 0) {
m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.ned_left);
} else if (diff.getY() > 0) {
m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.ned_down);
} else if (diff.getY() < 0) {
m = new Mouvement(e).addPosition(diff).addAnimation(AnimationType.ned_up);
}
}
e.getComponent(Position.class).setX(newP.getX());
e.getComponent(Position.class).setY(newP.getY());
return m;
}
return null;
}
private boolean testStopOnPlate(Entity eMove, Square obj) {
if (obj == null) {
return false;
}
ArrayList<Entity> array = obj.getWith(Plate.class);
if (array.size() == 0) {
return false;
}
Entity plate = obj.getWith(Plate.class).get(0);
Plate p = plateMapper.getSafe(plate);
StopOnPlate b = stopOnPlateMapper.getSafe(eMove);
if (b == null) {
return false;
}
if (p.isPlate()) {
if (b.stop()) {
return true;
}
}
return false;
}
private boolean testBlockedPlate(Entity eMove, Square obj) {
if (obj == null) {
return false;
}
ArrayList<Entity> array = obj.getWith(Plate.class);
if (array.size() == 0) {
return false;
}
Entity plate = obj.getWith(Plate.class).get(0);
Plate p = plate.getComponent(Plate.class);
BlockOnPlate b = blockOnPlateMapper.getSafe(eMove);
if (b == null) {
return false;
}
if (p.isPlate()) {
if (b.block()) {
return true;
}
}
return false;
}
public boolean positionIsVoid(Position p) {
Square s = index.getSquare(p.getX(), p.getY());
if (s != null) {
ArrayList<Entity> plate = s.getWith(Plate.class);
ArrayList<Entity> all = s.getAll();
if (all.size() == plate.size()) {
return true;
} else {
return false;
}
}
return true;
}
public boolean isPushableEntity(Entity e) {
Pushable p = this.pushableMapper.getSafe(e);
if (p != null) {
if (p.isPushable()) {
return true;
}
}
return false;
}
public boolean isPusherEntity(Entity e) {
Pusher p = this.pusherMapper.getSafe(e);
if (p != null) {
if (p.isPusher()) {
return true;
}
}
return false;
}
public Position getPosition(Entity e) {
Position p = this.positionMapper.getSafe(e);
if (p != null) {
return p;
}
return new Position(-1, -1);
}
public int getMovable(Entity e) {
Movable m = this.movableMapper.getSafe(e);
if (m != null) {
return m.getNbCase();
}
return 0;
}
public void printIndex() {
for (int i = 0; i != 15; i++) {
for (int j = 0; j != 15; j++) {
Square s = index.getSquare(i, j);
if (s != null) {
ArrayList<Entity> array = s.getAll();
for (Entity e : array) {
System.out.printf("[%d, %d] : ", i, j);
System.out.print(e);
System.out.print("\n");
}
}
}
}
}
}
| true | true | public ArrayList<Mouvement> moveEntity(Entity e, Position dirP) {
/*Check if move possible*/
Position oldP = this.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList<Mouvement>();
for (int i = 0; i != this.getMovable(e); i++) {
Position newP = PosOperation.sum(oldP, dirP);
if (this.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
}
} else {
if (this.isPusherEntity(e)) {
Entity nextE = index.getEntity(newP.getX(), newP.getY()).get(0);
if (this.isPushableEntity(nextE)) {
mouv.addAll(this.moveEntity(nextE, dirP));
mouv.add(runValideMove(oldP, newP, e));
}
}
return mouv;
}
}
return mouv;
}
| public ArrayList<Mouvement> moveEntity(Entity e, Position dirP) {
/*Check if move possible*/
Position oldP = this.getPosition(e);
ArrayList<Mouvement> mouv = new ArrayList<Mouvement>();
for (int i = 0; i != this.getMovable(e); i++) {
Position newP = PosOperation.sum(oldP, dirP);
if (this.positionIsVoid(newP)) {
Square s = index.getSquare(newP.getX(), newP.getY());
if (this.testStopOnPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
return mouv;
}
if (!this.testBlockedPlate(e, s)) {
mouv.add(runValideMove(oldP, newP, e));
}
} else {
if (this.isPusherEntity(e)) {
ArrayList<Entity> aNextE = index.getSquare(newP.getX(), newP.getY()).getWith(Pushable.class);
if(!aNextE.isEmpty()) {
Entity nextE = aNextE.get(0);
if (this.isPushableEntity(nextE)) {
mouv.addAll(this.moveEntity(nextE, dirP));
mouv.add(runValideMove(oldP, newP, e));
}
}
}
return mouv;
}
}
return mouv;
}
|
diff --git a/src/net/sf/freecol/server/model/ServerPlayer.java b/src/net/sf/freecol/server/model/ServerPlayer.java
index dfcdb4ad3..d9f5fb223 100644
--- a/src/net/sf/freecol/server/model/ServerPlayer.java
+++ b/src/net/sf/freecol/server/model/ServerPlayer.java
@@ -1,3073 +1,3074 @@
/**
* Copyright (C) 2002-2011 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.server.model;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.AbstractGoods;
import net.sf.freecol.common.model.AbstractUnit;
import net.sf.freecol.common.model.Building;
import net.sf.freecol.common.model.BuildingType;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.CombatModel;
import net.sf.freecol.common.model.CombatModel.CombatResult;
import net.sf.freecol.common.model.EquipmentType;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.Europe.MigrationType;
import net.sf.freecol.common.model.Event;
import net.sf.freecol.common.model.FeatureContainer;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.FoundingFather.FoundingFatherType;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsContainer;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.HistoryEvent;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Market;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Modifier;
import net.sf.freecol.common.model.Monarch;
import net.sf.freecol.common.model.Monarch.MonarchAction;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.RandomRange;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.SettlementType;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tension;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.UnitTypeChange.ChangeType;
import net.sf.freecol.common.networking.Connection;
import net.sf.freecol.common.option.BooleanOption;
import net.sf.freecol.common.util.RandomChoice;
import net.sf.freecol.common.util.Utils;
import net.sf.freecol.server.control.ChangeSet;
import net.sf.freecol.server.control.ChangeSet.ChangePriority;
import net.sf.freecol.server.control.ChangeSet.See;
import net.sf.freecol.server.model.ServerColony;
import net.sf.freecol.server.model.ServerEurope;
import net.sf.freecol.server.model.ServerIndianSettlement;
import net.sf.freecol.server.model.ServerModelObject;
import net.sf.freecol.server.model.ServerUnit;
import net.sf.freecol.server.model.TransactionSession;
/**
* A <code>Player</code> with additional (server specific) information.
*
* That is: pointers to this player's
* {@link Connection} and {@link Socket}
*/
public class ServerPlayer extends Player implements ServerModelObject {
private static final Logger logger = Logger.getLogger(ServerPlayer.class.getName());
// TODO: move to options or spec?
public static final int ALARM_RADIUS = 2;
public static final int ALARM_TILE_IN_USE = 2;
public static final int ALARM_MISSIONARY_PRESENT = -10;
// How far to search for a colony to add an Indian convert to.
public static final int MAX_CONVERT_DISTANCE = 10;
/** The network socket to the player's client. */
private Socket socket;
/** The connection for this player. */
private Connection connection;
private boolean connected = false;
/** Remaining emigrants to select due to a fountain of youth */
private int remainingEmigrants = 0;
/**
* Trivial constructor required for all ServerModelObjects.
*/
public ServerPlayer(Game game, String id) {
super(game, id);
}
/**
* Creates a new ServerPlayer.
*
* @param game The <code>Game</code> this object belongs to.
* @param name The player name.
* @param admin Whether the player is the game administrator or not.
* @param nation The nation of the <code>Player</code>.
* @param socket The socket to the player's client.
* @param connection The <code>Connection</code> for the socket.
*/
public ServerPlayer(Game game, String name, boolean admin, Nation nation,
Socket socket, Connection connection) {
super(game);
this.name = name;
this.admin = admin;
featureContainer = new FeatureContainer(game.getSpecification());
europe = null;
if (nation != null && nation.getType() != null) {
this.nationType = nation.getType();
this.nationID = nation.getId();
try {
featureContainer.add(nationType.getFeatureContainer());
} catch (Throwable error) {
error.printStackTrace();
}
if (nationType.isEuropean()) {
/*
* Setting the amount of gold to
* "getGameOptions().getInteger(GameOptions.STARTING_MONEY)"
*
* just before starting the game. See
* "net.sf.freecol.server.control.PreGameController".
*/
this.playerType = (nationType.isREF()) ? PlayerType.ROYAL
: PlayerType.COLONIAL;
europe = new ServerEurope(game, this);
if (this.playerType == PlayerType.COLONIAL) {
monarch = new Monarch(game, this, nation.getRulerNameKey());
}
gold = 0;
} else { // indians
this.playerType = PlayerType.NATIVE;
gold = Player.GOLD_NOT_ACCOUNTED;
}
} else {
// virtual "enemy privateer" player
// or undead ?
this.nationID = Nation.UNKNOWN_NATION_ID;
this.playerType = PlayerType.COLONIAL;
gold = 0;
}
market = new Market(getGame(), this);
immigration = 0;
liberty = 0;
currentFather = null;
//call of super() will lead to this object being registered with AIMain
//before playerType has been set. AIMain will fall back to use of
//standard AIPlayer in this case. Set object again to fix this.
//Possible TODO: Is there a better way to do this?
final String curId = getId();
game.removeFreeColGameObject(curId);
game.setFreeColGameObject(curId, this);
this.socket = socket;
this.connection = connection;
connected = connection != null;
resetExploredTiles(getGame().getMap());
invalidateCanSeeTiles();
}
/**
* Checks if this player is currently connected to the server.
* @return <i>true</i> if this player is currently connected to the server
* and <code>false</code> otherwise.
*/
public boolean isConnected() {
return connected;
}
/**
* Sets the "connected"-status of this player.
*
* @param connected Should be <i>true</i> if this player is currently
* connected to the server and <code>false</code> otherwise.
* @see #isConnected
*/
public void setConnected(boolean connected) {
this.connected = connected;
}
/**
* Gets the socket of this player.
* @return The <code>Socket</code>.
*/
public Socket getSocket() {
return socket;
}
/**
* Gets the connection of this player.
*
* @return The <code>Connection</code>.
*/
public Connection getConnection() {
return connection;
}
/**
* Sets the connection of this player.
*
* @param connection The <code>Connection</code>.
*/
public void setConnection(Connection connection) {
this.connection = connection;
connected = (connection != null);
}
/**
* Performs initial randomizations for this player.
*
* @param random A pseudo-random number source.
*/
public void startGame(Random random) {
Specification spec = getGame().getSpecification();
if (isEuropean() && !isREF()) {
modifyGold(spec.getIntegerOption(GameOptions.STARTING_MONEY)
.getValue());
((ServerEurope) getEurope()).initializeMigration(random);
getMarket().randomizeInitialPrice(random);
}
}
/**
* Checks if this player has died.
*
* @return True if this player should die.
*/
public boolean checkForDeath() {
/*
* Die if: (isNative && (no colonies or units))
* || ((rebel or independent) && !(has coastal colony))
* || (isREF && !(rebel nation left) && (all units in Europe))
* || ((no units in New World)
* && ((year > 1600) || (cannot get a unit from Europe)))
*/
switch (getPlayerType()) {
case NATIVE: // All natives units are viable
return getUnits().isEmpty();
case COLONIAL: // Handle the hard case below
if (isUnknownEnemy()) return false;
break;
case REBEL: case INDEPENDENT:
// Post-declaration European player needs a coastal colony
// and can not hope for resupply from Europe.
for (Colony colony : getColonies()) {
if (colony.isConnected()) return false;
}
return true;
case ROYAL: // Still alive if there are rebels to quell
for (Player enemy : getGame().getPlayers()) {
if (enemy.getREFPlayer() == (Player) this
&& enemy.getPlayerType() == PlayerType.REBEL) {
return false;
}
}
// Still alive if there are units not in Europe
for (Unit u : getUnits()) {
if (!u.isInEurope()) return false;
}
// Otherwise, the REF has been defeated and gone home.
return true;
case UNDEAD:
return getUnits().isEmpty();
default:
throw new IllegalStateException("Bogus player type");
}
// Quick check for a colony
if (!getColonies().isEmpty()) {
return false;
}
// Verify player units
boolean hasCarrier = false;
List<Unit> unitList = getUnits();
for(Unit unit : unitList){
boolean isValidUnit = false;
if(unit.isCarrier()){
hasCarrier = true;
continue;
}
// Can found new colony
if(unit.isColonist()){
isValidUnit = true;
}
// Can capture units
if(unit.isOffensiveUnit()){
isValidUnit = true;
}
if(!isValidUnit){
continue;
}
// Verify if unit is in new world
Location unitLocation = unit.getLocation();
// unit in new world
if(unitLocation instanceof Tile){
logger.info(getName() + " found colonist in new world");
return false;
}
// onboard a carrier
if(unit.isOnCarrier()){
Unit carrier = (Unit) unitLocation;
// carrier in new world
if(carrier.getLocation() instanceof Tile){
logger.info(getName() + " found colonist aboard carrier in new world");
return false;
}
}
}
/*
* At this point we know the player does not have any valid units or
* settlements on the map.
*/
// After the year 1600, no presence in New World means endgame
if (getGame().getTurn().getYear() >= 1600) {
logger.info(getName() + " no presence in new world after 1600");
return true;
}
int goldNeeded = 0;
/*
* No carrier, check if has gold to buy one
*/
if(!hasCarrier){
/*
* Find the cheapest naval unit
*/
Iterator<UnitType> navalUnits = getSpecification()
.getUnitTypesWithAbility("model.ability.navalUnit").iterator();
int lowerPrice = Integer.MAX_VALUE;
while(navalUnits.hasNext()){
UnitType unit = navalUnits.next();
int unitPrice = getEurope().getUnitPrice(unit);
// cannot be bought
if(unitPrice == UnitType.UNDEFINED){
continue;
}
if(unitPrice < lowerPrice){
lowerPrice = unitPrice;
}
}
//Sanitation
if(lowerPrice == Integer.MAX_VALUE){
logger.warning(getName() + " could not find naval unit to buy");
return true;
}
goldNeeded += lowerPrice;
// cannot buy carrier
if (!checkGold(goldNeeded)) {
logger.info(getName() + " does not have enough money to buy carrier");
return true;
}
logger.info(getName() + " has enough money to buy carrier, has="
+ getGold() + ", needs=" + lowerPrice);
}
/*
* Check if player has colonists.
* We already checked that it has (or can buy) a carrier to
* transport them to New World
*/
for (Unit eu : getEurope().getUnitList()) {
if (eu.isCarrier()) {
/*
* The carrier has colonist units on board
*/
for (Unit u : eu.getUnitList()) {
if (u.isColonist()) return false;
}
// The carrier has units or goods that can be sold.
if (eu.getGoodsCount() > 0) {
logger.info(getName() + " has goods to sell");
return false;
}
continue;
}
if (eu.isColonist()) {
logger.info(getName() + " has colonist unit waiting in port");
return false;
}
}
// No colonists, check if has gold to train or recruit one.
int goldToRecruit = getEurope().getRecruitPrice();
/*
* Find the cheapest colonist, either by recruiting or training
*/
Iterator<UnitType> trainedUnits = getSpecification().getUnitTypesTrainedInEurope().iterator();
int goldToTrain = Integer.MAX_VALUE;
while(trainedUnits.hasNext()){
UnitType unit = trainedUnits.next();
if(!unit.hasAbility("model.ability.foundColony")){
continue;
}
int unitPrice = getEurope().getUnitPrice(unit);
// cannot be bought
if(unitPrice == UnitType.UNDEFINED){
continue;
}
if(unitPrice < goldToTrain){
goldToTrain = unitPrice;
}
}
goldNeeded += Math.min(goldToTrain, goldToRecruit);
if (checkGold(goldNeeded)) return false;
// Does not have enough money for recruiting or training
logger.info(getName() + " does not have enough money for recruiting or training");
return true;
}
/**
* Marks a player dead and remove any leftovers.
*
* @param cs A <code>ChangeSet</code> to update.
*/
public ChangeSet csKill(ChangeSet cs) {
// Mark the player as dead.
setDead(true);
cs.addDead(this);
// Notify everyone.
cs.addMessage(See.all().except(this),
new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY,
((isEuropean())
? "model.diplomacy.dead.european"
: "model.diplomacy.dead.native"),
this)
.addStringTemplate("%nation%", getNationName()));
// Clean up missions and remove tension/alarm.
if (isEuropean()) {
for (Player other : getGame().getPlayers()) {
for (IndianSettlement s : other.getIndianSettlements()) {
Unit unit = s.getMissionary();
if (unit != null
&& ((ServerPlayer) unit.getOwner()) == this) {
s.changeMissionary(null);
cs.addDispose(this, s.getTile(), unit);
cs.add(See.perhaps(), s.getTile());
}
s.removeAlarm(this);
}
other.removeTension(this);
}
}
// Remove settlements. Update formerly owned tiles.
List<Settlement> settlements = getSettlements();
while (!settlements.isEmpty()) {
Settlement settlement = settlements.remove(0);
cs.addDispose(this, settlement.getTile(), settlement);
}
// Clean up remaining tile ownerships
for (Tile tile : getGame().getMap().getAllTiles()) {
if (tile.getOwner() == this) tile.changeOwnership(null, null);
}
// Remove units
List<Unit> units = getUnits();
while (!units.isEmpty()) {
Unit unit = units.remove(0);
if (unit.getLocation() instanceof Tile) {
cs.add(See.perhaps(), unit.getTile());
}
cs.addDispose(this, unit.getLocation(), unit);
}
return cs;
}
public int getRemainingEmigrants() {
return remainingEmigrants;
}
public void setRemainingEmigrants(int emigrants) {
remainingEmigrants = emigrants;
}
/**
* Checks whether the current founding father has been recruited.
*
* @return The new founding father, or null if none available or ready.
*/
public FoundingFather checkFoundingFather() {
FoundingFather father = null;
if (currentFather != null) {
int extraLiberty = getRemainingFoundingFatherCost();
if (extraLiberty <= 0) {
boolean overflow = getSpecification()
.getBoolean(GameOptions.SAVE_PRODUCTION_OVERFLOW);
setLiberty((overflow) ? -extraLiberty : 0);
father = currentFather;
currentFather = null;
}
}
return father;
}
/**
* Checks whether to start recruiting a founding father.
*
* @return True if a new father should be chosen.
*/
public boolean canRecruitFoundingFather() {
return getPlayerType() == PlayerType.COLONIAL
&& canHaveFoundingFathers()
&& currentFather == null
&& !getSettlements().isEmpty();
}
/**
* Build a list of random FoundingFathers, one per type.
* Do not include any the player has or are not available.
*
* @param random A pseudo-random number source.
* @return A list of FoundingFathers.
*/
public List<FoundingFather> getRandomFoundingFathers(Random random) {
// Build weighted random choice for each father type
Specification spec = getGame().getSpecification();
int age = getGame().getTurn().getAge();
EnumMap<FoundingFatherType, List<RandomChoice<FoundingFather>>> choices
= new EnumMap<FoundingFatherType,
List<RandomChoice<FoundingFather>>>(FoundingFatherType.class);
for (FoundingFather father : spec.getFoundingFathers()) {
if (!hasFather(father) && father.isAvailableTo(this)) {
FoundingFatherType type = father.getType();
List<RandomChoice<FoundingFather>> rc = choices.get(type);
if (rc == null) {
rc = new ArrayList<RandomChoice<FoundingFather>>();
}
int weight = father.getWeight(age);
rc.add(new RandomChoice<FoundingFather>(father, weight));
choices.put(father.getType(), rc);
}
}
// Select one from each father type
List<FoundingFather> randomFathers = new ArrayList<FoundingFather>();
String logMessage = "Random fathers";
for (FoundingFatherType type : FoundingFatherType.values()) {
List<RandomChoice<FoundingFather>> rc = choices.get(type);
if (rc != null) {
FoundingFather f = RandomChoice.getWeightedRandom(logger,
"Choose founding father", random, rc);
randomFathers.add(f);
logMessage += ":" + f.getNameKey();
}
}
logger.info(logMessage);
return randomFathers;
}
/**
* Generate a weighted list of unit types recruitable by this player.
*
* @return A weighted list of recruitable unit types.
*/
public List<RandomChoice<UnitType>> generateRecruitablesList() {
ArrayList<RandomChoice<UnitType>> recruitables
= new ArrayList<RandomChoice<UnitType>>();
FeatureContainer fc = getFeatureContainer();
for (UnitType unitType : getSpecification().getUnitTypeList()) {
if (unitType.isRecruitable()
&& fc.hasAbility("model.ability.canRecruitUnit", unitType)) {
recruitables.add(new RandomChoice<UnitType>(unitType,
unitType.getRecruitProbability()));
}
}
return recruitables;
}
/**
* Add a HistoryEvent to this player.
*
* @param event The <code>HistoryEvent</code> to add.
*/
public void addHistory(HistoryEvent event) {
history.add(event);
}
/**
* Resets this player's explored tiles. This is done by setting
* all the tiles within a {@link Unit}s line of sight visible.
* The other tiles are made unvisible.
*
* @param map The <code>Map</code> to reset the explored tiles on.
* @see #hasExplored
*/
public void resetExploredTiles(Map map) {
if (map != null) {
for (Unit unit : getUnits()) {
Tile tile = unit.getTile();
setExplored(tile);
int radius = (unit.getColony() != null)
? unit.getColony().getLineOfSight()
: unit.getLineOfSight();
for (Tile t : tile.getSurroundingTiles(radius)) {
setExplored(t);
}
}
}
}
/**
* Checks if this <code>Player</code> has explored the given
* <code>Tile</code>.
*
* @param tile The <code>Tile</code>.
* @return <i>true</i> if the <code>Tile</code> has been explored and
* <i>false</i> otherwise.
*/
public boolean hasExplored(Tile tile) {
return tile.isExploredBy(this);
}
/**
* Sets the given tile to be explored by this player and updates
* the player's information about the tile.
*/
public void setExplored(Tile tile) {
tile.setExploredBy(this, true);
}
/**
* Sets the tiles within the given <code>Unit</code>'s line of
* sight to be explored by this player.
*
* @param unit The <code>Unit</code>.
* @see #setExplored(Tile)
* @see #hasExplored
*/
public void setExplored(Unit unit) {
if (getGame() == null || getGame().getMap() == null || unit == null
|| unit.getLocation() == null || unit.getTile() == null) {
return;
}
Tile tile = unit.getTile();
setExplored(tile);
for (Tile t : tile.getSurroundingTiles(unit.getLineOfSight())) {
setExplored(t);
}
invalidateCanSeeTiles();
}
/**
* Create units from a list of abstract units. Only used by
* Europeans at present, so the units are created in Europe.
*
* @param abstractUnits The list of <code>AbstractUnit</code>s to create.
* @return A list of units created.
*/
public List<Unit> createUnits(List<AbstractUnit> abstractUnits) {
Game game = getGame();
Specification spec = game.getSpecification();
List<Unit> units = new ArrayList<Unit>();
Europe europe = getEurope();
if (europe == null) return units;
for (AbstractUnit au : abstractUnits) {
for (int i = 0; i < au.getNumber(); i++) {
units.add(new ServerUnit(game, europe, this,
au.getUnitType(spec),
UnitState.ACTIVE,
au.getEquipment(spec)));
}
}
return units;
}
/**
* Makes the entire map visible.
* Debug mode helper.
*/
public void revealMap() {
for (Tile tile: getGame().getMap().getAllTiles()) {
setExplored(tile);
}
getSpecification().getBooleanOption(GameOptions.FOG_OF_WAR)
.setValue(false);
invalidateCanSeeTiles();
}
/**
* Propagate an European market change to the other European markets.
*
* @param type The type of goods that was traded.
* @param amount The amount of goods that was traded.
* @param random A <code>Random</code> number source.
*/
private void propagateToEuropeanMarkets(GoodsType type, int amount,
Random random) {
if (!type.isStorable()) return;
// Propagate 5-30% of the original change.
final int lowerBound = 5; // TODO: make into game option?
final int upperBound = 30;// TODO: make into game option?
amount *= Utils.randomInt(logger, "Propagate goods", random,
upperBound - lowerBound + 1) + lowerBound;
amount /= 100;
if (amount == 0) return;
// Do not need to update the clients here, these changes happen
// while it is not their turn.
for (Player other : getGame().getEuropeanPlayers()) {
Market market;
if ((ServerPlayer) other != this
&& (market = other.getMarket()) != null) {
market.addGoodsToMarket(type, amount);
}
}
}
/**
* Flush any market price changes for a specified goods type.
*
* @param type The <code>GoodsType</code> to check.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csFlushMarket(GoodsType type, ChangeSet cs) {
Market market = getMarket();
if (market.hasPriceChanged(type)) {
// This type of goods has changed price, so we will update
// the market and send a message as well.
cs.addMessage(See.only(this),
market.makePriceChangeMessage(type));
market.flushPriceChange(type);
cs.add(See.only(this), market.getMarketData(type));
}
}
/**
* Buy goods in Europe.
*
* @param container The <code>GoodsContainer</code> to carry the goods.
* @param type The <code>GoodsType</code> to buy.
* @param amount The amount of goods to buy.
* @param random A <code>Random</code> number source.
* @throws IllegalStateException If the <code>player</code> cannot afford
* to buy the goods.
*/
public void buy(GoodsContainer container, GoodsType type, int amount,
Random random)
throws IllegalStateException {
logger.finest(getName() + " buys " + amount + " " + type);
Market market = getMarket();
int price = market.getBidPrice(type, amount);
if (!checkGold(price)) {
throw new IllegalStateException("Player " + getName()
+ " tried to buy " + Integer.toString(amount)
+ " " + type.toString()
+ " for " + Integer.toString(price)
+ " but has " + Integer.toString(getGold()) + " gold.");
}
modifyGold(-price);
market.modifySales(type, -amount);
market.modifyIncomeBeforeTaxes(type, -price);
market.modifyIncomeAfterTaxes(type, -price);
int marketAmount = -(int) getFeatureContainer()
.applyModifier(amount, "model.modifier.tradeBonus",
type, getGame().getTurn());
market.addGoodsToMarket(type, marketAmount);
propagateToEuropeanMarkets(type, marketAmount, random);
container.addGoods(type, amount);
}
/**
* Sell goods in Europe.
*
* @param container An optional <code>GoodsContainer</code>
* carrying the goods.
* @param type The <code>GoodsType</code> to sell.
* @param amount The amount of goods to sell.
* @param random A <code>Random</code> number source.
*/
public void sell(GoodsContainer container, GoodsType type, int amount,
Random random) {
logger.finest(getName() + " sells " + amount + " " + type);
Market market = getMarket();
int tax = getTax();
int incomeBeforeTaxes = market.getSalePrice(type, amount);
int incomeAfterTaxes = ((100 - tax) * incomeBeforeTaxes) / 100;
modifyGold(incomeAfterTaxes);
market.modifySales(type, amount);
market.modifyIncomeBeforeTaxes(type, incomeBeforeTaxes);
market.modifyIncomeAfterTaxes(type, incomeAfterTaxes);
int marketAmount = (int) getFeatureContainer()
.applyModifier(amount, "model.modifier.tradeBonus",
type, getGame().getTurn());
market.addGoodsToMarket(type, marketAmount);
propagateToEuropeanMarkets(type, marketAmount, random);
if (container != null) container.addGoods(type, -amount);
}
/**
* Change stance and collect changes that need updating.
*
* @param stance The new <code>Stance</code>.
* @param otherPlayer The <code>Player</code> wrt which the stance changes.
* @param symmetric If true, change the otherPlayer stance as well.
* @param cs A <code>ChangeSet</code> containing the changes.
* @return True if there was a change in stance at all.
*/
public boolean csChangeStance(Stance stance, Player otherPlayer,
boolean symmetric, ChangeSet cs) {
boolean change = false;
Stance old = getStance(otherPlayer);
if (old != stance) {
try {
int modifier = old.getTensionModifier(stance);
setStance(otherPlayer, stance);
if (modifier != 0) {
cs.add(See.only(null).perhaps((ServerPlayer) otherPlayer),
modifyTension(otherPlayer, modifier));
}
cs.addStance(See.perhaps(), this, stance, otherPlayer);
change = true;
logger.finest("Stance change " + getName()
+ " " + old.toString()
+ " -> " + stance.toString()
+ " wrt " + otherPlayer.getName());
} catch (IllegalStateException e) { // Catch illegal transitions
logger.log(Level.WARNING, "Illegal stance transition", e);
}
}
if (symmetric && (old = otherPlayer.getStance(this)) != stance) {
try {
int modifier = old.getTensionModifier(stance);
otherPlayer.setStance(this, stance);
if (modifier != 0) {
cs.add(See.only(null).perhaps(this),
otherPlayer.modifyTension(this, modifier));
}
cs.addStance(See.perhaps(), otherPlayer, stance, this);
change = true;
logger.finest("Stance change " + otherPlayer.getName()
+ " " + old.toString()
+ " -> " + stance.toString()
+ " wrt " + getName());
} catch (IllegalStateException e) { // Catch illegal transitions
logger.log(Level.WARNING, "Illegal stance transition", e);
}
}
return change;
}
/**
* New turn for this player.
*
* @param random A <code>Random</code> number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csNewTurn(Random random, ChangeSet cs) {
logger.finest("ServerPlayer.csNewTurn, for " + toString());
// Settlements
List<Settlement> settlements
= new ArrayList<Settlement>(getSettlements());
int newSoL = 0;
for (Settlement settlement : settlements) {
((ServerModelObject) settlement).csNewTurn(random, cs);
newSoL += settlement.getSoL();
}
int numberOfColonies = settlements.size();
if (numberOfColonies > 0) {
newSoL = newSoL / numberOfColonies;
if (oldSoL / 10 != newSoL / 10) {
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY,
(newSoL > oldSoL)
? "model.player.SoLIncrease"
: "model.player.SoLDecrease", this)
.addAmount("%oldSoL%", oldSoL)
.addAmount("%newSoL%", newSoL));
}
oldSoL = newSoL; // Remember SoL for check changes at next turn.
}
// Europe.
if (europe != null) {
((ServerModelObject) europe).csNewTurn(random, cs);
}
// Units.
for (Unit unit : new ArrayList<Unit>(getUnits())) {
try {
((ServerModelObject) unit).csNewTurn(random, cs);
} catch (ClassCastException e) {
logger.log(Level.SEVERE, "Not a ServerUnit: " + unit.getId(), e);
}
}
if (isEuropean()) { // Update liberty and immigration
if (checkEmigrate()
&& !hasAbility("model.ability.selectRecruit")) {
// Auto-emigrate if selection not allowed.
csEmigrate(0, MigrationType.NORMAL, random, cs);
} else {
cs.addPartial(See.only(this), this, "immigration");
}
cs.addPartial(See.only(this), this, "liberty");
}
}
/**
* Starts a new turn for a player.
* Carefully do any random number generation outside of any
* threads that start so as to keep random number generation
* deterministic.
*
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csStartTurn(Random random, ChangeSet cs) {
Game game = getGame();
if (isEuropean()) {
csBombardEnemyShips(random, cs);
csYearlyGoodsRemoval(random, cs);
FoundingFather father = checkFoundingFather();
if (father != null) {
csAddFoundingFather(father, random, cs);
}
} else if (isIndian()) {
// We do not have to worry about Player level stance
// changes driving Stance, as that is delegated to the AI.
//
// However we want to notify of individual settlements
// that change tension level, but there are complex
// interactions between settlement and player tensions.
// The simple way to do it is just to save all old tension
// levels and check if they have changed after applying
// all the changes.
List<IndianSettlement> allSettlements = getIndianSettlements();
java.util.Map<IndianSettlement,
java.util.Map<Player, Tension.Level>> oldLevels
= new HashMap<IndianSettlement,
java.util.Map<Player, Tension.Level>>();
for (IndianSettlement settlement : allSettlements) {
java.util.Map<Player, Tension.Level> oldLevel
= new HashMap<Player, Tension.Level>();
oldLevels.put(settlement, oldLevel);
for (Player enemy : game.getEuropeanPlayers()) {
Tension alarm = settlement.getAlarm(enemy);
if (alarm != null) oldLevel.put(enemy, alarm.getLevel());
}
}
// Do the settlement alarms first.
for (IndianSettlement settlement : allSettlements) {
java.util.Map<Player, Integer> extra
= new HashMap<Player, Integer>();
for (Player enemy : game.getEuropeanPlayers()) {
extra.put(enemy, new Integer(0));
}
// Look at the uses of tiles surrounding the settlement.
int alarmRadius = settlement.getRadius() + ALARM_RADIUS;
int alarm = 0;
for (Tile tile: settlement.getTile()
.getSurroundingTiles(alarmRadius)) {
Colony colony = tile.getColony();
if (tile.getFirstUnit() != null) { // Military units
Player enemy = tile.getFirstUnit().getOwner();
if (enemy.isEuropean()) {
alarm = extra.get(enemy);
for (Unit unit : tile.getUnitList()) {
if (unit.isOffensiveUnit() && !unit.isNaval()) {
alarm += unit.getType().getOffence();
}
}
extra.put(enemy, alarm);
}
} else if (colony != null) { // Colonies
Player enemy = colony.getOwner();
extra.put(enemy, extra.get(enemy).intValue()
+ ALARM_TILE_IN_USE
+ colony.getUnitCount());
} else if (tile.getOwningSettlement() != null) { // Control
Player enemy = tile.getOwningSettlement().getOwner();
if (enemy != null && enemy.isEuropean()) {
extra.put(enemy, extra.get(enemy).intValue()
+ ALARM_TILE_IN_USE);
}
}
}
// Missionary helps reducing alarm a bit
if (settlement.getMissionary() != null) {
Unit mission = settlement.getMissionary();
int missionAlarm = ALARM_MISSIONARY_PRESENT;
if (mission.hasAbility("model.ability.expertMissionary")) {
missionAlarm *= 2;
}
Player enemy = mission.getOwner();
extra.put(enemy,
extra.get(enemy).intValue() + missionAlarm);
}
// Apply modifiers, and commit the total change.
for (Entry<Player, Integer> entry : extra.entrySet()) {
Player player = entry.getKey();
int change = entry.getValue().intValue();
if (change != 0) {
change = (int) player.getFeatureContainer()
.applyModifier(change,
"model.modifier.nativeAlarmModifier",
null, game.getTurn());
settlement.modifyAlarm(player, change);
}
}
}
// Calm down a bit at the whole-tribe level.
for (Player enemy : game.getEuropeanPlayers()) {
if (getTension(enemy).getValue() > 0) {
int change = -getTension(enemy).getValue()/100 - 4;
modifyTension(enemy, change);
}
}
// Now collect the settlements that changed.
for (IndianSettlement settlement : allSettlements) {
java.util.Map<Player, Tension.Level> oldLevel
= oldLevels.get(settlement);
for (Entry<Player, Tension.Level> entry : oldLevel.entrySet()) {
Player enemy = entry.getKey();
Tension.Level newLevel
= settlement.getAlarm(enemy).getLevel();
if (entry.getValue() != newLevel) {
cs.add(See.only(null).perhaps((ServerPlayer) enemy),
settlement);
}
}
}
// Check for braves converted by missionaries
List<UnitType> converts = game.getSpecification()
.getUnitTypesWithAbility("model.ability.convert");
StringTemplate nation = getNationName();
for (IndianSettlement settlement : allSettlements) {
if (settlement.checkForNewMissionaryConvert()) {
Unit missionary = settlement.getMissionary();
ServerPlayer other = (ServerPlayer) missionary.getOwner();
Settlement colony = settlement.getTile()
.getNearestSettlement(other, MAX_CONVERT_DISTANCE);
if (colony != null && converts.size() > 0) {
Unit brave = settlement.getFirstUnit();
brave.setOwner(other);
brave.setType(Utils.getRandomMember(logger,
"Choose brave", converts, random));
brave.setLocation(colony.getTile());
cs.add(See.perhaps(), colony.getTile(), settlement);
cs.addMessage(See.only(other),
new ModelMessage(ModelMessage.MessageType.UNIT_ADDED,
"model.colony.newConvert", brave)
.addStringTemplate("%nation%", nation)
.addName("%colony%", colony.getName()));
}
}
}
}
}
/**
* All player colonies bombard all available targets.
*
* @param random A random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csBombardEnemyShips(Random random, ChangeSet cs) {
for (Colony colony : getColonies()) {
if (colony.canBombardEnemyShip()) {
for (Tile tile : colony.getTile().getSurroundingTiles(1)) {
if (!tile.isLand() && tile.getFirstUnit() != null
&& tile.getFirstUnit().getOwner() != this) {
for (Unit unit : new ArrayList<Unit>(tile.getUnitList())) {
if (atWarWith(unit.getOwner())
|| unit.hasAbility("model.ability.piracy")) {
csCombat(colony, unit, null, random, cs);
}
}
}
}
}
}
}
/**
* Remove a standard yearly amount of storable goods, and
* a random extra amount of a random type.
*
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csYearlyGoodsRemoval(Random random, ChangeSet cs) {
List<GoodsType> goodsTypes = getGame().getSpecification()
.getGoodsTypeList();
Market market = getMarket();
// Pick a random type of storable goods to remove an extra amount of.
GoodsType removeType;
for (;;) {
removeType = Utils.getRandomMember(logger, "Choose goods type",
goodsTypes, random);
if (removeType.isStorable()) break;
}
// Remove standard amount, and the extra amount.
for (GoodsType type : goodsTypes) {
if (type.isStorable() && market.hasBeenTraded(type)) {
int amount = getGame().getTurn().getNumber() / 10;
if (type == removeType && amount > 0) {
amount += Utils.randomInt(logger, "Remove from market",
random, 2 * amount + 1);
}
if (amount > 0) {
market.addGoodsToMarket(type, -amount);
logger.finest(getName() + " removal of " + amount
+ " " + type
+ ", total: " + market.getAmountInMarket(type));
}
}
csFlushMarket(type, cs);
}
}
/**
* Adds a founding father to a players continental congress.
*
* @param father The <code>FoundingFather</code> to add.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csAddFoundingFather(FoundingFather father, Random random,
ChangeSet cs) {
Game game = getGame();
Specification spec = game.getSpecification();
Europe europe = getEurope();
boolean europeDirty = false;
// TODO: We do not want to have to update the whole player
// just to get the FF into the client. Use this hack until
// the client gets proper containers.
cs.addFather(this, father);
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY,
"model.player.foundingFatherJoinedCongress",
this)
.add("%foundingFather%", father.getNameKey())
.add("%description%", father.getDescriptionKey()));
cs.addHistory(this,
new HistoryEvent(getGame().getTurn(),
HistoryEvent.EventType.FOUNDING_FATHER)
.add("%father%", father.getNameKey()));
List<AbstractUnit> units = father.getUnits();
if (units != null && !units.isEmpty() && europe != null) {
createUnits(father.getUnits());
europeDirty = true;
}
java.util.Map<UnitType, UnitType> upgrades = father.getUpgrades();
if (upgrades != null) {
for (Unit u : getUnits()) {
UnitType newType = upgrades.get(u.getType());
if (newType != null) {
u.setType(newType);
cs.add(See.perhaps(), u);
}
}
}
for (Ability ability : father.getFeatureContainer().getAbilities()) {
if ("model.ability.addTaxToBells".equals(ability.getId())) {
// Provoke a tax/liberty recalculation
setTax(getTax());
cs.addPartial(See.only(this), this, "tax");
}
}
for (Event event : father.getEvents()) {
String eventId = event.getId();
if (eventId.equals("model.event.resetNativeAlarm")) {
for (Player p : game.getPlayers()) {
if (!p.isEuropean() && p.hasContacted(this)) {
p.setTension(this, new Tension(Tension.TENSION_MIN));
for (IndianSettlement is : p.getIndianSettlements()) {
if (is.hasContactedSettlement(this)) {
is.setAlarm(this,
new Tension(Tension.TENSION_MIN));
cs.add(See.only(this), is);
}
}
}
}
} else if (eventId.equals("model.event.boycottsLifted")) {
Market market = getMarket();
for (GoodsType goodsType : spec.getGoodsTypeList()) {
if (market.getArrears(goodsType) > 0) {
market.setArrears(goodsType, 0);
cs.add(See.only(this), market.getMarketData(goodsType));
}
}
} else if (eventId.equals("model.event.freeBuilding")) {
BuildingType type = spec.getBuildingType(event.getValue());
for (Colony colony : getColonies()) {
if (colony.canBuild(type)) {
colony.addBuilding(new ServerBuilding(game, colony, type));
colony.getBuildQueue().remove(type);
cs.add(See.only(this), colony);
}
}
} else if (eventId.equals("model.event.seeAllColonies")) {
for (Tile t : game.getMap().getAllTiles()) {
Colony colony = t.getColony();
if (colony != null
&& (ServerPlayer) colony.getOwner() != this) {
if (!t.isExploredBy(this)) {
t.setExploredBy(this, true);
}
t.updatePlayerExploredTile(this, false);
cs.add(See.only(this), t);
for (Tile x : colony.getOwnedTiles()) {
if (!x.isExploredBy(this)) {
x.setExploredBy(this, true);
}
x.updatePlayerExploredTile(this, false);
cs.add(See.only(this), x);
}
}
}
} else if (eventId.equals("model.event.increaseSonsOfLiberty")) {
int value = Integer.parseInt(event.getValue());
GoodsType bells = spec.getLibertyGoodsTypeList().get(0);
int totalBells = 0;
for (Colony colony : getColonies()) {
float oldRatio = (float) colony.getLiberty()
/ (colony.getUnitCount() * Colony.LIBERTY_PER_REBEL);
float reqRatio = Math.min(1.0f, oldRatio + 0.01f * value);
int reqBells = (int) Math.round(Colony.LIBERTY_PER_REBEL
* colony.getUnitCount()
* (reqRatio - oldRatio));
if (reqBells > 0) { // Can go negative if already over 100%
colony.addGoods(bells, reqBells);
colony.updateSoL();
cs.add(See.only(this), colony);
totalBells += reqBells;
}
}
// Bonus bells from the FF do not count towards recruiting
// the next one!
incrementLiberty(-totalBells);
} else if (eventId.equals("model.event.newRecruits")
&& europe != null) {
List<RandomChoice<UnitType>> recruits
= generateRecruitablesList();
FeatureContainer fc = getFeatureContainer();
for (int i = 0; i < Europe.RECRUIT_COUNT; i++) {
if (!fc.hasAbility("model.ability.canRecruitUnit",
europe.getRecruitable(i))) {
UnitType newType = RandomChoice
.getWeightedRandom(logger,
"Replace recruit", random, recruits);
europe.setRecruitable(i, newType);
europeDirty = true;
}
}
} else if (eventId.equals("model.event.movementChange")) {
for (Unit u : getUnits()) {
if (u.getMovesLeft() > 0) {
u.setMovesLeft(u.getInitialMovesLeft());
cs.addPartial(See.only(this), u, "movesLeft");
}
}
}
}
if (europeDirty) cs.add(See.only(this), europe);
}
/**
* Claim land.
*
* @param tile The <code>Tile</code> to claim.
* @param settlement The <code>Settlement</code> to claim for.
* @param price The price to pay for the land, which must agree
* with the owner valuation, unless negative which denotes stealing.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csClaimLand(Tile tile, Settlement settlement, int price,
ChangeSet cs) {
Player owner = tile.getOwner();
Settlement ownerSettlement = tile.getOwningSettlement();
tile.changeOwnership(this, settlement);
// Update the tile for all, and privately any now-angrier
// owners, or the player gold if a price was paid.
cs.add(See.perhaps(), tile);
if (price > 0) {
modifyGold(-price);
owner.modifyGold(price);
cs.addPartial(See.only(this), this, "gold");
} else if (price < 0 && owner.isIndian()) {
IndianSettlement is = (IndianSettlement) ownerSettlement;
if (is != null) {
is.makeContactSettlement(this);
cs.add(See.only(null).perhaps(this),
owner.modifyTension(this, Tension.TENSION_ADD_LAND_TAKEN, is));
}
}
}
/**
* A unit migrates from Europe.
*
* @param slot The slot within <code>Europe</code> to select the unit from.
* @param type The type of migration occurring.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csEmigrate(int slot, MigrationType type, Random random,
ChangeSet cs) {
// Valid slots are in [1,3], recruitable indices are in [0,2].
// An invalid slot is normal when the player has no control over
// recruit type.
boolean selected = 1 <= slot && slot <= Europe.RECRUIT_COUNT;
int index = (selected) ? slot-1
: Utils.randomInt(logger, "Choose emigrant", random,
Europe.RECRUIT_COUNT);
// Create the recruit, move it to the docks.
Europe europe = getEurope();
UnitType recruitType = europe.getRecruitable(index);
Game game = getGame();
Unit unit = new ServerUnit(game, europe, this, recruitType,
UnitState.ACTIVE);
unit.setLocation(europe);
// Handle migration type specific changes.
switch (type) {
case FOUNTAIN:
setRemainingEmigrants(getRemainingEmigrants() - 1);
break;
case RECRUIT:
modifyGold(-europe.getRecruitPrice());
cs.addPartial(See.only(this), this, "gold");
europe.increaseRecruitmentDifficulty();
// Fall through
case NORMAL:
updateImmigrationRequired();
reduceImmigration();
cs.addPartial(See.only(this), this,
"immigration", "immigrationRequired");
break;
default:
throw new IllegalArgumentException("Bogus migration type");
}
// Replace the recruit we used.
List<RandomChoice<UnitType>> recruits = generateRecruitablesList();
europe.setRecruitable(index,
RandomChoice.getWeightedRandom(logger,
"Replace recruit", random, recruits));
cs.add(See.only(this), europe);
// Add an informative message only if this was an ordinary
// migration where we did not select the unit type.
// Other cases were selected.
if (!selected) {
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.UNIT_ADDED,
"model.europe.emigrate",
this, unit)
.add("%europe%", europe.getNameKey())
.addStringTemplate("%unit%", unit.getLabel()));
}
}
/**
* Combat.
*
* @param attacker The <code>FreeColGameObject</code> that is attacking.
* @param defender The <code>FreeColGameObject</code> that is defending.
* @param crs A list of <code>CombatResult</code>s defining the result.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csCombat(FreeColGameObject attacker,
FreeColGameObject defender,
List<CombatResult> crs,
Random random,
ChangeSet cs) throws IllegalStateException {
CombatModel combatModel = getGame().getCombatModel();
boolean isAttack = combatModel.combatIsAttack(attacker, defender);
boolean isBombard = combatModel.combatIsBombard(attacker, defender);
Unit attackerUnit = null;
Settlement attackerSettlement = null;
Tile attackerTile = null;
Unit defenderUnit = null;
ServerPlayer defenderPlayer = null;
Tile defenderTile = null;
if (isAttack) {
attackerUnit = (Unit) attacker;
attackerTile = attackerUnit.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound",
(attackerUnit.isNaval())
? "sound.attack.naval"
: (attackerUnit.hasAbility("model.ability.bombard"))
? "sound.attack.artillery"
: (attackerUnit.isMounted())
? "sound.attack.mounted"
: "sound.attack.foot");
} else if (isBombard) {
attackerSettlement = (Settlement) attacker;
attackerTile = attackerSettlement.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound", "sound.attack.bombard");
} else {
throw new IllegalStateException("Bogus combat");
}
// If the combat results were not specified (usually the case),
// query the combat model.
if (crs == null) {
crs = combatModel.generateAttackResult(random, attacker, defender);
}
if (crs.isEmpty()) {
throw new IllegalStateException("empty attack result");
}
// Extract main result, insisting it is one of the fundamental cases,
// and add the animation.
// Set vis so that loser always sees things.
// TODO: Bombard animations
See vis; // Visibility that insists on the loser seeing the result.
CombatResult result = crs.remove(0);
switch (result) {
case NO_RESULT:
vis = See.perhaps();
break; // Do not animate if there is no result.
case WIN:
vis = See.perhaps().always(defenderPlayer);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, true);
}
break;
case LOSE:
vis = See.perhaps().always(this);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, false);
}
break;
default:
throw new IllegalStateException("generateAttackResult returned: "
+ result);
}
// Now process the details.
boolean attackerTileDirty = false;
boolean defenderTileDirty = false;
boolean moveAttacker = false;
boolean burnedNativeCapital = false;
Settlement settlement = defenderTile.getSettlement();
Colony colony = defenderTile.getColony();
IndianSettlement natives = (settlement instanceof IndianSettlement)
? (IndianSettlement) settlement
: null;
int attackerTension = 0;
int defenderTension = 0;
for (CombatResult cr : crs) {
boolean ok;
switch (cr) {
case AUTOEQUIP_UNIT:
ok = isAttack && settlement != null;
if (ok) {
csAutoequipUnit(defenderUnit, settlement, cs);
}
break;
case BURN_MISSIONS:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
defenderTileDirty |= natives.getMissionary(this) != null;
csBurnMissions(attackerUnit, natives, cs);
}
break;
case CAPTURE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csCaptureAutoEquip(attackerUnit, defenderUnit, cs);
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isEuropean() && defenderPlayer.isEuropean();
if (ok) {
csCaptureColony(attackerUnit, colony, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case CAPTURE_CONVERT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
csCaptureConvert(attackerUnit, natives, random, cs);
attackerTileDirty = true;
}
break;
case CAPTURE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureEquip(attackerUnit, defenderUnit, cs);
} else {
csCaptureEquip(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureUnit(attackerUnit, defenderUnit, cs);
} else {
csCaptureUnit(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case DAMAGE_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csDamageColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case DAMAGE_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csDamageShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDamageShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DAMAGE_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csDamageShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case DEMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csDemoteUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDemoteUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DESTROY_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csDestroyColony(attackerUnit, colony, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case DESTROY_SETTLEMENT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& defenderPlayer.isIndian();
if (ok) {
csDestroySettlement(attackerUnit, natives, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
burnedNativeCapital = settlement.isCapital();
attackerTension -= Tension.TENSION_ADD_NORMAL;
if (!burnedNativeCapital) {
defenderTension += Tension.TENSION_ADD_MAJOR;
}
}
break;
case EVADE_ATTACK:
ok = isAttack && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeAttack(attackerUnit, defenderUnit, cs);
}
break;
case EVADE_BOMBARD:
ok = isBombard && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeBombard(attackerSettlement, defenderUnit, cs);
}
break;
case LOOT_SHIP:
ok = isAttack && result != CombatResult.NO_RESULT
&& attackerUnit.isNaval() && defenderUnit.isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csLootShip(attackerUnit, defenderUnit, cs);
} else {
csLootShip(defenderUnit, attackerUnit, cs);
}
}
break;
case LOSE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csLoseAutoEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case LOSE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csLoseEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csLoseEquip(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case PILLAGE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csPillageColony(attackerUnit, colony, random, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
}
break;
case PROMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csPromoteUnit(attackerUnit, defenderUnit, cs);
attackerTileDirty = true;
} else {
csPromoteUnit(defenderUnit, attackerUnit, cs);
defenderTileDirty = true;
}
}
break;
case SINK_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csSinkColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case SINK_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csSinkShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csSinkShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case SINK_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csSinkShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case SLAUGHTER_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csSlaughterUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += getSlaughterTension(defenderUnit);
} else {
csSlaughterUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
attackerTension += getSlaughterTension(attackerUnit);
defenderTension -= Tension.TENSION_ADD_NORMAL;
}
}
break;
default:
ok = false;
break;
}
if (!ok) {
throw new IllegalStateException("Attack (result=" + result
+ ") has bogus subresult: "
+ cr);
}
}
// Handle stance and tension.
// - Privateers do not provoke stance changes but can set the
// attackedByPrivateers flag
// - Attacks among Europeans imply war
// - Burning of a native capital results in surrender
// - Other attacks involving natives do not imply war, but
// changes in Tension can drive Stance, however this is
// decided by the native AI in their turn so just adjust tension.
if (attacker.hasAbility("model.ability.piracy")) {
if (!defenderPlayer.getAttackedByPrivateers()) {
defenderPlayer.setAttackedByPrivateers(true);
cs.addPartial(See.only(defenderPlayer), defenderPlayer,
"attackedByPrivateers");
}
} else if (defender.hasAbility("model.ability.piracy")) {
; // do nothing
} else if (isEuropean() && defenderPlayer.isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, true, cs);
} else if (burnedNativeCapital) {
csChangeStance(Stance.PEACE, defenderPlayer, true, cs);
defenderPlayer.getTension(this).setValue(Tension.SURRENDERED);
for (IndianSettlement is : defenderPlayer.getIndianSettlements()) {
+ is.makeContactSettlement(this);
is.getAlarm(this).setValue(Tension.SURRENDERED);
cs.add(See.perhaps(), is);
}
} else { // At least one player is non-European
if (isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, false, cs);
} else if (isIndian()) {
if (result == CombatResult.WIN) {
attackerTension -= Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
attackerTension += Tension.TENSION_ADD_MINOR;
}
}
if (defenderPlayer.isEuropean()) {
defenderPlayer.csChangeStance(Stance.WAR, this, false, cs);
} else if (defenderPlayer.isIndian()) {
if (result == CombatResult.WIN) {
defenderTension += Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
defenderTension -= Tension.TENSION_ADD_MINOR;
}
}
if (attackerTension != 0) {
cs.add(See.only(null).perhaps(defenderPlayer),
modifyTension(defenderPlayer, attackerTension));
}
if (defenderTension != 0) {
cs.add(See.only(null).perhaps(this),
defenderPlayer.modifyTension(this, defenderTension));
}
}
// Move the attacker if required.
if (moveAttacker) {
attackerUnit.setMovesLeft(attackerUnit.getInitialMovesLeft());
((ServerUnit) attackerUnit).csMove(defenderTile, random, cs);
attackerUnit.setMovesLeft(0);
// Move adds in updates for the tiles, but...
attackerTileDirty = defenderTileDirty = false;
// ...with visibility of perhaps().
// Thus the defender might see the change,
// but because its settlement is gone it also might not.
// So add in another defender-specific update.
// The worst that can happen is a duplicate update.
cs.add(See.only(defenderPlayer), defenderTile);
} else if (isAttack) {
// The Revenger unit can attack multiple times, so spend
// at least the eventual cost of moving to the tile.
// Other units consume the entire move.
if (attacker.hasAbility("model.ability.multipleAttacks")) {
int movecost = attackerUnit.getMoveCost(defenderTile);
attackerUnit.setMovesLeft(attackerUnit.getMovesLeft()
- movecost);
} else {
attackerUnit.setMovesLeft(0);
}
if (!attackerTileDirty) {
cs.addPartial(See.only(this), attacker, "movesLeft");
}
}
// Make sure we always update the attacker and defender tile
// if it is not already done yet.
if (attackerTileDirty) cs.add(vis, attackerTile);
if (defenderTileDirty) cs.add(vis, defenderTile);
}
/**
* Gets the amount to raise tension by when a unit is slaughtered.
*
* @param loser The <code>Unit</code> that dies.
* @return An amount to raise tension by.
*/
private int getSlaughterTension(Unit loser) {
// Tension rises faster when units die.
Settlement settlement = loser.getSettlement();
if (settlement != null) {
if (settlement instanceof IndianSettlement) {
return (((IndianSettlement) settlement).isCapital())
? Tension.TENSION_ADD_CAPITAL_ATTACKED
: Tension.TENSION_ADD_SETTLEMENT_ATTACKED;
} else {
return Tension.TENSION_ADD_NORMAL;
}
} else { // attack in the open
return (loser.getIndianSettlement() != null)
? Tension.TENSION_ADD_UNIT_DESTROYED
: Tension.TENSION_ADD_MINOR;
}
}
/**
* Notifies of automatic arming.
*
* @param unit The <code>Unit</code> that is auto-equipping.
* @param settlement The <code>Settlement</code> being defended.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csAutoequipUnit(Unit unit, Settlement settlement,
ChangeSet cs) {
ServerPlayer player = (ServerPlayer) unit.getOwner();
cs.addMessage(See.only(player),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.automaticDefence",
unit)
.addStringTemplate("%unit%", unit.getLabel())
.addName("%colony%", settlement.getName()));
}
/**
* Burns a players missions.
*
* @param attacker The <code>Unit</code> that attacked.
* @param settlement The <code>IndianSettlement</code> that was attacked.
* @param cs The <code>ChangeSet</code> to update.
*/
private void csBurnMissions(Unit attacker, IndianSettlement settlement,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attackerPlayer.getNationName();
ServerPlayer nativePlayer = (ServerPlayer) settlement.getOwner();
StringTemplate nativeNation = nativePlayer.getNationName();
// Message only for the European player
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.burnMissions",
attacker, settlement)
.addStringTemplate("%nation%", attackerNation)
.addStringTemplate("%enemyNation%", nativeNation));
// Burn down the missions
for (IndianSettlement s : nativePlayer.getIndianSettlements()) {
Unit missionary = s.getMissionary(attackerPlayer);
if (missionary != null) {
s.changeMissionary(null);
if (s != settlement) cs.add(See.perhaps(), s.getTile());
}
}
}
/**
* Defender autoequips but loses and attacker captures the equipment.
*
* @param attacker The <code>Unit</code> that attacked.
* @param defender The <code>Unit</code> that defended and loses equipment.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureAutoEquip(Unit attacker, Unit defender,
ChangeSet cs) {
EquipmentType equip
= defender.getBestCombatEquipmentType(defender.getAutomaticEquipment());
csLoseAutoEquip(attacker, defender, cs);
csCaptureEquipment(attacker, defender, equip, cs);
}
/**
* Captures a colony.
*
* @param attacker The attacking <code>Unit</code>.
* @param colony The <code>Colony</code> to capture.
* @param random A pseudo-random number source.
* @param cs The <code>ChangeSet</code> to update.
*/
private void csCaptureColony(Unit attacker, Colony colony, Random random,
ChangeSet cs) {
Game game = attacker.getGame();
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attackerPlayer.getNationName();
ServerPlayer colonyPlayer = (ServerPlayer) colony.getOwner();
StringTemplate colonyNation = colonyPlayer.getNationName();
Tile tile = colony.getTile();
int plunder = colony.getPlunder(attacker, random);
// Handle history and messages before colony handover
cs.addHistory(attackerPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.CONQUER_COLONY)
.addStringTemplate("%nation%", colonyNation)
.addName("%colony%", colony.getName()));
cs.addHistory(colonyPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.COLONY_CONQUERED)
.addStringTemplate("%nation%", attackerNation)
.addName("%colony%", colony.getName()));
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.colonyCaptured",
colony)
.addName("%colony%", colony.getName())
.addAmount("%amount%", plunder));
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.colonyCapturedBy",
colony.getTile())
.addName("%colony%", colony.getName())
.addAmount("%amount%", plunder)
.addStringTemplate("%player%", attackerNation));
// Allocate some plunder
if (plunder > 0) {
attackerPlayer.modifyGold(plunder);
colonyPlayer.modifyGold(-plunder);
cs.addPartial(See.only(attackerPlayer), attackerPlayer, "gold");
cs.addPartial(See.only(colonyPlayer), colonyPlayer, "gold");
}
// Hand over the colony
colony.changeOwner(attackerPlayer);
// Inform former owner of loss of owned tiles, and process possible
// increase in line of sight. Leave other exploration etc to csMove.
for (Tile t : colony.getOwnedTiles()) {
cs.add(See.perhaps().always(colonyPlayer), t);
}
if (colony.getLineOfSight() > attacker.getLineOfSight()) {
for (Tile t : tile.getSurroundingTiles(attacker.getLineOfSight(),
colony.getLineOfSight())) {
// New owner has now explored within settlement line of sight.
attackerPlayer.setExplored(t);
cs.add(See.only(attackerPlayer), t);
}
}
cs.addAttribute(See.only(attackerPlayer), "sound",
"sound.event.captureColony");
}
/**
* Extracts a convert from a native settlement.
*
* @pamam attacker The <code>Unit</code> that is attacking.
* @param settlement The <code>IndianSettlement</code> under attack.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureConvert(Unit attacker, IndianSettlement natives,
Random random, ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate convertNation = natives.getOwner().getNationName();
List<UnitType> converts = getGame().getSpecification()
.getUnitTypesWithAbility("model.ability.convert");
UnitType type = Utils.getRandomMember(logger, "Choose convert",
converts, random);
Unit convert = natives.getLastUnit();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.newConvertFromAttack",
convert)
.addStringTemplate("%nation%", convertNation)
.addStringTemplate("%unit%", convert.getLabel()));
convert.setOwner(attacker.getOwner());
convert.setType(type);
convert.setLocation(attacker.getTile());
}
/**
* Captures equipment.
*
* @param winner The <code>Unit</code> that captures equipment.
* @param loser The <code>Unit</code> that defended and loses equipment.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureEquip(Unit winner, Unit loser, ChangeSet cs) {
EquipmentType equip
= loser.getBestCombatEquipmentType(loser.getEquipment());
csLoseEquip(winner, loser, cs);
csCaptureEquipment(winner, loser, equip, cs);
}
/**
* Capture equipment.
*
* @param winner The <code>Unit</code> that is capturing equipment.
* @param loser The <code>Unit</code> that is losing equipment.
* @param equip The <code>EquipmentType</code> to capture.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureEquipment(Unit winner, Unit loser,
EquipmentType equip, ChangeSet cs) {
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
if ((equip = winner.canCaptureEquipment(equip, loser)) != null) {
// TODO: what if winner captures equipment that is
// incompatible with their current equipment?
// Currently, can-not-happen, so ignoring the return from
// changeEquipment. Beware.
winner.changeEquipment(equip, 1);
// Currently can not capture equipment back so this only
// makes sense for native players, and the message is
// native specific.
if (winnerPlayer.isIndian()) {
StringTemplate winnerNation = winnerPlayer.getNationName();
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.equipmentCaptured",
winnerPlayer)
.addStringTemplate("%nation%", winnerNation)
.add("%equipment%", equip.getNameKey()));
// CHEAT: Immediately transferring the captured goods
// back to a potentially remote settlement is pretty
// dubious. Apparently Col1 did it. Better would be
// to give the capturing unit a go-home-with-plunder mission.
IndianSettlement settlement = winner.getIndianSettlement();
if (settlement != null) {
for (AbstractGoods goods : equip.getGoodsRequired()) {
settlement.addGoods(goods);
logger.finest("CHEAT teleporting " + goods.toString()
+ " back to " + settlement.getName());
}
cs.add(See.only(winnerPlayer), settlement);
}
}
}
}
/**
* Capture a unit.
*
* @param winner A <code>Unit</code> that is capturing.
* @param loser A <code>Unit</code> to capture.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureUnit(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
StringTemplate loserNation = loserPlayer.getNationName();
StringTemplate loserLocation = loser.getLocation()
.getLocationNameFor(loserPlayer);
StringTemplate oldName = loser.getLabel();
String messageId = loser.getType().getId() + ".captured";
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate winnerLocation = winner.getLocation()
.getLocationNameFor(winnerPlayer);
// Capture the unit
UnitType type = loser.getTypeChange((winnerPlayer.isUndead())
? ChangeType.UNDEAD
: ChangeType.CAPTURE, winnerPlayer);
loser.setOwner(winnerPlayer);
if (type != null) loser.setType(type);
loser.setLocation(winner.getTile());
loser.setState(UnitState.ACTIVE);
// Winner message post-capture when it owns the loser
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser)
.setDefaultId("model.unit.unitCaptured")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%unit%", oldName)
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", winnerLocation));
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser.getTile())
.setDefaultId("model.unit.unitCaptured")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%unit%", oldName)
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", loserLocation));
}
/**
* Damages all ships in a colony.
*
* @param attacker The <code>Unit</code> that is damaging.
* @param colony The <code>Colony</code> to damage ships in.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDamageColonyShips(Unit attacker, Colony colony,
ChangeSet cs) {
List<Unit> units = new ArrayList<Unit>(colony.getTile().getUnitList());
while (!units.isEmpty()) {
Unit unit = units.remove(0);
if (unit.isNaval()) {
csDamageShipAttack(attacker, unit, cs);
}
}
}
/**
* Damage a ship through normal attack.
*
* @param attacker The attacker <code>Unit</code>.
* @param ship The <code>Unit</code> which is a ship to damage.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDamageShipAttack(Unit attacker, Unit ship,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attacker.getApparentOwnerName();
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
Location repair = ship.getRepairLocation();
StringTemplate repairLocationName = repair.getLocationNameFor(shipPlayer);
Location oldLocation = ship.getLocation();
StringTemplate shipNation = ship.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.enemyShipDamaged",
attacker)
.addStringTemplate("%unit%", attacker.getLabel())
.addStringTemplate("%enemyNation%", shipNation)
.addStringTemplate("%enemyUnit%", ship.getLabel()));
cs.addMessage(See.only(shipPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipDamaged",
ship)
.addStringTemplate("%unit%", ship.getLabel())
.addStringTemplate("%enemyUnit%", attacker.getLabel())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%repairLocation%", repairLocationName));
csDamageShip(ship, repair, cs);
}
/**
* Damage a ship through bombard.
*
* @param settlement The attacker <code>Settlement</code>.
* @param ship The <code>Unit</code> which is a ship to damage.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDamageShipBombard(Settlement settlement, Unit ship,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) settlement.getOwner();
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
Location repair = ship.getRepairLocation();
StringTemplate repairLocationName = repair.getLocationNameFor(shipPlayer);
StringTemplate shipNation = ship.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.enemyShipDamagedByBombardment",
settlement)
.addName("%colony%", settlement.getName())
.addStringTemplate("%nation%", shipNation)
.addStringTemplate("%unit%", ship.getLabel()));
cs.addMessage(See.only(shipPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipDamagedByBombardment",
ship)
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", ship.getLabel())
.addStringTemplate("%repairLocation%", repairLocationName));
csDamageShip(ship, repair, cs);
}
/**
* Damage a ship.
*
* @param ship The naval <code>Unit</code> to damage.
* @param repair The <code>Location</code> to send it to.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDamageShip(Unit ship, Location repair, ChangeSet cs) {
ServerPlayer player = (ServerPlayer) ship.getOwner();
// Lose the units aboard
Unit u;
while ((u = ship.getFirstUnit()) != null) {
u.setLocation(null);
cs.addDispose(player, ship, u);
}
// Damage the ship and send it off for repair
ship.getGoodsContainer().removeAll();
ship.setHitpoints(1);
ship.setDestination(null);
ship.setLocation(repair);
ship.setState(UnitState.ACTIVE);
ship.setMovesLeft(0);
cs.add(See.only(player), (FreeColGameObject) repair);
}
/**
* Demotes a unit.
*
* @param winner The <code>Unit</code> that won.
* @param loser The <code>Unit</code> that lost and should be demoted.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDemoteUnit(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
StringTemplate loserNation = loserPlayer.getNationName();
StringTemplate loserLocation = loser.getLocation()
.getLocationNameFor(loserPlayer);
StringTemplate oldName = loser.getLabel();
String messageId = loser.getType().getId() + ".demoted";
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate winnerLocation = winner.getLocation()
.getLocationNameFor(winnerPlayer);
UnitType type = loser.getTypeChange(ChangeType.DEMOTION, loserPlayer);
if (type == null || type == loser.getType()) {
logger.warning("Demotion failed, type="
+ ((type == null) ? "null"
: "same type: " + type));
return;
}
loser.setType(type);
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, winner)
.setDefaultId("model.unit.unitDemoted")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", winnerLocation));
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser)
.setDefaultId("model.unit.unitDemoted")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", loserLocation));
}
/**
* Destroy a colony.
*
* @param attacker The <code>Unit</code> that attacked.
* @param colony The <code>Colony</code> that was attacked.
* @param random A pseudo-random number source.
* @param cs The <code>ChangeSet</code> to update.
*/
private void csDestroyColony(Unit attacker, Colony colony, Random random,
ChangeSet cs) {
Game game = attacker.getGame();
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attackerPlayer.getNationName();
ServerPlayer colonyPlayer = (ServerPlayer) colony.getOwner();
StringTemplate colonyNation = colonyPlayer.getNationName();
Tile tile = colony.getTile();
int plunder = colony.getPlunder(attacker, random);
// Handle history and messages before colony destruction.
cs.addHistory(colonyPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.COLONY_DESTROYED)
.addStringTemplate("%nation%", attackerNation)
.addName("%colony%", colony.getName()));
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.colonyBurning",
colony.getTile())
.addName("%colony%", colony.getName())
.addAmount("%amount%", plunder)
.addStringTemplate("%nation%", attackerNation)
.addStringTemplate("%unit%", attacker.getLabel()));
cs.addMessage(See.all().except(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.colonyBurning.other",
attackerPlayer)
.addName("%colony%", colony.getName())
.addStringTemplate("%nation%", colonyNation)
.addStringTemplate("%attackerNation%", attackerNation));
// Allocate some plunder.
if (plunder > 0) {
attackerPlayer.modifyGold(plunder);
colonyPlayer.modifyGold(-plunder);
cs.addPartial(See.only(attackerPlayer), attackerPlayer, "gold");
cs.addPartial(See.only(colonyPlayer), colonyPlayer, "gold");
}
// Dispose of the colony and its contents.
csDisposeSettlement(colony, cs);
}
/**
* Destroys an Indian settlement.
*
* @param attacker an <code>Unit</code> value
* @param settlement an <code>IndianSettlement</code> value
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDestroySettlement(Unit attacker,
IndianSettlement settlement,
Random random, ChangeSet cs) {
Game game = getGame();
Tile tile = settlement.getTile();
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
ServerPlayer nativePlayer = (ServerPlayer) settlement.getOwner();
StringTemplate nativeNation = nativePlayer.getNationName();
String settlementName = settlement.getName();
boolean capital = settlement.isCapital();
int plunder = settlement.getPlunder(attacker, random);
// Destroy the settlement, update settlement tiles.
csDisposeSettlement(settlement, cs);
// Make the treasure train if there is treasure.
if (plunder > 0) {
List<UnitType> unitTypes = game.getSpecification()
.getUnitTypesWithAbility("model.ability.carryTreasure");
UnitType type = Utils.getRandomMember(logger, "Choose train",
unitTypes, random);
Unit train = new ServerUnit(game, tile, attackerPlayer, type,
UnitState.ACTIVE);
train.setTreasureAmount(plunder);
}
// This is an atrocity.
int atrocities = Player.SCORE_SETTLEMENT_DESTROYED;
if (settlement.getType().getClaimableRadius() > 1) atrocities *= 2;
if (capital) atrocities = (atrocities * 3) / 2;
attackerPlayer.modifyScore(atrocities);
cs.addPartial(See.only(attackerPlayer), attackerPlayer, "score");
// Finish with messages and history.
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.indianTreasure",
attacker)
.addName("%settlement%", settlementName)
.addAmount("%amount%", plunder));
cs.addHistory(attackerPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.DESTROY_SETTLEMENT)
.addStringTemplate("%nation%", nativeNation)
.addName("%settlement%", settlementName));
if (capital) {
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY,
"indianSettlement.capitalBurned",
attacker)
.addName("%name%", settlementName)
.addStringTemplate("%nation%", nativeNation));
}
if (nativePlayer.checkForDeath()) {
cs.addHistory(attackerPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.DESTROY_NATION)
.addStringTemplate("%nation%", nativeNation));
}
cs.addAttribute(See.only(attackerPlayer), "sound",
"sound.event.destroySettlement");
}
/**
* Disposes of a settlement and reassign its tiles.
*
* @param settlement The <code>Settlement</code> under attack.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDisposeSettlement(Settlement settlement, ChangeSet cs) {
ServerPlayer owner = (ServerPlayer) settlement.getOwner();
HashMap<Settlement, Integer> votes = new HashMap<Settlement, Integer>();
// Try to reassign the tiles
List<Tile> owned = settlement.getOwnedTiles();
Tile centerTile = settlement.getTile();
Settlement centerClaimant = null;
while (!owned.isEmpty()) {
Tile tile = owned.remove(0);
votes.clear();
for (Tile t : tile.getSurroundingTiles(1)) {
// For each lost tile, find any neighbouring
// settlements and give them a shout at claiming the tile.
// Note that settlements now can own tiles outside
// their radius--- if we encounter any of these clean
// them up too.
Settlement s = t.getOwningSettlement();
if (s == null) {
;
} else if (s == settlement) {
// Add this to the tiles to process if its not
// there already.
if (!owned.contains(t)) owned.add(t);
} else if (s.getOwner().canOwnTile(tile)
&& (s.getOwner().isIndian()
|| s.getTile().getDistanceTo(tile) <= s.getRadius())) {
// Weight claimant settlements:
// settlements owned by the same player
// > settlements owned by same type of player
// > other settlements
int value = (s.getOwner() == owner) ? 3
: (s.getOwner().isEuropean() == owner.isEuropean()) ? 2
: 1;
if (votes.get(s) != null) value += votes.get(s).intValue();
votes.put(s, new Integer(value));
}
}
Settlement bestClaimant = null;
int bestClaim = 0;
for (Entry<Settlement, Integer> vote : votes.entrySet()) {
if (vote.getValue().intValue() > bestClaim) {
bestClaimant = vote.getKey();
bestClaim = vote.getValue().intValue();
}
}
if (tile == centerTile) {
centerClaimant = bestClaimant; // Defer until settlement gone
} else {
if (bestClaimant == null) {
tile.changeOwnership(null, null);
} else {
tile.changeOwnership(bestClaimant.getOwner(), bestClaimant);
}
cs.add(See.perhaps().always(owner), tile);
}
}
// Settlement goes away
cs.addDispose(owner, centerTile, settlement);
if (centerClaimant != null) {
centerTile.changeOwnership(centerClaimant.getOwner(),
centerClaimant);
}
}
/**
* Evade a normal attack.
*
* @param attacker The attacker <code>Unit</code>.
* @param defender A naval <code>Unit</code> that evades the attacker.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csEvadeAttack(Unit attacker, Unit defender, ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attacker.getApparentOwnerName();
ServerPlayer defenderPlayer = (ServerPlayer) defender.getOwner();
StringTemplate defenderNation = defender.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.enemyShipEvaded",
attacker)
.addStringTemplate("%unit%", attacker.getLabel())
.addStringTemplate("%enemyUnit%", defender.getLabel())
.addStringTemplate("%enemyNation%", defenderNation));
cs.addMessage(See.only(defenderPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipEvaded",
defender)
.addStringTemplate("%unit%", defender.getLabel())
.addStringTemplate("%enemyUnit%", attacker.getLabel())
.addStringTemplate("%enemyNation%", attackerNation));
}
/**
* Evade a bombardment.
*
* @param settlement The attacker <code>Settlement</code>.
* @param defender A naval <code>Unit</code> that evades the attacker.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csEvadeBombard(Settlement settlement, Unit defender,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) settlement.getOwner();
ServerPlayer defenderPlayer = (ServerPlayer) defender.getOwner();
StringTemplate defenderNation = defender.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipEvadedBombardment",
settlement)
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", defender.getLabel())
.addStringTemplate("%nation%", defenderNation));
cs.addMessage(See.only(defenderPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipEvadedBombardment",
defender)
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", defender.getLabel())
.addStringTemplate("%nation%", defenderNation));
}
/**
* Loot a ship.
*
* @param winner The winning naval <code>Unit</code>.
* @param loser The losing naval <code>Unit</code>
* @param cs A <code>ChangeSet</code> to update.
*/
private void csLootShip(Unit winner, Unit loser, ChangeSet cs) {
List<Goods> capture = new ArrayList<Goods>(loser.getGoodsList());
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
if (capture.size() <= 0) return;
if (winnerPlayer.isAI()) {
// This should be in the AI code.
// Just loot in order of sale value.
final Market market = winnerPlayer.getMarket();
Collections.sort(capture, new Comparator<Goods>() {
public int compare(Goods g1, Goods g2) {
int p1 = market.getPaidForSale(g1.getType())
* g1.getAmount();
int p2 = market.getPaidForSale(g2.getType())
* g2.getAmount();
return p2 - p1;
}
});
while (capture.size() > 0) {
Goods g = capture.remove(0);
if (!winner.canAdd(g)) break;
winner.add(g);
}
} else if (winner.getSpaceLeft() > 0) {
for (Goods g : capture) g.setLocation(null);
TransactionSession.establishLootSession(winner, loser, capture);
cs.addAttribute(See.only(winnerPlayer), "loot", "true");
}
loser.getGoodsContainer().removeAll();
loser.setState(UnitState.ACTIVE);
}
/**
* Unit autoequips but loses equipment.
*
* @param attacker The <code>Unit</code> that attacked.
* @param defender The <code>Unit</code> that defended and loses equipment.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csLoseAutoEquip(Unit attacker, Unit defender, ChangeSet cs) {
ServerPlayer defenderPlayer = (ServerPlayer) defender.getOwner();
StringTemplate defenderNation = defenderPlayer.getNationName();
Settlement settlement = defender.getSettlement();
StringTemplate defenderLocation = defender.getLocation()
.getLocationNameFor(defenderPlayer);
EquipmentType equip = defender
.getBestCombatEquipmentType(defender.getAutomaticEquipment());
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerLocation = attacker.getLocation()
.getLocationNameFor(attackerPlayer);
StringTemplate attackerNation = attackerPlayer.getNationName();
// Autoequipment is not actually with the unit, it is stored
// in the settlement of the unit. Remove it from there.
for (AbstractGoods goods : equip.getGoodsRequired()) {
settlement.removeGoods(goods);
}
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.unitWinColony",
attacker)
.addStringTemplate("%location%", attackerLocation)
.addStringTemplate("%nation%", attackerNation)
.addStringTemplate("%unit%", attacker.getLabel())
.addName("%settlement%", settlement.getNameFor(attackerPlayer))
.addStringTemplate("%enemyNation%", defenderNation)
.addStringTemplate("%enemyUnit%", defender.getLabel()));
cs.addMessage(See.only(defenderPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.unitLoseAutoEquip",
defender)
.addStringTemplate("%location%", defenderLocation)
.addStringTemplate("%nation%", defenderNation)
.addStringTemplate("%unit%", defender.getLabel())
.addName("%settlement%", settlement.getNameFor(defenderPlayer))
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
}
/**
* Unit drops some equipment.
*
* @param winner The <code>Unit</code> that won.
* @param loser The <code>Unit</code> that lost and loses equipment.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csLoseEquip(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
StringTemplate loserNation = loserPlayer.getNationName();
StringTemplate loserLocation = loser.getLocation()
.getLocationNameFor(loserPlayer);
StringTemplate oldName = loser.getLabel();
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate winnerLocation = winner.getLocation()
.getLocationNameFor(winnerPlayer);
EquipmentType equip
= loser.getBestCombatEquipmentType(loser.getEquipment());
// Remove the equipment, accounting for possible loss of
// mobility due to horses going away.
loser.changeEquipment(equip, -1);
loser.setMovesLeft(Math.min(loser.getMovesLeft(),
loser.getInitialMovesLeft()));
String messageId;
if (loser.getEquipment().isEmpty()) {
messageId = "model.unit.unitDemotedToUnarmed";
loser.setState(UnitState.ACTIVE);
} else {
messageId = loser.getType().getId() + ".demoted";
}
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, winner)
.setDefaultId("model.unit.unitDemoted")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", winnerLocation));
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser)
.setDefaultId("model.unit.unitDemoted")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", loserLocation));
}
/**
* Damage a building or a ship or steal some goods or gold.
*
* @param attacker The attacking <code>Unit</code>.
* @param colony The <code>Colony</code> to pillage.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csPillageColony(Unit attacker, Colony colony,
Random random, ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attackerPlayer.getNationName();
ServerPlayer colonyPlayer = (ServerPlayer) colony.getOwner();
// Collect the damagable buildings, ships, movable goods.
List<Building> buildingList = colony.getBurnableBuildingList();
List<Unit> shipList = colony.getShipList();
List<Goods> goodsList = colony.getLootableGoodsList();
// Pick one, with one extra choice for stealing gold.
int pillage = Utils.randomInt(logger, "Pillage choice", random,
buildingList.size() + shipList.size()
+ goodsList.size()
+ ((colony.canBePlundered()) ? 1 : 0));
if (pillage < buildingList.size()) {
Building building = buildingList.get(pillage);
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.buildingDamaged",
colony)
.add("%building%", building.getNameKey())
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
colony.damageBuilding(building);
} else if (pillage < buildingList.size() + shipList.size()) {
Unit ship = shipList.get(pillage - buildingList.size());
if (ship.getRepairLocation() == null) {
csSinkShipAttack(attacker, ship, cs);
} else {
csDamageShipAttack(attacker, ship, cs);
}
} else if (pillage < buildingList.size() + shipList.size()
+ goodsList.size()) {
Goods goods = goodsList.get(pillage - buildingList.size()
- shipList.size());
goods.setAmount(Math.min(goods.getAmount() / 2, 50));
colony.removeGoods(goods);
if (attacker.getSpaceLeft() > 0) attacker.add(goods);
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.goodsStolen",
colony, goods)
.addAmount("%amount%", goods.getAmount())
.add("%goods%", goods.getNameKey())
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
} else {
int plunder = colony.getPlunder(attacker, random) / 10;
if (plunder > 0) {
colonyPlayer.modifyGold(-plunder);
attackerPlayer.modifyGold(plunder);
cs.addPartial(See.only(colonyPlayer), colonyPlayer, "gold");
}
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.indianPlunder",
colony)
.addAmount("%amount%", plunder)
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
}
}
/**
* Promotes a unit.
*
* @param winner The <code>Unit</code> that won and should be promoted.
* @param loser The <code>Unit</code> that lost.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csPromoteUnit(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate oldName = winner.getLabel();
UnitType type = winner.getTypeChange(ChangeType.PROMOTION,
winnerPlayer);
if (type == null || type == winner.getType()) {
logger.warning("Promotion failed, type="
+ ((type == null) ? "null"
: "same type: " + type));
return;
}
winner.setType(type);
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.unitPromoted", winner)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", winner.getLabel())
.addStringTemplate("%nation%", winnerNation));
}
/**
* Sinks all ships in a colony.
*
* @param attacker The attacker <code>Unit</code>.
* @param colony The <code>Colony</code> to sink ships in.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSinkColonyShips(Unit attacker, Colony colony, ChangeSet cs) {
List<Unit> units = new ArrayList<Unit>(colony.getTile().getUnitList());
while (!units.isEmpty()) {
Unit unit = units.remove(0);
if (unit.isNaval()) {
csSinkShipAttack(attacker, unit, cs);
}
}
}
/**
* Sinks this ship as result of a normal attack.
*
* @param attacker The attacker <code>Unit</code>.
* @param ship The naval <code>Unit</code> to sink.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSinkShipAttack(Unit attacker, Unit ship, ChangeSet cs) {
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
StringTemplate shipNation = ship.getApparentOwnerName();
Unit attackerUnit = (Unit) attacker;
ServerPlayer attackerPlayer = (ServerPlayer) attackerUnit.getOwner();
StringTemplate attackerNation = attackerUnit.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.enemyShipSunk",
attackerUnit)
.addStringTemplate("%unit%", attackerUnit.getLabel())
.addStringTemplate("%enemyUnit%", ship.getLabel())
.addStringTemplate("%enemyNation%", shipNation));
cs.addMessage(See.only(shipPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipSunk",
ship.getTile())
.addStringTemplate("%unit%", ship.getLabel())
.addStringTemplate("%enemyUnit%", attackerUnit.getLabel())
.addStringTemplate("%enemyNation%", attackerNation));
csSinkShip(ship, attackerPlayer, cs);
}
/**
* Sinks this ship as result of a bombard.
*
* @param settlement The bombarding <code>Settlement</code>.
* @param ship The naval <code>Unit</code> to sink.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSinkShipBombard(Settlement settlement, Unit ship,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) settlement.getOwner();
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
StringTemplate shipNation = ship.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipSunkByBombardment",
settlement)
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", ship.getLabel())
.addStringTemplate("%nation%", shipNation));
cs.addMessage(See.only(shipPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipSunkByBombardment",
ship.getTile())
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", ship.getLabel()));
csSinkShip(ship, attackerPlayer, cs);
}
/**
* Sink the ship.
*
* @param ship The naval <code>Unit</code> to sink.
* @param attackerPlayer The <code>ServerPlayer</code> that attacked.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSinkShip(Unit ship, ServerPlayer attackerPlayer,
ChangeSet cs) {
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
cs.addDispose(shipPlayer, ship.getLocation(), ship);
cs.addAttribute(See.only(attackerPlayer), "sound",
"sound.event.shipSunk");
}
/**
* Slaughter a unit.
*
* @param winner The <code>Unit</code> that is slaughtering.
* @param loser The <code>Unit</code> to slaughter.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSlaughterUnit(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate winnerLocation = winner.getLocation()
.getLocationNameFor(winnerPlayer);
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
StringTemplate loserNation = loserPlayer.getNationName();
StringTemplate loserLocation = loser.getLocation()
.getLocationNameFor(loserPlayer);
String messageId = loser.getType().getId() + ".destroyed";
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, winner)
.setDefaultId("model.unit.unitSlaughtered")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", winnerLocation));
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser.getTile())
.setDefaultId("model.unit.unitSlaughtered")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", loserLocation));
if (loserPlayer.isIndian() && loserPlayer.checkForDeath()) {
StringTemplate nativeNation = loserPlayer.getNationName();
cs.addHistory(winnerPlayer,
new HistoryEvent(getGame().getTurn(),
HistoryEvent.EventType.DESTROY_NATION)
.addStringTemplate("%nation%", nativeNation));
}
// Transfer equipment, do not generate messages for the loser.
EquipmentType equip;
while ((equip = loser.getBestCombatEquipmentType(loser.getEquipment()))
!= null) {
loser.changeEquipment(equip, -loser.getEquipmentCount(equip));
csCaptureEquipment(winner, loser, equip, cs);
}
// Destroy unit.
cs.addDispose(loserPlayer, loser.getLocation(), loser);
}
/**
* Updates the PlayerExploredTile for each new tile on a supplied list,
* and update a changeset as well.
*
* @param newTiles A list of <code>Tile</code>s to update.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csSeeNewTiles(List<Tile> newTiles, ChangeSet cs) {
for (Tile t : newTiles) {
t.updatePlayerExploredTile(this, false);
cs.add(See.only(this), t);
}
}
@Override
public String toString() {
return "ServerPlayer[name=" + getName() + ",ID=" + getId()
+ ",conn=" + connection + "]";
}
/**
* Returns the tag name of the root element representing this object.
*
* @return "serverPlayer"
*/
public String getServerXMLElementTagName() {
return "serverPlayer";
}
}
| true | true | public void csCombat(FreeColGameObject attacker,
FreeColGameObject defender,
List<CombatResult> crs,
Random random,
ChangeSet cs) throws IllegalStateException {
CombatModel combatModel = getGame().getCombatModel();
boolean isAttack = combatModel.combatIsAttack(attacker, defender);
boolean isBombard = combatModel.combatIsBombard(attacker, defender);
Unit attackerUnit = null;
Settlement attackerSettlement = null;
Tile attackerTile = null;
Unit defenderUnit = null;
ServerPlayer defenderPlayer = null;
Tile defenderTile = null;
if (isAttack) {
attackerUnit = (Unit) attacker;
attackerTile = attackerUnit.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound",
(attackerUnit.isNaval())
? "sound.attack.naval"
: (attackerUnit.hasAbility("model.ability.bombard"))
? "sound.attack.artillery"
: (attackerUnit.isMounted())
? "sound.attack.mounted"
: "sound.attack.foot");
} else if (isBombard) {
attackerSettlement = (Settlement) attacker;
attackerTile = attackerSettlement.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound", "sound.attack.bombard");
} else {
throw new IllegalStateException("Bogus combat");
}
// If the combat results were not specified (usually the case),
// query the combat model.
if (crs == null) {
crs = combatModel.generateAttackResult(random, attacker, defender);
}
if (crs.isEmpty()) {
throw new IllegalStateException("empty attack result");
}
// Extract main result, insisting it is one of the fundamental cases,
// and add the animation.
// Set vis so that loser always sees things.
// TODO: Bombard animations
See vis; // Visibility that insists on the loser seeing the result.
CombatResult result = crs.remove(0);
switch (result) {
case NO_RESULT:
vis = See.perhaps();
break; // Do not animate if there is no result.
case WIN:
vis = See.perhaps().always(defenderPlayer);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, true);
}
break;
case LOSE:
vis = See.perhaps().always(this);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, false);
}
break;
default:
throw new IllegalStateException("generateAttackResult returned: "
+ result);
}
// Now process the details.
boolean attackerTileDirty = false;
boolean defenderTileDirty = false;
boolean moveAttacker = false;
boolean burnedNativeCapital = false;
Settlement settlement = defenderTile.getSettlement();
Colony colony = defenderTile.getColony();
IndianSettlement natives = (settlement instanceof IndianSettlement)
? (IndianSettlement) settlement
: null;
int attackerTension = 0;
int defenderTension = 0;
for (CombatResult cr : crs) {
boolean ok;
switch (cr) {
case AUTOEQUIP_UNIT:
ok = isAttack && settlement != null;
if (ok) {
csAutoequipUnit(defenderUnit, settlement, cs);
}
break;
case BURN_MISSIONS:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
defenderTileDirty |= natives.getMissionary(this) != null;
csBurnMissions(attackerUnit, natives, cs);
}
break;
case CAPTURE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csCaptureAutoEquip(attackerUnit, defenderUnit, cs);
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isEuropean() && defenderPlayer.isEuropean();
if (ok) {
csCaptureColony(attackerUnit, colony, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case CAPTURE_CONVERT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
csCaptureConvert(attackerUnit, natives, random, cs);
attackerTileDirty = true;
}
break;
case CAPTURE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureEquip(attackerUnit, defenderUnit, cs);
} else {
csCaptureEquip(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureUnit(attackerUnit, defenderUnit, cs);
} else {
csCaptureUnit(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case DAMAGE_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csDamageColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case DAMAGE_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csDamageShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDamageShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DAMAGE_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csDamageShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case DEMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csDemoteUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDemoteUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DESTROY_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csDestroyColony(attackerUnit, colony, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case DESTROY_SETTLEMENT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& defenderPlayer.isIndian();
if (ok) {
csDestroySettlement(attackerUnit, natives, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
burnedNativeCapital = settlement.isCapital();
attackerTension -= Tension.TENSION_ADD_NORMAL;
if (!burnedNativeCapital) {
defenderTension += Tension.TENSION_ADD_MAJOR;
}
}
break;
case EVADE_ATTACK:
ok = isAttack && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeAttack(attackerUnit, defenderUnit, cs);
}
break;
case EVADE_BOMBARD:
ok = isBombard && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeBombard(attackerSettlement, defenderUnit, cs);
}
break;
case LOOT_SHIP:
ok = isAttack && result != CombatResult.NO_RESULT
&& attackerUnit.isNaval() && defenderUnit.isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csLootShip(attackerUnit, defenderUnit, cs);
} else {
csLootShip(defenderUnit, attackerUnit, cs);
}
}
break;
case LOSE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csLoseAutoEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case LOSE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csLoseEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csLoseEquip(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case PILLAGE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csPillageColony(attackerUnit, colony, random, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
}
break;
case PROMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csPromoteUnit(attackerUnit, defenderUnit, cs);
attackerTileDirty = true;
} else {
csPromoteUnit(defenderUnit, attackerUnit, cs);
defenderTileDirty = true;
}
}
break;
case SINK_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csSinkColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case SINK_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csSinkShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csSinkShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case SINK_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csSinkShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case SLAUGHTER_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csSlaughterUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += getSlaughterTension(defenderUnit);
} else {
csSlaughterUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
attackerTension += getSlaughterTension(attackerUnit);
defenderTension -= Tension.TENSION_ADD_NORMAL;
}
}
break;
default:
ok = false;
break;
}
if (!ok) {
throw new IllegalStateException("Attack (result=" + result
+ ") has bogus subresult: "
+ cr);
}
}
// Handle stance and tension.
// - Privateers do not provoke stance changes but can set the
// attackedByPrivateers flag
// - Attacks among Europeans imply war
// - Burning of a native capital results in surrender
// - Other attacks involving natives do not imply war, but
// changes in Tension can drive Stance, however this is
// decided by the native AI in their turn so just adjust tension.
if (attacker.hasAbility("model.ability.piracy")) {
if (!defenderPlayer.getAttackedByPrivateers()) {
defenderPlayer.setAttackedByPrivateers(true);
cs.addPartial(See.only(defenderPlayer), defenderPlayer,
"attackedByPrivateers");
}
} else if (defender.hasAbility("model.ability.piracy")) {
; // do nothing
} else if (isEuropean() && defenderPlayer.isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, true, cs);
} else if (burnedNativeCapital) {
csChangeStance(Stance.PEACE, defenderPlayer, true, cs);
defenderPlayer.getTension(this).setValue(Tension.SURRENDERED);
for (IndianSettlement is : defenderPlayer.getIndianSettlements()) {
is.getAlarm(this).setValue(Tension.SURRENDERED);
cs.add(See.perhaps(), is);
}
} else { // At least one player is non-European
if (isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, false, cs);
} else if (isIndian()) {
if (result == CombatResult.WIN) {
attackerTension -= Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
attackerTension += Tension.TENSION_ADD_MINOR;
}
}
if (defenderPlayer.isEuropean()) {
defenderPlayer.csChangeStance(Stance.WAR, this, false, cs);
} else if (defenderPlayer.isIndian()) {
if (result == CombatResult.WIN) {
defenderTension += Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
defenderTension -= Tension.TENSION_ADD_MINOR;
}
}
if (attackerTension != 0) {
cs.add(See.only(null).perhaps(defenderPlayer),
modifyTension(defenderPlayer, attackerTension));
}
if (defenderTension != 0) {
cs.add(See.only(null).perhaps(this),
defenderPlayer.modifyTension(this, defenderTension));
}
}
// Move the attacker if required.
if (moveAttacker) {
attackerUnit.setMovesLeft(attackerUnit.getInitialMovesLeft());
((ServerUnit) attackerUnit).csMove(defenderTile, random, cs);
attackerUnit.setMovesLeft(0);
// Move adds in updates for the tiles, but...
attackerTileDirty = defenderTileDirty = false;
// ...with visibility of perhaps().
// Thus the defender might see the change,
// but because its settlement is gone it also might not.
// So add in another defender-specific update.
// The worst that can happen is a duplicate update.
cs.add(See.only(defenderPlayer), defenderTile);
} else if (isAttack) {
// The Revenger unit can attack multiple times, so spend
// at least the eventual cost of moving to the tile.
// Other units consume the entire move.
if (attacker.hasAbility("model.ability.multipleAttacks")) {
int movecost = attackerUnit.getMoveCost(defenderTile);
attackerUnit.setMovesLeft(attackerUnit.getMovesLeft()
- movecost);
} else {
attackerUnit.setMovesLeft(0);
}
if (!attackerTileDirty) {
cs.addPartial(See.only(this), attacker, "movesLeft");
}
}
// Make sure we always update the attacker and defender tile
// if it is not already done yet.
if (attackerTileDirty) cs.add(vis, attackerTile);
if (defenderTileDirty) cs.add(vis, defenderTile);
}
| public void csCombat(FreeColGameObject attacker,
FreeColGameObject defender,
List<CombatResult> crs,
Random random,
ChangeSet cs) throws IllegalStateException {
CombatModel combatModel = getGame().getCombatModel();
boolean isAttack = combatModel.combatIsAttack(attacker, defender);
boolean isBombard = combatModel.combatIsBombard(attacker, defender);
Unit attackerUnit = null;
Settlement attackerSettlement = null;
Tile attackerTile = null;
Unit defenderUnit = null;
ServerPlayer defenderPlayer = null;
Tile defenderTile = null;
if (isAttack) {
attackerUnit = (Unit) attacker;
attackerTile = attackerUnit.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound",
(attackerUnit.isNaval())
? "sound.attack.naval"
: (attackerUnit.hasAbility("model.ability.bombard"))
? "sound.attack.artillery"
: (attackerUnit.isMounted())
? "sound.attack.mounted"
: "sound.attack.foot");
} else if (isBombard) {
attackerSettlement = (Settlement) attacker;
attackerTile = attackerSettlement.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound", "sound.attack.bombard");
} else {
throw new IllegalStateException("Bogus combat");
}
// If the combat results were not specified (usually the case),
// query the combat model.
if (crs == null) {
crs = combatModel.generateAttackResult(random, attacker, defender);
}
if (crs.isEmpty()) {
throw new IllegalStateException("empty attack result");
}
// Extract main result, insisting it is one of the fundamental cases,
// and add the animation.
// Set vis so that loser always sees things.
// TODO: Bombard animations
See vis; // Visibility that insists on the loser seeing the result.
CombatResult result = crs.remove(0);
switch (result) {
case NO_RESULT:
vis = See.perhaps();
break; // Do not animate if there is no result.
case WIN:
vis = See.perhaps().always(defenderPlayer);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, true);
}
break;
case LOSE:
vis = See.perhaps().always(this);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, false);
}
break;
default:
throw new IllegalStateException("generateAttackResult returned: "
+ result);
}
// Now process the details.
boolean attackerTileDirty = false;
boolean defenderTileDirty = false;
boolean moveAttacker = false;
boolean burnedNativeCapital = false;
Settlement settlement = defenderTile.getSettlement();
Colony colony = defenderTile.getColony();
IndianSettlement natives = (settlement instanceof IndianSettlement)
? (IndianSettlement) settlement
: null;
int attackerTension = 0;
int defenderTension = 0;
for (CombatResult cr : crs) {
boolean ok;
switch (cr) {
case AUTOEQUIP_UNIT:
ok = isAttack && settlement != null;
if (ok) {
csAutoequipUnit(defenderUnit, settlement, cs);
}
break;
case BURN_MISSIONS:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
defenderTileDirty |= natives.getMissionary(this) != null;
csBurnMissions(attackerUnit, natives, cs);
}
break;
case CAPTURE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csCaptureAutoEquip(attackerUnit, defenderUnit, cs);
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isEuropean() && defenderPlayer.isEuropean();
if (ok) {
csCaptureColony(attackerUnit, colony, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case CAPTURE_CONVERT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
csCaptureConvert(attackerUnit, natives, random, cs);
attackerTileDirty = true;
}
break;
case CAPTURE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureEquip(attackerUnit, defenderUnit, cs);
} else {
csCaptureEquip(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureUnit(attackerUnit, defenderUnit, cs);
} else {
csCaptureUnit(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case DAMAGE_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csDamageColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case DAMAGE_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csDamageShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDamageShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DAMAGE_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csDamageShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case DEMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csDemoteUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDemoteUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DESTROY_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csDestroyColony(attackerUnit, colony, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case DESTROY_SETTLEMENT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& defenderPlayer.isIndian();
if (ok) {
csDestroySettlement(attackerUnit, natives, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
burnedNativeCapital = settlement.isCapital();
attackerTension -= Tension.TENSION_ADD_NORMAL;
if (!burnedNativeCapital) {
defenderTension += Tension.TENSION_ADD_MAJOR;
}
}
break;
case EVADE_ATTACK:
ok = isAttack && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeAttack(attackerUnit, defenderUnit, cs);
}
break;
case EVADE_BOMBARD:
ok = isBombard && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeBombard(attackerSettlement, defenderUnit, cs);
}
break;
case LOOT_SHIP:
ok = isAttack && result != CombatResult.NO_RESULT
&& attackerUnit.isNaval() && defenderUnit.isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csLootShip(attackerUnit, defenderUnit, cs);
} else {
csLootShip(defenderUnit, attackerUnit, cs);
}
}
break;
case LOSE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csLoseAutoEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case LOSE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csLoseEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csLoseEquip(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case PILLAGE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csPillageColony(attackerUnit, colony, random, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
}
break;
case PROMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csPromoteUnit(attackerUnit, defenderUnit, cs);
attackerTileDirty = true;
} else {
csPromoteUnit(defenderUnit, attackerUnit, cs);
defenderTileDirty = true;
}
}
break;
case SINK_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csSinkColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case SINK_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csSinkShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csSinkShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case SINK_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csSinkShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case SLAUGHTER_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csSlaughterUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += getSlaughterTension(defenderUnit);
} else {
csSlaughterUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
attackerTension += getSlaughterTension(attackerUnit);
defenderTension -= Tension.TENSION_ADD_NORMAL;
}
}
break;
default:
ok = false;
break;
}
if (!ok) {
throw new IllegalStateException("Attack (result=" + result
+ ") has bogus subresult: "
+ cr);
}
}
// Handle stance and tension.
// - Privateers do not provoke stance changes but can set the
// attackedByPrivateers flag
// - Attacks among Europeans imply war
// - Burning of a native capital results in surrender
// - Other attacks involving natives do not imply war, but
// changes in Tension can drive Stance, however this is
// decided by the native AI in their turn so just adjust tension.
if (attacker.hasAbility("model.ability.piracy")) {
if (!defenderPlayer.getAttackedByPrivateers()) {
defenderPlayer.setAttackedByPrivateers(true);
cs.addPartial(See.only(defenderPlayer), defenderPlayer,
"attackedByPrivateers");
}
} else if (defender.hasAbility("model.ability.piracy")) {
; // do nothing
} else if (isEuropean() && defenderPlayer.isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, true, cs);
} else if (burnedNativeCapital) {
csChangeStance(Stance.PEACE, defenderPlayer, true, cs);
defenderPlayer.getTension(this).setValue(Tension.SURRENDERED);
for (IndianSettlement is : defenderPlayer.getIndianSettlements()) {
is.makeContactSettlement(this);
is.getAlarm(this).setValue(Tension.SURRENDERED);
cs.add(See.perhaps(), is);
}
} else { // At least one player is non-European
if (isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, false, cs);
} else if (isIndian()) {
if (result == CombatResult.WIN) {
attackerTension -= Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
attackerTension += Tension.TENSION_ADD_MINOR;
}
}
if (defenderPlayer.isEuropean()) {
defenderPlayer.csChangeStance(Stance.WAR, this, false, cs);
} else if (defenderPlayer.isIndian()) {
if (result == CombatResult.WIN) {
defenderTension += Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
defenderTension -= Tension.TENSION_ADD_MINOR;
}
}
if (attackerTension != 0) {
cs.add(See.only(null).perhaps(defenderPlayer),
modifyTension(defenderPlayer, attackerTension));
}
if (defenderTension != 0) {
cs.add(See.only(null).perhaps(this),
defenderPlayer.modifyTension(this, defenderTension));
}
}
// Move the attacker if required.
if (moveAttacker) {
attackerUnit.setMovesLeft(attackerUnit.getInitialMovesLeft());
((ServerUnit) attackerUnit).csMove(defenderTile, random, cs);
attackerUnit.setMovesLeft(0);
// Move adds in updates for the tiles, but...
attackerTileDirty = defenderTileDirty = false;
// ...with visibility of perhaps().
// Thus the defender might see the change,
// but because its settlement is gone it also might not.
// So add in another defender-specific update.
// The worst that can happen is a duplicate update.
cs.add(See.only(defenderPlayer), defenderTile);
} else if (isAttack) {
// The Revenger unit can attack multiple times, so spend
// at least the eventual cost of moving to the tile.
// Other units consume the entire move.
if (attacker.hasAbility("model.ability.multipleAttacks")) {
int movecost = attackerUnit.getMoveCost(defenderTile);
attackerUnit.setMovesLeft(attackerUnit.getMovesLeft()
- movecost);
} else {
attackerUnit.setMovesLeft(0);
}
if (!attackerTileDirty) {
cs.addPartial(See.only(this), attacker, "movesLeft");
}
}
// Make sure we always update the attacker and defender tile
// if it is not already done yet.
if (attackerTileDirty) cs.add(vis, attackerTile);
if (defenderTileDirty) cs.add(vis, defenderTile);
}
|
diff --git a/src/com/nexus/webserver/WebServer.java b/src/com/nexus/webserver/WebServer.java
index d6fd35d..debc7e3 100644
--- a/src/com/nexus/webserver/WebServer.java
+++ b/src/com/nexus/webserver/WebServer.java
@@ -1,131 +1,128 @@
package com.nexus.webserver;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
import com.nexus.logging.NexusLogger;
public class WebServer implements Runnable {
private Logger Log = Logger.getLogger("Webserver");
private int port;
private boolean restart = false;
private ServerSocket Socket;
private ServerSocketChannel SocketChannel;
private Selector SocketSelector;
public WebServer(int port){
this.port = port;
this.Log.setParent(NexusLogger.getLogger());
}
public void run() {
this.Log.info("Server starting...");
try {
SocketAddress addr = new InetSocketAddress(port);
SocketChannel = ServerSocketChannel.open();
SocketChannel.configureBlocking(false);
Socket = this.SocketChannel.socket();
Socket.bind(addr);
SocketSelector = Selector.open();
SocketChannel.register(SocketSelector, SocketChannel.validOps());
}
catch (IOException e) {
this.Log.severe("Could not listen on port " + this.port + "!");
return;
}
this.Log.info("Server started!");
boolean stop = false;
while (!stop) {
Socket ClientSocket = null;
SelectionKey Key = null;
try {
SocketSelector.select();
Set<SelectionKey> keys = SocketSelector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while(i.hasNext()){
Key = i.next();
i.remove();
if(!Key.isValid()){
continue;
}
try{
if (Key.isAcceptable()) {
SocketChannel Channel = SocketChannel.accept();
Channel.configureBlocking(false);
Channel.register(SocketSelector, SelectionKey.OP_READ);
}else if (Key.isReadable()) {
SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if (Session == null) {
Session = new WebServerSession(Channel);
Key.attach(Session);
}
Session.readData();
ClientSocket = Channel.socket();
this.Log.finest("Connected by " + ClientSocket.getRemoteSocketAddress().toString().substring(1).split(":")[0] + ".");
WebServerRequestThread Handler = new WebServerRequestThread(Session);
(new Thread(Handler)).run();
Session.close();
ClientSocket.close();
Channel.close();
if (Handler.requestedStop())
stop = true;
if (Handler.requestedRestart()) {
stop = true;
this.setRestart(true);
}
}
}catch(Exception e){
- System.err.println("Error handling client: " + Key.channel());
- System.err.println(e);
- System.err.println("\tat " + e.getStackTrace()[0]);
if (Key.attachment() instanceof WebServerSession) {
((WebServerSession) Key.attachment()).close();
}
}
}
}
catch (IOException e) {
- this.Log.severe("Error while accepting connections.");
+ System.err.println("Error while accepting connections.");
e.printStackTrace();
stop = true;
}
}
try {
Socket.close();
SocketChannel.close();
} catch (IOException e) {
}
}
public boolean requestedRestart() {
return restart;
}
public void setRestart(boolean restart) {
this.restart = restart;
}
}
| false | true | public void run() {
this.Log.info("Server starting...");
try {
SocketAddress addr = new InetSocketAddress(port);
SocketChannel = ServerSocketChannel.open();
SocketChannel.configureBlocking(false);
Socket = this.SocketChannel.socket();
Socket.bind(addr);
SocketSelector = Selector.open();
SocketChannel.register(SocketSelector, SocketChannel.validOps());
}
catch (IOException e) {
this.Log.severe("Could not listen on port " + this.port + "!");
return;
}
this.Log.info("Server started!");
boolean stop = false;
while (!stop) {
Socket ClientSocket = null;
SelectionKey Key = null;
try {
SocketSelector.select();
Set<SelectionKey> keys = SocketSelector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while(i.hasNext()){
Key = i.next();
i.remove();
if(!Key.isValid()){
continue;
}
try{
if (Key.isAcceptable()) {
SocketChannel Channel = SocketChannel.accept();
Channel.configureBlocking(false);
Channel.register(SocketSelector, SelectionKey.OP_READ);
}else if (Key.isReadable()) {
SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if (Session == null) {
Session = new WebServerSession(Channel);
Key.attach(Session);
}
Session.readData();
ClientSocket = Channel.socket();
this.Log.finest("Connected by " + ClientSocket.getRemoteSocketAddress().toString().substring(1).split(":")[0] + ".");
WebServerRequestThread Handler = new WebServerRequestThread(Session);
(new Thread(Handler)).run();
Session.close();
ClientSocket.close();
Channel.close();
if (Handler.requestedStop())
stop = true;
if (Handler.requestedRestart()) {
stop = true;
this.setRestart(true);
}
}
}catch(Exception e){
System.err.println("Error handling client: " + Key.channel());
System.err.println(e);
System.err.println("\tat " + e.getStackTrace()[0]);
if (Key.attachment() instanceof WebServerSession) {
((WebServerSession) Key.attachment()).close();
}
}
}
}
catch (IOException e) {
this.Log.severe("Error while accepting connections.");
e.printStackTrace();
stop = true;
}
}
try {
Socket.close();
SocketChannel.close();
} catch (IOException e) {
}
}
| public void run() {
this.Log.info("Server starting...");
try {
SocketAddress addr = new InetSocketAddress(port);
SocketChannel = ServerSocketChannel.open();
SocketChannel.configureBlocking(false);
Socket = this.SocketChannel.socket();
Socket.bind(addr);
SocketSelector = Selector.open();
SocketChannel.register(SocketSelector, SocketChannel.validOps());
}
catch (IOException e) {
this.Log.severe("Could not listen on port " + this.port + "!");
return;
}
this.Log.info("Server started!");
boolean stop = false;
while (!stop) {
Socket ClientSocket = null;
SelectionKey Key = null;
try {
SocketSelector.select();
Set<SelectionKey> keys = SocketSelector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while(i.hasNext()){
Key = i.next();
i.remove();
if(!Key.isValid()){
continue;
}
try{
if (Key.isAcceptable()) {
SocketChannel Channel = SocketChannel.accept();
Channel.configureBlocking(false);
Channel.register(SocketSelector, SelectionKey.OP_READ);
}else if (Key.isReadable()) {
SocketChannel Channel = (SocketChannel) Key.channel();
WebServerSession Session = (WebServerSession) Key.attachment();
if (Session == null) {
Session = new WebServerSession(Channel);
Key.attach(Session);
}
Session.readData();
ClientSocket = Channel.socket();
this.Log.finest("Connected by " + ClientSocket.getRemoteSocketAddress().toString().substring(1).split(":")[0] + ".");
WebServerRequestThread Handler = new WebServerRequestThread(Session);
(new Thread(Handler)).run();
Session.close();
ClientSocket.close();
Channel.close();
if (Handler.requestedStop())
stop = true;
if (Handler.requestedRestart()) {
stop = true;
this.setRestart(true);
}
}
}catch(Exception e){
if (Key.attachment() instanceof WebServerSession) {
((WebServerSession) Key.attachment()).close();
}
}
}
}
catch (IOException e) {
System.err.println("Error while accepting connections.");
e.printStackTrace();
stop = true;
}
}
try {
Socket.close();
SocketChannel.close();
} catch (IOException e) {
}
}
|
diff --git a/src/test/java/com/zestia/rest/capsule/restapi/SocialNetworkLinks.java b/src/test/java/com/zestia/rest/capsule/restapi/SocialNetworkLinks.java
index 8ecabdf..1044ffd 100644
--- a/src/test/java/com/zestia/rest/capsule/restapi/SocialNetworkLinks.java
+++ b/src/test/java/com/zestia/rest/capsule/restapi/SocialNetworkLinks.java
@@ -1,188 +1,188 @@
package com.zestia.rest.capsule.restapi;
import com.google.common.base.CharMatcher;
import com.google.common.collect.Sets;
import com.zestia.capsule.restapi.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.libs.WS;
import java.io.IOException;
import java.nio.charset.IllegalCharsetNameException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static play.test.Helpers.running;
/**
* Integration tests or demo's that serve a greater purpose.
* <ul>
* <li>Skype: creates Skype social network links from phone numbers of your contacts (ignores fax numbers and deletes duplicate numbers)</li>
* <li>Twitter: creates Twitter social network lniks by visiting your contacts' websites and looking for a screen name</li>
* </ul>
*
* @author Mathias Bogaert
*/
public class SocialNetworkLinks extends CapsuleTest {
// TODO logging isn't working in Play 2.0 unit tests, find a solution
private static final Logger logger = LoggerFactory.getLogger("application");
@Test
public void addSkypeLinks() throws Exception {
running(fakeApplication(), new Runnable() {
public void run() {
logger.info("Listing all parties...");
CParties parties = CParty.listAll(5, TimeUnit.SECONDS).get(50l, TimeUnit.SECONDS);
System.out.println("Found " + parties.size + " parties, adding Skype links from phone numbers...");
for (CParty party : parties) {
Set<String> phoneNumbers = Sets.newHashSet();
Set<String> skypeNumbers = Sets.newHashSet();
for (CContact contact : party.contacts) {
if (contact instanceof CPhone) {
CPhone phone = (CPhone) contact;
if (!"Fax".equals(phone.type)) {
String phoneNumber = CharMatcher.WHITESPACE.removeFrom(((CPhone) contact).phoneNumber);
if (phoneNumbers.contains(phoneNumber)) {
System.out.println("CParty " + party + " has duplicate phone number (" + ((CPhone) contact).phoneNumber + "). Deleting.");
party.deleteContact(contact); // remove dup
} else {
phoneNumbers.add(CharMatcher.WHITESPACE.removeFrom(((CPhone) contact).phoneNumber));
}
}
}
if (contact instanceof CWebsite) {
if ("SKYPE".equals(((CWebsite) contact).webService)) {
String skypeNumber = ((CWebsite) contact).webAddress;
if (skypeNumbers.contains(skypeNumber)) {
System.out.println("CParty " + party + " has duplicate Skype number (" + ((CWebsite) contact).webAddress + "). Deleting.");
party.deleteContact(contact); // remove dup
} else {
skypeNumbers.add(skypeNumber);
}
}
}
}
boolean save = false;
for (String phoneNumber : phoneNumbers) {
if (!skypeNumbers.contains(phoneNumber)) {
CWebsite website = new CWebsite(null, phoneNumber, "SKYPE");
party.addContact(website);
save = true;
}
}
if (save) {
System.out.println("Saving " + party);
WS.Response response = party.save().get();
if (response.getStatus() < 200 || response.getStatus() > 206) {
System.out.println("Failure saving party " + party + ", response " + response.getStatus() + " " + response.getStatusText());
}
else {
System.out.println("Success saving party " + party + ", response " + response.getStatus() + " " + response.getStatusText());
}
}
}
}
});
}
@Test
public void addTwitterLinks() throws InterruptedException {
running(fakeApplication(), new Runnable() {
public void run() {
logger.info("Listing all parties...");
CParties parties = CParty.listAll(5, TimeUnit.SECONDS).get(50l, TimeUnit.SECONDS);
logger.info("Found " + parties.size + " parties, finding and adding Twitter links...");
for (CParty party : parties) {
boolean hasTwitterLink = false;
for (CContact contact : party.contacts) {
if (contact instanceof CWebsite) {
CWebsite website = (CWebsite) contact;
if ("TWITTER".equals(website.webService)) {
logger.info("Skipping " + party + " since it already has a twitter link.");
hasTwitterLink = true;
}
}
}
if (!hasTwitterLink) {
Set<String> twitterUsers = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
for (CContact contact : party.contacts) {
if (contact instanceof CWebsite) {
CWebsite website = (CWebsite) contact;
if ("URL".equals(website.webService) && !website.url.contains("google")) {
System.out.println("Visiting website of " + party.getName() + " at " + website.url);
try {
Document doc = Jsoup.connect(website.url)
.ignoreHttpErrors(true)
.get();
Elements links = doc.select("a[href]");
for (Element link : links) {
String href = link.attr("href");
if (!href.contains("/search")
&& !href.contains("/share")
&& !href.contains("/home")
&& !href.contains("/intent")) {
Matcher matcher = Pattern.compile("(www\\.)?twitter\\.com/(#!/)?@?([^/]*)").matcher(href);
while (matcher.find()) {
String twitterUser = CharMatcher.WHITESPACE.trimFrom(href.substring(matcher.start(3), matcher.end(3)));
if (!"".equals(twitterUser)) {
twitterUsers.add(twitterUser);
}
}
}
}
} catch (IllegalCharsetNameException e) { // see https://github.com/jhy/jsoup/commit/2714d6be6cbe465b522a724c2796ddf74df06482#-P0
logger.info("Illegal charset name for " + website + " of " + party);
} catch (IOException e) {
logger.info("Unable to GET " + website + " of " + party);
}
}
}
}
for (String twitterUser : twitterUsers) {
logger.info("Found twitter user @" + twitterUser + ", adding it to " + party.getName() + " and saving...");
CWebsite twitterLink = new CWebsite(null, twitterUser, "TWITTER");
party.addContact(twitterLink);
WS.Response response = party.save().get();
- if (response.getStatus() != 200 || response.getStatus() != 201) {
+ if (response.getStatus() < 200 || response.getStatus() > 206) {
logger.info("Failure saving party " + party + ", response " + response.getStatusText());
}
}
}
}
}
});
}
}
| true | true | public void addTwitterLinks() throws InterruptedException {
running(fakeApplication(), new Runnable() {
public void run() {
logger.info("Listing all parties...");
CParties parties = CParty.listAll(5, TimeUnit.SECONDS).get(50l, TimeUnit.SECONDS);
logger.info("Found " + parties.size + " parties, finding and adding Twitter links...");
for (CParty party : parties) {
boolean hasTwitterLink = false;
for (CContact contact : party.contacts) {
if (contact instanceof CWebsite) {
CWebsite website = (CWebsite) contact;
if ("TWITTER".equals(website.webService)) {
logger.info("Skipping " + party + " since it already has a twitter link.");
hasTwitterLink = true;
}
}
}
if (!hasTwitterLink) {
Set<String> twitterUsers = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
for (CContact contact : party.contacts) {
if (contact instanceof CWebsite) {
CWebsite website = (CWebsite) contact;
if ("URL".equals(website.webService) && !website.url.contains("google")) {
System.out.println("Visiting website of " + party.getName() + " at " + website.url);
try {
Document doc = Jsoup.connect(website.url)
.ignoreHttpErrors(true)
.get();
Elements links = doc.select("a[href]");
for (Element link : links) {
String href = link.attr("href");
if (!href.contains("/search")
&& !href.contains("/share")
&& !href.contains("/home")
&& !href.contains("/intent")) {
Matcher matcher = Pattern.compile("(www\\.)?twitter\\.com/(#!/)?@?([^/]*)").matcher(href);
while (matcher.find()) {
String twitterUser = CharMatcher.WHITESPACE.trimFrom(href.substring(matcher.start(3), matcher.end(3)));
if (!"".equals(twitterUser)) {
twitterUsers.add(twitterUser);
}
}
}
}
} catch (IllegalCharsetNameException e) { // see https://github.com/jhy/jsoup/commit/2714d6be6cbe465b522a724c2796ddf74df06482#-P0
logger.info("Illegal charset name for " + website + " of " + party);
} catch (IOException e) {
logger.info("Unable to GET " + website + " of " + party);
}
}
}
}
for (String twitterUser : twitterUsers) {
logger.info("Found twitter user @" + twitterUser + ", adding it to " + party.getName() + " and saving...");
CWebsite twitterLink = new CWebsite(null, twitterUser, "TWITTER");
party.addContact(twitterLink);
WS.Response response = party.save().get();
if (response.getStatus() != 200 || response.getStatus() != 201) {
logger.info("Failure saving party " + party + ", response " + response.getStatusText());
}
}
}
}
}
});
}
| public void addTwitterLinks() throws InterruptedException {
running(fakeApplication(), new Runnable() {
public void run() {
logger.info("Listing all parties...");
CParties parties = CParty.listAll(5, TimeUnit.SECONDS).get(50l, TimeUnit.SECONDS);
logger.info("Found " + parties.size + " parties, finding and adding Twitter links...");
for (CParty party : parties) {
boolean hasTwitterLink = false;
for (CContact contact : party.contacts) {
if (contact instanceof CWebsite) {
CWebsite website = (CWebsite) contact;
if ("TWITTER".equals(website.webService)) {
logger.info("Skipping " + party + " since it already has a twitter link.");
hasTwitterLink = true;
}
}
}
if (!hasTwitterLink) {
Set<String> twitterUsers = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
for (CContact contact : party.contacts) {
if (contact instanceof CWebsite) {
CWebsite website = (CWebsite) contact;
if ("URL".equals(website.webService) && !website.url.contains("google")) {
System.out.println("Visiting website of " + party.getName() + " at " + website.url);
try {
Document doc = Jsoup.connect(website.url)
.ignoreHttpErrors(true)
.get();
Elements links = doc.select("a[href]");
for (Element link : links) {
String href = link.attr("href");
if (!href.contains("/search")
&& !href.contains("/share")
&& !href.contains("/home")
&& !href.contains("/intent")) {
Matcher matcher = Pattern.compile("(www\\.)?twitter\\.com/(#!/)?@?([^/]*)").matcher(href);
while (matcher.find()) {
String twitterUser = CharMatcher.WHITESPACE.trimFrom(href.substring(matcher.start(3), matcher.end(3)));
if (!"".equals(twitterUser)) {
twitterUsers.add(twitterUser);
}
}
}
}
} catch (IllegalCharsetNameException e) { // see https://github.com/jhy/jsoup/commit/2714d6be6cbe465b522a724c2796ddf74df06482#-P0
logger.info("Illegal charset name for " + website + " of " + party);
} catch (IOException e) {
logger.info("Unable to GET " + website + " of " + party);
}
}
}
}
for (String twitterUser : twitterUsers) {
logger.info("Found twitter user @" + twitterUser + ", adding it to " + party.getName() + " and saving...");
CWebsite twitterLink = new CWebsite(null, twitterUser, "TWITTER");
party.addContact(twitterLink);
WS.Response response = party.save().get();
if (response.getStatus() < 200 || response.getStatus() > 206) {
logger.info("Failure saving party " + party + ", response " + response.getStatusText());
}
}
}
}
}
});
}
|
diff --git a/jsonhome-jersey/src/test/java/de/otto/jsonhome/JsonHomePropertiesTest.java b/jsonhome-jersey/src/test/java/de/otto/jsonhome/JsonHomePropertiesTest.java
index 45c825c..441ba05 100644
--- a/jsonhome-jersey/src/test/java/de/otto/jsonhome/JsonHomePropertiesTest.java
+++ b/jsonhome-jersey/src/test/java/de/otto/jsonhome/JsonHomePropertiesTest.java
@@ -1,18 +1,17 @@
package de.otto.jsonhome;
import org.testng.annotations.Test;
import java.util.Properties;
import static org.testng.AssertJUnit.assertEquals;
public class JsonHomePropertiesTest {
@Test
public void testReadingProperties() throws Exception {
Properties properties = JsonHomeProperties.getProperties();
assertEquals(3, properties.size());
- assertEquals("de.otto", properties.getProperty("resource.packages"));
}
}
| true | true | public void testReadingProperties() throws Exception {
Properties properties = JsonHomeProperties.getProperties();
assertEquals(3, properties.size());
assertEquals("de.otto", properties.getProperty("resource.packages"));
}
| public void testReadingProperties() throws Exception {
Properties properties = JsonHomeProperties.getProperties();
assertEquals(3, properties.size());
}
|
diff --git a/errai-workspaces/src/main/java/org/jboss/errai/workspaces/client/Workspace.java b/errai-workspaces/src/main/java/org/jboss/errai/workspaces/client/Workspace.java
index 0dbc3a329..0b8fac96d 100644
--- a/errai-workspaces/src/main/java/org/jboss/errai/workspaces/client/Workspace.java
+++ b/errai-workspaces/src/main/java/org/jboss/errai/workspaces/client/Workspace.java
@@ -1,370 +1,370 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 2.1 of
* the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.errai.workspaces.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.ProvidesResize;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.Widget;
import org.gwt.mosaic.ui.client.DeckLayoutPanel;
import org.gwt.mosaic.ui.client.DecoratedTabLayoutPanel;
import org.gwt.mosaic.ui.client.layout.LayoutPanel;
import org.gwt.mosaic.ui.client.util.WidgetHelper;
import org.jboss.errai.bus.client.ErraiBus;
import org.jboss.errai.bus.client.Message;
import org.jboss.errai.bus.client.MessageCallback;
import org.jboss.errai.workspaces.client.api.ResourceFactory;
import org.jboss.errai.workspaces.client.api.Tool;
import org.jboss.errai.workspaces.client.api.WidgetCallback;
import org.jboss.errai.workspaces.client.api.ToolSet;
import org.jboss.errai.workspaces.client.icons.ErraiImageBundle;
import org.jboss.errai.workspaces.client.protocols.LayoutCommands;
import org.jboss.errai.workspaces.client.protocols.LayoutParts;
import org.jboss.errai.workspaces.client.util.LayoutUtil;
import org.jboss.errai.workspaces.client.widgets.WSToolSetLauncher;
import java.util.ArrayList;
import java.util.List;
/**
* Maintains {@link Tool}'s
*
* @author Heiko.Braun <[email protected]>
*/
public class Workspace extends DeckLayoutPanel implements RequiresResize {
public static final String SUBJECT = "Workspace";
private Menu menu;
private static List<ToolSet> toolSets = new ArrayList<ToolSet>();
private static Workspace instance;
public static Workspace createInstance(Menu menu)
{
if(null==instance)
instance = new Workspace(menu);
return instance;
}
public static Workspace getInstance()
{
return instance;
}
private Workspace(Menu menu) {
super();
this.menu = menu;
this.setPadding(5);
ErraiBus.get().subscribe(
Workspace.SUBJECT,
new MessageCallback()
{
public void callback(final Message message)
{
switch(LayoutCommands.valueOf(message.getCommandType()))
{
case ActivateTool:
String toolsetId = message.get(String.class, LayoutParts.TOOLSET);
String toolId = message.get(String.class, LayoutParts.TOOL);
showToolSet(toolsetId, toolId);
// create browser history
String toolToken = toolId!=null ? toolId : "none";
String historyToken = "errai_"+toolsetId+";"+toolToken;
History.newItem(historyToken, false);
break;
}
}
}
);
// handle browser history
History.addValueChangeHandler(
new ValueChangeHandler<String>()
{
public void onValueChange(ValueChangeEvent<String> event)
{
// avoid interference with other history tokens
// example token: errai_Administration;Users.5
String tokenString = event.getValue();
if(tokenString.startsWith("errai_"))
{
String[] tokens = splitHistoryToken(tokenString);
String toolsetId = tokens[0];
String toolId = tokens[1].equals("none") ? null : tokens[1];
showToolSet(toolsetId, toolId);
// correlation id
if(tokens.length>2)
{
String corrId = tokens[3];
// not used at the moment
}
}
}
}
);
}
public static String[] splitHistoryToken(String tokenString)
{
String s = tokenString.substring(6, tokenString.length());
String[] token = s.split(";");
return token;
}
public void addToolSet(ToolSet toolSet) {
// register for lookup, late reference
toolSets.add(toolSet);
// Menu
Widget w = toolSet.getWidget();
String id = "ToolSet_" + toolSet.getToolSetName().replace(" ", "_");
if (w != null)
{
w.getElement().setId(id);
menu.addLauncher(w, toolSet.getToolSetName());
}
else
{
WSToolSetLauncher toolSetLauncher = new WSToolSetLauncher(toolSet.getToolSetName());
for (Tool t : toolSet.getAllProvidedTools()) {
toolSetLauncher.addLink(t.getName(), t);
}
toolSetLauncher.getElement().setId(id);
menu.addLauncher(toolSetLauncher, toolSet.getToolSetName());
}
menu.getStack().layout();
// ToolSet deck
ToolSetDeck deck = createDeck(toolSet);
deck.index = this.getWidgetCount();
this.add(deck);
}
public boolean hasToolSet(String id) {
return findToolSet(id) != null;
}
public void showToolSet(final String id) {
showToolSet(id, null); // opens the default tool
}
public void showToolSet(final String toolSetId, final String toolId)
{
ToolSetDeck deck = findToolSet(toolSetId);
if (null == deck)
throw new IllegalArgumentException("No such toolSet: " + toolSetId);
// select tool
ToolSet selectedToolSet = deck.toolSet;
Tool selectedTool = null;
if (toolId != null) // particular tool
{
for (Tool t : selectedToolSet.getAllProvidedTools()) {
if (toolId.equals(t.getId())) {
selectedTool = t;
break;
}
}
}
else // default tool, the first one
{
Tool[] availableTools = selectedToolSet.getAllProvidedTools();
if (availableTools == null || availableTools.length == 0)
throw new IllegalArgumentException("Empty toolset: " + toolSetId);
selectedTool = availableTools[0];
}
// is it already open?
boolean isOpen = false;
for (int i = 0; i < deck.tabLayout.getWidgetCount(); i++)
{
ToolTabPanel toolTab = (ToolTabPanel) deck.tabLayout.getWidget(i);
if (toolTab.toolId.equals(toolId)) {
isOpen = true;
deck.tabLayout.selectTab(i);
}
}
if (!isOpen) // & selectedTool.multipleAllowed()==false
{
final ToolTabPanel panelTool = new ToolTabPanel(toolSetId, selectedTool);
panelTool.invalidate();
ResourceFactory resourceFactory = GWT.create(ResourceFactory.class);
ErraiImageBundle erraiImageBundle = GWT.create(ErraiImageBundle.class);
ImageResource resource = resourceFactory.createImage(selectedTool.getName()) != null ?
- resourceFactory.createImage(selectedTool.getName()) : erraiImageBundle.questionCube();
+ resourceFactory.createImage(selectedTool.getName()) : erraiImageBundle.application();
deck.tabLayout.add(
panelTool,
AbstractImagePrototype.create(resource).getHTML() + " " + selectedTool.getName(),
true
);
deck.tabLayout.selectTab(
deck.tabLayout.getWidgetCount() - 1
);
DeferredCommand.addCommand(new Command() {
public void execute() {
panelTool.onResize();
}
});
}
// display toolset
this.showWidget(deck.index);
this.layout();
DeferredCommand.addCommand(new Command() {
public void execute() {
menu.toggle(toolSetId);
}
});
}
private ToolSetDeck createDeck(ToolSet toolSet) {
ToolSetDeck deck = new ToolSetDeck(toolSet);
//deck.add(toolSet);
return deck;
}
private ToolSetDeck findToolSet(String id) {
ToolSetDeck match = null;
for (int i = 0; i < this.getWidgetCount(); i++) {
ToolSetDeck deck = (ToolSetDeck) this.getWidget(i);
if (id.equals(deck.toolSet.getToolSetName())) {
match = deck;
break;
}
}
return match;
}
public List<ToolSet> getToolsets()
{
/*List<ToolSetRef> result = new ArrayList<ToolSetRef>(this.getWidgetCount());
for(int i=0; i<this.getWidgetCount(); i++)
{
ToolSetDeck deck = (ToolSetDeck) this.getWidget(i);
ToolSet toolSet = deck.toolSet;
result.add(new ToolSetRef(toolSet.getToolSetName(), editor.getEditorId()));
} */
return toolSets;
}
private class ToolSetDeck extends LayoutPanel implements RequiresResize, ProvidesResize {
ToolSet toolSet;
int index;
DecoratedTabLayoutPanel tabLayout;
public ToolSetDeck(ToolSet toolSet) {
super();
this.toolSet = toolSet;
this.tabLayout = new DecoratedTabLayoutPanel();
this.add(tabLayout);
}
public void onResize() {
setPixelSize(getParent().getOffsetWidth(), getParent().getOffsetHeight());
LayoutUtil.layoutHints(tabLayout);
}
}
class ToolTabPanel extends LayoutPanel implements RequiresResize, ProvidesResize {
String toolId;
String toolsetId;
ToolTabPanel(final String toolsetId, final Tool tool) {
this.toolsetId = toolsetId;
this.toolId = tool.getId();
tool.getWidget(new WidgetCallback()
{
public void onSuccess(Widget instance)
{
String baseRef = toolsetId+";"+toolId;
instance.getElement().setAttribute("baseRef", baseRef); // used by history management & perma links
add(instance);
WidgetHelper.invalidate(instance);
layout();
}
public void onUnavailable()
{
throw new RuntimeException("Failed to load tool: " + tool.getId());
}
});
}
public void onResize() {
setPixelSize(getParent().getOffsetWidth(), getParent().getOffsetHeight());
LayoutUtil.layoutHints(this);
}
}
public void onResize() {
LayoutUtil.layoutHints(this);
}
/*public final class ToolSetRef
{
String title;
String id;
public ToolSetRef(String title, String id)
{
this.title = title;
this.id = id;
}
} */
}
| true | true | public void showToolSet(final String toolSetId, final String toolId)
{
ToolSetDeck deck = findToolSet(toolSetId);
if (null == deck)
throw new IllegalArgumentException("No such toolSet: " + toolSetId);
// select tool
ToolSet selectedToolSet = deck.toolSet;
Tool selectedTool = null;
if (toolId != null) // particular tool
{
for (Tool t : selectedToolSet.getAllProvidedTools()) {
if (toolId.equals(t.getId())) {
selectedTool = t;
break;
}
}
}
else // default tool, the first one
{
Tool[] availableTools = selectedToolSet.getAllProvidedTools();
if (availableTools == null || availableTools.length == 0)
throw new IllegalArgumentException("Empty toolset: " + toolSetId);
selectedTool = availableTools[0];
}
// is it already open?
boolean isOpen = false;
for (int i = 0; i < deck.tabLayout.getWidgetCount(); i++)
{
ToolTabPanel toolTab = (ToolTabPanel) deck.tabLayout.getWidget(i);
if (toolTab.toolId.equals(toolId)) {
isOpen = true;
deck.tabLayout.selectTab(i);
}
}
if (!isOpen) // & selectedTool.multipleAllowed()==false
{
final ToolTabPanel panelTool = new ToolTabPanel(toolSetId, selectedTool);
panelTool.invalidate();
ResourceFactory resourceFactory = GWT.create(ResourceFactory.class);
ErraiImageBundle erraiImageBundle = GWT.create(ErraiImageBundle.class);
ImageResource resource = resourceFactory.createImage(selectedTool.getName()) != null ?
resourceFactory.createImage(selectedTool.getName()) : erraiImageBundle.questionCube();
deck.tabLayout.add(
panelTool,
AbstractImagePrototype.create(resource).getHTML() + " " + selectedTool.getName(),
true
);
deck.tabLayout.selectTab(
deck.tabLayout.getWidgetCount() - 1
);
DeferredCommand.addCommand(new Command() {
public void execute() {
panelTool.onResize();
}
});
}
// display toolset
this.showWidget(deck.index);
this.layout();
DeferredCommand.addCommand(new Command() {
public void execute() {
menu.toggle(toolSetId);
}
});
}
| public void showToolSet(final String toolSetId, final String toolId)
{
ToolSetDeck deck = findToolSet(toolSetId);
if (null == deck)
throw new IllegalArgumentException("No such toolSet: " + toolSetId);
// select tool
ToolSet selectedToolSet = deck.toolSet;
Tool selectedTool = null;
if (toolId != null) // particular tool
{
for (Tool t : selectedToolSet.getAllProvidedTools()) {
if (toolId.equals(t.getId())) {
selectedTool = t;
break;
}
}
}
else // default tool, the first one
{
Tool[] availableTools = selectedToolSet.getAllProvidedTools();
if (availableTools == null || availableTools.length == 0)
throw new IllegalArgumentException("Empty toolset: " + toolSetId);
selectedTool = availableTools[0];
}
// is it already open?
boolean isOpen = false;
for (int i = 0; i < deck.tabLayout.getWidgetCount(); i++)
{
ToolTabPanel toolTab = (ToolTabPanel) deck.tabLayout.getWidget(i);
if (toolTab.toolId.equals(toolId)) {
isOpen = true;
deck.tabLayout.selectTab(i);
}
}
if (!isOpen) // & selectedTool.multipleAllowed()==false
{
final ToolTabPanel panelTool = new ToolTabPanel(toolSetId, selectedTool);
panelTool.invalidate();
ResourceFactory resourceFactory = GWT.create(ResourceFactory.class);
ErraiImageBundle erraiImageBundle = GWT.create(ErraiImageBundle.class);
ImageResource resource = resourceFactory.createImage(selectedTool.getName()) != null ?
resourceFactory.createImage(selectedTool.getName()) : erraiImageBundle.application();
deck.tabLayout.add(
panelTool,
AbstractImagePrototype.create(resource).getHTML() + " " + selectedTool.getName(),
true
);
deck.tabLayout.selectTab(
deck.tabLayout.getWidgetCount() - 1
);
DeferredCommand.addCommand(new Command() {
public void execute() {
panelTool.onResize();
}
});
}
// display toolset
this.showWidget(deck.index);
this.layout();
DeferredCommand.addCommand(new Command() {
public void execute() {
menu.toggle(toolSetId);
}
});
}
|
diff --git a/supervisor/model/Model.java b/supervisor/model/Model.java
index 73f57268..83f4bd53 100644
--- a/supervisor/model/Model.java
+++ b/supervisor/model/Model.java
@@ -1,979 +1,980 @@
/**
* This file is part of VoteBox.
*
* VoteBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* You should have received a copy of the GNU General Public License
* along with VoteBox, found in the root of any distribution or
* repository containing all or part of VoteBox.
*
* THIS SOFTWARE IS PROVIDED BY WILLIAM MARSH RICE UNIVERSITY, HOUSTON,
* TX AND IS PROVIDED 'AS IS' AND WITHOUT ANY EXPRESS, IMPLIED OR
* STATUTORY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, WARRANTIES OF
* ACCURACY, COMPLETENESS, AND NONINFRINGEMENT. THE SOFTWARE USER SHALL
* INDEMNIFY, DEFEND AND HOLD HARMLESS RICE UNIVERSITY AND ITS FACULTY,
* STAFF AND STUDENTS FROM ANY AND ALL CLAIMS, ACTIONS, DAMAGES, LOSSES,
* LIABILITIES, COSTS AND EXPENSES, INCLUDING ATTORNEYS' FEES AND COURT
* COSTS, DIRECTLY OR INDIRECTLY ARISING OUR OF OR IN CONNECTION WITH
* ACCESS OR USE OF THE SOFTWARE.
*/
package supervisor.model;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import javax.swing.Timer;
import edu.uconn.cse.adder.PrivateKey;
import edu.uconn.cse.adder.PublicKey;
import sexpression.ASExpression;
import sexpression.NoMatch;
import sexpression.StringExpression;
import supervisor.model.tallier.ChallengeDelayedTallier;
import supervisor.model.tallier.ChallengeDelayedWithNIZKsTallier;
import supervisor.model.tallier.EncryptedTallier;
import supervisor.model.tallier.EncryptedTallierWithNIZKs;
import supervisor.model.tallier.ITallier;
import supervisor.model.tallier.Tallier;
import votebox.crypto.interop.AdderKeyManipulator;
import votebox.events.*;
import auditorium.AuditoriumCryptoException;
import auditorium.Key;
import auditorium.NetworkException;
import auditorium.IAuditoriumParams;
/**
* The main model of the Supervisor. Contains the status of the machines, and of
* the election in general. Also contains a link to Auditorium, for broadcasting
* (and hearing) messages on the network.
*
* @author cshaw
*/
public class Model {
private TreeSet<AMachine> machines;
private ObservableEvent machinesChangedObs;
private ArrayList<Integer> validPins;
private VoteBoxAuditoriumConnector auditorium;
private int mySerial;
private boolean activated;
private ObservableEvent activatedObs;
private boolean connected;
private ObservableEvent connectedObs;
private boolean pollsOpen;
private ObservableEvent pollsOpenObs;
private int numConnected;
private String keyword;
private String ballotLocation;
private ITallier tallier;
private Timer statusTimer;
private IAuditoriumParams auditoriumParams;
private HashMap<String, ASExpression> bids;
//private Key privateKey = null;
/**
* Equivalent to Model(-1, params);
*
* @param params IAuditoriumParams to use for determining settings on this Supervisor model.
*/
public Model(IAuditoriumParams params){
this(-1, params);
}
/**
* Constructs a new model with the given serial
*
* @param serial serial number to identify as
* @param params parameters to use for configuration purposes
*/
public Model(int serial, IAuditoriumParams params) {
auditoriumParams = params;
if(serial != -1)
this.mySerial = serial;
else
this.mySerial = params.getDefaultSerialNumber();
if(mySerial == -1)
throw new RuntimeException("Expected serial number in configuration file if not on command line");
machines = new TreeSet<AMachine>();
machinesChangedObs = new ObservableEvent();
activatedObs = new ObservableEvent();
connectedObs = new ObservableEvent();
pollsOpenObs = new ObservableEvent();
keyword = "";
ballotLocation = "ballot.zip";
tallier = new Tallier();
bids = new HashMap<String, ASExpression>();
validPins = new ArrayList<Integer>();
statusTimer = new Timer(300000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isConnected()) {
auditorium.announce(getStatus());
}
}
});
}
/**
* Activates this supervisor.<br>
* Formats the activated message (containing the statuses of known
* machines), and labels any unlabeled machines.
*/
public void activate() {
ArrayList<StatusEvent> statuses = new ArrayList<StatusEvent>();
ArrayList<VoteBoxBooth> unlabeled = new ArrayList<VoteBoxBooth>();
int maxlabel = 0;
for (AMachine m : machines) {
if (m.isOnline()) {
IAnnounceEvent s = null;
if (m instanceof SupervisorMachine) {
SupervisorMachine ma = (SupervisorMachine) m;
if (ma.getStatus() == SupervisorMachine.ACTIVE)
s = new SupervisorEvent(0, 0, "active");
else if (ma.getStatus() == SupervisorMachine.INACTIVE)
s = new SupervisorEvent(0, 0, "inactive");
} else if (m instanceof VoteBoxBooth) {
VoteBoxBooth ma = (VoteBoxBooth) m;
if (ma.getStatus() == VoteBoxBooth.READY)
s = new VoteBoxEvent(0, ma.getLabel(), "ready", ma
.getBattery(), ma.getProtectedCount(), ma
.getPublicCount());
else if (ma.getStatus() == VoteBoxBooth.IN_USE)
s = new VoteBoxEvent(0, ma.getLabel(), "in-use", ma
.getBattery(), ma.getProtectedCount(), ma
.getPublicCount());
if (ma.getLabel() == 0)
unlabeled.add(ma);
else if (ma.getLabel() > maxlabel)
maxlabel = ma.getLabel();
}
if (s == null)
throw new IllegalStateException("Unknown machine or status");
statuses.add(new StatusEvent(0, m.getSerial(), s));
}
}
auditorium.announce(new ActivatedEvent(mySerial, statuses));
for (VoteBoxBooth b : unlabeled) {
auditorium.announce(new AssignLabelEvent(mySerial, b.getSerial(),
++maxlabel));
}
if (!pollsOpen)
auditorium.announce(new PollsOpenQEvent(mySerial, keyword));
}
/**
* Authorizes a VoteBox booth
*
* @param node
* the serial number of the booth
* @throws IOException
*/
public void authorize(int node) throws IOException {
byte[] nonce = new byte[256];
for (int i = 0; i < 256; i++)
nonce[i] = (byte) (Math.random() * 256);
File file = new File(ballotLocation);
FileInputStream fin = new FileInputStream(file);
byte[] ballot = new byte[(int) file.length()];
fin.read(ballot);
if(!this.auditoriumParams.getEnableNIZKs()){
auditorium.announce(new AuthorizedToCastEvent(mySerial, node, nonce,
ballot));
}else{
auditorium.announce(new AuthorizedToCastWithNIZKsEvent(mySerial, node,
nonce, ballot,
AdderKeyManipulator.generateFinalPublicKey((PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public"))));
}
}
/**
* Closes the polls
*
* @return the output from the tally
*/
public Map<String, BigInteger> closePolls() {
auditorium
.announce(new PollsClosedEvent(mySerial, new Date().getTime()));
//return tallier.getReport(privateKey);
return tallier.getReport();
}
/**
* Gets the index in the list of machines of the machine with the given
* serial
*
* @param serial
* @return the index
*/
public int getIndexForSerial(int serial) {
int i = 0;
for (AMachine m : machines)
if (m.getSerial() == serial)
return i;
else
++i;
return -1;
}
/**
* Gets today's election keyword (entered at program launch)
*
* @return the keyword
*/
public String getKeyword() {
return keyword;
}
/**
* Gets an AMachine from the list of machines by its serial number
*
* @param serial
* @return the machine
*/
public AMachine getMachineForSerial(int serial) {
for (AMachine m : machines)
if (m.getSerial() == serial)
return m;
return null;
}
/**
* Gets the list of machines, in serial number order
*
* @return the machines
*/
public TreeSet<AMachine> getMachines() {
return machines;
}
/**
* @return this machine's serial
*/
public int getMySerial() {
return mySerial;
}
/**
* @return the number of active connections
*/
public int getNumConnected() {
return numConnected;
}
/**
* @return a SupervisorEvent with this machine's status (used for periodic
* broadcasts)
*/
public SupervisorEvent getStatus() {
SupervisorEvent event;
if (isActivated())
event = new SupervisorEvent(mySerial, new Date().getTime(),
"active");
else
event = new SupervisorEvent(mySerial, new Date().getTime(),
"inactive");
return event;
}
/**
* @return whether this supervisor is active
*/
public boolean isActivated() {
return activated;
}
/**
* @return whether this supervisor is connected to any machines
*/
public boolean isConnected() {
return connected;
}
/**
* @return whether the polls are open
*/
public boolean isPollsOpen() {
return pollsOpen;
}
/**
* Opens the polls.
*/
public void openPolls() {
auditorium.announce(new PollsOpenEvent(mySerial, new Date().getTime(),
keyword));
}
/**
* Sends an override-cancel request to a VoteBox booth
*
* @param node
* the serial number of the booth
*/
public void overrideCancel(int node) {
byte[] nonce = ((VoteBoxBooth) getMachineForSerial(node)).getNonce();
if (nonce == null)
{
System.err.println("ERROR: VoteBox machine has no associated nonce!");
throw new RuntimeException("VoteBox machine has no associated nonce!");
}
auditorium.announce(new OverrideCancelEvent(mySerial, node, nonce));
}
/**
* Sends an override-cast request to a VoteBox booth
*
* @param node
* the serial number of the booth
*/
public void overrideCast(int node) {
byte[] nonce = ((VoteBoxBooth) getMachineForSerial(node)).getNonce();
auditorium.announce(new OverrideCastEvent(mySerial, node, nonce));
}
/**
* Register to be notified when this supervisor's active status changes
*
* @param obs
* the observer
*/
public void registerForActivated(Observer obs) {
activatedObs.addObserver(obs);
}
/**
* Register to be notified when this supervisor's connected status changes
*
* @param obs
* the observer
*/
public void registerForConnected(Observer obs) {
connectedObs.addObserver(obs);
}
/**
* Register to be notified when the list of machines changes
*
* @param obs
* the observer
*/
public void registerForMachinesChanged(Observer obs) {
machinesChangedObs.addObserver(obs);
}
/**
* Register to be notified when the polls open status changes
*
* @param obs
* the observer
*/
public void registerForPollsOpen(Observer obs) {
pollsOpenObs.addObserver(obs);
}
/**
* Sets this supervisor's active status
*
* @param activated
* the activated to set
*/
public void setActivated(boolean activated) {
this.activated = activated;
activatedObs.notifyObservers();
}
/**
* Sets this supervisor's ballot location
*
* @param newLoc
* the ballot location
*/
public void setBallotLocation(String newLoc) {
ballotLocation = newLoc;
}
/**
* Sets this supervisor's connected status
*
* @param connected
* the connected to set
*/
public void setConnected(boolean connected) {
this.connected = connected;
connectedObs.notifyObservers();
}
/**
* Sets the election keyword
*
* @param keyword
* the keyword to set
*/
public void setKeyword(String keyword) {
this.keyword = keyword;
}
/**
* Sets this supervisor's polls open status
*
* @param pollsOpen
* the pollsOpen to set
*/
public void setPollsOpen(boolean pollsOpen) {
this.pollsOpen = pollsOpen;
pollsOpenObs.notifyObservers();
}
/**
* Starts auditorium, registers the event listener, and connects to the
* network.
*/
public void start() {
try {
auditorium = new VoteBoxAuditoriumConnector(mySerial,
auditoriumParams, ActivatedEvent.getMatcher(),
AssignLabelEvent.getMatcher(), AuthorizedToCastEvent.getMatcher(),
CastBallotEvent.getMatcher(), LastPollsOpenEvent.getMatcher(),
OverrideCastConfirmEvent.getMatcher(), PollsClosedEvent.getMatcher(),
PollsOpenEvent.getMatcher(), PollsOpenQEvent.getMatcher(),
SupervisorEvent.getMatcher(), VoteBoxEvent.getMatcher(),
EncryptedCastBallotEvent.getMatcher(), CommitBallotEvent.getMatcher(),
CastCommittedBallotEvent.getMatcher(), ChallengeResponseEvent.getMatcher(),
ChallengeEvent.getMatcher(), EncryptedCastBallotWithNIZKsEvent.getMatcher(),
AuthorizedToCastWithNIZKsEvent.getMatcher(), AdderChallengeEvent.getMatcher(),
PinEnteredEvent.getMatcher(), InvalidPinEvent.getMatcher(),
PollStatusEvent.getMatcher());
} catch (NetworkException e1) {
throw new RuntimeException(e1);
}
auditorium.addListener(new VoteBoxEventListener() {
public void ballotCounted(BallotCountedEvent e){
//NO-OP
}
/**
* Handler for the activated message. Sets all other supervisors
* (including this one, if necessary) to the inactive state. Also
* checks to see if this machine's status is listed, and responds
* with it if not.
*/
public void activated(ActivatedEvent e) {
for (AMachine m : machines) {
if (m instanceof SupervisorMachine) {
if (m.getSerial() == e.getSerial())
m.setStatus(SupervisorMachine.ACTIVE);
else
m.setStatus(SupervisorMachine.INACTIVE);
}
}
if (e.getSerial() == mySerial)
setActivated(true);
else {
setActivated(false);
boolean found = false;
for (StatusEvent ae : e.getStatuses()) {
if (ae.getNode() == mySerial) {
SupervisorEvent se = (SupervisorEvent) ae
.getStatus();
if (!se.getStatus().equals("inactive"))
broadcastStatus();
found = true;
}
}
if (!found) broadcastStatus();
}
}
/**
* Handler for the assign-label message. Sets that machine's label.
*/
public void assignLabel(AssignLabelEvent e) {
AMachine m = getMachineForSerial(e.getNode());
if (m != null) {
m.setLabel(e.getLabel());
machines.remove(m);
machines.add(m);
machinesChangedObs.notifyObservers();
}
}
/**
* Handler for the authorized-to-cast message. Sets the nonce for
* that machine.
*/
public void authorizedToCast(AuthorizedToCastEvent e) {
AMachine m = getMachineForSerial(e.getNode());
if (m != null && m instanceof VoteBoxBooth) {
((VoteBoxBooth) m).setNonce(e.getNonce());
}
}
public void ballotReceived(BallotReceivedEvent e) {
//NO-OP
}
/**
* Handler for the cast-ballot message. Increments the booth's
* public and protected counts, replies with ballot-received, and
* stores the votes in the tallier.
*/
public void castBallot(CastBallotEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
//If we're using the commit-challenge model, then the ballot is already cached and we
// just need to confirm it
if(auditoriumParams.getUseCommitChallengeModel()){
auditorium.announce(new BallotCountedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
tallier.confirmed(e.getNonce());
}else{
auditorium.announce(new BallotReceivedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
//Otheriwse, we need to count the whole thing.
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce());
}
}
}
/**
* Handler for a joined event. When a new machine joins, check and
* see if it exists, and set it to online if so. Also increment the
* number of connections.
*/
public void joined(JoinEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null) {
m.setOnline(true);
}
numConnected++;
setConnected(true);
machinesChangedObs.notifyObservers();
}
/**
* Handler for the last-polls-open message. If the keywords match,
* set the polls to open (without sending a message).
*/
public void lastPollsOpen(LastPollsOpenEvent e) {
PollsOpenEvent e2 = e.getPollsOpenMsg();
if (e2.getKeyword().equals(keyword))
setPollsOpen(true);
}
/**
* Handler for a left event. Set the machine to offline, and
* decrement the number of connections. If we are no longer
* connected to any machines, assume we're offline and deactivate.<br>
* The supervisor needs to deactivate when it goes offline so that
* when it comes back on, it needs to be activated again so it can
* get a fresh list of machines and their statuses. Also, that way
* you cannot have two machines activate separately and then join
* the network, giving you two active supervisors.
*/
public void left(LeaveEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null) {
m.setOnline(false);
}
numConnected--;
if (numConnected == 0) {
setConnected(false);
setActivated(false);
}
machinesChangedObs.notifyObservers();
}
public void overrideCancel(OverrideCancelEvent e) {
// NO-OP
}
public void overrideCancelConfirm(OverrideCancelConfirmEvent e) {
// NO-OP
}
public void overrideCancelDeny(OverrideCancelDenyEvent e) {
// NO-OP
}
public void overrideCast(OverrideCastEvent e) {
// NO-OP
}
/**
* Handler for the override-cast-confirm event. Similar to
* cast-ballot, but no received reply is sent.
*/
public void overrideCastConfirm(OverrideCastConfirmEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
tallier.recordVotes(e.getBallot(), StringExpression.makeString(e.getNonce()));
}
}
public void overrideCastDeny(OverrideCastDenyEvent e) {
// NO-OP
}
/**
* Handler for the polls-closed event. Sets the polls to closed.
*/
public void pollsClosed(PollsClosedEvent e) {
setPollsOpen(false);
}
/**
* Handler for the polls-open event. Sets the polls to open, and
* gets a fresh tallier.
* @throws AuditoriumCryptoException
*/
public void pollsOpen(PollsOpenEvent e){
if(auditoriumParams.getUseCommitChallengeModel()){
try {
if(!auditoriumParams.getEnableNIZKs()){
//Loading privateKey well in advance so the whole affair is "fail-fast"
Key privateKey = auditoriumParams.getKeyStore().loadKey("private");
tallier = new ChallengeDelayedTallier(privateKey);
}else{
//Loading privateKey well in advance so the whole affair is "fail-fast"
PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private");
PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public");
tallier = new ChallengeDelayedWithNIZKsTallier(publicKey, privateKey);
}//if
} catch (AuditoriumCryptoException e1) {
System.err.println("Crypto error encountered: "+e1.getMessage());
e1.printStackTrace();
}
}else{
//If Encryption is not enabled, use a vanilla tallier
if(!auditoriumParams.getCastBallotEncryptionEnabled()){
if(auditoriumParams.getEnableNIZKs())
throw new RuntimeException("Encryption must be enabled to use NIZKs");
//privateKey = null;
tallier = new Tallier();
}else{
//Otherwise, grab the private key and allocate an encrypted tallier
try{
if(!auditoriumParams.getEnableNIZKs()){
//Loading privateKey well in advance so the whole affair is "fail-fast"
Key privateKey = auditoriumParams.getKeyStore().loadKey("private");
tallier = new EncryptedTallier(privateKey);
}else{
//Loading privateKey well in advance so the whole affair is "fail-fast"
PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private");
PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public");
tallier = new EncryptedTallierWithNIZKs(publicKey, privateKey);
}//if
}catch(AuditoriumCryptoException e1){
System.err.println("Crypto error encountered: "+e1.getMessage());
e1.printStackTrace();
}//catch
}//if
}//if
setPollsOpen(true);
}
/**
* Handler for the polls-open? event. Searches the machine's log,
* and replies with a last-polls-open message if an appropriate
* polls-open message is found.
*/
public void pollsOpenQ(PollsOpenQEvent e) {
if (e.getSerial() != mySerial) {
// TODO: Search the log and extract an appropriate
// polls-open message
ASExpression res = null;
if (res != null && res != NoMatch.SINGLETON) {
VoteBoxEventMatcher matcher = new VoteBoxEventMatcher(
PollsOpenEvent.getMatcher());
PollsOpenEvent event = (PollsOpenEvent) matcher.match(
0, res);
if (event != null
&& event.getKeyword().equals(e.getKeyword()))
auditorium.announce(new LastPollsOpenEvent(
mySerial, event));
}
}
}
/**
* Handler for a ballotscanner (status) event. Adds the machine if it
* hasn't been seen, and updates its status if it has.
*/
public void ballotscanner(BallotScannerEvent e) {
//NO-OP until scanner is further implemented
//TODO Finish this method
}
/**
* Handler for a supervisor (status) event. Adds the machine if it
* hasn't been seen, and updates its status if it has.
*/
public void supervisor(SupervisorEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && !(m instanceof SupervisorMachine))
throw new IllegalStateException(
"Machine "
+ e.getSerial()
+ " is not a supervisor, but broadcasted supervisor message");
if (m == null) {
m = new SupervisorMachine(e.getSerial(),
e.getSerial() == mySerial);
machines.add(m);
machinesChangedObs.notifyObservers();
}
SupervisorMachine sup = (SupervisorMachine) m;
if (e.getStatus().equals("active")) {
sup.setStatus(SupervisorMachine.ACTIVE);
if (e.getSerial() != mySerial)
setActivated(false);
} else if (e.getStatus().equals("inactive"))
sup.setStatus(SupervisorMachine.INACTIVE);
else
throw new IllegalStateException(
"Invalid Supervisor Status: " + e.getStatus());
sup.setOnline(true);
}
/**
* Handler for a votebox (status) event. Adds the machine if it
* hasn't been seen, or updates the status if it has. Also, if the
* booth is unlabeled and this is the active supervisor, labels the
* booth with its previous label if known, or the next available
* number.
*/
public void votebox(VoteBoxEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && !(m instanceof VoteBoxBooth))
throw new IllegalStateException(
"Machine "
+ e.getSerial()
+ " is not a booth, but broadcasted votebox message");
if (m == null) {
m = new VoteBoxBooth(e.getSerial());
machines.add(m);
machinesChangedObs.notifyObservers();
}
VoteBoxBooth booth = (VoteBoxBooth) m;
if (e.getStatus().equals("ready"))
booth.setStatus(VoteBoxBooth.READY);
else if (e.getStatus().equals("in-use"))
booth.setStatus(VoteBoxBooth.IN_USE);
else
throw new IllegalStateException("Invalid VoteBox Status: "
+ e.getStatus());
booth.setBattery(e.getBattery());
booth.setProtectedCount(e.getProtectedCount());
booth.setPublicCount(e.getPublicCount());
booth.setOnline(true);
//Check to see if this votebox has a conflicting label
//TODO Apparently this doesn't do what it says it does....
if (e.getLabel() > 0){
for(AMachine machine : machines){
if(machine.getLabel() == e.getLabel() && machine != m){
//If there is a conflict, relabel this (the event generator) machine.
int maxlabel = 0;
for(AMachine ma : machines){
if(ma instanceof VoteBoxBooth)
maxlabel = (int)Math.max(maxlabel, ma.getLabel());
}//for
auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1));
return;
}
}
}//if
if (e.getLabel() > 0)
booth.setLabel(e.getLabel());
else {
if (activated) {
if (booth.getLabel() > 0)
auditorium.announce(new AssignLabelEvent(mySerial, e
.getSerial(), booth.getLabel()));
else {
int maxlabel = 0;
for (AMachine ma : machines) {
if (ma instanceof VoteBoxBooth
&& ((VoteBoxBooth) ma).getLabel() > maxlabel)
maxlabel = ((VoteBoxBooth) ma).getLabel();
}
auditorium.announce(new AssignLabelEvent(mySerial, e
.getSerial(), maxlabel + 1));
}
auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 ));
}
}
}
/**
* Indicate to the tallier that the vote in question is being challenged,
* and as such should be excluded from the final tally.
*/
public void challengeResponse(ChallengeResponseEvent e) {
//NO-OP
}
/**
* Indicate to the tallier that the vote in question is being challenged,
* and as such should be excluded from the final tally.
*/
public void challenge(ChallengeEvent e) {
System.out.println("Received challenge: "+e);
tallier.challenged(e.getNonce());
auditorium.announce(new ChallengeResponseEvent(mySerial,
e.getSerial(), e.getNonce()));
}
/**
* Record the vote received in the commit event.
* It should not yet be tallied.
*/
public void commitBallot(CommitBallotEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
auditorium.announce(new BallotReceivedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce());
String bid = e.getBID().toString();
bids.put(bid, e.getNonce());
}
}
public void ballotScanned(BallotScannedEvent e) {
String bid = e.getBID();
int serial = e.getSerial();
if (bids.containsKey(bid)) {
ASExpression nonce = bids.get(bid);
BallotStore.castBallot(e.getBID(), nonce);
// used to be in voteBox registerForCommit listener.
auditorium.announce(new CastCommittedBallotEvent(serial, nonce));
// that should trigger my own castBallot listener.
} else {
throw new IllegalStateException("got ballot scanned message for invalid BID");
}
+ //TODO checking to make sure I branched successfully
}
public void pinEntered(PinEnteredEvent e){
if(isPollsOpen()) {
if(validPins.contains(e.getPin())) {
validPins.remove((Integer)e.getPin());
try {
authorize(e.getSerial());
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
}
else {
auditorium.announce(new InvalidPinEvent(mySerial, e.getNonce()));
}
}
}
public void invalidPin(InvalidPinEvent e) {}
public void pollStatus(PollStatusEvent pollStatusEvent) {
pollsOpen = pollStatusEvent.getPollStatus()==1;
}
});
try {
auditorium.connect();
auditorium.announce(getStatus());
} catch (NetworkException e1) {
//NetworkException represents a recoverable error
// so just note it and continue
System.out.println("Recoverable error occured: "+e1.getMessage());
e1.printStackTrace(System.err);
}
statusTimer.start();
}
/**
* Broadcasts this supervisor's status, and resets the status timer
*/
public void broadcastStatus() {
auditorium.announce(getStatus());
statusTimer.restart();
}
public VoteBoxAuditoriumConnector getAuditoriumConnector() {
return auditorium;
}
/**
* A method for retrieving the parameters of the election
*/
public IAuditoriumParams getParams(){
return auditoriumParams;
}
/**
* A method that will generate a random pin for the voter to enter into his votebox machine
*/
public int generatePin(){
Random rand = (new Random());
int pin = rand.nextInt(10000);
while(validPins.contains(pin))
pin = rand.nextInt(10000);
validPins.add(pin);
return pin;
}
}
| true | true | public void start() {
try {
auditorium = new VoteBoxAuditoriumConnector(mySerial,
auditoriumParams, ActivatedEvent.getMatcher(),
AssignLabelEvent.getMatcher(), AuthorizedToCastEvent.getMatcher(),
CastBallotEvent.getMatcher(), LastPollsOpenEvent.getMatcher(),
OverrideCastConfirmEvent.getMatcher(), PollsClosedEvent.getMatcher(),
PollsOpenEvent.getMatcher(), PollsOpenQEvent.getMatcher(),
SupervisorEvent.getMatcher(), VoteBoxEvent.getMatcher(),
EncryptedCastBallotEvent.getMatcher(), CommitBallotEvent.getMatcher(),
CastCommittedBallotEvent.getMatcher(), ChallengeResponseEvent.getMatcher(),
ChallengeEvent.getMatcher(), EncryptedCastBallotWithNIZKsEvent.getMatcher(),
AuthorizedToCastWithNIZKsEvent.getMatcher(), AdderChallengeEvent.getMatcher(),
PinEnteredEvent.getMatcher(), InvalidPinEvent.getMatcher(),
PollStatusEvent.getMatcher());
} catch (NetworkException e1) {
throw new RuntimeException(e1);
}
auditorium.addListener(new VoteBoxEventListener() {
public void ballotCounted(BallotCountedEvent e){
//NO-OP
}
/**
* Handler for the activated message. Sets all other supervisors
* (including this one, if necessary) to the inactive state. Also
* checks to see if this machine's status is listed, and responds
* with it if not.
*/
public void activated(ActivatedEvent e) {
for (AMachine m : machines) {
if (m instanceof SupervisorMachine) {
if (m.getSerial() == e.getSerial())
m.setStatus(SupervisorMachine.ACTIVE);
else
m.setStatus(SupervisorMachine.INACTIVE);
}
}
if (e.getSerial() == mySerial)
setActivated(true);
else {
setActivated(false);
boolean found = false;
for (StatusEvent ae : e.getStatuses()) {
if (ae.getNode() == mySerial) {
SupervisorEvent se = (SupervisorEvent) ae
.getStatus();
if (!se.getStatus().equals("inactive"))
broadcastStatus();
found = true;
}
}
if (!found) broadcastStatus();
}
}
/**
* Handler for the assign-label message. Sets that machine's label.
*/
public void assignLabel(AssignLabelEvent e) {
AMachine m = getMachineForSerial(e.getNode());
if (m != null) {
m.setLabel(e.getLabel());
machines.remove(m);
machines.add(m);
machinesChangedObs.notifyObservers();
}
}
/**
* Handler for the authorized-to-cast message. Sets the nonce for
* that machine.
*/
public void authorizedToCast(AuthorizedToCastEvent e) {
AMachine m = getMachineForSerial(e.getNode());
if (m != null && m instanceof VoteBoxBooth) {
((VoteBoxBooth) m).setNonce(e.getNonce());
}
}
public void ballotReceived(BallotReceivedEvent e) {
//NO-OP
}
/**
* Handler for the cast-ballot message. Increments the booth's
* public and protected counts, replies with ballot-received, and
* stores the votes in the tallier.
*/
public void castBallot(CastBallotEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
//If we're using the commit-challenge model, then the ballot is already cached and we
// just need to confirm it
if(auditoriumParams.getUseCommitChallengeModel()){
auditorium.announce(new BallotCountedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
tallier.confirmed(e.getNonce());
}else{
auditorium.announce(new BallotReceivedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
//Otheriwse, we need to count the whole thing.
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce());
}
}
}
/**
* Handler for a joined event. When a new machine joins, check and
* see if it exists, and set it to online if so. Also increment the
* number of connections.
*/
public void joined(JoinEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null) {
m.setOnline(true);
}
numConnected++;
setConnected(true);
machinesChangedObs.notifyObservers();
}
/**
* Handler for the last-polls-open message. If the keywords match,
* set the polls to open (without sending a message).
*/
public void lastPollsOpen(LastPollsOpenEvent e) {
PollsOpenEvent e2 = e.getPollsOpenMsg();
if (e2.getKeyword().equals(keyword))
setPollsOpen(true);
}
/**
* Handler for a left event. Set the machine to offline, and
* decrement the number of connections. If we are no longer
* connected to any machines, assume we're offline and deactivate.<br>
* The supervisor needs to deactivate when it goes offline so that
* when it comes back on, it needs to be activated again so it can
* get a fresh list of machines and their statuses. Also, that way
* you cannot have two machines activate separately and then join
* the network, giving you two active supervisors.
*/
public void left(LeaveEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null) {
m.setOnline(false);
}
numConnected--;
if (numConnected == 0) {
setConnected(false);
setActivated(false);
}
machinesChangedObs.notifyObservers();
}
public void overrideCancel(OverrideCancelEvent e) {
// NO-OP
}
public void overrideCancelConfirm(OverrideCancelConfirmEvent e) {
// NO-OP
}
public void overrideCancelDeny(OverrideCancelDenyEvent e) {
// NO-OP
}
public void overrideCast(OverrideCastEvent e) {
// NO-OP
}
/**
* Handler for the override-cast-confirm event. Similar to
* cast-ballot, but no received reply is sent.
*/
public void overrideCastConfirm(OverrideCastConfirmEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
tallier.recordVotes(e.getBallot(), StringExpression.makeString(e.getNonce()));
}
}
public void overrideCastDeny(OverrideCastDenyEvent e) {
// NO-OP
}
/**
* Handler for the polls-closed event. Sets the polls to closed.
*/
public void pollsClosed(PollsClosedEvent e) {
setPollsOpen(false);
}
/**
* Handler for the polls-open event. Sets the polls to open, and
* gets a fresh tallier.
* @throws AuditoriumCryptoException
*/
public void pollsOpen(PollsOpenEvent e){
if(auditoriumParams.getUseCommitChallengeModel()){
try {
if(!auditoriumParams.getEnableNIZKs()){
//Loading privateKey well in advance so the whole affair is "fail-fast"
Key privateKey = auditoriumParams.getKeyStore().loadKey("private");
tallier = new ChallengeDelayedTallier(privateKey);
}else{
//Loading privateKey well in advance so the whole affair is "fail-fast"
PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private");
PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public");
tallier = new ChallengeDelayedWithNIZKsTallier(publicKey, privateKey);
}//if
} catch (AuditoriumCryptoException e1) {
System.err.println("Crypto error encountered: "+e1.getMessage());
e1.printStackTrace();
}
}else{
//If Encryption is not enabled, use a vanilla tallier
if(!auditoriumParams.getCastBallotEncryptionEnabled()){
if(auditoriumParams.getEnableNIZKs())
throw new RuntimeException("Encryption must be enabled to use NIZKs");
//privateKey = null;
tallier = new Tallier();
}else{
//Otherwise, grab the private key and allocate an encrypted tallier
try{
if(!auditoriumParams.getEnableNIZKs()){
//Loading privateKey well in advance so the whole affair is "fail-fast"
Key privateKey = auditoriumParams.getKeyStore().loadKey("private");
tallier = new EncryptedTallier(privateKey);
}else{
//Loading privateKey well in advance so the whole affair is "fail-fast"
PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private");
PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public");
tallier = new EncryptedTallierWithNIZKs(publicKey, privateKey);
}//if
}catch(AuditoriumCryptoException e1){
System.err.println("Crypto error encountered: "+e1.getMessage());
e1.printStackTrace();
}//catch
}//if
}//if
setPollsOpen(true);
}
/**
* Handler for the polls-open? event. Searches the machine's log,
* and replies with a last-polls-open message if an appropriate
* polls-open message is found.
*/
public void pollsOpenQ(PollsOpenQEvent e) {
if (e.getSerial() != mySerial) {
// TODO: Search the log and extract an appropriate
// polls-open message
ASExpression res = null;
if (res != null && res != NoMatch.SINGLETON) {
VoteBoxEventMatcher matcher = new VoteBoxEventMatcher(
PollsOpenEvent.getMatcher());
PollsOpenEvent event = (PollsOpenEvent) matcher.match(
0, res);
if (event != null
&& event.getKeyword().equals(e.getKeyword()))
auditorium.announce(new LastPollsOpenEvent(
mySerial, event));
}
}
}
/**
* Handler for a ballotscanner (status) event. Adds the machine if it
* hasn't been seen, and updates its status if it has.
*/
public void ballotscanner(BallotScannerEvent e) {
//NO-OP until scanner is further implemented
//TODO Finish this method
}
/**
* Handler for a supervisor (status) event. Adds the machine if it
* hasn't been seen, and updates its status if it has.
*/
public void supervisor(SupervisorEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && !(m instanceof SupervisorMachine))
throw new IllegalStateException(
"Machine "
+ e.getSerial()
+ " is not a supervisor, but broadcasted supervisor message");
if (m == null) {
m = new SupervisorMachine(e.getSerial(),
e.getSerial() == mySerial);
machines.add(m);
machinesChangedObs.notifyObservers();
}
SupervisorMachine sup = (SupervisorMachine) m;
if (e.getStatus().equals("active")) {
sup.setStatus(SupervisorMachine.ACTIVE);
if (e.getSerial() != mySerial)
setActivated(false);
} else if (e.getStatus().equals("inactive"))
sup.setStatus(SupervisorMachine.INACTIVE);
else
throw new IllegalStateException(
"Invalid Supervisor Status: " + e.getStatus());
sup.setOnline(true);
}
/**
* Handler for a votebox (status) event. Adds the machine if it
* hasn't been seen, or updates the status if it has. Also, if the
* booth is unlabeled and this is the active supervisor, labels the
* booth with its previous label if known, or the next available
* number.
*/
public void votebox(VoteBoxEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && !(m instanceof VoteBoxBooth))
throw new IllegalStateException(
"Machine "
+ e.getSerial()
+ " is not a booth, but broadcasted votebox message");
if (m == null) {
m = new VoteBoxBooth(e.getSerial());
machines.add(m);
machinesChangedObs.notifyObservers();
}
VoteBoxBooth booth = (VoteBoxBooth) m;
if (e.getStatus().equals("ready"))
booth.setStatus(VoteBoxBooth.READY);
else if (e.getStatus().equals("in-use"))
booth.setStatus(VoteBoxBooth.IN_USE);
else
throw new IllegalStateException("Invalid VoteBox Status: "
+ e.getStatus());
booth.setBattery(e.getBattery());
booth.setProtectedCount(e.getProtectedCount());
booth.setPublicCount(e.getPublicCount());
booth.setOnline(true);
//Check to see if this votebox has a conflicting label
//TODO Apparently this doesn't do what it says it does....
if (e.getLabel() > 0){
for(AMachine machine : machines){
if(machine.getLabel() == e.getLabel() && machine != m){
//If there is a conflict, relabel this (the event generator) machine.
int maxlabel = 0;
for(AMachine ma : machines){
if(ma instanceof VoteBoxBooth)
maxlabel = (int)Math.max(maxlabel, ma.getLabel());
}//for
auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1));
return;
}
}
}//if
if (e.getLabel() > 0)
booth.setLabel(e.getLabel());
else {
if (activated) {
if (booth.getLabel() > 0)
auditorium.announce(new AssignLabelEvent(mySerial, e
.getSerial(), booth.getLabel()));
else {
int maxlabel = 0;
for (AMachine ma : machines) {
if (ma instanceof VoteBoxBooth
&& ((VoteBoxBooth) ma).getLabel() > maxlabel)
maxlabel = ((VoteBoxBooth) ma).getLabel();
}
auditorium.announce(new AssignLabelEvent(mySerial, e
.getSerial(), maxlabel + 1));
}
auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 ));
}
}
}
/**
* Indicate to the tallier that the vote in question is being challenged,
* and as such should be excluded from the final tally.
*/
public void challengeResponse(ChallengeResponseEvent e) {
//NO-OP
}
/**
* Indicate to the tallier that the vote in question is being challenged,
* and as such should be excluded from the final tally.
*/
public void challenge(ChallengeEvent e) {
System.out.println("Received challenge: "+e);
tallier.challenged(e.getNonce());
auditorium.announce(new ChallengeResponseEvent(mySerial,
e.getSerial(), e.getNonce()));
}
/**
* Record the vote received in the commit event.
* It should not yet be tallied.
*/
public void commitBallot(CommitBallotEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
auditorium.announce(new BallotReceivedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce());
String bid = e.getBID().toString();
bids.put(bid, e.getNonce());
}
}
public void ballotScanned(BallotScannedEvent e) {
String bid = e.getBID();
int serial = e.getSerial();
if (bids.containsKey(bid)) {
ASExpression nonce = bids.get(bid);
BallotStore.castBallot(e.getBID(), nonce);
// used to be in voteBox registerForCommit listener.
auditorium.announce(new CastCommittedBallotEvent(serial, nonce));
// that should trigger my own castBallot listener.
} else {
throw new IllegalStateException("got ballot scanned message for invalid BID");
}
}
public void pinEntered(PinEnteredEvent e){
if(isPollsOpen()) {
if(validPins.contains(e.getPin())) {
validPins.remove((Integer)e.getPin());
try {
authorize(e.getSerial());
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
}
else {
auditorium.announce(new InvalidPinEvent(mySerial, e.getNonce()));
}
}
}
public void invalidPin(InvalidPinEvent e) {}
public void pollStatus(PollStatusEvent pollStatusEvent) {
pollsOpen = pollStatusEvent.getPollStatus()==1;
}
});
try {
auditorium.connect();
auditorium.announce(getStatus());
} catch (NetworkException e1) {
//NetworkException represents a recoverable error
// so just note it and continue
System.out.println("Recoverable error occured: "+e1.getMessage());
e1.printStackTrace(System.err);
}
statusTimer.start();
}
| public void start() {
try {
auditorium = new VoteBoxAuditoriumConnector(mySerial,
auditoriumParams, ActivatedEvent.getMatcher(),
AssignLabelEvent.getMatcher(), AuthorizedToCastEvent.getMatcher(),
CastBallotEvent.getMatcher(), LastPollsOpenEvent.getMatcher(),
OverrideCastConfirmEvent.getMatcher(), PollsClosedEvent.getMatcher(),
PollsOpenEvent.getMatcher(), PollsOpenQEvent.getMatcher(),
SupervisorEvent.getMatcher(), VoteBoxEvent.getMatcher(),
EncryptedCastBallotEvent.getMatcher(), CommitBallotEvent.getMatcher(),
CastCommittedBallotEvent.getMatcher(), ChallengeResponseEvent.getMatcher(),
ChallengeEvent.getMatcher(), EncryptedCastBallotWithNIZKsEvent.getMatcher(),
AuthorizedToCastWithNIZKsEvent.getMatcher(), AdderChallengeEvent.getMatcher(),
PinEnteredEvent.getMatcher(), InvalidPinEvent.getMatcher(),
PollStatusEvent.getMatcher());
} catch (NetworkException e1) {
throw new RuntimeException(e1);
}
auditorium.addListener(new VoteBoxEventListener() {
public void ballotCounted(BallotCountedEvent e){
//NO-OP
}
/**
* Handler for the activated message. Sets all other supervisors
* (including this one, if necessary) to the inactive state. Also
* checks to see if this machine's status is listed, and responds
* with it if not.
*/
public void activated(ActivatedEvent e) {
for (AMachine m : machines) {
if (m instanceof SupervisorMachine) {
if (m.getSerial() == e.getSerial())
m.setStatus(SupervisorMachine.ACTIVE);
else
m.setStatus(SupervisorMachine.INACTIVE);
}
}
if (e.getSerial() == mySerial)
setActivated(true);
else {
setActivated(false);
boolean found = false;
for (StatusEvent ae : e.getStatuses()) {
if (ae.getNode() == mySerial) {
SupervisorEvent se = (SupervisorEvent) ae
.getStatus();
if (!se.getStatus().equals("inactive"))
broadcastStatus();
found = true;
}
}
if (!found) broadcastStatus();
}
}
/**
* Handler for the assign-label message. Sets that machine's label.
*/
public void assignLabel(AssignLabelEvent e) {
AMachine m = getMachineForSerial(e.getNode());
if (m != null) {
m.setLabel(e.getLabel());
machines.remove(m);
machines.add(m);
machinesChangedObs.notifyObservers();
}
}
/**
* Handler for the authorized-to-cast message. Sets the nonce for
* that machine.
*/
public void authorizedToCast(AuthorizedToCastEvent e) {
AMachine m = getMachineForSerial(e.getNode());
if (m != null && m instanceof VoteBoxBooth) {
((VoteBoxBooth) m).setNonce(e.getNonce());
}
}
public void ballotReceived(BallotReceivedEvent e) {
//NO-OP
}
/**
* Handler for the cast-ballot message. Increments the booth's
* public and protected counts, replies with ballot-received, and
* stores the votes in the tallier.
*/
public void castBallot(CastBallotEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
//If we're using the commit-challenge model, then the ballot is already cached and we
// just need to confirm it
if(auditoriumParams.getUseCommitChallengeModel()){
auditorium.announce(new BallotCountedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
tallier.confirmed(e.getNonce());
}else{
auditorium.announce(new BallotReceivedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
//Otheriwse, we need to count the whole thing.
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce());
}
}
}
/**
* Handler for a joined event. When a new machine joins, check and
* see if it exists, and set it to online if so. Also increment the
* number of connections.
*/
public void joined(JoinEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null) {
m.setOnline(true);
}
numConnected++;
setConnected(true);
machinesChangedObs.notifyObservers();
}
/**
* Handler for the last-polls-open message. If the keywords match,
* set the polls to open (without sending a message).
*/
public void lastPollsOpen(LastPollsOpenEvent e) {
PollsOpenEvent e2 = e.getPollsOpenMsg();
if (e2.getKeyword().equals(keyword))
setPollsOpen(true);
}
/**
* Handler for a left event. Set the machine to offline, and
* decrement the number of connections. If we are no longer
* connected to any machines, assume we're offline and deactivate.<br>
* The supervisor needs to deactivate when it goes offline so that
* when it comes back on, it needs to be activated again so it can
* get a fresh list of machines and their statuses. Also, that way
* you cannot have two machines activate separately and then join
* the network, giving you two active supervisors.
*/
public void left(LeaveEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null) {
m.setOnline(false);
}
numConnected--;
if (numConnected == 0) {
setConnected(false);
setActivated(false);
}
machinesChangedObs.notifyObservers();
}
public void overrideCancel(OverrideCancelEvent e) {
// NO-OP
}
public void overrideCancelConfirm(OverrideCancelConfirmEvent e) {
// NO-OP
}
public void overrideCancelDeny(OverrideCancelDenyEvent e) {
// NO-OP
}
public void overrideCast(OverrideCastEvent e) {
// NO-OP
}
/**
* Handler for the override-cast-confirm event. Similar to
* cast-ballot, but no received reply is sent.
*/
public void overrideCastConfirm(OverrideCastConfirmEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
tallier.recordVotes(e.getBallot(), StringExpression.makeString(e.getNonce()));
}
}
public void overrideCastDeny(OverrideCastDenyEvent e) {
// NO-OP
}
/**
* Handler for the polls-closed event. Sets the polls to closed.
*/
public void pollsClosed(PollsClosedEvent e) {
setPollsOpen(false);
}
/**
* Handler for the polls-open event. Sets the polls to open, and
* gets a fresh tallier.
* @throws AuditoriumCryptoException
*/
public void pollsOpen(PollsOpenEvent e){
if(auditoriumParams.getUseCommitChallengeModel()){
try {
if(!auditoriumParams.getEnableNIZKs()){
//Loading privateKey well in advance so the whole affair is "fail-fast"
Key privateKey = auditoriumParams.getKeyStore().loadKey("private");
tallier = new ChallengeDelayedTallier(privateKey);
}else{
//Loading privateKey well in advance so the whole affair is "fail-fast"
PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private");
PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public");
tallier = new ChallengeDelayedWithNIZKsTallier(publicKey, privateKey);
}//if
} catch (AuditoriumCryptoException e1) {
System.err.println("Crypto error encountered: "+e1.getMessage());
e1.printStackTrace();
}
}else{
//If Encryption is not enabled, use a vanilla tallier
if(!auditoriumParams.getCastBallotEncryptionEnabled()){
if(auditoriumParams.getEnableNIZKs())
throw new RuntimeException("Encryption must be enabled to use NIZKs");
//privateKey = null;
tallier = new Tallier();
}else{
//Otherwise, grab the private key and allocate an encrypted tallier
try{
if(!auditoriumParams.getEnableNIZKs()){
//Loading privateKey well in advance so the whole affair is "fail-fast"
Key privateKey = auditoriumParams.getKeyStore().loadKey("private");
tallier = new EncryptedTallier(privateKey);
}else{
//Loading privateKey well in advance so the whole affair is "fail-fast"
PrivateKey privateKey = (PrivateKey)auditoriumParams.getKeyStore().loadAdderKey("private");
PublicKey publicKey = (PublicKey)auditoriumParams.getKeyStore().loadAdderKey("public");
tallier = new EncryptedTallierWithNIZKs(publicKey, privateKey);
}//if
}catch(AuditoriumCryptoException e1){
System.err.println("Crypto error encountered: "+e1.getMessage());
e1.printStackTrace();
}//catch
}//if
}//if
setPollsOpen(true);
}
/**
* Handler for the polls-open? event. Searches the machine's log,
* and replies with a last-polls-open message if an appropriate
* polls-open message is found.
*/
public void pollsOpenQ(PollsOpenQEvent e) {
if (e.getSerial() != mySerial) {
// TODO: Search the log and extract an appropriate
// polls-open message
ASExpression res = null;
if (res != null && res != NoMatch.SINGLETON) {
VoteBoxEventMatcher matcher = new VoteBoxEventMatcher(
PollsOpenEvent.getMatcher());
PollsOpenEvent event = (PollsOpenEvent) matcher.match(
0, res);
if (event != null
&& event.getKeyword().equals(e.getKeyword()))
auditorium.announce(new LastPollsOpenEvent(
mySerial, event));
}
}
}
/**
* Handler for a ballotscanner (status) event. Adds the machine if it
* hasn't been seen, and updates its status if it has.
*/
public void ballotscanner(BallotScannerEvent e) {
//NO-OP until scanner is further implemented
//TODO Finish this method
}
/**
* Handler for a supervisor (status) event. Adds the machine if it
* hasn't been seen, and updates its status if it has.
*/
public void supervisor(SupervisorEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && !(m instanceof SupervisorMachine))
throw new IllegalStateException(
"Machine "
+ e.getSerial()
+ " is not a supervisor, but broadcasted supervisor message");
if (m == null) {
m = new SupervisorMachine(e.getSerial(),
e.getSerial() == mySerial);
machines.add(m);
machinesChangedObs.notifyObservers();
}
SupervisorMachine sup = (SupervisorMachine) m;
if (e.getStatus().equals("active")) {
sup.setStatus(SupervisorMachine.ACTIVE);
if (e.getSerial() != mySerial)
setActivated(false);
} else if (e.getStatus().equals("inactive"))
sup.setStatus(SupervisorMachine.INACTIVE);
else
throw new IllegalStateException(
"Invalid Supervisor Status: " + e.getStatus());
sup.setOnline(true);
}
/**
* Handler for a votebox (status) event. Adds the machine if it
* hasn't been seen, or updates the status if it has. Also, if the
* booth is unlabeled and this is the active supervisor, labels the
* booth with its previous label if known, or the next available
* number.
*/
public void votebox(VoteBoxEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && !(m instanceof VoteBoxBooth))
throw new IllegalStateException(
"Machine "
+ e.getSerial()
+ " is not a booth, but broadcasted votebox message");
if (m == null) {
m = new VoteBoxBooth(e.getSerial());
machines.add(m);
machinesChangedObs.notifyObservers();
}
VoteBoxBooth booth = (VoteBoxBooth) m;
if (e.getStatus().equals("ready"))
booth.setStatus(VoteBoxBooth.READY);
else if (e.getStatus().equals("in-use"))
booth.setStatus(VoteBoxBooth.IN_USE);
else
throw new IllegalStateException("Invalid VoteBox Status: "
+ e.getStatus());
booth.setBattery(e.getBattery());
booth.setProtectedCount(e.getProtectedCount());
booth.setPublicCount(e.getPublicCount());
booth.setOnline(true);
//Check to see if this votebox has a conflicting label
//TODO Apparently this doesn't do what it says it does....
if (e.getLabel() > 0){
for(AMachine machine : machines){
if(machine.getLabel() == e.getLabel() && machine != m){
//If there is a conflict, relabel this (the event generator) machine.
int maxlabel = 0;
for(AMachine ma : machines){
if(ma instanceof VoteBoxBooth)
maxlabel = (int)Math.max(maxlabel, ma.getLabel());
}//for
auditorium.announce(new AssignLabelEvent(mySerial, e.getSerial(), maxlabel + 1));
return;
}
}
}//if
if (e.getLabel() > 0)
booth.setLabel(e.getLabel());
else {
if (activated) {
if (booth.getLabel() > 0)
auditorium.announce(new AssignLabelEvent(mySerial, e
.getSerial(), booth.getLabel()));
else {
int maxlabel = 0;
for (AMachine ma : machines) {
if (ma instanceof VoteBoxBooth
&& ((VoteBoxBooth) ma).getLabel() > maxlabel)
maxlabel = ((VoteBoxBooth) ma).getLabel();
}
auditorium.announce(new AssignLabelEvent(mySerial, e
.getSerial(), maxlabel + 1));
}
auditorium.announce(new PollStatusEvent(mySerial, e.getSerial(), pollsOpen ? 1:0 ));
}
}
}
/**
* Indicate to the tallier that the vote in question is being challenged,
* and as such should be excluded from the final tally.
*/
public void challengeResponse(ChallengeResponseEvent e) {
//NO-OP
}
/**
* Indicate to the tallier that the vote in question is being challenged,
* and as such should be excluded from the final tally.
*/
public void challenge(ChallengeEvent e) {
System.out.println("Received challenge: "+e);
tallier.challenged(e.getNonce());
auditorium.announce(new ChallengeResponseEvent(mySerial,
e.getSerial(), e.getNonce()));
}
/**
* Record the vote received in the commit event.
* It should not yet be tallied.
*/
public void commitBallot(CommitBallotEvent e) {
AMachine m = getMachineForSerial(e.getSerial());
if (m != null && m instanceof VoteBoxBooth) {
VoteBoxBooth booth = (VoteBoxBooth) m;
booth.setPublicCount(booth.getPublicCount() + 1);
booth.setProtectedCount(booth.getProtectedCount() + 1);
auditorium.announce(new BallotReceivedEvent(mySerial, e
.getSerial(), ((StringExpression) e.getNonce())
.getBytes()));
tallier.recordVotes(e.getBallot().toVerbatim(), e.getNonce());
String bid = e.getBID().toString();
bids.put(bid, e.getNonce());
}
}
public void ballotScanned(BallotScannedEvent e) {
String bid = e.getBID();
int serial = e.getSerial();
if (bids.containsKey(bid)) {
ASExpression nonce = bids.get(bid);
BallotStore.castBallot(e.getBID(), nonce);
// used to be in voteBox registerForCommit listener.
auditorium.announce(new CastCommittedBallotEvent(serial, nonce));
// that should trigger my own castBallot listener.
} else {
throw new IllegalStateException("got ballot scanned message for invalid BID");
}
//TODO checking to make sure I branched successfully
}
public void pinEntered(PinEnteredEvent e){
if(isPollsOpen()) {
if(validPins.contains(e.getPin())) {
validPins.remove((Integer)e.getPin());
try {
authorize(e.getSerial());
}
catch(IOException ex) {
System.out.println(ex.getMessage());
}
}
else {
auditorium.announce(new InvalidPinEvent(mySerial, e.getNonce()));
}
}
}
public void invalidPin(InvalidPinEvent e) {}
public void pollStatus(PollStatusEvent pollStatusEvent) {
pollsOpen = pollStatusEvent.getPollStatus()==1;
}
});
try {
auditorium.connect();
auditorium.announce(getStatus());
} catch (NetworkException e1) {
//NetworkException represents a recoverable error
// so just note it and continue
System.out.println("Recoverable error occured: "+e1.getMessage());
e1.printStackTrace(System.err);
}
statusTimer.start();
}
|
diff --git a/src/org/openjump/core/ui/plugin/layer/SortCategoryRestorePlugIn.java b/src/org/openjump/core/ui/plugin/layer/SortCategoryRestorePlugIn.java
index f9f8fa93..0e267f33 100644
--- a/src/org/openjump/core/ui/plugin/layer/SortCategoryRestorePlugIn.java
+++ b/src/org/openjump/core/ui/plugin/layer/SortCategoryRestorePlugIn.java
@@ -1,264 +1,262 @@
/*
* The Unified Mapping Platform (JUMP) is an extensible, interactive GUI
* for visualizing and manipulating spatial features with geometry and attributes.
*
* JUMP is Copyright (C) 2003 Vivid Solutions
*
* This program implements extensions to JUMP and is
* Copyright (C) 2004 Integrated Systems Analysts, 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; 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
* 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.
*
* For more information, contact:
*
* Integrated Systems Analysts, Inc.
* 630C Anchors St., Suite 101
* Fort Walton Beach, Florida
* USA
*
* (850)862-7321
* www.ashs.isa.com
*/
package org.openjump.core.ui.plugin.layer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import com.vividsolutions.jump.I18N;
import com.vividsolutions.jump.workbench.WorkbenchContext;
import com.vividsolutions.jump.workbench.model.Category;
import com.vividsolutions.jump.workbench.model.LayerManager;
import com.vividsolutions.jump.workbench.model.Layerable;
import com.vividsolutions.jump.workbench.plugin.AbstractPlugIn;
import com.vividsolutions.jump.workbench.plugin.EnableCheck;
import com.vividsolutions.jump.workbench.plugin.MultiEnableCheck;
import com.vividsolutions.jump.workbench.plugin.PlugInContext;
import com.vividsolutions.jump.workbench.ui.MenuNames;
/**
* Restore layers from the saved location
*
* @author clark4444
*
*/
public class SortCategoryRestorePlugIn extends AbstractPlugIn {
static private WorkbenchContext workbenchContext = null;
private static final ImageIcon ICON = null;
private String menuLabel = "Restore";
public void initialize(PlugInContext context) throws Exception {
menuLabel = I18N
.get("org.openjump.core.ui.plugin.layer.SortCategoryRestorePlugIn.Restore");
context
.getFeatureInstaller()
.addMainMenuItemWithJava14Fix(
this,
new String[] {
MenuNames.LAYER,
I18N
.get(SortCategoryAbstractPlugIn.I18N_SORT_MENU_LABEL) },
menuLabel, false, ICON, null);
}
public boolean execute(PlugInContext context) throws Exception {
try {
LayerManager layerManager = context.getWorkbenchContext()
.getLayerManager();
List<Layerable> allLayerables = context.getWorkbenchContext()
.getLayerNamePanel().getLayerManager().getLayerables(
Layerable.class);
Map<LayerableLocation, Layerable> saved = new TreeMap<LayerableLocation, Layerable>(
Collections.reverseOrder());
List<Layerable> unsaved = new ArrayList<Layerable>();
getSavedUnsavedLayerables(saved, unsaved, allLayerables);
Map<Layerable, String> layerableToCategory = getLayerableToCategory(
unsaved, layerManager.getCategories());
try {
removeLayers(layerManager, allLayerables);
- allLayerables.get(18).getBlackboard().get(
- SortCategorySavePlugIn.BLACKBOARD_CATEGORY);
// add unsaved to end, saved to beginning
addUnSavedBack(layerManager, allLayerables, unsaved,
layerableToCategory);
addSavedBack(layerManager, allLayerables, saved);
} finally {
// context.getLayerManager().setFiringEvents(firingEvents);
context.getLayerViewPanel().repaint();
context.getWorkbenchFrame().repaint();
}
return true;
} catch (Exception e) {
context.getWorkbenchFrame().warnUser("Error: see output window");
context.getWorkbenchFrame().getOutputFrame().createNewDocument();
context.getWorkbenchFrame().getOutputFrame().addText(
getName() + " PlugIn Exception:" + e.toString());
return false;
}
}
private Map<Layerable, String> getLayerableToCategory(
List<Layerable> unsaved, List<Category> categories) {
Map<Layerable, String> layerableToCategory = new HashMap<Layerable, String>();
for (Layerable layerable : unsaved) {
for (Category category : categories) {
if (category.contains(layerable)) {
layerableToCategory.put(layerable, category.getName());
break;
} else
continue;
}
}
return layerableToCategory;
}
private void addSavedBack(LayerManager layerManager,
List<Layerable> allLayerables,
Map<LayerableLocation, Layerable> saved) {
for (Layerable layerable : saved.values()) {
if (layerable.getBlackboard().get(
SortCategorySavePlugIn.BLACKBOARD_CATEGORY) != null)
layerManager.addLayerable((String) layerable.getBlackboard()
.get(SortCategorySavePlugIn.BLACKBOARD_CATEGORY),
layerable);
}
}
private void addUnSavedBack(LayerManager layerManager,
List<Layerable> allLayerables, List<Layerable> unsaved,
Map<Layerable, String> layerableToCategory) {
Collections.reverse(unsaved);
for (Layerable layerable : unsaved) {
layerManager.addLayerable(layerableToCategory.get(layerable),
layerable);
}
}
private void getSavedUnsavedLayerables(
Map<LayerableLocation, Layerable> saved, List<Layerable> unsaved,
List<Layerable> allLayerables) {
for (Layerable layerable : allLayerables) {
if (layerable.getBlackboard().get(
SortCategorySavePlugIn.BLACKBOARD_CATEGORY) != null
&& layerable != null) {
saved.put(new LayerableLocation((String) layerable
.getBlackboard().get(
SortCategorySavePlugIn.BLACKBOARD_CATEGORY),
layerable.getBlackboard().getInt(
SortCategorySavePlugIn.BLACKBOARD_LAYER)),
layerable);
} else if (layerable != null) {
unsaved.add(layerable);
} else
throw new IllegalStateException("Unknown layerable");
}
}
private void removeLayers(LayerManager layerManager, List<Layerable> layers) {
for (Layerable layerable : layers) {
layerManager.remove(layerable);
}
}
static public EnableCheck createSaveCategorySectionMustExistCheck() {
return new EnableCheck() {
public String check(JComponent component) {
boolean notSaved = true;
Collection layerCollection = (Collection) workbenchContext
.getLayerNamePanel().getLayerManager().getLayerables(
Layerable.class);
for (Iterator i = layerCollection.iterator(); i.hasNext();) {
Layerable layer = (Layerable) i.next();
if (layer.getBlackboard().get(
SortCategorySavePlugIn.BLACKBOARD_LAYER) != null)
notSaved = false;
}
return (((notSaved))) ? "Use Save Category first." : null;
}
};
}
public static MultiEnableCheck createEnableCheck(
WorkbenchContext workbenchContext) {
return new MultiEnableCheck().add(SortCategoryRestorePlugIn
.createSaveCategorySectionMustExistCheck());
}
class LayerableLocation implements Comparable<LayerableLocation> {
private String category;
private Integer position;
LayerableLocation(String category, Integer position) {
this.category = category;
this.position = position;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public int compareTo(LayerableLocation location) {
if (category.compareTo(location.getCategory()) == 0)
return position.compareTo(location.getPosition());
else
return category.compareTo(location.getCategory());
}
}
}
| true | true | public boolean execute(PlugInContext context) throws Exception {
try {
LayerManager layerManager = context.getWorkbenchContext()
.getLayerManager();
List<Layerable> allLayerables = context.getWorkbenchContext()
.getLayerNamePanel().getLayerManager().getLayerables(
Layerable.class);
Map<LayerableLocation, Layerable> saved = new TreeMap<LayerableLocation, Layerable>(
Collections.reverseOrder());
List<Layerable> unsaved = new ArrayList<Layerable>();
getSavedUnsavedLayerables(saved, unsaved, allLayerables);
Map<Layerable, String> layerableToCategory = getLayerableToCategory(
unsaved, layerManager.getCategories());
try {
removeLayers(layerManager, allLayerables);
allLayerables.get(18).getBlackboard().get(
SortCategorySavePlugIn.BLACKBOARD_CATEGORY);
// add unsaved to end, saved to beginning
addUnSavedBack(layerManager, allLayerables, unsaved,
layerableToCategory);
addSavedBack(layerManager, allLayerables, saved);
} finally {
// context.getLayerManager().setFiringEvents(firingEvents);
context.getLayerViewPanel().repaint();
context.getWorkbenchFrame().repaint();
}
return true;
} catch (Exception e) {
context.getWorkbenchFrame().warnUser("Error: see output window");
context.getWorkbenchFrame().getOutputFrame().createNewDocument();
context.getWorkbenchFrame().getOutputFrame().addText(
getName() + " PlugIn Exception:" + e.toString());
return false;
}
}
| public boolean execute(PlugInContext context) throws Exception {
try {
LayerManager layerManager = context.getWorkbenchContext()
.getLayerManager();
List<Layerable> allLayerables = context.getWorkbenchContext()
.getLayerNamePanel().getLayerManager().getLayerables(
Layerable.class);
Map<LayerableLocation, Layerable> saved = new TreeMap<LayerableLocation, Layerable>(
Collections.reverseOrder());
List<Layerable> unsaved = new ArrayList<Layerable>();
getSavedUnsavedLayerables(saved, unsaved, allLayerables);
Map<Layerable, String> layerableToCategory = getLayerableToCategory(
unsaved, layerManager.getCategories());
try {
removeLayers(layerManager, allLayerables);
// add unsaved to end, saved to beginning
addUnSavedBack(layerManager, allLayerables, unsaved,
layerableToCategory);
addSavedBack(layerManager, allLayerables, saved);
} finally {
// context.getLayerManager().setFiringEvents(firingEvents);
context.getLayerViewPanel().repaint();
context.getWorkbenchFrame().repaint();
}
return true;
} catch (Exception e) {
context.getWorkbenchFrame().warnUser("Error: see output window");
context.getWorkbenchFrame().getOutputFrame().createNewDocument();
context.getWorkbenchFrame().getOutputFrame().addText(
getName() + " PlugIn Exception:" + e.toString());
return false;
}
}
|
diff --git a/components/bio-formats/src/loci/formats/in/PSDReader.java b/components/bio-formats/src/loci/formats/in/PSDReader.java
index eb451cdbf..8cca8d71b 100644
--- a/components/bio-formats/src/loci/formats/in/PSDReader.java
+++ b/components/bio-formats/src/loci/formats/in/PSDReader.java
@@ -1,304 +1,308 @@
//
// PSDReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, 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; 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
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
*/
package loci.formats.in;
import java.io.IOException;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.codec.CodecOptions;
import loci.formats.codec.PackbitsCodec;
import loci.formats.meta.MetadataStore;
/**
* PSDReader is the file format reader for Photoshop PSD files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/PSDReader.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/PSDReader.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class PSDReader extends FormatReader {
// -- Constants --
public static final String PSD_MAGIC_STRING = "8BPS";
// -- Fields --
/** Lookup table. */
private byte[][] lut;
/** Offset to pixel data. */
private long offset;
// -- Constructor --
/** Constructs a new PSD reader. */
public PSDReader() {
super("Adobe Photoshop", "psd");
domains = new String[] {FormatTools.GRAPHICS_DOMAIN};
suffixNecessary = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = PSD_MAGIC_STRING.length();
if (!FormatTools.validStream(stream, blockLen, false)) return false;
return stream.readString(blockLen).startsWith(PSD_MAGIC_STRING);
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() {
FormatTools.assertId(currentId, true, 1);
return lut;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
in.seek(offset);
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int plane = getSizeX() * getSizeY() * bpp;
int[][] lens = new int[getSizeC()][getSizeY()];
boolean compressed = in.readShort() == 1;
if (compressed) {
PackbitsCodec codec = new PackbitsCodec();
for (int c=0; c<getSizeC(); c++) {
for (int row=0; row<getSizeY(); row++) {
lens[c][row] = in.readShort();
}
}
CodecOptions options = new CodecOptions();
options.maxBytes = getSizeX() * bpp;
int len = w * bpp;
for (int c=0; c<getSizeC(); c++) {
for (int row=0; row<getSizeY(); row++) {
if (row < y || row >= (y + h)) in.skipBytes(lens[c][row]);
else {
byte[] b = codec.decompress(in, options);
System.arraycopy(b, x*bpp, buf, c * h * len + (row - y) * len, len);
}
}
}
}
else {
readPlane(in, x, y, w, h, buf);
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
lut = null;
offset = 0;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
core[0].littleEndian = false;
if (!in.readString(4).equals("8BPS")) {
throw new FormatException("Not a valid Photoshop file.");
}
addGlobalMeta("Version", in.readShort());
in.skipBytes(6); // reserved, set to 0
core[0].sizeC = in.readShort();
core[0].sizeY = in.readInt();
core[0].sizeX = in.readInt();
int bits = in.readShort();
addGlobalMeta("Bits per pixel", bits);
core[0].pixelType = FormatTools.pixelTypeFromBytes(bits / 8, false, false);
int colorMode = in.readShort();
String modeString = null;
switch (colorMode) {
case 0:
modeString = "monochrome";
break;
case 1:
modeString = "gray-scale";
break;
case 2:
modeString = "palette color";
break;
case 3:
modeString = "RGB";
break;
case 4:
modeString = "CMYK";
break;
case 6:
modeString = "Duotone";
break;
case 7:
modeString = "Multichannel color";
break;
case 8:
modeString = "Duotone";
break;
case 9:
modeString = "LAB color";
break;
}
addGlobalMeta("Color mode", modeString);
// read color mode block, if present
int modeDataLength = in.readInt();
long fp = in.getFilePointer();
if (modeDataLength != 0) {
if (colorMode == 2) {
lut = new byte[3][256];
for (int i=0; i<lut.length; i++) {
in.read(lut[i]);
}
}
in.seek(fp + modeDataLength);
}
// read image resources block
in.skipBytes(4);
while (in.readString(4).equals("8BIM")) {
int tag = in.readShort();
int read = 1;
while (in.read() != 0) read++;
if (read % 2 == 1) in.skipBytes(1);
int size = in.readInt();
if (size % 2 == 1) size++;
in.skipBytes(size);
}
in.seek(in.getFilePointer() - 4);
int blockLen = in.readInt();
if (blockLen == 0) {
offset = in.getFilePointer();
}
else {
int layerLen = in.readInt();
int layerCount = in.readShort();
if (layerCount < 0) {
throw new FormatException("Vector data is not supported.");
}
int[] w = new int[layerCount];
int[] h = new int[layerCount];
int[] c = new int[layerCount];
for (int i=0; i<layerCount; i++) {
int top = in.readInt();
int left = in.readInt();
int bottom = in.readInt();
int right = in.readInt();
w[i] = right - left;
h[i] = bottom - top;
c[i] = in.readShort();
in.skipBytes(c[i] * 6 + 12);
int len = in.readInt();
if (len % 2 == 1) len++;
in.skipBytes(len);
}
// skip over pixel data for each layer
for (int i=0; i<layerCount; i++) {
int[] lens = new int[h[i]];
for (int cc=0; cc<c[i]; cc++) {
boolean compressed = in.readShort() == 1;
if (!compressed) in.skipBytes(w[i] * h[i]);
else {
for (int y=0; y<h[i]; y++) {
lens[y] = in.readShort();
}
for (int y=0; y<h[i]; y++) {
in.skipBytes(lens[y]);
}
}
}
}
+ long start = in.getFilePointer();
while (in.read() != '8');
in.skipBytes(7);
+ if (in.getFilePointer() - start > 1024) {
+ in.seek(start);
+ }
int len = in.readInt();
if ((len % 4) != 0) len += 4 - (len % 4);
in.skipBytes(len);
String s = in.readString(4);
while (s.equals("8BIM")) {
in.skipBytes(4);
len = in.readInt();
if ((len % 4) != 0) len += 4 - (len % 4);
in.skipBytes(len);
s = in.readString(4);
}
offset = in.getFilePointer() - 4;
}
core[0].sizeZ = 1;
core[0].sizeT = 1;
core[0].rgb = modeString.equals("RGB");
core[0].imageCount = getSizeC() / (isRGB() ? 3 : 1);
core[0].indexed = modeString.equals("palette color");
core[0].falseColor = false;
core[0].dimensionOrder = "XYCZT";
core[0].interleaved = false;
core[0].metadataComplete = true;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
MetadataTools.setDefaultCreationDate(store, id, 0);
}
}
| false | true | protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
core[0].littleEndian = false;
if (!in.readString(4).equals("8BPS")) {
throw new FormatException("Not a valid Photoshop file.");
}
addGlobalMeta("Version", in.readShort());
in.skipBytes(6); // reserved, set to 0
core[0].sizeC = in.readShort();
core[0].sizeY = in.readInt();
core[0].sizeX = in.readInt();
int bits = in.readShort();
addGlobalMeta("Bits per pixel", bits);
core[0].pixelType = FormatTools.pixelTypeFromBytes(bits / 8, false, false);
int colorMode = in.readShort();
String modeString = null;
switch (colorMode) {
case 0:
modeString = "monochrome";
break;
case 1:
modeString = "gray-scale";
break;
case 2:
modeString = "palette color";
break;
case 3:
modeString = "RGB";
break;
case 4:
modeString = "CMYK";
break;
case 6:
modeString = "Duotone";
break;
case 7:
modeString = "Multichannel color";
break;
case 8:
modeString = "Duotone";
break;
case 9:
modeString = "LAB color";
break;
}
addGlobalMeta("Color mode", modeString);
// read color mode block, if present
int modeDataLength = in.readInt();
long fp = in.getFilePointer();
if (modeDataLength != 0) {
if (colorMode == 2) {
lut = new byte[3][256];
for (int i=0; i<lut.length; i++) {
in.read(lut[i]);
}
}
in.seek(fp + modeDataLength);
}
// read image resources block
in.skipBytes(4);
while (in.readString(4).equals("8BIM")) {
int tag = in.readShort();
int read = 1;
while (in.read() != 0) read++;
if (read % 2 == 1) in.skipBytes(1);
int size = in.readInt();
if (size % 2 == 1) size++;
in.skipBytes(size);
}
in.seek(in.getFilePointer() - 4);
int blockLen = in.readInt();
if (blockLen == 0) {
offset = in.getFilePointer();
}
else {
int layerLen = in.readInt();
int layerCount = in.readShort();
if (layerCount < 0) {
throw new FormatException("Vector data is not supported.");
}
int[] w = new int[layerCount];
int[] h = new int[layerCount];
int[] c = new int[layerCount];
for (int i=0; i<layerCount; i++) {
int top = in.readInt();
int left = in.readInt();
int bottom = in.readInt();
int right = in.readInt();
w[i] = right - left;
h[i] = bottom - top;
c[i] = in.readShort();
in.skipBytes(c[i] * 6 + 12);
int len = in.readInt();
if (len % 2 == 1) len++;
in.skipBytes(len);
}
// skip over pixel data for each layer
for (int i=0; i<layerCount; i++) {
int[] lens = new int[h[i]];
for (int cc=0; cc<c[i]; cc++) {
boolean compressed = in.readShort() == 1;
if (!compressed) in.skipBytes(w[i] * h[i]);
else {
for (int y=0; y<h[i]; y++) {
lens[y] = in.readShort();
}
for (int y=0; y<h[i]; y++) {
in.skipBytes(lens[y]);
}
}
}
}
while (in.read() != '8');
in.skipBytes(7);
int len = in.readInt();
if ((len % 4) != 0) len += 4 - (len % 4);
in.skipBytes(len);
String s = in.readString(4);
while (s.equals("8BIM")) {
in.skipBytes(4);
len = in.readInt();
if ((len % 4) != 0) len += 4 - (len % 4);
in.skipBytes(len);
s = in.readString(4);
}
offset = in.getFilePointer() - 4;
}
core[0].sizeZ = 1;
core[0].sizeT = 1;
core[0].rgb = modeString.equals("RGB");
core[0].imageCount = getSizeC() / (isRGB() ? 3 : 1);
core[0].indexed = modeString.equals("palette color");
core[0].falseColor = false;
core[0].dimensionOrder = "XYCZT";
core[0].interleaved = false;
core[0].metadataComplete = true;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
MetadataTools.setDefaultCreationDate(store, id, 0);
}
| protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
core[0].littleEndian = false;
if (!in.readString(4).equals("8BPS")) {
throw new FormatException("Not a valid Photoshop file.");
}
addGlobalMeta("Version", in.readShort());
in.skipBytes(6); // reserved, set to 0
core[0].sizeC = in.readShort();
core[0].sizeY = in.readInt();
core[0].sizeX = in.readInt();
int bits = in.readShort();
addGlobalMeta("Bits per pixel", bits);
core[0].pixelType = FormatTools.pixelTypeFromBytes(bits / 8, false, false);
int colorMode = in.readShort();
String modeString = null;
switch (colorMode) {
case 0:
modeString = "monochrome";
break;
case 1:
modeString = "gray-scale";
break;
case 2:
modeString = "palette color";
break;
case 3:
modeString = "RGB";
break;
case 4:
modeString = "CMYK";
break;
case 6:
modeString = "Duotone";
break;
case 7:
modeString = "Multichannel color";
break;
case 8:
modeString = "Duotone";
break;
case 9:
modeString = "LAB color";
break;
}
addGlobalMeta("Color mode", modeString);
// read color mode block, if present
int modeDataLength = in.readInt();
long fp = in.getFilePointer();
if (modeDataLength != 0) {
if (colorMode == 2) {
lut = new byte[3][256];
for (int i=0; i<lut.length; i++) {
in.read(lut[i]);
}
}
in.seek(fp + modeDataLength);
}
// read image resources block
in.skipBytes(4);
while (in.readString(4).equals("8BIM")) {
int tag = in.readShort();
int read = 1;
while (in.read() != 0) read++;
if (read % 2 == 1) in.skipBytes(1);
int size = in.readInt();
if (size % 2 == 1) size++;
in.skipBytes(size);
}
in.seek(in.getFilePointer() - 4);
int blockLen = in.readInt();
if (blockLen == 0) {
offset = in.getFilePointer();
}
else {
int layerLen = in.readInt();
int layerCount = in.readShort();
if (layerCount < 0) {
throw new FormatException("Vector data is not supported.");
}
int[] w = new int[layerCount];
int[] h = new int[layerCount];
int[] c = new int[layerCount];
for (int i=0; i<layerCount; i++) {
int top = in.readInt();
int left = in.readInt();
int bottom = in.readInt();
int right = in.readInt();
w[i] = right - left;
h[i] = bottom - top;
c[i] = in.readShort();
in.skipBytes(c[i] * 6 + 12);
int len = in.readInt();
if (len % 2 == 1) len++;
in.skipBytes(len);
}
// skip over pixel data for each layer
for (int i=0; i<layerCount; i++) {
int[] lens = new int[h[i]];
for (int cc=0; cc<c[i]; cc++) {
boolean compressed = in.readShort() == 1;
if (!compressed) in.skipBytes(w[i] * h[i]);
else {
for (int y=0; y<h[i]; y++) {
lens[y] = in.readShort();
}
for (int y=0; y<h[i]; y++) {
in.skipBytes(lens[y]);
}
}
}
}
long start = in.getFilePointer();
while (in.read() != '8');
in.skipBytes(7);
if (in.getFilePointer() - start > 1024) {
in.seek(start);
}
int len = in.readInt();
if ((len % 4) != 0) len += 4 - (len % 4);
in.skipBytes(len);
String s = in.readString(4);
while (s.equals("8BIM")) {
in.skipBytes(4);
len = in.readInt();
if ((len % 4) != 0) len += 4 - (len % 4);
in.skipBytes(len);
s = in.readString(4);
}
offset = in.getFilePointer() - 4;
}
core[0].sizeZ = 1;
core[0].sizeT = 1;
core[0].rgb = modeString.equals("RGB");
core[0].imageCount = getSizeC() / (isRGB() ? 3 : 1);
core[0].indexed = modeString.equals("palette color");
core[0].falseColor = false;
core[0].dimensionOrder = "XYCZT";
core[0].interleaved = false;
core[0].metadataComplete = true;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
MetadataTools.setDefaultCreationDate(store, id, 0);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.