lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | e13a2007f96f05aed6c4de1cee7a3283343542b0 | 0 | tonussi/teia | /**
*
*/
package test;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import model.Amigo;
import model.AmigoHomem;
import model.AmigoMulher;
import model.DesenhistaAmigoDestacado;
import model.DesenhistaAmigoHomem;
import model.DesenhistaAmigoMulher;
import model.Info;
import model.Vertice;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import processing.core.PApplet;
import processing.core.PFont;
import dao.AmigoDataAccessObjectImpl;
import dao.DBConnection;
import dao.DBConnectionImpl;
/**
* @author lucastonussi
*
*/
public class TeiaTest {
List<Amigo> amigos;
List<AmigoMulher> amigosMulheres;
List<AmigoHomem> amigosHomens;
List<Info> infoAmigosHomens;
List<Info> infoAmigosMulheres;
List<DesenhistaAmigoHomem> desenhistasAmigosHomens;
List<DesenhistaAmigoMulher> desenhistasAmigosMulheres;
List<DesenhistaAmigoDestacado> desenhistasAmigosDestacados;
List<Vertice> grafo;
Map<BigInteger, BigInteger> mapeamentoNodular;
AmigoDataAccessObjectImpl amigoDataAccessObject;
DBConnection dbConnection;
PFont font;
PApplet processing;
Info infoHomem, infoMulher;
AmigoHomem amigoHomem;
AmigoMulher amigoMulher;
DesenhistaAmigoHomem desenhistaAmigoHomem;
DesenhistaAmigoMulher desenhistaAmigoMulher;
private final Logger logger = Logger.getLogger(TeiaTest.class.getName());
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
processing = new PApplet();
font = processing.createFont("Helvetica", 6, true);
amigos = new ArrayList<>();
amigosMulheres = new ArrayList<>();
amigosHomens = new ArrayList<>();
dbConnection = new DBConnectionImpl("lucastonussi", "lucastonussi",
"hung4ro5");
amigoDataAccessObject = new AmigoDataAccessObjectImpl(processing, font,
dbConnection);
infoAmigosHomens = new ArrayList<>(
amigoDataAccessObject.listaAmigosPorGenero("male"));
infoAmigosMulheres = new ArrayList<>(
amigoDataAccessObject.listaAmigosPorGenero("female"));
grafo = new ArrayList<Vertice>(amigoDataAccessObject.listaRelacoes());
mapeamentoNodular = new HashMap<BigInteger, BigInteger>();
mapeamentoNodular = amigoDataAccessObject.mapeiaRelacoes();
for (AmigoHomem amigoHomem : amigosHomens) {
desenhistasAmigosHomens.add(new DesenhistaAmigoHomem(processing,
amigoHomem));
logger.info(amigoHomem.toString());
}
for (AmigoMulher amigoMulher : amigosMulheres) {
desenhistasAmigosMulheres.add(new DesenhistaAmigoMulher(processing,
amigoMulher));
logger.info(amigoMulher.toString());
}
infoHomem = new Info(processing, font, new BigInteger("1318200713"),
"Diego Fagundes", "male", "pt_BR", 193);
amigoHomem = new AmigoHomem(infoHomem);
desenhistaAmigoHomem = new DesenhistaAmigoHomem(processing, amigoHomem);
infoMulher = new Info(processing, font, new BigInteger("580905942"),
"Erica Mattos", "female", "pt_BR", 227);
amigoMulher = new AmigoMulher(infoMulher);
desenhistaAmigoMulher = new DesenhistaAmigoMulher(processing, amigoMulher);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
grafo.clear();
mapeamentoNodular.clear();
amigos.clear();
infoAmigosHomens.clear();
infoAmigosMulheres.clear();
dbConnection.close();
}
@Test
public void testSeVerticeTemIdentificadorHomemIgualAoInfoHomem() {
for (Vertice vertice : grafo)
if (vertice.getIdentificador().equals(new BigInteger("1318200713")))
assertEquals(infoHomem.getUid(), vertice.getIdentificador());
}
@Test
public void testSeVerticeTemIdentificadorMulherIgualAoInfoMulher() {
for (Vertice vertice : grafo)
if (vertice.getIdentificador().equals(new BigInteger("580905942")))
assertEquals(infoMulher.getUid(), vertice.getIdentificador());
}
}
| src/test/TeiaTest.java | /**
*
*/
package test;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import model.Amigo;
import model.DesenhistaAmigoHomem;
import model.DesenhistaAmigoMulher;
import model.Info;
import model.Vertice;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import processing.core.PApplet;
import processing.core.PFont;
import dao.AmigoDataAccessObjectImpl;
import dao.DBConnection;
import dao.DBConnectionImpl;
/**
* @author lucastonussi
*
*/
public class TeiaTest {
List<Amigo> amigos;
List<Info> infoAmigosHomens;
List<Info> infoAmigosMulheres;
List<Vertice> grafo;
Map<BigInteger, BigInteger> mapeamentoNodular;
AmigoDataAccessObjectImpl amigoDataAccessObject;
DBConnection dbConnection;
PFont font;
PApplet processing;
Info infoHomem, infoMulher;
Amigo amigoHomem, amigoMulher;
private final Logger logger = Logger.getLogger(TeiaTest.class.getName());
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
processing = new PApplet();
font = processing.createFont("Helvetica", 6, true);
amigos = new ArrayList<Amigo>();
dbConnection = new DBConnectionImpl("lucastonussi", "lucastonussi",
"hung4ro5");
amigoDataAccessObject = new AmigoDataAccessObjectImpl(processing, font,
dbConnection);
infoAmigosHomens = new ArrayList<Info>(
amigoDataAccessObject.listaAmigosPorGenero("male"));
infoAmigosMulheres = new ArrayList<Info>(
amigoDataAccessObject.listaAmigosPorGenero("female"));
grafo = new ArrayList<Vertice>(amigoDataAccessObject.listaRelacoes());
mapeamentoNodular = new HashMap<BigInteger, BigInteger>();
mapeamentoNodular = amigoDataAccessObject.mapeiaRelacoes();
for (Info infoAmigo : infoAmigosHomens) {
amigos.add(new DesenhistaAmigoHomem(processing, infoAmigo));
logger.info(infoAmigo.toString());
}
for (Info infoAmigo : infoAmigosMulheres) {
amigos.add(new DesenhistaAmigoMulher(processing, infoAmigo));
logger.info(infoAmigo.toString());
}
infoHomem = new Info(processing, font, new BigInteger("1318200713"),
"Diego Fagundes", "male", "pt_BR", 193);
amigoHomem = new DesenhistaAmigoHomem(processing, infoHomem);
infoMulher = new Info(processing, font, new BigInteger("580905942"),
"Erica Mattos", "female", "pt_BR", 227);
amigoMulher = new DesenhistaAmigoMulher(processing, infoMulher);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
grafo.clear();
mapeamentoNodular.clear();
amigos.clear();
infoAmigosHomens.clear();
infoAmigosMulheres.clear();
dbConnection.close();
}
@Test
public void testSeVerticeTemIdentificadorHomemIgualAoInfoHomem() {
for (Vertice vertice : grafo)
if (vertice.getIdentificador().equals(new BigInteger("1318200713")))
assertEquals(infoHomem.getUid(), vertice.getIdentificador());
}
@Test
public void testSeVerticeTemIdentificadorMulherIgualAoInfoMulher() {
for (Vertice vertice : grafo)
if (vertice.getIdentificador().equals(new BigInteger("580905942")))
assertEquals(infoMulher.getUid(), vertice.getIdentificador());
}
}
| Adiciona testes de sistema para os desenhistas compostos | src/test/TeiaTest.java | Adiciona testes de sistema para os desenhistas compostos |
|
Java | epl-1.0 | 044e1fbdbc0deefbcf4b15e30c0c0d90f439cd2e | 0 | gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime,gameduell/eclipselink.runtime | /*******************************************************************************
* Copyright (c) 1998, 2008 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.jaxb;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import org.eclipse.persistence.exceptions.XMLMarshalException;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.sessions.Session;
/**
* INTERNAL
* <p><b>Purpose:</b>Provide a TopLink implementation of JAXBIntrospector
* <p><b>Responsibilities:</b><ul>
* <li>Determine if a an object has an associated Global Element</li>
* <li>Get an element QName for an object that has an associated global element</li>
* </ul>
* <p>This class is the TopLink implementation of JAXBIntrospector. An Introspector is created
* by a JAXBContext and allows the user to access certain peices of meta-data about an instance
* of a JAXB bound class.
*
* @see javax.xml.bind.JAXBIntrospector
* @see org.eclipse.persistence.jaxb.JAXB20Context
* @author mmacivor
* @since Oracle TopLink 11.1.1.0.0
*/
public class JAXBIntrospector extends javax.xml.bind.JAXBIntrospector {
private XMLContext context;
public JAXBIntrospector(XMLContext context) {
this.context = context;
}
public boolean isElement(Object obj) {
if (obj instanceof JAXBElement) {
return true;
}
try {
Session session = context.getSession(obj);
if(session == null) {
return false;
}
XMLDescriptor descriptor = (XMLDescriptor)session.getDescriptor(obj);
if(descriptor == null) {
return false;
}
return descriptor.getDefaultRootElement() != null;
} catch(XMLMarshalException e) {
return false;
}
}
public QName getElementName(Object obj) {
if(!isElement(obj)) {
return null;
}
if(obj instanceof JAXBElement) {
return ((JAXBElement) obj).getName();
}
try {
XMLDescriptor descriptor = (XMLDescriptor)context.getSession(obj).getDescriptor(obj);
String rootElem = descriptor.getDefaultRootElement();
int prefixIndex = rootElem.indexOf(":");
if(prefixIndex == -1) {
return new QName(rootElem);
} else {
String prefix = rootElem.substring(0, prefixIndex);
String localPart = rootElem.substring(prefixIndex + 1);
String URI = descriptor.getNamespaceResolver().resolveNamespacePrefix(prefix);
return new QName(URI, localPart);
}
} catch(XMLMarshalException e) {
return null;
}
}
}
| moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBIntrospector.java | /*******************************************************************************
* Copyright (c) 1998, 2008 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.jaxb;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.sessions.Session;
/**
* INTERNAL
* <p><b>Purpose:</b>Provide a TopLink implementation of JAXBIntrospector
* <p><b>Responsibilities:</b><ul>
* <li>Determine if a an object has an associated Global Element</li>
* <li>Get an element QName for an object that has an associated global element</li>
* </ul>
* <p>This class is the TopLink implementation of JAXBIntrospector. An Introspector is created
* by a JAXBContext and allows the user to access certain peices of meta-data about an instance
* of a JAXB bound class.
*
* @see javax.xml.bind.JAXBIntrospector
* @see org.eclipse.persistence.jaxb.JAXB20Context
* @author mmacivor
* @since Oracle TopLink 11.1.1.0.0
*/
public class JAXBIntrospector extends javax.xml.bind.JAXBIntrospector {
private XMLContext context;
public JAXBIntrospector(XMLContext context) {
this.context = context;
}
public boolean isElement(Object obj) {
if (obj instanceof JAXBElement) {
return true;
}
Session session = context.getSession(obj);
if(session == null) {
return false;
}
XMLDescriptor descriptor = (XMLDescriptor)session.getDescriptor(obj);
if(descriptor == null) {
return false;
}
return descriptor.getDefaultRootElement() != null;
}
public QName getElementName(Object obj) {
if(!isElement(obj)) {
return null;
}
XMLDescriptor descriptor = (XMLDescriptor)context.getSession(obj).getDescriptor(obj);
String rootElem = descriptor.getDefaultRootElement();
int prefixIndex = rootElem.indexOf(":");
if(prefixIndex == -1) {
return new QName(rootElem);
} else {
String prefix = rootElem.substring(0, prefixIndex);
String localPart = rootElem.substring(prefixIndex + 1);
String URI = descriptor.getNamespaceResolver().resolveNamespacePrefix(prefix);
return new QName(URI, localPart);
}
}
}
| Fix for bug #268553
| moxy/org.eclipse.persistence.moxy/src/org/eclipse/persistence/jaxb/JAXBIntrospector.java | Fix for bug #268553 |
|
Java | epl-1.0 | c8119fa7465e122ec7047a046548b7382c8b1a27 | 0 | edgware/edgware,edgware/edgware,acshea/edgware,acshea/edgware,acshea/edgware,acshea/edgware,edgware/edgware,edgware/edgware | /*
* Licensed Materials - Property of IBM
*
* (C) Copyright IBM Corp. 2007, 2014
*
* LICENSE: Eclipse Public License v1.0
* http://www.eclipse.org/legal/epl-v10.html
*/
package fabric.bus.impl;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import fabric.Fabric;
import fabric.FabricBus;
import fabric.FabricMetric;
import fabric.ServiceDescriptor;
import fabric.bus.BusIOChannels;
import fabric.bus.BusMessageHandler;
import fabric.bus.IBusIO;
import fabric.bus.NeighbourChannels;
import fabric.bus.SharedEndPoint;
import fabric.bus.feeds.impl.SubscriptionRecord;
import fabric.bus.messages.FabricMessageFactory;
import fabric.bus.messages.IFabricMessage;
import fabric.bus.messages.IFeedMessage;
import fabric.bus.messages.IMessagePayload;
import fabric.bus.messages.IServiceMessage;
import fabric.bus.messages.impl.FeedMessage;
import fabric.bus.messages.impl.MessagePayload;
import fabric.bus.messages.impl.ServiceMessage;
import fabric.core.io.EndPoint;
import fabric.core.io.ICallback;
import fabric.core.io.IEndPointCallback;
import fabric.core.io.InputTopic;
import fabric.core.io.Message;
import fabric.core.io.MessageQoS;
import fabric.core.io.OutputTopic;
import fabric.core.logging.LogUtil;
import fabric.core.properties.ConfigProperties;
import fabric.registry.FabricRegistry;
import fabric.registry.NodeIpMapping;
import fabric.registry.NodeNeighbour;
import fabric.services.floodmessage.FloodRouting;
import fabric.session.NodeDescriptor;
/**
* Class managing I/O on the Fabric bus.
* <p>
* This includes:
* <ul>
* <li>Placing messages onto the bus</li>
* <li>Moving messages across the bus</li>
* <li>Pulling messages off of the bus to fulfill user subscriptions</li>
* </ul>
*/
public class BusIO extends FabricBus implements IBusIO, ICallback, IEndPointCallback {
/** Copyright notice. */
public static final String copyrightNotice = "(C) Copyright IBM Corp. 2007, 2014";
/*
* Class fields
*/
/** The handler for Fabric messages */
private BusMessageHandler messageHandler = null;
/** The list of nodes neighbouring this Fabric Manager */
private final HashMap<NodeDescriptor, NeighbourChannels> neighbourChannelsTable = new HashMap<NodeDescriptor, NeighbourChannels>();
/** To hold the channels and topics used by the Fabric Manager */
private final BusIOChannels ioChannels = new BusIOChannels();
/** The template topic for sending Fabric Manager commands to a neighbouring node */
private String fabricCommandsBusTemplate = null;
/** The template topic for sending data feed message to a neighbouring node */
private String fabricFeedsBusTemplate = null;
/** The template topic for the Fabric registry bus connection to a neighbouring node */
private String fabricRegistryBusTemplate = null;
/** The UID of the next message to be published onto the Fabric */
private long fabricMessageUID = 0;
/*
* Class methods
*/
/**
* Constructs a new instance.
*/
public BusIO() {
super(Logger.getLogger("fabric.bus"));
initConfig();
}
/**
* Constructs a new instance.
*/
public BusIO(Logger logger) {
super(logger);
initConfig();
}
/**
* Initializes neighbour connection configuration.
*/
private void initConfig() {
fabricCommandsBusTemplate = config(ConfigProperties.TOPIC_SEND_SESSION_COMMANDS,
ConfigProperties.TOPIC_SEND_SESSION_COMMANDS_DEFAULT);
fabricFeedsBusTemplate = config(ConfigProperties.TOPIC_FEEDS_BUS, ConfigProperties.TOPIC_FEEDS_BUS_DEFAULT);
fabricRegistryBusTemplate = config(ConfigProperties.REGISTRY_COMMAND_TOPIC,
ConfigProperties.REGISTRY_COMMAND_TOPIC_DEFAULT);
}
/**
* Opens the required channels to the local broker.
*/
public void openHomeNodeChannels() {
try {
logger.log(Level.FINE, "Fabric connecting on node {0} at address {1}:{2}", new Object[] {homeNode(),
homeNodeEndPoint().ipName(), homeNodeEndPoint().ipPort()});
/*
* Connect to the local node and open the ports
*/
/* The topic on which the Fabric Manager listens for commands */
ioChannels.receiveCommands = new InputTopic(config(ConfigProperties.TOPIC_SEND_SESSION_COMMANDS,
ConfigProperties.TOPIC_SEND_SESSION_COMMANDS_DEFAULT, homeNode()));
ioChannels.receiveCommandsChannel = homeNodeEndPoint().openInputChannel(ioChannels.receiveCommands, this);
logger.log(Level.FINER, "Listening on: {0}", ioChannels.receiveCommands);
/* The topic on which the Fabric Manager sends commands */
ioChannels.sendCommands = new OutputTopic(config(ConfigProperties.TOPIC_SEND_SESSION_COMMANDS,
ConfigProperties.TOPIC_SEND_SESSION_COMMANDS_DEFAULT, homeNode()));
ioChannels.sendCommandsChannel = homeNodeEndPoint().openOutputChannel(ioChannels.sendCommands);
logger.log(Level.FINER, "Commands will be sent to: {0}", ioChannels.sendCommands);
/*
* The channel on which the Fabric Manager publishes commands to locally attached clients (note that the
* client-specific topic must be provided when this channel is used)
*/
ioChannels.sendClientCommandsChannel = homeNodeEndPoint().openOutputChannel();
logger.log(Level.FINER, "Client commands will be sent via channel: {0}",
ioChannels.sendClientCommandsChannel);
/* The channel on which the Fabric Manager publishes commands to locally attached platforms */
ioChannels.sendPlatformCommandsChannel = homeNodeEndPoint().openOutputChannel();
logger.log(Level.FINER, "Platform commands will be sent via channel: {0}",
ioChannels.sendPlatformCommandsChannel);
/* The channel on which the Fabric Manager publishes commands to locally attached services */
ioChannels.sendServiceCommandsChannel = homeNodeEndPoint().openOutputChannel(ioChannels.sendCommands);
logger.log(Level.FINER, "System commands will be sent to: {0}", ioChannels.sendCommands);
/* The topic on which the Fabric Manager listens for locally connected data feeds */
ioChannels.receiveLocalFeeds = new InputTopic(config("fabric.feeds.onramp", null, homeNode()));
ioChannels.receiveLocalFeedsChannel = homeNodeEndPoint().openInputChannel(
new InputTopic(ioChannels.receiveLocalFeeds + "/#"), this);
logger.log(Level.FINER, "Listening for locally connected data feeds on: {0}", ioChannels.receiveLocalFeeds
+ "/#");
/* The topic on which the Fabric Manager listens for messages en route across the Fabric */
ioChannels.receiveBus = new InputTopic(config(ConfigProperties.TOPIC_FEEDS_BUS,
ConfigProperties.TOPIC_FEEDS_BUS_DEFAULT, homeNode()));
ioChannels.receiveBusChannel = homeNodeEndPoint().openInputChannel(
new InputTopic(ioChannels.receiveBus + "/#"), this);
logger.log(Level.FINER, "Listening for bus data feed messages on: {0}", ioChannels.receiveBus + "/#");
/* The topic on which the Fabric Manager listens for local replay messages */
ioChannels.receiveLocalReplayFeeds = new InputTopic(config("fabric.feeds.replay", null, homeNode()));
ioChannels.receiveLocalReplayFeedsChannel = homeNodeEndPoint().openInputChannel(
new InputTopic(ioChannels.receiveLocalReplayFeeds + "/#"), this);
logger.log(Level.FINER, "Listening for local replay messages on: {0}", ioChannels.receiveLocalReplayFeeds
+ "/#");
/* The topic on which the Fabric Manager listens for last will and testament messages */
ioChannels.connectionComands = new InputTopic(config("fabric.commands.topology", null, "+"));
ioChannels.connectionCommandsChannel = homeNodeEndPoint().openInputChannel(ioChannels.connectionComands,
this);
logger.log(Level.FINER, "Listening for LWT messages on: {0}", ioChannels.connectionComands);
/* The topic on which the Fabric Manager publishes messages for local consumption */
ioChannels.sendLocalSubscription = new OutputTopic(config("fabric.feeds.offramp", null, homeNode()));
ioChannels.sendLocalSubscriptionChannel = homeNodeEndPoint().openOutputChannel(
ioChannels.sendLocalSubscription);
logger.log(Level.FINER, "Delivered messages will be sent to: {0}", ioChannels.sendLocalSubscription);
} catch (Exception e) {
logger.log(Level.SEVERE, "Cannot set up publish and/or subscribe topics with broker:", e);
}
}
/**
* @see fabric.core.io.ICallback#startCallback(java.lang.Object)
*/
@Override
public void startCallback(Object arg1) {
/* Unused */
}
/**
* @see fabric.core.io.ICallback#handleMessage(fabric.core.io.Message)
*/
@Override
public synchronized void handleMessage(Message message) {
logger.log(Level.FINER, "Handling message from topic \"{0}\":\n{1}", new Object[] {message.topic,
new String((message.data != null) ? message.data : new byte[0])});
String messageTopic = (String) message.topic;
byte[] messageData = message.data;
String messageString = new String(messageData);
/* Instrumentation */
FabricMetric metric = null;
if (doInstrument()) {
metric = new FabricMetric(homeNode(), null, null, null, null, -1, messageData, null);
metrics().startTiming(metric, FabricMetric.EVENT_NODE_PROCESSING_START);
}
try {
/* If this is a local message from a source attached directly to the node... */
if (messageTopic.startsWith(ioChannels.receiveLocalFeeds.name())) {
String feedTopic = ServiceDescriptor.extract(messageTopic);
if (feedTopic.startsWith("$")) {
try {
floodFeedMessage(feedTopic, message.data);
} catch (Exception e) {
logger.log(Level.SEVERE, "Failed publish virtual service message", e);
}
} else {
sendRawMessage(messageTopic, message.data, false);
}
}
/* Else if it's a local replay message from a source attached directly to the node... */
else if (messageTopic.startsWith(ioChannels.receiveLocalReplayFeeds.name())) {
sendRawMessage(messageTopic, message.data, true);
}
/* Else this should be a message that we can parse */
else {
IFabricMessage parsedMessage = null;
try {
/* Parse the message */
parsedMessage = FabricMessageFactory.create(messageTopic, messageData);
} catch (Exception e) {
logger.log(Level.WARNING, "Improperly formatted message received on topic {0}: {1}", new Object[] {
messageTopic, messageString});
logger.log(Level.FINE, "Exception:", e);
}
/* If this is a Fabric feed message... */
if (parsedMessage instanceof IFeedMessage) {
messageHandler.handleFeedMessage((IFeedMessage) parsedMessage);
}
/* Else if this is a Fabric service message... */
else if (parsedMessage instanceof IServiceMessage) {
logger.log(Level.FINEST, "Service message recevied on topic {0}: {1}", new Object[] {messageTopic,
parsedMessage.toString()});
messageHandler.handleServiceMessage((ServiceMessage) parsedMessage);
}
/* Else if this is any other kind of Fabric message... */
else if (parsedMessage != null) {
logger.log(Level.WARNING, "Unsupported Fabric message recevied on topic {0}: {1}", new Object[] {
messageTopic, parsedMessage.toString()});
}
/*
* Else if it's an improperly formatted last will and testament message (any thing on this topic should
* be an IConnectionMessage)...
*/
else if (messageTopic.startsWith(ioChannels.connectionComands.name())) {
logger.log(Level.WARNING,
"Ignoring improperly formatted connection status (last-will-and-testament) message");
} else {
logger.log(Level.WARNING, "Ignoring improperly formatted message: {0}", messageString);
}
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception handling message received on topic \"{0}\":\n{1}\n{2}", new Object[] {
messageTopic, messageString, LogUtil.stackTrace(e)});
} finally {
if (doInstrument()) {
metrics().endTiming(metric, FabricMetric.EVENT_NODE_PROCESSING_STOP);
}
}
}
/**
* Builds and sends a flood message to distribute a virtual feed message across the Fabric.
*
* @param feedTopic
* the topic to which the message will be delivered on each node.
*
* @param messageData
* the message payload.
*
* @throws Exception
*/
private void floodFeedMessage(String feedTopic, byte[] messageData) throws Exception {
ServiceMessage serviceMessage = new ServiceMessage();
serviceMessage.setServiceFamilyName(Fabric.FABRIC_PLUGIN_FAMILY);
serviceMessage.setActionEnRoute(true);
serviceMessage.setNotification(false);
serviceMessage.setCorrelationID(FabricMessageFactory.generateUID());
serviceMessage.setServiceName("fabric.services.proxypublisher.ProxyPublisherService");
serviceMessage.setAction(IServiceMessage.ACTION_PUBLISH_ON_NODE);
serviceMessage.setEvent(IServiceMessage.EVENT_ACTOR_REQUEST);
serviceMessage.setProperty(IServiceMessage.PROPERTY_DELIVER_TO_FEED, feedTopic);
IMessagePayload messagePayload = new MessagePayload();
messagePayload.setPayloadBytes(messageData);
serviceMessage.setPayload(messagePayload);
serviceMessage.setRouting(new FloodRouting(homeNode()));
try {
ioChannels.sendServiceCommandsChannel.write(serviceMessage.toWireBytes());
} catch (Exception e) {
logger.log(Level.WARNING,
"Internal error: cannot convert {0} to bytes, message cannot be pushed onto the bus",
FeedMessage.class.getName());
logger.log(Level.WARNING, "Internal error: ", e);
}
}
/**
* @see fabric.core.io.ICallback#cancelCallback(java.lang.Object)
*/
@Override
public void cancelCallback(Object arg1) {
/* Unused */
}
/**
* @see fabric.bus.IBusIO#nodeName()
*/
@Override
public String nodeName() {
return homeNode();
}
/**
* @see fabric.bus.IBusIO#connectNeighbour(java.lang.String)
*/
@Override
public NeighbourChannels connectNeighbour(String neighbour) {
NeighbourChannels neighbourChannels = null;
NodeDescriptor nodeDescriptor = createDescriptor(neighbour);
while (neighbourChannels == null && nodeDescriptor != null) {
/* Get the the existing Fabric connection to the node */
neighbourChannels = neighbourChannelsTable.get(nodeDescriptor);
/* If we don't currently have a connection to the neighbour... */
if (neighbourChannels == null) {
logger.log(Level.FINER, "Attempting to connect to potential new neighbour {0}", neighbour);
/* Connect to the neighbour */
neighbourChannels = connectNeighbour(nodeDescriptor, fabricCommandsBusTemplate, fabricFeedsBusTemplate,
fabricRegistryBusTemplate);
/* If the connection was successful... */
if (neighbourChannels != null) {
logger.log(Level.FINER, "Connected to new neighbour: {0}", neighbour);
neighbourChannelsTable.put(nodeDescriptor, neighbourChannels);
} else {
/* Mark this nodeDescriptor as unavailable */
FabricRegistry.getNodeNeighbourFactory(true).markUnavailable(homeNode(), nodeDescriptor);
/*
* Move onto next possible nodeDescriptor, previous one should be marked unavailable and not
* returned.
*/
nodeDescriptor = createDescriptor(neighbour);
}
/*
* Reset all static neighbours to available - nothing else currently does this and we should retry them
* again next time.
*/
FabricRegistry.getNodeNeighbourFactory(true).markStaticNeighboursAsAvailable(homeNode());
}
}
if (nodeDescriptor == null) {
logger.log(Level.WARNING, "Could not connect to potential new neighbour \"{0}\"; node details not found",
neighbour);
}
return neighbourChannels;
}
/**
* Determines the node descriptor for the specified node name.
* <p>
* The method will determine the network interface to be used based upon the order given in the
* <code>ConfigProperties.NODE_INTERFACES</code> configuration property.
* </p>
*
* @param neighbourId
* the Fabric name of the node to which a connection is being made.
*
* @return the descriptor.
*/
private NodeDescriptor createDescriptor(String neighbourId) {
NodeDescriptor nodeDescriptor = null;
/* Establish possible Neighbour Entries from Node_Neighbours */
NodeNeighbour[] neighbours = FabricRegistry.getNodeNeighbourFactory(true).getAvailableNeighboursEntries(
homeNode(), neighbourId);
String[] interfaces = config()
.getProperty(ConfigProperties.NODE_INTERFACES, NodeDescriptor.loopbackInterface()).split(",");
int i = 0;
// Loop in order of local interfaces configured
while (nodeDescriptor == null && i < interfaces.length) {
String localInterface = interfaces[i];
// Loop through neighbours for a match
int j = 0;
while (nodeDescriptor == null && j < neighbours.length) {
NodeNeighbour neighbour = neighbours[j];
if (neighbour.getNodeInterface().equals(localInterface)) {
NodeIpMapping nodeIPMapping = neighbour.getIpMappingForNeighbour();
nodeDescriptor = new NodeDescriptor(nodeIPMapping);
}
j++;
}
i++;
}
return nodeDescriptor;
}
/**
* Connect to a specific neighbouring Fabric node.
*
* @param neighbourDescriptor
* the neighbour to which a connection is to be made.
*
* @param fabricCommandsBusTemplate
* the template topic for Fabric Manager commands to the neighbour.
*
* @param fabricFeedsBusTemplate
* the template topic for the Fabric message bus connection to the neighbour.
*
* @param fabricRegistryBusTemplate
* the template topic for the Fabric registry bus connection to the neighbour.
*
* @return the connection to the new neighbour.
*/
private NeighbourChannels connectNeighbour(NodeDescriptor neighbourDescriptor, String fabricCommandsBusTemplate,
String fabricFeedsBusTemplate, String fabricRegistryBusTemplate) {
/* To hold the connection object for the new neighbour */
NeighbourChannels newNeighbour = null;
try {
/* Connect to the node and open the channels */
SharedEndPoint neighbourEndPoint = connectNode(neighbourDescriptor);
if (neighbourEndPoint != null) {
/* Register to receive notifications about connectivity issues with this end point */
neighbourEndPoint.register(this);
/* Open the core set of channels for this node */
newNeighbour = new NeighbourChannels(neighbourDescriptor, neighbourEndPoint, fabricCommandsBusTemplate,
fabricFeedsBusTemplate, fabricRegistryBusTemplate, this);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Cannot connect to Fabric neighbour node {0}: {1}", new Object[] {
neighbourDescriptor, LogUtil.stackTrace(e)});
}
return newNeighbour;
}
/**
* @see fabric.bus.IBusIO#neighbourChannels(java.lang.String)
*/
@Override
public NeighbourChannels neighbourChannels(String id) {
return neighbourChannelsTable.get(id);
}
/**
* @see fabric.bus.IBusIO#connectedNeighbours()
*/
@Override
public NodeDescriptor[] connectedNeighbours() {
Set<NodeDescriptor> neighbours = neighbourChannelsTable.keySet();
return neighbours.toArray(new NodeDescriptor[0]);
}
/**
* @see fabric.bus.IBusIO#disconnectNeighbour(java.lang.String)
*/
@Override
public void disconnectNeighbour(String id) throws UnsupportedOperationException, IOException {
HashMap<NodeDescriptor, NeighbourChannels> neighbourChannelsTableCopy = (HashMap<NodeDescriptor, NeighbourChannels>) neighbourChannelsTable
.clone();
for (NodeDescriptor nodeDescriptor : neighbourChannelsTableCopy.keySet()) {
if (nodeDescriptor.name().equals(id)) {
disconnectNeighbour(nodeDescriptor, false);
}
}
}
/**
* @see fabric.bus.IBusIO#disconnectNeighbour(fabric.session.NodeDescriptor, boolean)
*/
@Override
public NeighbourChannels disconnectNeighbour(NodeDescriptor nodeDescriptor, boolean doRetry)
throws UnsupportedOperationException, IOException {
NeighbourChannels currentChannels = neighbourChannelsTable.remove(nodeDescriptor);
NeighbourChannels newChannels = null;
if (currentChannels != null) {
currentChannels.closeChannels();
disconnectNode(nodeDescriptor);
}
if (doRetry) {
newChannels = connectNeighbour(nodeDescriptor.name());
}
return newChannels;
}
/**
* @see fabric.bus.IBusIO#sendRawMessage(java.lang.String, byte[], boolean)
*/
@Override
public void sendRawMessage(String fullTopic, byte[] messageData, boolean isReplay) throws IOException {
/* Package the incoming resource message as a Fabric feed message */
IFeedMessage message = wrapRawMessage(messageData, isReplay);
message.metaSetTopic(fullTopic);
/* Republish the message onto the Fabric */
byte[] fabricMessageBytes = null;
try {
fabricMessageBytes = message.toWireBytes();
} catch (Exception e) {
logger.log(Level.WARNING,
"Internal error: cannot convert {0} to bytes, message cannot be pushed onto the bus: {1}",
new Object[] {FeedMessage.class.getName(), LogUtil.stackTrace(e)});
}
ioChannels.receiveBusChannel.write(fabricMessageBytes, new OutputTopic(ioChannels.receiveBus.name() + '/'
+ message.metaGetFeedDescriptor()));
}
/**
* @see fabric.bus.IBusIO#sendServiceMessage(fabric.bus.messages.IServiceMessage, java.lang.String)
*/
@Override
public void sendServiceMessage(IServiceMessage message, String node) throws Exception {
sendServiceMessage(message, new String[] {node});
}
/**
* @see fabric.bus.IBusIO#sendServiceMessage(fabric.bus.messages.IServiceMessage, java.lang.String[])
*/
@Override
public void sendServiceMessage(IServiceMessage message, String[] nodes) throws Exception {
/* For each node... */
for (int n = 0; nodes != null && n < nodes.length; n++) {
if (nodes[n].equalsIgnoreCase(homeNode())) {
ioChannels.sendCommandsChannel.write(message.toWireBytes());
} else {
/* Get the connection to the neighbour */
NeighbourChannels nodeConnection = connectNeighbour(nodes[n]);
/* If we have a connection to the neighbour... */
if (nodeConnection != null) {
/* Forward the message */
nodeConnection.commandBusChannel().write(message.toWireBytes());
} else {
logger.log(Level.WARNING, "No connection to node {0}, cannot send message", new Object[] {nodes[n]});
}
}
}
}
/**
* @see fabric.bus.IBusIO#sendFeedMessage(java.lang.String, java.lang.String, fabric.bus.messages.IFeedMessage,
* fabric.core.io.MessageQoS)
*/
@Override
public void sendFeedMessage(String node, String feedTopic, IFeedMessage message, MessageQoS qos) throws Exception {
/* Get the connection to the neighbour */
NeighbourChannels nodeConnection = connectNeighbour(node);
/* If we have a connection to the neighbour... */
if (nodeConnection != null) {
logger.log(Level.FINEST, "Sending feed {0} message to node {1}", new Object[] {feedTopic,
nodeConnection.neighbourDescriptor()});
String fullTopic = nodeConnection.outboundFeedBus().name() + '/' + feedTopic;
nodeConnection.feedBusChannel().write(message.toWireBytes(), new OutputTopic(fullTopic));
} else {
logger.log(Level.WARNING, "No connection to node {0}, cannot send feed message", node);
}
}
/**
* @see fabric.bus.IBusIO#deliverFeedMessage(java.lang.String, fabric.bus.messages.IFeedMessage,
* fabric.bus.feeds.impl.SubscriptionRecord, fabric.core.io.MessageQoS)
*/
@Override
public void deliverFeedMessage(String feedTopic, IFeedMessage message, SubscriptionRecord subscription,
MessageQoS qos) throws Exception {
String fullTopic = ioChannels.sendLocalSubscription.name() + '/' + subscription.actor() + '/'
+ subscription.actorPlatform() + '/' + subscription.feed().task() + '/' + feedTopic;
logger.log(Level.FINEST, "Delivering feed {0} message to client {1}, task {2} using topic {3}", new Object[] {
subscription.feed(), subscription.actor(), subscription.feed().task(), fullTopic});
ioChannels.sendLocalSubscriptionChannel.write(message.toWireBytes(), new OutputTopic(fullTopic));
}
/**
* @see fabric.bus.IBusIO#ioChannels()
*/
@Override
public BusIOChannels ioChannels() {
return ioChannels;
}
/**
* Gets the current handler for Fabric messages.
*
* @return the current handler.
*/
public BusMessageHandler getBusMessageHandler() {
return messageHandler;
}
/**
* Sets the handler for Fabric messages.
*
* @param messageHandler
* the handler.
*/
public void setBusMessageHandler(BusMessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
/**
* @see fabric.core.io.IEndPointCallback#endPointConnected(fabric.core.io.EndPoint)
*/
@Override
public void endPointConnected(EndPoint ep) {
/* No action required */
}
/**
* @see fabric.core.io.IEndPointCallback#endPointDisconnected(fabric.core.io.EndPoint)
*/
@Override
public void endPointDisconnected(EndPoint ep) {
/* No action required */
}
/**
* @see fabric.core.io.IEndPointCallback#endPointReconnected(fabric.core.io.EndPoint)
*/
@Override
public void endPointReconnected(EndPoint ep) {
/* No action required */
}
/**
* @see fabric.core.io.IEndPointCallback#endPointClosed(fabric.core.io.EndPoint)
*/
@Override
public void endPointClosed(EndPoint ep) {
/* No action required */
}
/**
* @see fabric.core.io.IEndPointCallback#endPointLost(fabric.core.io.EndPoint)
*/
@Override
public void endPointLost(EndPoint ep) {
try {
/* Clean up the end point */
SharedEndPoint sep = (SharedEndPoint) ep;
disconnectNeighbour(sep.node());
} catch (UnsupportedOperationException | IOException e) {
e.printStackTrace();
}
}
}
| fabric.lib/src/fabric/bus/impl/BusIO.java | /*
* Licensed Materials - Property of IBM
*
* (C) Copyright IBM Corp. 2007, 2014
*
* LICENSE: Eclipse Public License v1.0
* http://www.eclipse.org/legal/epl-v10.html
*/
package fabric.bus.impl;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import fabric.Fabric;
import fabric.FabricBus;
import fabric.FabricMetric;
import fabric.ServiceDescriptor;
import fabric.bus.BusIOChannels;
import fabric.bus.BusMessageHandler;
import fabric.bus.IBusIO;
import fabric.bus.NeighbourChannels;
import fabric.bus.SharedEndPoint;
import fabric.bus.feeds.impl.SubscriptionRecord;
import fabric.bus.messages.FabricMessageFactory;
import fabric.bus.messages.IFabricMessage;
import fabric.bus.messages.IFeedMessage;
import fabric.bus.messages.IMessagePayload;
import fabric.bus.messages.IServiceMessage;
import fabric.bus.messages.impl.FeedMessage;
import fabric.bus.messages.impl.MessagePayload;
import fabric.bus.messages.impl.ServiceMessage;
import fabric.core.io.EndPoint;
import fabric.core.io.ICallback;
import fabric.core.io.IEndPointCallback;
import fabric.core.io.InputTopic;
import fabric.core.io.Message;
import fabric.core.io.MessageQoS;
import fabric.core.io.OutputTopic;
import fabric.core.logging.LogUtil;
import fabric.core.properties.ConfigProperties;
import fabric.registry.FabricRegistry;
import fabric.registry.NodeIpMapping;
import fabric.registry.NodeNeighbour;
import fabric.services.floodmessage.FloodRouting;
import fabric.session.NodeDescriptor;
/**
* Class managing I/O on the Fabric bus.
* <p>
* This includes:
* <ul>
* <li>Placing messages onto the bus</li>
* <li>Moving messages across the bus</li>
* <li>Pulling messages off of the bus to fulfill user subscriptions</li>
* </ul>
*/
public class BusIO extends FabricBus implements IBusIO, ICallback, IEndPointCallback {
/** Copyright notice. */
public static final String copyrightNotice = "(C) Copyright IBM Corp. 2007, 2014";
/*
* Class fields
*/
/** The handler for Fabric messages */
private BusMessageHandler messageHandler = null;
/** The list of nodes neighbouring this Fabric Manager */
private final HashMap<NodeDescriptor, NeighbourChannels> neighbourChannelsTable = new HashMap<NodeDescriptor, NeighbourChannels>();
/** To hold the channels and topics used by the Fabric Manager */
private final BusIOChannels ioChannels = new BusIOChannels();
/** The template topic for sending Fabric Manager commands to a neighbouring node */
private String fabricCommandsBusTemplate = null;
/** The template topic for sending data feed message to a neighbouring node */
private String fabricFeedsBusTemplate = null;
/** The template topic for the Fabric registry bus connection to a neighbouring node */
private String fabricRegistryBusTemplate = null;
/** The UID of the next message to be published onto the Fabric */
private long fabricMessageUID = 0;
/*
* Class methods
*/
/**
* Constructs a new instance.
*/
public BusIO() {
super(Logger.getLogger("fabric.bus"));
initConfig();
}
/**
* Constructs a new instance.
*/
public BusIO(Logger logger) {
super(logger);
initConfig();
}
/**
* Initializes neighbour connection configuration.
*/
private void initConfig() {
fabricCommandsBusTemplate = config(ConfigProperties.TOPIC_SEND_SESSION_COMMANDS,
ConfigProperties.TOPIC_SEND_SESSION_COMMANDS_DEFAULT);
fabricFeedsBusTemplate = config(ConfigProperties.TOPIC_FEEDS_BUS, ConfigProperties.TOPIC_FEEDS_BUS_DEFAULT);
fabricRegistryBusTemplate = config(ConfigProperties.REGISTRY_COMMAND_TOPIC,
ConfigProperties.REGISTRY_COMMAND_TOPIC_DEFAULT);
}
/**
* Opens the required channels to the local broker.
*/
public void openHomeNodeChannels() {
try {
logger.log(Level.FINE, "Fabric connecting on node {0} at address {1}:{2}", new Object[] {homeNode(),
homeNodeEndPoint().ipName(), homeNodeEndPoint().ipPort()});
/*
* Connect to the local node and open the ports
*/
/* The topic on which the Fabric Manager listens for commands */
ioChannels.receiveCommands = new InputTopic(config(ConfigProperties.TOPIC_SEND_SESSION_COMMANDS,
ConfigProperties.TOPIC_SEND_SESSION_COMMANDS_DEFAULT, homeNode()));
ioChannels.receiveCommandsChannel = homeNodeEndPoint().openInputChannel(ioChannels.receiveCommands, this);
logger.log(Level.FINER, "Listening on: {0}", ioChannels.receiveCommands);
/* The topic on which the Fabric Manager sends commands */
ioChannels.sendCommands = new OutputTopic(config(ConfigProperties.TOPIC_SEND_SESSION_COMMANDS,
ConfigProperties.TOPIC_SEND_SESSION_COMMANDS_DEFAULT, homeNode()));
ioChannels.sendCommandsChannel = homeNodeEndPoint().openOutputChannel(ioChannels.sendCommands);
logger.log(Level.FINER, "Commands will be sent to: {0}", ioChannels.sendCommands);
/*
* The channel on which the Fabric Manager publishes commands to locally attached clients (note that the
* client-specific topic must be provided when this channel is used)
*/
ioChannels.sendClientCommandsChannel = homeNodeEndPoint().openOutputChannel();
logger.log(Level.FINER, "Client commands will be sent via channel: {0}",
ioChannels.sendClientCommandsChannel);
/* The channel on which the Fabric Manager publishes commands to locally attached platforms */
ioChannels.sendPlatformCommandsChannel = homeNodeEndPoint().openOutputChannel();
logger.log(Level.FINER, "Platform commands will be sent via channel: {0}",
ioChannels.sendPlatformCommandsChannel);
/* The channel on which the Fabric Manager publishes commands to locally attached services */
ioChannels.sendServiceCommandsChannel = homeNodeEndPoint().openOutputChannel(ioChannels.sendCommands);
logger.log(Level.FINER, "System commands will be sent to: {0}", ioChannels.sendCommands);
/* The topic on which the Fabric Manager listens for locally connected data feeds */
ioChannels.receiveLocalFeeds = new InputTopic(config("fabric.feeds.onramp", null, homeNode()));
ioChannels.receiveLocalFeedsChannel = homeNodeEndPoint().openInputChannel(
new InputTopic(ioChannels.receiveLocalFeeds + "/#"), this);
logger.log(Level.FINER, "Listening for locally connected data feeds on: {0}", ioChannels.receiveLocalFeeds
+ "/#");
/* The topic on which the Fabric Manager listens for messages en route across the Fabric */
ioChannels.receiveBus = new InputTopic(config(ConfigProperties.TOPIC_FEEDS_BUS,
ConfigProperties.TOPIC_FEEDS_BUS_DEFAULT, homeNode()));
ioChannels.receiveBusChannel = homeNodeEndPoint().openInputChannel(
new InputTopic(ioChannels.receiveBus + "/#"), this);
logger.log(Level.FINER, "Listening for bus data feed messages on: {0}", ioChannels.receiveBus + "/#");
/* The topic on which the Fabric Manager listens for local replay messages */
ioChannels.receiveLocalReplayFeeds = new InputTopic(config("fabric.feeds.replay", null, homeNode()));
ioChannels.receiveLocalReplayFeedsChannel = homeNodeEndPoint().openInputChannel(
new InputTopic(ioChannels.receiveLocalReplayFeeds + "/#"), this);
logger.log(Level.FINER, "Listening for local replay messages on: {0}", ioChannels.receiveLocalReplayFeeds
+ "/#");
/* The topic on which the Fabric Manager listens for last will and testament messages */
ioChannels.connectionComands = new InputTopic(config("fabric.commands.topology", null, "+"));
ioChannels.connectionCommandsChannel = homeNodeEndPoint().openInputChannel(ioChannels.connectionComands,
this);
logger.log(Level.FINER, "Listening for LWT messages on: {0}", ioChannels.connectionComands);
/* The topic on which the Fabric Manager publishes messages for local consumption */
ioChannels.sendLocalSubscription = new OutputTopic(config("fabric.feeds.offramp", null, homeNode()));
ioChannels.sendLocalSubscriptionChannel = homeNodeEndPoint().openOutputChannel(
ioChannels.sendLocalSubscription);
logger.log(Level.FINER, "Delivered messages will be sent to: {0}", ioChannels.sendLocalSubscription);
} catch (Exception e) {
logger.log(Level.SEVERE, "Cannot set up publish and/or subscribe topics with broker:", e);
}
}
/**
* @see fabric.core.io.ICallback#startCallback(java.lang.Object)
*/
@Override
public void startCallback(Object arg1) {
/* Unused */
}
/**
* @see fabric.core.io.ICallback#handleMessage(fabric.core.io.Message)
*/
@Override
public synchronized void handleMessage(Message message) {
logger.log(Level.FINER, "Handling message from topic \"{0}\":\n{1}", new Object[] {message.topic,
new String((message.data != null) ? message.data : new byte[0])});
String messageTopic = (String) message.topic;
byte[] messageData = message.data;
String messageString = new String(messageData);
/* Instrumentation */
FabricMetric metric = null;
if (doInstrument()) {
metric = new FabricMetric(homeNode(), null, null, null, null, -1, messageData, null);
metrics().startTiming(metric, FabricMetric.EVENT_NODE_PROCESSING_START);
}
try {
/* If this is a local message from a source attached directly to the node... */
if (messageTopic.startsWith(ioChannels.receiveLocalFeeds.name())) {
String feedTopic = ServiceDescriptor.extract(messageTopic);
if (feedTopic.startsWith("$")) {
try {
floodFeedMessage(feedTopic, message.data);
} catch (Exception e) {
logger.log(Level.SEVERE, "Failed publish virtual service message", e);
}
} else {
sendRawMessage(messageTopic, message.data, false);
}
}
/* Else if it's a local replay message from a source attached directly to the node... */
else if (messageTopic.startsWith(ioChannels.receiveLocalReplayFeeds.name())) {
sendRawMessage(messageTopic, message.data, true);
}
/* Else this should be a message that we can parse */
else {
IFabricMessage parsedMessage = null;
try {
/* Parse the message */
parsedMessage = FabricMessageFactory.create(messageTopic, messageData);
} catch (Exception e) {
logger.log(Level.INFO, "Improperly formatted message received on topic {0}: {1}", new Object[] {
messageTopic, messageString});
logger.log(Level.WARNING, "Exception:", e);
}
/* If this is a Fabric feed message... */
if (parsedMessage instanceof IFeedMessage) {
messageHandler.handleFeedMessage((IFeedMessage) parsedMessage);
}
/* Else if this is a Fabric service message... */
else if (parsedMessage instanceof IServiceMessage) {
logger.log(Level.FINEST, "Service message recevied on topic {0}: {1}", new Object[] {messageTopic,
parsedMessage.toString()});
messageHandler.handleServiceMessage((ServiceMessage) parsedMessage);
}
/* Else if this is any other kind of Fabric message... */
else if (parsedMessage != null) {
logger.log(Level.WARNING, "Unsupported Fabric message recevied on topic {0}: {1}", new Object[] {
messageTopic, parsedMessage.toString()});
}
/*
* Else if it's an improperly formatted last will and testament message (any thing on this topic should
* be an IConnectionMessage)...
*/
else if (messageTopic.startsWith(ioChannels.connectionComands.name())) {
logger.log(Level.FINE,
"Ignoring improperly formatted connection status (last-will-and-testament) message");
} else {
logger.log(Level.FINE, "Ignoring improperly formatted message");
}
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception handling message received on topic \"{0}\":\n{1}\n{2}", new Object[] {
messageTopic, messageString, LogUtil.stackTrace(e)});
} finally {
if (doInstrument()) {
metrics().endTiming(metric, FabricMetric.EVENT_NODE_PROCESSING_STOP);
}
}
}
/**
* Builds and sends a flood message to distribute a virtual feed message across the Fabric.
*
* @param feedTopic
* the topic to which the message will be delivered on each node.
*
* @param messageData
* the message payload.
*
* @throws Exception
*/
private void floodFeedMessage(String feedTopic, byte[] messageData) throws Exception {
ServiceMessage serviceMessage = new ServiceMessage();
serviceMessage.setServiceFamilyName(Fabric.FABRIC_PLUGIN_FAMILY);
serviceMessage.setActionEnRoute(true);
serviceMessage.setNotification(false);
serviceMessage.setCorrelationID(FabricMessageFactory.generateUID());
serviceMessage.setServiceName("fabric.services.proxypublisher.ProxyPublisherService");
serviceMessage.setAction(IServiceMessage.ACTION_PUBLISH_ON_NODE);
serviceMessage.setEvent(IServiceMessage.EVENT_ACTOR_REQUEST);
serviceMessage.setProperty(IServiceMessage.PROPERTY_DELIVER_TO_FEED, feedTopic);
IMessagePayload messagePayload = new MessagePayload();
messagePayload.setPayloadBytes(messageData);
serviceMessage.setPayload(messagePayload);
serviceMessage.setRouting(new FloodRouting(homeNode()));
try {
ioChannels.sendServiceCommandsChannel.write(serviceMessage.toWireBytes());
} catch (Exception e) {
logger.log(Level.WARNING,
"Internal error: cannot convert {0} to bytes, message cannot be pushed onto the bus",
FeedMessage.class.getName());
logger.log(Level.WARNING, "Internal error: ", e);
}
}
/**
* @see fabric.core.io.ICallback#cancelCallback(java.lang.Object)
*/
@Override
public void cancelCallback(Object arg1) {
/* Unused */
}
/**
* @see fabric.bus.IBusIO#nodeName()
*/
@Override
public String nodeName() {
return homeNode();
}
/**
* @see fabric.bus.IBusIO#connectNeighbour(java.lang.String)
*/
@Override
public NeighbourChannels connectNeighbour(String neighbour) {
NeighbourChannels neighbourChannels = null;
NodeDescriptor nodeDescriptor = createDescriptor(neighbour);
while (neighbourChannels == null && nodeDescriptor != null) {
/* Get the the existing Fabric connection to the node */
neighbourChannels = neighbourChannelsTable.get(nodeDescriptor);
/* If we don't currently have a connection to the neighbour... */
if (neighbourChannels == null) {
logger.log(Level.FINER, "Attempting to connect to potential new neighbour {0}", neighbour);
/* Connect to the neighbour */
neighbourChannels = connectNeighbour(nodeDescriptor, fabricCommandsBusTemplate, fabricFeedsBusTemplate,
fabricRegistryBusTemplate);
/* If the connection was successful... */
if (neighbourChannels != null) {
logger.log(Level.FINER, "Connected to new neighbour: {0}", neighbour);
neighbourChannelsTable.put(nodeDescriptor, neighbourChannels);
} else {
/* Mark this nodeDescriptor as unavailable */
FabricRegistry.getNodeNeighbourFactory(true).markUnavailable(homeNode(), nodeDescriptor);
/*
* Move onto next possible nodeDescriptor, previous one should be marked unavailable and not
* returned.
*/
nodeDescriptor = createDescriptor(neighbour);
}
/*
* Reset all static neighbours to available - nothing else currently does this and we should retry them
* again next time.
*/
FabricRegistry.getNodeNeighbourFactory(true).markStaticNeighboursAsAvailable(homeNode());
}
}
if (nodeDescriptor == null) {
logger.log(Level.WARNING, "Could not connect to potential new neighbour \"{0}\"; node details not found",
neighbour);
}
return neighbourChannels;
}
/**
* Determines the node descriptor for the specified node name.
* <p>
* The method will determine the network interface to be used based upon the order given in the
* <code>ConfigProperties.NODE_INTERFACES</code> configuration property.
* </p>
*
* @param neighbourId
* the Fabric name of the node to which a connection is being made.
*
* @return the descriptor.
*/
private NodeDescriptor createDescriptor(String neighbourId) {
NodeDescriptor nodeDescriptor = null;
/* Establish possible Neighbour Entries from Node_Neighbours */
NodeNeighbour[] neighbours = FabricRegistry.getNodeNeighbourFactory(true).getAvailableNeighboursEntries(
homeNode(), neighbourId);
String[] interfaces = config()
.getProperty(ConfigProperties.NODE_INTERFACES, NodeDescriptor.loopbackInterface()).split(",");
int i = 0;
// Loop in order of local interfaces configured
while (nodeDescriptor == null && i < interfaces.length) {
String localInterface = interfaces[i];
// Loop through neighbours for a match
int j = 0;
while (nodeDescriptor == null && j < neighbours.length) {
NodeNeighbour neighbour = neighbours[j];
if (neighbour.getNodeInterface().equals(localInterface)) {
NodeIpMapping nodeIPMapping = neighbour.getIpMappingForNeighbour();
nodeDescriptor = new NodeDescriptor(nodeIPMapping);
}
j++;
}
i++;
}
return nodeDescriptor;
}
/**
* Connect to a specific neighbouring Fabric node.
*
* @param neighbourDescriptor
* the neighbour to which a connection is to be made.
*
* @param fabricCommandsBusTemplate
* the template topic for Fabric Manager commands to the neighbour.
*
* @param fabricFeedsBusTemplate
* the template topic for the Fabric message bus connection to the neighbour.
*
* @param fabricRegistryBusTemplate
* the template topic for the Fabric registry bus connection to the neighbour.
*
* @return the connection to the new neighbour.
*/
private NeighbourChannels connectNeighbour(NodeDescriptor neighbourDescriptor, String fabricCommandsBusTemplate,
String fabricFeedsBusTemplate, String fabricRegistryBusTemplate) {
/* To hold the connection object for the new neighbour */
NeighbourChannels newNeighbour = null;
try {
/* Connect to the node and open the channels */
SharedEndPoint neighbourEndPoint = connectNode(neighbourDescriptor);
if (neighbourEndPoint != null) {
/* Register to receive notifications about connectivity issues with this end point */
neighbourEndPoint.register(this);
/* Open the core set of channels for this node */
newNeighbour = new NeighbourChannels(neighbourDescriptor, neighbourEndPoint, fabricCommandsBusTemplate,
fabricFeedsBusTemplate, fabricRegistryBusTemplate, this);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Cannot connect to Fabric neighbour node {0}: {1}", new Object[] {
neighbourDescriptor, LogUtil.stackTrace(e)});
}
return newNeighbour;
}
/**
* @see fabric.bus.IBusIO#neighbourChannels(java.lang.String)
*/
@Override
public NeighbourChannels neighbourChannels(String id) {
return neighbourChannelsTable.get(id);
}
/**
* @see fabric.bus.IBusIO#connectedNeighbours()
*/
@Override
public NodeDescriptor[] connectedNeighbours() {
Set<NodeDescriptor> neighbours = neighbourChannelsTable.keySet();
return neighbours.toArray(new NodeDescriptor[0]);
}
/**
* @see fabric.bus.IBusIO#disconnectNeighbour(java.lang.String)
*/
@Override
public void disconnectNeighbour(String id) throws UnsupportedOperationException, IOException {
HashMap<NodeDescriptor, NeighbourChannels> neighbourChannelsTableCopy = (HashMap<NodeDescriptor, NeighbourChannels>) neighbourChannelsTable
.clone();
for (NodeDescriptor nodeDescriptor : neighbourChannelsTableCopy.keySet()) {
if (nodeDescriptor.name().equals(id)) {
disconnectNeighbour(nodeDescriptor, false);
}
}
}
/**
* @see fabric.bus.IBusIO#disconnectNeighbour(fabric.session.NodeDescriptor, boolean)
*/
@Override
public NeighbourChannels disconnectNeighbour(NodeDescriptor nodeDescriptor, boolean doRetry)
throws UnsupportedOperationException, IOException {
NeighbourChannels currentChannels = neighbourChannelsTable.remove(nodeDescriptor);
NeighbourChannels newChannels = null;
if (currentChannels != null) {
currentChannels.closeChannels();
disconnectNode(nodeDescriptor);
}
if (doRetry) {
newChannels = connectNeighbour(nodeDescriptor.name());
}
return newChannels;
}
/**
* @see fabric.bus.IBusIO#sendRawMessage(java.lang.String, byte[], boolean)
*/
@Override
public void sendRawMessage(String fullTopic, byte[] messageData, boolean isReplay) throws IOException {
/* Package the incoming resource message as a Fabric feed message */
IFeedMessage message = wrapRawMessage(messageData, isReplay);
message.metaSetTopic(fullTopic);
/* Republish the message onto the Fabric */
byte[] fabricMessageBytes = null;
try {
fabricMessageBytes = message.toWireBytes();
} catch (Exception e) {
logger.log(Level.WARNING,
"Internal error: cannot convert {0} to bytes, message cannot be pushed onto the bus: {1}",
new Object[] {FeedMessage.class.getName(), LogUtil.stackTrace(e)});
}
ioChannels.receiveBusChannel.write(fabricMessageBytes, new OutputTopic(ioChannels.receiveBus.name() + '/'
+ message.metaGetFeedDescriptor()));
}
/**
* @see fabric.bus.IBusIO#sendServiceMessage(fabric.bus.messages.IServiceMessage, java.lang.String)
*/
@Override
public void sendServiceMessage(IServiceMessage message, String node) throws Exception {
sendServiceMessage(message, new String[] {node});
}
/**
* @see fabric.bus.IBusIO#sendServiceMessage(fabric.bus.messages.IServiceMessage, java.lang.String[])
*/
@Override
public void sendServiceMessage(IServiceMessage message, String[] nodes) throws Exception {
/* For each node... */
for (int n = 0; nodes != null && n < nodes.length; n++) {
if (nodes[n].equalsIgnoreCase(homeNode())) {
ioChannels.sendCommandsChannel.write(message.toWireBytes());
} else {
/* Get the connection to the neighbour */
NeighbourChannels nodeConnection = connectNeighbour(nodes[n]);
/* If we have a connection to the neighbour... */
if (nodeConnection != null) {
/* Forward the message */
nodeConnection.commandBusChannel().write(message.toWireBytes());
} else {
logger.log(Level.WARNING, "No connection to node {0}, cannot send message", new Object[] {nodes[n]});
}
}
}
}
/**
* @see fabric.bus.IBusIO#sendFeedMessage(java.lang.String, java.lang.String, fabric.bus.messages.IFeedMessage,
* fabric.core.io.MessageQoS)
*/
@Override
public void sendFeedMessage(String node, String feedTopic, IFeedMessage message, MessageQoS qos) throws Exception {
/* Get the connection to the neighbour */
NeighbourChannels nodeConnection = connectNeighbour(node);
/* If we have a connection to the neighbour... */
if (nodeConnection != null) {
logger.log(Level.FINEST, "Sending feed {0} message to node {1}", new Object[] {feedTopic,
nodeConnection.neighbourDescriptor()});
String fullTopic = nodeConnection.outboundFeedBus().name() + '/' + feedTopic;
nodeConnection.feedBusChannel().write(message.toWireBytes(), new OutputTopic(fullTopic));
} else {
logger.log(Level.WARNING, "No connection to node {0}, cannot send feed message", node);
}
}
/**
* @see fabric.bus.IBusIO#deliverFeedMessage(java.lang.String, fabric.bus.messages.IFeedMessage,
* fabric.bus.feeds.impl.SubscriptionRecord, fabric.core.io.MessageQoS)
*/
@Override
public void deliverFeedMessage(String feedTopic, IFeedMessage message, SubscriptionRecord subscription,
MessageQoS qos) throws Exception {
String fullTopic = ioChannels.sendLocalSubscription.name() + '/' + subscription.actor() + '/'
+ subscription.actorPlatform() + '/' + subscription.feed().task() + '/' + feedTopic;
logger.log(Level.FINEST, "Delivering feed {0} message to client {1}, task {2} using topic {3}", new Object[] {
subscription.feed(), subscription.actor(), subscription.feed().task(), fullTopic});
ioChannels.sendLocalSubscriptionChannel.write(message.toWireBytes(), new OutputTopic(fullTopic));
}
/**
* @see fabric.bus.IBusIO#ioChannels()
*/
@Override
public BusIOChannels ioChannels() {
return ioChannels;
}
/**
* Gets the current handler for Fabric messages.
*
* @return the current handler.
*/
public BusMessageHandler getBusMessageHandler() {
return messageHandler;
}
/**
* Sets the handler for Fabric messages.
*
* @param messageHandler
* the handler.
*/
public void setBusMessageHandler(BusMessageHandler messageHandler) {
this.messageHandler = messageHandler;
}
/**
* @see fabric.core.io.IEndPointCallback#endPointConnected(fabric.core.io.EndPoint)
*/
@Override
public void endPointConnected(EndPoint ep) {
/* No action required */
}
/**
* @see fabric.core.io.IEndPointCallback#endPointDisconnected(fabric.core.io.EndPoint)
*/
@Override
public void endPointDisconnected(EndPoint ep) {
/* No action required */
}
/**
* @see fabric.core.io.IEndPointCallback#endPointReconnected(fabric.core.io.EndPoint)
*/
@Override
public void endPointReconnected(EndPoint ep) {
/* No action required */
}
/**
* @see fabric.core.io.IEndPointCallback#endPointClosed(fabric.core.io.EndPoint)
*/
@Override
public void endPointClosed(EndPoint ep) {
/* No action required */
}
/**
* @see fabric.core.io.IEndPointCallback#endPointLost(fabric.core.io.EndPoint)
*/
@Override
public void endPointLost(EndPoint ep) {
try {
/* Clean up the end point */
SharedEndPoint sep = (SharedEndPoint) ep;
disconnectNeighbour(sep.node());
} catch (UnsupportedOperationException | IOException e) {
e.printStackTrace();
}
}
}
| Changes to logging levels for badly formatted bus messages. | fabric.lib/src/fabric/bus/impl/BusIO.java | Changes to logging levels for badly formatted bus messages. |
|
Java | epl-1.0 | 2ed918525e8031ee2c0db03517f5e099377fa851 | 0 | subclipse/subclipse,subclipse/subclipse,subclipse/subclipse | /*******************************************************************************
* Copyright (c) 2005, 2006 Subclipse project 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:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.ui.dialogs;
import java.util.Date;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.tigris.subversion.subclipse.core.ISVNRemoteFile;
import org.tigris.subversion.subclipse.core.ISVNRemoteResource;
import org.tigris.subversion.subclipse.core.SVNProviderPlugin;
import org.tigris.subversion.subclipse.ui.IHelpContextIds;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
import org.tigris.subversion.svnclientadapter.ISVNInfo;
import org.tigris.subversion.svnclientadapter.ISVNProperty;
public class RemoteResourcePropertiesDialog extends TrayDialog {
private ISVNRemoteResource remoteResource;
private ISVNInfo svnInfo;
private ISVNProperty[] properties;
private String errorMessage;
private ColumnLayoutData columnLayouts[] = {
new ColumnWeightData(75, 75, true),
new ColumnWeightData(200, 200, true)};
private String columnHeaders[] = {
Policy.bind("RemoteResourcePropertiesDialog.property"),
Policy.bind("RemoteResourcePropertiesDialog.value")
};
public RemoteResourcePropertiesDialog(Shell parentShell, ISVNRemoteResource remoteResource) {
super(parentShell);
setShellStyle(SWT.CLOSE | SWT.TITLE | SWT.RESIZE);
this.remoteResource = remoteResource;
}
protected Control createDialogArea(Composite parent) {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().createSVNClient();
SVNProviderPlugin.disableConsoleLogging();
svnInfo = client.getInfo(remoteResource.getUrl());
properties = client.getProperties(remoteResource.getUrl());
SVNProviderPlugin.enableConsoleLogging();
} catch (Exception e) {
errorMessage = e.getMessage();
SVNProviderPlugin.enableConsoleLogging();
}
}
});
getShell().setText(Policy.bind("RemoteResourcePropertiesDialog.title")); //$NON-NLS-1$
Composite composite = new Composite(parent, SWT.NULL);
GridLayout gridLayout = new GridLayout();
gridLayout.marginTop = 5;
gridLayout.marginWidth = 10;
gridLayout.numColumns = 2;
composite.setLayout(gridLayout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
if (svnInfo == null) {
Text errorText = new Text(composite, SWT.V_SCROLL | SWT.WRAP | SWT.READ_ONLY);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
data.widthHint = 600;
data.heightHint = 100;
errorText.setLayoutData(data);
errorText.setEditable(false);
errorText.setText(errorMessage);
errorText.setBackground(composite.getBackground());
return composite;
}
Label urlLabel = new Label(composite, SWT.NONE);
urlLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.url"));
Text urlText = new Text(composite, SWT.READ_ONLY);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
data.widthHint = 600;
urlText.setLayoutData(data);
urlText.setEditable(false);
urlText.setText(remoteResource.getUrl().toString());
urlText.setBackground(composite.getBackground());
Label authorLabel = new Label(composite, SWT.NONE);
authorLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.author"));
Text authorText = new Text(composite, SWT.READ_ONLY);
authorText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
authorText.setEditable(false);
authorText.setText(svnInfo.getLastCommitAuthor());
authorText.setBackground(composite.getBackground());
Label revisionLabel = new Label(composite, SWT.NONE);
revisionLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.revision"));
Text revisionText = new Text(composite, SWT.READ_ONLY);
revisionText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
revisionText.setEditable(false);
revisionText.setText(svnInfo.getLastChangedRevision().toString());
revisionText.setBackground(composite.getBackground());
Label dateLabel = new Label(composite, SWT.NONE);
dateLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.date"));
Text dateText = new Text(composite, SWT.READ_ONLY);
dateText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
dateText.setEditable(false);
dateText.setText(svnInfo.getLastChangedDate().toString());
dateText.setBackground(composite.getBackground());
if (remoteResource instanceof ISVNRemoteFile) {
String lockOwner = null;
try {
lockOwner = svnInfo.getLockOwner();
} catch (Exception e) {
}
if (lockOwner != null) {
Label lockOwnerLabel = new Label(composite, SWT.NONE);
lockOwnerLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.lockOwner"));
Text lockOwnerText = new Text(composite, SWT.READ_ONLY);
data = new GridData(SWT.FILL, SWT.FILL, true, false);
data.widthHint = 600;
lockOwnerText.setLayoutData(data);
lockOwnerText.setEditable(false);
lockOwnerText.setText(svnInfo.getLockOwner());
lockOwnerText.setBackground(composite.getBackground());
}
Date lockCreationDate = null;
try {
lockCreationDate = svnInfo.getLockCreationDate();
} catch (Exception e) {
}
if (lockCreationDate != null) {
Label lockCreatedLabel = new Label(composite, SWT.NONE);
lockCreatedLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.lockCreated"));
Text lockCreatedText = new Text(composite, SWT.READ_ONLY);
data = new GridData(SWT.FILL, SWT.FILL, true, false);
data.widthHint = 600;
lockCreatedText.setLayoutData(data);
lockCreatedText.setEditable(false);
lockCreatedText.setText(svnInfo.getLockCreationDate().toString());
lockCreatedText.setBackground(composite.getBackground());
}
String lockComment = null;
try {
lockComment = svnInfo.getLockComment();
} catch (Exception e) {
}
if (lockComment != null) {
Label lockCommentLabel = new Label(composite, SWT.NONE);
lockCommentLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
lockCommentLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.lockComment"));
Text lockCommentText = new Text(composite, SWT.V_SCROLL | SWT.WRAP | SWT.READ_ONLY);
GridData lockCommentTextData = new GridData(SWT.FILL, SWT.FILL, true, false);
lockCommentTextData.heightHint = 100;
lockCommentTextData.widthHint = 600;
lockCommentText.setLayoutData(lockCommentTextData);
lockCommentText.setEditable(false);
lockCommentText.setText(svnInfo.getLockComment());
lockCommentText.setBackground(composite.getBackground());
}
}
// Group propertyGroup = new Group(composite, SWT.NULL);
// propertyGroup.setText(Policy.bind("RemoteResourcePropertiesDialog.properties")); //$NON-NLS-1$
// propertyGroup.setLayout(new GridLayout());
// propertyGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
Table table = new Table(composite, SWT.BORDER);
table.setLinesVisible(true);
TableViewer viewer = new TableViewer(table);
viewer.setUseHashlookup(true);
TableLayout tableLayout = new TableLayout();
table.setLayout(tableLayout);
table.setHeaderVisible(true);
for (int i = 0; i < columnHeaders.length; i++) {
tableLayout.addColumnData(columnLayouts[i]);
TableColumn tc = new TableColumn(table, SWT.NONE,i);
tc.setResizable(columnLayouts[i].resizable);
tc.setText(columnHeaders[i]);
}
data = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
data.verticalIndent = 5;
data.heightHint = 150;
table.setLayoutData(data);
viewer.setContentProvider(new RemoteResourceContentProvider());
viewer.setLabelProvider(new RemoteResourceLabelProvider());
viewer.setInput(remoteResource);
// set f1 help
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.REMOTE_RESOURCE_PROPERTIES_DIALOG);
return composite;
}
class RemoteResourceContentProvider implements IStructuredContentProvider {
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public Object[] getElements(Object arg0) {
return properties;
}
}
class RemoteResourceLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object element, int columnIndex) {
if ((columnIndex >= 0) && (columnIndex <= 1)) {
ISVNProperty property = (ISVNProperty)element;
switch (columnIndex) {
case 0: return property.getName();
case 1: return property.getValue();
default: return "";
}
}
return "";
}
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
}
}
| org.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/dialogs/RemoteResourcePropertiesDialog.java | /*******************************************************************************
* Copyright (c) 2005, 2006 Subclipse project 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:
* Subclipse project committers - initial API and implementation
******************************************************************************/
package org.tigris.subversion.subclipse.ui.dialogs;
import java.util.Date;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.tigris.subversion.subclipse.core.ISVNRemoteFile;
import org.tigris.subversion.subclipse.core.ISVNRemoteResource;
import org.tigris.subversion.subclipse.core.SVNProviderPlugin;
import org.tigris.subversion.subclipse.ui.IHelpContextIds;
import org.tigris.subversion.subclipse.ui.Policy;
import org.tigris.subversion.svnclientadapter.ISVNClientAdapter;
import org.tigris.subversion.svnclientadapter.ISVNInfo;
import org.tigris.subversion.svnclientadapter.ISVNProperty;
public class RemoteResourcePropertiesDialog extends TrayDialog {
private ISVNRemoteResource remoteResource;
private ISVNInfo svnInfo;
private ISVNProperty[] properties;
private String errorMessage;
private ColumnLayoutData columnLayouts[] = {
new ColumnWeightData(75, 75, true),
new ColumnWeightData(200, 200, true)};
private String columnHeaders[] = {
Policy.bind("RemoteResourcePropertiesDialog.property"),
Policy.bind("RemoteResourcePropertiesDialog.value")
};
public RemoteResourcePropertiesDialog(Shell parentShell, ISVNRemoteResource remoteResource) {
super(parentShell);
setShellStyle(SWT.CLOSE | SWT.TITLE | SWT.RESIZE);
this.remoteResource = remoteResource;
}
protected Control createDialogArea(Composite parent) {
BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {
public void run() {
try {
ISVNClientAdapter client = SVNProviderPlugin.getPlugin().getSVNClientManager().createSVNClient();
SVNProviderPlugin.disableConsoleLogging();
svnInfo = client.getInfo(remoteResource.getUrl());
properties = client.getProperties(remoteResource.getUrl());
SVNProviderPlugin.enableConsoleLogging();
} catch (Exception e) {
errorMessage = e.getMessage();
SVNProviderPlugin.enableConsoleLogging();
}
}
});
getShell().setText(Policy.bind("RemoteResourcePropertiesDialog.title")); //$NON-NLS-1$
Composite composite = new Composite(parent, SWT.NULL);
GridLayout gridLayout = new GridLayout();
gridLayout.marginTop = 5;
gridLayout.marginWidth = 10;
gridLayout.numColumns = 2;
composite.setLayout(gridLayout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
if (svnInfo == null) {
Text errorText = new Text(composite, SWT.V_SCROLL | SWT.WRAP);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
data.widthHint = 600;
data.heightHint = 100;
errorText.setLayoutData(data);
errorText.setEditable(false);
errorText.setText(errorMessage);
errorText.setBackground(composite.getBackground());
return composite;
}
Label urlLabel = new Label(composite, SWT.NONE);
urlLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.url"));
Text urlText = new Text(composite, SWT.NONE);
GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false);
data.widthHint = 600;
urlText.setLayoutData(data);
urlText.setEditable(false);
urlText.setText(remoteResource.getUrl().toString());
urlText.setBackground(composite.getBackground());
Label authorLabel = new Label(composite, SWT.NONE);
authorLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.author"));
Text authorText = new Text(composite, SWT.NONE);
authorText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
authorText.setEditable(false);
authorText.setText(svnInfo.getLastCommitAuthor());
authorText.setBackground(composite.getBackground());
Label revisionLabel = new Label(composite, SWT.NONE);
revisionLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.revision"));
Text revisionText = new Text(composite, SWT.NONE);
revisionText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
revisionText.setEditable(false);
revisionText.setText(svnInfo.getLastChangedRevision().toString());
revisionText.setBackground(composite.getBackground());
Label dateLabel = new Label(composite, SWT.NONE);
dateLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.date"));
Text dateText = new Text(composite, SWT.NONE);
dateText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
dateText.setEditable(false);
dateText.setText(svnInfo.getLastChangedDate().toString());
dateText.setBackground(composite.getBackground());
if (remoteResource instanceof ISVNRemoteFile) {
String lockOwner = null;
try {
lockOwner = svnInfo.getLockOwner();
} catch (Exception e) {
}
if (lockOwner != null) {
Label lockOwnerLabel = new Label(composite, SWT.NONE);
lockOwnerLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.lockOwner"));
Text lockOwnerText = new Text(composite, SWT.NONE);
data = new GridData(SWT.FILL, SWT.CENTER, true, false);
data.widthHint = 600;
lockOwnerText.setLayoutData(data);
lockOwnerText.setEditable(false);
lockOwnerText.setText(svnInfo.getLockOwner());
lockOwnerText.setBackground(composite.getBackground());
}
Date lockCreationDate = null;
try {
lockCreationDate = svnInfo.getLockCreationDate();
} catch (Exception e) {
}
if (lockCreationDate != null) {
Label lockCreatedLabel = new Label(composite, SWT.NONE);
lockCreatedLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.lockCreated"));
Text lockCreatedText = new Text(composite, SWT.NONE);
data = new GridData(SWT.FILL, SWT.CENTER, true, false);
data.widthHint = 600;
lockCreatedText.setLayoutData(data);
lockCreatedText.setEditable(false);
lockCreatedText.setText(svnInfo.getLockCreationDate().toString());
lockCreatedText.setBackground(composite.getBackground());
}
String lockComment = null;
try {
lockComment = svnInfo.getLockComment();
} catch (Exception e) {
}
if (lockComment != null) {
Label lockCommentLabel = new Label(composite, SWT.NONE);
lockCommentLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
lockCommentLabel.setText(Policy.bind("RemoteResourcePropertiesDialog.lockComment"));
Text lockCommentText = new Text(composite, SWT.V_SCROLL | SWT.WRAP);
GridData lockCommentTextData = new GridData(SWT.FILL, SWT.TOP, true, false);
lockCommentTextData.heightHint = 100;
lockCommentTextData.widthHint = 600;
lockCommentText.setLayoutData(lockCommentTextData);
lockCommentText.setEditable(false);
lockCommentText.setText(svnInfo.getLockComment());
lockCommentText.setBackground(composite.getBackground());
}
}
// Group propertyGroup = new Group(composite, SWT.NULL);
// propertyGroup.setText(Policy.bind("RemoteResourcePropertiesDialog.properties")); //$NON-NLS-1$
// propertyGroup.setLayout(new GridLayout());
// propertyGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
Table table = new Table(composite, SWT.BORDER);
table.setLinesVisible(true);
TableViewer viewer = new TableViewer(table);
viewer.setUseHashlookup(true);
TableLayout tableLayout = new TableLayout();
table.setLayout(tableLayout);
table.setHeaderVisible(true);
for (int i = 0; i < columnHeaders.length; i++) {
tableLayout.addColumnData(columnLayouts[i]);
TableColumn tc = new TableColumn(table, SWT.NONE,i);
tc.setResizable(columnLayouts[i].resizable);
tc.setText(columnHeaders[i]);
}
data = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
data.verticalIndent = 5;
data.heightHint = 150;
table.setLayoutData(data);
viewer.setContentProvider(new RemoteResourceContentProvider());
viewer.setLabelProvider(new RemoteResourceLabelProvider());
viewer.setInput(remoteResource);
// set f1 help
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IHelpContextIds.REMOTE_RESOURCE_PROPERTIES_DIALOG);
return composite;
}
class RemoteResourceContentProvider implements IStructuredContentProvider {
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public Object[] getElements(Object arg0) {
return properties;
}
}
class RemoteResourceLabelProvider extends LabelProvider implements ITableLabelProvider {
public String getColumnText(Object element, int columnIndex) {
if ((columnIndex >= 0) && (columnIndex <= 1)) {
ISVNProperty property = (ISVNProperty)element;
switch (columnIndex) {
case 0: return property.getName();
case 1: return property.getValue();
default: return "";
}
}
return "";
}
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
}
}
| trying to fix rendering of the read-only fields on osx
| org.tigris.subversion.subclipse.ui/src/org/tigris/subversion/subclipse/ui/dialogs/RemoteResourcePropertiesDialog.java | trying to fix rendering of the read-only fields on osx |
|
Java | epl-1.0 | 290bbf40e6219281b4f161e3e7c9f657451974de | 0 | asupdev/asup,asupdev/asup,asupdev/asup | package org.asup.os.type.msgf.base.api;
import javax.inject.Inject;
import org.asup.fw.core.annotation.Supported;
import org.asup.il.data.BinaryType;
import org.asup.il.data.DatetimeType;
import org.asup.il.data.QBinary;
import org.asup.il.data.QCharacter;
import org.asup.il.data.QCharacterDef;
import org.asup.il.data.QDataStructDelegator;
import org.asup.il.data.QDatetime;
import org.asup.il.data.QDecimalDef;
import org.asup.il.data.QEnum;
import org.asup.il.data.QHexadecimal;
import org.asup.il.data.QIntegratedLanguageDataFactory;
import org.asup.il.data.QScroller;
import org.asup.il.data.QStroller;
import org.asup.il.data.annotation.DataDef;
import org.asup.il.data.annotation.Entry;
import org.asup.il.data.annotation.Program;
import org.asup.il.data.annotation.Special;
import org.asup.os.core.OperatingSystemException;
import org.asup.os.core.OperatingSystemRuntimeException;
import org.asup.os.core.Scope;
import org.asup.os.core.jobs.QJob;
import org.asup.os.core.jobs.QJobLogManager;
import org.asup.os.core.resources.QResourceWriter;
import org.asup.os.type.msgf.QMessageDescription;
import org.asup.os.type.msgf.QMessageDescriptionDataField;
import org.asup.os.type.msgf.QMessageFile;
import org.asup.os.type.msgf.QMessageFileManager;
import org.asup.os.type.msgf.QOperatingSystemMessageFileFactory;
import org.asup.os.type.msgf.impl.OperatingSystemMessageFileFactoryImpl;
@Supported
@Program(name = "QMHCRMSD")
public class MessageDescriptionAdder {
@Inject
private QMessageFileManager messageFileManager;
@Inject
private QJob job;
@Inject
private QJobLogManager jobLogManager;
public @Entry void main(
@Supported @DataDef(length = 7) QCharacter messageIdentifier,
@Supported @DataDef(qualified = true) MessageFile messageFile,
@Supported @DataDef(length = 132) QCharacter firstLevelMessageText,
@Supported @DataDef(length = 3000) QEnum<SecondLevelMessageTextEnum, QCharacter> secondLevelMessageText,
@Supported @DataDef(binaryType = BinaryType.SHORT) QBinary severityCode,
@Supported @DataDef(dimension = 99) QEnum<MessageDataFieldsFormatEnum, QStroller<MessageDataFieldsFormat>> messageDataFieldsFormats,
@DataDef(length = 1) QEnum<ReplyTypeEnum, QCharacter> replyType,
QEnum<MaximumReplyLengthEnum, MaximumReplyLength> maximumReplyLength,
@DataDef(dimension = 20, length = 32) QEnum<ValidReplyValueEnum, QScroller<QCharacter>> validReplyValues,
@DataDef(dimension = 20) QEnum<SpecialReplyValueEnum, QStroller<SpecialReplyValue>> specialReplyValues,
QEnum<RangeOfReplyValuesEnum, RangeOfReplyValues> rangeOfReplyValues,
QEnum<RelationshipForValidRepliesEnum, RelationshipForValidReplies> relationshipForValidReplies,
@DataDef(length = 132) QEnum<DefaultReplyValueEnum, QCharacter> defaultReplyValue,
@DataDef(qualified = true) QEnum<DefaultProgramToCallEnum, DefaultProgramToCall> defaultProgramToCall,
@DataDef(dimension = 102, binaryType = BinaryType.SHORT) QEnum<DataToBeDumpedEnum, QScroller<QBinary>> dataToBeDumped,
LevelOfMessage levelOfMessage,
AlertOptions alertOptions,
@DataDef(length = 1) QEnum<LogProblemEnum, QCharacter> logProblem,
@DataDef(binaryType = BinaryType.INTEGER) QEnum<CodedCharacterSetIDEnum, QBinary> codedCharacterSetID) {
QResourceWriter<QMessageFile> resource = null;
String library = null;
switch (messageFile.library.asEnum()) {
case LIBL:
resource = messageFileManager.getResourceWriter(job, Scope.LIBRARY_LIST);
break;
case CURLIB:
resource = messageFileManager.getResourceWriter(job, Scope.CURRENT_LIBRARY);
break;
case OTHER:
library = messageFile.library.asData().trimR();
resource = messageFileManager.getResourceWriter(job, library);
break;
}
QMessageFile qMessageFile = resource.lookup(messageFile.name.trimR());
if (qMessageFile == null)
throw messageFileManager.prepareException(job, QCPFMSG.CPF2407, new String[] {messageFile.name.trimR(),messageFile.library.asData().trimR()});
// TODO Come verifico l'esistenza???
for (QMessageDescription messageDescription : qMessageFile.getMessages()) {
if (messageDescription.getName().equals(messageIdentifier.trimR()))
throw messageFileManager.prepareException(job, QCPFMSG.CPF2412, new String[] {messageIdentifier.trimR(), messageFile.name.trimR(),messageFile.library.asData().trimR()});
}
QMessageDescription qMessageDescription = QOperatingSystemMessageFileFactory.eINSTANCE.createMessageDescription();
// MSGID
qMessageDescription.setName(messageIdentifier.trimR());
// MSG
qMessageDescription.setMessageText(firstLevelMessageText.trimR());
// SECLVL
switch (secondLevelMessageText.asEnum()) {
case NONE:
qMessageDescription.setMessageHelp("");
break;
case OTHER:
qMessageDescription.setMessageHelp(secondLevelMessageText.asData().trimR());
break;
}
// SEV
qMessageDescription.setSeverity(severityCode.asInteger());
// FMT TODO
QMessageDescriptionDataField messageDescriptionDataField = null;
messageDescriptionDataField = OperatingSystemMessageFileFactoryImpl.eINSTANCE.createMessageDescriptionDataField();
switch (messageDataFieldsFormats.asEnum()) {
case NONE:
break;
case OTHER:
int i = 0;
for(MessageDataFieldsFormat messageDataFieldsFormat: messageDataFieldsFormats.asData()) {
if(messageDataFieldsFormat.isEmpty())
continue;
switch (messageDataFieldsFormat.dataType.asEnum()) {
case BIN:
break;
case CCHAR:
break;
case QTDCHAR:
case CHAR:
messageDescriptionDataField = OperatingSystemMessageFileFactoryImpl.eINSTANCE.createMessageDescriptionDataField();
messageDescriptionDataField.setOutputMask(messageDataFieldsFormat.dataType.getSpecialName());
QCharacterDef characterDefinition = QIntegratedLanguageDataFactory.eINSTANCE.createCharacterDef();
switch (messageDataFieldsFormat.length.asEnum()) {
case OTHER:
characterDefinition.setLength(messageDataFieldsFormat.length.asData().asInteger());
break;
case VARY:
characterDefinition.setLength(messageDataFieldsFormat.VARYBytesOrDecPos.asShort());
characterDefinition.setVarying(true);
break;
}
messageDescriptionDataField.setDataDef(characterDefinition);
qMessageDescription.getMessageDataFields().add(i, messageDescriptionDataField);
break;
case DEC:
messageDescriptionDataField = OperatingSystemMessageFileFactoryImpl.eINSTANCE.createMessageDescriptionDataField();
messageDescriptionDataField.setOutputMask(messageDataFieldsFormat.dataType.getSpecialName());
QDecimalDef decimalDefinition = QIntegratedLanguageDataFactory.eINSTANCE.createDecimalDef();
switch (messageDataFieldsFormat.length.asEnum()) {
case OTHER:
decimalDefinition.setPrecision(messageDataFieldsFormat.length.asData().asInteger());
break;
case VARY:
break;
}
decimalDefinition.setScale(messageDataFieldsFormat.VARYBytesOrDecPos.asShort());
messageDescriptionDataField.setDataDef(decimalDefinition);
qMessageDescription.getMessageDataFields().add(i, messageDescriptionDataField);
break;
case DTS:
break;
case HEX:
break;
case ITV:
break;
case SPP:
break;
case SYP:
break;
case UBIN:
break;
case UTC:
break;
case UTCD:
break;
case UTCT:
break;
}
i++;
}
break;
}
qMessageFile.getMessages().add(qMessageDescription);
try {
resource.save(qMessageFile, true);
jobLogManager.info(job, "Message Description " + messageIdentifier + " added to Message File " + messageFile.name.trimR());
} catch (OperatingSystemException e) {
throw new OperatingSystemRuntimeException(e);
}
}
public static enum QCPFMSG {
CPF2407, CPF2412
}
public static class MessageFile extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LibraryEnum, QCharacter> library;
public static enum LibraryEnum {
LIBL, CURLIB, OTHER
}
}
public static enum SecondLevelMessageTextEnum {
@Special(value = "")
NONE, OTHER
}
public static class MessageDataFieldsFormat extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<DataTypeEnum, QHexadecimal> dataType;
@DataDef(binaryType = BinaryType.SHORT, value = "*VARY")
public QEnum<LengthEnum, QBinary> length;
@DataDef(binaryType = BinaryType.SHORT, value = "0")
public QBinary VARYBytesOrDecPos;
public static enum DataTypeEnum {
@Special(value = "04")
QTDCHAR, @Special(value = "44")
CHAR, @Special(value = "24")
HEX, @Special(value = "2F")
SPP, @Special(value = "03")
DEC, @Special(value = "00")
BIN, @Special(value = "02")
UBIN, @Special(value = "05")
CCHAR, @Special(value = "15")
UTC, @Special(value = "16")
UTCD, @Special(value = "17")
UTCT, @Special(value = "14")
DTS, @Special(value = "0F")
SYP, @Special(value = "34")
ITV
}
public static enum LengthEnum {
@Special(value = "-1")
VARY, OTHER
}
}
public static enum MessageDataFieldsFormatEnum {
@Special(value = "FF")
NONE, OTHER
}
public static enum ReplyTypeEnum {
@Special(value = "C")
CHAR, @Special(value = "D")
DEC, @Special(value = "A")
ALPHA, @Special(value = "N")
NAME, @Special(value = "X")
NONE
}
public static class MaximumReplyLength extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(binaryType = BinaryType.SHORT)
public QBinary length;
@DataDef(binaryType = BinaryType.SHORT)
public QBinary decimalPositions;
}
public static enum MaximumReplyLengthEnum {
@Special(value = "-1")
TYPE, @Special(value = "-2")
NONE, OTHER
}
public static enum ValidReplyValueEnum {
NONE, OTHER
}
public static class SpecialReplyValue extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 32)
public QCharacter originalFromValue;
@DataDef(length = 32)
public QCharacter replacementToValue;
}
public static enum SpecialReplyValueEnum {
NONE, OTHER
}
public static class RangeOfReplyValues extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 32)
public QCharacter lowerValue;
@DataDef(length = 32)
public QCharacter upperValue;
}
public static enum RangeOfReplyValuesEnum {
NONE, OTHER
}
public static class RelationshipForValidReplies extends
QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<RelationalOperatorEnum, QHexadecimal> relationalOperator;
@DataDef(length = 32)
public QCharacter value;
public static enum RelationalOperatorEnum {
@Special(value = "50")
EQ, @Special(value = "70")
LE, @Special(value = "40")
GE, @Special(value = "30")
GT, @Special(value = "80")
LT, @Special(value = "60")
NE, @Special(value = "40")
NL, @Special(value = "70")
NG
}
}
public static enum RelationshipForValidRepliesEnum {
@Special(value = "FF")
NONE, OTHER
}
public static enum DefaultReplyValueEnum {
NONE, OTHER
}
public static class DefaultProgramToCall extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LibraryEnum, QCharacter> library;
public static enum LibraryEnum {
LIBL, CURLIB, OTHER
}
}
public static enum DefaultProgramToCallEnum {
NONE, OTHER
}
public static enum DataToBeDumpedEnum {
@Special(value = "0")
NONE, @Special(value = "-4")
JOB, @Special(value = "-2")
JOBINT, @Special(value = "-1")
JOBDMP, OTHER
}
public static class LevelOfMessage extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(datetimeType = DatetimeType.DATE, value = "*CURRENT")
public QEnum<CreationDateEnum, QDatetime> creationDate;
@DataDef(binaryType = BinaryType.SHORT, value = "1")
public QBinary levelNumber;
public static enum CreationDateEnum {
@Special(value = "0040000")
CURRENT, OTHER
}
}
public static class AlertOptions extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 1, value = "*NO")
public QEnum<AlertTypeEnum, QCharacter> alertType;
@DataDef(binaryType = BinaryType.SHORT, value = "*NONE")
public QEnum<ResourceNameVariableEnum, QBinary> resourceNameVariable;
public static enum AlertTypeEnum {
@Special(value = "I")
IMMED, @Special(value = "D")
DEFER, @Special(value = "U")
UNATTEND, @Special(value = "N")
NO
}
public static enum ResourceNameVariableEnum {
@Special(value = "0")
NONE, OTHER
}
}
public static enum LogProblemEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum CodedCharacterSetIDEnum {
@Special(value = "0")
JOB, @Special(value = "65535")
HEX, OTHER
}
}
| org.asup.os.type.msgf.base/src/org/asup/os/type/msgf/base/api/MessageDescriptionAdder.java | package org.asup.os.type.msgf.base.api;
import javax.inject.Inject;
import org.asup.fw.core.annotation.Supported;
import org.asup.il.data.BinaryType;
import org.asup.il.data.DatetimeType;
import org.asup.il.data.QBinary;
import org.asup.il.data.QCharacter;
import org.asup.il.data.QCharacterDef;
import org.asup.il.data.QDataStructDelegator;
import org.asup.il.data.QDatetime;
import org.asup.il.data.QDecimalDef;
import org.asup.il.data.QEnum;
import org.asup.il.data.QHexadecimal;
import org.asup.il.data.QIntegratedLanguageDataFactory;
import org.asup.il.data.QScroller;
import org.asup.il.data.QStroller;
import org.asup.il.data.annotation.DataDef;
import org.asup.il.data.annotation.Entry;
import org.asup.il.data.annotation.Program;
import org.asup.il.data.annotation.Special;
import org.asup.os.core.OperatingSystemException;
import org.asup.os.core.OperatingSystemRuntimeException;
import org.asup.os.core.Scope;
import org.asup.os.core.jobs.QJob;
import org.asup.os.core.jobs.QJobLogManager;
import org.asup.os.core.resources.QResourceWriter;
import org.asup.os.type.msgf.QMessageDescription;
import org.asup.os.type.msgf.QMessageDescriptionDataField;
import org.asup.os.type.msgf.QMessageFile;
import org.asup.os.type.msgf.QMessageFileManager;
import org.asup.os.type.msgf.QOperatingSystemMessageFileFactory;
import org.asup.os.type.msgf.impl.OperatingSystemMessageFileFactoryImpl;
@Supported
@Program(name = "QMHCRMSD")
public class MessageDescriptionAdder {
@Inject
private QMessageFileManager messageFileManager;
@Inject
private QJob job;
@Inject
private QJobLogManager jobLogManager;
public @Entry void main(
@Supported @DataDef(length = 7) QCharacter messageIdentifier,
@Supported @DataDef(qualified = true) MessageFile messageFile,
@Supported @DataDef(length = 132) QCharacter firstLevelMessageText,
@Supported @DataDef(length = 3000) QEnum<SecondLevelMessageTextEnum, QCharacter> secondLevelMessageText,
@Supported @DataDef(binaryType = BinaryType.SHORT) QBinary severityCode,
@Supported @DataDef(dimension = 99) QEnum<MessageDataFieldsFormatEnum, QStroller<MessageDataFieldsFormat>> messageDataFieldsFormats,
@DataDef(length = 1) QEnum<ReplyTypeEnum, QCharacter> replyType,
QEnum<MaximumReplyLengthEnum, MaximumReplyLength> maximumReplyLength,
@DataDef(dimension = 20, length = 32) QEnum<ValidReplyValueEnum, QScroller<QCharacter>> validReplyValues,
@DataDef(dimension = 20) QEnum<SpecialReplyValueEnum, QStroller<SpecialReplyValue>> specialReplyValues,
QEnum<RangeOfReplyValuesEnum, RangeOfReplyValues> rangeOfReplyValues,
QEnum<RelationshipForValidRepliesEnum, RelationshipForValidReplies> relationshipForValidReplies,
@DataDef(length = 132) QEnum<DefaultReplyValueEnum, QCharacter> defaultReplyValue,
@DataDef(qualified = true) QEnum<DefaultProgramToCallEnum, DefaultProgramToCall> defaultProgramToCall,
@DataDef(dimension = 102, binaryType = BinaryType.SHORT) QEnum<DataToBeDumpedEnum, QScroller<QBinary>> dataToBeDumped,
LevelOfMessage levelOfMessage,
AlertOptions alertOptions,
@DataDef(length = 1) QEnum<LogProblemEnum, QCharacter> logProblem,
@DataDef(binaryType = BinaryType.INTEGER) QEnum<CodedCharacterSetIDEnum, QBinary> codedCharacterSetID) {
QResourceWriter<QMessageFile> resource = null;
String library = null;
switch (messageFile.library.asEnum()) {
case LIBL:
resource = messageFileManager.getResourceWriter(job, Scope.LIBRARY_LIST);
break;
case CURLIB:
resource = messageFileManager.getResourceWriter(job, Scope.CURRENT_LIBRARY);
break;
case OTHER:
library = messageFile.library.asData().trimR();
resource = messageFileManager.getResourceWriter(job, library);
break;
}
QMessageFile qMessageFile = resource.lookup(messageFile.name.trimR());
if (qMessageFile == null)
throw new OperatingSystemRuntimeException("Message File " + messageFile.name + " not exists in library " + library);
// TODO Come verifico l'esistenza???
for (QMessageDescription messageDescription : qMessageFile.getMessages()) {
if (messageDescription.getName().equals(messageIdentifier.trimR()))
throw new OperatingSystemRuntimeException("Message Description " + messageIdentifier + " already exist");
}
QMessageDescription qMessageDescription = QOperatingSystemMessageFileFactory.eINSTANCE.createMessageDescription();
// MSGID
qMessageDescription.setName(messageIdentifier.trimR());
// MSG
qMessageDescription.setMessageText(firstLevelMessageText.trimR());
// SECLVL
switch (secondLevelMessageText.asEnum()) {
case NONE:
qMessageDescription.setMessageHelp("");
break;
case OTHER:
qMessageDescription.setMessageHelp(secondLevelMessageText.asData().trimR());
break;
}
// SEV
qMessageDescription.setSeverity(severityCode.asInteger());
// FMT TODO
QMessageDescriptionDataField messageDescriptionDataField = null;
messageDescriptionDataField = OperatingSystemMessageFileFactoryImpl.eINSTANCE.createMessageDescriptionDataField();
System.out.println(messageDataFieldsFormats.asData().asString());
switch (messageDataFieldsFormats.asEnum()) {
case NONE:
break;
case OTHER:
int i = 0;
for(MessageDataFieldsFormat messageDataFieldsFormat: messageDataFieldsFormats.asData()) {
if(messageDataFieldsFormat.isEmpty())
continue;
switch (messageDataFieldsFormat.dataType.asEnum()) {
case BIN:
break;
case CCHAR:
break;
case QTDCHAR:
case CHAR:
messageDescriptionDataField = OperatingSystemMessageFileFactoryImpl.eINSTANCE.createMessageDescriptionDataField();
messageDescriptionDataField.setOutputMask(messageDataFieldsFormat.dataType.getSpecialName());
QCharacterDef characterDefinition = QIntegratedLanguageDataFactory.eINSTANCE.createCharacterDef();
switch (messageDataFieldsFormat.length.asEnum()) {
case OTHER:
characterDefinition.setLength(messageDataFieldsFormat.length.asData().asInteger());
break;
case VARY:
characterDefinition.setLength(messageDataFieldsFormat.VARYBytesOrDecPos.asShort());
characterDefinition.setVarying(true);
break;
}
messageDescriptionDataField.setDataDef(characterDefinition);
qMessageDescription.getMessageDataFields().add(i, messageDescriptionDataField);
break;
case DEC:
messageDescriptionDataField = OperatingSystemMessageFileFactoryImpl.eINSTANCE.createMessageDescriptionDataField();
messageDescriptionDataField.setOutputMask(messageDataFieldsFormat.dataType.getSpecialName());
QDecimalDef decimalDefinition = QIntegratedLanguageDataFactory.eINSTANCE.createDecimalDef();
switch (messageDataFieldsFormat.length.asEnum()) {
case OTHER:
decimalDefinition.setPrecision(messageDataFieldsFormat.length.asData().asInteger());
break;
case VARY:
break;
}
decimalDefinition.setScale(messageDataFieldsFormat.VARYBytesOrDecPos.asShort());
messageDescriptionDataField.setDataDef(decimalDefinition);
qMessageDescription.getMessageDataFields().add(i, messageDescriptionDataField);
break;
case DTS:
break;
case HEX:
break;
case ITV:
break;
case SPP:
break;
case SYP:
break;
case UBIN:
break;
case UTC:
break;
case UTCD:
break;
case UTCT:
break;
}
i++;
}
break;
}
qMessageFile.getMessages().add(qMessageDescription);
try {
resource.save(qMessageFile, true);
jobLogManager.info(job, "Message Description " + messageIdentifier + " added to Message File " + messageFile.name.trimR());
} catch (OperatingSystemException e) {
throw new OperatingSystemRuntimeException(e);
}
}
public static class MessageFile extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LibraryEnum, QCharacter> library;
public static enum LibraryEnum {
LIBL, CURLIB, OTHER
}
}
public static enum SecondLevelMessageTextEnum {
@Special(value = "")
NONE, OTHER
}
public static class MessageDataFieldsFormat extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<DataTypeEnum, QHexadecimal> dataType;
@DataDef(binaryType = BinaryType.SHORT, value = "*VARY")
public QEnum<LengthEnum, QBinary> length;
@DataDef(binaryType = BinaryType.SHORT, value = "0")
public QBinary VARYBytesOrDecPos;
public static enum DataTypeEnum {
@Special(value = "04")
QTDCHAR, @Special(value = "44")
CHAR, @Special(value = "24")
HEX, @Special(value = "2F")
SPP, @Special(value = "03")
DEC, @Special(value = "00")
BIN, @Special(value = "02")
UBIN, @Special(value = "05")
CCHAR, @Special(value = "15")
UTC, @Special(value = "16")
UTCD, @Special(value = "17")
UTCT, @Special(value = "14")
DTS, @Special(value = "0F")
SYP, @Special(value = "34")
ITV
}
public static enum LengthEnum {
@Special(value = "-1")
VARY, OTHER
}
}
public static enum MessageDataFieldsFormatEnum {
@Special(value = "FF")
NONE, OTHER
}
public static enum ReplyTypeEnum {
@Special(value = "C")
CHAR, @Special(value = "D")
DEC, @Special(value = "A")
ALPHA, @Special(value = "N")
NAME, @Special(value = "X")
NONE
}
public static class MaximumReplyLength extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(binaryType = BinaryType.SHORT)
public QBinary length;
@DataDef(binaryType = BinaryType.SHORT)
public QBinary decimalPositions;
}
public static enum MaximumReplyLengthEnum {
@Special(value = "-1")
TYPE, @Special(value = "-2")
NONE, OTHER
}
public static enum ValidReplyValueEnum {
NONE, OTHER
}
public static class SpecialReplyValue extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 32)
public QCharacter originalFromValue;
@DataDef(length = 32)
public QCharacter replacementToValue;
}
public static enum SpecialReplyValueEnum {
NONE, OTHER
}
public static class RangeOfReplyValues extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 32)
public QCharacter lowerValue;
@DataDef(length = 32)
public QCharacter upperValue;
}
public static enum RangeOfReplyValuesEnum {
NONE, OTHER
}
public static class RelationshipForValidReplies extends
QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 1)
public QEnum<RelationalOperatorEnum, QHexadecimal> relationalOperator;
@DataDef(length = 32)
public QCharacter value;
public static enum RelationalOperatorEnum {
@Special(value = "50")
EQ, @Special(value = "70")
LE, @Special(value = "40")
GE, @Special(value = "30")
GT, @Special(value = "80")
LT, @Special(value = "60")
NE, @Special(value = "40")
NL, @Special(value = "70")
NG
}
}
public static enum RelationshipForValidRepliesEnum {
@Special(value = "FF")
NONE, OTHER
}
public static enum DefaultReplyValueEnum {
NONE, OTHER
}
public static class DefaultProgramToCall extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 10)
public QCharacter name;
@DataDef(length = 10, value = "*LIBL")
public QEnum<LibraryEnum, QCharacter> library;
public static enum LibraryEnum {
LIBL, CURLIB, OTHER
}
}
public static enum DefaultProgramToCallEnum {
NONE, OTHER
}
public static enum DataToBeDumpedEnum {
@Special(value = "0")
NONE, @Special(value = "-4")
JOB, @Special(value = "-2")
JOBINT, @Special(value = "-1")
JOBDMP, OTHER
}
public static class LevelOfMessage extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(datetimeType = DatetimeType.DATE, value = "*CURRENT")
public QEnum<CreationDateEnum, QDatetime> creationDate;
@DataDef(binaryType = BinaryType.SHORT, value = "1")
public QBinary levelNumber;
public static enum CreationDateEnum {
@Special(value = "0040000")
CURRENT, OTHER
}
}
public static class AlertOptions extends QDataStructDelegator {
private static final long serialVersionUID = 1L;
@DataDef(length = 1, value = "*NO")
public QEnum<AlertTypeEnum, QCharacter> alertType;
@DataDef(binaryType = BinaryType.SHORT, value = "*NONE")
public QEnum<ResourceNameVariableEnum, QBinary> resourceNameVariable;
public static enum AlertTypeEnum {
@Special(value = "I")
IMMED, @Special(value = "D")
DEFER, @Special(value = "U")
UNATTEND, @Special(value = "N")
NO
}
public static enum ResourceNameVariableEnum {
@Special(value = "0")
NONE, OTHER
}
}
public static enum LogProblemEnum {
@Special(value = "N")
NO, @Special(value = "Y")
YES
}
public static enum CodedCharacterSetIDEnum {
@Special(value = "0")
JOB, @Special(value = "65535")
HEX, OTHER
}
}
| Issue #23 | org.asup.os.type.msgf.base/src/org/asup/os/type/msgf/base/api/MessageDescriptionAdder.java | Issue #23 |
|
Java | mpl-2.0 | 3dc77fd25ef7120c1ddd470c6396956789291c15 | 0 | Appverse/appverse-web-tools,Appverse/appverse-web-archetypes,Appverse/appverse-web-archetypes,Appverse/appverse-web,Appverse/appverse-web-archetypes,Appverse/appverse-web-tools,Appverse/appverse-web-gwt-frontend | /*
Copyright (c) 2012 GFT Appverse, S.L., Sociedad Unipersonal.
This Source Code Form is subject to the terms of the Appverse Public License
Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this
file, You can obtain one at http://www.appverse.mobi/licenses/apl_v2.0.pdf. [^]
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the conditions of the AppVerse Public License v2.0
are met.
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. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.appverse.web.framework.backend.api.model.integration;
import java.util.ArrayList;
public class IntegrationDataFilter extends AbstractIntegrationBean {
private static final long serialVersionUID = -9158631576861856869L;
// This fields go in a group. If a column is added a value has to be added
// to every array as the stragy is to match by position.
// All constructors in this class need to respect this.
// For instance: column 'name', value 'Mickey Mouse', negate 'false', like
// 'true'.
// In case negate or like does not apply for the current condition we need
// to add a null object to keep the positions.
private ArrayList<String> columns;
private ArrayList<Object> values;
private ArrayList<Boolean> negates;
private ArrayList<Boolean> likes;
private ArrayList<Boolean> ignoreCase;
private ArrayList<Boolean> equalsOrGreaterThan;
private ArrayList<Boolean> equalsOrLessThan;
private ArrayList<String> booleanConditions;
// This fields go in a group. If a column is added a value has to be added
// to every array as the stragy is to match by position.
// All constructors in this class need to respect this.
// For instance: columnToSort 'name', sortingDirection 'ASC'
// In case the sortingDirection is not specified, we will add a default in
// constructor to keep the positions.
private ArrayList<String> columnsToSort;
private ArrayList<String> sortingDirections;
private String defaultBooleanCondition;
// This fields go in a group as they do not have the field 'value' and other
// operators do not apply
private ArrayList<String> columnsIsNull;
private ArrayList<Boolean> negatesIsNull;
private ArrayList<String> booleanConditionsIsNull;
public static String ASC = "ASC";
public static String DESC = "DESC";
public static char WILDCARD_ALL = '%';
public static char WILDCARD_ONE = '_';
public static String CONDITION_AND = "AND";
public static String CONDITION_OR = "OR";
/**
* Default constructor. The default operation to concatenate conditions will
* be logic "AND" operation if this is not specified in the condition
* explicitly
*/
public IntegrationDataFilter() {
defaultBooleanCondition = CONDITION_AND;
columns = new ArrayList<String>();
values = new ArrayList<Object>();
negates = new ArrayList<Boolean>();
likes = new ArrayList<Boolean>();
ignoreCase = new ArrayList<Boolean>();
columnsToSort = new ArrayList<String>();
sortingDirections = new ArrayList<String>();
equalsOrGreaterThan = new ArrayList<Boolean>();
equalsOrLessThan = new ArrayList<Boolean>();
booleanConditions = new ArrayList<String>();
booleanConditionsIsNull = new ArrayList<String>();
columnsIsNull = new ArrayList<String>();
negatesIsNull = new ArrayList<Boolean>();
}
/**
* This constructor allows to specify the default operation to concatenate
* conditions (logic "AND" or "OR" operation). All conditions will be added
* with this operator unless the condition species the operator to use
* explicitly.
*
* @param defaultConditionOperation
* default logic operator to concatenate conditions to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public IntegrationDataFilter(final String defaultConditionOperation) {
this.defaultBooleanCondition = defaultConditionOperation;
columns = new ArrayList<String>();
values = new ArrayList<Object>();
negates = new ArrayList<Boolean>();
likes = new ArrayList<Boolean>();
ignoreCase = new ArrayList<Boolean>();
columnsToSort = new ArrayList<String>();
sortingDirections = new ArrayList<String>();
equalsOrGreaterThan = new ArrayList<Boolean>();
equalsOrLessThan = new ArrayList<Boolean>();
booleanConditionsIsNull = new ArrayList<String>();
columnsIsNull = new ArrayList<String>();
negatesIsNull = new ArrayList<Boolean>();
}
/**
* This methods allows to add "EqualsOrGreaterThan" conditions: column >=
* value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addEqualsOrGreaterThanCondition(final String column,
final Object value) {
addEqualsOrGreaterThanCondition(column, value, defaultBooleanCondition);
}
/**
* This methods allows to add "EqualsOrGreaterThan" conditions: column >=
* value specifying the logic operator ("AND" or "OR") to use to add this
* condition to the filter
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addEqualsOrGreaterThanCondition(final String column,
final Object value, final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(false);
likes.add(false);
ignoreCase.add(false);
equalsOrGreaterThan.add(true);
equalsOrLessThan.add(false);
booleanConditions.add(booleanCondition);
}
/**
* This methods allows to add "EqualsOrLessThan" conditions: column <= value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addEqualsOrLessThanCondition(final String column,
final Object value) {
addEqualsOrLessThanCondition(column, value, defaultBooleanCondition);
}
/**
* This methods allows to add "EqualsOrLessThan" conditions: column <= value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addEqualsOrLessThanCondition(final String column,
final Object value, final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(false);
likes.add(false);
ignoreCase.add(false);
equalsOrGreaterThan.add(false);
equalsOrLessThan.add(true);
booleanConditions.add(booleanCondition);
}
/**
* This method allows to add a IsNull condition. This will restrict the
* result to the columns that have a null in the specified column.
*
* @param column
* column name that provides the value that has to fullfill the
* condition
*/
public void addIsNullCondition(final String column) {
addIsNullCondition(column, false, defaultBooleanCondition);
}
/**
* This method allows to add a IsNull condition. This will restrict the
* result to the columns that have a null in the specified column.
*
* @param column
* column name that provides the value that has to fullfill the
* condition
* @param isNegativeCondition
* specifies if the condition it is added with IS NULL or IS NOT
* NULL
*/
public void addIsNullCondition(final String column,
final boolean isNegativeCondition) {
addIsNullCondition(column, isNegativeCondition, defaultBooleanCondition);
}
/**
* This method allows to add a IsNull condition. This will restrict the
* result to the columns that have a null in the specified column.
*
* @param column
* column name that provides the value that has to fullfill the
* condition
* @param isNegativeCondition
* specifies if the condition it is added with IS NULL or IS NOT
* NULL
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addIsNullCondition(final String column,
final boolean isNegativeCondition, final String booleanCondition) {
columnsIsNull.add(column);
negatesIsNull.add(isNegativeCondition);
booleanConditionsIsNull.add(booleanCondition);
}
/**
* This method allows to add 'like' conditions: column like 'value'. You can
* use static fields WILDCARD_ALL and WILDCARD_ONE to build your value
* string for different matching combinations like: column like 'value%' or
* column like '_value'
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addLikeCondition(final String column, final Object value) {
addLikeCondition(column, value, defaultBooleanCondition);
}
/**
* This method allows to add 'like' conditions: column like 'value'. You can
* use static fields WILDCARD_ALL and WILDCARD_ONE to build your value
* string for different matching combinations like: column like 'value%' or
* column like '_value'
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addLikeCondition(final String column, final Object value,
final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(false);
likes.add(true);
ignoreCase.add(false);
equalsOrGreaterThan.add(false);
equalsOrLessThan.add(false);
booleanConditions.add(booleanCondition);
}
/**
* This method allows to add 'like' conditions: column like 'value'. You can
* use static fields WILDCARD_ALL and WILDCARD_ONE to build your value
* string for different matching combinations like: column like 'value%' or
* column like '_value'
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addLikeConditionIgnoreCase(final String column,
final Object value) {
addLikeConditionIgnoreCase(column, value, defaultBooleanCondition);
}
/**
* This method allows to add 'like' conditions: column like 'value'. You can
* use static fields WILDCARD_ALL and WILDCARD_ONE to build your value
* string for different matching combinations like: column like 'value%' or
* column like '_value'
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addLikeConditionIgnoreCase(final String column,
final Object value, final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(false);
likes.add(true);
ignoreCase.add(true);
equalsOrGreaterThan.add(false);
equalsOrLessThan.add(false);
booleanConditions.add(booleanCondition);
}
/**
* This method allows to add a sorting column to the filter and specify a
* sorting direction (order by columnToSort ASC | DESC). In order to specify
* the sorting direction you can use static fields ASC and DESC. You can add
* several columns to sort to a filter with different sorting directions and
* they will be apply in order to have more complex 'order by' order by
* columnToSort1 ASC, columnToSort2 DESC)
*
* @param columnToSort
* @param sortingDirection
*/
public void addSortingColumn(final String columnToSort,
final String sortingDirection) {
columnsToSort.add(columnToSort);
sortingDirections.add(sortingDirection);
}
/**
* This method allows to add an 'strict' condition. This will restrict the
* result to the columns that have exactly the specified value. It will add
* to the filter a condition like: column = value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addStrictCondition(final String column, final Object value) {
addStrictCondition(column, value, false, defaultBooleanCondition);
}
/**
* This method allows to add a 'strict' condition. This will restrict the
* result to the columns that do not have the specified value. It allows to
* specify if a condition is negative. In this case, t will add to the
* filter a condition like: column != value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param isNegativeCondition
* specifies if the condition it is added with = or != operator
*/
public void addStrictCondition(final String column, final Object value,
final boolean isNegativeCondition) {
addStrictCondition(column, value, isNegativeCondition,
defaultBooleanCondition);
}
/**
* This method allows to add a 'strict' condition. This will restrict the
* result to the columns that do not have the specified value. It allows to
* specify if a condition is negative. In this case, t will add to the
* filter a condition like: column != value.
*
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param isNegativeCondition
* specifies if the condition it is added with = or != operator
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addStrictCondition(final String column, final Object value,
final boolean isNegativeCondition, final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(isNegativeCondition);
likes.add(false);
ignoreCase.add(false);
equalsOrGreaterThan.add(false);
equalsOrLessThan.add(false);
booleanConditions.add(booleanCondition);
}
public ArrayList<String> getBooleanConditions() {
return booleanConditions;
}
public ArrayList<String> getBooleanConditionsIsNull() {
return booleanConditionsIsNull;
}
public ArrayList<String> getColumns() {
return columns;
}
public ArrayList<String> getColumnsIsNull() {
return columnsIsNull;
}
public ArrayList<String> getColumnsToSort() {
return columnsToSort;
}
public String getDefaultBooleanCondition() {
return defaultBooleanCondition;
}
public String getDefaultConditionOperation() {
return defaultBooleanCondition;
}
public ArrayList<Boolean> getEqualsOrGreaterThan() {
return equalsOrGreaterThan;
}
public ArrayList<Boolean> getEqualsOrLessThan() {
return equalsOrLessThan;
}
public ArrayList<Boolean> getIgnoreCase() {
return ignoreCase;
}
public ArrayList<Boolean> getLikes() {
return likes;
}
public ArrayList<Boolean> getNegates() {
return negates;
}
public ArrayList<Boolean> getNegatesIsNull() {
return negatesIsNull;
}
public ArrayList<String> getSortingDirections() {
return sortingDirections;
}
public ArrayList<Object> getValues() {
return values;
}
public void reset() {
resetConditions();
resetSortingColumns();
resetIsNullConditions();
}
public void resetConditions() {
columns = new ArrayList<String>();
values = new ArrayList<Object>();
negates = new ArrayList<Boolean>();
likes = new ArrayList<Boolean>();
ignoreCase = new ArrayList<Boolean>();
equalsOrGreaterThan = new ArrayList<Boolean>();
equalsOrLessThan = new ArrayList<Boolean>();
booleanConditions = new ArrayList<String>();
}
public void resetIsNullConditions() {
columnsIsNull = new ArrayList<String>();
negatesIsNull = new ArrayList<Boolean>();
booleanConditionsIsNull = new ArrayList<String>();
}
public void resetSortingColumns() {
columnsToSort = new ArrayList<String>();
sortingDirections = new ArrayList<String>();
}
}
| modules/backend/core/api/src/main/java/org/appverse/web/framework/backend/api/model/integration/IntegrationDataFilter.java | /*
Copyright (c) 2012 GFT Appverse, S.L., Sociedad Unipersonal.
This Source Code Form is subject to the terms of the Appverse Public License
Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this
file, You can obtain one at http://www.appverse.mobi/licenses/apl_v2.0.pdf. [^]
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the conditions of the AppVerse Public License v2.0
are met.
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. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.appverse.web.framework.backend.api.model.integration;
import java.util.ArrayList;
public class IntegrationDataFilter extends AbstractIntegrationBean {
private static final long serialVersionUID = -9158631576861856869L;
// This fields go in a group. If a column is added a value has to be added
// to every array as the stragy is to match by position.
// All constructors in this class need to respect this.
// For instance: column 'name', value 'Mickey Mouse', negate 'false', like
// 'true'.
// In case negate or like does not apply for the current condition we need
// to add a null object to keep the positions.
private ArrayList<String> columns;
private ArrayList<Object> values;
private ArrayList<Boolean> negates;
private ArrayList<Boolean> likes;
private ArrayList<Boolean> ignoreCase;
private ArrayList<Boolean> equalsOrGreaterThan;
private ArrayList<Boolean> equalsOrLessThan;
private ArrayList<String> booleanConditions;
// This fields go in a group. If a column is added a value has to be added
// to every array as the stragy is to match by position.
// All constructors in this class need to respect this.
// For instance: columnToSort 'name', sortingDirection 'ASC'
// In case the sortingDirection is not specified, we will add a default in
// constructor to keep the positions.
private ArrayList<String> columnsToSort;
private ArrayList<String> sortingDirections;
private String defaultBooleanCondition;
// This fields go in a group as they do not have the field 'value' and other
// operators do not apply
private ArrayList<String> columnsIsNull;
private ArrayList<Boolean> negatesIsNull;
private ArrayList<String> booleanConditionsIsNull;
public static String ASC = "ASC";
public static String DESC = "DESC";
public static char WILDCARD_ALL = '%';
public static char WILDCARD_ONE = '_';
public static String CONDITION_AND = "AND";
public static String CONDITION_OR = "OR";
/**
* Default constructor. The default operation to concatenate conditions will
* be logic "AND" operation if this is not specified in the condition
* explicitly
*/
public IntegrationDataFilter() {
defaultBooleanCondition = CONDITION_AND;
columns = new ArrayList<String>();
values = new ArrayList<Object>();
negates = new ArrayList<Boolean>();
likes = new ArrayList<Boolean>();
ignoreCase = new ArrayList<Boolean>();
columnsToSort = new ArrayList<String>();
sortingDirections = new ArrayList<String>();
equalsOrGreaterThan = new ArrayList<Boolean>();
equalsOrLessThan = new ArrayList<Boolean>();
booleanConditions = new ArrayList<String>();
booleanConditionsIsNull = new ArrayList<String>();
columnsIsNull = new ArrayList<String>();
negatesIsNull = new ArrayList<Boolean>();
}
/**
* This constructor allows to specify the default operation to concatenate
* conditions (logic "AND" or "OR" operation). All conditions will be added
* with this operator unless the condition species the operator to use
* explicitly.
*
* @param defaultConditionOperation
* default logic operator to concatenate conditions to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public IntegrationDataFilter(final String defaultConditionOperation) {
this.defaultBooleanCondition = defaultConditionOperation;
columns = new ArrayList<String>();
values = new ArrayList<Object>();
negates = new ArrayList<Boolean>();
likes = new ArrayList<Boolean>();
ignoreCase = new ArrayList<Boolean>();
columnsToSort = new ArrayList<String>();
sortingDirections = new ArrayList<String>();
equalsOrGreaterThan = new ArrayList<Boolean>();
equalsOrLessThan = new ArrayList<Boolean>();
booleanConditionsIsNull = new ArrayList<String>();
columnsIsNull = new ArrayList<String>();
negatesIsNull = new ArrayList<Boolean>();
}
/**
* This methods allows to add "EqualsOrGreaterThan" conditions: column >=
* value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addEqualsOrGreaterThanCondition(final String column,
final Object value) {
addEqualsOrGreaterThanCondition(column, value, defaultBooleanCondition);
}
/**
* This methods allows to add "EqualsOrGreaterThan" conditions: column >=
* value specifying the logic operator ("AND" or "OR") to use to add this
* condition to the filter
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addEqualsOrGreaterThanCondition(final String column,
final Object value, final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(false);
likes.add(false);
ignoreCase.add(false);
equalsOrGreaterThan.add(true);
equalsOrLessThan.add(false);
booleanConditions.add(booleanCondition);
}
/**
* This methods allows to add "EqualsOrLessThan" conditions: column <= value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addEqualsOrLessThanCondition(final String column,
final Object value) {
addEqualsOrLessThanCondition(column, value, defaultBooleanCondition);
}
/**
* This methods allows to add "EqualsOrLessThan" conditions: column <= value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addEqualsOrLessThanCondition(final String column,
final Object value, final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(false);
likes.add(false);
ignoreCase.add(false);
equalsOrGreaterThan.add(false);
equalsOrLessThan.add(true);
booleanConditions.add(booleanCondition);
}
/**
* This method allows to add a IsNull condition. This will restrict the
* result to the columns that have a null in the specified column.
*
* @param column
* column name that provides the value that has to fullfill the
* condition
*/
public void addIsNullCondition(final String column) {
addIsNullCondition(column, false, defaultBooleanCondition);
}
/**
* This method allows to add a IsNull condition. This will restrict the
* result to the columns that have a null in the specified column.
*
* @param column
* column name that provides the value that has to fullfill the
* condition
* @param isNegativeCondition
* specifies if the condition it is added with IS NULL or IS NOT
* NULL
*/
public void addIsNullCondition(final String column,
final boolean isNegativeCondition) {
addIsNullCondition(column, isNegativeCondition, defaultBooleanCondition);
}
/**
* This method allows to add a IsNull condition. This will restrict the
* result to the columns that have a null in the specified column.
*
* @param column
* column name that provides the value that has to fullfill the
* condition
* @param isNegativeCondition
* specifies if the condition it is added with IS NULL or IS NOT
* NULL
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addIsNullCondition(final String column,
final boolean isNegativeCondition, final String booleanCondition) {
columnsIsNull.add(column);
negatesIsNull.add(isNegativeCondition);
booleanConditionsIsNull.add(booleanCondition);
}
/**
* This method allows to add 'like' conditions: column like 'value'. You can
* use static fields WILDCARD_ALL and WILDCARD_ONE to build your value
* string for different matching combinations like: column like 'value%' or
* column like '_value'
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addLikeCondition(final String column, final Object value) {
addLikeCondition(column, value, defaultBooleanCondition);
}
/**
* This method allows to add 'like' conditions: column like 'value'. You can
* use static fields WILDCARD_ALL and WILDCARD_ONE to build your value
* string for different matching combinations like: column like 'value%' or
* column like '_value'
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addLikeCondition(final String column, final Object value,
final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(false);
likes.add(true);
ignoreCase.add(false);
equalsOrGreaterThan.add(false);
equalsOrLessThan.add(false);
booleanConditions.add(booleanCondition);
}
/**
* This method allows to add 'like' conditions: column like 'value'. You can
* use static fields WILDCARD_ALL and WILDCARD_ONE to build your value
* string for different matching combinations like: column like 'value%' or
* column like '_value'
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addLikeConditionIgnoreCase(final String column,
final Object value) {
addLikeConditionIgnoreCase(column, value, defaultBooleanCondition);
}
/**
* This method allows to add 'like' conditions: column like 'value'. You can
* use static fields WILDCARD_ALL and WILDCARD_ONE to build your value
* string for different matching combinations like: column like 'value%' or
* column like '_value'
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addLikeConditionIgnoreCase(final String column,
final Object value, final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(false);
likes.add(true);
ignoreCase.add(true);
equalsOrGreaterThan.add(false);
equalsOrLessThan.add(false);
booleanConditions.add(booleanCondition);
}
/**
* This method allows to add a sorting column to the filter and specify a
* sorting direction (order by columnToSort ASC | DESC). In order to specify
* the sorting direction you can use static fields ASC and DESC. You can add
* several columns to sort to a filter with different sorting directions and
* they will be apply in order to have more complex 'order by' order by
* columnToSort1 ASC, columnToSort2 DESC)
*
* @param columnToSort
* @param sortingDirection
*/
public void addSortingColumn(final String columnToSort,
final String sortingDirection) {
columnsToSort.add(columnToSort);
sortingDirections.add(sortingDirection);
}
/**
* This method allows to add an 'strict' condition. This will restrict the
* result to the columns that have exactly the specified value. It will add
* to the filter a condition like: column = value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
*/
public void addStrictCondition(final String column, final Object value) {
addStrictCondition(column, value, false, defaultBooleanCondition);
}
/**
* This method allows to add a 'strict' condition. This will restrict the
* result to the columns that do not have the specified value. It allows to
* specify if a condition is negative. In this case, t will add to the
* filter a condition like: column != value
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param isNegativeCondition
* specifies if the condition it is added with = or != operator
*/
public void addStrictCondition(final String column, final Object value,
final boolean isNegativeCondition) {
addStrictCondition(column, value, isNegativeCondition,
defaultBooleanCondition);
}
/**
* This method allows to add a 'strict' condition. This will restrict the
* result to the columns that do not have the specified value. It allows to
* specify if a condition is negative. In this case, t will add to the
* filter a condition like: column != value.
*
*
* @param column
* column name that provides the value to compare with 'value'
* @param value
* value to compare in the condition
* @param isNegativeCondition
* specifies if the condition it is added with = or != operator
* @param booleanCondition
* logic operator (AND or OR) to add this condition to the
* filter. You can use static fields CONDITION_AND and
* CONDITION_OR for this
*/
public void addStrictCondition(final String column, final Object value,
final boolean isNegativeCondition, final String booleanCondition) {
columns.add(column);
values.add(value);
negates.add(isNegativeCondition);
likes.add(false);
ignoreCase.add(false);
equalsOrGreaterThan.add(false);
equalsOrLessThan.add(false);
booleanConditions.add(booleanCondition);
}
public ArrayList<String> getBooleanConditions() {
return booleanConditions;
}
public ArrayList<String> getBooleanConditionsIsNull() {
return booleanConditionsIsNull;
}
public ArrayList<String> getColumns() {
return columns;
}
public ArrayList<String> getColumnsIsNull() {
return columnsIsNull;
}
public ArrayList<String> getColumnsToSort() {
return columnsToSort;
}
public String getDefaultBooleanCondition() {
return defaultBooleanCondition;
}
public String getDefaultConditionOperation() {
return defaultBooleanCondition;
}
public ArrayList<Boolean> getEqualsOrGreaterThan() {
return equalsOrGreaterThan;
}
public ArrayList<Boolean> getEqualsOrLessThan() {
return equalsOrLessThan;
}
public ArrayList<Boolean> getIgnoreCase() {
return ignoreCase;
}
public ArrayList<Boolean> getLikes() {
return likes;
}
public ArrayList<Boolean> getNegates() {
return negates;
}
public ArrayList<Boolean> getNegatesIsNull() {
return negatesIsNull;
}
public ArrayList<String> getSortingDirections() {
return sortingDirections;
}
public ArrayList<Object> getValues() {
return values;
}
public void reset() {
resetConditions();
resetSortingColumns();
}
public void resetConditions() {
columns = new ArrayList<String>();
values = new ArrayList<Object>();
negates = new ArrayList<Boolean>();
likes = new ArrayList<Boolean>();
ignoreCase = new ArrayList<Boolean>();
equalsOrGreaterThan = new ArrayList<Boolean>();
equalsOrLessThan = new ArrayList<Boolean>();
booleanConditions = new ArrayList<String>();
}
public void resetIsNullConditions() {
columnsIsNull = new ArrayList<String>();
negatesIsNull = new ArrayList<Boolean>();
booleanConditionsIsNull = new ArrayList<String>();
}
public void resetSortingColumns() {
columnsToSort = new ArrayList<String>();
sortingDirections = new ArrayList<String>();
}
}
| Added resetIsNullConditions() to reset() method | modules/backend/core/api/src/main/java/org/appverse/web/framework/backend/api/model/integration/IntegrationDataFilter.java | Added resetIsNullConditions() to reset() method |
|
Java | mpl-2.0 | ad2d7c62d9442ca37f50e0223d7ecfa696ab5f50 | 0 | Ch3ck/openmrs-core,spereverziev/openmrs-core,kabariyamilind/openMRSDEV,dcmul/openmrs-core,maekstr/openmrs-core,sadhanvejella/openmrs,prisamuel/openmrs-core,ern2/openmrs-core,shiangree/openmrs-core,Winbobob/openmrs-core,dlahn/openmrs-core,AbhijitParate/openmrs-core,hoquangtruong/TestMylyn,lbl52001/openmrs-core,jamesfeshner/openmrs-module,asifur77/openmrs,iLoop2/openmrs-core,siddharthkhabia/openmrs-core,alexei-grigoriev/openmrs-core,Winbobob/openmrs-core,asifur77/openmrs,foolchan2556/openmrs-core,naraink/openmrs-core,lilo2k/openmrs-core,Ch3ck/openmrs-core,maekstr/openmrs-core,dcmul/openmrs-core,joansmith/openmrs-core,aboutdata/openmrs-core,prisamuel/openmrs-core,jembi/openmrs-core,andyvand/OpenMRS,nilusi/Legacy-UI,jembi/openmrs-core,MuhammadSafwan/Stop-Button-Ability,maany/openmrs-core,sravanthi17/openmrs-core,iLoop2/openmrs-core,sadhanvejella/openmrs,pselle/openmrs-core,hoquangtruong/TestMylyn,kristopherschmidt/openmrs-core,kristopherschmidt/openmrs-core,ssmusoke/openmrs-core,jamesfeshner/openmrs-module,hoquangtruong/TestMylyn,lbl52001/openmrs-core,aj-jaswanth/openmrs-core,lbl52001/openmrs-core,chethandeshpande/openmrs-core,rbtracker/openmrs-core,pselle/openmrs-core,kckc/openmrs-core,Winbobob/openmrs-core,andyvand/OpenMRS,MitchellBot/openmrs-core,AbhijitParate/openmrs-core,jamesfeshner/openmrs-module,kigsmtua/openmrs-core,AbhijitParate/openmrs-core,donaldgavis/openmrs-core,jvena1/openmrs-core,milankarunarathne/openmrs-core,macorrales/openmrs-core,Ch3ck/openmrs-core,jvena1/openmrs-core,lilo2k/openmrs-core,shiangree/openmrs-core,asifur77/openmrs,sintjuri/openmrs-core,lilo2k/openmrs-core,nilusi/Legacy-UI,sravanthi17/openmrs-core,lbl52001/openmrs-core,aj-jaswanth/openmrs-core,geoff-wasilwa/openmrs-core,pselle/openmrs-core,Winbobob/openmrs-core,Openmrs-joel/openmrs-core,andyvand/OpenMRS,kabariyamilind/openMRSDEV,andyvand/OpenMRS,preethi29/openmrs-core,spereverziev/openmrs-core,andyvand/OpenMRS,MuhammadSafwan/Stop-Button-Ability,koskedk/openmrs-core,MuhammadSafwan/Stop-Button-Ability,sadhanvejella/openmrs,maany/openmrs-core,dlahn/openmrs-core,naraink/openmrs-core,alexwind26/openmrs-core,koskedk/openmrs-core,sadhanvejella/openmrs,ern2/openmrs-core,nilusi/Legacy-UI,michaelhofer/openmrs-core,alexei-grigoriev/openmrs-core,sravanthi17/openmrs-core,naraink/openmrs-core,alexei-grigoriev/openmrs-core,iLoop2/openmrs-core,pselle/openmrs-core,jcantu1988/openmrs-core,ern2/openmrs-core,michaelhofer/openmrs-core,kckc/openmrs-core,joansmith/openmrs-core,trsorsimoII/openmrs-core,alexwind26/openmrs-core,ldf92/openmrs-core,chethandeshpande/openmrs-core,sintjuri/openmrs-core,foolchan2556/openmrs-core,Negatu/openmrs-core,nilusi/Legacy-UI,maekstr/openmrs-core,alexwind26/openmrs-core,maany/openmrs-core,AbhijitParate/openmrs-core,aboutdata/openmrs-core,spereverziev/openmrs-core,joansmith/openmrs-core,kigsmtua/openmrs-core,sintjuri/openmrs-core,lilo2k/openmrs-core,preethi29/openmrs-core,jamesfeshner/openmrs-module,kabariyamilind/openMRSDEV,dcmul/openmrs-core,kigsmtua/openmrs-core,kckc/openmrs-core,MitchellBot/openmrs-core,spereverziev/openmrs-core,ldf92/openmrs-core,aj-jaswanth/openmrs-core,MitchellBot/openmrs-core,siddharthkhabia/openmrs-core,siddharthkhabia/openmrs-core,koskedk/openmrs-core,macorrales/openmrs-core,lilo2k/openmrs-core,WANeves/openmrs-core,jembi/openmrs-core,kckc/openmrs-core,Negatu/openmrs-core,sintjuri/openmrs-core,asifur77/openmrs,Ch3ck/openmrs-core,shiangree/openmrs-core,nilusi/Legacy-UI,dcmul/openmrs-core,koskedk/openmrs-core,maekstr/openmrs-core,AbhijitParate/openmrs-core,Openmrs-joel/openmrs-core,foolchan2556/openmrs-core,dlahn/openmrs-core,preethi29/openmrs-core,MuhammadSafwan/Stop-Button-Ability,ern2/openmrs-core,prisamuel/openmrs-core,kristopherschmidt/openmrs-core,alexei-grigoriev/openmrs-core,MuhammadSafwan/Stop-Button-Ability,MitchellBot/openmrs-core,aj-jaswanth/openmrs-core,Negatu/openmrs-core,hoquangtruong/TestMylyn,joansmith/openmrs-core,jembi/openmrs-core,iLoop2/openmrs-core,trsorsimoII/openmrs-core,milankarunarathne/openmrs-core,WANeves/openmrs-core,kristopherschmidt/openmrs-core,aboutdata/openmrs-core,MuhammadSafwan/Stop-Button-Ability,shiangree/openmrs-core,hoquangtruong/TestMylyn,WANeves/openmrs-core,aj-jaswanth/openmrs-core,vinayvenu/openmrs-core,prisamuel/openmrs-core,geoff-wasilwa/openmrs-core,preethi29/openmrs-core,jcantu1988/openmrs-core,dlahn/openmrs-core,WANeves/openmrs-core,donaldgavis/openmrs-core,naraink/openmrs-core,milankarunarathne/openmrs-core,vinayvenu/openmrs-core,siddharthkhabia/openmrs-core,ssmusoke/openmrs-core,rbtracker/openmrs-core,sintjuri/openmrs-core,sravanthi17/openmrs-core,dlahn/openmrs-core,naraink/openmrs-core,Ch3ck/openmrs-core,vinayvenu/openmrs-core,jvena1/openmrs-core,chethandeshpande/openmrs-core,vinayvenu/openmrs-core,alexei-grigoriev/openmrs-core,WANeves/openmrs-core,sravanthi17/openmrs-core,dcmul/openmrs-core,foolchan2556/openmrs-core,maekstr/openmrs-core,aboutdata/openmrs-core,maekstr/openmrs-core,AbhijitParate/openmrs-core,jamesfeshner/openmrs-module,pselle/openmrs-core,Openmrs-joel/openmrs-core,iLoop2/openmrs-core,ldf92/openmrs-core,geoff-wasilwa/openmrs-core,chethandeshpande/openmrs-core,geoff-wasilwa/openmrs-core,macorrales/openmrs-core,ldf92/openmrs-core,sadhanvejella/openmrs,asifur77/openmrs,ssmusoke/openmrs-core,lilo2k/openmrs-core,alexwind26/openmrs-core,andyvand/OpenMRS,vinayvenu/openmrs-core,lbl52001/openmrs-core,Negatu/openmrs-core,rbtracker/openmrs-core,Openmrs-joel/openmrs-core,naraink/openmrs-core,sintjuri/openmrs-core,shiangree/openmrs-core,trsorsimoII/openmrs-core,chethandeshpande/openmrs-core,donaldgavis/openmrs-core,jembi/openmrs-core,kristopherschmidt/openmrs-core,aboutdata/openmrs-core,koskedk/openmrs-core,jcantu1988/openmrs-core,Winbobob/openmrs-core,milankarunarathne/openmrs-core,iLoop2/openmrs-core,ssmusoke/openmrs-core,Winbobob/openmrs-core,geoff-wasilwa/openmrs-core,preethi29/openmrs-core,trsorsimoII/openmrs-core,kigsmtua/openmrs-core,spereverziev/openmrs-core,foolchan2556/openmrs-core,maany/openmrs-core,pselle/openmrs-core,donaldgavis/openmrs-core,rbtracker/openmrs-core,alexei-grigoriev/openmrs-core,alexwind26/openmrs-core,nilusi/Legacy-UI,foolchan2556/openmrs-core,kabariyamilind/openMRSDEV,joansmith/openmrs-core,ssmusoke/openmrs-core,ldf92/openmrs-core,koskedk/openmrs-core,kabariyamilind/openMRSDEV,milankarunarathne/openmrs-core,maany/openmrs-core,siddharthkhabia/openmrs-core,michaelhofer/openmrs-core,rbtracker/openmrs-core,shiangree/openmrs-core,lbl52001/openmrs-core,prisamuel/openmrs-core,siddharthkhabia/openmrs-core,jembi/openmrs-core,macorrales/openmrs-core,Negatu/openmrs-core,ern2/openmrs-core,hoquangtruong/TestMylyn,milankarunarathne/openmrs-core,kigsmtua/openmrs-core,MitchellBot/openmrs-core,prisamuel/openmrs-core,jcantu1988/openmrs-core,jcantu1988/openmrs-core,spereverziev/openmrs-core,macorrales/openmrs-core,Negatu/openmrs-core,jvena1/openmrs-core,michaelhofer/openmrs-core,kigsmtua/openmrs-core,kckc/openmrs-core,michaelhofer/openmrs-core,jvena1/openmrs-core,WANeves/openmrs-core,aboutdata/openmrs-core,trsorsimoII/openmrs-core,Openmrs-joel/openmrs-core,sadhanvejella/openmrs,dcmul/openmrs-core,kckc/openmrs-core,donaldgavis/openmrs-core | package org.openmrs.util;
import java.io.File;
import java.io.FilenameFilter;
import junit.framework.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.openmrs.test.BaseContextSensitiveTest;
public class OpenmrsClassLoaderTest extends BaseContextSensitiveTest {
/**
* TODO : Determine the correct current cache when other tests have created another lib-cache
* @see OpenmrsClassLoader#deleteOldLibCaches(java.io.File)
* @verifies return current cache folders
*/
@Test
@Ignore
public void deleteOldLibCaches_shouldReturnOnlyCurrentCacheFolders() throws Exception {
FilenameFilter cacheDirFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".openmrs-lib-cache");
}
};
FilenameFilter lockFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals("lock");
}
};
File oldCache = new File(System.getProperty("java.io.tmpdir"), "001.openmrs-lib-cache");
//create old cache folder
oldCache.mkdirs();
File currentCache = new File(System.getProperty("java.io.tmpdir"), "002.openmrs-lib-cache");
//create current cache folder
currentCache.mkdirs();
File tempDir = currentCache.getParentFile();
int folderCount = 0;
File tempFolder = new File(System.getProperty("java.io.tmpdir"));
File[] listFiles = tempFolder.listFiles(cacheDirFilter);
for (File cacheDir : listFiles) {
if (cacheDir.list(lockFilter).length != 0) {
folderCount++;
}
}
OpenmrsClassLoader.deleteOldLibCaches(currentCache);
//verify after deleting only one cache should exist
Assert.assertEquals(folderCount + 1, tempDir.listFiles(cacheDirFilter).length);
//verify that it is current cache
Assert.assertEquals(tempDir.listFiles(cacheDirFilter)[0], currentCache);
}
}
| api/src/test/java/org/openmrs/util/OpenmrsClassLoaderTest.java | package org.openmrs.util;
import java.io.File;
import java.io.FilenameFilter;
import junit.framework.Assert;
import org.junit.Test;
import org.openmrs.test.BaseContextSensitiveTest;
public class OpenmrsClassLoaderTest extends BaseContextSensitiveTest {
/**
* @see OpenmrsClassLoader#deleteOldLibCaches(java.io.File)
* @verifies return current cache folders
*/
@Test
public void deleteOldLibCaches_shouldReturnOnlyCurrentCacheFolders() throws Exception {
FilenameFilter cacheDirFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".openmrs-lib-cache");
}
};
FilenameFilter lockFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.equals("lock");
}
};
File oldCache = new File(System.getProperty("java.io.tmpdir"), "001.openmrs-lib-cache");
//create old cache folder
oldCache.mkdirs();
File currentCache = new File(System.getProperty("java.io.tmpdir"), "002.openmrs-lib-cache");
//create current cache folder
currentCache.mkdirs();
File tempDir = currentCache.getParentFile();
int folderCount = 0;
File tempFolder = new File(System.getProperty("java.io.tmpdir"));
File[] listFiles = tempFolder.listFiles(cacheDirFilter);
for (File cacheDir : listFiles) {
if (cacheDir.list(lockFilter).length != 0) {
folderCount++;
}
}
OpenmrsClassLoader.deleteOldLibCaches(currentCache);
//verify after deleting only one cache should exist
Assert.assertEquals(folderCount + 1, tempDir.listFiles(cacheDirFilter).length);
//verify that it is current cache
Assert.assertEquals(tempDir.listFiles(cacheDirFilter)[0], currentCache);
}
}
| Ignore failing test, as it works well as single, but other tests create different lib-cache
git-svn-id: ce3478dfdc990238714fcdf4fc6855b7489218cf@20639 5bac5841-c719-aa4e-b3fe-cce5062f897a
| api/src/test/java/org/openmrs/util/OpenmrsClassLoaderTest.java | Ignore failing test, as it works well as single, but other tests create different lib-cache |
|
Java | agpl-3.0 | 65d326ba58fd6c4ae2a957d0993a1163945a804c | 0 | battlecode/battlecode-server,battlecode/battlecode-server | package battlecode.world;
import battlecode.common.Chassis;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import battlecode.common.ComponentType;
import battlecode.common.GameActionException;
import battlecode.common.GameActionExceptionType;
import battlecode.common.GameObject;
import battlecode.common.MapLocation;
import battlecode.common.Mine;
import battlecode.common.MineInfo;
import battlecode.common.Robot;
import battlecode.common.RobotInfo;
import battlecode.common.RobotLevel;
import battlecode.common.SensorController;
public class Sensor extends BaseComponent implements SensorController {
public Sensor(ComponentType type, InternalRobot robot) {
super(type, robot);
robot.saveMapMemory(robot.getLocation(), type);
}
public GameObject senseObjectAtLocation(MapLocation loc, RobotLevel height) throws GameActionException {
assertEquipped();
assertNotNull(loc);
assertNotNull(height);
assertWithinRange(loc);
return gameWorld.getObject(loc, height);
}
public boolean checkWithinRangeNoDropship(InternalObject obj) {
if(!obj.exists()) return false;
return checkWithinRange(obj.getLocation());
}
@SuppressWarnings("unchecked")
public <T extends GameObject> T[] senseNearbyGameObjects(final Class<T> type) {
Predicate<InternalObject> p = new Predicate<InternalObject>() {
public boolean apply(InternalObject o) {
return checkWithinRangeNoDropship(o) && (type.isInstance(o)) && (!o.equals(robot));
}
};
return Iterables.toArray((Iterable<T>) Iterables.filter(gameWorld.allObjects(), p), type);
}
public RobotInfo senseRobotInfo(Robot r) throws GameActionException {
assertEquipped();
InternalRobot ir = castInternalRobot(r);
assertWithinRange(ir);
ComponentType[] components;
if (canSenseComponents(ir))
components = ir.getComponentTypes();
else
components = null;
MapLocation loc;
if (ir.container() != null)
loc = ir.container().getLocation();
else
loc = ir.getLocation();
Chassis ch = ir.getChassis();
boolean on = ir.isOn();
if (ir.getChassis() == Chassis.DUMMY && ir.getTeam() != this.getRobot().getTeam()) {
ch = Chassis.MEDIUM;
if (canSenseComponents(ir)) {
components = new ComponentType[]{ComponentType.MEDIUM_MOTOR};
}
on = true;
}
return new RobotInfo(ir, loc, ir.getEnergonLevel(), ir.getMaxEnergon(),
ir.getDirection(), on, components, ch);
}
public boolean canSenseComponents(InternalRobot ir) {
return type() == ComponentType.SATELLITE ||
type() == ComponentType.BUG ||
type() == ComponentType.TELESCOPE ||
robot.getTeam() == ir.getTeam();
}
public MineInfo senseMineInfo(Mine m) throws GameActionException {
InternalMine im = castInternalMine(m);
assertWithinRange(im);
return new MineInfo(im, im.getRoundsLeft());
}
public MapLocation senseLocationOf(GameObject o) throws GameActionException {
InternalObject io = castInternalObject(o);
assertWithinRange(io);
return io.getLocation();
}
public boolean canSenseObject(GameObject o) {
assertEquipped();
return checkWithinRange(castInternalObject(o));
}
public boolean canSenseSquare(MapLocation loc) {
return checkWithinRange(loc);
}
public double senseIncome(Robot r) throws GameActionException {
InternalRobot ir = castInternalRobot(r);
assertWithinRange(ir);
if (ir.hasComponentType(ComponentType.RECYCLER)) {
return this.gameWorld.getLastRoundResources()[ir.getTeam().ordinal()];
} else
throw new GameActionException(GameActionExceptionType.WRONG_ROBOT_TYPE, "Must sense a robot with a recycler");
}
}
| src/main/battlecode/world/Sensor.java | package battlecode.world;
import battlecode.common.Chassis;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import battlecode.common.ComponentType;
import battlecode.common.GameActionException;
import battlecode.common.GameActionExceptionType;
import battlecode.common.GameObject;
import battlecode.common.MapLocation;
import battlecode.common.Mine;
import battlecode.common.MineInfo;
import battlecode.common.Robot;
import battlecode.common.RobotInfo;
import battlecode.common.RobotLevel;
import battlecode.common.SensorController;
public class Sensor extends BaseComponent implements SensorController {
public Sensor(ComponentType type, InternalRobot robot) {
super(type, robot);
robot.saveMapMemory(robot.getLocation(), type);
}
public GameObject senseObjectAtLocation(MapLocation loc, RobotLevel height) throws GameActionException {
assertEquipped();
assertNotNull(loc);
assertNotNull(height);
assertWithinRange(loc);
return gameWorld.getObject(loc, height);
}
@SuppressWarnings("unchecked")
public <T extends GameObject> T[] senseNearbyGameObjects(final Class<T> type) {
Predicate<InternalObject> p = new Predicate<InternalObject>() {
public boolean apply(InternalObject o) {
return checkWithinRange(o) && (type.isInstance(o)) && (!o.equals(robot));
}
};
return Iterables.toArray((Iterable<T>) Iterables.filter(gameWorld.allObjects(), p), type);
}
public RobotInfo senseRobotInfo(Robot r) throws GameActionException {
assertEquipped();
InternalRobot ir = castInternalRobot(r);
assertWithinRange(ir);
ComponentType[] components;
if (canSenseComponents(ir))
components = ir.getComponentTypes();
else
components = null;
MapLocation loc;
if (ir.container() != null)
loc = ir.container().getLocation();
else
loc = ir.getLocation();
Chassis ch = ir.getChassis();
boolean on = ir.isOn();
if (ir.getChassis() == Chassis.DUMMY && ir.getTeam() != this.getRobot().getTeam()) {
ch = Chassis.MEDIUM;
if (canSenseComponents(ir)) {
components = new ComponentType[]{ComponentType.MEDIUM_MOTOR};
}
on = true;
}
return new RobotInfo(ir, ir.getLocation(), ir.getEnergonLevel(), ir.getMaxEnergon(),
ir.getDirection(), on, components, ch);
}
public boolean canSenseComponents(InternalRobot ir) {
return type() == ComponentType.SATELLITE ||
type() == ComponentType.BUG ||
type() == ComponentType.TELESCOPE ||
robot.getTeam() == ir.getTeam();
}
public MineInfo senseMineInfo(Mine m) throws GameActionException {
InternalMine im = castInternalMine(m);
assertWithinRange(im);
return new MineInfo(im, im.getRoundsLeft());
}
public MapLocation senseLocationOf(GameObject o) throws GameActionException {
InternalObject io = castInternalObject(o);
assertWithinRange(io);
return io.getLocation();
}
public boolean canSenseObject(GameObject o) {
assertEquipped();
return checkWithinRange(castInternalObject(o));
}
public boolean canSenseSquare(MapLocation loc) {
return checkWithinRange(loc);
}
public double senseIncome(Robot r) throws GameActionException {
InternalRobot ir = castInternalRobot(r);
assertWithinRange(ir);
if (ir.hasComponentType(ComponentType.RECYCLER)) {
return this.gameWorld.getLastRoundResources()[ir.getTeam().ordinal()];
} else
throw new GameActionException(GameActionExceptionType.WRONG_ROBOT_TYPE, "Must sense a robot with a recycler");
}
}
| fix dropship location sensing
| src/main/battlecode/world/Sensor.java | fix dropship location sensing |
|
Java | agpl-3.0 | e0352b05c7339d1570f043e0002aeea9cac2460f | 0 | imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms | package com.imcode.imcms.domain.service;
import com.imcode.imcms.domain.dto.ImageFolderDTO;
import com.imcode.imcms.domain.dto.ImageFolderItemUsageDTO;
import java.io.IOException;
import java.util.List;
/**
* Service for Images Content Manager.
* CRUD operations with image folders and content.
*
* @author Serhii Maksymchuk from Ubrainians for imCode
* 30.10.17.
*/
public interface ImageFolderService {
ImageFolderDTO getImageFolder();
boolean createImageFolder(ImageFolderDTO folderToCreate);
boolean renameFolder(ImageFolderDTO renameMe);
boolean canBeDeleted(ImageFolderDTO folderToCheck) throws IOException;
boolean deleteFolder(ImageFolderDTO deleteMe) throws IOException;
ImageFolderDTO getImagesFrom(ImageFolderDTO folderToGetImages);
List<ImageFolderItemUsageDTO> checkFolder(ImageFolderDTO folderToCheck);
}
| src/main/java/com/imcode/imcms/domain/service/ImageFolderService.java | package com.imcode.imcms.domain.service;
import com.imcode.imcms.domain.dto.ImageFolderDTO;
import java.io.IOException;
/**
* Service for Images Content Manager.
* CRUD operations with image folders and content.
*
* @author Serhii Maksymchuk from Ubrainians for imCode
* 30.10.17.
*/
public interface ImageFolderService {
ImageFolderDTO getImageFolder();
boolean createImageFolder(ImageFolderDTO folderToCreate);
boolean renameFolder(ImageFolderDTO renameMe);
boolean canBeDeleted(ImageFolderDTO folderToCheck) throws IOException;
boolean deleteFolder(ImageFolderDTO deleteMe) throws IOException;
ImageFolderDTO getImagesFrom(ImageFolderDTO folderToGetImages);
}
| IMCMS-376 - Image list - erasing images:
- Add interface method to check folder
| src/main/java/com/imcode/imcms/domain/service/ImageFolderService.java | IMCMS-376 - Image list - erasing images: - Add interface method to check folder |
|
Java | agpl-3.0 | fa0736266cd84def97008dd1095f57d9a6e016ee | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 63df160e-2e60-11e5-9284-b827eb9e62be | hello.java | 63d99440-2e60-11e5-9284-b827eb9e62be | 63df160e-2e60-11e5-9284-b827eb9e62be | hello.java | 63df160e-2e60-11e5-9284-b827eb9e62be |
|
Java | agpl-3.0 | 1f52201cc87344f364674a2893c03cc22f9b314a | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | db1ce3b2-2e61-11e5-9284-b827eb9e62be | hello.java | db1783a4-2e61-11e5-9284-b827eb9e62be | db1ce3b2-2e61-11e5-9284-b827eb9e62be | hello.java | db1ce3b2-2e61-11e5-9284-b827eb9e62be |
|
Java | lgpl-2.1 | f2da22664e9cfb3f709f7456eb5a330ea9e226d5 | 0 | craigpetchell/Jaudiotagger,craigpetchell/Jaudiotagger | package org.jaudiotagger.tag.datatype;
import org.jaudiotagger.tag.AbstractTagFrameBody;
import org.jaudiotagger.tag.InvalidDataTypeException;
import org.jaudiotagger.tag.id3.valuepair.TextEncoding;
import java.nio.charset.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
/**
* Represents a String whose size is determined by finding of a null character at the end of the String. The String
* itself might be of lenght zero (i.e just consist of the null character)
*
* The String will be encoded based upon the text encoding of the frame that it belongs to.
*/
public class TextEncodedStringNullTerminated
extends AbstractString
{
/**
* Creates a new TextEncodedStringNullTerminated datatype.
*
* @param identifier identifies the frame type
*/
public TextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody)
{
super(identifier, frameBody);
}
/**
* Creates a new TextEncodedStringNullTerminated datatype, with value
*
* @param identifier
* @param frameBody
* @param value
*/
public TextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody,String value)
{
super(identifier, frameBody,value);
}
public TextEncodedStringNullTerminated(TextEncodedStringNullTerminated object)
{
super(object);
}
public boolean equals(Object obj)
{
if (obj instanceof TextEncodedStringNullTerminated == false)
{
return false;
}
return super.equals(obj);
}
/**
* Read a string from buffer upto null character (if exists)
*
* Must take into account the text encoding defined in the Encoding Object
* ID3 Text Frames often allow multiple strings seperated by the null char
* appropriate for the encoding.
*
* @param arr this is the buffer for the frame
* @param offset this is where to start reading in the buffer for this field
*/
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException
{
int bufferSize =0;
try
{
logger.finer("Reading from array starting from offset:" + offset);
int size = 0;
//Get the Specified Decoder
String charSetName = getTextEncodingCharSet();
CharsetDecoder decoder = Charset.forName(charSetName).newDecoder();
//We only want to load up to null terminator, data after this is part of different
//field and it may not be possible to decode it so do the check before we do
//do the decoding,encoding dependent.
ByteBuffer buffer = ByteBuffer.wrap(arr, offset, arr.length - offset);
int endPosition = 0;
//Latin-1 and UTF-8 strings are terminated by a single-byte null,
//while UTF-16 and its variants need two bytes for the null terminator.
final boolean nullIsOneByte
= (charSetName.equals(TextEncoding.CHARSET_ISO_8859_1)|| charSetName.equals(TextEncoding.CHARSET_UTF_8));
boolean isNullTerminatorFound=false;
while (buffer.hasRemaining())
{
byte nextByte = buffer.get();
if (nextByte == 0x00)
{
if (nullIsOneByte)
{
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 1;
logger.finest("Null terminator found starting at:"+endPosition );
isNullTerminatorFound=true;
break;
}
else
{
// Looking for two-byte null
if(buffer.hasRemaining())
{
nextByte = buffer.get();
if (nextByte == 0x00)
{
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 2;
logger.finest("UTF16:Null terminator found starting at:"+endPosition);
isNullTerminatorFound=true;
break;
}
else
{
//Nothing to do, we have checked 2nd value of pair it was not a null terminator
//so will just start looking again in next invocation of loop
}
}
else
{
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 1;
logger.warning("UTF16:Should be two null terminator marks but only found one starting at:"
+endPosition);
isNullTerminatorFound=true;
break;
}
}
}
else
{
//If UTF16, we should only be looking on 2 byte boundaries
if (!nullIsOneByte)
{
if(buffer.hasRemaining())
{
buffer.get();
}
}
}
}
if(isNullTerminatorFound==false)
{
throw new InvalidDataTypeException("Unable to find null terminated string");
}
logger.finest("End Position is:" + endPosition + "Offset:" + offset);
//Set Size so offset is ready for next field (includes the null terminator)
size = endPosition - offset;
size++;
if (!nullIsOneByte)
{
size++;
}
setSize(size);
//Decode buffer if runs into problems should throw exception which we
//catch and then set value to empty string. (We don't read the null terminator
//because we dont want to display this */
bufferSize = endPosition - offset;
logger.finest("Text size is:" + bufferSize);
if (bufferSize == 0)
{
value = "";
}
else
{
String str = decoder.decode(ByteBuffer.wrap(arr, offset, bufferSize)).toString();
if (str == null)
{
throw new NullPointerException("String is null");
}
value = str;
}
}
catch (CharacterCodingException ce)
{
logger.warning("Problem decoding text encoded string"+ce.getMessage());
value = "";
}
//Set Size so offset is ready for next field (includes the null terminator)
logger.info("Read NullTerminatedString:" + value+" size inc terminator:"+size);
}
/**
* Write String into byte array, adding a null character to the end of the String
*
* @return the data as a byte array in format to write to file
*/
public byte[] writeByteArray()
{
logger.info("Writing NullTerminatedString." + value);
byte[] data = null;
//Write to buffer using the CharSet defined by getTextEncodingCharSet()
//Add a null terminator which will be encoded based on encoding.
try
{
String charSetName = getTextEncodingCharSet();
CharsetEncoder encoder = Charset.forName(charSetName).newEncoder();
ByteBuffer bb = encoder.encode(CharBuffer.wrap((String) value + '\0'));
data = new byte[bb.limit()];
bb.get(data, 0, bb.limit());
}
//Should never happen so if does throw a RuntimeException
catch (CharacterCodingException ce)
{
logger.severe(ce.getMessage());
throw new RuntimeException(ce);
}
setSize(data.length);
return data;
}
protected String getTextEncodingCharSet()
{
byte textEncoding = this.getBody().getTextEncoding();
String charSetName = TextEncoding.getInstanceOf().getValueForId(textEncoding);
logger.finest("text encoding:"+textEncoding + " charset:"+charSetName);
return charSetName;
}
}
| src/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java | package org.jaudiotagger.tag.datatype;
import org.jaudiotagger.tag.AbstractTagFrameBody;
import org.jaudiotagger.tag.InvalidDataTypeException;
import org.jaudiotagger.tag.id3.valuepair.TextEncoding;
import java.nio.charset.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
/**
* Represents a String whose size is determined by finding of a null character at the end of the String.
*
* The String will be encoded based upon the text encoding of the frame that it belongs to.
*/
public class TextEncodedStringNullTerminated
extends AbstractString
{
/**
* Creates a new TextEncodedStringNullTerminated datatype.
*
* @param identifier identifies the frame type
*/
public TextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody)
{
super(identifier, frameBody);
}
/**
* Creates a new TextEncodedStringNullTerminated datatype, with value
*
* @param identifier
* @param frameBody
* @param value
*/
public TextEncodedStringNullTerminated(String identifier, AbstractTagFrameBody frameBody,String value)
{
super(identifier, frameBody,value);
}
public TextEncodedStringNullTerminated(TextEncodedStringNullTerminated object)
{
super(object);
}
public boolean equals(Object obj)
{
if (obj instanceof TextEncodedStringNullTerminated == false)
{
return false;
}
return super.equals(obj);
}
/**
* Read a string from buffer upto null character (if exists)
*
* Must take into account the text encoding defined in the Encoding Object
* ID3 Text Frames often allow multiple strings seperated by the null char
* appropriate for the encoding.
*
* @param arr this is the buffer for the frame
* @param offset this is where to start reading in the buffer for this field
*/
public void readByteArray(byte[] arr, int offset) throws InvalidDataTypeException
{
int bufferSize =0;
try
{
logger.finer("Reading from array from offset:" + offset);
int size = 0;
//Get the Specified Decoder
String charSetName = getTextEncodingCharSet();
CharsetDecoder decoder = Charset.forName(charSetName).newDecoder();
/* We only want to load up to null terminator, data after this is part of different
* field and it may not be possible to decode it so do the check before we do
* do the decoding,encoding dependent. */
ByteBuffer buffer = ByteBuffer.wrap(arr, offset, arr.length - offset);
int endPosition = 0;
/* Latin-1 and UTF-8 strings are terminated by a single-byte null,
* while UTF-16 and its variants need two bytes for the null terminator.
*/
final boolean nullIsOneByte
= (charSetName.equals(TextEncoding.CHARSET_ISO_8859_1)|| charSetName.equals(TextEncoding.CHARSET_UTF_8));
boolean isNullTerminatorFound=false;
while (buffer.hasRemaining())
{
byte nextByte = buffer.get();
if (nextByte == 0x00)
{
if (nullIsOneByte)
{
logger.finest("Null terminator found at:"+buffer.position());
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 1;
isNullTerminatorFound=true;
break;
}
else
{
// Looking for two-byte null
if(buffer.hasRemaining())
{
nextByte = buffer.get();
if (nextByte == 0x00)
{
logger.finest("UTF16:Null terminator found at:"+buffer.position());
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 2;
isNullTerminatorFound=true;
break;
}
}
else
{
logger.finest("UTF16:Should be two null terminator marks but only found one:"+buffer.position());
buffer.mark();
buffer.reset();
endPosition = buffer.position() - 1;
isNullTerminatorFound=true;
break;
}
}
}
else
{
//If UTF16, we should only be looking on 2 byte boundaries
if (!nullIsOneByte)
{
if(buffer.hasRemaining())
{
buffer.get();
}
}
}
}
if(isNullTerminatorFound==false)
{
throw new InvalidDataTypeException("Unable to find null terminated string");
}
logger.finest("End Position is:" + endPosition + "Offset:" + offset);
//Set Size so offset is ready for next field (includes the null terminator)
size = endPosition - offset;
size++;
if (!nullIsOneByte)
{
size++;
}
setSize(size);
/* Decode buffer if runs into problems should throw exception which we
* catch and then set value to empty string. (We dont read the null terminator
* because we dont want to display this */
bufferSize = endPosition - offset;
logger.finest("Buffer size is:" + bufferSize);
if (bufferSize == 0)
{
value = "";
}
else
{
String str = decoder.decode(ByteBuffer.wrap(arr, offset, bufferSize)).toString();
if (str == null)
{
throw new NullPointerException("String is null");
}
value = str;
}
}
catch (CharacterCodingException ce)
{
logger.warning("Problem decoding text encoded string"+ce.getMessage());
value = "";
}
//Set Size so offset is ready for next field (includes the null terminator)
logger.info("Read NullTerminatedString:" + value+" size:"+size);
}
/**
* Write String into byte array, adding a null character to the end of the String
*
* @return the data as a byte array in format to write to file
*/
public byte[] writeByteArray()
{
logger.info("Writing NullTerminatedString." + value);
byte[] data = null;
//Write to buffer using the CharSet defined by getTextEncodingCharSet()
//Add a null terminator which will be encoded based on encoding.
try
{
String charSetName = getTextEncodingCharSet();
CharsetEncoder encoder = Charset.forName(charSetName).newEncoder();
ByteBuffer bb = encoder.encode(CharBuffer.wrap((String) value + '\0'));
data = new byte[bb.limit()];
bb.get(data, 0, bb.limit());
}
//Should never happen so if does throw a RuntimeException
catch (CharacterCodingException ce)
{
logger.severe(ce.getMessage());
throw new RuntimeException(ce);
}
setSize(data.length);
return data;
}
protected String getTextEncodingCharSet()
{
byte textEncoding = this.getBody().getTextEncoding();
String charSetName = TextEncoding.getInstanceOf().getValueForId(textEncoding);
logger.finest("text encoding:"+textEncoding + " charset:"+charSetName);
return charSetName;
}
}
| Issue #23:Improved logging output
| src/org/jaudiotagger/tag/datatype/TextEncodedStringNullTerminated.java | Issue #23:Improved logging output |
|
Java | lgpl-2.1 | abdcea6a65a0722d7e58225814fa5b1900af6228 | 0 | genomescale/starbeast2,genomescale/starbeast2 | // Based on Exchange.java in BEAST2, which in turn was based on ExchangeOperator.java in BEAST.
package starbeast2;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import beast.core.Description;
import beast.evolution.tree.Node;
import beast.evolution.tree.Tree;
import beast.evolution.tree.TreeInterface;
import beast.util.Randomizer;
/**
* @author Remco Bouckaert
* @author Alexei Drummond
* @author Huw Ogilvie
* @author Andrew Rambaut
*/
@Description("Implements the co-ordinated species and gene tree operator described in Rannala & Yang 2015. "
+ "This performs a wide exchange operation, then prunes-and-regrafts gene tree nodes made invalid "
+ "by the operation onto a valid contemporary branch (without changing node heights). "
+ "See http://arxiv.org/abs/1512.03843 for full details.")
public class WideExchange extends CoordinatedOperator {
private Node brotherNode;
private Node parentNode;
private Node cousinNode;
private List<SortedMap<Node, Node>> forwardMovedNodes;
private SetMultimap<Integer, Node> forwardGraftNodes;
final static Comparator<Node> nhc = new NodeHeightComparator().reversed();
/**
* override this for proposals,
*
* @return log of Hastings Ratio, or Double.NEGATIVE_INFINITY if proposal should not be accepted *
*/
@Override
public double proposal() {
double fLogHastingsRatio = wide();
// only rearrange gene trees if the species tree has changed
if (fLogHastingsRatio != Double.NEGATIVE_INFINITY) {
fLogHastingsRatio += rearrangeGeneTrees();
}
return fLogHastingsRatio;
}
public double wide() {
final TreeInterface speciesTree = speciesTreeInput.get().getTree();
final Node[] speciesTreeNodes = speciesTree.getNodesAsArray();
final int nLeafNodes = speciesTree.getLeafNodeCount();
final int nInternalNodes = speciesTree.getInternalNodeCount() - 1; // excludes the root
final int nNodesExceptRoot = nLeafNodes + nInternalNodes;
final Node rootNode = speciesTreeNodes[nNodesExceptRoot];
// pick an internal node at random (excluding the root)
final int parentNodeNumber = nLeafNodes + Randomizer.nextInt(nInternalNodes);
parentNode = speciesTreeNodes[parentNodeNumber];
final double parentNodeHeight = parentNode.getHeight();
brotherNode = Randomizer.nextBoolean() ? parentNode.getLeft() : parentNode.getRight();
// for all internal nodes (excluding the root)
final double[] mrcaHeights = new double[nNodesExceptRoot];
fillMrcaHeights(parentNode, rootNode, parentNodeHeight, mrcaHeights);
// pick a cousin from the available candidates
int cousinNodeNumber = Randomizer.nextInt(nNodesExceptRoot);
while (mrcaHeights[cousinNodeNumber] == 0.0) {
cousinNodeNumber = Randomizer.nextInt(nNodesExceptRoot);
}
cousinNode = speciesTreeNodes[cousinNodeNumber];
final double cousinMrcaHeight = mrcaHeights[cousinNodeNumber];
exchangeNodes(parentNode, brotherNode, cousinNode, cousinMrcaHeight);
return 0.0;
}
private List<Integer> fillMrcaHeights(final Node parentNode, final Node currentNode, final double parentNodeHeight, final double[] mrcaHeights) {
// possible cousins (nodes defining branches which include the height of the parent node)
final List<Integer> candidateList = new ArrayList<>();
final double currentNodeHeight = currentNode.getHeight();
if (parentNode == currentNode) {
return null;
} else if (currentNodeHeight < parentNodeHeight) {
// this is a candidate node (could be a cousin)
candidateList.add(currentNode.getNr());
return candidateList;
} else {
final List<Integer> leftCandidateNodeNumbers = fillMrcaHeights(parentNode, currentNode.getLeft(), parentNodeHeight, mrcaHeights);
final List<Integer> rightCandidateNodeNumbers = fillMrcaHeights(parentNode, currentNode.getRight(), parentNodeHeight, mrcaHeights);
if (leftCandidateNodeNumbers == null) { // parent is the left child or descendant of the left child
// therefore the current node is the most recent common ancestor connecting the parent and right candidates
for (final Integer candidateNodeNumber: rightCandidateNodeNumbers) {
mrcaHeights[candidateNodeNumber] = currentNodeHeight;
}
return null;
} else if (rightCandidateNodeNumbers == null) { // parent is the right child or descendant of the right child
// therefore the current node is the most recent common ancestor connecting the parent and left candidates
for (final Integer candidateNodeNumber: leftCandidateNodeNumbers) {
mrcaHeights[candidateNodeNumber] = currentNodeHeight;
}
return null;
} else {
candidateList.addAll(leftCandidateNodeNumbers);
candidateList.addAll(rightCandidateNodeNumbers);
return candidateList;
}
}
}
// for testing purposes
/* public void manipulateSpeciesTree(Node argBrother) {
brother = argBrother;
parent = brother.getParent();
final Node grandparent = parent.getParent();
if (grandparent.getLeft().getNr() == parent.getNr()) {
cousin = grandparent.getRight();
} else {
cousin = grandparent.getLeft();
}
forwardMovedNodes = getMovedPairs(brother);
forwardGraftNodes = getGraftBranches(cousin);
exchangeNodes(parent, grandparent, brother, cousin);
} */
public double rearrangeGeneTrees() {
final List<Map<Node, Integer>> forwardGraftCounts = new ArrayList<>();
for (int j = 0; j < nGeneTrees; j++) {
final Map<Node, Integer> jForwardGraftCounts = new HashMap<>();
final Set<Node> jForwardGraftNodes = forwardGraftNodes.get(j);
final SortedMap<Node, Node> jForwardMovedNodes = forwardMovedNodes.get(j);
for (final Entry<Node, Node> nodePair: jForwardMovedNodes.entrySet()) {
final Node movedNode = nodePair.getKey();
final Node disownedChild = nodePair.getValue();
final double movedNodeHeight = movedNode.getHeight();
final List<Node> validGraftBranches = new ArrayList<>();
int forwardGraftCount = 0;
for (Node potentialGraft: jForwardGraftNodes) {
final double potentialGraftBottom = potentialGraft.getHeight();
double potentialGraftTop;
if (potentialGraft.isRoot()) {
potentialGraftTop = Double.POSITIVE_INFINITY;
} else {
potentialGraftTop = potentialGraft.getParent().getHeight();
}
if (movedNodeHeight > potentialGraftBottom && movedNodeHeight < potentialGraftTop) {
forwardGraftCount++;
validGraftBranches.add(potentialGraft);
}
}
// no compatible branches to graft this node on to
// this only occurs when there is missing data and the gene tree root is in the "parent" branch
// or if two gene tree nodes which need moving are of equal height
if (forwardGraftCount == 0) {
return Double.NEGATIVE_INFINITY;
} else {
final Node chosenGraft = validGraftBranches.get(Randomizer.nextInt(forwardGraftCount));
pruneAndRegraft(movedNode, chosenGraft, disownedChild);
movedNode.makeDirty(Tree.IS_FILTHY);
jForwardGraftCounts.put(movedNode, forwardGraftCount);
}
}
forwardGraftCounts.add(jForwardGraftCounts);
}
SetMultimap<Integer, Node> reverseGraftNodes = getGraftBranches(brotherNode);
double logHastingsRatio = 0.0;
for (int j = 0; j < nGeneTrees; j++) {
final Map<Node, Integer> jForwardGraftCounts = forwardGraftCounts.get(j);
final Set<Node> jReverseGraftNodes = reverseGraftNodes.get(j);
for (Node movedNode: jForwardGraftCounts.keySet()) {
final double movedNodeHeight = movedNode.getHeight();
final int forwardGraftCount = jForwardGraftCounts.get(movedNode);
int reverseGraftCount = 0;
for (Node potentialGraft: jReverseGraftNodes) {
final double potentialGraftBottom = potentialGraft.getHeight();
double potentialGraftTop;
if (potentialGraft.isRoot()) {
potentialGraftTop = Double.POSITIVE_INFINITY;
} else {
potentialGraftTop = potentialGraft.getParent().getHeight();
}
if (movedNodeHeight > potentialGraftBottom && movedNodeHeight < potentialGraftTop) {
reverseGraftCount++;
}
}
logHastingsRatio += Math.log(forwardGraftCount) - Math.log(reverseGraftCount);
}
}
return logHastingsRatio;
}
protected static void pruneAndRegraft(final Node nodeToMove, final Node newChild, final Node disownedChild) {
final Node parent = nodeToMove.getParent();
final Node destinationParent = newChild.getParent();
// debug string
// System.out.println(String.format("%d-%d-%d > %d-%d", parent.getNr(), nodeToMove.getNr(), disownedChild.getNr(), destinationParent.getNr(), newChild.getNr()));
nodeToMove.removeChild(disownedChild);
parent.removeChild(nodeToMove);
destinationParent.removeChild(newChild);
nodeToMove.addChild(newChild);
parent.addChild(disownedChild);
destinationParent.addChild(nodeToMove);
nodeToMove.makeDirty(Tree.IS_FILTHY);
newChild.makeDirty(Tree.IS_FILTHY);
disownedChild.makeDirty(Tree.IS_FILTHY);
parent.makeDirty(Tree.IS_FILTHY);
destinationParent.makeDirty(Tree.IS_FILTHY);
}
protected static void exchangeNodes(final Node parent, final Node brother, final Node cousin, final double mrcaHeight) {
final Node parentParent = parent.getParent();
final Node cousinParent = cousin.getParent();
parent.removeChild(brother);
parentParent.removeChild(parent);
cousinParent.removeChild(cousin);
parent.addChild(cousin);
parentParent.addChild(brother);
cousinParent.addChild(parent);
}
// identify nodes that can serve as graft branches as part of a coordinated exchange move
protected SetMultimap<Integer, Node> getGraftBranches(Node cousinNode) {
final int cousinNodeNumber = cousinNode.getNr();
final Set<String> cousinDescendants = findDescendants(cousinNode, cousinNodeNumber);
final SetMultimap<Integer, Node> allGraftBranches = HashMultimap.create();
final List<TreeInterface> geneTrees = geneTreeInput.get();
for (int j = 0; j < nGeneTrees; j++) {
final Node geneTreeRootNode = geneTrees.get(j).getRoot();
final Set<Node> jGraftBranches = new HashSet<Node>();
findGraftBranches(geneTreeRootNode, jGraftBranches, cousinDescendants);
allGraftBranches.putAll(j, jGraftBranches);
}
return allGraftBranches;
}
// identify nodes that can serve as graft branches as part of a coordinated exchange move
private boolean findGraftBranches(Node geneTreeNode, Set<Node> graftNodes, Set<String> branchDescendants) {
if (geneTreeNode.isLeaf()) {
final String descendantName = geneTreeNode.getID();
return branchDescendants.contains(descendantName);
}
final Node leftChild = geneTreeNode.getLeft();
final Node rightChild = geneTreeNode.getRight();
final boolean leftOverlaps = findGraftBranches(leftChild, graftNodes, branchDescendants);
final boolean rightOverlaps = findGraftBranches(rightChild, graftNodes, branchDescendants);
// subtree defined by a child node overlaps species subtree defined by branch
if (leftOverlaps || rightOverlaps) {
if (leftOverlaps) {
graftNodes.add(leftChild);
}
if (rightOverlaps) {
graftNodes.add(rightChild);
}
return true;
}
return false;
}
// identify nodes to be grafted in a narrow move, and children to be "disowned" (joined directly to their grandparent)
private List<SortedMap<Node, Node>> getMovedPairs(Node brotherNode) {
final int brotherNodeNumber = brotherNode.getNr();
final Set<String> brotherDescendants = findDescendants(brotherNode, brotherNodeNumber);
final double lowerHeight = brotherNode.getParent().getHeight(); // parent height (bottom of parent branch)
final double upperHeight = brotherNode.getParent().getParent().getHeight(); // grandparent height (top of parent branch)
final List<SortedMap<Node, Node>> allMovedNodes = new ArrayList<>();
final List<TreeInterface> geneTrees = geneTreeInput.get();
for (int j = 0; j < nGeneTrees; j++) {
final Node geneTreeRootNode = geneTrees.get(j).getRoot();
final SortedMap<Node, Node> jMovedNodes = new TreeMap<>(nhc);
findMovedPairs(geneTreeRootNode, jMovedNodes, brotherDescendants, lowerHeight, upperHeight);
allMovedNodes.add(jMovedNodes);
}
return allMovedNodes;
}
// identify nodes to be moved as part of a coordinated exchange move
private boolean findMovedPairs(Node geneTreeNode, Map<Node, Node> movedNodes, Set<String> brotherDescendants, double lowerHeight, double upperHeight) {
if (geneTreeNode.isLeaf()) {
final String descendantName = geneTreeNode.getID();
return brotherDescendants.contains(descendantName);
}
final Node leftChild = geneTreeNode.getLeft();
final Node rightChild = geneTreeNode.getRight();
final boolean leftOverlapsBrother = findMovedPairs(leftChild, movedNodes, brotherDescendants, lowerHeight, upperHeight);
final boolean rightOverlapsBrother = findMovedPairs(rightChild, movedNodes, brotherDescendants, lowerHeight, upperHeight);
final double nodeHeight = geneTreeNode.getHeight();
if (nodeHeight >= lowerHeight && nodeHeight < upperHeight) {
if (leftOverlapsBrother ^ rightOverlapsBrother) {
if (leftOverlapsBrother) {
movedNodes.put(geneTreeNode, leftChild);
} else {
movedNodes.put(geneTreeNode, rightChild);
}
}
}
return leftOverlapsBrother || rightOverlapsBrother;
}
}
| src/starbeast2/WideExchange.java | // Based on Exchange.java in BEAST2, which in turn was based on ExchangeOperator.java in BEAST.
package starbeast2;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;
import beast.core.Description;
import beast.evolution.tree.Node;
import beast.evolution.tree.Tree;
import beast.evolution.tree.TreeInterface;
import beast.util.Randomizer;
/**
* @author Remco Bouckaert
* @author Alexei Drummond
* @author Huw Ogilvie
* @author Andrew Rambaut
*/
@Description("Implements the co-ordinated species and gene tree operator described in Rannala & Yang 2015. "
+ "This performs a wide exchange operation, then prunes-and-regrafts gene tree nodes made invalid "
+ "by the operation onto a valid contemporary branch (without changing node heights). "
+ "See http://arxiv.org/abs/1512.03843 for full details.")
public class WideExchange extends CoordinatedOperator {
private Node brother;
private Node parent;
private Node uncle;
private List<SortedMap<Node, Node>> forwardMovedNodes;
private SetMultimap<Integer, Node> forwardGraftNodes;
final static Comparator<Node> nhc = new NodeHeightComparator().reversed();
/**
* override this for proposals,
*
* @return log of Hastings Ratio, or Double.NEGATIVE_INFINITY if proposal should not be accepted *
*/
@Override
public double proposal() {
double fLogHastingsRatio = narrow();
// only rearrange gene trees if the species tree has changed
if (fLogHastingsRatio != Double.NEGATIVE_INFINITY) {
fLogHastingsRatio += rearrangeGeneTrees();
}
return fLogHastingsRatio;
}
private int isg(final Node n) {
return (n.getLeft().isLeaf() && n.getRight().isLeaf()) ? 0 : 1;
}
private int sisg(final Node n) {
return n.isLeaf() ? 0 : isg(n);
}
public double narrow() {
final TreeInterface speciesTree = speciesTreeInput.get().getTree();
final int nInternalNodes = speciesTree.getInternalNodeCount();
if (nInternalNodes <= 1) {
return Double.NEGATIVE_INFINITY;
}
Node grandparent = speciesTree.getNode(nInternalNodes + 1 + Randomizer.nextInt(nInternalNodes));
while (grandparent.getLeft().isLeaf() && grandparent.getRight().isLeaf()) {
grandparent = speciesTree.getNode(nInternalNodes + 1 + Randomizer.nextInt(nInternalNodes));
}
parent = grandparent.getLeft();
uncle = grandparent.getRight();
if (parent.getHeight() < uncle.getHeight()) {
parent = grandparent.getRight();
uncle = grandparent.getLeft();
}
if (parent.isLeaf()) {
return Double.NEGATIVE_INFINITY;
}
brother = Randomizer.nextBoolean() ? parent.getLeft() : parent.getRight();
// must be done before any changes are made to the gene or species trees
forwardMovedNodes = getMovedPairs(brother);
forwardGraftNodes = getGraftBranches(uncle);
int validGP = 0;
{
for(int i = nInternalNodes + 1; i < 1 + 2*nInternalNodes; ++i) {
validGP += isg(speciesTree.getNode(i));
}
}
final int c2 = sisg(parent) + sisg(uncle);
exchangeNodes(parent, grandparent, brother, uncle);
final int validGPafter = validGP - c2 + sisg(parent) + sisg(uncle);
return Math.log((float)validGP/validGPafter);
}
// for testing purposes
public void manipulateSpeciesTree(Node argBrother) {
brother = argBrother;
parent = brother.getParent();
final Node grandparent = parent.getParent();
if (grandparent.getLeft().getNr() == parent.getNr()) {
uncle = grandparent.getRight();
} else {
uncle = grandparent.getLeft();
}
forwardMovedNodes = getMovedPairs(brother);
forwardGraftNodes = getGraftBranches(uncle);
exchangeNodes(parent, grandparent, brother, uncle);
}
public double rearrangeGeneTrees() {
final List<Map<Node, Integer>> forwardGraftCounts = new ArrayList<>();
for (int j = 0; j < nGeneTrees; j++) {
final Map<Node, Integer> jForwardGraftCounts = new HashMap<>();
final Set<Node> jForwardGraftNodes = forwardGraftNodes.get(j);
final SortedMap<Node, Node> jForwardMovedNodes = forwardMovedNodes.get(j);
for (final Entry<Node, Node> nodePair: jForwardMovedNodes.entrySet()) {
final Node movedNode = nodePair.getKey();
final Node disownedChild = nodePair.getValue();
final double movedNodeHeight = movedNode.getHeight();
final List<Node> validGraftBranches = new ArrayList<>();
int forwardGraftCount = 0;
for (Node potentialGraft: jForwardGraftNodes) {
final double potentialGraftBottom = potentialGraft.getHeight();
double potentialGraftTop;
if (potentialGraft.isRoot()) {
potentialGraftTop = Double.POSITIVE_INFINITY;
} else {
potentialGraftTop = potentialGraft.getParent().getHeight();
}
if (movedNodeHeight > potentialGraftBottom && movedNodeHeight < potentialGraftTop) {
forwardGraftCount++;
validGraftBranches.add(potentialGraft);
}
}
// no compatible branches to graft this node on to
// this only occurs when there is missing data and the gene tree root is in the "parent" branch
// or if two gene tree nodes which need moving are of equal height
if (forwardGraftCount == 0) {
return Double.NEGATIVE_INFINITY;
} else {
final Node chosenGraft = validGraftBranches.get(Randomizer.nextInt(forwardGraftCount));
pruneAndRegraft(movedNode, chosenGraft, disownedChild);
movedNode.makeDirty(Tree.IS_FILTHY);
jForwardGraftCounts.put(movedNode, forwardGraftCount);
}
}
forwardGraftCounts.add(jForwardGraftCounts);
}
SetMultimap<Integer, Node> reverseGraftNodes = getGraftBranches(brother);
double logHastingsRatio = 0.0;
for (int j = 0; j < nGeneTrees; j++) {
final Map<Node, Integer> jForwardGraftCounts = forwardGraftCounts.get(j);
final Set<Node> jReverseGraftNodes = reverseGraftNodes.get(j);
for (Node movedNode: jForwardGraftCounts.keySet()) {
final double movedNodeHeight = movedNode.getHeight();
final int forwardGraftCount = jForwardGraftCounts.get(movedNode);
int reverseGraftCount = 0;
for (Node potentialGraft: jReverseGraftNodes) {
final double potentialGraftBottom = potentialGraft.getHeight();
double potentialGraftTop;
if (potentialGraft.isRoot()) {
potentialGraftTop = Double.POSITIVE_INFINITY;
} else {
potentialGraftTop = potentialGraft.getParent().getHeight();
}
if (movedNodeHeight > potentialGraftBottom && movedNodeHeight < potentialGraftTop) {
reverseGraftCount++;
}
}
logHastingsRatio += Math.log(forwardGraftCount) - Math.log(reverseGraftCount);
}
}
return logHastingsRatio;
}
protected static void pruneAndRegraft(final Node nodeToMove, final Node newChild, final Node disownedChild) {
final Node sourceParent = nodeToMove.getParent();
final Node destinationParent = newChild.getParent();
// debug string
// System.out.println(String.format("%d-%d-%d > %d-%d", sourceParent.getNr(), nodeToMove.getNr(), disownedChild.getNr(), destinationParent.getNr(), newChild.getNr()));
nodeToMove.removeChild(disownedChild);
sourceParent.removeChild(nodeToMove);
destinationParent.removeChild(newChild);
nodeToMove.addChild(newChild);
sourceParent.addChild(disownedChild);
destinationParent.addChild(nodeToMove);
nodeToMove.makeDirty(Tree.IS_FILTHY);
newChild.makeDirty(Tree.IS_FILTHY);
disownedChild.makeDirty(Tree.IS_FILTHY);
sourceParent.makeDirty(Tree.IS_FILTHY);
destinationParent.makeDirty(Tree.IS_FILTHY);
}
protected static void exchangeNodes(final Node parent, final Node grandparent, final Node brother, final Node uncle) {
grandparent.removeChild(uncle);
parent.addChild(uncle);
parent.removeChild(brother);
grandparent.addChild(brother);
parent.makeDirty(Tree.IS_FILTHY);
grandparent.makeDirty(Tree.IS_FILTHY);
brother.makeDirty(Tree.IS_FILTHY);
uncle.makeDirty(Tree.IS_FILTHY);
}
// identify nodes that can serve as graft branches as part of a coordinated exchange move
protected SetMultimap<Integer, Node> getGraftBranches(Node uncleNode) {
final int uncleNodeNumber = uncleNode.getNr();
final Set<String> uncleDescendants = findDescendants(uncleNode, uncleNodeNumber);
final SetMultimap<Integer, Node> allGraftBranches = HashMultimap.create();
final List<TreeInterface> geneTrees = geneTreeInput.get();
for (int j = 0; j < nGeneTrees; j++) {
final Node geneTreeRootNode = geneTrees.get(j).getRoot();
final Set<Node> jGraftBranches = new HashSet<Node>();
findGraftBranches(geneTreeRootNode, jGraftBranches, uncleDescendants);
allGraftBranches.putAll(j, jGraftBranches);
}
return allGraftBranches;
}
// identify nodes that can serve as graft branches as part of a coordinated exchange move
private boolean findGraftBranches(Node geneTreeNode, Set<Node> graftNodes, Set<String> branchDescendants) {
if (geneTreeNode.isLeaf()) {
final String descendantName = geneTreeNode.getID();
return branchDescendants.contains(descendantName);
}
final Node leftChild = geneTreeNode.getLeft();
final Node rightChild = geneTreeNode.getRight();
final boolean leftOverlaps = findGraftBranches(leftChild, graftNodes, branchDescendants);
final boolean rightOverlaps = findGraftBranches(rightChild, graftNodes, branchDescendants);
// subtree defined by a child node overlaps species subtree defined by branch
if (leftOverlaps || rightOverlaps) {
if (leftOverlaps) {
graftNodes.add(leftChild);
}
if (rightOverlaps) {
graftNodes.add(rightChild);
}
return true;
}
return false;
}
// identify nodes to be grafted in a narrow move, and children to be "disowned" (joined directly to their grandparent)
private List<SortedMap<Node, Node>> getMovedPairs(Node brotherNode) {
final int brotherNodeNumber = brotherNode.getNr();
final Set<String> brotherDescendants = findDescendants(brotherNode, brotherNodeNumber);
final double lowerHeight = brotherNode.getParent().getHeight(); // parent height (bottom of parent branch)
final double upperHeight = brotherNode.getParent().getParent().getHeight(); // grandparent height (top of parent branch)
final List<SortedMap<Node, Node>> allMovedNodes = new ArrayList<>();
final List<TreeInterface> geneTrees = geneTreeInput.get();
for (int j = 0; j < nGeneTrees; j++) {
final Node geneTreeRootNode = geneTrees.get(j).getRoot();
final SortedMap<Node, Node> jMovedNodes = new TreeMap<>(nhc);
findMovedPairs(geneTreeRootNode, jMovedNodes, brotherDescendants, lowerHeight, upperHeight);
allMovedNodes.add(jMovedNodes);
}
return allMovedNodes;
}
// identify nodes to be moved as part of a coordinated exchange move
private boolean findMovedPairs(Node geneTreeNode, Map<Node, Node> movedNodes, Set<String> brotherDescendants, double lowerHeight, double upperHeight) {
if (geneTreeNode.isLeaf()) {
final String descendantName = geneTreeNode.getID();
return brotherDescendants.contains(descendantName);
}
final Node leftChild = geneTreeNode.getLeft();
final Node rightChild = geneTreeNode.getRight();
final boolean leftOverlapsBrother = findMovedPairs(leftChild, movedNodes, brotherDescendants, lowerHeight, upperHeight);
final boolean rightOverlapsBrother = findMovedPairs(rightChild, movedNodes, brotherDescendants, lowerHeight, upperHeight);
final double nodeHeight = geneTreeNode.getHeight();
if (nodeHeight >= lowerHeight && nodeHeight < upperHeight) {
if (leftOverlapsBrother ^ rightOverlapsBrother) {
if (leftOverlapsBrother) {
movedNodes.put(geneTreeNode, leftChild);
} else {
movedNodes.put(geneTreeNode, rightChild);
}
}
}
return leftOverlapsBrother || rightOverlapsBrother;
}
}
| More work on coordinated wide exchange | src/starbeast2/WideExchange.java | More work on coordinated wide exchange |
|
Java | apache-2.0 | f1d765dfc7c394777393e410e7e434729a80b142 | 0 | buckett/sakai-gitflow,hackbuteer59/sakai,buckett/sakai-gitflow,pushyamig/sakai,surya-janani/sakai,tl-its-umich-edu/sakai,ktakacs/sakai,introp-software/sakai,hackbuteer59/sakai,frasese/sakai,ktakacs/sakai,kwedoff1/sakai,conder/sakai,buckett/sakai-gitflow,liubo404/sakai,bkirschn/sakai,lorenamgUMU/sakai,pushyamig/sakai,zqian/sakai,wfuedu/sakai,bzhouduke123/sakai,ktakacs/sakai,kwedoff1/sakai,introp-software/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,zqian/sakai,udayg/sakai,whumph/sakai,bkirschn/sakai,introp-software/sakai,noondaysun/sakai,kingmook/sakai,tl-its-umich-edu/sakai,liubo404/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,lorenamgUMU/sakai,colczr/sakai,bzhouduke123/sakai,tl-its-umich-edu/sakai,kwedoff1/sakai,liubo404/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,surya-janani/sakai,willkara/sakai,kwedoff1/sakai,liubo404/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,joserabal/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,puramshetty/sakai,liubo404/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,Fudan-University/sakai,hackbuteer59/sakai,conder/sakai,willkara/sakai,noondaysun/sakai,joserabal/sakai,colczr/sakai,willkara/sakai,bkirschn/sakai,wfuedu/sakai,wfuedu/sakai,ouit0408/sakai,whumph/sakai,lorenamgUMU/sakai,puramshetty/sakai,colczr/sakai,OpenCollabZA/sakai,udayg/sakai,ouit0408/sakai,kingmook/sakai,conder/sakai,colczr/sakai,noondaysun/sakai,udayg/sakai,rodriguezdevera/sakai,noondaysun/sakai,frasese/sakai,conder/sakai,udayg/sakai,rodriguezdevera/sakai,joserabal/sakai,conder/sakai,clhedrick/sakai,pushyamig/sakai,wfuedu/sakai,frasese/sakai,introp-software/sakai,frasese/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,liubo404/sakai,puramshetty/sakai,puramshetty/sakai,introp-software/sakai,clhedrick/sakai,OpenCollabZA/sakai,buckett/sakai-gitflow,pushyamig/sakai,kwedoff1/sakai,joserabal/sakai,zqian/sakai,Fudan-University/sakai,frasese/sakai,bkirschn/sakai,surya-janani/sakai,surya-janani/sakai,joserabal/sakai,buckett/sakai-gitflow,clhedrick/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,whumph/sakai,introp-software/sakai,noondaysun/sakai,bzhouduke123/sakai,whumph/sakai,ktakacs/sakai,Fudan-University/sakai,bzhouduke123/sakai,bzhouduke123/sakai,hackbuteer59/sakai,surya-janani/sakai,bzhouduke123/sakai,rodriguezdevera/sakai,udayg/sakai,willkara/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,Fudan-University/sakai,puramshetty/sakai,zqian/sakai,bkirschn/sakai,colczr/sakai,rodriguezdevera/sakai,colczr/sakai,frasese/sakai,clhedrick/sakai,bzhouduke123/sakai,tl-its-umich-edu/sakai,clhedrick/sakai,bkirschn/sakai,buckett/sakai-gitflow,Fudan-University/sakai,OpenCollabZA/sakai,whumph/sakai,joserabal/sakai,lorenamgUMU/sakai,frasese/sakai,ouit0408/sakai,kwedoff1/sakai,udayg/sakai,ktakacs/sakai,rodriguezdevera/sakai,whumph/sakai,clhedrick/sakai,zqian/sakai,duke-compsci290-spring2016/sakai,Fudan-University/sakai,kingmook/sakai,lorenamgUMU/sakai,willkara/sakai,ktakacs/sakai,puramshetty/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,kwedoff1/sakai,surya-janani/sakai,ktakacs/sakai,introp-software/sakai,joserabal/sakai,liubo404/sakai,wfuedu/sakai,rodriguezdevera/sakai,surya-janani/sakai,zqian/sakai,liubo404/sakai,bkirschn/sakai,kingmook/sakai,Fudan-University/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,OpenCollabZA/sakai,udayg/sakai,frasese/sakai,kingmook/sakai,joserabal/sakai,introp-software/sakai,puramshetty/sakai,lorenamgUMU/sakai,conder/sakai,udayg/sakai,colczr/sakai,zqian/sakai,OpenCollabZA/sakai,ouit0408/sakai,kingmook/sakai,duke-compsci290-spring2016/sakai,ouit0408/sakai,OpenCollabZA/sakai,bkirschn/sakai,kingmook/sakai,zqian/sakai,OpenCollabZA/sakai,conder/sakai,willkara/sakai,Fudan-University/sakai,wfuedu/sakai,conder/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,buckett/sakai-gitflow,ouit0408/sakai,wfuedu/sakai,hackbuteer59/sakai,noondaysun/sakai,surya-janani/sakai,pushyamig/sakai,pushyamig/sakai,noondaysun/sakai,pushyamig/sakai,willkara/sakai,hackbuteer59/sakai,puramshetty/sakai,rodriguezdevera/sakai,OpenCollabZA/sakai,clhedrick/sakai,colczr/sakai,ouit0408/sakai,wfuedu/sakai,kingmook/sakai,willkara/sakai | package org.sakaiproject.dash.entityprovider;
import java.util.List;
import java.util.Map;
import lombok.Setter;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.sakaiproject.dash.logic.DashboardLogic;
import org.sakaiproject.dash.app.DashboardCommonLogic;
import org.sakaiproject.dash.app.SakaiProxy;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.EntityView;
import org.sakaiproject.entitybroker.entityprovider.EntityProvider;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction;
import org.sakaiproject.entitybroker.entityprovider.capabilities.ActionsExecutable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Describeable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Outputable;
import org.sakaiproject.entitybroker.entityprovider.extension.Formats;
import org.sakaiproject.entitybroker.util.AbstractEntityProvider;
public class DashboardEntityProvider extends AbstractEntityProvider implements EntityProvider, AutoRegisterEntityProvider, Outputable, Describeable, ActionsExecutable {
public String getEntityPrefix() {
return "dash";
}
public String[] getHandledOutputFormats() {
return new String[] {Formats.JSON, Formats.XML};
}
public boolean entityExists(String id) {
return true;
}
@EntityCustomAction(action="news",viewKey=EntityView.VIEW_LIST)
public List<?> getNewsItems(EntityView view, EntityReference ref, Map<String, Object> params) {
String userUuid = sakaiProxy.getCurrentUserId();
if(StringUtils.isBlank(userUuid)) {
throw new SecurityException("You must be logged in to get a user's dashboard");
}
//get optional params
String siteId = (String)params.get("site");
boolean hidden = BooleanUtils.toBoolean((String)params.get("hidden"));
boolean starred = BooleanUtils.toBoolean((String)params.get("starred"));
//only return hidden items
if(hidden){
return dashboardCommonLogic.getHiddenNewsLinks(userUuid, siteId);
}
//only return starred items
if(starred){
return dashboardCommonLogic.getStarredNewsLinks(userUuid, siteId);
}
//return everything
return dashboardCommonLogic.getCurrentNewsLinks(userUuid, siteId);
}
@EntityCustomAction(action="calendar",viewKey=EntityView.VIEW_LIST)
public List<?> getCalendarItems(EntityView view, EntityReference ref, Map<String, Object> params) {
String userUuid = sakaiProxy.getCurrentUserId();
if(StringUtils.isBlank(userUuid)) {
throw new SecurityException("You must be logged in to get a user's dashboard");
}
//get optional params
String siteId = (String)params.get("site");
boolean hidden = BooleanUtils.toBoolean((String)params.get("hidden"));
boolean starred = BooleanUtils.toBoolean((String)params.get("starred"));
boolean past = BooleanUtils.toBoolean((String)params.get("past"));
//only return starred items
if(starred){
return dashboardCommonLogic.getStarredCalendarLinks(userUuid, siteId);
}
//only return past items. Could be hidden depending on param
if(past){
return dashboardCommonLogic.getPastCalendarLinks(userUuid, siteId, hidden);
}
//return everything. Could be hidden depending on param
return dashboardCommonLogic.getFutureCalendarLinks(userUuid, siteId, hidden);
}
@Setter
private DashboardLogic dashboardLogic;
public void setDashboardLogic( DashboardLogic dashboardLogic )
{
this.dashboardLogic = dashboardLogic;
}
@Setter
private DashboardCommonLogic dashboardCommonLogic;
public void setDashboardCommonLogic( DashboardCommonLogic dashboardCommonLogic )
{
this.dashboardCommonLogic = dashboardCommonLogic;
}
@Setter
private SakaiProxy sakaiProxy;
public void setSakaiProxy( SakaiProxy sakaiProxy )
{
this.sakaiProxy = sakaiProxy;
}
} | dashboard/impl/src/java/org/sakaiproject/dash/entityprovider/DashboardEntityProvider.java | package org.sakaiproject.dash.entityprovider;
import java.util.List;
import java.util.Map;
import lombok.Setter;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.sakaiproject.dash.logic.DashboardLogic;
import org.sakaiproject.dash.app.DashboardCommonLogic;
import org.sakaiproject.dash.app.SakaiProxy;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.EntityView;
import org.sakaiproject.entitybroker.entityprovider.EntityProvider;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction;
import org.sakaiproject.entitybroker.entityprovider.capabilities.ActionsExecutable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.AutoRegisterEntityProvider;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Describeable;
import org.sakaiproject.entitybroker.entityprovider.capabilities.Outputable;
import org.sakaiproject.entitybroker.entityprovider.extension.Formats;
import org.sakaiproject.entitybroker.util.AbstractEntityProvider;
public class DashboardEntityProvider extends AbstractEntityProvider implements EntityProvider, AutoRegisterEntityProvider, Outputable, Describeable, ActionsExecutable {
public String getEntityPrefix() {
return "dash";
}
public String[] getHandledOutputFormats() {
return new String[] {Formats.JSON, Formats.XML};
}
public boolean entityExists(String id) {
return true;
}
@EntityCustomAction(action="news",viewKey=EntityView.VIEW_LIST)
public List<?> getNewsItems(EntityView view, EntityReference ref, Map<String, Object> params) {
String userUuid = sakaiProxy.getCurrentUserId();
if(StringUtils.isBlank(userUuid)) {
throw new SecurityException("You must be logged in to get a user's dashboard");
}
//get optional params
String siteId = (String)params.get("site");
boolean hidden = BooleanUtils.toBoolean((String)params.get("hidden"));
boolean starred = BooleanUtils.toBoolean((String)params.get("starred"));
//only return hidden items
if(hidden){
return dashboardCommonLogic.getHiddenNewsLinks(userUuid, siteId);
}
//only return starred items
if(starred){
return dashboardCommonLogic.getStarredNewsLinks(userUuid, siteId);
}
//return everything
return dashboardCommonLogic.getCurrentNewsLinks(userUuid, siteId);
}
@EntityCustomAction(action="calendar",viewKey=EntityView.VIEW_LIST)
public List<?> getCalendarItems(EntityView view, EntityReference ref, Map<String, Object> params) {
String userUuid = sakaiProxy.getCurrentUserId();
if(StringUtils.isBlank(userUuid)) {
throw new SecurityException("You must be logged in to get a user's dashboard");
}
//get optional params
String siteId = (String)params.get("site");
boolean hidden = BooleanUtils.toBoolean((String)params.get("hidden"));
boolean starred = BooleanUtils.toBoolean((String)params.get("starred"));
boolean past = BooleanUtils.toBoolean((String)params.get("past"));
//only return starred items
if(starred){
return dashboardCommonLogic.getStarredCalendarLinks(userUuid, siteId);
}
//only return past items. Could be hidden depending on param
if(past){
return dashboardCommonLogic.getPastCalendarLinks(userUuid, siteId, hidden);
}
//return everything. Could be hidden depending on param
return dashboardCommonLogic.getFutureCalendarLinks(userUuid, siteId, hidden);
}
@Setter
private DashboardLogic dashboardLogic;
@Setter
private DashboardCommonLogic dashboardCommonLogic;
@Setter
private SakaiProxy sakaiProxy;
} | DASH-336 Java 8 fixes
| dashboard/impl/src/java/org/sakaiproject/dash/entityprovider/DashboardEntityProvider.java | DASH-336 Java 8 fixes |
|
Java | apache-2.0 | 441181ca2297d53d61946b5c0b3dee2ac916240b | 0 | ANPez/FramedImageView | package com.antonionicolaspina.framedimageview;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
public final class FramedImageView extends View implements ScaleGestureDetector.OnScaleGestureListener {
private static final String TAG = FramedImageView.class.getSimpleName();
private static final int INVALID_POINTER_ID = -1;
private Bitmap image;
private Bitmap frame;
private float minScale = 0.1f;
private float maxScale = 5f;
private float scale = 1.0f;
private Rect frameDestinationRect = new Rect();
private int activePointerId = INVALID_POINTER_ID;
private float activePointerX;
private float activePointerY;
private float positionX;
private float positionY;
private int viewWidth;
private int viewHeight;
public FramedImageView(Context context) {
super(context);
init(context, null);
}
public FramedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public FramedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FramedImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
ScaleGestureDetector gestureDetector;
protected void init(Context context, AttributeSet attributes) {
if (null != attributes) {
TypedArray attrs = context.getTheme().obtainStyledAttributes(attributes, R.styleable.FramedImageView, 0, 0);
int imageResId = attrs.getResourceId(R.styleable.FramedImageView_image, View.NO_ID);
if (View.NO_ID != imageResId) {
setImage(imageResId);
}
int frameResId = attrs.getResourceId(R.styleable.FramedImageView_frame, View.NO_ID);
if (View.NO_ID != frameResId) {
setFrame(frameResId);
}
minScale = attrs.getFloat(R.styleable.FramedImageView_minScale, minScale);
maxScale = attrs.getFloat(R.styleable.FramedImageView_maxScale, maxScale);
attrs.recycle();
}
gestureDetector = new ScaleGestureDetector(context, this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (null != image) {
canvas.save();
canvas.translate(positionX, positionY);
canvas.scale(scale, scale);
canvas.drawBitmap(image, 0, 0, null);
canvas.restore();
}
if (null != frame) {
canvas.drawBitmap(frame, null, frameDestinationRect, null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
final int action = event.getAction();
switch(action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
activePointerId = event.getPointerId(0);
activePointerX = event.getX(activePointerId);
activePointerY = event.getY(activePointerId);
break;
case MotionEvent.ACTION_UP:
activePointerId = INVALID_POINTER_ID;
break;
case MotionEvent.ACTION_POINTER_UP: {
// Extract the index of the pointer that left the touch sensor
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == activePointerId) { // This was our active pointer going up. Choose a new active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
activePointerX = event.getX(newPointerIndex);
activePointerY = event.getY(newPointerIndex);
activePointerId = event.getPointerId(newPointerIndex);
}
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = event.findPointerIndex(activePointerId);
final float x = event.getX(pointerIndex);
final float y = event.getY(pointerIndex);
positionX += x - activePointerX;
positionY += y - activePointerY;
activePointerX = x;
activePointerY = y;
invalidate();
return true;
}
}
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
viewWidth = MeasureSpec.getSize(widthMeasureSpec);
viewHeight = MeasureSpec.getSize(heightMeasureSpec);
Log.d(TAG, String.format("onMeasure(%d, %d)", viewWidth, viewHeight));
if (null != frame) {
final float frameWidth = frame.getWidth();
final float frameHeight = frame.getHeight();
final float scale = Math.min(viewWidth/frameWidth, viewHeight/frameHeight);
viewWidth = (int) (scale*frameWidth);
viewHeight = (int) (scale*frameHeight);
}
resetPositions();
Log.d(TAG, String.format("setMeasuredDimension(%d, %d)", viewWidth, viewHeight));
frameDestinationRect.right = viewWidth;
frameDestinationRect.bottom = viewHeight;
setMeasuredDimension(viewWidth, viewHeight);
}
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
float scaleFactor = scaleGestureDetector.getScaleFactor();
scale = Math.max(minScale, Math.min(scale*scaleFactor, maxScale));
invalidate();
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) {
}
public void setImage(int resourceId) {
image = BitmapFactory.decodeResource(getResources(), resourceId);
resetPositions();
invalidate();
}
public void setFrame(int resourceId) {
frame = BitmapFactory.decodeResource(getResources(), resourceId);
requestLayout();
}
public void resetPositions() {
if (null != image) {
final float imageWidth = image.getWidth();
final float imageHeight = image.getHeight();
scale = Math.min(viewWidth/imageWidth, viewHeight/imageHeight);
positionX = (viewWidth - imageWidth*scale)/2f;
positionY = (viewHeight - imageHeight*scale)/2f;
if (scale < minScale) {
minScale = scale;
}
}
}
}
| framedimageview/src/main/java/com/antonionicolaspina/framedimageview/FramedImageView.java | package com.antonionicolaspina.framedimageview;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
public final class FramedImageView extends View implements ScaleGestureDetector.OnScaleGestureListener {
private static final String TAG = FramedImageView.class.getSimpleName();
private static final int INVALID_POINTER_ID = -1;
private Bitmap image;
private Bitmap frame;
private float minScale = 0.1f;
private float maxScale = 5f;
private float scale = 1.0f;
private Rect frameDestinationRect = new Rect();
private int activePointerId = INVALID_POINTER_ID;
private float activePointerX;
private float activePointerY;
private float positionX;
private float positionY;
public FramedImageView(Context context) {
super(context);
init(context, null);
}
public FramedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public FramedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FramedImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
ScaleGestureDetector gestureDetector;
protected void init(Context context, AttributeSet attributes) {
if (null != attributes) {
TypedArray attrs = context.getTheme().obtainStyledAttributes(attributes, R.styleable.FramedImageView, 0, 0);
int imageResId = attrs.getResourceId(R.styleable.FramedImageView_image, View.NO_ID);
if (View.NO_ID != imageResId) {
image = BitmapFactory.decodeResource(context.getResources(), imageResId);
}
int frameResId = attrs.getResourceId(R.styleable.FramedImageView_frame, View.NO_ID);
if (View.NO_ID != frameResId) {
frame = BitmapFactory.decodeResource(context.getResources(), frameResId);
frameDestinationRect.right = frame.getWidth();
frameDestinationRect.bottom = frame.getHeight();
}
minScale = attrs.getFloat(R.styleable.FramedImageView_minScale, minScale);
maxScale = attrs.getFloat(R.styleable.FramedImageView_maxScale, maxScale);
attrs.recycle();
}
gestureDetector = new ScaleGestureDetector(context, this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (null != image) {
canvas.save();
canvas.translate(positionX, positionY);
canvas.scale(scale, scale);
canvas.drawBitmap(image, 0, 0, null);
canvas.restore();
}
if (null != frame) {
canvas.drawBitmap(frame, null, frameDestinationRect, null);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
final int action = event.getAction();
switch(action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
activePointerId = event.getPointerId(0);
activePointerX = event.getX(activePointerId);
activePointerY = event.getY(activePointerId);
break;
case MotionEvent.ACTION_UP:
activePointerId = INVALID_POINTER_ID;
break;
case MotionEvent.ACTION_POINTER_UP: {
// Extract the index of the pointer that left the touch sensor
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == activePointerId) { // This was our active pointer going up. Choose a new active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
activePointerX = event.getX(newPointerIndex);
activePointerY = event.getY(newPointerIndex);
activePointerId = event.getPointerId(newPointerIndex);
}
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = event.findPointerIndex(activePointerId);
final float x = event.getX(pointerIndex);
final float y = event.getY(pointerIndex);
positionX += x - activePointerX;
positionY += y - activePointerY;
activePointerX = x;
activePointerY = y;
invalidate();
return true;
}
}
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
Log.d(TAG, String.format("onMeasure(%d, %d)", width, height));
if (null != frame) {
final float frameWidth = frame.getWidth();
final float frameHeight = frame.getHeight();
final float scale = Math.min(width/frameWidth, height/frameHeight);
width = (int) (scale*frameWidth);
height = (int) (scale*frameHeight);
}
if (null != image) {
final float imageWidth = image.getWidth();
final float imageHeight = image.getHeight();
scale = Math.min(width/imageWidth, height/imageHeight);
positionX = (width - imageWidth*scale)/2f;
positionY = (height - imageHeight*scale)/2f;
if (scale < minScale) {
minScale = scale;
}
}
Log.d(TAG, String.format("setMeasuredDimension(%d, %d)", width, height));
frameDestinationRect.right = width;
frameDestinationRect.bottom = height;
setMeasuredDimension(width, height);
}
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
float scaleFactor = scaleGestureDetector.getScaleFactor();
scale = Math.max(minScale, Math.min(scale*scaleFactor, maxScale));
invalidate();
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) {
}
}
| Ability to set frame and image in code.
| framedimageview/src/main/java/com/antonionicolaspina/framedimageview/FramedImageView.java | Ability to set frame and image in code. |
|
Java | apache-2.0 | f815e18b05b020ebbdcb3028d4e3a9e82b0a0327 | 0 | AndroidX/constraintlayout,androidx/constraintlayout,androidx/constraintlayout,AndroidX/constraintlayout,androidx/constraintlayout,AndroidX/constraintlayout | /*
* Copyright (C) 2019 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 androidx.constraintLayout.desktop.ui.timeline;
import androidx.constraintLayout.desktop.scan.CLScan;
import androidx.constraintLayout.desktop.ui.adapters.Annotations.NotNull;
import androidx.constraintLayout.desktop.ui.adapters.*;
import androidx.constraintLayout.desktop.ui.timeline.TimeLineTopLeft.TimelineCommands;
import androidx.constraintLayout.desktop.ui.ui.MTagActionListener;
import androidx.constraintLayout.desktop.ui.ui.MeModel;
import androidx.constraintLayout.desktop.ui.ui.MotionEditorSelector;
import androidx.constraintLayout.desktop.ui.ui.MotionEditorSelector.TimeLineCmd;
import androidx.constraintLayout.desktop.ui.ui.MotionEditorSelector.TimeLineListener;
import androidx.constraintLayout.desktop.ui.ui.Utils;
import androidx.constraintLayout.desktop.ui.utils.Debug;
import androidx.constraintLayout.desktop.utils.Desk;
import androidx.constraintLayout.desktop.utils.ScenePicker;
import androidx.constraintlayout.core.parser.CLKey;
import androidx.constraintlayout.core.parser.CLObject;
import androidx.constraintlayout.core.parser.CLParser;
import androidx.constraintlayout.core.parser.CLParsingException;
import javax.swing.Timer;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.LayerUI;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.List;
import java.util.*;
import static androidx.constraintLayout.desktop.ui.adapters.MotionSceneAttrs.Tags.KEY_FRAME_SET;
/**
* The panel that displays the timeline
*/
public class TimeLinePanel extends JPanel {
public static final boolean DEBUG = false;
private static int PLAY_TIMEOUT = 60 * 60 * 1000;
private static int MS_PER_FRAME = 15;
private static float TIMELINE_MIN = 0.0f;
private static float TIMELINE_MAX = 100.0f;
private static float[] ourSpeedsMultipliers = {0.25f, 0.5f, 1f, 2f, 4f};
MotionEditorSelector mMotionEditorSelector;
private TimelineStructure mTimelineStructure = new TimelineStructure();
private TimeLineTopPanel myTimeLineTopPanel = new TimeLineTopPanel(mTimelineStructure);
private MTag mSelectedKeyFrame;
private boolean mMouseDown = false;
private METimeLine mTimeLine = new METimeLine();
private JScrollPane myScrollPane = new MEScrollPane(mTimeLine);
private TimeLineTopLeft mTimeLineTopLeft = new TimeLineTopLeft();
private MeModel mMeModel;
private MTag mTransitionTag;
private float mMotionProgress; // from 0 .. 1;
private Timer myTimer;
private Timer myPlayLimiter;
private int myYoyo = 0;
private int mDuration = 1000;
private float myProgressPerMillisecond = 1 / (float) mDuration;
private long last_time;
private int mCurrentSpeed = 2;
private boolean mIsPlaying = false;
private ArrayList<TimeLineListener> mTimeLineListeners = new ArrayList<>();
private int mDirection = 1;
int[] myXPoints = new int[5];
int[] myYPoints = new int[5];
private MTagActionListener mListener;
Timer myMouseDownTimer;
JPopupMenu myPlaybackSpeedPopupMenu = new JPopupMenu();
private long mLastEmitted;
@Override
public void updateUI() {
super.updateUI();
if (mTimeLineTopLeft != null) {
mTimeLineTopLeft.updateUI();
}
if (mTimeLine != null) {
mTimeLine.updateUI();
}
}
public TimeLinePanel() {
super(new BorderLayout());
for (int i = 0; i < ourSpeedsMultipliers.length; i++) {
myPlaybackSpeedPopupMenu.add(ourSpeedsMultipliers[i] + "x").addActionListener(createPlaybackSpeedPopupMenuActionListener(i));
}
JPanel top = new JPanel(new BorderLayout());
top.add(myTimeLineTopPanel, BorderLayout.CENTER);
top.add(mTimeLineTopLeft, BorderLayout.WEST);
myScrollPane.setColumnHeaderView(top);
myScrollPane.setBorder(BorderFactory.createEmptyBorder());
int flags = 0;
mTimeLine.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int code = e.getExtendedKeyCode();
switch (code) {
case KeyEvent.VK_V:
if (!e.isControlDown()) {
break;
}
// Fallthrough
case KeyEvent.VK_PASTE:
paste();
break;
//////////////////////////////////////////////////////////////
case KeyEvent.VK_C:
if (!e.isControlDown()) {
break;
}
// Fallthrough copy
case KeyEvent.VK_COPY:
if (e.isControlDown()) {
if (mSelectedKeyFrame != null) {
MEUI.copy(mSelectedKeyFrame);
}
}
break;
/////////////////////////////////////////////////////////
case KeyEvent.VK_X:
if (!e.isControlDown()) {
break;
}
// Fallthrough cut
case KeyEvent.VK_CUT:
if (e.isControlDown()) {
if (mSelectedKeyFrame != null) {
MEUI.cut(mSelectedKeyFrame);
}
}
break;
case KeyEvent.VK_UP:
int index = mTimeLine.getSelectedIndex() - 1;
if (index < 0) {
index = mTimeLine.getComponentCount() - 2;
}
mSelectedKeyFrame = null;
mTimeLine.setSelectedIndex(index);
groupSelected();
break;
case KeyEvent.VK_DOWN:
index = mTimeLine.getSelectedIndex() + 1;
if (index > mTimeLine.getComponentCount() - 2) {
index = 0;
}
mSelectedKeyFrame = null;
mTimeLine.setSelectedIndex(index);
groupSelected();
break;
case KeyEvent.VK_DELETE:
case KeyEvent.VK_BACK_SPACE:
if (mListener != null) {
if (mSelectedKeyFrame != null) {
mListener.delete(new MTag[]{mSelectedKeyFrame}, 0);
}
}
break;
case KeyEvent.VK_LEFT: {
TimeLineRowData rowData = mTimeLine.getSelectedValue();
int numOfKeyFrames = rowData.mKeyFrames.size();
int indexInRow = -1;
for (int i = 0; i < numOfKeyFrames; i++) {
if (rowData.mKeyFrames.get(i).equals(mSelectedKeyFrame)) {
indexInRow = i;
break;
}
}
int selIndex = (indexInRow - 1 + numOfKeyFrames) % numOfKeyFrames;
mSelectedKeyFrame = rowData.mKeyFrames.get(selIndex);
mTimeLine.getTimeLineRow(mTimeLine.getSelectedIndex()).setSelectedKeyFrame(mSelectedKeyFrame);
Track.timelineTableSelect(mMeModel.myTrack);
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME, new MTag[]{mSelectedKeyFrame}, flags);
if (mListener != null && mSelectedKeyFrame != null) {
mListener.select(mSelectedKeyFrame, 0);
}
}
break;
case KeyEvent.VK_RIGHT: {
TimeLineRowData rowData = mTimeLine.getSelectedValue();
int numOfKeyFrames = rowData.mKeyFrames.size();
int indexInRow = -1;
for (int i = 0; i < numOfKeyFrames; i++) {
if (rowData.mKeyFrames.get(i).equals(mSelectedKeyFrame)) {
indexInRow = i;
break;
}
}
int selIndex = (indexInRow + 1) % numOfKeyFrames;
mSelectedKeyFrame = rowData.mKeyFrames.get(selIndex);
mTimeLine.getTimeLineRow(mTimeLine.getSelectedIndex()).setSelectedKeyFrame(mSelectedKeyFrame);
Track.timelineTableSelect(mMeModel.myTrack);
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME, new MTag[]{mSelectedKeyFrame}, flags);
if (mListener != null && mSelectedKeyFrame != null) {
mListener.select(mSelectedKeyFrame, 0);
}
}
break;
}
}
});
mTimeLine.setFocusable(true);
mTimeLine.setRequestFocusEnabled(true);
mTimeLineTopLeft.addControlsListener((e, mode) -> {
performCommand(e, mode);
});
JLayer<JComponent> jlayer = new JLayer<JComponent>(myScrollPane, new LayerUI<JComponent>() {
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
paintCursor(g, c);
}
@Override
public void installUI(JComponent c) {
super.installUI(c);
JLayer jlayer = (JLayer) c;
jlayer.setLayerEventMask(
AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK
);
}
@Override
protected void processMouseMotionEvent(MouseEvent e, JLayer l) {
processMouseDrag(e);
}
@Override
protected void processMouseEvent(MouseEvent e, JLayer l) {
processMouseDrag(e);
}
});
add(jlayer);
mTimelineStructure.addWidthChangedListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
mTimeLine.repaint();
}
});
mTimeLine.setBackground(MEUI.ourAvgBackground);
myTimeLineTopPanel.setRange(TIMELINE_MIN, TIMELINE_MAX);
mTimeLine.addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
groupSelected();
}
});
}
private void paste() {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
String buff = (String) (clipboard.getContents(this).getTransferData(DataFlavor.stringFlavor));
StringMTag pastedTag = StringMTag.parse(buff);
HashMap<String, MTag.Attribute> attr = pastedTag.getAttrList();
if (mSelectedKeyFrame == null) {
TimeLineRowData rowData = mTimeLine.getSelectedValue();
if (rowData.mKeyFrames.isEmpty()) {
return;
}
mSelectedKeyFrame = rowData.mKeyFrames.get(0);
}
MTag keyFrameSet = mSelectedKeyFrame.getParent();
MTag.TagWriter writer = keyFrameSet.getChildTagWriter(pastedTag.getTagName());
for (String s : attr.keySet()) {
MTag.Attribute a = attr.get(s);
if (a == null || a.mAttribute.equals("framePosition")) {
writer.setAttribute(a.mNamespace, a.mAttribute, Integer.toString((int) (mMotionProgress * 100 + 0.5)));
} else {
writer.setAttribute(a.mNamespace, a.mAttribute, a.mValue);
}
}
MTag[] children = pastedTag.getChildTags();
for (int i = 0; i < children.length; i++) {
MTag child = children[i];
MTag.TagWriter cw = writer.getChildTagWriter(child.getTagName());
HashMap<String, MTag.Attribute> cwAttrMap = child.getAttrList();
for (String cwAttrStr : cwAttrMap.keySet()) {
MTag.Attribute cwAttr = cwAttrMap.get(cwAttrStr);
cw.setAttribute(cwAttr.mNamespace, cwAttr.mAttribute, cwAttr.mValue);
}
}
mSelectedKeyFrame = writer.commit("paste");
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setActionListener(MTagActionListener l) {
mListener = l;
}
public void stopAnimation() {
performCommand(TimelineCommands.PAUSE, 0);
}
private static String buildKey(MTag keyFrame) {
String targetKey;
String target = keyFrame.getAttributeValue("motionTarget");
targetKey = target;
if (target != null && target.startsWith("@")) {
targetKey = "Id:" + Utils.stripID(target);
} else {
targetKey = "Tag:" + target;
}
String name = keyFrame.getTagName();
targetKey += name;
String[] keys = new String[0];
switch (name) {
case "KeyPosition":
keys = MotionLayoutAttrs.KeyPositionKey;
break;
case "KeyAttribute":
keys = MotionLayoutAttrs.KeyAttributesKey;
break;
case "KeyCycle":
keys = MotionLayoutAttrs.KeyCycleKey;
break;
case "KeyTimeCycle":
keys = MotionLayoutAttrs.KeyTimeCycleKey;
break;
case "KeyTrigger":
keys = MotionLayoutAttrs.KeyTriggerKey;
break;
}
for (String key : keys) {
targetKey += get(keyFrame, key);
}
return targetKey;
}
private static String get(MTag tag, String attr) {
String s = tag.getAttributeValue(attr);
return (s == null) ? "" : attr;
}
public void clearSelection() {
mSelectedKeyFrame = null;
int n = mTimeLine.getComponentCount();
if (n == 0 || mTimeLine.mSelectedIndex >= n) {
return;
}
Component component = mTimeLine.getComponent(mTimeLine.mSelectedIndex);
if (component instanceof TimeLineRow) {
TimeLineRow child = ((TimeLineRow) component);
child.setSelected(true);
repaint();
}
}
public void addTimeLineListener(TimeLineListener timeLineListener) {
mTimeLineListeners.add(timeLineListener);
}
public void notifyTimeLineListeners(TimeLineCmd cmd, Float value) {
mLastEmitted = System.currentTimeMillis();
for (TimeLineListener listener : mTimeLineListeners) {
listener.command(cmd, value);
}
}
private void refreshCycling(boolean cycle) {
MTag[] kef = mTransitionTag.getChildTags(MotionSceneAttrs.Tags.KEY_FRAME_SET);
if (kef == null || kef.length == 0) {
cycle = false;
} else {
MTag[] timeCycle = kef[0].getChildTags(MotionSceneAttrs.Tags.KEY_TIME_CYCLE);
if (timeCycle == null || timeCycle.length == 0) {
cycle = false;
}
}
if (cycle) {
if (myMouseDownTimer != null) {
myMouseDownTimer.stop();
myMouseDownTimer = null;
}
myMouseDownTimer = new Timer(MS_PER_FRAME, e -> {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, mMotionProgress);
});
myMouseDownTimer.start();
} else {
if (myMouseDownTimer != null) {
myMouseDownTimer.stop();
myMouseDownTimer = null;
}
}
}
private void createTimer() {
if (myTimer == null) {
myTimer = new Timer(MS_PER_FRAME, e -> {
progress();
});
myTimer.setRepeats(true);
myTimer.start();
}
if (myPlayLimiter == null) {
myPlayLimiter = new Timer(PLAY_TIMEOUT, e -> {
destroyTimer();
});
myPlayLimiter.setRepeats(false);
myPlayLimiter.start();
}
}
private void watchdog() {
if (myPlayLimiter != null) {
myPlayLimiter.restart();
}
}
private void destroyTimer() {
if (myTimer != null) {
myTimer.stop();
myTimer = null;
}
if (myPlayLimiter != null) {
myPlayLimiter.stop();
myPlayLimiter = null;
}
}
private ActionListener createPlaybackSpeedPopupMenuActionListener(int playbackSpeedIndex) {
return new ActionListener() {
int speedIndex = playbackSpeedIndex;
@Override
public void actionPerformed(ActionEvent e) {
Track.animationSpeed(mMeModel.myTrack);
mCurrentSpeed = speedIndex;
myProgressPerMillisecond = ourSpeedsMultipliers[mCurrentSpeed] / (float) mDuration;
mTimeLineTopLeft.mSlow.setToolTipText(mDuration + " x " + ourSpeedsMultipliers[mCurrentSpeed]);
mTimeLineTopLeft.mSlow.setText(ourSpeedsMultipliers[mCurrentSpeed] + "x");
}
};
}
private void showPlaybackSpeedPopup() {
myPlaybackSpeedPopupMenu.show(mTimeLineTopLeft.mSlow, 0, 20);
}
private void performCommand(TimelineCommands e, int mode) {
watchdog();
switch (e) {
case PLAY:
last_time = System.nanoTime();
Track.playAnimation(mMeModel.myTrack);
createTimer();
notifyTimeLineListeners(TimeLineCmd.MOTION_PLAY, mMotionProgress);
mIsPlaying = true;
break;
case SPEED:
showPlaybackSpeedPopup();
break;
case LOOP:
Track.animationDirectionToggle(mMeModel.myTrack);
myYoyo = mode;
break;
case PAUSE:
mIsPlaying = false;
destroyTimer();
notifyTimeLineListeners(TimeLineCmd.MOTION_STOP, mMotionProgress);
mTimeLineTopLeft.displayPlay();
break;
case END:
Track.animationEnd(mMeModel.myTrack);
mIsPlaying = false;
destroyTimer();
mMotionProgress = 1;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, mMotionProgress);
notifyTimeLineListeners(TimeLineCmd.MOTION_STOP, mMotionProgress);
break;
case START:
Track.animationStart(mMeModel.myTrack);
mIsPlaying = false;
destroyTimer();
mMotionProgress = 0;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, mMotionProgress);
notifyTimeLineListeners(TimeLineCmd.MOTION_STOP, mMotionProgress);
break;
}
}
private void progress() {
if (!mIsPlaying || mMouseDown) {
return;
}
long time = System.nanoTime();
switch (myYoyo) {
case 0:
mMotionProgress += myProgressPerMillisecond * ((time - last_time) * 1E-6f);
if (mMotionProgress > 1f) {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, 1f);
mMotionProgress = mMotionProgress - 1;
}
break;
case 1:
mMotionProgress -= myProgressPerMillisecond * ((time - last_time) * 1E-6f);
if (mMotionProgress < 0f) {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, 0f);
mMotionProgress = 1 + mMotionProgress;
}
break;
case 2:
mMotionProgress += (mDirection) * myProgressPerMillisecond * ((time - last_time) * 1E-6f);
if (mMotionProgress < 0f) {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, 0f);
mDirection = +1;
mMotionProgress = -mMotionProgress;
} else if (mMotionProgress > 1f) {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, 1f);
mDirection = -1;
mMotionProgress = 1 - (mMotionProgress - 1);
}
break;
}
last_time = time;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, mMotionProgress);
repaint();
}
private void groupSelected() {
if (mTimeLine == null || mTimeLine.getSelectedValue() == null
|| mTimeLine.getSelectedValue().mKeyFrames == null) {
if (mTransitionTag != null) {
mMotionEditorSelector
.notifyListeners(MotionEditorSelector.Type.TRANSITION, new MTag[]{mTransitionTag}, 0);
}
return;
}
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME_GROUP,
mTimeLine.getSelectedValue().mKeyFrames.toArray(new MTag[0]), 0);
}
public void setMTag(MTag transitionTag, MeModel model) {
MTag newSelection = (model == null) ? null : findSelectedKeyFrameInNewModel(model);
mTransitionTag = transitionTag;
if (mTransitionTag != null) {
String duration = mTransitionTag.getAttributeValue("duration");
if (duration != null) {
try {
int durationInt = Integer.parseInt(duration);
mDuration = durationInt;
if (mDuration == 0) {
mDuration = 1000;
}
mCurrentSpeed = 2;
myProgressPerMillisecond = 1 / (float) mDuration;
} catch (NumberFormatException e) {
}
}
} else {
mDuration = 1000;
mCurrentSpeed = 2;
myProgressPerMillisecond = 1 / (float) mDuration;
}
if (mTimeLineTopLeft != null && mTimeLineTopLeft.mSlow != null) {
mTimeLineTopLeft.mSlow.setToolTipText(mDuration + " x " + ourSpeedsMultipliers[mCurrentSpeed]);
}
mSelectedKeyFrame = null;
mMeModel = model;
List<TimeLineRowData> list = transitionTag != null ? buildTransitionList() : Collections.emptyList();
mTimeLine.setListData(list, model);
if (transitionTag != null && mMotionEditorSelector != null) {
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.TRANSITION, new MTag[]{transitionTag}, 0);
}
if (newSelection != null) {
int index = findKeyFrameInRows(list, newSelection);
if (index >= 0) {
mTimeLine.setSelectedIndex(index);
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME, new MTag[]{newSelection}, 0);
mSelectedKeyFrame = newSelection;
}
}
}
private MTag findSelectedKeyFrameInNewModel(@NotNull MeModel newModel) {
if (mSelectedKeyFrame == null) {
return null;
}
MTag oldKeyFrameSet = mSelectedKeyFrame.getParent();
if (oldKeyFrameSet == null) {
return null;
}
MTag oldTransition = oldKeyFrameSet.getParent();
if (oldTransition == null) {
return null;
}
MTag transition = newModel.motionScene.getChildTagWithTreeId(MotionSceneAttrs.Tags.TRANSITION, oldTransition.getTreeId());
if (transition == null) {
return null;
}
for (MTag kfSet : transition.getChildTags(MotionSceneAttrs.Tags.KEY_FRAME_SET)) {
MTag keyFrame = kfSet.getChildTagWithTreeId(mSelectedKeyFrame.getTagName(), mSelectedKeyFrame.getTreeId());
if (keyFrame != null) {
return keyFrame;
}
}
return null;
}
private int findKeyFrameInRows(@NotNull List<TimeLineRowData> rows, @NotNull MTag keyFrame) {
for (int index = 0; index < rows.size(); index++) {
if (rows.get(index).mKeyFrames.contains(keyFrame)) {
return index;
}
}
return -1;
}
private List<TimeLineRowData> buildTransitionList() {
List<TimeLineRowData> views = new ArrayList<>();
TreeMap<String, ArrayList<MTag>> keyMap = new TreeMap<>();
MTag[] keyFrameSets = mTransitionTag.getChildTags("KeyFrameSet");
for (int i = 0; i < keyFrameSets.length; i++) {
MTag keyFrameSet = keyFrameSets[i];
MTag[] keyFrames = keyFrameSet.getChildTags();
for (int j = 0; j < keyFrames.length; j++) {
MTag keyFrame = keyFrames[j];
String targetKey = buildKey(keyFrame);
if (!keyMap.containsKey(targetKey)) {
ArrayList<MTag> list = new ArrayList<>();
keyMap.put(targetKey, list);
}
keyMap.get(targetKey).add(keyFrame);
}
}
for (String id : keyMap.keySet()) {
TimeLineRowData row = new TimeLineRowData();
row.mKeyFrames = keyMap.get(id);
row.buildKey(row.mKeyFrames.get(0));
row.buildTargetStrings(row.mKeyFrames.get(0));
views.add(row);
}
return views;
}
boolean matches(String target, TimeLineRowData view) {
if (target == null) {
return false;
}
if (target.startsWith("@id") || target.startsWith("@+id")) {
return Utils.stripID(target).equals(view.mKey);
}
String tag = view.mStartConstraintSet.getAttributeValue("layout_constraintTag");
if (tag == null) { // TODO walk derived constraints
System.err.println(
view.mKey + " " + view.mLayoutView + " id = " + ((view.mLayoutView == null)
? view.mLayoutView.getAttributeValue("id") : ""));
tag = view.mLayoutView.getAttributeValue("layout_constraintTag");
}
if (tag.matches(target)) {
return true;
}
return false;
}
/**
* Get and create if does not exist.
*/
TimeLineRowData addRow(List<TimeLineRowData> views, String viewId) {
for (TimeLineRowData view : views) {
if (view.mKey.equals(viewId)) {
return view;
}
}
TimeLineRowData view = new TimeLineRowData();
view.mKey = viewId;
views.add(view);
return view;
}
TimeLineRowData get(List<TimeLineRowData> views, String viewId) {
for (TimeLineRowData view : views) {
if (view.mKey.equals(viewId)) {
return view;
}
}
return null;
}
/**
* Draws the cursor
*
* @param g
* @param c
*/
private void paintCursor(Graphics g, JComponent c) {
if (mTimelineStructure.myXTicksPixels == null
|| mTimelineStructure.myXTicksPixels.length == 0) {
return;
}
Graphics2D g2 = (Graphics2D) g;
int w = c.getWidth();
int h = c.getHeight();
int timeStart = MEUI.ourLeftColumnWidth + mTimelineStructure.myXTicksPixels[0];
int timeWidth = mTimelineStructure.myXTicksPixels[mTimelineStructure.myXTicksPixels.length - 1]
- mTimelineStructure.myXTicksPixels[0];
int y = 0;
int x = timeStart + (int) (mMotionProgress * (timeWidth));
Color lineColor = MEUI.myTimeCursorColor;
int inset = 2;
int d = (int) (mMotionProgress * 100);
String digits = Integer.toString(d);
switch (digits.length()) {
case 1:
digits = ".0" + digits;
break;
case 2:
digits = "." + digits;
break;
case 3:
digits = "1.0";
break;
}
FontMetrics fm = g2.getFontMetrics();
Color orig = g.getColor();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(lineColor);
Rectangle2D bounds = fm.getStringBounds(digits, g2);
int xStart = (int) (x - bounds.getWidth() / 2 - inset);
int halfWidth = (2 * inset + (int) bounds.getWidth()) / 2;
int yHeight = 2 * inset + (int) bounds.getHeight() + 2;
if (mMouseDown) {
myXPoints[0] = xStart;
myYPoints[0] = 0;
myXPoints[1] = xStart;
myYPoints[1] = yHeight;
myXPoints[2] = xStart + halfWidth;
myYPoints[2] = yHeight + 10;
myXPoints[3] = xStart + halfWidth * 2;
myYPoints[3] = yHeight;
myXPoints[4] = xStart + halfWidth * 2;
myYPoints[4] = 0;
g2.fillPolygon(myXPoints, myYPoints, 5);
g.setColor(MEUI.Graph.ourCursorTextColor);
g2.drawString(digits, (int) (x - bounds.getWidth() / 2), (int) (fm.getAscent() + inset));
} else {
myXPoints[0] = xStart;
myYPoints[0] = yHeight;
myXPoints[1] = xStart + halfWidth;
myYPoints[1] = yHeight + 10;
myXPoints[2] = xStart + halfWidth * 2;
myYPoints[2] = yHeight;
g2.fillPolygon(myXPoints, myYPoints, 3);
}
g2.setColor(lineColor);
g2.drawLine(xStart + halfWidth, yHeight, xStart + halfWidth, h);
}
/**
* This is being called by the layer pain to implement the timeline cursor
*
* @param e
*/
private void processMouseDrag(MouseEvent e) {
if (mTimelineStructure == null) {
return;
}
int timeStart = MEUI.ourLeftColumnWidth + mTimelineStructure.myXTicksPixels[0];
int timeWidth =
mTimelineStructure.myXTicksPixels[mTimelineStructure.myXTicksPixels.length - 1]
- mTimelineStructure.myXTicksPixels[0];
float progress = (e.getX() - timeStart) / (float) (timeWidth);
float error = (float) (2 / timeWidth);
boolean inRange = progress > -error && progress < 1 + error;
switch (e.getID()) {
case MouseEvent.MOUSE_CLICKED: {
mTimeLine.requestFocus();
if (inRange) {
MTag oldSelection = mSelectedKeyFrame;
selectKeyFrame(progress);
int index = mTimeLine.getSelectedIndex();
mTimeLine.setSelectedIndex(index);
TimeLineRow row = mTimeLine.getTimeLineRow(index);
if (row == null) {
return;
}
Track.timelineTableSelect(mMeModel.myTrack);
row.setSelectedKeyFrame(mSelectedKeyFrame);
if (mSelectedKeyFrame != null && oldSelection != mSelectedKeyFrame) {
}
}
if (e.getX() < mTimeLineTopLeft.getWidth() && e.getY() > mTimeLineTopLeft.getHeight()) {
int index = mTimeLine.getSelectedIndex();
TimeLineRow row = mTimeLine.getTimeLineRow(index);
if (row != null) { // TODO: Check why this is being hit
row.toggleGraph();
}
}
}
break;
case MouseEvent.MOUSE_PRESSED: {
mMouseDown = (progress >= 0.0f && progress <= 1.0f);
if (mMouseDown) {
notifyTimeLineListeners(TimeLineCmd.MOTION_SCRUB, mMotionProgress);
}
repaint();
}
break;
case MouseEvent.MOUSE_RELEASED: {
if (mMouseDown) {
notifyTimeLineListeners(TimeLineCmd.MOTION_STOP, mMotionProgress);
}
mMouseDown = false;
repaint();
}
}
if (!mMouseDown) {
return;
}
if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
if (progress >= 0.0f && progress <= 1.0f) {
mMotionProgress = progress;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, progress);
repaint();
} else if (progress <= 0.0f && mMotionProgress != 0.0f) {
mMotionProgress = 0.0f;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, progress);
repaint();
} else if (progress >= 1.0f && mMotionProgress != 1.0f) {
mMotionProgress = 1.0f;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, progress);
repaint();
}
}
}
private void selectKeyFrame(float progress) {
if (mTimeLine == null || mTimeLine.getSelectedValue() == null) {
return;
}
mSelectedKeyFrame = null;
ArrayList<MTag> f = mTimeLine.getSelectedValue().mKeyFrames;
float minDist = Float.MAX_VALUE;
MTag minTag = null;
for (MTag tag : f) {
String posString = tag.getAttributeValue("framePosition");
if (posString != null) {
float dist = Math.abs(progress - Integer.parseInt(posString) / 100f);
if (dist < minDist) {
minTag = tag;
minDist = dist;
}
}
}
if (minDist < 0.1f) {
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME, new MTag[]{minTag}, 0);
mSelectedKeyFrame = minTag;
repaint();
}
}
public void setListeners(MotionEditorSelector listeners) {
mMotionEditorSelector = listeners;
}
/**
* This is a very simple vertical flow layout with special handling of the last Component
*/
static class VertLayout implements LayoutManager {
Dimension dimension = new Dimension();
@Override
public void addLayoutComponent(String name, Component comp) {
}
@Override
public void removeLayoutComponent(Component comp) {
}
@Override
public Dimension preferredLayoutSize(Container parent) {
int y = 0;
int width = 0;
int n = parent.getComponentCount();
for (int i = 0; i < n; i++) {
Component c = parent.getComponent(i);
Dimension size = c.getPreferredSize();
width = Math.max(width, size.width);
y += size.height;
}
dimension.height = y;
dimension.width = width;
return dimension;
}
@Override
public Dimension minimumLayoutSize(Container parent) {
int y = 0;
int width = 0;
int n = parent.getComponentCount();
for (int i = 0; i < n; i++) {
Component c = parent.getComponent(i);
Dimension size = c.getMinimumSize();
width = Math.max(width, size.width);
y += size.height;
}
dimension.height = y;
dimension.width = width;
return dimension;
}
@Override
public void layoutContainer(Container parent) {
int y = 0;
int n = parent.getComponentCount();
int parent_height = parent.getHeight();
int parent_width = parent.getWidth();
for (int i = 0; i < n; i++) {
Component c = parent.getComponent(i);
Dimension size = c.getPreferredSize();
if (i < n - 1) {
c.setBounds(0, y, parent_width, size.height);
} else {
if (parent_height - y <= 0) {
c.setBounds(0, y, parent_width, 0);
c.setVisible(false);
} else {
c.setBounds(0, y, parent_width, parent_height - y);
}
}
y += size.height;
}
}
}
public class METimeLine extends JPanel {
JPanel pad = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(MEUI.ourAvgBackground);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(MEUI.myGridColor);
TimeLineRow.drawTicks(g, mTimelineStructure, getHeight());
// draw line on the divider
g.setColor(MEUI.ourBorder);
g.fillRect(MEUI.ourLeftColumnWidth, 0, 1, getHeight());
}
};
int mSelectedIndex = 0;
ArrayList<ListSelectionListener> listeners = new ArrayList<>();
METimeLine() {
super(new VertLayout());
add(pad);
pad.setBackground(MEUI.ourAvgBackground);
MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
refreshCycling(true);
}
@Override
public void mouseReleased(MouseEvent e) {
refreshCycling(false);
int n = getComponentCount() - 1;
int y = e.getY();
for (int i = 0; i < n; i++) {
Component c = getComponent(i);
if (y < c.getY() + c.getHeight()) {
setSelectedIndex(i);
break;
}
}
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
};
addMouseListener(mouseAdapter);
}
void addListSelectionListener(ListSelectionListener l) {
listeners.add(l);
}
public TimeLineRow getTimeLineRow(int index) {
if (getComponent(index) instanceof TimeLineRow) {
return (TimeLineRow) getComponent(index);
}
return null;
}
public TimeLineRowData getSelectedValue() {
if (getComponent(mSelectedIndex) instanceof TimeLineRow) {
return ((TimeLineRow) getComponent(mSelectedIndex)).mRow;
}
return null;
}
public void setListData(List<TimeLineRowData> list, MeModel model) {
Component[] children = getComponents();
removeAll();
String lastName = null;
int n = Math.min(children.length - 1, list.size());
for (int i = 0; i < n; i++) {
TimeLineRow child = (TimeLineRow) children[i];
TimeLineRowData data = list.get(i);
boolean showTitle = !(data.mName != null && data.mName.equals(lastName));
child.setRowData(model, data, i, false, false, mSelectedKeyFrame, showTitle);
lastName = data.mName;
add(child);
}
if (n >= 0 && list.size() > n) {
for (int i = n; i < list.size(); i++) {
TimeLineRow child = new TimeLineRow(mTimelineStructure);
TimeLineRowData data = list.get(i);
boolean showTitle = !(data.mName != null && data.mName.equals(lastName));
if (data == null || data.mName == null) {
showTitle = false;
} else {
lastName = data.mName;
}
child.setRowData(model, data, i, false, false, mSelectedKeyFrame, showTitle);
add(child);
}
}
add(pad);
revalidate();
}
public int getSelectedIndex() {
return mSelectedIndex;
}
public void setSelectedIndex(int index) {
int prev = mSelectedIndex;
mSelectedIndex = index;
if (mSelectedKeyFrame == null) {
notifySelectionListener(index);
}
if (getComponentCount() > prev) {
Component comp = getComponent(prev);
if (!(comp instanceof TimeLineRow)) {
return;
}
TimeLineRow child = ((TimeLineRow) comp);
child.setSelected(false);
child.repaint();
}
TimeLineRow child = ((TimeLineRow) getComponent(mSelectedIndex));
child.setSelected(true);
child.repaint();
}
private void notifySelectionListener(int index) {
ListSelectionEvent event = new ListSelectionEvent(this, index, index, false);
for (ListSelectionListener listener : listeners) {
listener.valueChanged(event);
}
}
}
public static void main(String[] arg) {
String str = "{\n" +
" Debug: {\n" +
" name: 'motion8'\n" +
" },\n" +
" ConstraintSets: {\n" +
" start: {\n" +
" a: {\n" +
" width: 40,\n" +
" height: 40,\n" +
" start: ['parent', 'start', 16],\n" +
" bottom: ['parent', 'bottom', 16]\n" +
" }\n" +
" },\n" +
" end: {\n" +
" a: {\n" +
" width: 150,\n" +
" height: 100,\n" +
" rotationZ: 390,\n" +
" end: ['parent', 'end', 16],\n" +
" top: ['parent', 'top', 16]\n" +
" }\n" +
" }\n" +
" },\n" +
" Transitions: {\n" +
" default: {\n" +
" from: 'start',\n" +
" to: 'end',\n" +
" KeyFrames: {\n" +
" KeyPositions: [\n" +
" {\n" +
" target: ['a'],\n" +
" frames: [25, 50, 75],\n" +
" percentX: [0.1, 0.8, 0.1],\n" +
" percentY: [0.4, 0.8, 0]\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
showTimeline(str);
}
JFrame mTimeLineFrame;
public static TimeLinePanel showTimeline(String motionSceneString) {
JFrame frame = new JFrame();
TimeLinePanel tlp = new TimeLinePanel();
tlp.updateMotionScene(motionSceneString);
tlp.setListeners(new MotionEditorSelector());
frame.setContentPane(tlp);
frame.setTitle("TimeLinePanel");
Desk.rememberPosition(frame, null);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true);
tlp.mTimeLineFrame = frame;
return tlp;
}
public void updateMotionScene(String motionSceneString) {
ScenePicker picker = new ScenePicker();
picker.foreachObject(p -> {
if (p instanceof MouseAdapter) {
MouseAdapter ma = (MouseAdapter) p;
ma.mouseDragged(null);
}
});
DefaultMTag transition = (DefaultMTag) KeyFramesTag.parseForTimeLine(motionSceneString);
if (DEBUG) {
Debug.log("Transition ... ");
transition.printFormal("|", System.out);
Debug.log("-----------------");
}
DefaultMTag motionScene = new DefaultMTag("MotionScene");
motionScene.addChild(transition);
DefaultMTag startTag = new DefaultMTag("ConstraintSet");
DefaultMTag endTag = new DefaultMTag("ConstraintSet");
motionScene.addChild(startTag, endTag);
MTag[] tags = transition.getChildTags(KEY_FRAME_SET);
MTag keyFramesTag = null;
if (tags.length > 0) {
keyFramesTag = tags[0];
MTag kfs = keyFramesTag;
MTag[] keyFrames = kfs.getChildTags();
HashSet<String> ids = new HashSet<>();
for (int i = 0; i < keyFrames.length; i++) {
MTag keyFrame = keyFrames[i];
ids.add(keyFrame.getAttributeValue("motionTarget"));
}
String[] widgets = ids.toArray(new String[0]);
String start = transition.getAttributeValue("constraintSetStart");
String end = transition.getAttributeValue("constraintSetEnd");
try {
CLKey key = CLScan.findCLKey(CLParser.parse(motionSceneString), "ConstraintSets");
CLObject obj = (CLObject) key.getValue();
CLObject startObj = (CLObject) obj.get(start);
CLObject endObj = (CLObject) obj.get(end);
startTag.addAttribute("id", start);
endTag.addAttribute("id", end);
for (int i = 0; i < widgets.length; i++) {
String widget = widgets[i];
DefaultMTag wc_s = new DefaultMTag("Constraint");
startTag.addChild(wc_s);
wc_s.addAttribute("layout_constraintTag", widget);
wc_s.addAttribute("id", widget);
DefaultMTag wc_e = new DefaultMTag("Constraint");
wc_e.addAttribute("layout_constraintTag", widget);
wc_e.addAttribute("id", widget);
endTag.addChild(wc_e);
}
} catch (CLParsingException e) {
e.printStackTrace();
}
}
setMTag(transition, new MeModel(motionScene, null, null, null, null));
}
public void exitTimeLine() {
if (mTimeLineFrame != null) {
mTimeLineFrame.setVisible(false);
}
}
public void popUp() {
mTimeLineFrame.setVisible(true);
}
public void popDown() {
mTimeLineFrame.setVisible(false);
}
interface ProgressListener {
void setProgress(float p);
}
public void setMotionProgress(float progress) {
if (( System.currentTimeMillis() - mLastEmitted) < 800) {
return;
}
mMeModel.setProgress(progress);
mMotionProgress = progress;
repaint();
}
public void setProgressListener(ProgressListener listener) {
TimeLinePanel mTimeLinePanel = null;
mTimeLinePanel.addTimeLineListener((cmd, pos) -> {
System.out.println(pos);
});
}
public void updateTransition(String str) {
MTag tag = KeyFramesTag.parseForTimeLine(str);
setMTag(tag, mMeModel);
}
}
| desktop/ConstraintLayoutInspector/app/src/androidx/constraintLayout/desktop/ui/timeline/TimeLinePanel.java | /*
* Copyright (C) 2019 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 androidx.constraintLayout.desktop.ui.timeline;
import androidx.constraintLayout.desktop.scan.CLScan;
import androidx.constraintLayout.desktop.ui.adapters.Annotations.NotNull;
import androidx.constraintLayout.desktop.ui.adapters.*;
import androidx.constraintLayout.desktop.ui.timeline.TimeLineTopLeft.TimelineCommands;
import androidx.constraintLayout.desktop.ui.ui.MTagActionListener;
import androidx.constraintLayout.desktop.ui.ui.MeModel;
import androidx.constraintLayout.desktop.ui.ui.MotionEditorSelector;
import androidx.constraintLayout.desktop.ui.ui.MotionEditorSelector.TimeLineCmd;
import androidx.constraintLayout.desktop.ui.ui.MotionEditorSelector.TimeLineListener;
import androidx.constraintLayout.desktop.ui.ui.Utils;
import androidx.constraintLayout.desktop.ui.utils.Debug;
import androidx.constraintLayout.desktop.utils.Desk;
import androidx.constraintLayout.desktop.utils.ScenePicker;
import androidx.constraintlayout.core.parser.CLKey;
import androidx.constraintlayout.core.parser.CLObject;
import androidx.constraintlayout.core.parser.CLParser;
import androidx.constraintlayout.core.parser.CLParsingException;
import javax.swing.Timer;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.LayerUI;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.util.List;
import java.util.*;
import static androidx.constraintLayout.desktop.ui.adapters.MotionSceneAttrs.Tags.KEY_FRAME_SET;
/**
* The panel that displays the timeline
*/
public class TimeLinePanel extends JPanel {
public static final boolean DEBUG = false;
private static int PLAY_TIMEOUT = 60 * 60 * 1000;
private static int MS_PER_FRAME = 15;
private static float TIMELINE_MIN = 0.0f;
private static float TIMELINE_MAX = 100.0f;
private static float[] ourSpeedsMultipliers = {0.25f, 0.5f, 1f, 2f, 4f};
MotionEditorSelector mMotionEditorSelector;
private TimelineStructure mTimelineStructure = new TimelineStructure();
private TimeLineTopPanel myTimeLineTopPanel = new TimeLineTopPanel(mTimelineStructure);
private MTag mSelectedKeyFrame;
private boolean mMouseDown = false;
private METimeLine mTimeLine = new METimeLine();
private JScrollPane myScrollPane = new MEScrollPane(mTimeLine);
private TimeLineTopLeft mTimeLineTopLeft = new TimeLineTopLeft();
private MeModel mMeModel;
private MTag mTransitionTag;
private float mMotionProgress; // from 0 .. 1;
private Timer myTimer;
private Timer myPlayLimiter;
private int myYoyo = 0;
private int mDuration = 1000;
private float myProgressPerMillisecond = 1 / (float) mDuration;
private long last_time;
private int mCurrentSpeed = 2;
private boolean mIsPlaying = false;
private ArrayList<TimeLineListener> mTimeLineListeners = new ArrayList<>();
private int mDirection = 1;
int[] myXPoints = new int[5];
int[] myYPoints = new int[5];
private MTagActionListener mListener;
Timer myMouseDownTimer;
JPopupMenu myPlaybackSpeedPopupMenu = new JPopupMenu();
@Override
public void updateUI() {
super.updateUI();
if (mTimeLineTopLeft != null) {
mTimeLineTopLeft.updateUI();
}
if (mTimeLine != null) {
mTimeLine.updateUI();
}
}
public TimeLinePanel() {
super(new BorderLayout());
for (int i = 0; i < ourSpeedsMultipliers.length; i++) {
myPlaybackSpeedPopupMenu.add(ourSpeedsMultipliers[i] + "x").addActionListener(createPlaybackSpeedPopupMenuActionListener(i));
}
JPanel top = new JPanel(new BorderLayout());
top.add(myTimeLineTopPanel, BorderLayout.CENTER);
top.add(mTimeLineTopLeft, BorderLayout.WEST);
myScrollPane.setColumnHeaderView(top);
myScrollPane.setBorder(BorderFactory.createEmptyBorder());
int flags = 0;
mTimeLine.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int code = e.getExtendedKeyCode();
switch (code) {
case KeyEvent.VK_V:
if (!e.isControlDown()) {
break;
}
// Fallthrough
case KeyEvent.VK_PASTE:
paste();
break;
//////////////////////////////////////////////////////////////
case KeyEvent.VK_C:
if (!e.isControlDown()) {
break;
}
// Fallthrough copy
case KeyEvent.VK_COPY:
if (e.isControlDown()) {
if (mSelectedKeyFrame != null) {
MEUI.copy(mSelectedKeyFrame);
}
}
break;
/////////////////////////////////////////////////////////
case KeyEvent.VK_X:
if (!e.isControlDown()) {
break;
}
// Fallthrough cut
case KeyEvent.VK_CUT:
if (e.isControlDown()) {
if (mSelectedKeyFrame != null) {
MEUI.cut(mSelectedKeyFrame);
}
}
break;
case KeyEvent.VK_UP:
int index = mTimeLine.getSelectedIndex() - 1;
if (index < 0) {
index = mTimeLine.getComponentCount() - 2;
}
mSelectedKeyFrame = null;
mTimeLine.setSelectedIndex(index);
groupSelected();
break;
case KeyEvent.VK_DOWN:
index = mTimeLine.getSelectedIndex() + 1;
if (index > mTimeLine.getComponentCount() - 2) {
index = 0;
}
mSelectedKeyFrame = null;
mTimeLine.setSelectedIndex(index);
groupSelected();
break;
case KeyEvent.VK_DELETE:
case KeyEvent.VK_BACK_SPACE:
if (mListener != null) {
if (mSelectedKeyFrame != null) {
mListener.delete(new MTag[]{mSelectedKeyFrame}, 0);
}
}
break;
case KeyEvent.VK_LEFT: {
TimeLineRowData rowData = mTimeLine.getSelectedValue();
int numOfKeyFrames = rowData.mKeyFrames.size();
int indexInRow = -1;
for (int i = 0; i < numOfKeyFrames; i++) {
if (rowData.mKeyFrames.get(i).equals(mSelectedKeyFrame)) {
indexInRow = i;
break;
}
}
int selIndex = (indexInRow - 1 + numOfKeyFrames) % numOfKeyFrames;
mSelectedKeyFrame = rowData.mKeyFrames.get(selIndex);
mTimeLine.getTimeLineRow(mTimeLine.getSelectedIndex()).setSelectedKeyFrame(mSelectedKeyFrame);
Track.timelineTableSelect(mMeModel.myTrack);
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME, new MTag[]{mSelectedKeyFrame}, flags);
if (mListener != null && mSelectedKeyFrame != null) {
mListener.select(mSelectedKeyFrame, 0);
}
}
break;
case KeyEvent.VK_RIGHT: {
TimeLineRowData rowData = mTimeLine.getSelectedValue();
int numOfKeyFrames = rowData.mKeyFrames.size();
int indexInRow = -1;
for (int i = 0; i < numOfKeyFrames; i++) {
if (rowData.mKeyFrames.get(i).equals(mSelectedKeyFrame)) {
indexInRow = i;
break;
}
}
int selIndex = (indexInRow + 1) % numOfKeyFrames;
mSelectedKeyFrame = rowData.mKeyFrames.get(selIndex);
mTimeLine.getTimeLineRow(mTimeLine.getSelectedIndex()).setSelectedKeyFrame(mSelectedKeyFrame);
Track.timelineTableSelect(mMeModel.myTrack);
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME, new MTag[]{mSelectedKeyFrame}, flags);
if (mListener != null && mSelectedKeyFrame != null) {
mListener.select(mSelectedKeyFrame, 0);
}
}
break;
}
}
});
mTimeLine.setFocusable(true);
mTimeLine.setRequestFocusEnabled(true);
mTimeLineTopLeft.addControlsListener((e, mode) -> {
performCommand(e, mode);
});
JLayer<JComponent> jlayer = new JLayer<JComponent>(myScrollPane, new LayerUI<JComponent>() {
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
paintCursor(g, c);
}
@Override
public void installUI(JComponent c) {
super.installUI(c);
JLayer jlayer = (JLayer) c;
jlayer.setLayerEventMask(
AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK
);
}
@Override
protected void processMouseMotionEvent(MouseEvent e, JLayer l) {
processMouseDrag(e);
}
@Override
protected void processMouseEvent(MouseEvent e, JLayer l) {
processMouseDrag(e);
}
});
add(jlayer);
mTimelineStructure.addWidthChangedListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
mTimeLine.repaint();
}
});
mTimeLine.setBackground(MEUI.ourAvgBackground);
myTimeLineTopPanel.setRange(TIMELINE_MIN, TIMELINE_MAX);
mTimeLine.addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
groupSelected();
}
});
}
private void paste() {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
try {
String buff = (String) (clipboard.getContents(this).getTransferData(DataFlavor.stringFlavor));
StringMTag pastedTag = StringMTag.parse(buff);
HashMap<String, MTag.Attribute> attr = pastedTag.getAttrList();
if (mSelectedKeyFrame == null) {
TimeLineRowData rowData = mTimeLine.getSelectedValue();
if (rowData.mKeyFrames.isEmpty()) {
return;
}
mSelectedKeyFrame = rowData.mKeyFrames.get(0);
}
MTag keyFrameSet = mSelectedKeyFrame.getParent();
MTag.TagWriter writer = keyFrameSet.getChildTagWriter(pastedTag.getTagName());
for (String s : attr.keySet()) {
MTag.Attribute a = attr.get(s);
if (a == null || a.mAttribute.equals("framePosition")) {
writer.setAttribute(a.mNamespace, a.mAttribute, Integer.toString((int) (mMotionProgress * 100 + 0.5)));
} else {
writer.setAttribute(a.mNamespace, a.mAttribute, a.mValue);
}
}
MTag[] children = pastedTag.getChildTags();
for (int i = 0; i < children.length; i++) {
MTag child = children[i];
MTag.TagWriter cw = writer.getChildTagWriter(child.getTagName());
HashMap<String, MTag.Attribute> cwAttrMap = child.getAttrList();
for (String cwAttrStr : cwAttrMap.keySet()) {
MTag.Attribute cwAttr = cwAttrMap.get(cwAttrStr);
cw.setAttribute(cwAttr.mNamespace, cwAttr.mAttribute, cwAttr.mValue);
}
}
mSelectedKeyFrame = writer.commit("paste");
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setActionListener(MTagActionListener l) {
mListener = l;
}
public void stopAnimation() {
performCommand(TimelineCommands.PAUSE, 0);
}
private static String buildKey(MTag keyFrame) {
String targetKey;
String target = keyFrame.getAttributeValue("motionTarget");
targetKey = target;
if (target != null && target.startsWith("@")) {
targetKey = "Id:" + Utils.stripID(target);
} else {
targetKey = "Tag:" + target;
}
String name = keyFrame.getTagName();
targetKey += name;
String[] keys = new String[0];
switch (name) {
case "KeyPosition":
keys = MotionLayoutAttrs.KeyPositionKey;
break;
case "KeyAttribute":
keys = MotionLayoutAttrs.KeyAttributesKey;
break;
case "KeyCycle":
keys = MotionLayoutAttrs.KeyCycleKey;
break;
case "KeyTimeCycle":
keys = MotionLayoutAttrs.KeyTimeCycleKey;
break;
case "KeyTrigger":
keys = MotionLayoutAttrs.KeyTriggerKey;
break;
}
for (String key : keys) {
targetKey += get(keyFrame, key);
}
return targetKey;
}
private static String get(MTag tag, String attr) {
String s = tag.getAttributeValue(attr);
return (s == null) ? "" : attr;
}
public void clearSelection() {
mSelectedKeyFrame = null;
int n = mTimeLine.getComponentCount();
if (n == 0 || mTimeLine.mSelectedIndex >= n) {
return;
}
Component component = mTimeLine.getComponent(mTimeLine.mSelectedIndex);
if (component instanceof TimeLineRow) {
TimeLineRow child = ((TimeLineRow) component);
child.setSelected(true);
repaint();
}
}
public void addTimeLineListener(TimeLineListener timeLineListener) {
mTimeLineListeners.add(timeLineListener);
}
public void notifyTimeLineListeners(TimeLineCmd cmd, Float value) {
for (TimeLineListener listener : mTimeLineListeners) {
listener.command(cmd, value);
}
}
private void refreshCycling(boolean cycle) {
MTag[] kef = mTransitionTag.getChildTags(MotionSceneAttrs.Tags.KEY_FRAME_SET);
if (kef == null || kef.length == 0) {
cycle = false;
} else {
MTag[] timeCycle = kef[0].getChildTags(MotionSceneAttrs.Tags.KEY_TIME_CYCLE);
if (timeCycle == null || timeCycle.length == 0) {
cycle = false;
}
}
if (cycle) {
if (myMouseDownTimer != null) {
myMouseDownTimer.stop();
myMouseDownTimer = null;
}
myMouseDownTimer = new Timer(MS_PER_FRAME, e -> {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, mMotionProgress);
});
myMouseDownTimer.start();
} else {
if (myMouseDownTimer != null) {
myMouseDownTimer.stop();
myMouseDownTimer = null;
}
}
}
private void createTimer() {
if (myTimer == null) {
myTimer = new Timer(MS_PER_FRAME, e -> {
progress();
});
myTimer.setRepeats(true);
myTimer.start();
}
if (myPlayLimiter == null) {
myPlayLimiter = new Timer(PLAY_TIMEOUT, e -> {
destroyTimer();
});
myPlayLimiter.setRepeats(false);
myPlayLimiter.start();
}
}
private void watchdog() {
if (myPlayLimiter != null) {
myPlayLimiter.restart();
}
}
private void destroyTimer() {
if (myTimer != null) {
myTimer.stop();
myTimer = null;
}
if (myPlayLimiter != null) {
myPlayLimiter.stop();
myPlayLimiter = null;
}
}
private ActionListener createPlaybackSpeedPopupMenuActionListener(int playbackSpeedIndex) {
return new ActionListener() {
int speedIndex = playbackSpeedIndex;
@Override
public void actionPerformed(ActionEvent e) {
Track.animationSpeed(mMeModel.myTrack);
mCurrentSpeed = speedIndex;
myProgressPerMillisecond = ourSpeedsMultipliers[mCurrentSpeed] / (float) mDuration;
mTimeLineTopLeft.mSlow.setToolTipText(mDuration + " x " + ourSpeedsMultipliers[mCurrentSpeed]);
mTimeLineTopLeft.mSlow.setText(ourSpeedsMultipliers[mCurrentSpeed] + "x");
}
};
}
private void showPlaybackSpeedPopup() {
myPlaybackSpeedPopupMenu.show(mTimeLineTopLeft.mSlow, 0, 20);
}
private void performCommand(TimelineCommands e, int mode) {
watchdog();
switch (e) {
case PLAY:
last_time = System.nanoTime();
Track.playAnimation(mMeModel.myTrack);
createTimer();
notifyTimeLineListeners(TimeLineCmd.MOTION_PLAY, mMotionProgress);
mIsPlaying = true;
break;
case SPEED:
showPlaybackSpeedPopup();
break;
case LOOP:
Track.animationDirectionToggle(mMeModel.myTrack);
myYoyo = mode;
break;
case PAUSE:
mIsPlaying = false;
destroyTimer();
notifyTimeLineListeners(TimeLineCmd.MOTION_STOP, mMotionProgress);
mTimeLineTopLeft.displayPlay();
break;
case END:
Track.animationEnd(mMeModel.myTrack);
mIsPlaying = false;
destroyTimer();
mMotionProgress = 1;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, mMotionProgress);
notifyTimeLineListeners(TimeLineCmd.MOTION_STOP, mMotionProgress);
break;
case START:
Track.animationStart(mMeModel.myTrack);
mIsPlaying = false;
destroyTimer();
mMotionProgress = 0;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, mMotionProgress);
notifyTimeLineListeners(TimeLineCmd.MOTION_STOP, mMotionProgress);
break;
}
}
private void progress() {
if (!mIsPlaying || mMouseDown) {
return;
}
long time = System.nanoTime();
switch (myYoyo) {
case 0:
mMotionProgress += myProgressPerMillisecond * ((time - last_time) * 1E-6f);
if (mMotionProgress > 1f) {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, 1f);
mMotionProgress = mMotionProgress - 1;
}
break;
case 1:
mMotionProgress -= myProgressPerMillisecond * ((time - last_time) * 1E-6f);
if (mMotionProgress < 0f) {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, 0f);
mMotionProgress = 1 + mMotionProgress;
}
break;
case 2:
mMotionProgress += (mDirection) * myProgressPerMillisecond * ((time - last_time) * 1E-6f);
if (mMotionProgress < 0f) {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, 0f);
mDirection = +1;
mMotionProgress = -mMotionProgress;
} else if (mMotionProgress > 1f) {
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, 1f);
mDirection = -1;
mMotionProgress = 1 - (mMotionProgress - 1);
}
break;
}
last_time = time;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, mMotionProgress);
repaint();
}
private void groupSelected() {
if (mTimeLine == null || mTimeLine.getSelectedValue() == null
|| mTimeLine.getSelectedValue().mKeyFrames == null) {
if (mTransitionTag != null) {
mMotionEditorSelector
.notifyListeners(MotionEditorSelector.Type.TRANSITION, new MTag[]{mTransitionTag}, 0);
}
return;
}
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME_GROUP,
mTimeLine.getSelectedValue().mKeyFrames.toArray(new MTag[0]), 0);
}
public void setMTag(MTag transitionTag, MeModel model) {
MTag newSelection = (model == null) ? null : findSelectedKeyFrameInNewModel(model);
mTransitionTag = transitionTag;
if (mTransitionTag != null) {
String duration = mTransitionTag.getAttributeValue("duration");
if (duration != null) {
try {
int durationInt = Integer.parseInt(duration);
mDuration = durationInt;
if (mDuration == 0) {
mDuration = 1000;
}
mCurrentSpeed = 2;
myProgressPerMillisecond = 1 / (float) mDuration;
} catch (NumberFormatException e) {
}
}
} else {
mDuration = 1000;
mCurrentSpeed = 2;
myProgressPerMillisecond = 1 / (float) mDuration;
}
if (mTimeLineTopLeft != null && mTimeLineTopLeft.mSlow != null) {
mTimeLineTopLeft.mSlow.setToolTipText(mDuration + " x " + ourSpeedsMultipliers[mCurrentSpeed]);
}
mSelectedKeyFrame = null;
mMeModel = model;
List<TimeLineRowData> list = transitionTag != null ? buildTransitionList() : Collections.emptyList();
mTimeLine.setListData(list, model);
if (transitionTag != null && mMotionEditorSelector != null) {
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.TRANSITION, new MTag[]{transitionTag}, 0);
}
if (newSelection != null) {
int index = findKeyFrameInRows(list, newSelection);
if (index >= 0) {
mTimeLine.setSelectedIndex(index);
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME, new MTag[]{newSelection}, 0);
mSelectedKeyFrame = newSelection;
}
}
}
private MTag findSelectedKeyFrameInNewModel(@NotNull MeModel newModel) {
if (mSelectedKeyFrame == null) {
return null;
}
MTag oldKeyFrameSet = mSelectedKeyFrame.getParent();
if (oldKeyFrameSet == null) {
return null;
}
MTag oldTransition = oldKeyFrameSet.getParent();
if (oldTransition == null) {
return null;
}
MTag transition = newModel.motionScene.getChildTagWithTreeId(MotionSceneAttrs.Tags.TRANSITION, oldTransition.getTreeId());
if (transition == null) {
return null;
}
for (MTag kfSet : transition.getChildTags(MotionSceneAttrs.Tags.KEY_FRAME_SET)) {
MTag keyFrame = kfSet.getChildTagWithTreeId(mSelectedKeyFrame.getTagName(), mSelectedKeyFrame.getTreeId());
if (keyFrame != null) {
return keyFrame;
}
}
return null;
}
private int findKeyFrameInRows(@NotNull List<TimeLineRowData> rows, @NotNull MTag keyFrame) {
for (int index = 0; index < rows.size(); index++) {
if (rows.get(index).mKeyFrames.contains(keyFrame)) {
return index;
}
}
return -1;
}
private List<TimeLineRowData> buildTransitionList() {
List<TimeLineRowData> views = new ArrayList<>();
TreeMap<String, ArrayList<MTag>> keyMap = new TreeMap<>();
MTag[] keyFrameSets = mTransitionTag.getChildTags("KeyFrameSet");
for (int i = 0; i < keyFrameSets.length; i++) {
MTag keyFrameSet = keyFrameSets[i];
MTag[] keyFrames = keyFrameSet.getChildTags();
for (int j = 0; j < keyFrames.length; j++) {
MTag keyFrame = keyFrames[j];
String targetKey = buildKey(keyFrame);
if (!keyMap.containsKey(targetKey)) {
ArrayList<MTag> list = new ArrayList<>();
keyMap.put(targetKey, list);
}
keyMap.get(targetKey).add(keyFrame);
}
}
for (String id : keyMap.keySet()) {
TimeLineRowData row = new TimeLineRowData();
row.mKeyFrames = keyMap.get(id);
row.buildKey(row.mKeyFrames.get(0));
row.buildTargetStrings(row.mKeyFrames.get(0));
views.add(row);
}
return views;
}
boolean matches(String target, TimeLineRowData view) {
if (target == null) {
return false;
}
if (target.startsWith("@id") || target.startsWith("@+id")) {
return Utils.stripID(target).equals(view.mKey);
}
String tag = view.mStartConstraintSet.getAttributeValue("layout_constraintTag");
if (tag == null) { // TODO walk derived constraints
System.err.println(
view.mKey + " " + view.mLayoutView + " id = " + ((view.mLayoutView == null)
? view.mLayoutView.getAttributeValue("id") : ""));
tag = view.mLayoutView.getAttributeValue("layout_constraintTag");
}
if (tag.matches(target)) {
return true;
}
return false;
}
/**
* Get and create if does not exist.
*/
TimeLineRowData addRow(List<TimeLineRowData> views, String viewId) {
for (TimeLineRowData view : views) {
if (view.mKey.equals(viewId)) {
return view;
}
}
TimeLineRowData view = new TimeLineRowData();
view.mKey = viewId;
views.add(view);
return view;
}
TimeLineRowData get(List<TimeLineRowData> views, String viewId) {
for (TimeLineRowData view : views) {
if (view.mKey.equals(viewId)) {
return view;
}
}
return null;
}
/**
* Draws the cursor
*
* @param g
* @param c
*/
private void paintCursor(Graphics g, JComponent c) {
if (mTimelineStructure.myXTicksPixels == null
|| mTimelineStructure.myXTicksPixels.length == 0) {
return;
}
Graphics2D g2 = (Graphics2D) g;
int w = c.getWidth();
int h = c.getHeight();
int timeStart = MEUI.ourLeftColumnWidth + mTimelineStructure.myXTicksPixels[0];
int timeWidth = mTimelineStructure.myXTicksPixels[mTimelineStructure.myXTicksPixels.length - 1]
- mTimelineStructure.myXTicksPixels[0];
int y = 0;
int x = timeStart + (int) (mMotionProgress * (timeWidth));
Color lineColor = MEUI.myTimeCursorColor;
int inset = 2;
int d = (int) (mMotionProgress * 100);
String digits = Integer.toString(d);
switch (digits.length()) {
case 1:
digits = ".0" + digits;
break;
case 2:
digits = "." + digits;
break;
case 3:
digits = "1.0";
break;
}
FontMetrics fm = g2.getFontMetrics();
Color orig = g.getColor();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(lineColor);
Rectangle2D bounds = fm.getStringBounds(digits, g2);
int xStart = (int) (x - bounds.getWidth() / 2 - inset);
int halfWidth = (2 * inset + (int) bounds.getWidth()) / 2;
int yHeight = 2 * inset + (int) bounds.getHeight() + 2;
if (mMouseDown) {
myXPoints[0] = xStart;
myYPoints[0] = 0;
myXPoints[1] = xStart;
myYPoints[1] = yHeight;
myXPoints[2] = xStart + halfWidth;
myYPoints[2] = yHeight + 10;
myXPoints[3] = xStart + halfWidth * 2;
myYPoints[3] = yHeight;
myXPoints[4] = xStart + halfWidth * 2;
myYPoints[4] = 0;
g2.fillPolygon(myXPoints, myYPoints, 5);
g.setColor(MEUI.Graph.ourCursorTextColor);
g2.drawString(digits, (int) (x - bounds.getWidth() / 2), (int) (fm.getAscent() + inset));
} else {
myXPoints[0] = xStart;
myYPoints[0] = yHeight;
myXPoints[1] = xStart + halfWidth;
myYPoints[1] = yHeight + 10;
myXPoints[2] = xStart + halfWidth * 2;
myYPoints[2] = yHeight;
g2.fillPolygon(myXPoints, myYPoints, 3);
}
g2.setColor(lineColor);
g2.drawLine(xStart + halfWidth, yHeight, xStart + halfWidth, h);
}
/**
* This is being called by the layer pain to implement the timeline cursor
*
* @param e
*/
private void processMouseDrag(MouseEvent e) {
if (mTimelineStructure == null) {
return;
}
int timeStart = MEUI.ourLeftColumnWidth + mTimelineStructure.myXTicksPixels[0];
int timeWidth =
mTimelineStructure.myXTicksPixels[mTimelineStructure.myXTicksPixels.length - 1]
- mTimelineStructure.myXTicksPixels[0];
float progress = (e.getX() - timeStart) / (float) (timeWidth);
float error = (float) (2 / timeWidth);
boolean inRange = progress > -error && progress < 1 + error;
switch (e.getID()) {
case MouseEvent.MOUSE_CLICKED: {
mTimeLine.requestFocus();
if (inRange) {
MTag oldSelection = mSelectedKeyFrame;
selectKeyFrame(progress);
int index = mTimeLine.getSelectedIndex();
mTimeLine.setSelectedIndex(index);
TimeLineRow row = mTimeLine.getTimeLineRow(index);
if (row == null) {
return;
}
Track.timelineTableSelect(mMeModel.myTrack);
row.setSelectedKeyFrame(mSelectedKeyFrame);
if (mSelectedKeyFrame != null && oldSelection != mSelectedKeyFrame) {
}
}
if (e.getX() < mTimeLineTopLeft.getWidth() && e.getY() > mTimeLineTopLeft.getHeight()) {
int index = mTimeLine.getSelectedIndex();
TimeLineRow row = mTimeLine.getTimeLineRow(index);
if (row != null) { // TODO: Check why this is being hit
row.toggleGraph();
}
}
}
break;
case MouseEvent.MOUSE_PRESSED: {
mMouseDown = (progress >= 0.0f && progress <= 1.0f);
if (mMouseDown) {
notifyTimeLineListeners(TimeLineCmd.MOTION_SCRUB, mMotionProgress);
}
repaint();
}
break;
case MouseEvent.MOUSE_RELEASED: {
if (mMouseDown) {
notifyTimeLineListeners(TimeLineCmd.MOTION_STOP, mMotionProgress);
}
mMouseDown = false;
repaint();
}
}
if (!mMouseDown) {
return;
}
if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0) {
if (progress >= 0.0f && progress <= 1.0f) {
mMotionProgress = progress;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, progress);
repaint();
} else if (progress <= 0.0f && mMotionProgress != 0.0f) {
mMotionProgress = 0.0f;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, progress);
repaint();
} else if (progress >= 1.0f && mMotionProgress != 1.0f) {
mMotionProgress = 1.0f;
notifyTimeLineListeners(TimeLineCmd.MOTION_PROGRESS, progress);
repaint();
}
}
}
private void selectKeyFrame(float progress) {
if (mTimeLine == null || mTimeLine.getSelectedValue() == null) {
return;
}
mSelectedKeyFrame = null;
ArrayList<MTag> f = mTimeLine.getSelectedValue().mKeyFrames;
float minDist = Float.MAX_VALUE;
MTag minTag = null;
for (MTag tag : f) {
String posString = tag.getAttributeValue("framePosition");
if (posString != null) {
float dist = Math.abs(progress - Integer.parseInt(posString) / 100f);
if (dist < minDist) {
minTag = tag;
minDist = dist;
}
}
}
if (minDist < 0.1f) {
mMotionEditorSelector.notifyListeners(MotionEditorSelector.Type.KEY_FRAME, new MTag[]{minTag}, 0);
mSelectedKeyFrame = minTag;
repaint();
}
}
public void setListeners(MotionEditorSelector listeners) {
mMotionEditorSelector = listeners;
}
/**
* This is a very simple vertical flow layout with special handling of the last Component
*/
static class VertLayout implements LayoutManager {
Dimension dimension = new Dimension();
@Override
public void addLayoutComponent(String name, Component comp) {
}
@Override
public void removeLayoutComponent(Component comp) {
}
@Override
public Dimension preferredLayoutSize(Container parent) {
int y = 0;
int width = 0;
int n = parent.getComponentCount();
for (int i = 0; i < n; i++) {
Component c = parent.getComponent(i);
Dimension size = c.getPreferredSize();
width = Math.max(width, size.width);
y += size.height;
}
dimension.height = y;
dimension.width = width;
return dimension;
}
@Override
public Dimension minimumLayoutSize(Container parent) {
int y = 0;
int width = 0;
int n = parent.getComponentCount();
for (int i = 0; i < n; i++) {
Component c = parent.getComponent(i);
Dimension size = c.getMinimumSize();
width = Math.max(width, size.width);
y += size.height;
}
dimension.height = y;
dimension.width = width;
return dimension;
}
@Override
public void layoutContainer(Container parent) {
int y = 0;
int n = parent.getComponentCount();
int parent_height = parent.getHeight();
int parent_width = parent.getWidth();
for (int i = 0; i < n; i++) {
Component c = parent.getComponent(i);
Dimension size = c.getPreferredSize();
if (i < n - 1) {
c.setBounds(0, y, parent_width, size.height);
} else {
if (parent_height - y <= 0) {
c.setBounds(0, y, parent_width, 0);
c.setVisible(false);
} else {
c.setBounds(0, y, parent_width, parent_height - y);
}
}
y += size.height;
}
}
}
public class METimeLine extends JPanel {
JPanel pad = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(MEUI.ourAvgBackground);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(MEUI.myGridColor);
TimeLineRow.drawTicks(g, mTimelineStructure, getHeight());
// draw line on the divider
g.setColor(MEUI.ourBorder);
g.fillRect(MEUI.ourLeftColumnWidth, 0, 1, getHeight());
}
};
int mSelectedIndex = 0;
ArrayList<ListSelectionListener> listeners = new ArrayList<>();
METimeLine() {
super(new VertLayout());
add(pad);
pad.setBackground(MEUI.ourAvgBackground);
MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
refreshCycling(true);
}
@Override
public void mouseReleased(MouseEvent e) {
refreshCycling(false);
int n = getComponentCount() - 1;
int y = e.getY();
for (int i = 0; i < n; i++) {
Component c = getComponent(i);
if (y < c.getY() + c.getHeight()) {
setSelectedIndex(i);
break;
}
}
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
};
addMouseListener(mouseAdapter);
}
void addListSelectionListener(ListSelectionListener l) {
listeners.add(l);
}
public TimeLineRow getTimeLineRow(int index) {
if (getComponent(index) instanceof TimeLineRow) {
return (TimeLineRow) getComponent(index);
}
return null;
}
public TimeLineRowData getSelectedValue() {
if (getComponent(mSelectedIndex) instanceof TimeLineRow) {
return ((TimeLineRow) getComponent(mSelectedIndex)).mRow;
}
return null;
}
public void setListData(List<TimeLineRowData> list, MeModel model) {
Component[] children = getComponents();
removeAll();
String lastName = null;
int n = Math.min(children.length - 1, list.size());
for (int i = 0; i < n; i++) {
TimeLineRow child = (TimeLineRow) children[i];
TimeLineRowData data = list.get(i);
boolean showTitle = !(data.mName != null && data.mName.equals(lastName));
child.setRowData(model, data, i, false, false, mSelectedKeyFrame, showTitle);
lastName = data.mName;
add(child);
}
if (n >= 0 && list.size() > n) {
for (int i = n; i < list.size(); i++) {
TimeLineRow child = new TimeLineRow(mTimelineStructure);
TimeLineRowData data = list.get(i);
boolean showTitle = !(data.mName != null && data.mName.equals(lastName));
if (data == null || data.mName == null) {
showTitle = false;
} else {
lastName = data.mName;
}
child.setRowData(model, data, i, false, false, mSelectedKeyFrame, showTitle);
add(child);
}
}
add(pad);
revalidate();
}
public int getSelectedIndex() {
return mSelectedIndex;
}
public void setSelectedIndex(int index) {
int prev = mSelectedIndex;
mSelectedIndex = index;
if (mSelectedKeyFrame == null) {
notifySelectionListener(index);
}
if (getComponentCount() > prev) {
Component comp = getComponent(prev);
if (!(comp instanceof TimeLineRow)) {
return;
}
TimeLineRow child = ((TimeLineRow) comp);
child.setSelected(false);
child.repaint();
}
TimeLineRow child = ((TimeLineRow) getComponent(mSelectedIndex));
child.setSelected(true);
child.repaint();
}
private void notifySelectionListener(int index) {
ListSelectionEvent event = new ListSelectionEvent(this, index, index, false);
for (ListSelectionListener listener : listeners) {
listener.valueChanged(event);
}
}
}
public static void main(String[] arg) {
String str = "{\n" +
" Debug: {\n" +
" name: 'motion8'\n" +
" },\n" +
" ConstraintSets: {\n" +
" start: {\n" +
" a: {\n" +
" width: 40,\n" +
" height: 40,\n" +
" start: ['parent', 'start', 16],\n" +
" bottom: ['parent', 'bottom', 16]\n" +
" }\n" +
" },\n" +
" end: {\n" +
" a: {\n" +
" width: 150,\n" +
" height: 100,\n" +
" rotationZ: 390,\n" +
" end: ['parent', 'end', 16],\n" +
" top: ['parent', 'top', 16]\n" +
" }\n" +
" }\n" +
" },\n" +
" Transitions: {\n" +
" default: {\n" +
" from: 'start',\n" +
" to: 'end',\n" +
" KeyFrames: {\n" +
" KeyPositions: [\n" +
" {\n" +
" target: ['a'],\n" +
" frames: [25, 50, 75],\n" +
" percentX: [0.1, 0.8, 0.1],\n" +
" percentY: [0.4, 0.8, 0]\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
showTimeline(str);
}
JFrame mTimeLineFrame;
public static TimeLinePanel showTimeline(String motionSceneString) {
JFrame frame = new JFrame();
TimeLinePanel tlp = new TimeLinePanel();
tlp.updateMotionScene(motionSceneString);
tlp.setListeners(new MotionEditorSelector());
frame.setContentPane(tlp);
frame.setTitle("TimeLinePanel");
Desk.rememberPosition(frame, null);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true);
tlp.mTimeLineFrame = frame;
return tlp;
}
public void updateMotionScene(String motionSceneString){
ScenePicker picker = new ScenePicker();
picker.foreachObject(p->{
if (p instanceof MouseAdapter) {
MouseAdapter ma = (MouseAdapter) p;
ma.mouseDragged(null);
}
});
DefaultMTag transition = (DefaultMTag) KeyFramesTag.parseForTimeLine(motionSceneString);
if (DEBUG) {
Debug.log("Transition ... ");
transition.printFormal("|", System.out);
Debug.log("-----------------");
}
DefaultMTag motionScene = new DefaultMTag("MotionScene");
motionScene.addChild(transition);
DefaultMTag startTag = new DefaultMTag("ConstraintSet");
DefaultMTag endTag = new DefaultMTag("ConstraintSet");
motionScene.addChild(startTag, endTag);
MTag[] tags = transition.getChildTags(KEY_FRAME_SET);
MTag keyFramesTag = null;
if (tags.length > 0) {
keyFramesTag = tags[0];
MTag kfs = keyFramesTag;
MTag[] keyFrames = kfs.getChildTags();
HashSet<String> ids = new HashSet<>();
for (int i = 0; i < keyFrames.length; i++) {
MTag keyFrame = keyFrames[i];
ids.add(keyFrame.getAttributeValue("motionTarget"));
}
String[] widgets = ids.toArray(new String[0]);
String start = transition.getAttributeValue("constraintSetStart");
String end = transition.getAttributeValue("constraintSetEnd");
try {
CLKey key = CLScan.findCLKey(CLParser.parse(motionSceneString), "ConstraintSets");
CLObject obj = (CLObject) key.getValue();
CLObject startObj = (CLObject) obj.get(start);
CLObject endObj = (CLObject) obj.get(end);
startTag.addAttribute("id", start);
endTag.addAttribute("id", end);
for (int i = 0; i < widgets.length; i++) {
String widget = widgets[i];
DefaultMTag wc_s = new DefaultMTag("Constraint");
startTag.addChild(wc_s);
wc_s.addAttribute("layout_constraintTag", widget);
wc_s.addAttribute("id", widget);
DefaultMTag wc_e = new DefaultMTag("Constraint");
wc_e.addAttribute("layout_constraintTag", widget);
wc_e.addAttribute("id", widget);
endTag.addChild(wc_e);
}
} catch (CLParsingException e) {
e.printStackTrace();
}
}
setMTag(transition, new MeModel(motionScene, null, null, null, null));
}
public void exitTimeLine() {
if (mTimeLineFrame != null) {
mTimeLineFrame.setVisible(false);
}
}
public void popUp() {
mTimeLineFrame.setVisible(true);
}
public void popDown() {
mTimeLineFrame.setVisible(false);
}
interface ProgressListener {
void setProgress(float p);
}
public void setMotionProgress(float progress){
mMeModel.setProgress(progress);
mMotionProgress = progress;
repaint();
}
public void setProgressListener(ProgressListener listener) {
TimeLinePanel mTimeLinePanel = null;
mTimeLinePanel.addTimeLineListener( (cmd, pos) ->{
System.out.println(pos);
});
}
public void updateTransition(String str) {
MTag tag = KeyFramesTag.parseForTimeLine(str);
setMTag(tag, mMeModel);
}
}
| fix timeline panel cine play jitter (#347)
| desktop/ConstraintLayoutInspector/app/src/androidx/constraintLayout/desktop/ui/timeline/TimeLinePanel.java | fix timeline panel cine play jitter (#347) |
|
Java | apache-2.0 | 3a9a9169571b608bac808a61b146f20a836efb76 | 0 | Neoskai/greycat,datathings/greycat,electricalwind/greycat,Neoskai/greycat,Neoskai/greycat,datathings/greycat,datathings/greycat,Neoskai/greycat,datathings/greycat,electricalwind/greycat,electricalwind/greycat,datathings/greycat,datathings/greycat,electricalwind/greycat,Neoskai/greycat,electricalwind/greycat,Neoskai/greycat,electricalwind/greycat | package org.kevoree.modeling.generator.standalone;
import org.kevoree.modeling.action.VersionAnalyzer;
import org.kevoree.modeling.generator.GenerationContext;
import org.kevoree.modeling.generator.Generator;
import org.kevoree.modeling.generator.JSOptimizer;
import org.kevoree.modeling.generator.mavenplugin.GenModelPlugin;
import org.kevoree.modeling.generator.mavenplugin.TscRunner;
import org.kevoree.modeling.java2typescript.SourceTranslator;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class App {
public static void main(final String[] args) throws IOException, InterruptedException {
ThreadGroup tg = new ThreadGroup("KMFCompiler");
Thread t = new Thread(tg, new Runnable() {
@Override
public void run() {
try {
if (args.length != 1 && args.length != 2) {
System.out.println("Bad arguments : <metaModelFile> [<js/jar/umd>]");
return;
}
String ecore = args[0];
File metaModelFile = new File(ecore);
if (!metaModelFile.exists()) {
System.out.println("Bad arguments : <metaModelFile> [<js/jar>] : metaModelFile not exists");
}
if (!metaModelFile.getName().contains(".")) {
System.out.println("Bad input file " + metaModelFile.getName() + " , must be .mm");
}
Boolean js = false;
Boolean umd = false;
if (args.length > 1 && args[1].toLowerCase().equals("js")) {
js = true;
}
if (args.length > 1 && args[1].toLowerCase().equals("umd")) {
js = true;
umd = true;
}
GenerationContext ctx = new GenerationContext();
File masterOut = new File("gen");
if (System.getProperty("output") != null) {
masterOut = new File(System.getProperty("output"));
}
masterOut.mkdirs();
File srcOut = new File(masterOut, "java");
srcOut.mkdirs();
File jsDir = new File(masterOut, "js");
jsDir.mkdirs();
ctx.setMetaModel(metaModelFile);
String mmName = metaModelFile.getName().substring(0, metaModelFile.getName().lastIndexOf("."));
ctx.setMetaModelName(mmName.substring(0, 1).toUpperCase() + mmName.substring(1));
ctx.setTargetSrcDir(srcOut);
ctx.setVersion(VersionAnalyzer.getVersion(metaModelFile));
Generator generator = new Generator();
generator.execute(ctx);
if (js) {
Files.createDirectories(jsDir.toPath());
Path libDts = Paths.get(jsDir.toPath().toString(), GenModelPlugin.LIB_D_TS);
Files.copy(this.getClass().getClassLoader().getResourceAsStream("tsc/" + GenModelPlugin.LIB_D_TS), libDts, StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getClassLoader().getResourceAsStream(GenModelPlugin.TSC_JS), Paths.get(jsDir.toPath().toString(), GenModelPlugin.TSC_JS), StandardCopyOption.REPLACE_EXISTING);
SourceTranslator sourceTranslator = new SourceTranslator();
sourceTranslator.additionalAppend = "org.kevoree.modeling.microframework.browser.ts";
sourceTranslator.exportPackage = new String[]{"org"};
String[] javaClassPath = System.getProperty("java.class.path").split(File.pathSeparator);
for (String dep : javaClassPath) {
if (dep.endsWith(".jar")) {
sourceTranslator.getAnalyzer().addClasspath(dep);
}
}
sourceTranslator.translateSources(srcOut.getAbsolutePath(), jsDir.getAbsolutePath(), ctx.getMetaModelName(), false, false, umd);
TscRunner runner = new TscRunner();
Path tscPath = Paths.get(jsDir.toPath().toString(), GenModelPlugin.TSC_JS);
runner.runTsc(jsDir, jsDir, null, true, umd);
File input = new File(jsDir.getAbsolutePath(), ctx.getMetaModelName() + ".js");
File outputMin = new File(jsDir.getAbsolutePath(), ctx.getMetaModelName() + ".min.js");
JSOptimizer.optimize(input, outputMin);
tscPath.toFile().delete();
libDts.toFile().delete();
}
System.out.println("Output : " + masterOut.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
t.join();
Thread[] subT = new Thread[1000];
tg.enumerate(subT, true);
for (Thread sub : subT) {
try {
if (sub != null) {
sub.interrupt();
sub.stop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
tg.interrupt();
tg.stop();
}
}
| org.kevoree.modeling.generator.standalone/src/main/java/org/kevoree/modeling/generator/standalone/App.java | package org.kevoree.modeling.generator.standalone;
import org.kevoree.modeling.action.VersionAnalyzer;
import org.kevoree.modeling.generator.GenerationContext;
import org.kevoree.modeling.generator.Generator;
import org.kevoree.modeling.generator.mavenplugin.GenModelPlugin;
import org.kevoree.modeling.generator.mavenplugin.TscRunner;
import org.kevoree.modeling.java2typescript.SourceTranslator;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class App {
public static void main(final String[] args) throws IOException, InterruptedException {
ThreadGroup tg = new ThreadGroup("KMFCompiler");
Thread t = new Thread(tg, new Runnable() {
@Override
public void run() {
try {
if (args.length != 1 && args.length != 2) {
System.out.println("Bad arguments : <metaModelFile> [<js/jar/umd>]");
return;
}
String ecore = args[0];
File metaModelFile = new File(ecore);
if (!metaModelFile.exists()) {
System.out.println("Bad arguments : <metaModelFile> [<js/jar>] : metaModelFile not exists");
}
if (!metaModelFile.getName().contains(".")) {
System.out.println("Bad input file " + metaModelFile.getName() + " , must be .mm");
}
Boolean js = false;
Boolean umd = false;
if (args.length > 1 && args[1].toLowerCase().equals("js")) {
js = true;
}
if (args.length > 1 && args[1].toLowerCase().equals("umd")) {
js = true;
umd = true;
}
GenerationContext ctx = new GenerationContext();
File masterOut = new File("gen");
if (System.getProperty("output") != null) {
masterOut = new File(System.getProperty("output"));
}
masterOut.mkdirs();
File srcOut = new File(masterOut, "java");
srcOut.mkdirs();
File jsDir = new File(masterOut, "js");
jsDir.mkdirs();
ctx.setMetaModel(metaModelFile);
String mmName = metaModelFile.getName().substring(0, metaModelFile.getName().lastIndexOf("."));
ctx.setMetaModelName(mmName.substring(0, 1).toUpperCase() + mmName.substring(1));
ctx.setTargetSrcDir(srcOut);
ctx.setVersion(VersionAnalyzer.getVersion(metaModelFile));
Generator generator = new Generator();
generator.execute(ctx);
if (js) {
Files.createDirectories(jsDir.toPath());
Path libDts = Paths.get(jsDir.toPath().toString(), GenModelPlugin.LIB_D_TS);
Files.copy(this.getClass().getClassLoader().getResourceAsStream("tsc/" + GenModelPlugin.LIB_D_TS), libDts, StandardCopyOption.REPLACE_EXISTING);
Files.copy(getClass().getClassLoader().getResourceAsStream(GenModelPlugin.TSC_JS), Paths.get(jsDir.toPath().toString(), GenModelPlugin.TSC_JS), StandardCopyOption.REPLACE_EXISTING);
SourceTranslator sourceTranslator = new SourceTranslator();
sourceTranslator.additionalAppend = "org.kevoree.modeling.microframework.browser.ts";
sourceTranslator.exportPackage = new String[]{"org"};
String[] javaClassPath = System.getProperty("java.class.path").split(File.pathSeparator);
for (String dep : javaClassPath) {
if (dep.endsWith(".jar")) {
sourceTranslator.getAnalyzer().addClasspath(dep);
}
}
sourceTranslator.translateSources(srcOut.getAbsolutePath(), jsDir.getAbsolutePath(), ctx.getMetaModelName(), false, false, umd);
TscRunner runner = new TscRunner();
Path tscPath = Paths.get(jsDir.toPath().toString(), GenModelPlugin.TSC_JS);
runner.runTsc(jsDir, jsDir, null, true, umd);
tscPath.toFile().delete();
libDts.toFile().delete();
}
System.out.println("Output : " + masterOut.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
t.join();
Thread[] subT = new Thread[1000];
tg.enumerate(subT, true);
for (Thread sub : subT) {
try {
if (sub != null) {
sub.interrupt();
sub.stop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
tg.interrupt();
tg.stop();
}
}
| fix the standalone generator
| org.kevoree.modeling.generator.standalone/src/main/java/org/kevoree/modeling/generator/standalone/App.java | fix the standalone generator |
|
Java | apache-2.0 | f39f088ae1a17a3d2f2f7449d41d5fe48b5d2b9e | 0 | abburgess/ENVIJava | /*
* 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.
*
* @Author: Arturo Beltran
*/
package edu.usc.sunset.burgess.tika;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Set;
import java.nio.charset.Charset;
import org.apache.tika.detect.AutoDetectReader;
import org.apache.tika.io.CloseShieldInputStream;
import org.apache.tika.io.IOUtils;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.AbstractParser;
import org.apache.tika.sax.XHTMLContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
public class EnviHeaderParser extends AbstractParser
{
private static final Set<MediaType> SUPPORTED_TYPES =
Collections.singleton(MediaType.application("envi.hdr"));
public static final String HELLO_MIME_TYPE =
"application/envi.hdr";
public Set<MediaType> getSupportedTypes(ParseContext context) {
return SUPPORTED_TYPES;
}
public void parse(InputStream stream, ContentHandler handler,
Metadata metadata, ParseContext context)
throws IOException, SAXException, TikaException {
//Only outputting the MIME type as metadata
metadata.set(Metadata.CONTENT_TYPE, HELLO_MIME_TYPE);
// The following code was taken from the TXTParser
// Automatically detect the character encoding
AutoDetectReader reader =
new AutoDetectReader(new CloseShieldInputStream(stream), metadata);
try {
Charset charset = reader.getCharset();
MediaType type = new MediaType(ENVI_MIME_TYPE, charset);
// deprecated, see TIKA-431
metadata.set(Metadata.CONTENT_ENCODING, charset.name());
XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
xhtml.startDocument();
//text contents of the xhtml
xhtml.startElement("p");
char[] buffer = new char[4096];
int n = reader.read(buffer);
while (n != -1) {
xhtml.characters(buffer, 0, n);
n = reader.read(buffer);
}
xhtml.endElement("p");
xhtml.endDocument();
}
finally{
reader.close();
}
}
} | src/main/java/edu/usc/sunset/burgess/tika/EnviHeaderParser.java | /*
* 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.
*
* @Author: Arturo Beltran
*/
package edu.usc.sunset.burgess.tika;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Set;
import java.nio.charset.Charset;
import org.apache.tika.detect.AutoDetectReader;
import org.apache.tika.io.CloseShieldInputStream;
import org.apache.tika.io.IOUtils;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.AbstractParser;
import org.apache.tika.sax.XHTMLContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
public class EnviHeaderParser extends AbstractParser
{
private static final Set<MediaType> SUPPORTED_TYPES =
Collections.singleton(MediaType.application("envi.hdr"));
public static final String HELLO_MIME_TYPE =
"application/envi.hdr";
public Set<MediaType> getSupportedTypes(ParseContext context) {
return SUPPORTED_TYPES;
}
public void parse(InputStream stream, ContentHandler handler,
Metadata metadata, ParseContext context)
throws IOException, SAXException, TikaException {
//Only outputting the MIME type as metadata
metadata.set(Metadata.CONTENT_TYPE, HELLO_MIME_TYPE);
// The following code was taken from the TXTParser
// Automatically detect the character encoding
AutoDetectReader reader =
new AutoDetectReader(new CloseShieldInputStream(stream), metadata);
try {
Charset charset = reader.getCharset();
MediaType type = new MediaType(MediaType.TEXT_PLAIN, charset);
// deprecated, see TIKA-431
metadata.set(Metadata.CONTENT_ENCODING, charset.name());
XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
xhtml.startDocument();
//text contents of the xhtml
xhtml.startElement("p");
char[] buffer = new char[4096];
int n = reader.read(buffer);
while (n != -1) {
xhtml.characters(buffer, 0, n);
n = reader.read(buffer);
}
xhtml.endElement("p");
xhtml.endDocument();
}
finally{
reader.close();
}
}
} | revert media type to text.plain
| src/main/java/edu/usc/sunset/burgess/tika/EnviHeaderParser.java | revert media type to text.plain |
|
Java | apache-2.0 | b6c68d18a013a9bb8c1fa37073cef1ff84500ef4 | 0 | d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor | /**
* Copyright 2016 Netflix, Inc.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.netflix.conductor.service;
import com.google.common.base.Preconditions;
import com.netflix.conductor.annotations.Trace;
import com.netflix.conductor.common.metadata.events.EventHandler;
import com.netflix.conductor.common.metadata.tasks.TaskDef;
import com.netflix.conductor.common.metadata.workflow.WorkflowDef;
import com.netflix.conductor.common.run.SearchResult;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.common.run.WorkflowSummary;
import com.netflix.conductor.core.WorkflowContext;
import com.netflix.conductor.core.events.EventQueues;
import com.netflix.conductor.core.execution.ApplicationException;
import com.netflix.conductor.core.execution.ApplicationException.Code;
import com.netflix.conductor.core.execution.WorkflowExecutor;
import com.netflix.conductor.dao.IndexDAO;
import com.netflix.conductor.dao.MetadataDAO;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
/**
* @author Viren
*/
@Singleton
@Trace
public class MetadataService {
private IndexDAO indexer;
private MetadataDAO metadata;
private WorkflowExecutor executor;
private ExecutionService service;
@Inject
public MetadataService(MetadataDAO metadata, IndexDAO indexDAO, ExecutionService service, WorkflowExecutor executor) {
this.metadata = metadata;
this.service = service;
this.executor = executor;
this.indexer = indexDAO;
}
/**
* @param taskDefs Task Definitions to register
*/
public void registerTaskDef(List<TaskDef> taskDefs) {
for (TaskDef taskDef : taskDefs) {
taskDef.setCreatedBy(WorkflowContext.get().getClientApp());
taskDef.setCreateTime(System.currentTimeMillis());
taskDef.setUpdatedBy(null);
taskDef.setUpdateTime(null);
metadata.createTaskDef(taskDef);
}
}
/**
* @param taskDef Task Definition to be updated
*/
public void updateTaskDef(TaskDef taskDef) {
TaskDef existing = metadata.getTaskDef(taskDef.getName());
if (existing == null) {
throw new ApplicationException(Code.NOT_FOUND, "No such task by name " + taskDef.getName());
}
taskDef.setUpdatedBy(WorkflowContext.get().getClientApp());
taskDef.setUpdateTime(System.currentTimeMillis());
metadata.updateTaskDef(taskDef);
}
/**
* @param taskType Remove task definition
*/
public void unregisterTaskDef(String taskType) {
metadata.removeTaskDef(taskType);
}
/**
* @return List of all the registered tasks
*/
public List<TaskDef> getTaskDefs() {
return metadata.getAllTaskDefs();
}
/**
* @param taskType Task to retrieve
* @return Task Definition
*/
public TaskDef getTaskDef(String taskType) {
return metadata.getTaskDef(taskType);
}
/**
* @param def Workflow definition to be updated
*/
public void updateWorkflowDef(WorkflowDef def) {
metadata.update(def);
}
/**
* @param wfs Workflow definitions to be updated.
*/
public void updateWorkflowDef(List<WorkflowDef> wfs) {
for (WorkflowDef wf : wfs) {
metadata.update(wf);
}
}
/**
* @param name Name of the workflow to retrieve
* @param version Optional. Version. If null, then retrieves the latest
* @return Workflow definition
*/
public WorkflowDef getWorkflowDef(String name, Integer version) {
if (version == null) {
return metadata.getLatest(name);
}
return metadata.get(name, version);
}
/**
* Remove workflow definition
*
* @param name workflow name
* @param version workflow version
*/
public void unregisterWorkflow(String name, Integer version) {
WorkflowDef def;
if (version == null) {
def = metadata.getLatest(name);
} else {
def = metadata.get(name, version);
}
if (def == null) {
throw new ApplicationException(Code.NOT_FOUND, "No such workflow by name " + name + " and version " + version);
}
String query = "workflowType IN (" + def.getName() + ") AND version IN (" + def.getVersion() + ")";
// Work in the batch mode
while (true) {
// Get the batch
SearchResult<WorkflowSummary> workflows = service.search(query, "*", 0, 100, null, null, null);
if (workflows.getTotalHits() <= 0) {
break;
}
// Process batch
workflows.getResults().forEach(workflow -> {
// Terminate workflow if it is running
if (Workflow.WorkflowStatus.RUNNING == workflow.getStatus()) {
try {
executor.terminateWorkflow(workflow.getWorkflowId(), "Metadata deleting requested");
} catch (Exception ignore) {
}
}
// remove workflow
try {
service.removeWorkflow(workflow.getWorkflowId());
} catch (Exception ignore) {
}
// remove from index
try {
indexer.remove(workflow.getWorkflowId());
} catch (Exception ignore) {
}
});
}
// remove metadata
metadata.removeWorkflow(def);
}
/**
* @param name Name of the workflow to retrieve
* @return Latest version of the workflow definition
*/
public WorkflowDef getLatestWorkflow(String name) {
return metadata.getLatest(name);
}
public List<WorkflowDef> getWorkflowDefs() {
return metadata.getAll();
}
public void registerWorkflowDef(WorkflowDef def) {
if (def.getName().contains(":")) {
throw new ApplicationException(Code.INVALID_INPUT, "Workflow name cannot contain the following set of characters: ':'");
}
if (def.getSchemaVersion() < 1 || def.getSchemaVersion() > 2) {
def.setSchemaVersion(2);
}
metadata.create(def);
}
/**
* @param eventHandler Event handler to be added.
* Will throw an exception if an event handler already exists with the name
*/
public void addEventHandler(EventHandler eventHandler) {
validateEvent(eventHandler);
EventHandler existing = getEventHandler(eventHandler.getName());
if (existing != null) {
throw new ApplicationException(ApplicationException.Code.CONFLICT, "EventHandler with name " + eventHandler.getName() + " already exists!");
}
validateQueue(eventHandler);
metadata.addEventHandler(eventHandler);
}
/**
* @param eventHandler Event handler to be updated.
*/
public void updateEventHandler(EventHandler eventHandler) {
validateEvent(eventHandler);
EventHandler existing = getEventHandler(eventHandler.getName());
if (existing == null) {
throw new ApplicationException(ApplicationException.Code.NOT_FOUND, "EventHandler with name " + eventHandler.getName() + " not found!");
}
// Are subject:queue the same or been updated ?
boolean eventEquals = existing.getEvent().equalsIgnoreCase(eventHandler.getEvent());
// The new handler is disabled - close old queue
if (existing.isActive() && !eventHandler.isActive()) {
EventQueues.remove(existing.getEvent());
} else if (!eventEquals) { // if subject:queue was updated
EventQueues.remove(existing.getEvent());
}
validateQueue(eventHandler);
metadata.updateEventHandler(eventHandler);
}
/**
* @param name Removes the event handler from the system
*/
public void removeEventHandlerStatus(String name) {
EventHandler existing = getEventHandler(name);
if (existing == null) {
throw new ApplicationException(ApplicationException.Code.NOT_FOUND, "EventHandler with name " + name + " not found!");
}
EventQueues.remove(existing.getEvent());
metadata.removeEventHandlerStatus(name);
}
/**
* @return All the event handlers registered in the system
*/
public List<EventHandler> getEventHandlers() {
return metadata.getEventHandlers();
}
/**
* @param event name of the event
* @param activeOnly if true, returns only the active handlers
* @return Returns the list of all the event handlers for a given event
*/
public List<EventHandler> getEventHandlersForEvent(String event, boolean activeOnly) {
return metadata.getEventHandlersForEvent(event, activeOnly);
}
/**
* This method just validates required fields
*
* @param eh Event handler definition
*/
private void validateEvent(EventHandler eh) {
Preconditions.checkNotNull(eh.getName(), "Missing event handler name");
Preconditions.checkNotNull(eh.getEvent(), "Missing event location");
Preconditions.checkNotNull(eh.getActions(), "No actions specified. Please specify at-least one action");
}
/**
* This method was created to divide event handler validation logic and the queue validation.
* We do not want to register queue in the EventQueues if existence logic fails
*
* @param eh Event handler definition
*/
private void validateQueue(EventHandler eh) {
String event = eh.getEvent();
if (eh.isActive()) {
EventQueues.getQueue(event, true);
}
}
private EventHandler getEventHandler(String name) {
return getEventHandlers().stream()
.filter(eh -> eh.getName().equalsIgnoreCase(name))
.findFirst().orElse(null);
}
}
| core/src/main/java/com/netflix/conductor/service/MetadataService.java | /**
* Copyright 2016 Netflix, Inc.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.netflix.conductor.service;
import com.google.common.base.Preconditions;
import com.netflix.conductor.annotations.Trace;
import com.netflix.conductor.common.metadata.events.EventHandler;
import com.netflix.conductor.common.metadata.tasks.TaskDef;
import com.netflix.conductor.common.metadata.workflow.WorkflowDef;
import com.netflix.conductor.common.run.SearchResult;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.common.run.WorkflowSummary;
import com.netflix.conductor.core.WorkflowContext;
import com.netflix.conductor.core.events.EventQueues;
import com.netflix.conductor.core.execution.ApplicationException;
import com.netflix.conductor.core.execution.ApplicationException.Code;
import com.netflix.conductor.core.execution.WorkflowExecutor;
import com.netflix.conductor.dao.IndexDAO;
import com.netflix.conductor.dao.MetadataDAO;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.List;
/**
* @author Viren
*/
@Singleton
@Trace
public class MetadataService {
private IndexDAO indexer;
private MetadataDAO metadata;
private WorkflowExecutor executor;
private ExecutionService service;
@Inject
public MetadataService(MetadataDAO metadata, IndexDAO indexDAO, ExecutionService service, WorkflowExecutor executor) {
this.metadata = metadata;
this.service = service;
this.executor = executor;
this.indexer = indexDAO;
}
/**
* @param taskDefs Task Definitions to register
*/
public void registerTaskDef(List<TaskDef> taskDefs) {
for (TaskDef taskDef : taskDefs) {
taskDef.setCreatedBy(WorkflowContext.get().getClientApp());
taskDef.setCreateTime(System.currentTimeMillis());
taskDef.setUpdatedBy(null);
taskDef.setUpdateTime(null);
metadata.createTaskDef(taskDef);
}
}
/**
* @param taskDef Task Definition to be updated
*/
public void updateTaskDef(TaskDef taskDef) {
TaskDef existing = metadata.getTaskDef(taskDef.getName());
if (existing == null) {
throw new ApplicationException(Code.NOT_FOUND, "No such task by name " + taskDef.getName());
}
taskDef.setUpdatedBy(WorkflowContext.get().getClientApp());
taskDef.setUpdateTime(System.currentTimeMillis());
metadata.updateTaskDef(taskDef);
}
/**
* @param taskType Remove task definition
*/
public void unregisterTaskDef(String taskType) {
metadata.removeTaskDef(taskType);
}
/**
* @return List of all the registered tasks
*/
public List<TaskDef> getTaskDefs() {
return metadata.getAllTaskDefs();
}
/**
* @param taskType Task to retrieve
* @return Task Definition
*/
public TaskDef getTaskDef(String taskType) {
return metadata.getTaskDef(taskType);
}
/**
* @param def Workflow definition to be updated
*/
public void updateWorkflowDef(WorkflowDef def) {
metadata.update(def);
}
/**
* @param wfs Workflow definitions to be updated.
*/
public void updateWorkflowDef(List<WorkflowDef> wfs) {
for (WorkflowDef wf : wfs) {
metadata.update(wf);
}
}
/**
* @param name Name of the workflow to retrieve
* @param version Optional. Version. If null, then retrieves the latest
* @return Workflow definition
*/
public WorkflowDef getWorkflowDef(String name, Integer version) {
if (version == null) {
return metadata.getLatest(name);
}
return metadata.get(name, version);
}
/**
* Remove workflow definition
*
* @param name workflow name
* @param version workflow version
*/
public void unregisterWorkflow(String name, Integer version) {
WorkflowDef def;
if (version == null) {
def = metadata.getLatest(name);
} else {
def = metadata.get(name, version);
}
if (def == null) {
throw new ApplicationException(Code.NOT_FOUND, "No such workflow by name " + name + " and version " + version);
}
String query = "workflowType IN (" + def.getName() + ") AND version IN (" + def.getVersion() + ")";
// Work in the batch mode
while (true) {
// Get the batch
SearchResult<WorkflowSummary> workflows = service.search(query, "*", 0, 100, null, null, null);
if (workflows.getTotalHits() <= 0) {
break;
}
// Process batch
workflows.getResults().forEach(workflow -> {
// Terminate workflow if it is running
if (Workflow.WorkflowStatus.RUNNING == workflow.getStatus()) {
try {
executor.terminateWorkflow(workflow.getWorkflowId(), "Metadata deleting requested");
} catch (Exception ignore) {
}
}
// remove workflow
try {
service.removeWorkflow(workflow.getWorkflowId());
} catch (Exception ignore) {
}
// remove from index
try {
indexer.remove(workflow.getWorkflowId());
} catch (Exception ignore) {
}
});
}
// remove metadata
metadata.removeWorkflow(def);
}
/**
* @param name Name of the workflow to retrieve
* @return Latest version of the workflow definition
*/
public WorkflowDef getLatestWorkflow(String name) {
return metadata.getLatest(name);
}
public List<WorkflowDef> getWorkflowDefs() {
return metadata.getAll();
}
public void registerWorkflowDef(WorkflowDef def) {
if (def.getName().contains(":")) {
throw new ApplicationException(Code.INVALID_INPUT, "Workflow name cannot contain the following set of characters: ':'");
}
if (def.getSchemaVersion() < 1 || def.getSchemaVersion() > 2) {
def.setSchemaVersion(2);
}
metadata.create(def);
}
/**
* @param eventHandler Event handler to be added.
* Will throw an exception if an event handler already exists with the name
*/
public void addEventHandler(EventHandler eventHandler) {
validateEvent(eventHandler);
EventHandler existing = getEventHandler(eventHandler.getName());
if (existing != null) {
throw new ApplicationException(ApplicationException.Code.CONFLICT, "EventHandler with name " + eventHandler.getName() + " already exists!");
}
validateQueue(eventHandler);
metadata.addEventHandler(eventHandler);
}
/**
* @param eventHandler Event handler to be updated.
*/
public void updateEventHandler(EventHandler eventHandler) {
validateEvent(eventHandler);
EventHandler existing = getEventHandler(eventHandler.getName());
if (existing == null) {
throw new ApplicationException(ApplicationException.Code.NOT_FOUND, "EventHandler with name " + eventHandler.getName() + " not found!");
}
boolean eventEquals = existing.getEvent().equalsIgnoreCase(eventHandler.getEvent());
// if event name was updated or the new is disabled - close old queue
if (!eventEquals || !eventHandler.isActive()) {
EventQueues.remove(existing.getEvent());
}
validateQueue(eventHandler);
metadata.updateEventHandler(eventHandler);
}
/**
* @param name Removes the event handler from the system
*/
public void removeEventHandlerStatus(String name) {
EventHandler existing = getEventHandler(name);
if (existing == null) {
throw new ApplicationException(ApplicationException.Code.NOT_FOUND, "EventHandler with name " + name + " not found!");
}
EventQueues.remove(existing.getEvent());
metadata.removeEventHandlerStatus(name);
}
/**
* @return All the event handlers registered in the system
*/
public List<EventHandler> getEventHandlers() {
return metadata.getEventHandlers();
}
/**
* @param event name of the event
* @param activeOnly if true, returns only the active handlers
* @return Returns the list of all the event handlers for a given event
*/
public List<EventHandler> getEventHandlersForEvent(String event, boolean activeOnly) {
return metadata.getEventHandlersForEvent(event, activeOnly);
}
/**
* This method just validates required fields
*
* @param eh Event handler definition
*/
private void validateEvent(EventHandler eh) {
Preconditions.checkNotNull(eh.getName(), "Missing event handler name");
Preconditions.checkNotNull(eh.getEvent(), "Missing event location");
Preconditions.checkNotNull(eh.getActions(), "No actions specified. Please specify at-least one action");
}
/**
* This method was created to divide event handler validation logic and the queue validation.
* We do not want to register queue in the EventQueues if existence logic fails
*
* @param eh Event handler definition
*/
private void validateQueue(EventHandler eh) {
String event = eh.getEvent();
if (eh.isActive()) {
EventQueues.getQueue(event, true);
}
}
private EventHandler getEventHandler(String name) {
return getEventHandlers().stream()
.filter(eh -> eh.getName().equalsIgnoreCase(name))
.findFirst().orElse(null);
}
}
| ONECOND-1048 Handler doesn't receive the message but no notification.
| core/src/main/java/com/netflix/conductor/service/MetadataService.java | ONECOND-1048 Handler doesn't receive the message but no notification. |
|
Java | apache-2.0 | 44222807ba086feb939e85afe128f5d46e37099e | 0 | PedroGomes/TPCw-benchmark | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package benchmarks.TpcwBenchmark;
//import JaNaG_Source.de.beimax.janag.Namegenerator;
import benchmarks.helpers.BenchmarkUtil;
import benchmarks.interfaces.DataBaseCRUDInterface;
import java.io.FileNotFoundException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import benchmarks.DatabaseEngineInterfaces.CassandraInterface;
import benchmarks.TpcwBenchmark.testEntities.Address;
import benchmarks.TpcwBenchmark.testEntities.Author;
import benchmarks.TpcwBenchmark.testEntities.CCXact;
import benchmarks.TpcwBenchmark.testEntities.Costumer;
import benchmarks.TpcwBenchmark.testEntities.Country;
import benchmarks.TpcwBenchmark.testEntities.Item;
import benchmarks.TpcwBenchmark.testEntities.OrderLine;
import benchmarks.TpcwBenchmark.testEntities.Orders;
import benchmarks.helpers.JsonUtil;
import benchmarks.dataStatistics.ResultHandler;
import benchmarks.interfaces.Entity;
import benchmarks.interfaces.BenchmarkPopulator;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
/**
* @author pedro
*/
public class Populator implements BenchmarkPopulator {
/**
* Time measurements
*/
private static boolean delay_inserts = false;
private static int delay_time = 100;
private static Random rand = new Random();
private int rounds = 500;
private ResultHandler results;
String result_path;
//ATTENTION: The NUM_EBS and NUM_ITEMS variables are the only variables
//that should be modified in order to rescale the DB.
private static /* final */ int NUM_EBS = 10;
private static /* final */ int NUM_ITEMS = 1000;
private static /* final */ int NUM_CUSTOMERS = NUM_EBS * 2880;
private static /* final */ int NUM_ADDRESSES = 2 * NUM_CUSTOMERS;
private static /* final */ int NUM_AUTHORS = (int) (.25 * NUM_ITEMS);
private static /* final */ int NUM_ORDERS = (int) (.9 * NUM_CUSTOMERS);
private static /* final */ int NUM_COUNTRIES = 92; // this is constant. Never changes!
// static Client client;
private static DataBaseCRUDInterface databaseClientFactory;
ArrayList<String> authors = new ArrayList<String>();
ArrayList<String> addresses = new ArrayList<String>();
ArrayList<String> countries = new ArrayList<String>();
ArrayList<String> costumers = new ArrayList<String>();
ArrayList<String> items = new ArrayList<String>();
// CopyOnWriteArrayList<Orders> orders = new CopyOnWriteArrayList<Orders>();
// CopyOnWriteArrayList<OrderLine> orderLines = new CopyOnWriteArrayList<OrderLine>();
boolean debug = true;
private static int num_threads = 1;
boolean error = false;
private CountDownLatch barrier;
//databaseClient,number_threads_populator,benchmarkPopulatorInfo
public Populator(DataBaseCRUDInterface databaseCrudClient, int clients, Map<String, String> info) {
databaseClientFactory = databaseCrudClient;
num_threads = clients;
String do_delays = info.get("delay_inserts");
delay_inserts = Boolean.valueOf(do_delays.trim());
String delay_time_info = info.get("delay_time");
delay_time = Integer.valueOf(delay_time_info.trim());
String rounds_info = info.get("rounds");
if (rounds_info != null) {
rounds = Integer.valueOf(rounds_info.trim());
} else {
System.out.println("ROUND NUMBER NOT FOUND: 500 DEFAULT");
}
this.results = new ResultHandler("TPCW_POPULATOR", rounds);
result_path = info.get("result_path");
String ebs = info.get("tpcw_numEBS");
if (ebs != null) {
NUM_EBS = Integer.valueOf(ebs.trim());
} else {
System.out.println("SCALE FACTOR (EBS) NOT DEFINED. SET TO: " + NUM_EBS);
}
String items = info.get("tpcw_numItems");
if (items != null) {
NUM_ITEMS = Integer.valueOf(items.trim());
} else {
System.out.println("NUMBER OF ITEMS NOT DEFINED. SET TO: " + NUM_ITEMS);
}
NUM_CUSTOMERS = NUM_EBS * 2880;
NUM_ADDRESSES = 2 * NUM_CUSTOMERS;
NUM_AUTHORS = (int) (.25 * NUM_ITEMS);
NUM_ORDERS = (int) (.9 * NUM_CUSTOMERS);
}
// /**
// * @param args the command line arguments
// */
// public static void main(String[] args) {
//
// ResultHandler resultHandler = new ResultHandler("TPCW benchamrk", 400);
// // BenchmarkPopulator m = new Populator(resultHandler, 10);
// m.populate();
//
// }
public void databaseInsert(DataBaseCRUDInterface.CRUDclient client, String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
public boolean populate() {
if (error) {
return false;
} else {
try {
insertCountries(NUM_COUNTRIES);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertAddresses(NUM_ADDRESSES);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertCostumers(NUM_CUSTOMERS);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertAuthors(NUM_AUTHORS);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertItems(NUM_ITEMS);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertOrder_and_CC_XACTS(NUM_ORDERS);
System.out.println("***Finished***");
} catch (InterruptedException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (Exception ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
results.listDataToSOutput();
results.listDatatoFiles(result_path, "", true);
results.cleanResults();
return true;
}
}
public void cleanDB() {
removeALL();
}
public Map<String, Object> getUseFullData() {
TreeMap<String, Object> data = new TreeMap<String, Object>();
data.put("ITEMS", items);
data.put("COSTUMERS", costumers);
return data;
}
public void removeALL() {
DataBaseCRUDInterface.CRUDclient client = databaseClientFactory.getClient();
client.truncate("Costumer");
client.truncate("Items");
client.truncate("Orders");
client.truncate("OrderLines");
client.truncate("CC_XACTS");
client.truncate("Author");
client.truncate("Countries");
client.truncate("Addresses");
client.closeClient();
}
/************************************************************************/
/************************************************************************/
/************************************************************************/
/**
* ************
* Authors*
* **************
*/
public void insertAuthors(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Authors || populatores " + num_threads);
barrier = new CountDownLatch(threads);
AuthorPopulator[] partial_authors = new AuthorPopulator[threads];
for (int i = 0; i < threads; i++) {
AuthorPopulator populator = null;
if (i == 0) {
populator = new AuthorPopulator(firstSection);
} else {
populator = new AuthorPopulator(sections);
}
partial_authors[i] = populator;
Thread t = new Thread(populator);
t.start();
}
barrier.await();
for (AuthorPopulator populator : partial_authors) {
ArrayList<String> ids = populator.getData();
for (String id : ids) {
authors.add(id);
}
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
}
partial_authors = null;
System.gc();
}
class AuthorPopulator implements Runnable {
int num_authors;
DataBaseCRUDInterface.CRUDclient client;
ArrayList<String> partial_authors;
ResultHandler partial_results;
public AuthorPopulator(int num_authors) {
client = databaseClientFactory.getClient();
this.num_authors = num_authors;
partial_authors = new ArrayList<String>();
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertAuthors(num_authors);
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
public void insertAuthors(int n) {
System.out.println("Inserting Authors: " + n);
for (int i = 0; i < n; i++) {
GregorianCalendar cal = BenchmarkUtil.getRandomDate(1800, 1990);
String[] names = (BenchmarkUtil.getRandomAString(3, 20) + " " + BenchmarkUtil.getRandomAString(2, 20)).split(" ");
String[] Mnames = ("d " + BenchmarkUtil.getRandomAString(2, 20)).split(" ");
String first_name = names[0];
String last_name = names[1];
String middle_name = Mnames[1];
java.sql.Date dob = new java.sql.Date(cal.getTime().getTime());
String bio = BenchmarkUtil.getRandomAString(125, 500);
String key = first_name + middle_name + last_name + rand.nextInt(1000);
// insert(first_name, key, "Author", "A_FNAME", writeConsistency);
// insert(last_name, key, "Author", "A_LNAME", writeConsistency);
// insert(middle_name, key, "Author", "A_MNAME", writeConsistency);
// insert(dob, key, "Author", "A_DOB", writeConsistency);
// insert(bio, key, "Author", "A_BIO", writeConsistency);
Author a = new Author(key, first_name, last_name, middle_name, dob, bio);
databaseInsert("INSERT_Authors", key, "Author", a, partial_results);
partial_authors.add(a.getA_id());
}
if (debug) {
System.out.println("Thread finished: " + num_authors + " authors inserted");
}
barrier.countDown();
client.closeClient();
}
public ArrayList<String> getData() {
return partial_authors;
}
public ResultHandler returnResults() {
return partial_results;
}
}
/**
* ************
* Costumers*
* **************
*/
public void insertCostumers(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Costumers || populatores " + num_threads);
barrier = new CountDownLatch(threads);
CostumerPopulator[] partial_costumers = new CostumerPopulator[threads];
for (int i = 0; i < threads; i++) {
CostumerPopulator populator = null;
if (i == 0) {
populator = new CostumerPopulator(firstSection);
} else {
populator = new CostumerPopulator(sections);
}
partial_costumers[i] = populator;
Thread t = new Thread(populator);
t.start();
}
barrier.await();
for (CostumerPopulator populator : partial_costumers) {
ArrayList<String> ids = populator.getData();
for (String id : ids) {
costumers.add(id);
}
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
}
partial_costumers = null;
System.gc();
}
class CostumerPopulator implements Runnable {
DataBaseCRUDInterface.CRUDclient client;
int num_costumers;
ArrayList<String> partial_costumers;
ResultHandler partial_results;
public CostumerPopulator(int num_costumers) {
client = databaseClientFactory.getClient();
this.num_costumers = num_costumers;
partial_costumers = new ArrayList<String>();
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertCostumers(num_costumers);
}
public void insertCostumers(int n) {
System.out.println("Inserting Costumers: " + n);
for (int i = 0; i < n; i++) {
String name = (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15));
String[] names = name.split(" ");
Random r = new Random();
int random_int = r.nextInt(1000);
String key = name + "_" + random_int;
String pass = names[0].charAt(0) + names[1].charAt(0) + "" + random_int;
// insert(pass, key, "Costumer", "C_PASSWD", writeCon);
String first_name = names[0];
// insert(first_name, key, "Costumer", "C_FNAME", writeCon);
String last_name = names[1];
// insert(last_name, key, "Costumer", "C_LNAME", writeCon);
int phone = r.nextInt(999999999 - 100000000) + 100000000;
// insert(phone, key, "Costumer", "C_PHONE", writeCon);
String email = key + "@" + BenchmarkUtil.getRandomAString(2, 9) + ".com";
// insert(email, key, "Costumer", "C_EMAIL", writeCon);
double discount = r.nextDouble();
// insert(discount, key, "Costumer", "C_DISCOUNT", writeCon);
String adress = "Street: " + (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15)) + " number: " + r.nextInt(500);
// insert(adress, key, "Costumer", "C_PHONE", writeCon);
double C_BALANCE = 0.00;
// insert(C_BALANCE, key, "Costumer", "C_BALANCE", writeCon);
double C_YTD_PMT = (double) BenchmarkUtil.getRandomInt(0, 99999) / 100.0;
// insert(C_YTD_PMT, key, "Costumer", "C_YTD_PMT", writeCon);
GregorianCalendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, -1 * BenchmarkUtil.getRandomInt(1, 730));
java.sql.Date C_SINCE = new java.sql.Date(cal.getTime().getTime());
// insert(C_SINCE, key, "Costumer", "C_SINCE ", writeCon);
cal.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(0, 60));
if (cal.after(new GregorianCalendar())) {
cal = new GregorianCalendar();
}
java.sql.Date C_LAST_LOGIN = new java.sql.Date(cal.getTime().getTime());
//insert(C_LAST_LOGIN, key, "Costumer", "C_LAST_LOGIN", writeCon);
java.sql.Timestamp C_LOGIN = new java.sql.Timestamp(System.currentTimeMillis());
//insert(C_LOGIN, key, "Costumer", "C_LOGIN", writeCon);
cal = new GregorianCalendar();
cal.add(Calendar.HOUR, 2);
java.sql.Timestamp C_EXPIRATION = new java.sql.Timestamp(cal.getTime().getTime());
//insert(C_EXPIRATION, key, "Costumer", "C_EXPIRATION", writeCon);
cal = BenchmarkUtil.getRandomDate(1880, 2000);
java.sql.Date C_BIRTHDATE = new java.sql.Date(cal.getTime().getTime());
//insert(C_BIRTHDATE, key, "Costumer", "C_BIRTHDATE", writeCon);
String C_DATA = BenchmarkUtil.getRandomAString(100, 500);
//insert(C_DATA, key, "Costumer", "C_DATA", writeCon);
String address_id = addresses.get(rand.nextInt(addresses.size()));
//insert(address.getAddr_id(), key, "Costumer", "C_ADDR_ID", writeCon);
Costumer c = new Costumer(key, key, pass, last_name, first_name, phone, email, C_SINCE, C_LAST_LOGIN, C_LOGIN, C_EXPIRATION, C_BALANCE, C_YTD_PMT, C_BIRTHDATE, C_DATA, discount, address_id);
databaseInsert("INSERT_Costumers", key, "Costumer", c, partial_results);
partial_costumers.add(c.getC_id());
}
if (debug) {
System.out.println("Thread finished: " + num_costumers + " costumers inserted");
}
barrier.countDown();
client.closeClient();
}
public ArrayList<String> getData() {
return partial_costumers;
}
public ResultHandler returnResults() {
return partial_results;
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
}
/**
* ************
* Items*
* **************
*/
public void insertItems(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Items || populatores " + num_threads);
barrier = new CountDownLatch(threads);
ItemPopulator[] partial_items = new ItemPopulator[threads];
for (int i = 0; i < threads; i++) {
ItemPopulator populator = null;
if (i == 0) {
populator = new ItemPopulator(firstSection);
} else {
populator = new ItemPopulator(sections);
}
partial_items[i] = populator;
Thread t = new Thread(populator);
t.start();
}
barrier.await();
for (ItemPopulator populator : partial_items) {
ArrayList<String> ids = populator.getData();
for (String id : ids) {
items.add(id);
}
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
}
partial_items = null;
System.gc();
}
class ItemPopulator implements Runnable {
DataBaseCRUDInterface.CRUDclient client;
int num_items;
ArrayList<String> partial_items;
ResultHandler partial_results;
public ItemPopulator(int num_items) {
client = databaseClientFactory.getClient();
this.num_items = num_items;
partial_items = new ArrayList<String>();
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertItems(num_items);
}
public void insertItems(int n) {
String[] subjects = {"ARTS", "BIOGRAPHIES", "BUSINESS", "CHILDREN",
"COMPUTERS", "COOKING", "HEALTH", "HISTORY",
"HOME", "HUMOR", "LITERATURE", "MYSTERY",
"NON-FICTION", "PARENTING", "POLITICS",
"REFERENCE", "RELIGION", "ROMANCE",
"SELF-HELP", "SCIENCE-NATURE", "SCIENCE-FICTION",
"SPORTS", "YOUTH", "TRAVEL"};
String[] backings = {"HARDBACK", "PAPERBACK", "USED", "AUDIO",
"LIMITED-EDITION"};
String column_family = "Items";
System.out.println("Inserting Items: " + n);
ArrayList<String> titles = new ArrayList<String>();
for (int i = 0; i < n; i++) {
String f_name = BenchmarkUtil.getRandomAString(14, 60);
int num = rand.nextInt(1000);
titles.add(f_name + " " + num);
}
for (int i = 0; i < n; i++) {
String I_TITLE; //ID
String I_AUTHOR;
String I_PUBLISHER;
String I_DESC;
String I_SUBJECT;
float I_COST;
long I_STOCK;
List<String> I_RELATED = new ArrayList<String>();
int I_PAGE;
String I_BACKING;
I_TITLE = titles.get(i);
int author_pos = rand.nextInt(authors.size());
String author = authors.get(author_pos);
I_AUTHOR = (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15));
// insert(I_AUTHOR, I_TITLE, column_family, "I_AUTHOR", writeCon);
I_PUBLISHER = BenchmarkUtil.getRandomAString(14, 60);
// insert(I_PUBLISHER, I_TITLE, column_family, "I_PUBLISHER", writeCon);
boolean rad1 = rand.nextBoolean();
I_DESC = null;
if (rad1) {
I_DESC = BenchmarkUtil.getRandomAString(100, 500);
// insert(I_DESC, I_TITLE, column_family, "I_DESC", writeCon);
}
I_COST = rand.nextInt(100);
// insert(I_AUTHOR, I_TITLE, column_family, "I_AUTHOR", writeCon);
I_STOCK = (long) rand.nextInt(10);
// insert(I_STOCK, I_TITLE, column_family, "I_STOCK", writeCon);
int related_number = rand.nextInt(5);
for (int z = 0; z < related_number; z++) {
String title = titles.get(rand.nextInt(n));
if (!I_RELATED.contains(title)) {
I_RELATED.add(title);
}
}
if (related_number > 0) {
// insert(I_RELATED, I_TITLE, column_family, "I_RELATED", writeCon);
}
I_PAGE = rand.nextInt(500) + 10;
// insert(I_PAGE, I_TITLE, column_family, "I_PAGE", writeCon);
I_SUBJECT = subjects[rand.nextInt(subjects.length - 1)];
// insert(I_SUBJECT, I_TITLE, column_family, "I_SUBJECT", writeCon);
I_BACKING = backings[rand.nextInt(backings.length - 1)];
//insert(I_BACKING, I_TITLE, column_family, "I_BACKING", writeCon);
GregorianCalendar cal = BenchmarkUtil.getRandomDate(1930, 2000);
java.sql.Date pubDate = new java.sql.Date(cal.getTime().getTime());
String thumbnail = new String("img" + i % 100 + "/thumb_" + i + ".gif");
String image = new String("img" + i % 100 + "/image_" + i + ".gif");
double srp = (double) BenchmarkUtil.getRandomInt(100, 99999);
srp /= 100.0;
String isbn = BenchmarkUtil.getRandomAString(13);
java.sql.Date avail = new java.sql.Date(cal.getTime().getTime()); //Data when available
String dimensions = ((double) BenchmarkUtil.getRandomInt(1, 9999) / 100.0) + "x"
+ ((double) BenchmarkUtil.getRandomInt(1, 9999) / 100.0) + "x"
+ ((double) BenchmarkUtil.getRandomInt(1, 9999) / 100.0);
Item item = new Item(I_TITLE, I_TITLE, pubDate, I_PUBLISHER, I_DESC, I_SUBJECT, thumbnail, image, I_COST, I_STOCK, isbn, srp, I_RELATED, I_PAGE, avail, I_BACKING, dimensions, author);
databaseInsert("INSERT_Items", I_TITLE, column_family, item, partial_results);
partial_items.add(item.getI_id());
}
if (debug) {
System.out.println("Thread finished: " + num_items + " items inserted");
}
barrier.countDown();
client.closeClient();
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
public ArrayList<String> getData() {
return partial_items;
}
public ResultHandler returnResults() {
return partial_results;
}
}
/**
* ***********
* Addresses*
* ***********
*/
public void insertAddresses(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Addresses || populatores " + num_threads);
barrier = new CountDownLatch(threads);
AddressPopulator[] partial_addresses = new AddressPopulator[threads];
for (int i = 0; i < threads; i++) {
AddressPopulator populator = null;
if (i == 0) {
populator = new AddressPopulator(firstSection);
} else {
populator = new AddressPopulator(sections);
}
Thread t = new Thread(populator);
partial_addresses[i] = populator;
t.start();
}
barrier.await();
for (AddressPopulator populator : partial_addresses) {
ArrayList<String> ids = populator.getData();
for (String id : ids) {
addresses.add(id);
}
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
populator = null;
}
partial_addresses = null;
System.gc();
}
class AddressPopulator implements Runnable {
int num_addresses;
DataBaseCRUDInterface.CRUDclient client;
ArrayList<String> partial_adresses;
ResultHandler partial_results;
public AddressPopulator(int num_addresses) {
client = databaseClientFactory.getClient();
this.num_addresses = num_addresses;
partial_adresses = new ArrayList<String>();
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertAddress(num_addresses);
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
private void insertAddress(int n) {
System.out.println("Inserting Address: " + n);
String ADDR_STREET1, ADDR_STREET2, ADDR_CITY, ADDR_STATE;
String ADDR_ZIP;
String country_id;
for (int i = 0; i < n; i++) {
ADDR_STREET1 = "street" + BenchmarkUtil.getRandomAString(10, 30);
ADDR_STREET2 = "street" + BenchmarkUtil.getRandomAString(10, 30);
ADDR_CITY = BenchmarkUtil.getRandomAString(4, 30);
ADDR_STATE = BenchmarkUtil.getRandomAString(2, 20);
ADDR_ZIP = BenchmarkUtil.getRandomAString(5, 10);
country_id = countries.get(BenchmarkUtil.getRandomInt(0, NUM_COUNTRIES - 1));
String key = country_id + ADDR_STATE + ADDR_CITY + ADDR_ZIP + rand.nextInt(1000);
Address address = new Address(key, ADDR_STREET1, ADDR_STREET2, ADDR_CITY,
ADDR_STATE, ADDR_ZIP, country_id);
// insert(ADDR_STREET1, key, "Addresses", "ADDR_STREET1", writeConsistency);
// insert(ADDR_STREET2, key, "Addresses", "ADDR_STREET2", writeConsistency);
// insert(ADDR_STATE, key, "Addresses", "ADDR_STATE", writeConsistency);
// insert(ADDR_CITY, key, "Addresses", "ADDR_CITY", writeConsistency);
// insert(ADDR_ZIP, key, "Addresses", "ADDR_ZIP", writeConsistency);
// insert(country.getCo_id(), key, "Addresses", "ADDR_CO_ID", writeConsistency);
databaseInsert("INSERT_Addresses", key, "Addresses", address, partial_results);
partial_adresses.add(address.getAddr_id());
}
if (debug) {
System.out.println("Thread finished: " + num_addresses + " addresses.");
}
barrier.countDown();
client.closeClient();
}
public ArrayList<String> getData() {
return partial_adresses;
}
public ResultHandler returnResults() {
return partial_results;
}
}
/**
* ********
* Countries *
* *********
*/
private void insertCountries(int numCountries) {
DataBaseCRUDInterface.CRUDclient client;
client = databaseClientFactory.getClient();
String[] countriesNames = {
"United States", "United Kingdom", "Canada", "Germany", "France", "Japan",
"Netherlands", "Italy", "Switzerland", "Australia", "Algeria", "Argentina",
"Armenia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangla Desh",
"Barbados", "Belarus", "Belgium", "Bermuda", "Bolivia", "Botswana", "Brazil",
"Bulgaria", "Cayman Islands", "Chad", "Chile", "China", "Christmas Island",
"Colombia", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark",
"Dominican Republic", "Eastern Caribbean", "Ecuador", "Egypt", "El Salvador",
"Estonia", "Ethiopia", "Falkland Island", "Faroe Island", "Fiji", "Finland",
"Gabon", "Gibraltar", "Greece", "Guam", "Hong Kong", "Hungary", "Iceland",
"India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Jamaica", "Jordan",
"Kazakhstan", "Kuwait", "Lebanon", "Luxembourg", "Malaysia", "Mexico",
"Mauritius", "New Zealand", "Norway", "Pakistan", "Philippines", "Poland",
"Portugal", "Romania", "Russia", "Saudi Arabia", "Singapore", "Slovakia",
"South Africa", "South Korea", "Spain", "Sudan", "Sweden", "Taiwan",
"Thailand", "Trinidad", "Turkey", "Venezuela", "Zambia"
};
double[] exchanges = {
1, .625461, 1.46712, 1.86125, 6.24238, 121.907, 2.09715, 1842.64, 1.51645,
1.54208, 65.3851, 0.998, 540.92, 13.0949, 3977, 1, .3757, 48.65, 2, 248000,
38.3892, 1, 5.74, 4.7304, 1.71, 1846, .8282, 627.1999, 494.2, 8.278,
1.5391, 1677, 7.3044, 23, .543, 36.0127, 7.0707, 15.8, 2.7, 9600, 3.33771,
8.7, 14.9912, 7.7, .6255, 7.124, 1.9724, 5.65822, 627.1999, .6255, 309.214,
1, 7.75473, 237.23, 74.147, 42.75, 8100, 3000, .3083, .749481, 4.12, 37.4,
0.708, 150, .3062, 1502, 38.3892, 3.8, 9.6287, 25.245, 1.87539, 7.83101, 52,
37.8501, 3.9525, 190.788, 15180.2, 24.43, 3.7501, 1.72929, 43.9642, 6.25845,
1190.15, 158.34, 5.282, 8.54477, 32.77, 37.1414, 6.1764, 401500, 596, 2447.7
};
String[] currencies = {
"Dollars", "Pounds", "Dollars", "Deutsche Marks", "Francs", "Yen", "Guilders",
"Lira", "Francs", "Dollars", "Dinars", "Pesos", "Dram", "Schillings", "Manat",
"Dollars", "Dinar", "Taka", "Dollars", "Rouble", "Francs", "Dollars",
"Boliviano", "Pula", "Real", "Lev", "Dollars", "Franc", "Pesos", "Yuan Renmimbi",
"Dollars", "Pesos", "Kuna", "Pesos", "Pounds", "Koruna", "Kroner", "Pesos",
"Dollars", "Sucre", "Pounds", "Colon", "Kroon", "Birr", "Pound", "Krone", "Dollars",
"Markka", "Franc", "Pound", "Drachmas", "Dollars", "Dollars", "Forint", "Krona",
"Rupees", "Rupiah", "Rial", "Dinar", "Punt", "Shekels", "Dollars", "Dinar", "Tenge",
"Dinar", "Pounds", "Francs", "Ringgit", "Pesos", "Rupees", "Dollars", "Kroner",
"Rupees", "Pesos", "Zloty", "Escudo", "Leu", "Rubles", "Riyal", "Dollars", "Koruna",
"Rand", "Won", "Pesetas", "Dinar", "Krona", "Dollars", "Baht", "Dollars", "Lira",
"Bolivar", "Kwacha"
};
if (numCountries > countriesNames.length) {
numCountries = countriesNames.length - 1;
}
System.out.println(">>Inserting " + numCountries + " countries || populatores " + num_threads);
for (int i = 0; i < numCountries; i++) {
//Country name = key
//insert(exchanges[i], countriesNames[i], "Countries", "CO_EXCHANGE", writeConsitency);
//insert(currencies[i], countriesNames[i], "Countries", "CO_CURRENCY", writeConsitency);
Country country = new Country(countriesNames[i], countriesNames[i], exchanges[i], currencies[i]);
databaseInsert(client, "INSERT_Countries", countriesNames[i], "Countries", country, results);
this.countries.add(country.getCo_id());
}
if (debug) {
System.out.println("Countries:" + countriesNames.length + " inserted");
}
}
/**
* ****************
* Orders and XACTS *
* ******************
*/
public void insertOrder_and_CC_XACTS(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Orders .. || populatores " + num_threads);
barrier = new CountDownLatch(threads);
int lastkey = 1;
Order_and_XACTSPopulator[] partial_orders = new Order_and_XACTSPopulator[threads];
for (int i = 0; i < threads; i++) {
Order_and_XACTSPopulator populator = null;
if (i == 0) {
populator = new Order_and_XACTSPopulator(lastkey, firstSection);
lastkey = lastkey + firstSection;
} else {
populator = new Order_and_XACTSPopulator(lastkey, sections);
lastkey = lastkey + sections;
}
partial_orders[i] = populator;
Thread t = new Thread(populator);
t.start();
}
barrier.await();
for (Order_and_XACTSPopulator populator : partial_orders) {
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
populator = null;
}
System.gc();
}
class Order_and_XACTSPopulator implements Runnable {
int num_orders;
int begin_key;
DataBaseCRUDInterface.CRUDclient client;
ResultHandler partial_results;
public Order_and_XACTSPopulator(int begin_key, int num_orders) {
client = databaseClientFactory.getClient();
this.num_orders = num_orders;
this.begin_key = begin_key;
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertOrder_and_CC_XACTS(begin_key, num_orders);
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
public void insertOrder_and_CC_XACTS(int begin_key, int number_keys) {
System.out.println("Inserting Orders: " + number_keys);
String column_family = "Orders";
String subcolumn_family = "OrderLines";
String[] credit_cards = {"VISA", "MASTERCARD", "DISCOVER", "AMEX", "DINERS"};
String[] ship_types = {"AIR", "UPS", "FEDEX", "SHIP", "COURIER", "MAIL"};
String[] status_types = {"PROCESSING", "SHIPPED", "PENDING", "DENIED"};
long O_ID = begin_key;
// ColumnPath path = new ColumnPath(column_family);
// path.setSuper_column("ids".getBytes());
for (int z = 0; z < number_keys; z++) {
column_family = "Orders";
subcolumn_family = "OrderLines";
String O_C_ID;
java.sql.Timestamp O_DATE;
float O_SUB_TOTAL;
float O_TAX;
float O_TOTAL;
java.sql.Timestamp O_SHIP_DATE;
String O_SHIP_TYPE;
String O_SHIP_ADDR;
String O_STATUS;
String costumer_id = costumers.get(rand.nextInt(costumers.size()));
O_C_ID = costumer_id;
GregorianCalendar call = new GregorianCalendar();
O_DATE = new java.sql.Timestamp(call.getTime().getTime());
//insertInSuperColumn(O_DATE, O_C_ID, column_family, O_ID + "", "O_DATE", write_con);
O_SUB_TOTAL = rand.nextFloat() * 100 * 4;
//insertInSuperColumn(O_SUB_TOTAL, O_C_ID, column_family, O_ID + "", "O_SUB_TOTAL", write_con);
O_TAX = O_SUB_TOTAL * 0.21f;
//insertInSuperColumn(O_TAX, O_C_ID, column_family, O_ID + "", "O_TAX", write_con);
O_TOTAL = O_SUB_TOTAL + O_TAX;
//insertInSuperColumn(O_TOTAL, O_C_ID, column_family, O_ID + "", "O_TOTAL", write_con);
call.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(0, 7));
O_SHIP_DATE = new java.sql.Timestamp(call.getTime().getTime());
//insertInSuperColumn(O_SHIP_DATE, O_C_ID, column_family, O_ID + "", "O_SHIP_DATE", write_con);
O_SHIP_TYPE = ship_types[rand.nextInt(ship_types.length)];
//insertInSuperColumn(O_SHIP_TYPE, O_C_ID, column_family, O_ID + "", "O_SHIP_TYPE", write_con);
O_STATUS = status_types[rand.nextInt(status_types.length)];
//insertInSuperColumn(O_STATUS, O_C_ID, column_family, O_ID + "", "O_STATUS", write_con);
String billAddress = addresses.get(BenchmarkUtil.getRandomInt(0, NUM_ADDRESSES - 1));
// insertInSuperColumn(billAddress.getAddr_id(), O_C_ID, column_family, O_ID + "", "O_BILL_ADDR_ID", write_con);
O_SHIP_ADDR = addresses.get(BenchmarkUtil.getRandomInt(0, NUM_ADDRESSES - 1));
// insertInSuperColumn(O_SHIP_ADDR.getAddr_id(), O_C_ID, column_family, O_ID + "", "O_SHIP_ADDR_ID", write_con);
Orders order = new Orders(O_ID, O_C_ID, O_DATE, O_SUB_TOTAL, O_TAX, O_TOTAL, O_SHIP_TYPE, O_SHIP_DATE, O_STATUS, billAddress, O_SHIP_ADDR);
databaseInsert("INSERT Orders", O_C_ID, column_family, order, partial_results);
//orders.add(order);
int number_of_items = rand.nextInt(4) + 1;
for (int i = 0; i < number_of_items; i++) {
/**
* OL_ID
* OL_O_ID
* OL_I_ID
* OL_QTY
* OL_DISCOUNT
* OL_COMMENT
*/
String OL_ID;
String OL_I_ID;
int OL_QTY;
float OL_DISCOUNT;
String OL_COMMENT;
OL_ID = O_ID + "N" + i;
OL_I_ID = items.get(rand.nextInt(items.size()));
//insertInSuperColumn(OL_I_ID, O_ID + "", subcolumn_family, OL_ID, "OL_I_ID", write_con);
OL_QTY = rand.nextInt(4) + 1;
//insertInSuperColumn(OL_QTY, O_ID + "", subcolumn_family, OL_ID, "OL_QTY", write_con);
OL_DISCOUNT = rand.nextBoolean() ? 0 : rand.nextFloat() * 10;
//insertInSuperColumn(OL_DISCOUNT, O_ID + "", subcolumn_family, OL_ID, "OL_DISCOUNT", write_con);
OL_COMMENT = null;
if (rand.nextBoolean()) {
OL_COMMENT = BenchmarkUtil.getRandomAString(20, 100);
//insertInSuperColumn(OL_COMMENT, O_ID + "", subcolumn_family, OL_ID, "OL_COMMENT", write_con);
}
OrderLine orderline = new OrderLine(OL_ID, order.getO_ID(), OL_I_ID, OL_QTY, OL_DISCOUNT, OL_COMMENT);
databaseInsert("INSERT Orders Lines", O_ID + "", subcolumn_family, orderline, partial_results);
//orderLines.add(orderline);
}
String CX_TYPE;
int CX_NUM;
String CX_NAME;
java.sql.Date CX_EXPIRY;
double CX_XACT_AMT; //O_TOTAL
int CX_CO_ID; //Order.getID;
column_family = "CC_XACTS";
CX_NUM = BenchmarkUtil.getRandomNString(16);
String key = O_ID + "";
CX_TYPE = credit_cards[BenchmarkUtil.getRandomInt(0, credit_cards.length - 1)];
//insert(CX_TYPE, key, column_family, "CX_TYPE", write_con);
//insert(CX_NUM, key, column_family, "CX_NUM", write_con);
CX_NAME = BenchmarkUtil.getRandomAString(14, 30);
//insert(CX_NAME, key, column_family, "CX_NAME", write_con);
GregorianCalendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(10, 730));
CX_EXPIRY = new java.sql.Date(cal.getTime().getTime());
//insert(CX_EXPIRY, key, column_family, "CX_EXPIRY", write_con);
//DATE
// insert(O_SHIP_DATE, key, column_family, "CX_XACT_DATE", write_con);
//AMOUNT
// insert(O_TOTAL, key, column_family, "CX_XACT_AMT", write_con);
//CX_AUTH_ID = getRandomAString(5,15);// unused
String country_id = countries.get(BenchmarkUtil.getRandomInt(0, countries.size() - 1));
// insert(country.getCo_id(), key, column_family, "CX_CO_ID", write_con);
CCXact ccXact = new CCXact(CX_TYPE, CX_NUM, CX_NAME, CX_EXPIRY,/* CX_AUTH_ID,*/ O_TOTAL,
O_SHIP_DATE, /* 1 + _counter, */ order.getO_ID(), country_id);
databaseInsert("INSERT_CCXact", key, column_family, order, partial_results);
O_ID++;
}
if (debug) {
System.out.println("Thread finished: " + number_keys + " orders and xact inserted. key:" + begin_key);
}
barrier.countDown();
client.closeClient();
}
public ResultHandler returnResults() {
return partial_results;
}
}
/************************************************************************/
/************************************************************************/
/**
* ********************************************************************
*/
// public void ShowValues(String column_family) {
//
// System.out.println("Show Values for Column family : " + column_family);
// try {
// SlicePredicate predicate = new SlicePredicate();
// SliceRange range = new SliceRange("".getBytes(), "".getBytes(), false, 300);
//
// // ColumnParent parent = new ColumnParent(column_family, null);
// ColumnParent parent = new ColumnParent(column_family);
// predicate.setSlice_range(range);
//
// //List<String> keys = client..get_key_range(Keyspace, column_family, "", "", 300, ConsistencyLevel.ONE);
// List<KeySlice> keys = client.get_range_slice(Keyspace, parent, predicate, "", "", 300, ConsistencyLevel.ONE);
// System.out.println("Keys size: " + keys.size());
// for (KeySlice ks : keys) {
// System.out.println("For key: " + ks.key);
// List<ColumnOrSuperColumn> line = ks.columns;
// StringBuilder builder = new StringBuilder();
// for (ColumnOrSuperColumn column : line) {
//
// Column c = column.getColumn();
//
// builder.append(" Name: " + new String(c.getName()) + " Value: " + new String(c.getValue()) + "||");
// }
// System.out.println("Key on column: " + ks.key + "with values: " + builder.toString());
//
// }
//
//
//// Map<String, List<ColumnOrSuperColumn>> results = client.multiget_slice(Keyspace, keys, parent, predicate, ConsistencyLevel.ONE);
//// for (String key : results.keySet()) {
//// List<ColumnOrSuperColumn> line = results.get(key);
//// StringBuilder builder = new StringBuilder();
//// for (ColumnOrSuperColumn column : line) {
////
//// Column c = column.getColumn();
////
//// builder.append(" Name: " + new String(c.getName()) + " Value: " + new String(c.getValue()) + "||");
//// }
//// System.out.println("Key on column: " + key + "with values: " + builder.toString());
//// }
// } catch (TimedOutException ex) {
// Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
// } catch (InvalidRequestException ex) {
// Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
// } catch (UnavailableException ex) {
// Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
// } catch (TException ex) {
// Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
public static boolean loadDescriptor() {
try {
FileInputStream in = null;
String jsonString_r = "";
try {
in = new FileInputStream("CassandraDB.xml");
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String s = "";
StringBuilder sb = new StringBuilder();
while (s != null) {
sb.append(s);
s = bin.readLine();
}
jsonString_r = sb.toString().replace("\n", "");
bin.close();
in.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CassandraInterface.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CassandraInterface.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
Logger.getLogger(CassandraInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
Map<String, Map<String, String>> map = JsonUtil.getMapMapFromJsonString(jsonString_r);
if (!map.containsKey("BenchmarkInfo")) {
System.out.println("ERROR: NO INFORMATION ABOUT THE DATA ENGINE FOUND, ABORTING");
return false;
} else {
Map<String, String> databaseInfo = map.get("BenchmarkInfo");
String databaseClass = databaseInfo.get("DataEngineInterface");
System.out.println("CHOSEN DATABASE ENGINE: " + databaseClass);
databaseClientFactory = (DataBaseCRUDInterface) Class.forName(databaseClass).getConstructor().newInstance();
if (!map.containsKey("LoadParameters")) {
System.out.println("WARNING: NO LOAD DEFINITIONS FOUND, NO DELAYS WILL BE USED , ONE THREAD USED");
} else {
Map<String, String> loadInfo = map.get("LoadParameters");
String do_delays = loadInfo.get("delay_inserts");
delay_inserts = Boolean.valueOf(do_delays);
String delay_time_info = loadInfo.get("delay_time");
delay_time = Integer.valueOf(delay_time_info);
String thread_number_info = loadInfo.get("thread_number");
num_threads = Integer.parseInt(thread_number_info);
}
return true;
}
} catch (NoSuchMethodException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("ERROR: THERE IS SOME PROBLEM WITH THE DEFINITIONS FILE");
return false;
}
public void info() {
// Namegenerator ng = new Namegenerator("src/JaNaG_Source/languages.txt", "src/JaNaG_Source/semantics.txt");
// //String[] ns = ng.getPatterns();
// String[] ns = ng.getGenders("Orkisch");
// for (String ss : ns) {
// System.out.println(ss);
//
// }
/**
Patterns:
Pseudo-Altdeutsch
Menschlich Fantasy (Mann , Frau)
Götternamen
Dämonen
Griechisch
Spanisch
Italienisch
Irisch
Französisch
Polnisch
Hebräisch (Mann , Frau)
Orkisch
US-Zensus//english
*
*/
//
// try {
// Map<String, Map<String, String>> info = client.describe_keyspace("Tpcw");
// System.out.println("Info =" + info.toString());
//
// } catch (NotFoundException ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
// } catch (TException ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
/**
try {
ColumnOrSuperColumn scolumn = client.get(Keyspace, "all", path, write_con);
SuperColumn super_column = scolumn.getSuper_column();
Column column = super_column.columns.get(0);
O_ID = (Long) BenchmarkUtil.toObject(column.value) + 1;
insertInSuperColumn(O_ID, "all", column_family, "ids", "LAST_ID", write_con);
} catch (TimedOutException ex) {
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidRequestException ex) {
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
O_ID = 0;
} catch (NotFoundException ex) {
O_ID = 0;
insertInSuperColumn(O_ID, "all", column_family, "ids", "LAST_ID", write_con);
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
}
*
*
*
*
try {
ColumnOrSuperColumn scolumn = client.get(Keyspace, "all", path, write_con);
SuperColumn super_column = scolumn.getSuper_column();
Column column = super_column.columns.get(0);
O_ID = (Long) BenchmarkUtil.toObject(column.value);
O_ID++;
//new Long(new String(column.value)) + 1;
insertInSuperColumn(O_ID, "all", "Orders", "ids", "LAST_ID", write_con);
**/
| benchmarks/TpcwBenchmark/Populator.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package benchmarks.TpcwBenchmark;
//import JaNaG_Source.de.beimax.janag.Namegenerator;
import benchmarks.helpers.BenchmarkUtil;
import benchmarks.interfaces.DataBaseCRUDInterface;
import java.io.FileNotFoundException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import benchmarks.DatabaseEngineInterfaces.CassandraInterface;
import benchmarks.TpcwBenchmark.testEntities.Address;
import benchmarks.TpcwBenchmark.testEntities.Author;
import benchmarks.TpcwBenchmark.testEntities.CCXact;
import benchmarks.TpcwBenchmark.testEntities.Costumer;
import benchmarks.TpcwBenchmark.testEntities.Country;
import benchmarks.TpcwBenchmark.testEntities.Item;
import benchmarks.TpcwBenchmark.testEntities.OrderLine;
import benchmarks.TpcwBenchmark.testEntities.Orders;
import benchmarks.helpers.JsonUtil;
import benchmarks.dataStatistics.ResultHandler;
import benchmarks.interfaces.Entity;
import benchmarks.interfaces.BenchmarkPopulator;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
/**
* @author pedro
*/
public class Populator implements BenchmarkPopulator {
/**
* Time measurements
*/
private static boolean delay_inserts = false;
private static int delay_time = 100;
private static Random rand = new Random();
private int rounds = 500;
private ResultHandler results;
String result_path;
//ATTENTION: The NUM_EBS and NUM_ITEMS variables are the only variables
//that should be modified in order to rescale the DB.
private static /* final */ int NUM_EBS = 10;
private static /* final */ int NUM_ITEMS = 1000;
private static /* final */ int NUM_CUSTOMERS = NUM_EBS * 2880;
private static /* final */ int NUM_ADDRESSES = 2 * NUM_CUSTOMERS;
private static /* final */ int NUM_AUTHORS = (int) (.25 * NUM_ITEMS);
private static /* final */ int NUM_ORDERS = (int) (.9 * NUM_CUSTOMERS);
private static /* final */ int NUM_COUNTRIES = 92; // this is constant. Never changes!
// static Client client;
private static DataBaseCRUDInterface databaseClientFactory;
ArrayList<String> authors = new ArrayList<String>();
ArrayList<String> addresses = new ArrayList<String>();
ArrayList<String> countries = new ArrayList<String>();
ArrayList<String> costumers = new ArrayList<String>();
ArrayList<String> items = new ArrayList<String>();
// CopyOnWriteArrayList<Orders> orders = new CopyOnWriteArrayList<Orders>();
// CopyOnWriteArrayList<OrderLine> orderLines = new CopyOnWriteArrayList<OrderLine>();
boolean debug = true;
private static int num_threads = 1;
boolean error = false;
private CountDownLatch barrier;
//databaseClient,number_threads_populator,benchmarkPopulatorInfo
public Populator(DataBaseCRUDInterface databaseCrudClient, int clients, Map<String, String> info) {
databaseClientFactory = databaseCrudClient;
num_threads = clients;
String do_delays = info.get("delay_inserts");
delay_inserts = Boolean.valueOf(do_delays.trim());
String delay_time_info = info.get("delay_time");
delay_time = Integer.valueOf(delay_time_info.trim());
String rounds_info = info.get("rounds");
if (rounds_info != null) {
rounds = Integer.valueOf(rounds_info.trim());
} else {
System.out.println("ROUND NUMBER NOT FOUND: 500 DEFAULT");
}
this.results = new ResultHandler("TPCW_POPULATOR", rounds);
result_path = info.get("result_path");
String ebs = info.get("tpcw_numEBS");
if (ebs != null) {
NUM_EBS = Integer.valueOf(ebs.trim());
} else {
System.out.println("SCALE FACTOR (EBS) NOT DEFINED. SET TO: " + NUM_EBS);
}
String items = info.get("tpcw_numItems");
if (items != null) {
NUM_ITEMS = Integer.valueOf(items.trim());
} else {
System.out.println("NUMBER OF ITEMS NOT DEFINED. SET TO: " + NUM_ITEMS);
}
NUM_CUSTOMERS = NUM_EBS * 2880;
NUM_ADDRESSES = 2 * NUM_CUSTOMERS;
NUM_AUTHORS = (int) (.25 * NUM_ITEMS);
NUM_ORDERS = (int) (.9 * NUM_CUSTOMERS);
}
// /**
// * @param args the command line arguments
// */
// public static void main(String[] args) {
//
// ResultHandler resultHandler = new ResultHandler("TPCW benchamrk", 400);
// // BenchmarkPopulator m = new Populator(resultHandler, 10);
// m.populate();
//
// }
public void databaseInsert(DataBaseCRUDInterface.CRUDclient client, String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
public boolean populate() {
DataBaseCRUDInterface.CRUDclient client = databaseClientFactory.getClient();
client.truncate("ShoppingCart");
client.closeClient();
if (error) {
return false;
} else {
try {
insertCountries(NUM_COUNTRIES);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertAddresses(NUM_ADDRESSES);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertCostumers(NUM_CUSTOMERS);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertAuthors(NUM_AUTHORS);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertItems(NUM_ITEMS);
if (delay_inserts) {
Thread.sleep(delay_time);
}
insertOrder_and_CC_XACTS(NUM_ORDERS);
System.out.println("***Finished***");
} catch (InterruptedException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (Exception ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
results.listDataToSOutput();
results.listDatatoFiles(result_path, "", true);
results.cleanResults();
return true;
}
}
public void cleanDB() {
removeALL();
}
public Map<String, Object> getUseFullData() {
TreeMap<String, Object> data = new TreeMap<String, Object>();
data.put("ITEMS", items);
data.put("COSTUMERS", costumers);
return data;
}
public void removeALL() {
DataBaseCRUDInterface.CRUDclient client = databaseClientFactory.getClient();
client.truncate("Costumer");
client.truncate("Items");
client.truncate("Orders");
client.truncate("OrderLines");
client.truncate("CC_XACTS");
client.truncate("Author");
client.truncate("Countries");
client.truncate("Addresses");
}
/************************************************************************/
/************************************************************************/
/************************************************************************/
/**
* ************
* Authors*
* **************
*/
public void insertAuthors(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Authors || populatores " + num_threads);
barrier = new CountDownLatch(threads);
AuthorPopulator[] partial_authors = new AuthorPopulator[threads];
for (int i = 0; i < threads; i++) {
AuthorPopulator populator = null;
if (i == 0) {
populator = new AuthorPopulator(firstSection);
} else {
populator = new AuthorPopulator(sections);
}
partial_authors[i] = populator;
Thread t = new Thread(populator);
t.start();
}
barrier.await();
for (AuthorPopulator populator : partial_authors) {
ArrayList<String> ids = populator.getData();
for (String id : ids) {
authors.add(id);
}
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
}
partial_authors = null;
System.gc();
}
class AuthorPopulator implements Runnable {
int num_authors;
DataBaseCRUDInterface.CRUDclient client;
ArrayList<String> partial_authors;
ResultHandler partial_results;
public AuthorPopulator(int num_authors) {
client = databaseClientFactory.getClient();
this.num_authors = num_authors;
partial_authors = new ArrayList<String>();
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertAuthors(num_authors);
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
public void insertAuthors(int n) {
System.out.println("Inserting Authors: " + n);
for (int i = 0; i < n; i++) {
GregorianCalendar cal = BenchmarkUtil.getRandomDate(1800, 1990);
String[] names = (BenchmarkUtil.getRandomAString(3, 20) + " " + BenchmarkUtil.getRandomAString(2, 20)).split(" ");
String[] Mnames = ("d " + BenchmarkUtil.getRandomAString(2, 20)).split(" ");
String first_name = names[0];
String last_name = names[1];
String middle_name = Mnames[1];
java.sql.Date dob = new java.sql.Date(cal.getTime().getTime());
String bio = BenchmarkUtil.getRandomAString(125, 500);
String key = first_name + middle_name + last_name + rand.nextInt(1000);
// insert(first_name, key, "Author", "A_FNAME", writeConsistency);
// insert(last_name, key, "Author", "A_LNAME", writeConsistency);
// insert(middle_name, key, "Author", "A_MNAME", writeConsistency);
// insert(dob, key, "Author", "A_DOB", writeConsistency);
// insert(bio, key, "Author", "A_BIO", writeConsistency);
Author a = new Author(key, first_name, last_name, middle_name, dob, bio);
databaseInsert("INSERT_Authors", key, "Author", a, partial_results);
partial_authors.add(a.getA_id());
}
if (debug) {
System.out.println("Thread finished: " + num_authors + " authors inserted");
}
barrier.countDown();
client.closeClient();
}
public ArrayList<String> getData() {
return partial_authors;
}
public ResultHandler returnResults() {
return partial_results;
}
}
/**
* ************
* Costumers*
* **************
*/
public void insertCostumers(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Costumers || populatores " + num_threads);
barrier = new CountDownLatch(threads);
CostumerPopulator[] partial_costumers = new CostumerPopulator[threads];
for (int i = 0; i < threads; i++) {
CostumerPopulator populator = null;
if (i == 0) {
populator = new CostumerPopulator(firstSection);
} else {
populator = new CostumerPopulator(sections);
}
partial_costumers[i] = populator;
Thread t = new Thread(populator);
t.start();
}
barrier.await();
for (CostumerPopulator populator : partial_costumers) {
ArrayList<String> ids = populator.getData();
for (String id : ids) {
costumers.add(id);
}
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
}
partial_costumers = null;
System.gc();
}
class CostumerPopulator implements Runnable {
DataBaseCRUDInterface.CRUDclient client;
int num_costumers;
ArrayList<String> partial_costumers;
ResultHandler partial_results;
public CostumerPopulator(int num_costumers) {
client = databaseClientFactory.getClient();
this.num_costumers = num_costumers;
partial_costumers = new ArrayList<String>();
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertCostumers(num_costumers);
}
public void insertCostumers(int n) {
System.out.println("Inserting Costumers: " + n);
for (int i = 0; i < n; i++) {
String name = (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15));
String[] names = name.split(" ");
Random r = new Random();
int random_int = r.nextInt(1000);
String key = name + "_" + random_int;
String pass = names[0].charAt(0) + names[1].charAt(0) + "" + random_int;
// insert(pass, key, "Costumer", "C_PASSWD", writeCon);
String first_name = names[0];
// insert(first_name, key, "Costumer", "C_FNAME", writeCon);
String last_name = names[1];
// insert(last_name, key, "Costumer", "C_LNAME", writeCon);
int phone = r.nextInt(999999999 - 100000000) + 100000000;
// insert(phone, key, "Costumer", "C_PHONE", writeCon);
String email = key + "@" + BenchmarkUtil.getRandomAString(2, 9) + ".com";
// insert(email, key, "Costumer", "C_EMAIL", writeCon);
double discount = r.nextDouble();
// insert(discount, key, "Costumer", "C_DISCOUNT", writeCon);
String adress = "Street: " + (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15)) + " number: " + r.nextInt(500);
// insert(adress, key, "Costumer", "C_PHONE", writeCon);
double C_BALANCE = 0.00;
// insert(C_BALANCE, key, "Costumer", "C_BALANCE", writeCon);
double C_YTD_PMT = (double) BenchmarkUtil.getRandomInt(0, 99999) / 100.0;
// insert(C_YTD_PMT, key, "Costumer", "C_YTD_PMT", writeCon);
GregorianCalendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, -1 * BenchmarkUtil.getRandomInt(1, 730));
java.sql.Date C_SINCE = new java.sql.Date(cal.getTime().getTime());
// insert(C_SINCE, key, "Costumer", "C_SINCE ", writeCon);
cal.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(0, 60));
if (cal.after(new GregorianCalendar())) {
cal = new GregorianCalendar();
}
java.sql.Date C_LAST_LOGIN = new java.sql.Date(cal.getTime().getTime());
//insert(C_LAST_LOGIN, key, "Costumer", "C_LAST_LOGIN", writeCon);
java.sql.Timestamp C_LOGIN = new java.sql.Timestamp(System.currentTimeMillis());
//insert(C_LOGIN, key, "Costumer", "C_LOGIN", writeCon);
cal = new GregorianCalendar();
cal.add(Calendar.HOUR, 2);
java.sql.Timestamp C_EXPIRATION = new java.sql.Timestamp(cal.getTime().getTime());
//insert(C_EXPIRATION, key, "Costumer", "C_EXPIRATION", writeCon);
cal = BenchmarkUtil.getRandomDate(1880, 2000);
java.sql.Date C_BIRTHDATE = new java.sql.Date(cal.getTime().getTime());
//insert(C_BIRTHDATE, key, "Costumer", "C_BIRTHDATE", writeCon);
String C_DATA = BenchmarkUtil.getRandomAString(100, 500);
//insert(C_DATA, key, "Costumer", "C_DATA", writeCon);
String address_id = addresses.get(rand.nextInt(addresses.size()));
//insert(address.getAddr_id(), key, "Costumer", "C_ADDR_ID", writeCon);
Costumer c = new Costumer(key, key, pass, last_name, first_name, phone, email, C_SINCE, C_LAST_LOGIN, C_LOGIN, C_EXPIRATION, C_BALANCE, C_YTD_PMT, C_BIRTHDATE, C_DATA, discount, address_id);
databaseInsert("INSERT_Costumers", key, "Costumer", c, partial_results);
partial_costumers.add(c.getC_id());
}
if (debug) {
System.out.println("Thread finished: " + num_costumers + " costumers inserted");
}
barrier.countDown();
client.closeClient();
}
public ArrayList<String> getData() {
return partial_costumers;
}
public ResultHandler returnResults() {
return partial_results;
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
}
/**
* ************
* Items*
* **************
*/
public void insertItems(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Items || populatores " + num_threads);
barrier = new CountDownLatch(threads);
ItemPopulator[] partial_items = new ItemPopulator[threads];
for (int i = 0; i < threads; i++) {
ItemPopulator populator = null;
if (i == 0) {
populator = new ItemPopulator(firstSection);
} else {
populator = new ItemPopulator(sections);
}
partial_items[i] = populator;
Thread t = new Thread(populator);
t.start();
}
barrier.await();
for (ItemPopulator populator : partial_items) {
ArrayList<String> ids = populator.getData();
for (String id : ids) {
items.add(id);
}
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
}
partial_items = null;
System.gc();
}
class ItemPopulator implements Runnable {
DataBaseCRUDInterface.CRUDclient client;
int num_items;
ArrayList<String> partial_items;
ResultHandler partial_results;
public ItemPopulator(int num_items) {
client = databaseClientFactory.getClient();
this.num_items = num_items;
partial_items = new ArrayList<String>();
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertItems(num_items);
}
public void insertItems(int n) {
String[] subjects = {"ARTS", "BIOGRAPHIES", "BUSINESS", "CHILDREN",
"COMPUTERS", "COOKING", "HEALTH", "HISTORY",
"HOME", "HUMOR", "LITERATURE", "MYSTERY",
"NON-FICTION", "PARENTING", "POLITICS",
"REFERENCE", "RELIGION", "ROMANCE",
"SELF-HELP", "SCIENCE-NATURE", "SCIENCE-FICTION",
"SPORTS", "YOUTH", "TRAVEL"};
String[] backings = {"HARDBACK", "PAPERBACK", "USED", "AUDIO",
"LIMITED-EDITION"};
String column_family = "Items";
System.out.println("Inserting Items: " + n);
ArrayList<String> titles = new ArrayList<String>();
for (int i = 0; i < n; i++) {
String f_name = BenchmarkUtil.getRandomAString(14, 60);
int num = rand.nextInt(1000);
titles.add(f_name + " " + num);
}
for (int i = 0; i < n; i++) {
String I_TITLE; //ID
String I_AUTHOR;
String I_PUBLISHER;
String I_DESC;
String I_SUBJECT;
float I_COST;
long I_STOCK;
List<String> I_RELATED = new ArrayList<String>();
int I_PAGE;
String I_BACKING;
I_TITLE = titles.get(i);
int author_pos = rand.nextInt(authors.size());
String author = authors.get(author_pos);
I_AUTHOR = (BenchmarkUtil.getRandomAString(8, 15) + " " + BenchmarkUtil.getRandomAString(8, 15));
// insert(I_AUTHOR, I_TITLE, column_family, "I_AUTHOR", writeCon);
I_PUBLISHER = BenchmarkUtil.getRandomAString(14, 60);
// insert(I_PUBLISHER, I_TITLE, column_family, "I_PUBLISHER", writeCon);
boolean rad1 = rand.nextBoolean();
I_DESC = null;
if (rad1) {
I_DESC = BenchmarkUtil.getRandomAString(100, 500);
// insert(I_DESC, I_TITLE, column_family, "I_DESC", writeCon);
}
I_COST = rand.nextInt(100);
// insert(I_AUTHOR, I_TITLE, column_family, "I_AUTHOR", writeCon);
I_STOCK = (long) rand.nextInt(10);
// insert(I_STOCK, I_TITLE, column_family, "I_STOCK", writeCon);
int related_number = rand.nextInt(5);
for (int z = 0; z < related_number; z++) {
String title = titles.get(rand.nextInt(n));
if (!I_RELATED.contains(title)) {
I_RELATED.add(title);
}
}
if (related_number > 0) {
// insert(I_RELATED, I_TITLE, column_family, "I_RELATED", writeCon);
}
I_PAGE = rand.nextInt(500) + 10;
// insert(I_PAGE, I_TITLE, column_family, "I_PAGE", writeCon);
I_SUBJECT = subjects[rand.nextInt(subjects.length - 1)];
// insert(I_SUBJECT, I_TITLE, column_family, "I_SUBJECT", writeCon);
I_BACKING = backings[rand.nextInt(backings.length - 1)];
//insert(I_BACKING, I_TITLE, column_family, "I_BACKING", writeCon);
GregorianCalendar cal = BenchmarkUtil.getRandomDate(1930, 2000);
java.sql.Date pubDate = new java.sql.Date(cal.getTime().getTime());
String thumbnail = new String("img" + i % 100 + "/thumb_" + i + ".gif");
String image = new String("img" + i % 100 + "/image_" + i + ".gif");
double srp = (double) BenchmarkUtil.getRandomInt(100, 99999);
srp /= 100.0;
String isbn = BenchmarkUtil.getRandomAString(13);
java.sql.Date avail = new java.sql.Date(cal.getTime().getTime()); //Data when available
String dimensions = ((double) BenchmarkUtil.getRandomInt(1, 9999) / 100.0) + "x"
+ ((double) BenchmarkUtil.getRandomInt(1, 9999) / 100.0) + "x"
+ ((double) BenchmarkUtil.getRandomInt(1, 9999) / 100.0);
Item item = new Item(I_TITLE, I_TITLE, pubDate, I_PUBLISHER, I_DESC, I_SUBJECT, thumbnail, image, I_COST, I_STOCK, isbn, srp, I_RELATED, I_PAGE, avail, I_BACKING, dimensions, author);
databaseInsert("INSERT_Items", I_TITLE, column_family, item, partial_results);
partial_items.add(item.getI_id());
}
if (debug) {
System.out.println("Thread finished: " + num_items + " items inserted");
}
barrier.countDown();
client.closeClient();
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
public ArrayList<String> getData() {
return partial_items;
}
public ResultHandler returnResults() {
return partial_results;
}
}
/**
* ***********
* Addresses*
* ***********
*/
public void insertAddresses(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Addresses || populatores " + num_threads);
barrier = new CountDownLatch(threads);
AddressPopulator[] partial_addresses = new AddressPopulator[threads];
for (int i = 0; i < threads; i++) {
AddressPopulator populator = null;
if (i == 0) {
populator = new AddressPopulator(firstSection);
} else {
populator = new AddressPopulator(sections);
}
Thread t = new Thread(populator);
partial_addresses[i] = populator;
t.start();
}
barrier.await();
for (AddressPopulator populator : partial_addresses) {
ArrayList<String> ids = populator.getData();
for (String id : ids) {
addresses.add(id);
}
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
populator = null;
}
partial_addresses = null;
System.gc();
}
class AddressPopulator implements Runnable {
int num_addresses;
DataBaseCRUDInterface.CRUDclient client;
ArrayList<String> partial_adresses;
ResultHandler partial_results;
public AddressPopulator(int num_addresses) {
client = databaseClientFactory.getClient();
this.num_addresses = num_addresses;
partial_adresses = new ArrayList<String>();
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertAddress(num_addresses);
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
private void insertAddress(int n) {
System.out.println("Inserting Address: " + n);
String ADDR_STREET1, ADDR_STREET2, ADDR_CITY, ADDR_STATE;
String ADDR_ZIP;
String country_id;
for (int i = 0; i < n; i++) {
ADDR_STREET1 = "street" + BenchmarkUtil.getRandomAString(10, 30);
ADDR_STREET2 = "street" + BenchmarkUtil.getRandomAString(10, 30);
ADDR_CITY = BenchmarkUtil.getRandomAString(4, 30);
ADDR_STATE = BenchmarkUtil.getRandomAString(2, 20);
ADDR_ZIP = BenchmarkUtil.getRandomAString(5, 10);
country_id = countries.get(BenchmarkUtil.getRandomInt(0, NUM_COUNTRIES - 1));
String key = country_id + ADDR_STATE + ADDR_CITY + ADDR_ZIP + rand.nextInt(1000);
Address address = new Address(key, ADDR_STREET1, ADDR_STREET2, ADDR_CITY,
ADDR_STATE, ADDR_ZIP, country_id);
// insert(ADDR_STREET1, key, "Addresses", "ADDR_STREET1", writeConsistency);
// insert(ADDR_STREET2, key, "Addresses", "ADDR_STREET2", writeConsistency);
// insert(ADDR_STATE, key, "Addresses", "ADDR_STATE", writeConsistency);
// insert(ADDR_CITY, key, "Addresses", "ADDR_CITY", writeConsistency);
// insert(ADDR_ZIP, key, "Addresses", "ADDR_ZIP", writeConsistency);
// insert(country.getCo_id(), key, "Addresses", "ADDR_CO_ID", writeConsistency);
databaseInsert("INSERT_Addresses", key, "Addresses", address, partial_results);
partial_adresses.add(address.getAddr_id());
}
if (debug) {
System.out.println("Thread finished: " + num_addresses + " addresses.");
}
barrier.countDown();
client.closeClient();
}
public ArrayList<String> getData() {
return partial_adresses;
}
public ResultHandler returnResults() {
return partial_results;
}
}
/**
* ********
* Countries *
* *********
*/
private void insertCountries(int numCountries) {
DataBaseCRUDInterface.CRUDclient client;
client = databaseClientFactory.getClient();
String[] countriesNames = {
"United States", "United Kingdom", "Canada", "Germany", "France", "Japan",
"Netherlands", "Italy", "Switzerland", "Australia", "Algeria", "Argentina",
"Armenia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangla Desh",
"Barbados", "Belarus", "Belgium", "Bermuda", "Bolivia", "Botswana", "Brazil",
"Bulgaria", "Cayman Islands", "Chad", "Chile", "China", "Christmas Island",
"Colombia", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark",
"Dominican Republic", "Eastern Caribbean", "Ecuador", "Egypt", "El Salvador",
"Estonia", "Ethiopia", "Falkland Island", "Faroe Island", "Fiji", "Finland",
"Gabon", "Gibraltar", "Greece", "Guam", "Hong Kong", "Hungary", "Iceland",
"India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Jamaica", "Jordan",
"Kazakhstan", "Kuwait", "Lebanon", "Luxembourg", "Malaysia", "Mexico",
"Mauritius", "New Zealand", "Norway", "Pakistan", "Philippines", "Poland",
"Portugal", "Romania", "Russia", "Saudi Arabia", "Singapore", "Slovakia",
"South Africa", "South Korea", "Spain", "Sudan", "Sweden", "Taiwan",
"Thailand", "Trinidad", "Turkey", "Venezuela", "Zambia"
};
double[] exchanges = {
1, .625461, 1.46712, 1.86125, 6.24238, 121.907, 2.09715, 1842.64, 1.51645,
1.54208, 65.3851, 0.998, 540.92, 13.0949, 3977, 1, .3757, 48.65, 2, 248000,
38.3892, 1, 5.74, 4.7304, 1.71, 1846, .8282, 627.1999, 494.2, 8.278,
1.5391, 1677, 7.3044, 23, .543, 36.0127, 7.0707, 15.8, 2.7, 9600, 3.33771,
8.7, 14.9912, 7.7, .6255, 7.124, 1.9724, 5.65822, 627.1999, .6255, 309.214,
1, 7.75473, 237.23, 74.147, 42.75, 8100, 3000, .3083, .749481, 4.12, 37.4,
0.708, 150, .3062, 1502, 38.3892, 3.8, 9.6287, 25.245, 1.87539, 7.83101, 52,
37.8501, 3.9525, 190.788, 15180.2, 24.43, 3.7501, 1.72929, 43.9642, 6.25845,
1190.15, 158.34, 5.282, 8.54477, 32.77, 37.1414, 6.1764, 401500, 596, 2447.7
};
String[] currencies = {
"Dollars", "Pounds", "Dollars", "Deutsche Marks", "Francs", "Yen", "Guilders",
"Lira", "Francs", "Dollars", "Dinars", "Pesos", "Dram", "Schillings", "Manat",
"Dollars", "Dinar", "Taka", "Dollars", "Rouble", "Francs", "Dollars",
"Boliviano", "Pula", "Real", "Lev", "Dollars", "Franc", "Pesos", "Yuan Renmimbi",
"Dollars", "Pesos", "Kuna", "Pesos", "Pounds", "Koruna", "Kroner", "Pesos",
"Dollars", "Sucre", "Pounds", "Colon", "Kroon", "Birr", "Pound", "Krone", "Dollars",
"Markka", "Franc", "Pound", "Drachmas", "Dollars", "Dollars", "Forint", "Krona",
"Rupees", "Rupiah", "Rial", "Dinar", "Punt", "Shekels", "Dollars", "Dinar", "Tenge",
"Dinar", "Pounds", "Francs", "Ringgit", "Pesos", "Rupees", "Dollars", "Kroner",
"Rupees", "Pesos", "Zloty", "Escudo", "Leu", "Rubles", "Riyal", "Dollars", "Koruna",
"Rand", "Won", "Pesetas", "Dinar", "Krona", "Dollars", "Baht", "Dollars", "Lira",
"Bolivar", "Kwacha"
};
if (numCountries > countriesNames.length) {
numCountries = countriesNames.length - 1;
}
System.out.println(">>Inserting " + numCountries + " countries || populatores " + num_threads);
for (int i = 0; i < numCountries; i++) {
//Country name = key
//insert(exchanges[i], countriesNames[i], "Countries", "CO_EXCHANGE", writeConsitency);
//insert(currencies[i], countriesNames[i], "Countries", "CO_CURRENCY", writeConsitency);
Country country = new Country(countriesNames[i], countriesNames[i], exchanges[i], currencies[i]);
databaseInsert(client, "INSERT_Countries", countriesNames[i], "Countries", country, results);
this.countries.add(country.getCo_id());
}
if (debug) {
System.out.println("Countries:" + countriesNames.length + " inserted");
}
}
/**
* ****************
* Orders and XACTS *
* ******************
*/
public void insertOrder_and_CC_XACTS(int n) throws InterruptedException {
int threads = num_threads;
int sections = n;
int firstSection = 0;
if (n < num_threads) {
threads = 1;
firstSection = n;
} else {
sections = (int) Math.floor(n / num_threads);
int rest = n - (num_threads * sections);
firstSection = sections + rest;
}
System.out.println(">>Inserting " + n + " Orders .. || populatores " + num_threads);
barrier = new CountDownLatch(threads);
int lastkey = 1;
Order_and_XACTSPopulator[] partial_orders = new Order_and_XACTSPopulator[threads];
for (int i = 0; i < threads; i++) {
Order_and_XACTSPopulator populator = null;
if (i == 0) {
populator = new Order_and_XACTSPopulator(lastkey, firstSection);
lastkey = lastkey + firstSection;
} else {
populator = new Order_and_XACTSPopulator(lastkey, sections);
lastkey = lastkey + sections;
}
partial_orders[i] = populator;
Thread t = new Thread(populator);
t.start();
}
barrier.await();
for (Order_and_XACTSPopulator populator : partial_orders) {
results.addResults(populator.returnResults());
populator.partial_results.cleanResults();
populator = null;
}
System.gc();
}
class Order_and_XACTSPopulator implements Runnable {
int num_orders;
int begin_key;
DataBaseCRUDInterface.CRUDclient client;
ResultHandler partial_results;
public Order_and_XACTSPopulator(int begin_key, int num_orders) {
client = databaseClientFactory.getClient();
this.num_orders = num_orders;
this.begin_key = begin_key;
partial_results = new ResultHandler("", rounds);
}
public void run() {
this.insertOrder_and_CC_XACTS(begin_key, num_orders);
}
public void databaseInsert(String Operation, String key, String path, Entity value, ResultHandler results) {
long time1 = System.currentTimeMillis();
Map result = client.insert(key, path, value);
long time2 = System.currentTimeMillis();
results.logResult(Operation, time2 - time1);
if (result.get(DataBaseCRUDInterface.TIME_TYPE).equals("SuperColumn"))
results.logResult("WRITE_SUPER", (Long) result.get(DataBaseCRUDInterface.TIME));
else
results.logResult("WRITE", (Long) result.get(DataBaseCRUDInterface.TIME));
}
public void insertOrder_and_CC_XACTS(int begin_key, int number_keys) {
System.out.println("Inserting Orders: " + number_keys);
String column_family = "Orders";
String subcolumn_family = "OrderLines";
String[] credit_cards = {"VISA", "MASTERCARD", "DISCOVER", "AMEX", "DINERS"};
String[] ship_types = {"AIR", "UPS", "FEDEX", "SHIP", "COURIER", "MAIL"};
String[] status_types = {"PROCESSING", "SHIPPED", "PENDING", "DENIED"};
long O_ID = begin_key;
// ColumnPath path = new ColumnPath(column_family);
// path.setSuper_column("ids".getBytes());
for (int z = 0; z < number_keys; z++) {
column_family = "Orders";
subcolumn_family = "OrderLines";
String O_C_ID;
java.sql.Timestamp O_DATE;
float O_SUB_TOTAL;
float O_TAX;
float O_TOTAL;
java.sql.Timestamp O_SHIP_DATE;
String O_SHIP_TYPE;
String O_SHIP_ADDR;
String O_STATUS;
String costumer_id = costumers.get(rand.nextInt(costumers.size()));
O_C_ID = costumer_id;
GregorianCalendar call = new GregorianCalendar();
O_DATE = new java.sql.Timestamp(call.getTime().getTime());
//insertInSuperColumn(O_DATE, O_C_ID, column_family, O_ID + "", "O_DATE", write_con);
O_SUB_TOTAL = rand.nextFloat() * 100 * 4;
//insertInSuperColumn(O_SUB_TOTAL, O_C_ID, column_family, O_ID + "", "O_SUB_TOTAL", write_con);
O_TAX = O_SUB_TOTAL * 0.21f;
//insertInSuperColumn(O_TAX, O_C_ID, column_family, O_ID + "", "O_TAX", write_con);
O_TOTAL = O_SUB_TOTAL + O_TAX;
//insertInSuperColumn(O_TOTAL, O_C_ID, column_family, O_ID + "", "O_TOTAL", write_con);
call.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(0, 7));
O_SHIP_DATE = new java.sql.Timestamp(call.getTime().getTime());
//insertInSuperColumn(O_SHIP_DATE, O_C_ID, column_family, O_ID + "", "O_SHIP_DATE", write_con);
O_SHIP_TYPE = ship_types[rand.nextInt(ship_types.length)];
//insertInSuperColumn(O_SHIP_TYPE, O_C_ID, column_family, O_ID + "", "O_SHIP_TYPE", write_con);
O_STATUS = status_types[rand.nextInt(status_types.length)];
//insertInSuperColumn(O_STATUS, O_C_ID, column_family, O_ID + "", "O_STATUS", write_con);
String billAddress = addresses.get(BenchmarkUtil.getRandomInt(0, NUM_ADDRESSES - 1));
// insertInSuperColumn(billAddress.getAddr_id(), O_C_ID, column_family, O_ID + "", "O_BILL_ADDR_ID", write_con);
O_SHIP_ADDR = addresses.get(BenchmarkUtil.getRandomInt(0, NUM_ADDRESSES - 1));
// insertInSuperColumn(O_SHIP_ADDR.getAddr_id(), O_C_ID, column_family, O_ID + "", "O_SHIP_ADDR_ID", write_con);
Orders order = new Orders(O_ID, O_C_ID, O_DATE, O_SUB_TOTAL, O_TAX, O_TOTAL, O_SHIP_TYPE, O_SHIP_DATE, O_STATUS, billAddress, O_SHIP_ADDR);
databaseInsert("INSERT Orders", O_C_ID, column_family, order, partial_results);
//orders.add(order);
int number_of_items = rand.nextInt(4) + 1;
for (int i = 0; i < number_of_items; i++) {
/**
* OL_ID
* OL_O_ID
* OL_I_ID
* OL_QTY
* OL_DISCOUNT
* OL_COMMENT
*/
String OL_ID;
String OL_I_ID;
int OL_QTY;
float OL_DISCOUNT;
String OL_COMMENT;
OL_ID = O_ID + "N" + i;
OL_I_ID = items.get(rand.nextInt(items.size()));
//insertInSuperColumn(OL_I_ID, O_ID + "", subcolumn_family, OL_ID, "OL_I_ID", write_con);
OL_QTY = rand.nextInt(4) + 1;
//insertInSuperColumn(OL_QTY, O_ID + "", subcolumn_family, OL_ID, "OL_QTY", write_con);
OL_DISCOUNT = rand.nextBoolean() ? 0 : rand.nextFloat() * 10;
//insertInSuperColumn(OL_DISCOUNT, O_ID + "", subcolumn_family, OL_ID, "OL_DISCOUNT", write_con);
OL_COMMENT = null;
if (rand.nextBoolean()) {
OL_COMMENT = BenchmarkUtil.getRandomAString(20, 100);
//insertInSuperColumn(OL_COMMENT, O_ID + "", subcolumn_family, OL_ID, "OL_COMMENT", write_con);
}
OrderLine orderline = new OrderLine(OL_ID, order.getO_ID(), OL_I_ID, OL_QTY, OL_DISCOUNT, OL_COMMENT);
databaseInsert("INSERT Orders Lines", O_ID + "", subcolumn_family, orderline, partial_results);
//orderLines.add(orderline);
}
String CX_TYPE;
int CX_NUM;
String CX_NAME;
java.sql.Date CX_EXPIRY;
double CX_XACT_AMT; //O_TOTAL
int CX_CO_ID; //Order.getID;
column_family = "CC_XACTS";
CX_NUM = BenchmarkUtil.getRandomNString(16);
String key = O_ID + "";
CX_TYPE = credit_cards[BenchmarkUtil.getRandomInt(0, credit_cards.length - 1)];
//insert(CX_TYPE, key, column_family, "CX_TYPE", write_con);
//insert(CX_NUM, key, column_family, "CX_NUM", write_con);
CX_NAME = BenchmarkUtil.getRandomAString(14, 30);
//insert(CX_NAME, key, column_family, "CX_NAME", write_con);
GregorianCalendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, BenchmarkUtil.getRandomInt(10, 730));
CX_EXPIRY = new java.sql.Date(cal.getTime().getTime());
//insert(CX_EXPIRY, key, column_family, "CX_EXPIRY", write_con);
//DATE
// insert(O_SHIP_DATE, key, column_family, "CX_XACT_DATE", write_con);
//AMOUNT
// insert(O_TOTAL, key, column_family, "CX_XACT_AMT", write_con);
//CX_AUTH_ID = getRandomAString(5,15);// unused
String country_id = countries.get(BenchmarkUtil.getRandomInt(0, countries.size() - 1));
// insert(country.getCo_id(), key, column_family, "CX_CO_ID", write_con);
CCXact ccXact = new CCXact(CX_TYPE, CX_NUM, CX_NAME, CX_EXPIRY,/* CX_AUTH_ID,*/ O_TOTAL,
O_SHIP_DATE, /* 1 + _counter, */ order.getO_ID(), country_id);
databaseInsert("INSERT_CCXact", key, column_family, order, partial_results);
O_ID++;
}
if (debug) {
System.out.println("Thread finished: " + number_keys + " orders and xact inserted. key:" + begin_key);
}
barrier.countDown();
client.closeClient();
}
public ResultHandler returnResults() {
return partial_results;
}
}
/************************************************************************/
/************************************************************************/
/**
* ********************************************************************
*/
// public void ShowValues(String column_family) {
//
// System.out.println("Show Values for Column family : " + column_family);
// try {
// SlicePredicate predicate = new SlicePredicate();
// SliceRange range = new SliceRange("".getBytes(), "".getBytes(), false, 300);
//
// // ColumnParent parent = new ColumnParent(column_family, null);
// ColumnParent parent = new ColumnParent(column_family);
// predicate.setSlice_range(range);
//
// //List<String> keys = client..get_key_range(Keyspace, column_family, "", "", 300, ConsistencyLevel.ONE);
// List<KeySlice> keys = client.get_range_slice(Keyspace, parent, predicate, "", "", 300, ConsistencyLevel.ONE);
// System.out.println("Keys size: " + keys.size());
// for (KeySlice ks : keys) {
// System.out.println("For key: " + ks.key);
// List<ColumnOrSuperColumn> line = ks.columns;
// StringBuilder builder = new StringBuilder();
// for (ColumnOrSuperColumn column : line) {
//
// Column c = column.getColumn();
//
// builder.append(" Name: " + new String(c.getName()) + " Value: " + new String(c.getValue()) + "||");
// }
// System.out.println("Key on column: " + ks.key + "with values: " + builder.toString());
//
// }
//
//
//// Map<String, List<ColumnOrSuperColumn>> results = client.multiget_slice(Keyspace, keys, parent, predicate, ConsistencyLevel.ONE);
//// for (String key : results.keySet()) {
//// List<ColumnOrSuperColumn> line = results.get(key);
//// StringBuilder builder = new StringBuilder();
//// for (ColumnOrSuperColumn column : line) {
////
//// Column c = column.getColumn();
////
//// builder.append(" Name: " + new String(c.getName()) + " Value: " + new String(c.getValue()) + "||");
//// }
//// System.out.println("Key on column: " + key + "with values: " + builder.toString());
//// }
// } catch (TimedOutException ex) {
// Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
// } catch (InvalidRequestException ex) {
// Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
// } catch (UnavailableException ex) {
// Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
// } catch (TException ex) {
// Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
public static boolean loadDescriptor() {
try {
FileInputStream in = null;
String jsonString_r = "";
try {
in = new FileInputStream("CassandraDB.xml");
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
String s = "";
StringBuilder sb = new StringBuilder();
while (s != null) {
sb.append(s);
s = bin.readLine();
}
jsonString_r = sb.toString().replace("\n", "");
bin.close();
in.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CassandraInterface.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CassandraInterface.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
Logger.getLogger(CassandraInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
Map<String, Map<String, String>> map = JsonUtil.getMapMapFromJsonString(jsonString_r);
if (!map.containsKey("BenchmarkInfo")) {
System.out.println("ERROR: NO INFORMATION ABOUT THE DATA ENGINE FOUND, ABORTING");
return false;
} else {
Map<String, String> databaseInfo = map.get("BenchmarkInfo");
String databaseClass = databaseInfo.get("DataEngineInterface");
System.out.println("CHOSEN DATABASE ENGINE: " + databaseClass);
databaseClientFactory = (DataBaseCRUDInterface) Class.forName(databaseClass).getConstructor().newInstance();
if (!map.containsKey("LoadParameters")) {
System.out.println("WARNING: NO LOAD DEFINITIONS FOUND, NO DELAYS WILL BE USED , ONE THREAD USED");
} else {
Map<String, String> loadInfo = map.get("LoadParameters");
String do_delays = loadInfo.get("delay_inserts");
delay_inserts = Boolean.valueOf(do_delays);
String delay_time_info = loadInfo.get("delay_time");
delay_time = Integer.valueOf(delay_time_info);
String thread_number_info = loadInfo.get("thread_number");
num_threads = Integer.parseInt(thread_number_info);
}
return true;
}
} catch (NoSuchMethodException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(BenchmarkPopulator.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("ERROR: THERE IS SOME PROBLEM WITH THE DEFINITIONS FILE");
return false;
}
public void info() {
// Namegenerator ng = new Namegenerator("src/JaNaG_Source/languages.txt", "src/JaNaG_Source/semantics.txt");
// //String[] ns = ng.getPatterns();
// String[] ns = ng.getGenders("Orkisch");
// for (String ss : ns) {
// System.out.println(ss);
//
// }
/**
Patterns:
Pseudo-Altdeutsch
Menschlich Fantasy (Mann , Frau)
Götternamen
Dämonen
Griechisch
Spanisch
Italienisch
Irisch
Französisch
Polnisch
Hebräisch (Mann , Frau)
Orkisch
US-Zensus//english
*
*/
//
// try {
// Map<String, Map<String, String>> info = client.describe_keyspace("Tpcw");
// System.out.println("Info =" + info.toString());
//
// } catch (NotFoundException ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
// } catch (TException ex) {
// Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
/**
try {
ColumnOrSuperColumn scolumn = client.get(Keyspace, "all", path, write_con);
SuperColumn super_column = scolumn.getSuper_column();
Column column = super_column.columns.get(0);
O_ID = (Long) BenchmarkUtil.toObject(column.value) + 1;
insertInSuperColumn(O_ID, "all", column_family, "ids", "LAST_ID", write_con);
} catch (TimedOutException ex) {
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidRequestException ex) {
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
O_ID = 0;
} catch (NotFoundException ex) {
O_ID = 0;
insertInSuperColumn(O_ID, "all", column_family, "ids", "LAST_ID", write_con);
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(PopulateDatabase.class.getName()).log(Level.SEVERE, null, ex);
}
*
*
*
*
try {
ColumnOrSuperColumn scolumn = client.get(Keyspace, "all", path, write_con);
SuperColumn super_column = scolumn.getSuper_column();
Column column = super_column.columns.get(0);
O_ID = (Long) BenchmarkUtil.toObject(column.value);
O_ID++;
//new Long(new String(column.value)) + 1;
insertInSuperColumn(O_ID, "all", "Orders", "ids", "LAST_ID", write_con);
**/
| The populator does not remove the Shopping carts as it was a necessary previous step to the benchmark executor, and it is now on the section.
| benchmarks/TpcwBenchmark/Populator.java | The populator does not remove the Shopping carts as it was a necessary previous step to the benchmark executor, and it is now on the section. |
|
Java | apache-2.0 | 4127e0fc75ac299366dd6077fa3183d2f1842e09 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.util;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.java.refactoring.JavaRefactoringBundle;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.search.GlobalSearchScopes;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.*;
import com.intellij.refactoring.PackageWrapper;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.introduceField.ElementToWorkOn;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.Stack;
import com.intellij.util.text.UniqueNameGenerator;
import gnu.trove.THashMap;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public final class RefactoringUtil {
private static final Logger LOG = Logger.getInstance(RefactoringUtil.class);
public static final int EXPR_COPY_SAFE = 0;
public static final int EXPR_COPY_UNSAFE = 1;
public static final int EXPR_COPY_PROHIBITED = 2;
private RefactoringUtil() {
}
public static boolean isSourceRoot(final PsiDirectory directory) {
if (directory.getManager() == null) return false;
final Project project = directory.getProject();
final VirtualFile virtualFile = directory.getVirtualFile();
final VirtualFile sourceRootForFile = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(virtualFile);
return Comparing.equal(virtualFile, sourceRootForFile);
}
public static boolean isInStaticContext(PsiElement element, @Nullable final PsiClass aClass) {
return PsiUtil.getEnclosingStaticElement(element, aClass) != null;
}
/**
* @deprecated use {@link PsiTypesUtil#hasUnresolvedComponents(PsiType)}
*/
@Deprecated
public static boolean isResolvableType(PsiType type) {
return !PsiTypesUtil.hasUnresolvedComponents(type);
}
public static PsiElement replaceOccurenceWithFieldRef(PsiExpression occurrence, PsiField newField, PsiClass destinationClass)
throws IncorrectOperationException {
final PsiManager manager = destinationClass.getManager();
final String fieldName = newField.getName();
final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
final PsiElement element = occurrence.getUserData(ElementToWorkOn.PARENT);
final PsiVariable psiVariable = facade.getResolveHelper().resolveAccessibleReferencedVariable(fieldName, element != null ? element : occurrence);
final PsiElementFactory factory = facade.getElementFactory();
if (psiVariable != null && psiVariable.equals(newField)) {
return IntroduceVariableBase.replace(occurrence, factory.createExpressionFromText(fieldName, null), manager.getProject());
}
else {
final PsiReferenceExpression ref = (PsiReferenceExpression)factory.createExpressionFromText("this." + fieldName, null);
if (!occurrence.isValid()) return null;
if (newField.hasModifierProperty(PsiModifier.STATIC)) {
ref.setQualifierExpression(factory.createReferenceExpression(destinationClass));
}
return IntroduceVariableBase.replace(occurrence, ref, manager.getProject());
}
}
/**
* @see JavaCodeStyleManager#suggestUniqueVariableName(String, PsiElement, boolean)
* Cannot use method from code style manager: a collision with fieldToReplace is not a collision
*/
public static String suggestUniqueVariableName(String baseName, PsiElement place, PsiField fieldToReplace) {
for(int index = 0;;index++) {
final String name = index > 0 ? baseName + index : baseName;
final PsiManager manager = place.getManager();
PsiResolveHelper helper = JavaPsiFacade.getInstance(manager.getProject()).getResolveHelper();
PsiVariable refVar = helper.resolveAccessibleReferencedVariable(name, place);
if (refVar != null && !manager.areElementsEquivalent(refVar, fieldToReplace)) continue;
final boolean[] found = {false};
place.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitClass(PsiClass aClass) {
}
@Override
public void visitVariable(PsiVariable variable) {
if (name.equals(variable.getName())) {
found[0] = true;
stopWalking();
}
}
});
if (found[0]) {
continue;
}
return name;
}
}
@Nullable
public static String suggestNewOverriderName(String oldOverriderName, String oldBaseName, String newBaseName) {
if (oldOverriderName.equals(oldBaseName)) {
return newBaseName;
}
int i;
if (oldOverriderName.startsWith(oldBaseName)) {
i = 0;
}
else {
i = StringUtil.indexOfIgnoreCase(oldOverriderName, oldBaseName, 0);
}
if (i >= 0) {
String newOverriderName = oldOverriderName.substring(0, i);
if (Character.isUpperCase(oldOverriderName.charAt(i))) {
newOverriderName += StringUtil.capitalize(newBaseName);
}
else {
newOverriderName += newBaseName;
}
final int j = i + oldBaseName.length();
if (j < oldOverriderName.length()) {
newOverriderName += oldOverriderName.substring(j);
}
return newOverriderName;
}
return null;
}
public static boolean hasOnDemandStaticImport(final PsiElement element, final PsiClass aClass) {
if (element.getContainingFile() instanceof PsiJavaFile) {
final PsiImportList importList = ((PsiJavaFile)element.getContainingFile()).getImportList();
if (importList != null) {
final PsiImportStaticStatement[] importStaticStatements = importList.getImportStaticStatements();
return Arrays.stream(importStaticStatements).anyMatch(stmt -> stmt.isOnDemand() && stmt.resolveTargetClass() == aClass);
}
}
return false;
}
public static PsiElement replaceElementsWithMap(PsiElement replaceIn, final Map<PsiElement, PsiElement> elementsToReplace) throws IncorrectOperationException {
for(Map.Entry<PsiElement, PsiElement> e: elementsToReplace.entrySet()) {
if (e.getKey() == replaceIn) {
return e.getKey().replace(e.getValue());
}
e.getKey().replace(e.getValue());
}
return replaceIn;
}
public static PsiElement getVariableScope(PsiLocalVariable localVar) {
if (!(localVar instanceof ImplicitVariable)) {
return localVar.getParent().getParent();
}
else {
return ((ImplicitVariable)localVar).getDeclarationScope();
}
}
@Nullable
public static PsiElement getParentStatement(@Nullable PsiElement place, boolean skipScopingStatements) {
PsiElement parent = place;
while (true) {
if (parent == null) return null;
if (parent instanceof PsiStatement) break;
if (parent instanceof PsiExpression && parent.getParent() instanceof PsiLambdaExpression) return parent;
parent = parent.getParent();
}
PsiElement parentStatement = parent;
while (parent instanceof PsiStatement && !(parent instanceof PsiSwitchLabeledRuleStatement)) {
if (!skipScopingStatements && ((parent instanceof PsiForStatement && parentStatement == ((PsiForStatement)parent).getBody()) || (
parent instanceof PsiForeachStatement && parentStatement == ((PsiForeachStatement)parent).getBody()) || (
parent instanceof PsiWhileStatement && parentStatement == ((PsiWhileStatement)parent).getBody()) || (
parent instanceof PsiIfStatement &&
(parentStatement == ((PsiIfStatement)parent).getThenBranch() || parentStatement == ((PsiIfStatement)parent).getElseBranch())))) {
return parentStatement;
}
parentStatement = parent;
parent = parent.getParent();
}
return parentStatement;
}
public static PsiElement getParentExpressionAnchorElement(PsiElement place) {
PsiElement parent = place.getUserData(ElementToWorkOn.PARENT);
if (place.getUserData(ElementToWorkOn.OUT_OF_CODE_BLOCK) != null) return parent;
if (parent == null) parent = place;
while (true) {
if (isExpressionAnchorElement(parent)) return parent;
if (parent instanceof PsiExpression && parent.getParent() instanceof PsiLambdaExpression) return parent;
parent = parent.getParent();
if (parent == null) return null;
}
}
public static boolean isExpressionAnchorElement(PsiElement element) {
if (element instanceof PsiDeclarationStatement && element.getParent() instanceof PsiForStatement) return false;
return element instanceof PsiStatement || element instanceof PsiClassInitializer || element instanceof PsiField ||
element instanceof PsiMethod;
}
/**
* @param expression
* @return loop body if expression is part of some loop's condition or for loop's increment part
* null otherwise
*/
public static PsiElement getLoopForLoopCondition(PsiExpression expression) {
PsiExpression outermost = expression;
while (outermost.getParent() instanceof PsiExpression) {
outermost = (PsiExpression)outermost.getParent();
}
if (outermost.getParent() instanceof PsiForStatement) {
final PsiForStatement forStatement = (PsiForStatement)outermost.getParent();
if (forStatement.getCondition() == outermost) {
return forStatement;
}
else {
return null;
}
}
if (outermost.getParent() instanceof PsiExpressionStatement && outermost.getParent().getParent() instanceof PsiForStatement) {
final PsiForStatement forStatement = (PsiForStatement)outermost.getParent().getParent();
if (forStatement.getUpdate() == outermost.getParent()) {
return forStatement;
}
else {
return null;
}
}
if (outermost.getParent() instanceof PsiWhileStatement) {
return outermost.getParent();
}
if (outermost.getParent() instanceof PsiDoWhileStatement) {
return outermost.getParent();
}
return null;
}
public static PsiClass getThisResolveClass(final PsiReferenceExpression place) {
final JavaResolveResult resolveResult = place.advancedResolve(false);
final PsiElement scope = resolveResult.getCurrentFileResolveScope();
if (scope instanceof PsiClass) {
return (PsiClass)scope;
}
return null;
}
public static PsiCall getEnclosingConstructorCall(PsiJavaCodeReferenceElement ref) {
PsiElement parent = ref.getParent();
if (ref instanceof PsiReferenceExpression && parent instanceof PsiMethodCallExpression) return (PsiCall)parent;
if (parent instanceof PsiAnonymousClass) {
parent = parent.getParent();
}
return parent instanceof PsiNewExpression ? (PsiNewExpression)parent : null;
}
public static PsiMethod getEnclosingMethod(PsiElement element) {
final PsiElement container = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class, PsiLambdaExpression.class);
return container instanceof PsiMethod ? (PsiMethod)container : null;
}
public static void renameVariableReferences(PsiVariable variable, String newName, SearchScope scope) throws IncorrectOperationException {
renameVariableReferences(variable, newName, scope, false);
}
public static void renameVariableReferences(PsiVariable variable,
String newName,
SearchScope scope,
final boolean ignoreAccessScope) throws IncorrectOperationException {
for (PsiReference reference : ReferencesSearch.search(variable, scope, ignoreAccessScope)) {
reference.handleElementRename(newName);
}
}
public static boolean canBeDeclaredFinal(@NotNull PsiVariable variable) {
LOG.assertTrue(variable instanceof PsiLocalVariable || variable instanceof PsiParameter);
final boolean isReassigned = HighlightControlFlowUtil
.isReassigned(variable, new THashMap<>());
return !isReassigned;
}
/**
* removes a reference to the specified class from the reference list given
*
* @return if removed - a reference to the class or null if there were no references to this class in the reference list
*/
public static PsiJavaCodeReferenceElement removeFromReferenceList(PsiReferenceList refList, PsiClass aClass)
throws IncorrectOperationException {
PsiJavaCodeReferenceElement[] refs = refList.getReferenceElements();
for (PsiJavaCodeReferenceElement ref : refs) {
if (ref.isReferenceTo(aClass)) {
PsiJavaCodeReferenceElement refCopy = (PsiJavaCodeReferenceElement)ref.copy();
ref.delete();
return refCopy;
}
}
return null;
}
public static PsiJavaCodeReferenceElement findReferenceToClass(PsiReferenceList refList, PsiClass aClass) {
PsiJavaCodeReferenceElement[] refs = refList.getReferenceElements();
for (PsiJavaCodeReferenceElement ref : refs) {
if (ref.isReferenceTo(aClass)) {
return ref;
}
}
return null;
}
public static PsiType getTypeByExpressionWithExpectedType(PsiExpression expr) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(expr.getProject());
PsiType typeByExpression = getTypeByExpression(expr, factory);
PsiType type = typeByExpression;
final boolean isFunctionalType = LambdaUtil.notInferredType(type);
PsiType exprType = expr.getType();
final boolean detectConjunct = exprType instanceof PsiIntersectionType ||
exprType instanceof PsiWildcardType && ((PsiWildcardType)exprType).getBound() instanceof PsiIntersectionType ||
exprType instanceof PsiCapturedWildcardType && ((PsiCapturedWildcardType)exprType).getUpperBound() instanceof PsiIntersectionType;
if (type != null && !isFunctionalType && !detectConjunct) {
return type;
}
ExpectedTypeInfo[] expectedTypes = ExpectedTypesProvider.getExpectedTypes(expr, false);
if (expectedTypes.length == 1 || (isFunctionalType || detectConjunct) && expectedTypes.length > 0 ) {
if (typeByExpression != null && Arrays.stream(expectedTypes).anyMatch(typeInfo -> typeByExpression.isAssignableFrom(typeInfo.getType()))) {
return type;
}
type = expectedTypes[0].getType();
if (!type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return type;
}
return detectConjunct ? type : null;
}
public static PsiType getTypeByExpression(PsiExpression expr) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(expr.getProject());
PsiType type = getTypeByExpression(expr, factory);
if (LambdaUtil.notInferredType(type)) {
type = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_OBJECT, expr.getResolveScope());
}
return type;
}
private static PsiType getTypeByExpression(PsiExpression expr, final PsiElementFactory factory) {
PsiType type = RefactoringChangeUtil.getTypeByExpression(expr);
if (PsiType.NULL.equals(type)) {
ExpectedTypeInfo[] infos = ExpectedTypesProvider.getExpectedTypes(expr, false);
if (infos.length > 0) {
type = infos[0].getType();
if (type instanceof PsiPrimitiveType) {
type = infos.length > 1 && !(infos[1].getType() instanceof PsiPrimitiveType) ? infos[1].getType()
: ((PsiPrimitiveType)type).getBoxedType(expr);
}
}
else {
type = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_OBJECT, expr.getResolveScope());
}
}
return type;
}
public static boolean isAssignmentLHS(@NotNull PsiElement element) {
return element instanceof PsiExpression && PsiUtil.isAccessedForWriting((PsiExpression)element);
}
private static void removeFinalParameters(PsiMethod method) throws IncorrectOperationException {
PsiParameterList paramList = method.getParameterList();
PsiParameter[] params = paramList.getParameters();
for (PsiParameter param : params) {
if (param.hasModifierProperty(PsiModifier.FINAL)) {
PsiUtil.setModifierProperty(param, PsiModifier.FINAL, false);
}
}
}
public static PsiElement getAnchorElementForMultipleExpressions(PsiExpression @NotNull [] occurrences, PsiElement scope) {
PsiElement anchor = null;
for (PsiExpression occurrence : occurrences) {
if (scope != null && !PsiTreeUtil.isAncestor(scope, occurrence, false)) {
continue;
}
PsiElement anchor1 = getParentExpressionAnchorElement(occurrence);
if (anchor1 == null) {
if (occurrence.isPhysical()) return null;
continue;
}
if (anchor == null) {
anchor = anchor1;
}
else {
PsiElement commonParent = PsiTreeUtil.findCommonParent(anchor, anchor1);
if (commonParent == null || anchor.getTextRange() == null || anchor1.getTextRange() == null) return null;
PsiElement firstAnchor = anchor.getTextRange().getStartOffset() < anchor1.getTextRange().getStartOffset() ? anchor : anchor1;
if (commonParent.equals(firstAnchor)) {
anchor = firstAnchor;
}
else {
if (commonParent instanceof PsiStatement) {
anchor = commonParent;
}
else {
PsiElement parent = firstAnchor;
while (!parent.getParent().equals(commonParent)) {
parent = parent.getParent();
}
final PsiElement newAnchor = getParentExpressionAnchorElement(parent);
if (newAnchor != null) {
anchor = newAnchor;
}
else {
anchor = parent;
}
}
}
}
}
if (anchor == null) return null;
if (occurrences.length > 1 && anchor.getParent().getParent() instanceof PsiSwitchStatement) {
PsiSwitchStatement switchStatement = (PsiSwitchStatement)anchor.getParent().getParent();
if (switchStatement.getBody().equals(anchor.getParent())) {
int startOffset = occurrences[0].getTextRange().getStartOffset();
int endOffset = occurrences[occurrences.length - 1].getTextRange().getEndOffset();
PsiStatement[] statements = switchStatement.getBody().getStatements();
boolean isInDifferentCases = false;
for (PsiStatement statement : statements) {
if (statement instanceof PsiSwitchLabelStatement) {
int caseOffset = statement.getTextRange().getStartOffset();
if (startOffset < caseOffset && caseOffset < endOffset) {
isInDifferentCases = true;
break;
}
}
}
if (isInDifferentCases) {
anchor = switchStatement;
}
}
}
return anchor;
}
public static boolean isMethodUsage(PsiElement element) {
if (element instanceof PsiEnumConstant) {
return JavaLanguage.INSTANCE.equals(element.getLanguage());
}
if (!(element instanceof PsiJavaCodeReferenceElement)) return false;
PsiElement parent = element.getParent();
if (parent instanceof PsiCall) {
return true;
}
else if (parent instanceof PsiAnonymousClass) {
return element.equals(((PsiAnonymousClass)parent).getBaseClassReference());
}
return false;
}
@Nullable
public static PsiExpressionList getArgumentListByMethodReference(PsiElement ref) {
if (ref instanceof PsiCall) return ((PsiCall)ref).getArgumentList();
PsiElement parent = ref.getParent();
if (parent instanceof PsiCall) {
return ((PsiCall)parent).getArgumentList();
}
else if (parent instanceof PsiAnonymousClass) {
return ((PsiNewExpression)parent.getParent()).getArgumentList();
}
LOG.assertTrue(false);
return null;
}
public static PsiCall getCallExpressionByMethodReference(PsiElement ref) {
if (ref instanceof PsiCall) return (PsiCall)ref;
PsiElement parent = ref.getParent();
if (parent instanceof PsiMethodCallExpression) {
return (PsiMethodCallExpression)parent;
}
else if (parent instanceof PsiNewExpression) {
return (PsiNewExpression)parent;
}
else if (parent instanceof PsiAnonymousClass) {
return (PsiNewExpression)parent.getParent();
}
else {
LOG.assertTrue(false);
return null;
}
}
/**
* @return List of highlighters
*/
public static List<RangeHighlighter> highlightAllOccurrences(Project project, PsiElement[] occurrences, Editor editor) {
ArrayList<RangeHighlighter> highlighters = new ArrayList<>();
HighlightManager highlightManager = HighlightManager.getInstance(project);
if (occurrences.length > 1) {
for (PsiElement occurrence : occurrences) {
final RangeMarker rangeMarker = occurrence.getUserData(ElementToWorkOn.TEXT_RANGE);
if (rangeMarker != null && rangeMarker.isValid()) {
highlightManager.addRangeHighlight(editor, rangeMarker.getStartOffset(), rangeMarker.getEndOffset(),
EditorColors.SEARCH_RESULT_ATTRIBUTES, true, highlighters);
}
else {
final TextRange textRange = occurrence.getTextRange();
highlightManager.addRangeHighlight(editor, textRange.getStartOffset(), textRange.getEndOffset(),
EditorColors.SEARCH_RESULT_ATTRIBUTES, true, highlighters);
}
}
}
return highlighters;
}
public static String createTempVar(PsiExpression expr, PsiElement context, boolean declareFinal) throws IncorrectOperationException {
PsiElement anchorStatement = getParentStatement(context, true);
LOG.assertTrue(anchorStatement != null && anchorStatement.getParent() != null);
Project project = expr.getProject();
String[] suggestedNames =
JavaCodeStyleManager.getInstance(project).suggestVariableName(VariableKind.LOCAL_VARIABLE, null, expr, null).names;
final String prefix = suggestedNames.length > 0 ? suggestedNames[0] : "var";
final String id = JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName(prefix, context, true);
PsiElementFactory factory = JavaPsiFacade.getElementFactory(expr.getProject());
if (expr instanceof PsiParenthesizedExpression) {
PsiExpression expr1 = ((PsiParenthesizedExpression)expr).getExpression();
if (expr1 != null) {
expr = expr1;
}
}
PsiDeclarationStatement decl = factory.createVariableDeclarationStatement(id, expr.getType(), expr);
if (declareFinal) {
PsiUtil.setModifierProperty(((PsiLocalVariable)decl.getDeclaredElements()[0]), PsiModifier.FINAL, true);
}
anchorStatement.getParent().addBefore(decl, anchorStatement);
return id;
}
public static int verifySafeCopyExpression(PsiElement expr) {
return verifySafeCopyExpressionSubElement(expr);
}
private static int verifySafeCopyExpressionSubElement(PsiElement element) {
int result = EXPR_COPY_SAFE;
if (element == null) return result;
if (element instanceof PsiThisExpression || element instanceof PsiSuperExpression || element instanceof PsiIdentifier) {
return EXPR_COPY_SAFE;
}
if (element instanceof PsiMethodCallExpression) {
result = EXPR_COPY_UNSAFE;
}
if (element instanceof PsiNewExpression) {
return EXPR_COPY_PROHIBITED;
}
if (element instanceof PsiAssignmentExpression) {
return EXPR_COPY_PROHIBITED;
}
if (PsiUtil.isIncrementDecrementOperation(element)) {
return EXPR_COPY_PROHIBITED;
}
PsiElement[] children = element.getChildren();
for (PsiElement child : children) {
int childResult = verifySafeCopyExpressionSubElement(child);
result = Math.max(result, childResult);
}
return result;
}
@Contract("null, _ -> null")
public static PsiExpression convertInitializerToNormalExpression(PsiExpression expression, PsiType forcedReturnType)
throws IncorrectOperationException {
if (expression instanceof PsiArrayInitializerExpression && (forcedReturnType == null || forcedReturnType instanceof PsiArrayType)) {
return createNewExpressionFromArrayInitializer((PsiArrayInitializerExpression)expression, forcedReturnType);
}
return expression;
}
public static PsiExpression createNewExpressionFromArrayInitializer(PsiArrayInitializerExpression initializer, PsiType forcedType)
throws IncorrectOperationException {
PsiType initializerType = null;
if (initializer != null) {
if (forcedType != null) {
initializerType = forcedType;
}
else {
initializerType = getTypeByExpression(initializer);
}
}
if (initializerType == null) {
return initializer;
}
LOG.assertTrue(initializerType instanceof PsiArrayType);
PsiElementFactory factory = JavaPsiFacade.getElementFactory(initializer.getProject());
PsiNewExpression result =
(PsiNewExpression)factory.createExpressionFromText("new " + initializerType.getPresentableText() + "{}", null);
result = (PsiNewExpression)CodeStyleManager.getInstance(initializer.getProject()).reformat(result);
PsiArrayInitializerExpression arrayInitializer = result.getArrayInitializer();
LOG.assertTrue(arrayInitializer != null);
arrayInitializer.replace(initializer);
return result;
}
public static void makeMethodAbstract(@NotNull PsiClass targetClass, @NotNull PsiMethod method) throws IncorrectOperationException {
if (!method.hasModifierProperty(PsiModifier.DEFAULT)) {
PsiCodeBlock body = method.getBody();
if (body != null) {
body.delete();
}
PsiUtil.setModifierProperty(method, PsiModifier.ABSTRACT, true);
}
if (!targetClass.isInterface()) {
PsiUtil.setModifierProperty(targetClass, PsiModifier.ABSTRACT, true);
prepareForAbstract(method);
}
else {
prepareForInterface(method);
}
}
public static void makeMethodDefault(@NotNull PsiMethod method) throws IncorrectOperationException {
PsiUtil.setModifierProperty(method, PsiModifier.DEFAULT, !method.hasModifierProperty(PsiModifier.STATIC));
PsiUtil.setModifierProperty(method, PsiModifier.ABSTRACT, false);
prepareForInterface(method);
}
private static void prepareForInterface(PsiMethod method) {
PsiUtil.setModifierProperty(method, PsiModifier.PUBLIC, false);
PsiUtil.setModifierProperty(method, PsiModifier.PRIVATE, false);
PsiUtil.setModifierProperty(method, PsiModifier.PROTECTED, false);
prepareForAbstract(method);
}
private static void prepareForAbstract(PsiMethod method) {
PsiUtil.setModifierProperty(method, PsiModifier.FINAL, false);
PsiUtil.setModifierProperty(method, PsiModifier.SYNCHRONIZED, false);
PsiUtil.setModifierProperty(method, PsiModifier.NATIVE, false);
removeFinalParameters(method);
}
public static boolean isInsideAnonymousOrLocal(PsiElement element, PsiElement upTo) {
for (PsiElement current = element; current != null && current != upTo; current = current.getParent()) {
if (current instanceof PsiAnonymousClass) return true;
if (current instanceof PsiClass && current.getParent() instanceof PsiDeclarationStatement) {
return true;
}
}
return false;
}
public static PsiExpression unparenthesizeExpression(PsiExpression expression) {
while (expression instanceof PsiParenthesizedExpression) {
final PsiExpression innerExpression = ((PsiParenthesizedExpression)expression).getExpression();
if (innerExpression == null) return expression;
expression = innerExpression;
}
return expression;
}
public static PsiExpression outermostParenthesizedExpression(PsiExpression expression) {
while (expression.getParent() instanceof PsiParenthesizedExpression) {
expression = (PsiParenthesizedExpression)expression.getParent();
}
return expression;
}
public static String getNewInnerClassName(PsiClass aClass, String oldInnerClassName, String newName) {
String className = aClass.getName();
if (className == null || !oldInnerClassName.endsWith(className)) return newName;
StringBuilder buffer = new StringBuilder(oldInnerClassName);
buffer.replace(buffer.length() - className.length(), buffer.length(), newName);
return buffer.toString();
}
public static void visitImplicitSuperConstructorUsages(PsiClass subClass,
final ImplicitConstructorUsageVisitor implicitConstructorUsageVisitor,
PsiClass superClass) {
final PsiMethod baseDefaultConstructor = findDefaultConstructor(superClass);
final PsiMethod[] constructors = subClass.getConstructors();
if (constructors.length > 0) {
for (PsiMethod constructor : constructors) {
PsiCodeBlock body = constructor.getBody();
if (body == null) continue;
final PsiStatement[] statements = body.getStatements();
if (statements.length < 1 || !JavaHighlightUtil.isSuperOrThisCall(statements[0], true, true)) {
implicitConstructorUsageVisitor.visitConstructor(constructor, baseDefaultConstructor);
}
}
}
else {
implicitConstructorUsageVisitor.visitClassWithoutConstructors(subClass);
}
}
private static PsiMethod findDefaultConstructor(final PsiClass aClass) {
final PsiMethod[] constructors = aClass.getConstructors();
for (PsiMethod constructor : constructors) {
if (constructor.getParameterList().isEmpty()) return constructor;
}
return null;
}
public static void replaceMovedMemberTypeParameters(final PsiElement member,
final Iterable<? extends PsiTypeParameter> parametersIterable,
final PsiSubstitutor substitutor,
final PsiElementFactory factory) {
final Map<PsiElement, PsiElement> replacement = new LinkedHashMap<>();
for (PsiTypeParameter parameter : parametersIterable) {
final PsiType substitutedType = substitutor.substitute(parameter);
final PsiType erasedType = substitutedType == null ? TypeConversionUtil.erasure(factory.createType(parameter))
: substitutedType;
for (PsiReference reference : ReferencesSearch.search(parameter, new LocalSearchScope(member))) {
final PsiElement element = reference.getElement();
final PsiElement parent = element.getParent();
if (parent instanceof PsiTypeElement) {
if (substitutedType == null) {
//extends/implements list of type parameters: S extends List<T>
final PsiJavaCodeReferenceElement codeReferenceElement = PsiTreeUtil.getTopmostParentOfType(parent, PsiJavaCodeReferenceElement.class);
if (codeReferenceElement != null) {
final PsiJavaCodeReferenceElement copy = (PsiJavaCodeReferenceElement)codeReferenceElement.copy();
final PsiReferenceParameterList parameterList = copy.getParameterList();
if (parameterList != null) {
parameterList.delete();
}
replacement.put(codeReferenceElement, copy);
}
else {
//nested types List<List<T> listOfLists;
PsiTypeElement topPsiTypeElement = PsiTreeUtil.getTopmostParentOfType(parent, PsiTypeElement.class);
if (topPsiTypeElement == null) {
topPsiTypeElement = (PsiTypeElement)parent;
}
replacement.put(topPsiTypeElement, factory.createTypeElement(TypeConversionUtil.erasure(topPsiTypeElement.getType())));
}
}
else {
replacement.put(parent, factory.createTypeElement(substitutedType));
}
}
else if (element instanceof PsiJavaCodeReferenceElement && erasedType instanceof PsiClassType) {
replacement.put(element, factory.createReferenceElementByType((PsiClassType)erasedType));
}
}
}
for (PsiElement element : replacement.keySet()) {
if (element.isValid()) {
element.replace(replacement.get(element));
}
}
}
public static void renameConflictingTypeParameters(PsiMember memberCopy, PsiClass targetClass) {
if (memberCopy instanceof PsiTypeParameterListOwner && !memberCopy.hasModifierProperty(PsiModifier.STATIC)) {
UniqueNameGenerator nameGenerator = new UniqueNameGenerator();
PsiUtil.typeParametersIterable(targetClass).forEach(param -> {
String paramName = param.getName();
if (paramName != null) {
nameGenerator.addExistingName(paramName);
}
});
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
PsiElementFactory factory = JavaPsiFacade.getElementFactory(memberCopy.getProject());
for (PsiTypeParameter parameter : ((PsiTypeParameterListOwner)memberCopy).getTypeParameters()) {
String parameterName = parameter.getName();
if (parameterName == null) continue;
if (!nameGenerator.isUnique(parameterName)) {
substitutor = substitutor.put(parameter, PsiSubstitutor.EMPTY.substitute(factory.createTypeParameter(nameGenerator.generateUniqueName(parameterName), PsiClassType.EMPTY_ARRAY)));
}
}
if (!PsiSubstitutor.EMPTY.equals(substitutor)) {
replaceMovedMemberTypeParameters(memberCopy, PsiUtil.typeParametersIterable((PsiTypeParameterListOwner)memberCopy), substitutor, factory);//rename usages in the method
for (Map.Entry<PsiTypeParameter, PsiType> entry : substitutor.getSubstitutionMap().entrySet()) {
entry.getKey().setName(entry.getValue().getCanonicalText()); //rename declaration after all usages renamed
}
}
}
}
@Nullable
public static PsiMethod getChainedConstructor(PsiMethod constructor) {
final PsiCodeBlock constructorBody = constructor.getBody();
if (constructorBody == null) return null;
final PsiStatement[] statements = constructorBody.getStatements();
if (statements.length == 1 && statements[0] instanceof PsiExpressionStatement) {
final PsiExpression expression = ((PsiExpressionStatement)statements[0]).getExpression();
if (expression instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression;
final PsiReferenceExpression methodExpr = methodCallExpression.getMethodExpression();
if ("this".equals(methodExpr.getReferenceName())) {
return (PsiMethod)methodExpr.resolve();
}
}
}
return null;
}
public static boolean isInMovedElement(PsiElement element, Set<? extends PsiMember> membersToMove) {
for (PsiMember member : membersToMove) {
if (PsiTreeUtil.isAncestor(member, element, false)) return true;
}
return false;
}
public static boolean inImportStatement(PsiReference ref, PsiElement element) {
if (PsiTreeUtil.getParentOfType(element, PsiImportStatement.class) != null) return true;
final PsiFile containingFile = element.getContainingFile();
if (containingFile instanceof PsiJavaFile) {
final PsiImportList importList = ((PsiJavaFile)containingFile).getImportList();
if (importList != null) {
final TextRange refRange = ref.getRangeInElement().shiftRight(element.getTextRange().getStartOffset());
for (PsiImportStatementBase importStatementBase : importList.getAllImportStatements()) {
final TextRange textRange = importStatementBase.getTextRange();
if (textRange.contains(refRange)) {
return true;
}
}
}
}
return false;
}
public static PsiStatement putStatementInLoopBody(PsiStatement declaration,
PsiElement container,
PsiElement finalAnchorStatement) throws IncorrectOperationException {
return putStatementInLoopBody(declaration, container, finalAnchorStatement, false);
}
public static PsiStatement putStatementInLoopBody(PsiStatement declaration,
PsiElement container,
PsiElement finalAnchorStatement,
boolean replaceBody)
throws IncorrectOperationException {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(container.getProject());
if(isLoopOrIf(container)) {
PsiStatement loopBody = getLoopBody(container, finalAnchorStatement);
PsiStatement loopBodyCopy = loopBody != null ? (PsiStatement) loopBody.copy() : null;
PsiBlockStatement blockStatement = (PsiBlockStatement)elementFactory
.createStatementFromText("{}", null);
blockStatement = (PsiBlockStatement) CodeStyleManager.getInstance(container.getProject()).reformat(blockStatement);
final PsiElement prevSibling = loopBody.getPrevSibling();
if(prevSibling instanceof PsiWhiteSpace) {
final PsiElement pprev = prevSibling.getPrevSibling();
if (!(pprev instanceof PsiComment) || !((PsiComment)pprev).getTokenType().equals(JavaTokenType.END_OF_LINE_COMMENT)) {
prevSibling.delete();
}
}
blockStatement = (PsiBlockStatement) loopBody.replace(blockStatement);
final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
declaration = (PsiStatement) codeBlock.add(declaration);
JavaCodeStyleManager.getInstance(declaration.getProject()).shortenClassReferences(declaration);
if (loopBodyCopy != null && !replaceBody) codeBlock.add(loopBodyCopy);
} else if (container instanceof PsiLambdaExpression) {
PsiLambdaExpression lambdaExpression = (PsiLambdaExpression)container;
final PsiElement invalidBody = lambdaExpression.getBody();
if (invalidBody == null) return declaration;
String lambdaParamListWithArrowAndComments = lambdaExpression.getText()
.substring(0, (declaration.isPhysical() ? declaration : invalidBody).getStartOffsetInParent());
final PsiLambdaExpression expressionFromText = (PsiLambdaExpression)elementFactory.createExpressionFromText(lambdaParamListWithArrowAndComments + "{}", lambdaExpression.getParent());
PsiCodeBlock newBody = (PsiCodeBlock)expressionFromText.getBody();
LOG.assertTrue(newBody != null);
newBody.add(declaration);
final PsiElement lambdaExpressionBody = lambdaExpression.getBody();
LOG.assertTrue(lambdaExpressionBody != null);
final PsiStatement lastBodyStatement;
if (PsiType.VOID.equals(LambdaUtil.getFunctionalInterfaceReturnType(lambdaExpression))) {
if (replaceBody) {
lastBodyStatement = null;
} else {
lastBodyStatement = elementFactory.createStatementFromText("a;", lambdaExpression);
((PsiExpressionStatement)lastBodyStatement).getExpression().replace(lambdaExpressionBody);
}
}
else {
lastBodyStatement = elementFactory.createStatementFromText("return a;", lambdaExpression);
final PsiExpression returnValue = ((PsiReturnStatement)lastBodyStatement).getReturnValue();
LOG.assertTrue(returnValue != null);
returnValue.replace(lambdaExpressionBody);
}
if (lastBodyStatement != null) {
newBody.add(lastBodyStatement);
}
final PsiLambdaExpression copy = (PsiLambdaExpression)lambdaExpression.replace(expressionFromText);
newBody = (PsiCodeBlock)copy.getBody();
LOG.assertTrue(newBody != null);
declaration = newBody.getStatements()[0];
declaration = (PsiStatement)JavaCodeStyleManager.getInstance(declaration.getProject()).shortenClassReferences(declaration);
}
return declaration;
}
@Nullable
private static PsiStatement getLoopBody(PsiElement container, PsiElement anchorStatement) {
if(container instanceof PsiLoopStatement) {
return ((PsiLoopStatement) container).getBody();
}
else if (container instanceof PsiIfStatement) {
final PsiStatement thenBranch = ((PsiIfStatement)container).getThenBranch();
if (thenBranch != null && PsiTreeUtil.isAncestor(thenBranch, anchorStatement, false)) {
return thenBranch;
}
final PsiStatement elseBranch = ((PsiIfStatement)container).getElseBranch();
if (elseBranch != null && PsiTreeUtil.isAncestor(elseBranch, anchorStatement, false)) {
return elseBranch;
}
LOG.assertTrue(false);
}
LOG.assertTrue(false);
return null;
}
public static boolean isLoopOrIf(PsiElement element) {
return element instanceof PsiLoopStatement || element instanceof PsiIfStatement;
}
public static PsiCodeBlock expandExpressionLambdaToCodeBlock(@NotNull PsiLambdaExpression lambdaExpression) {
final PsiElement body = lambdaExpression.getBody();
if (!(body instanceof PsiExpression)) return (PsiCodeBlock)body;
String newLambdaText = "{";
if (!PsiType.VOID.equals(LambdaUtil.getFunctionalInterfaceReturnType(lambdaExpression))) newLambdaText += "return ";
newLambdaText += "a;}";
final Project project = lambdaExpression.getProject();
final PsiCodeBlock codeBlock = JavaPsiFacade.getElementFactory(project).createCodeBlockFromText(newLambdaText, lambdaExpression);
PsiStatement statement = codeBlock.getStatements()[0];
if (statement instanceof PsiReturnStatement) {
PsiExpression value = ((PsiReturnStatement)statement).getReturnValue();
LOG.assertTrue(value != null);
value.replace(body);
}
else if (statement instanceof PsiExpressionStatement){
((PsiExpressionStatement)statement).getExpression().replace(body);
}
PsiElement arrow = PsiTreeUtil.skipWhitespacesBackward(body);
if (arrow != null && arrow.getNextSibling() != body) {
lambdaExpression.deleteChildRange(arrow.getNextSibling(), body.getPrevSibling());
}
return (PsiCodeBlock)CodeStyleManager.getInstance(project).reformat(body.replace(codeBlock));
}
public static String checkEnumConstantInSwitchLabel(PsiExpression expr) {
if (PsiImplUtil.getSwitchLabel(expr) != null) {
PsiReferenceExpression ref = ObjectUtils.tryCast(PsiUtil.skipParenthesizedExprDown(expr), PsiReferenceExpression.class);
if (ref != null && ref.resolve() instanceof PsiEnumConstant) {
return RefactoringBundle.getCannotRefactorMessage(JavaRefactoringBundle.message("refactoring.introduce.variable.enum.in.label.message"));
}
}
return null;
}
public interface ImplicitConstructorUsageVisitor {
void visitConstructor(PsiMethod constructor, PsiMethod baseConstructor);
void visitClassWithoutConstructors(PsiClass aClass);
}
public interface Graph<T> {
Set<T> getVertices();
Set<T> getTargets(T source);
}
/**
* Returns subset of {@code graph.getVertices()} that is a transitive closure (by <code>graph.getTargets()<code>)
* of the following property: initialRelation.value() of vertex or {@code graph.getTargets(vertex)} is true.
* <p/>
* Note that {@code graph.getTargets()} is not necessarily a subset of {@code graph.getVertex()}
*
* @param graph
* @param initialRelation
* @return subset of graph.getVertices()
*/
public static <T> Set<T> transitiveClosure(Graph<T> graph, Condition<? super T> initialRelation) {
Set<T> result = new HashSet<>();
final Set<T> vertices = graph.getVertices();
boolean anyChanged;
do {
anyChanged = false;
for (T currentVertex : vertices) {
if (!result.contains(currentVertex)) {
if (!initialRelation.value(currentVertex)) {
Set<T> targets = graph.getTargets(currentVertex);
for (T currentTarget : targets) {
if (result.contains(currentTarget) || initialRelation.value(currentTarget)) {
result.add(currentVertex);
anyChanged = true;
break;
}
}
}
else {
result.add(currentVertex);
}
}
}
}
while (anyChanged);
return result;
}
public static boolean equivalentTypes(PsiType t1, PsiType t2, PsiManager manager) {
while (t1 instanceof PsiArrayType) {
if (!(t2 instanceof PsiArrayType)) return false;
t1 = ((PsiArrayType)t1).getComponentType();
t2 = ((PsiArrayType)t2).getComponentType();
}
if (t1 instanceof PsiPrimitiveType) {
return t2 instanceof PsiPrimitiveType && t1.equals(t2);
}
return manager.areElementsEquivalent(PsiUtil.resolveClassInType(t1), PsiUtil.resolveClassInType(t2));
}
public static List<PsiVariable> collectReferencedVariables(PsiElement scope) {
final List<PsiVariable> result = new ArrayList<>();
scope.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement element = expression.resolve();
if (element instanceof PsiVariable) {
result.add((PsiVariable)element);
}
final PsiExpression qualifier = expression.getQualifierExpression();
if (qualifier != null) {
qualifier.accept(this);
}
}
});
return result;
}
public static boolean isModifiedInScope(PsiVariable variable, PsiElement scope) {
for (PsiReference reference : ReferencesSearch.search(variable, new LocalSearchScope(scope), false)) {
if (isAssignmentLHS(reference.getElement())) return true;
}
return false;
}
private static String getNameOfReferencedParameter(PsiDocTag tag) {
LOG.assertTrue("param".equals(tag.getName()));
final PsiElement[] dataElements = tag.getDataElements();
if (dataElements.length < 1) return null;
return dataElements[0].getText();
}
public static void fixJavadocsForParams(PsiMethod method, Set<? extends PsiParameter> newParameters) throws IncorrectOperationException {
fixJavadocsForParams(method, newParameters, Conditions.alwaysFalse());
}
public static void fixJavadocsForParams(PsiMethod method,
Set<? extends PsiParameter> newParameters,
Condition<? super Pair<PsiParameter, String>> eqCondition) throws IncorrectOperationException {
fixJavadocsForParams(method, newParameters, eqCondition, Conditions.alwaysTrue());
}
public static void fixJavadocsForParams(@NotNull PsiMethod method,
@NotNull Set<? extends PsiParameter> newParameters,
@NotNull Condition<? super Pair<PsiParameter, String>> eqCondition,
@NotNull Condition<? super String> matchedToOldParam) throws IncorrectOperationException {
fixJavadocsForParams(method, method.getDocComment(), newParameters, eqCondition, matchedToOldParam);
}
public static void fixJavadocsForParams(@NotNull PsiMethod method,
@Nullable PsiDocComment docComment,
@NotNull Set<? extends PsiParameter> newParameters,
@NotNull Condition<? super Pair<PsiParameter, String>> eqCondition,
@NotNull Condition<? super String> matchedToOldParam) throws IncorrectOperationException {
if (docComment == null) return;
final PsiParameter[] parameters = method.getParameterList().getParameters();
final PsiDocTag[] paramTags = docComment.findTagsByName("param");
if (parameters.length > 0 && newParameters.size() < parameters.length && paramTags.length == 0) return;
Map<PsiParameter, PsiDocTag> tagForParam = new HashMap<>();
for (PsiParameter parameter : parameters) {
boolean found = false;
for (PsiDocTag paramTag : paramTags) {
if (parameter.getName().equals(getNameOfReferencedParameter(paramTag))) {
tagForParam.put(parameter, paramTag);
found = true;
break;
}
}
if (!found) {
for (PsiDocTag paramTag : paramTags) {
final String paramName = getNameOfReferencedParameter(paramTag);
if (eqCondition.value(Pair.create(parameter, paramName))) {
tagForParam.put(parameter, paramTag);
found = true;
break;
}
}
}
if (!found && !newParameters.contains(parameter)) {
tagForParam.put(parameter, null);
}
}
List<PsiDocTag> newTags = new ArrayList<>();
for (PsiDocTag paramTag : paramTags) {
final String paramName = getNameOfReferencedParameter(paramTag);
if (!tagForParam.containsValue(paramTag) && !matchedToOldParam.value(paramName)) {
newTags.add((PsiDocTag)paramTag.copy());
}
}
for (PsiParameter parameter : parameters) {
if (tagForParam.containsKey(parameter)) {
final PsiDocTag psiDocTag = tagForParam.get(parameter);
if (psiDocTag != null) {
final PsiDocTag copy = (PsiDocTag)psiDocTag.copy();
final PsiDocTagValue valueElement = copy.getValueElement();
if (valueElement != null) {
valueElement.replace(createParamTag(parameter).getValueElement());
}
newTags.add(copy);
}
}
else {
newTags.add(createParamTag(parameter));
}
}
PsiElement anchor = paramTags.length > 0 ? paramTags[0].getPrevSibling() : null;
for (PsiDocTag paramTag : paramTags) {
paramTag.delete();
}
for (PsiDocTag psiDocTag : newTags) {
anchor = anchor != null && anchor.isValid() ? docComment.addAfter(psiDocTag, anchor) : docComment.add(psiDocTag);
}
}
@NotNull
private static PsiDocTag createParamTag(@NotNull PsiParameter parameter) {
return JavaPsiFacade.getElementFactory(parameter.getProject()).createParamTag(parameter.getName(), "");
}
@NotNull
public static PsiDirectory createPackageDirectoryInSourceRoot(@NotNull PackageWrapper aPackage, @NotNull final VirtualFile sourceRoot)
throws IncorrectOperationException {
PsiDirectory[] existing = aPackage.getDirectories(
GlobalSearchScopes.directoryScope(aPackage.getManager().getProject(), sourceRoot, true));
if (existing.length > 0) {
return existing[0];
}
String qNameToCreate = qNameToCreateInSourceRoot(aPackage, sourceRoot);
PsiDirectory current = aPackage.getManager().findDirectory(sourceRoot);
LOG.assertTrue(current != null);
if (qNameToCreate.isEmpty()) {
return current;
}
final String[] shortNames = qNameToCreate.split("\\.");
for (String shortName : shortNames) {
PsiDirectory subdirectory = current.findSubdirectory(shortName);
if (subdirectory == null) {
subdirectory = current.createSubdirectory(shortName);
}
current = subdirectory;
}
return current;
}
public static String qNameToCreateInSourceRoot(PackageWrapper aPackage, final VirtualFile sourceRoot) throws IncorrectOperationException {
String targetQName = aPackage.getQualifiedName();
String sourceRootPackage =
ProjectRootManager.getInstance(aPackage.getManager().getProject()).getFileIndex().getPackageNameByDirectory(sourceRoot);
if (!canCreateInSourceRoot(sourceRootPackage, targetQName)) {
throw new IncorrectOperationException(
"Cannot create package '" + targetQName + "' in source folder " + sourceRoot.getPresentableUrl());
}
String result = targetQName.substring(sourceRootPackage.length());
if (StringUtil.startsWithChar(result, '.')) result = result.substring(1); // remove initial '.'
return result;
}
public static boolean canCreateInSourceRoot(final String sourceRootPackage, final String targetQName) {
if (sourceRootPackage == null || !targetQName.startsWith(sourceRootPackage)) return false;
if (sourceRootPackage.isEmpty() || targetQName.length() == sourceRootPackage.length()) return true;
return targetQName.charAt(sourceRootPackage.length()) == '.';
}
@Nullable
public static PsiDirectory findPackageDirectoryInSourceRoot(PackageWrapper aPackage, final VirtualFile sourceRoot) {
final PsiDirectory[] directories = aPackage.getDirectories();
for (PsiDirectory directory : directories) {
if (VfsUtilCore.isAncestor(sourceRoot, directory.getVirtualFile(), false)) {
return directory;
}
}
String qNameToCreate;
try {
qNameToCreate = qNameToCreateInSourceRoot(aPackage, sourceRoot);
}
catch (IncorrectOperationException e) {
return null;
}
final String[] shortNames = qNameToCreate.split("\\.");
PsiDirectory current = aPackage.getManager().findDirectory(sourceRoot);
LOG.assertTrue(current != null);
for (String shortName : shortNames) {
PsiDirectory subdirectory = current.findSubdirectory(shortName);
if (subdirectory == null) {
return null;
}
current = subdirectory;
}
return current;
}
public static class ConditionCache<T> implements Condition<T> {
private final Condition<? super T> myCondition;
private final HashSet<T> myProcessedSet = new HashSet<>();
private final HashSet<T> myTrueSet = new HashSet<>();
public ConditionCache(Condition<? super T> condition) {
myCondition = condition;
}
@Override
public boolean value(T object) {
if (!myProcessedSet.contains(object)) {
myProcessedSet.add(object);
final boolean value = myCondition.value(object);
if (value) {
myTrueSet.add(object);
return true;
}
return false;
}
return myTrueSet.contains(object);
}
}
public static class IsDescendantOf implements Condition<PsiClass> {
private final PsiClass myClass;
private final ConditionCache<PsiClass> myConditionCache;
public IsDescendantOf(PsiClass aClass) {
myClass = aClass;
myConditionCache = new ConditionCache<>(aClass1 -> InheritanceUtil.isInheritorOrSelf(aClass1, myClass, true));
}
@Override
public boolean value(PsiClass aClass) {
return myConditionCache.value(aClass);
}
}
@Nullable
public static PsiTypeParameterList createTypeParameterListWithUsedTypeParameters(final PsiElement @NotNull ... elements) {
return createTypeParameterListWithUsedTypeParameters(null, elements);
}
@Nullable
public static PsiTypeParameterList createTypeParameterListWithUsedTypeParameters(@Nullable final PsiTypeParameterList fromList,
final PsiElement @NotNull ... elements) {
return createTypeParameterListWithUsedTypeParameters(fromList, Conditions.alwaysTrue(), elements);
}
@Nullable
public static PsiTypeParameterList createTypeParameterListWithUsedTypeParameters(@Nullable final PsiTypeParameterList fromList,
Condition<? super PsiTypeParameter> filter,
final PsiElement @NotNull ... elements) {
if (elements.length == 0) return null;
final Set<PsiTypeParameter> used = new HashSet<>();
for (final PsiElement element : elements) {
if (element == null) continue;
collectTypeParameters(used, element, filter); //pull up extends cls class with type params
}
collectTypeParametersInDependencies(filter, used);
if (fromList != null) {
used.retainAll(Arrays.asList(fromList.getTypeParameters()));
}
PsiTypeParameter[] typeParameters = used.toArray(PsiTypeParameter.EMPTY_ARRAY);
Arrays.sort(typeParameters, Comparator.comparingInt(tp -> tp.getTextRange().getStartOffset()));
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(elements[0].getProject());
try {
final PsiClass aClass = elementFactory.createClassFromText("class A {}", null);
PsiTypeParameterList list = aClass.getTypeParameterList();
assert list != null;
for (final PsiTypeParameter typeParameter : typeParameters) {
list.add(typeParameter);
}
return list;
}
catch (IncorrectOperationException e) {
LOG.error(e);
assert false;
return null;
}
}
private static void collectTypeParametersInDependencies(Condition<? super PsiTypeParameter> filter, Set<PsiTypeParameter> used) {
Stack<PsiTypeParameter> toProcess = new Stack<>();
toProcess.addAll(used);
while (!toProcess.isEmpty()) {
PsiTypeParameter parameter = toProcess.pop();
HashSet<PsiTypeParameter> dependencies = new HashSet<>();
collectTypeParameters(dependencies, parameter, param -> filter.value(param) && !used.contains(param));
used.addAll(dependencies);
toProcess.addAll(dependencies);
}
}
public static void collectTypeParameters(final Set<? super PsiTypeParameter> used, final PsiElement element) {
collectTypeParameters(used, element, Conditions.alwaysTrue());
}
public static void collectTypeParameters(final Set<? super PsiTypeParameter> used, final PsiElement element,
final Condition<? super PsiTypeParameter> filter) {
element.accept(new JavaRecursiveElementVisitor() {
@Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
super.visitReferenceElement(reference);
if (!reference.isQualified()) {
final PsiElement resolved = reference.resolve();
if (resolved instanceof PsiTypeParameter) {
final PsiTypeParameter typeParameter = (PsiTypeParameter)resolved;
if (PsiTreeUtil.isAncestor(typeParameter.getOwner(), element, false) && filter.value(typeParameter)) {
used.add(typeParameter);
}
}
}
}
@Override
public void visitExpression(final PsiExpression expression) {
super.visitExpression(expression);
final PsiType type = expression.getType();
if (type != null) {
final PsiTypesUtil.TypeParameterSearcher searcher = new PsiTypesUtil.TypeParameterSearcher();
type.accept(searcher);
for (PsiTypeParameter typeParam : searcher.getTypeParameters()) {
if (PsiTreeUtil.isAncestor(typeParam.getOwner(), element, false) && filter.value(typeParam)){
used.add(typeParam);
}
}
}
}
});
}
}
| java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.util;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.ExpectedTypesProvider;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil;
import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.java.refactoring.JavaRefactoringBundle;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.impl.PsiImplUtil;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.search.GlobalSearchScopes;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.*;
import com.intellij.refactoring.PackageWrapper;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.introduceField.ElementToWorkOn;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.Stack;
import com.intellij.util.text.UniqueNameGenerator;
import gnu.trove.THashMap;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public final class RefactoringUtil {
private static final Logger LOG = Logger.getInstance(RefactoringUtil.class);
public static final int EXPR_COPY_SAFE = 0;
public static final int EXPR_COPY_UNSAFE = 1;
public static final int EXPR_COPY_PROHIBITED = 2;
private RefactoringUtil() {
}
public static boolean isSourceRoot(final PsiDirectory directory) {
if (directory.getManager() == null) return false;
final Project project = directory.getProject();
final VirtualFile virtualFile = directory.getVirtualFile();
final VirtualFile sourceRootForFile = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(virtualFile);
return Comparing.equal(virtualFile, sourceRootForFile);
}
public static boolean isInStaticContext(PsiElement element, @Nullable final PsiClass aClass) {
return PsiUtil.getEnclosingStaticElement(element, aClass) != null;
}
/**
* @deprecated use {@link PsiTypesUtil#hasUnresolvedComponents(PsiType)}
*/
@Deprecated
public static boolean isResolvableType(PsiType type) {
return !PsiTypesUtil.hasUnresolvedComponents(type);
}
public static PsiElement replaceOccurenceWithFieldRef(PsiExpression occurrence, PsiField newField, PsiClass destinationClass)
throws IncorrectOperationException {
final PsiManager manager = destinationClass.getManager();
final String fieldName = newField.getName();
final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
final PsiElement element = occurrence.getUserData(ElementToWorkOn.PARENT);
final PsiVariable psiVariable = facade.getResolveHelper().resolveAccessibleReferencedVariable(fieldName, element != null ? element : occurrence);
final PsiElementFactory factory = facade.getElementFactory();
if (psiVariable != null && psiVariable.equals(newField)) {
return IntroduceVariableBase.replace(occurrence, factory.createExpressionFromText(fieldName, null), manager.getProject());
}
else {
final PsiReferenceExpression ref = (PsiReferenceExpression)factory.createExpressionFromText("this." + fieldName, null);
if (!occurrence.isValid()) return null;
if (newField.hasModifierProperty(PsiModifier.STATIC)) {
ref.setQualifierExpression(factory.createReferenceExpression(destinationClass));
}
return IntroduceVariableBase.replace(occurrence, ref, manager.getProject());
}
}
/**
* @see JavaCodeStyleManager#suggestUniqueVariableName(String, PsiElement, boolean)
* Cannot use method from code style manager: a collision with fieldToReplace is not a collision
*/
public static String suggestUniqueVariableName(String baseName, PsiElement place, PsiField fieldToReplace) {
for(int index = 0;;index++) {
final String name = index > 0 ? baseName + index : baseName;
final PsiManager manager = place.getManager();
PsiResolveHelper helper = JavaPsiFacade.getInstance(manager.getProject()).getResolveHelper();
PsiVariable refVar = helper.resolveAccessibleReferencedVariable(name, place);
if (refVar != null && !manager.areElementsEquivalent(refVar, fieldToReplace)) continue;
final boolean[] found = {false};
place.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitClass(PsiClass aClass) {
}
@Override
public void visitVariable(PsiVariable variable) {
if (name.equals(variable.getName())) {
found[0] = true;
stopWalking();
}
}
});
if (found[0]) {
continue;
}
return name;
}
}
@Nullable
public static String suggestNewOverriderName(String oldOverriderName, String oldBaseName, String newBaseName) {
if (oldOverriderName.equals(oldBaseName)) {
return newBaseName;
}
int i;
if (oldOverriderName.startsWith(oldBaseName)) {
i = 0;
}
else {
i = StringUtil.indexOfIgnoreCase(oldOverriderName, oldBaseName, 0);
}
if (i >= 0) {
String newOverriderName = oldOverriderName.substring(0, i);
if (Character.isUpperCase(oldOverriderName.charAt(i))) {
newOverriderName += StringUtil.capitalize(newBaseName);
}
else {
newOverriderName += newBaseName;
}
final int j = i + oldBaseName.length();
if (j < oldOverriderName.length()) {
newOverriderName += oldOverriderName.substring(j);
}
return newOverriderName;
}
return null;
}
public static boolean hasOnDemandStaticImport(final PsiElement element, final PsiClass aClass) {
if (element.getContainingFile() instanceof PsiJavaFile) {
final PsiImportList importList = ((PsiJavaFile)element.getContainingFile()).getImportList();
if (importList != null) {
final PsiImportStaticStatement[] importStaticStatements = importList.getImportStaticStatements();
return Arrays.stream(importStaticStatements).anyMatch(stmt -> stmt.isOnDemand() && stmt.resolveTargetClass() == aClass);
}
}
return false;
}
public static PsiElement replaceElementsWithMap(PsiElement replaceIn, final Map<PsiElement, PsiElement> elementsToReplace) throws IncorrectOperationException {
for(Map.Entry<PsiElement, PsiElement> e: elementsToReplace.entrySet()) {
if (e.getKey() == replaceIn) {
return e.getKey().replace(e.getValue());
}
e.getKey().replace(e.getValue());
}
return replaceIn;
}
public static PsiElement getVariableScope(PsiLocalVariable localVar) {
if (!(localVar instanceof ImplicitVariable)) {
return localVar.getParent().getParent();
}
else {
return ((ImplicitVariable)localVar).getDeclarationScope();
}
}
@Nullable
public static PsiElement getParentStatement(@Nullable PsiElement place, boolean skipScopingStatements) {
PsiElement parent = place;
while (true) {
if (parent == null) return null;
if (parent instanceof PsiStatement) break;
if (parent instanceof PsiExpression && parent.getParent() instanceof PsiLambdaExpression) return parent;
parent = parent.getParent();
}
PsiElement parentStatement = parent;
while (parent instanceof PsiStatement && !(parent instanceof PsiSwitchLabeledRuleStatement)) {
if (!skipScopingStatements && ((parent instanceof PsiForStatement && parentStatement == ((PsiForStatement)parent).getBody()) || (
parent instanceof PsiForeachStatement && parentStatement == ((PsiForeachStatement)parent).getBody()) || (
parent instanceof PsiWhileStatement && parentStatement == ((PsiWhileStatement)parent).getBody()) || (
parent instanceof PsiIfStatement &&
(parentStatement == ((PsiIfStatement)parent).getThenBranch() || parentStatement == ((PsiIfStatement)parent).getElseBranch())))) {
return parentStatement;
}
parentStatement = parent;
parent = parent.getParent();
}
return parentStatement;
}
public static PsiElement getParentExpressionAnchorElement(PsiElement place) {
PsiElement parent = place.getUserData(ElementToWorkOn.PARENT);
if (place.getUserData(ElementToWorkOn.OUT_OF_CODE_BLOCK) != null) return parent;
if (parent == null) parent = place;
while (true) {
if (isExpressionAnchorElement(parent)) return parent;
if (parent instanceof PsiExpression && parent.getParent() instanceof PsiLambdaExpression) return parent;
parent = parent.getParent();
if (parent == null) return null;
}
}
public static boolean isExpressionAnchorElement(PsiElement element) {
if (element instanceof PsiDeclarationStatement && element.getParent() instanceof PsiForStatement) return false;
return element instanceof PsiStatement || element instanceof PsiClassInitializer || element instanceof PsiField ||
element instanceof PsiMethod;
}
/**
* @param expression
* @return loop body if expression is part of some loop's condition or for loop's increment part
* null otherwise
*/
public static PsiElement getLoopForLoopCondition(PsiExpression expression) {
PsiExpression outermost = expression;
while (outermost.getParent() instanceof PsiExpression) {
outermost = (PsiExpression)outermost.getParent();
}
if (outermost.getParent() instanceof PsiForStatement) {
final PsiForStatement forStatement = (PsiForStatement)outermost.getParent();
if (forStatement.getCondition() == outermost) {
return forStatement;
}
else {
return null;
}
}
if (outermost.getParent() instanceof PsiExpressionStatement && outermost.getParent().getParent() instanceof PsiForStatement) {
final PsiForStatement forStatement = (PsiForStatement)outermost.getParent().getParent();
if (forStatement.getUpdate() == outermost.getParent()) {
return forStatement;
}
else {
return null;
}
}
if (outermost.getParent() instanceof PsiWhileStatement) {
return outermost.getParent();
}
if (outermost.getParent() instanceof PsiDoWhileStatement) {
return outermost.getParent();
}
return null;
}
public static PsiClass getThisResolveClass(final PsiReferenceExpression place) {
final JavaResolveResult resolveResult = place.advancedResolve(false);
final PsiElement scope = resolveResult.getCurrentFileResolveScope();
if (scope instanceof PsiClass) {
return (PsiClass)scope;
}
return null;
}
public static PsiCall getEnclosingConstructorCall(PsiJavaCodeReferenceElement ref) {
PsiElement parent = ref.getParent();
if (ref instanceof PsiReferenceExpression && parent instanceof PsiMethodCallExpression) return (PsiCall)parent;
if (parent instanceof PsiAnonymousClass) {
parent = parent.getParent();
}
return parent instanceof PsiNewExpression ? (PsiNewExpression)parent : null;
}
public static PsiMethod getEnclosingMethod(PsiElement element) {
final PsiElement container = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiClass.class, PsiLambdaExpression.class);
return container instanceof PsiMethod ? (PsiMethod)container : null;
}
public static void renameVariableReferences(PsiVariable variable, String newName, SearchScope scope) throws IncorrectOperationException {
renameVariableReferences(variable, newName, scope, false);
}
public static void renameVariableReferences(PsiVariable variable,
String newName,
SearchScope scope,
final boolean ignoreAccessScope) throws IncorrectOperationException {
for (PsiReference reference : ReferencesSearch.search(variable, scope, ignoreAccessScope)) {
reference.handleElementRename(newName);
}
}
public static boolean canBeDeclaredFinal(@NotNull PsiVariable variable) {
LOG.assertTrue(variable instanceof PsiLocalVariable || variable instanceof PsiParameter);
final boolean isReassigned = HighlightControlFlowUtil
.isReassigned(variable, new THashMap<>());
return !isReassigned;
}
/**
* removes a reference to the specified class from the reference list given
*
* @return if removed - a reference to the class or null if there were no references to this class in the reference list
*/
public static PsiJavaCodeReferenceElement removeFromReferenceList(PsiReferenceList refList, PsiClass aClass)
throws IncorrectOperationException {
PsiJavaCodeReferenceElement[] refs = refList.getReferenceElements();
for (PsiJavaCodeReferenceElement ref : refs) {
if (ref.isReferenceTo(aClass)) {
PsiJavaCodeReferenceElement refCopy = (PsiJavaCodeReferenceElement)ref.copy();
ref.delete();
return refCopy;
}
}
return null;
}
public static PsiJavaCodeReferenceElement findReferenceToClass(PsiReferenceList refList, PsiClass aClass) {
PsiJavaCodeReferenceElement[] refs = refList.getReferenceElements();
for (PsiJavaCodeReferenceElement ref : refs) {
if (ref.isReferenceTo(aClass)) {
return ref;
}
}
return null;
}
public static PsiType getTypeByExpressionWithExpectedType(PsiExpression expr) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(expr.getProject());
PsiType typeByExpression = getTypeByExpression(expr, factory);
PsiType type = typeByExpression;
final boolean isFunctionalType = LambdaUtil.notInferredType(type);
PsiType exprType = expr.getType();
final boolean detectConjunct = exprType instanceof PsiIntersectionType ||
exprType instanceof PsiWildcardType && ((PsiWildcardType)exprType).getBound() instanceof PsiIntersectionType ||
exprType instanceof PsiCapturedWildcardType && ((PsiCapturedWildcardType)exprType).getUpperBound() instanceof PsiIntersectionType;
if (type != null && !isFunctionalType && !detectConjunct) {
return type;
}
ExpectedTypeInfo[] expectedTypes = ExpectedTypesProvider.getExpectedTypes(expr, false);
if (expectedTypes.length == 1 || (isFunctionalType || detectConjunct) && expectedTypes.length > 0 ) {
if (typeByExpression != null && Arrays.stream(expectedTypes).anyMatch(typeInfo -> typeByExpression.isAssignableFrom(typeInfo.getType()))) {
return type;
}
type = expectedTypes[0].getType();
if (!type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return type;
}
return detectConjunct ? type : null;
}
public static PsiType getTypeByExpression(PsiExpression expr) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(expr.getProject());
PsiType type = getTypeByExpression(expr, factory);
if (LambdaUtil.notInferredType(type)) {
type = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_OBJECT, expr.getResolveScope());
}
return type;
}
private static PsiType getTypeByExpression(PsiExpression expr, final PsiElementFactory factory) {
PsiType type = RefactoringChangeUtil.getTypeByExpression(expr);
if (PsiType.NULL.equals(type)) {
ExpectedTypeInfo[] infos = ExpectedTypesProvider.getExpectedTypes(expr, false);
if (infos.length > 0) {
type = infos[0].getType();
if (type instanceof PsiPrimitiveType) {
type = infos.length > 1 && !(infos[1].getType() instanceof PsiPrimitiveType) ? infos[1].getType()
: ((PsiPrimitiveType)type).getBoxedType(expr);
}
}
else {
type = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_OBJECT, expr.getResolveScope());
}
}
return type;
}
public static boolean isAssignmentLHS(@NotNull PsiElement element) {
return element instanceof PsiExpression && PsiUtil.isAccessedForWriting((PsiExpression)element);
}
private static void removeFinalParameters(PsiMethod method) throws IncorrectOperationException {
PsiParameterList paramList = method.getParameterList();
PsiParameter[] params = paramList.getParameters();
for (PsiParameter param : params) {
if (param.hasModifierProperty(PsiModifier.FINAL)) {
PsiUtil.setModifierProperty(param, PsiModifier.FINAL, false);
}
}
}
public static PsiElement getAnchorElementForMultipleExpressions(PsiExpression @NotNull [] occurrences, PsiElement scope) {
PsiElement anchor = null;
for (PsiExpression occurrence : occurrences) {
if (scope != null && !PsiTreeUtil.isAncestor(scope, occurrence, false)) {
continue;
}
PsiElement anchor1 = getParentExpressionAnchorElement(occurrence);
if (anchor1 == null) {
if (occurrence.isPhysical()) return null;
continue;
}
if (anchor == null) {
anchor = anchor1;
}
else {
PsiElement commonParent = PsiTreeUtil.findCommonParent(anchor, anchor1);
if (commonParent == null || anchor.getTextRange() == null || anchor1.getTextRange() == null) return null;
PsiElement firstAnchor = anchor.getTextRange().getStartOffset() < anchor1.getTextRange().getStartOffset() ? anchor : anchor1;
if (commonParent.equals(firstAnchor)) {
anchor = firstAnchor;
}
else {
if (commonParent instanceof PsiStatement) {
anchor = commonParent;
}
else {
PsiElement parent = firstAnchor;
while (!parent.getParent().equals(commonParent)) {
parent = parent.getParent();
}
final PsiElement newAnchor = getParentExpressionAnchorElement(parent);
if (newAnchor != null) {
anchor = newAnchor;
}
else {
anchor = parent;
}
}
}
}
}
if (anchor == null) return null;
if (occurrences.length > 1 && anchor.getParent().getParent() instanceof PsiSwitchStatement) {
PsiSwitchStatement switchStatement = (PsiSwitchStatement)anchor.getParent().getParent();
if (switchStatement.getBody().equals(anchor.getParent())) {
int startOffset = occurrences[0].getTextRange().getStartOffset();
int endOffset = occurrences[occurrences.length - 1].getTextRange().getEndOffset();
PsiStatement[] statements = switchStatement.getBody().getStatements();
boolean isInDifferentCases = false;
for (PsiStatement statement : statements) {
if (statement instanceof PsiSwitchLabelStatement) {
int caseOffset = statement.getTextRange().getStartOffset();
if (startOffset < caseOffset && caseOffset < endOffset) {
isInDifferentCases = true;
break;
}
}
}
if (isInDifferentCases) {
anchor = switchStatement;
}
}
}
return anchor;
}
public static boolean isMethodUsage(PsiElement element) {
if (element instanceof PsiEnumConstant) {
return JavaLanguage.INSTANCE.equals(element.getLanguage());
}
if (!(element instanceof PsiJavaCodeReferenceElement)) return false;
PsiElement parent = element.getParent();
if (parent instanceof PsiCall) {
return true;
}
else if (parent instanceof PsiAnonymousClass) {
return element.equals(((PsiAnonymousClass)parent).getBaseClassReference());
}
return false;
}
@Nullable
public static PsiExpressionList getArgumentListByMethodReference(PsiElement ref) {
if (ref instanceof PsiCall) return ((PsiCall)ref).getArgumentList();
PsiElement parent = ref.getParent();
if (parent instanceof PsiCall) {
return ((PsiCall)parent).getArgumentList();
}
else if (parent instanceof PsiAnonymousClass) {
return ((PsiNewExpression)parent.getParent()).getArgumentList();
}
LOG.assertTrue(false);
return null;
}
public static PsiCall getCallExpressionByMethodReference(PsiElement ref) {
if (ref instanceof PsiCall) return (PsiCall)ref;
PsiElement parent = ref.getParent();
if (parent instanceof PsiMethodCallExpression) {
return (PsiMethodCallExpression)parent;
}
else if (parent instanceof PsiNewExpression) {
return (PsiNewExpression)parent;
}
else if (parent instanceof PsiAnonymousClass) {
return (PsiNewExpression)parent.getParent();
}
else {
LOG.assertTrue(false);
return null;
}
}
/**
* @return List of highlighters
*/
public static List<RangeHighlighter> highlightAllOccurrences(Project project, PsiElement[] occurrences, Editor editor) {
ArrayList<RangeHighlighter> highlighters = new ArrayList<>();
HighlightManager highlightManager = HighlightManager.getInstance(project);
if (occurrences.length > 1) {
for (PsiElement occurrence : occurrences) {
final RangeMarker rangeMarker = occurrence.getUserData(ElementToWorkOn.TEXT_RANGE);
if (rangeMarker != null && rangeMarker.isValid()) {
highlightManager.addRangeHighlight(editor, rangeMarker.getStartOffset(), rangeMarker.getEndOffset(),
EditorColors.SEARCH_RESULT_ATTRIBUTES, true, highlighters);
}
else {
final TextRange textRange = occurrence.getTextRange();
highlightManager.addRangeHighlight(editor, textRange.getStartOffset(), textRange.getEndOffset(),
EditorColors.SEARCH_RESULT_ATTRIBUTES, true, highlighters);
}
}
}
return highlighters;
}
public static String createTempVar(PsiExpression expr, PsiElement context, boolean declareFinal) throws IncorrectOperationException {
PsiElement anchorStatement = getParentStatement(context, true);
LOG.assertTrue(anchorStatement != null && anchorStatement.getParent() != null);
Project project = expr.getProject();
String[] suggestedNames =
JavaCodeStyleManager.getInstance(project).suggestVariableName(VariableKind.LOCAL_VARIABLE, null, expr, null).names;
final String prefix = suggestedNames.length > 0 ? suggestedNames[0] : "var";
final String id = JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName(prefix, context, true);
PsiElementFactory factory = JavaPsiFacade.getElementFactory(expr.getProject());
if (expr instanceof PsiParenthesizedExpression) {
PsiExpression expr1 = ((PsiParenthesizedExpression)expr).getExpression();
if (expr1 != null) {
expr = expr1;
}
}
PsiDeclarationStatement decl = factory.createVariableDeclarationStatement(id, expr.getType(), expr);
if (declareFinal) {
PsiUtil.setModifierProperty(((PsiLocalVariable)decl.getDeclaredElements()[0]), PsiModifier.FINAL, true);
}
anchorStatement.getParent().addBefore(decl, anchorStatement);
return id;
}
public static int verifySafeCopyExpression(PsiElement expr) {
return verifySafeCopyExpressionSubElement(expr);
}
private static int verifySafeCopyExpressionSubElement(PsiElement element) {
int result = EXPR_COPY_SAFE;
if (element == null) return result;
if (element instanceof PsiThisExpression || element instanceof PsiSuperExpression || element instanceof PsiIdentifier) {
return EXPR_COPY_SAFE;
}
if (element instanceof PsiMethodCallExpression) {
result = EXPR_COPY_UNSAFE;
}
if (element instanceof PsiNewExpression) {
return EXPR_COPY_PROHIBITED;
}
if (element instanceof PsiAssignmentExpression) {
return EXPR_COPY_PROHIBITED;
}
if (PsiUtil.isIncrementDecrementOperation(element)) {
return EXPR_COPY_PROHIBITED;
}
PsiElement[] children = element.getChildren();
for (PsiElement child : children) {
int childResult = verifySafeCopyExpressionSubElement(child);
result = Math.max(result, childResult);
}
return result;
}
@Contract("null, _ -> null")
public static PsiExpression convertInitializerToNormalExpression(PsiExpression expression, PsiType forcedReturnType)
throws IncorrectOperationException {
if (expression instanceof PsiArrayInitializerExpression && (forcedReturnType == null || forcedReturnType instanceof PsiArrayType)) {
return createNewExpressionFromArrayInitializer((PsiArrayInitializerExpression)expression, forcedReturnType);
}
return expression;
}
public static PsiExpression createNewExpressionFromArrayInitializer(PsiArrayInitializerExpression initializer, PsiType forcedType)
throws IncorrectOperationException {
PsiType initializerType = null;
if (initializer != null) {
if (forcedType != null) {
initializerType = forcedType;
}
else {
initializerType = getTypeByExpression(initializer);
}
}
if (initializerType == null) {
return initializer;
}
LOG.assertTrue(initializerType instanceof PsiArrayType);
PsiElementFactory factory = JavaPsiFacade.getElementFactory(initializer.getProject());
PsiNewExpression result =
(PsiNewExpression)factory.createExpressionFromText("new " + initializerType.getPresentableText() + "{}", null);
result = (PsiNewExpression)CodeStyleManager.getInstance(initializer.getProject()).reformat(result);
PsiArrayInitializerExpression arrayInitializer = result.getArrayInitializer();
LOG.assertTrue(arrayInitializer != null);
arrayInitializer.replace(initializer);
return result;
}
public static void makeMethodAbstract(@NotNull PsiClass targetClass, @NotNull PsiMethod method) throws IncorrectOperationException {
if (!method.hasModifierProperty(PsiModifier.DEFAULT)) {
PsiCodeBlock body = method.getBody();
if (body != null) {
body.delete();
}
PsiUtil.setModifierProperty(method, PsiModifier.ABSTRACT, true);
}
if (!targetClass.isInterface()) {
PsiUtil.setModifierProperty(targetClass, PsiModifier.ABSTRACT, true);
prepareForAbstract(method);
}
else {
prepareForInterface(method);
}
}
public static void makeMethodDefault(@NotNull PsiMethod method) throws IncorrectOperationException {
PsiUtil.setModifierProperty(method, PsiModifier.DEFAULT, !method.hasModifierProperty(PsiModifier.STATIC));
PsiUtil.setModifierProperty(method, PsiModifier.ABSTRACT, false);
prepareForInterface(method);
}
private static void prepareForInterface(PsiMethod method) {
PsiUtil.setModifierProperty(method, PsiModifier.PUBLIC, false);
PsiUtil.setModifierProperty(method, PsiModifier.PRIVATE, false);
PsiUtil.setModifierProperty(method, PsiModifier.PROTECTED, false);
prepareForAbstract(method);
}
private static void prepareForAbstract(PsiMethod method) {
PsiUtil.setModifierProperty(method, PsiModifier.FINAL, false);
PsiUtil.setModifierProperty(method, PsiModifier.SYNCHRONIZED, false);
PsiUtil.setModifierProperty(method, PsiModifier.NATIVE, false);
removeFinalParameters(method);
}
public static boolean isInsideAnonymousOrLocal(PsiElement element, PsiElement upTo) {
for (PsiElement current = element; current != null && current != upTo; current = current.getParent()) {
if (current instanceof PsiAnonymousClass) return true;
if (current instanceof PsiClass && current.getParent() instanceof PsiDeclarationStatement) {
return true;
}
}
return false;
}
public static PsiExpression unparenthesizeExpression(PsiExpression expression) {
while (expression instanceof PsiParenthesizedExpression) {
final PsiExpression innerExpression = ((PsiParenthesizedExpression)expression).getExpression();
if (innerExpression == null) return expression;
expression = innerExpression;
}
return expression;
}
public static PsiExpression outermostParenthesizedExpression(PsiExpression expression) {
while (expression.getParent() instanceof PsiParenthesizedExpression) {
expression = (PsiParenthesizedExpression)expression.getParent();
}
return expression;
}
public static String getNewInnerClassName(PsiClass aClass, String oldInnerClassName, String newName) {
String className = aClass.getName();
if (className == null || !oldInnerClassName.endsWith(className)) return newName;
StringBuilder buffer = new StringBuilder(oldInnerClassName);
buffer.replace(buffer.length() - className.length(), buffer.length(), newName);
return buffer.toString();
}
public static void visitImplicitSuperConstructorUsages(PsiClass subClass,
final ImplicitConstructorUsageVisitor implicitConstructorUsageVisitor,
PsiClass superClass) {
final PsiMethod baseDefaultConstructor = findDefaultConstructor(superClass);
final PsiMethod[] constructors = subClass.getConstructors();
if (constructors.length > 0) {
for (PsiMethod constructor : constructors) {
PsiCodeBlock body = constructor.getBody();
if (body == null) continue;
final PsiStatement[] statements = body.getStatements();
if (statements.length < 1 || !JavaHighlightUtil.isSuperOrThisCall(statements[0], true, true)) {
implicitConstructorUsageVisitor.visitConstructor(constructor, baseDefaultConstructor);
}
}
}
else {
implicitConstructorUsageVisitor.visitClassWithoutConstructors(subClass);
}
}
private static PsiMethod findDefaultConstructor(final PsiClass aClass) {
final PsiMethod[] constructors = aClass.getConstructors();
for (PsiMethod constructor : constructors) {
if (constructor.getParameterList().isEmpty()) return constructor;
}
return null;
}
public static void replaceMovedMemberTypeParameters(final PsiElement member,
final Iterable<? extends PsiTypeParameter> parametersIterable,
final PsiSubstitutor substitutor,
final PsiElementFactory factory) {
final Map<PsiElement, PsiElement> replacement = new LinkedHashMap<>();
for (PsiTypeParameter parameter : parametersIterable) {
final PsiType substitutedType = substitutor.substitute(parameter);
final PsiType erasedType = substitutedType == null ? TypeConversionUtil.erasure(factory.createType(parameter))
: substitutedType;
for (PsiReference reference : ReferencesSearch.search(parameter, new LocalSearchScope(member))) {
final PsiElement element = reference.getElement();
final PsiElement parent = element.getParent();
if (parent instanceof PsiTypeElement) {
if (substitutedType == null) {
//extends/implements list of type parameters: S extends List<T>
final PsiJavaCodeReferenceElement codeReferenceElement = PsiTreeUtil.getTopmostParentOfType(parent, PsiJavaCodeReferenceElement.class);
if (codeReferenceElement != null) {
final PsiJavaCodeReferenceElement copy = (PsiJavaCodeReferenceElement)codeReferenceElement.copy();
final PsiReferenceParameterList parameterList = copy.getParameterList();
if (parameterList != null) {
parameterList.delete();
}
replacement.put(codeReferenceElement, copy);
}
else {
//nested types List<List<T> listOfLists;
PsiTypeElement topPsiTypeElement = PsiTreeUtil.getTopmostParentOfType(parent, PsiTypeElement.class);
if (topPsiTypeElement == null) {
topPsiTypeElement = (PsiTypeElement)parent;
}
replacement.put(topPsiTypeElement, factory.createTypeElement(TypeConversionUtil.erasure(topPsiTypeElement.getType())));
}
}
else {
replacement.put(parent, factory.createTypeElement(substitutedType));
}
}
else if (element instanceof PsiJavaCodeReferenceElement && erasedType instanceof PsiClassType) {
replacement.put(element, factory.createReferenceElementByType((PsiClassType)erasedType));
}
}
}
for (PsiElement element : replacement.keySet()) {
if (element.isValid()) {
element.replace(replacement.get(element));
}
}
}
public static void renameConflictingTypeParameters(PsiMember memberCopy, PsiClass targetClass) {
if (memberCopy instanceof PsiTypeParameterListOwner && !memberCopy.hasModifierProperty(PsiModifier.STATIC)) {
UniqueNameGenerator nameGenerator = new UniqueNameGenerator();
PsiUtil.typeParametersIterable(targetClass).forEach(param -> {
String paramName = param.getName();
if (paramName != null) {
nameGenerator.addExistingName(paramName);
}
});
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
PsiElementFactory factory = JavaPsiFacade.getElementFactory(memberCopy.getProject());
for (PsiTypeParameter parameter : ((PsiTypeParameterListOwner)memberCopy).getTypeParameters()) {
String parameterName = parameter.getName();
if (parameterName == null) continue;
if (!nameGenerator.isUnique(parameterName)) {
substitutor = substitutor.put(parameter, PsiSubstitutor.EMPTY.substitute(factory.createTypeParameter(nameGenerator.generateUniqueName(parameterName), PsiClassType.EMPTY_ARRAY)));
}
}
if (!PsiSubstitutor.EMPTY.equals(substitutor)) {
replaceMovedMemberTypeParameters(memberCopy, PsiUtil.typeParametersIterable((PsiTypeParameterListOwner)memberCopy), substitutor, factory);//rename usages in the method
for (Map.Entry<PsiTypeParameter, PsiType> entry : substitutor.getSubstitutionMap().entrySet()) {
entry.getKey().setName(entry.getValue().getCanonicalText()); //rename declaration after all usages renamed
}
}
}
}
@Nullable
public static PsiMethod getChainedConstructor(PsiMethod constructor) {
final PsiCodeBlock constructorBody = constructor.getBody();
if (constructorBody == null) return null;
final PsiStatement[] statements = constructorBody.getStatements();
if (statements.length == 1 && statements[0] instanceof PsiExpressionStatement) {
final PsiExpression expression = ((PsiExpressionStatement)statements[0]).getExpression();
if (expression instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expression;
final PsiReferenceExpression methodExpr = methodCallExpression.getMethodExpression();
if ("this".equals(methodExpr.getReferenceName())) {
return (PsiMethod)methodExpr.resolve();
}
}
}
return null;
}
public static boolean isInMovedElement(PsiElement element, Set<? extends PsiMember> membersToMove) {
for (PsiMember member : membersToMove) {
if (PsiTreeUtil.isAncestor(member, element, false)) return true;
}
return false;
}
public static boolean inImportStatement(PsiReference ref, PsiElement element) {
if (PsiTreeUtil.getParentOfType(element, PsiImportStatement.class) != null) return true;
final PsiFile containingFile = element.getContainingFile();
if (containingFile instanceof PsiJavaFile) {
final PsiImportList importList = ((PsiJavaFile)containingFile).getImportList();
if (importList != null) {
final TextRange refRange = ref.getRangeInElement().shiftRight(element.getTextRange().getStartOffset());
for (PsiImportStatementBase importStatementBase : importList.getAllImportStatements()) {
final TextRange textRange = importStatementBase.getTextRange();
if (textRange.contains(refRange)) {
return true;
}
}
}
}
return false;
}
public static PsiStatement putStatementInLoopBody(PsiStatement declaration,
PsiElement container,
PsiElement finalAnchorStatement) throws IncorrectOperationException {
return putStatementInLoopBody(declaration, container, finalAnchorStatement, false);
}
public static PsiStatement putStatementInLoopBody(PsiStatement declaration,
PsiElement container,
PsiElement finalAnchorStatement,
boolean replaceBody)
throws IncorrectOperationException {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(container.getProject());
if(isLoopOrIf(container)) {
PsiStatement loopBody = getLoopBody(container, finalAnchorStatement);
PsiStatement loopBodyCopy = loopBody != null ? (PsiStatement) loopBody.copy() : null;
PsiBlockStatement blockStatement = (PsiBlockStatement)elementFactory
.createStatementFromText("{}", null);
blockStatement = (PsiBlockStatement) CodeStyleManager.getInstance(container.getProject()).reformat(blockStatement);
final PsiElement prevSibling = loopBody.getPrevSibling();
if(prevSibling instanceof PsiWhiteSpace) {
final PsiElement pprev = prevSibling.getPrevSibling();
if (!(pprev instanceof PsiComment) || !((PsiComment)pprev).getTokenType().equals(JavaTokenType.END_OF_LINE_COMMENT)) {
prevSibling.delete();
}
}
blockStatement = (PsiBlockStatement) loopBody.replace(blockStatement);
final PsiCodeBlock codeBlock = blockStatement.getCodeBlock();
declaration = (PsiStatement) codeBlock.add(declaration);
JavaCodeStyleManager.getInstance(declaration.getProject()).shortenClassReferences(declaration);
if (loopBodyCopy != null && !replaceBody) codeBlock.add(loopBodyCopy);
} else if (container instanceof PsiLambdaExpression) {
PsiLambdaExpression lambdaExpression = (PsiLambdaExpression)container;
final PsiElement invalidBody = lambdaExpression.getBody();
if (invalidBody == null) return declaration;
String lambdaParamListWithArrowAndComments = lambdaExpression.getText()
.substring(0, (declaration.isPhysical() ? declaration : invalidBody).getStartOffsetInParent());
final PsiLambdaExpression expressionFromText = (PsiLambdaExpression)elementFactory.createExpressionFromText(lambdaParamListWithArrowAndComments + "{}", lambdaExpression.getParent());
PsiCodeBlock newBody = (PsiCodeBlock)expressionFromText.getBody();
LOG.assertTrue(newBody != null);
newBody.add(declaration);
final PsiElement lambdaExpressionBody = lambdaExpression.getBody();
LOG.assertTrue(lambdaExpressionBody != null);
final PsiStatement lastBodyStatement;
if (PsiType.VOID.equals(LambdaUtil.getFunctionalInterfaceReturnType(lambdaExpression))) {
if (replaceBody) {
lastBodyStatement = null;
} else {
lastBodyStatement = elementFactory.createStatementFromText("a;", lambdaExpression);
((PsiExpressionStatement)lastBodyStatement).getExpression().replace(lambdaExpressionBody);
}
}
else {
lastBodyStatement = elementFactory.createStatementFromText("return a;", lambdaExpression);
final PsiExpression returnValue = ((PsiReturnStatement)lastBodyStatement).getReturnValue();
LOG.assertTrue(returnValue != null);
returnValue.replace(lambdaExpressionBody);
}
if (lastBodyStatement != null) {
newBody.add(lastBodyStatement);
}
final PsiLambdaExpression copy = (PsiLambdaExpression)lambdaExpression.replace(expressionFromText);
newBody = (PsiCodeBlock)copy.getBody();
LOG.assertTrue(newBody != null);
declaration = newBody.getStatements()[0];
declaration = (PsiStatement)JavaCodeStyleManager.getInstance(declaration.getProject()).shortenClassReferences(declaration);
}
return declaration;
}
@Nullable
private static PsiStatement getLoopBody(PsiElement container, PsiElement anchorStatement) {
if(container instanceof PsiLoopStatement) {
return ((PsiLoopStatement) container).getBody();
}
else if (container instanceof PsiIfStatement) {
final PsiStatement thenBranch = ((PsiIfStatement)container).getThenBranch();
if (thenBranch != null && PsiTreeUtil.isAncestor(thenBranch, anchorStatement, false)) {
return thenBranch;
}
final PsiStatement elseBranch = ((PsiIfStatement)container).getElseBranch();
if (elseBranch != null && PsiTreeUtil.isAncestor(elseBranch, anchorStatement, false)) {
return elseBranch;
}
LOG.assertTrue(false);
}
LOG.assertTrue(false);
return null;
}
public static boolean isLoopOrIf(PsiElement element) {
return element instanceof PsiLoopStatement || element instanceof PsiIfStatement;
}
public static PsiCodeBlock expandExpressionLambdaToCodeBlock(@NotNull PsiLambdaExpression lambdaExpression) {
final PsiElement body = lambdaExpression.getBody();
if (!(body instanceof PsiExpression)) return (PsiCodeBlock)body;
String newLambdaText = "{";
if (!PsiType.VOID.equals(LambdaUtil.getFunctionalInterfaceReturnType(lambdaExpression))) newLambdaText += "return ";
newLambdaText += "a;}";
final Project project = lambdaExpression.getProject();
final PsiCodeBlock codeBlock = JavaPsiFacade.getElementFactory(project).createCodeBlockFromText(newLambdaText, lambdaExpression);
PsiStatement statement = codeBlock.getStatements()[0];
if (statement instanceof PsiReturnStatement) {
PsiExpression value = ((PsiReturnStatement)statement).getReturnValue();
LOG.assertTrue(value != null);
value.replace(body);
}
else if (statement instanceof PsiExpressionStatement){
((PsiExpressionStatement)statement).getExpression().replace(body);
}
PsiElement arrow = PsiTreeUtil.skipWhitespacesBackward(body);
if (arrow != null && arrow.getNextSibling() != body) {
lambdaExpression.deleteChildRange(arrow.getNextSibling(), body.getPrevSibling());
}
return (PsiCodeBlock)CodeStyleManager.getInstance(project).reformat(body.replace(codeBlock));
}
public static String checkEnumConstantInSwitchLabel(PsiExpression expr) {
if (PsiImplUtil.getSwitchLabel(expr) != null) {
PsiReferenceExpression ref = ObjectUtils.tryCast(PsiUtil.skipParenthesizedExprDown(expr), PsiReferenceExpression.class);
if (ref != null && ref.resolve() instanceof PsiEnumConstant) {
return RefactoringBundle.getCannotRefactorMessage(JavaRefactoringBundle.message("refactoring.introduce.variable.enum.in.label.message"));
}
}
return null;
}
public interface ImplicitConstructorUsageVisitor {
void visitConstructor(PsiMethod constructor, PsiMethod baseConstructor);
void visitClassWithoutConstructors(PsiClass aClass);
}
public interface Graph<T> {
Set<T> getVertices();
Set<T> getTargets(T source);
}
/**
* Returns subset of {@code graph.getVertices()} that is a transitive closure (by <code>graph.getTargets()<code>)
* of the following property: initialRelation.value() of vertex or {@code graph.getTargets(vertex)} is true.
* <p/>
* Note that {@code graph.getTargets()} is not necessarily a subset of {@code graph.getVertex()}
*
* @param graph
* @param initialRelation
* @return subset of graph.getVertices()
*/
public static <T> Set<T> transitiveClosure(Graph<T> graph, Condition<? super T> initialRelation) {
Set<T> result = new HashSet<>();
final Set<T> vertices = graph.getVertices();
boolean anyChanged;
do {
anyChanged = false;
for (T currentVertex : vertices) {
if (!result.contains(currentVertex)) {
if (!initialRelation.value(currentVertex)) {
Set<T> targets = graph.getTargets(currentVertex);
for (T currentTarget : targets) {
if (result.contains(currentTarget) || initialRelation.value(currentTarget)) {
result.add(currentVertex);
anyChanged = true;
break;
}
}
}
else {
result.add(currentVertex);
}
}
}
}
while (anyChanged);
return result;
}
public static boolean equivalentTypes(PsiType t1, PsiType t2, PsiManager manager) {
while (t1 instanceof PsiArrayType) {
if (!(t2 instanceof PsiArrayType)) return false;
t1 = ((PsiArrayType)t1).getComponentType();
t2 = ((PsiArrayType)t2).getComponentType();
}
if (t1 instanceof PsiPrimitiveType) {
return t2 instanceof PsiPrimitiveType && t1.equals(t2);
}
return manager.areElementsEquivalent(PsiUtil.resolveClassInType(t1), PsiUtil.resolveClassInType(t2));
}
public static List<PsiVariable> collectReferencedVariables(PsiElement scope) {
final List<PsiVariable> result = new ArrayList<>();
scope.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitReferenceExpression(PsiReferenceExpression expression) {
final PsiElement element = expression.resolve();
if (element instanceof PsiVariable) {
result.add((PsiVariable)element);
}
final PsiExpression qualifier = expression.getQualifierExpression();
if (qualifier != null) {
qualifier.accept(this);
}
}
});
return result;
}
public static boolean isModifiedInScope(PsiVariable variable, PsiElement scope) {
for (PsiReference reference : ReferencesSearch.search(variable, new LocalSearchScope(scope), false)) {
if (isAssignmentLHS(reference.getElement())) return true;
}
return false;
}
private static String getNameOfReferencedParameter(PsiDocTag tag) {
LOG.assertTrue("param".equals(tag.getName()));
final PsiElement[] dataElements = tag.getDataElements();
if (dataElements.length < 1) return null;
return dataElements[0].getText();
}
public static void fixJavadocsForParams(PsiMethod method, Set<? extends PsiParameter> newParameters) throws IncorrectOperationException {
fixJavadocsForParams(method, newParameters, Conditions.alwaysFalse());
}
public static void fixJavadocsForParams(PsiMethod method,
Set<? extends PsiParameter> newParameters,
Condition<? super Pair<PsiParameter, String>> eqCondition) throws IncorrectOperationException {
fixJavadocsForParams(method, newParameters, eqCondition, Conditions.alwaysTrue());
}
public static void fixJavadocsForParams(@NotNull PsiMethod method,
@NotNull Set<? extends PsiParameter> newParameters,
@NotNull Condition<? super Pair<PsiParameter, String>> eqCondition,
@NotNull Condition<? super String> matchedToOldParam) throws IncorrectOperationException {
fixJavadocsForParams(method, method.getDocComment(), newParameters, eqCondition, matchedToOldParam);
}
public static void fixJavadocsForParams(@NotNull PsiMethod method,
@Nullable PsiDocComment docComment,
@NotNull Set<? extends PsiParameter> newParameters,
@NotNull Condition<? super Pair<PsiParameter, String>> eqCondition,
@NotNull Condition<? super String> matchedToOldParam) throws IncorrectOperationException {
if (docComment == null) return;
final PsiParameter[] parameters = method.getParameterList().getParameters();
final PsiDocTag[] paramTags = docComment.findTagsByName("param");
if (parameters.length > 0 && newParameters.size() < parameters.length && paramTags.length == 0) return;
Map<PsiParameter, PsiDocTag> tagForParam = new HashMap<>();
for (PsiParameter parameter : parameters) {
boolean found = false;
for (PsiDocTag paramTag : paramTags) {
if (parameter.getName().equals(getNameOfReferencedParameter(paramTag))) {
tagForParam.put(parameter, paramTag);
found = true;
break;
}
}
if (!found) {
for (PsiDocTag paramTag : paramTags) {
final String paramName = getNameOfReferencedParameter(paramTag);
if (eqCondition.value(Pair.create(parameter, paramName))) {
tagForParam.put(parameter, paramTag);
found = true;
break;
}
}
}
if (!found && !newParameters.contains(parameter)) {
tagForParam.put(parameter, null);
}
}
List<PsiDocTag> newTags = new ArrayList<>();
for (PsiDocTag paramTag : paramTags) {
final String paramName = getNameOfReferencedParameter(paramTag);
if (!tagForParam.containsValue(paramTag) && !matchedToOldParam.value(paramName)) {
newTags.add((PsiDocTag)paramTag.copy());
}
}
for (PsiParameter parameter : parameters) {
if (tagForParam.containsKey(parameter)) {
final PsiDocTag psiDocTag = tagForParam.get(parameter);
if (psiDocTag != null) {
final PsiDocTag copy = (PsiDocTag)psiDocTag.copy();
final PsiDocTagValue valueElement = copy.getValueElement();
if (valueElement != null) {
valueElement.replace(createParamTag(parameter).getValueElement());
}
newTags.add(copy);
}
}
else {
newTags.add(createParamTag(parameter));
}
}
PsiElement anchor = paramTags.length > 0 ? paramTags[0].getPrevSibling() : null;
for (PsiDocTag paramTag : paramTags) {
paramTag.delete();
}
for (PsiDocTag psiDocTag : newTags) {
anchor = anchor != null && anchor.isValid() ? docComment.addAfter(psiDocTag, anchor) : docComment.add(psiDocTag);
}
}
@NotNull
private static PsiDocTag createParamTag(@NotNull PsiParameter parameter) {
return JavaPsiFacade.getElementFactory(parameter.getProject()).createParamTag(parameter.getName(), "");
}
@NotNull
public static PsiDirectory createPackageDirectoryInSourceRoot(@NotNull PackageWrapper aPackage, @NotNull final VirtualFile sourceRoot)
throws IncorrectOperationException {
PsiDirectory[] existing = aPackage.getDirectories(
GlobalSearchScopes.directoryScope(aPackage.getManager().getProject(), sourceRoot, true));
if (existing.length > 0) {
return existing[0];
}
String qNameToCreate = qNameToCreateInSourceRoot(aPackage, sourceRoot);
final String[] shortNames = qNameToCreate.split("\\.");
PsiDirectory current = aPackage.getManager().findDirectory(sourceRoot);
LOG.assertTrue(current != null);
for (String shortName : shortNames) {
PsiDirectory subdirectory = current.findSubdirectory(shortName);
if (subdirectory == null) {
subdirectory = current.createSubdirectory(shortName);
}
current = subdirectory;
}
return current;
}
public static String qNameToCreateInSourceRoot(PackageWrapper aPackage, final VirtualFile sourceRoot) throws IncorrectOperationException {
String targetQName = aPackage.getQualifiedName();
String sourceRootPackage =
ProjectRootManager.getInstance(aPackage.getManager().getProject()).getFileIndex().getPackageNameByDirectory(sourceRoot);
if (!canCreateInSourceRoot(sourceRootPackage, targetQName)) {
throw new IncorrectOperationException(
"Cannot create package '" + targetQName + "' in source folder " + sourceRoot.getPresentableUrl());
}
String result = targetQName.substring(sourceRootPackage.length());
if (StringUtil.startsWithChar(result, '.')) result = result.substring(1); // remove initial '.'
return result;
}
public static boolean canCreateInSourceRoot(final String sourceRootPackage, final String targetQName) {
if (sourceRootPackage == null || !targetQName.startsWith(sourceRootPackage)) return false;
if (sourceRootPackage.isEmpty() || targetQName.length() == sourceRootPackage.length()) return true;
return targetQName.charAt(sourceRootPackage.length()) == '.';
}
@Nullable
public static PsiDirectory findPackageDirectoryInSourceRoot(PackageWrapper aPackage, final VirtualFile sourceRoot) {
final PsiDirectory[] directories = aPackage.getDirectories();
for (PsiDirectory directory : directories) {
if (VfsUtilCore.isAncestor(sourceRoot, directory.getVirtualFile(), false)) {
return directory;
}
}
String qNameToCreate;
try {
qNameToCreate = qNameToCreateInSourceRoot(aPackage, sourceRoot);
}
catch (IncorrectOperationException e) {
return null;
}
final String[] shortNames = qNameToCreate.split("\\.");
PsiDirectory current = aPackage.getManager().findDirectory(sourceRoot);
LOG.assertTrue(current != null);
for (String shortName : shortNames) {
PsiDirectory subdirectory = current.findSubdirectory(shortName);
if (subdirectory == null) {
return null;
}
current = subdirectory;
}
return current;
}
public static class ConditionCache<T> implements Condition<T> {
private final Condition<? super T> myCondition;
private final HashSet<T> myProcessedSet = new HashSet<>();
private final HashSet<T> myTrueSet = new HashSet<>();
public ConditionCache(Condition<? super T> condition) {
myCondition = condition;
}
@Override
public boolean value(T object) {
if (!myProcessedSet.contains(object)) {
myProcessedSet.add(object);
final boolean value = myCondition.value(object);
if (value) {
myTrueSet.add(object);
return true;
}
return false;
}
return myTrueSet.contains(object);
}
}
public static class IsDescendantOf implements Condition<PsiClass> {
private final PsiClass myClass;
private final ConditionCache<PsiClass> myConditionCache;
public IsDescendantOf(PsiClass aClass) {
myClass = aClass;
myConditionCache = new ConditionCache<>(aClass1 -> InheritanceUtil.isInheritorOrSelf(aClass1, myClass, true));
}
@Override
public boolean value(PsiClass aClass) {
return myConditionCache.value(aClass);
}
}
@Nullable
public static PsiTypeParameterList createTypeParameterListWithUsedTypeParameters(final PsiElement @NotNull ... elements) {
return createTypeParameterListWithUsedTypeParameters(null, elements);
}
@Nullable
public static PsiTypeParameterList createTypeParameterListWithUsedTypeParameters(@Nullable final PsiTypeParameterList fromList,
final PsiElement @NotNull ... elements) {
return createTypeParameterListWithUsedTypeParameters(fromList, Conditions.alwaysTrue(), elements);
}
@Nullable
public static PsiTypeParameterList createTypeParameterListWithUsedTypeParameters(@Nullable final PsiTypeParameterList fromList,
Condition<? super PsiTypeParameter> filter,
final PsiElement @NotNull ... elements) {
if (elements.length == 0) return null;
final Set<PsiTypeParameter> used = new HashSet<>();
for (final PsiElement element : elements) {
if (element == null) continue;
collectTypeParameters(used, element, filter); //pull up extends cls class with type params
}
collectTypeParametersInDependencies(filter, used);
if (fromList != null) {
used.retainAll(Arrays.asList(fromList.getTypeParameters()));
}
PsiTypeParameter[] typeParameters = used.toArray(PsiTypeParameter.EMPTY_ARRAY);
Arrays.sort(typeParameters, Comparator.comparingInt(tp -> tp.getTextRange().getStartOffset()));
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(elements[0].getProject());
try {
final PsiClass aClass = elementFactory.createClassFromText("class A {}", null);
PsiTypeParameterList list = aClass.getTypeParameterList();
assert list != null;
for (final PsiTypeParameter typeParameter : typeParameters) {
list.add(typeParameter);
}
return list;
}
catch (IncorrectOperationException e) {
LOG.error(e);
assert false;
return null;
}
}
private static void collectTypeParametersInDependencies(Condition<? super PsiTypeParameter> filter, Set<PsiTypeParameter> used) {
Stack<PsiTypeParameter> toProcess = new Stack<>();
toProcess.addAll(used);
while (!toProcess.isEmpty()) {
PsiTypeParameter parameter = toProcess.pop();
HashSet<PsiTypeParameter> dependencies = new HashSet<>();
collectTypeParameters(dependencies, parameter, param -> filter.value(param) && !used.contains(param));
used.addAll(dependencies);
toProcess.addAll(dependencies);
}
}
public static void collectTypeParameters(final Set<? super PsiTypeParameter> used, final PsiElement element) {
collectTypeParameters(used, element, Conditions.alwaysTrue());
}
public static void collectTypeParameters(final Set<? super PsiTypeParameter> used, final PsiElement element,
final Condition<? super PsiTypeParameter> filter) {
element.accept(new JavaRecursiveElementVisitor() {
@Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
super.visitReferenceElement(reference);
if (!reference.isQualified()) {
final PsiElement resolved = reference.resolve();
if (resolved instanceof PsiTypeParameter) {
final PsiTypeParameter typeParameter = (PsiTypeParameter)resolved;
if (PsiTreeUtil.isAncestor(typeParameter.getOwner(), element, false) && filter.value(typeParameter)) {
used.add(typeParameter);
}
}
}
}
@Override
public void visitExpression(final PsiExpression expression) {
super.visitExpression(expression);
final PsiType type = expression.getType();
if (type != null) {
final PsiTypesUtil.TypeParameterSearcher searcher = new PsiTypesUtil.TypeParameterSearcher();
type.accept(searcher);
for (PsiTypeParameter typeParam : searcher.getTypeParameters()) {
if (PsiTreeUtil.isAncestor(typeParam.getOwner(), element, false) && filter.value(typeParam)){
used.add(typeParam);
}
}
}
}
});
}
}
| move to source root: ensure subdirectory with empty name is not created
IDEA-CR-65592
GitOrigin-RevId: e4db72b3cd1243563d5a576db4d7f050c3c70224 | java/java-impl/src/com/intellij/refactoring/util/RefactoringUtil.java | move to source root: ensure subdirectory with empty name is not created |
|
Java | apache-2.0 | 9c747a2f8f15c41b95f02268d1308cb1954afab1 | 0 | maduhu/head,AArhin/head,maduhu/mifos-head,AArhin/head,maduhu/mifos-head,maduhu/mifos-head,vorburger/mifos-head,AArhin/head,AArhin/head,jpodeszwik/mifos,maduhu/mifos-head,jpodeszwik/mifos,maduhu/head,jpodeszwik/mifos,maduhu/head,AArhin/head,vorburger/mifos-head,jpodeszwik/mifos,maduhu/mifos-head,vorburger/mifos-head,maduhu/head,vorburger/mifos-head,maduhu/head | package org.mifos.application.accounts.business;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException;
import org.mifos.application.accounts.TestAccount;
import org.mifos.application.accounts.loan.business.LoanActivityEntity;
import org.mifos.application.accounts.loan.business.LoanBO;
import org.mifos.application.accounts.loan.business.LoanPerformanceHistoryEntity;
import org.mifos.application.accounts.loan.business.LoanSummaryEntity;
import org.mifos.application.accounts.persistence.service.AccountPersistanceService;
import org.mifos.application.accounts.util.helpers.AccountConstants;
import org.mifos.application.accounts.util.helpers.AccountStates;
import org.mifos.application.accounts.util.helpers.PaymentData;
import org.mifos.application.customer.business.CustomerBO;
import org.mifos.application.customer.center.business.CenterBO;
import org.mifos.application.fees.business.FeesBO;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.framework.components.configuration.business.Configuration;
import org.mifos.framework.components.scheduler.SchedulerException;
import org.mifos.framework.components.scheduler.SchedulerIntf;
import org.mifos.framework.components.scheduler.helpers.SchedulerHelper;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.ServiceException;
import org.mifos.framework.hibernate.helper.HibernateUtil;
import org.mifos.framework.security.util.UserContext;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
public class TestAccountBO extends TestAccount {
public TestAccountBO() {
}
public void testSuccessRemoveFees() throws Exception {
TestObjectFactory.flushandCloseSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
UserContext uc = TestObjectFactory.getUserContext();
Set<AccountFeesEntity> accountFeesEntitySet = accountBO
.getAccountFees();
((LoanBO)accountBO).getLoanOffering().setPrinDueLastInst(false);
for(AccountActionDateEntity accountActionDateEntity : accountBO.getAccountActionDates()){
if(accountActionDateEntity.getInstallmentId().equals(Short.valueOf("1")))
accountActionDateEntity.setMiscFee(new Money("20.3"));
}
Iterator itr = accountFeesEntitySet.iterator();
while (itr.hasNext())
accountBO.removeFees(((AccountFeesEntity) itr.next()).getFees()
.getFeeId(), uc.getId());
HibernateUtil.getTransaction().commit();
for (AccountFeesEntity accountFeesEntity : accountFeesEntitySet) {
assertEquals(accountFeesEntity.getFeeStatus(),
AccountConstants.INACTIVE_FEES);
}
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
for (LoanActivityEntity accountNonTrxnEntity : ((LoanBO) accountBO)
.getLoanActivityDetails()) {
assertEquals(loanSummaryEntity.getOriginalFees().subtract(
loanSummaryEntity.getFeesPaid()), accountNonTrxnEntity
.getFeeOutstanding());
assertEquals(loanSummaryEntity.getOriginalPrincipal().subtract(
loanSummaryEntity.getPrincipalPaid()),
accountNonTrxnEntity.getPrincipalOutstanding());
assertEquals(loanSummaryEntity.getOriginalInterest().subtract(
loanSummaryEntity.getInterestPaid()),
accountNonTrxnEntity.getInterestOutstanding());
assertEquals(loanSummaryEntity.getOriginalPenalty().subtract(
loanSummaryEntity.getPenaltyPaid()),
accountNonTrxnEntity.getPenaltyOutstanding());
break;
}
for(AccountActionDateEntity accountActionDate : accountBO.getAccountActionDates()){
if(accountActionDate.getInstallmentId().equals(Short.valueOf("1")))
assertEquals(new Money("133.0"),accountActionDate.getTotalDue());
else if(accountActionDate.getInstallmentId().equals(Short.valueOf("6")))
assertEquals(new Money("111.3"),accountActionDate.getTotalDue());
else
assertEquals(new Money("112.0"),accountActionDate.getTotalDue());
}
}
public void testFailureRemoveFees() {
try {
HibernateUtil.getSessionTL();
HibernateUtil.startTransaction();
UserContext uc = TestObjectFactory.getUserContext();
Set<AccountFeesEntity> accountFeesEntitySet = accountBO
.getAccountFees();
Iterator itr = accountFeesEntitySet.iterator();
while (itr.hasNext())
accountBO.removeFees(((AccountFeesEntity) itr.next()).getFees()
.getFeeId(), uc.getId());
HibernateUtil.getTransaction().commit();
assert (false);
} catch (Exception e) {
assertTrue(true);
}
}
public void testSuccessUpdateTotalFeeAmount() {
LoanBO loanBO = (LoanBO) accountBO;
LoanSummaryEntity loanSummaryEntity = loanBO.getLoanSummary();
Money orignalFeesAmount = loanSummaryEntity.getOriginalFees();
loanBO.updateTotalFeeAmount(new Money(TestObjectFactory
.getMFICurrency(), "20"));
assertEquals(loanSummaryEntity.getOriginalFees(), (orignalFeesAmount
.subtract(new Money(TestObjectFactory.getMFICurrency(), "20"))));
}
public void testSuccessUpdateAccountActionDateEntity() {
AccountPersistanceService accountPersistanceService = new AccountPersistanceService();
List<Short> installmentIdList;
try {
installmentIdList = accountPersistanceService
.getNextInstallmentList(accountBO.getAccountId());
Set<AccountFeesEntity> accountFeesEntitySet = accountBO
.getAccountFees();
Iterator itr = accountFeesEntitySet.iterator();
while (itr.hasNext()) {
accountBO.updateAccountActionDateEntity(installmentIdList,
((AccountFeesEntity) itr.next()).getFees().getFeeId());
assertTrue(true);
}
} catch (Exception e) {
assertFalse(false);
} finally {
accountPersistanceService = null;
}
}
public void testSuccessUpdateAccountFeesEntity() {
Set<AccountFeesEntity> accountFeesEntitySet = accountBO
.getAccountFees();
Iterator itr = accountFeesEntitySet.iterator();
while (itr.hasNext()) {
AccountFeesEntity accountFeesEntity = (AccountFeesEntity) itr
.next();
accountBO.updateAccountFeesEntity(accountFeesEntity.getFees()
.getFeeId());
assertEquals(accountFeesEntity.getFeeStatus(),
AccountConstants.INACTIVE_FEES);
}
}
public void testGetLastLoanPmntAmnt() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.addAll(loan.getAccountActionDates());
PaymentData paymentData = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(212 * 6), null, Short
.valueOf("1"), "receiptNum", Short.valueOf("1"),
currentDate,currentDate);
loan.applyPayment(paymentData);
TestObjectFactory.updateObject(loan);
TestObjectFactory.flushandCloseSession();
assertEquals(
"The amount returned for the payment should have been 1272",
1272.0, loan.getLastPmntAmnt());
accountBO = (AccountBO) TestObjectFactory.getObject(AccountBO.class,
loan.getAccountId());
}
public void testLoanAdjustment() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
loan.setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.add(loan.getAccountActionDate(Short.valueOf("1")));
PaymentData accountPaymentDataView = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(212), null, Short.valueOf("1"),
"receiptNum", Short.valueOf("1"), currentDate,currentDate);
loan.applyPayment(accountPaymentDataView);
TestObjectFactory.updateObject(loan);
TestObjectFactory.flushandCloseSession();
loan.adjustPmnt("loan account has been adjusted by test code");
TestObjectFactory.updateObject(loan);
assertEquals("The amount returned for the payment should have been 0",
0.0, loan.getLastPmntAmnt());
LoanTrxnDetailEntity lastLoanTrxn = null;
for (AccountTrxnEntity accntTrxn : loan.getLastPmnt().getAccountTrxns()) {
lastLoanTrxn = (LoanTrxnDetailEntity) accntTrxn;
break;
}
AccountActionDateEntity installment = loan
.getAccountActionDate(lastLoanTrxn.getInstallmentId());
assertEquals(
"The installment adjusted should now be marked unpaid(due).",
installment.getPaymentStatus(), AccountConstants.PAYMENT_UNPAID);
}
public void testAdjustmentForClosedAccnt() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
loan.setAccountState(new AccountStateEntity(
AccountStates.LOANACC_OBLIGATIONSMET));
loan.setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.addAll(loan.getAccountActionDates());
PaymentData accountPaymentDataView = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(212 * 6), null, Short
.valueOf("1"), "receiptNum", Short.valueOf("1"),
currentDate,currentDate);
loan.applyPayment(accountPaymentDataView);
TestObjectFactory.updateObject(loan);
try {
loan.adjustPmnt("loan account has been adjusted by test code");
assertTrue(false);
} catch (Exception e) {
assertTrue(true);
}
}
public void testRetrievalOfNullMonetaryValue() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
loan.setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.addAll(loan.getAccountActionDates());
PaymentData accountPaymentDataView = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(0), null, Short.valueOf("1"),
"receiptNum", Short.valueOf("1"), currentDate,currentDate);
loan.applyPayment(accountPaymentDataView);
TestObjectFactory.updateObject(loan);
TestObjectFactory.flushandCloseSession();
loan = (LoanBO) TestObjectFactory.getObject(AccountBO.class, loan
.getAccountId());
Money pmntAmnt = null;
for (AccountPaymentEntity accntPmnt : loan.getAccountPayments()) {
pmntAmnt = accntPmnt.getAmount();
}
TestObjectFactory.flushandCloseSession();
assertEquals(
"Account payment retrieved should be zero with currency MFI currency",
TestObjectFactory.getMoneyForMFICurrency(0), pmntAmnt);
}
public void testGetTransactionHistoryView() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
loan.setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.addAll(loan.getAccountActionDates());
PaymentData accountPaymentDataView = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(0), null, Short.valueOf("1"),
"receiptNum", Short.valueOf("1"), currentDate,
currentDate);
loan.applyPayment(accountPaymentDataView);
TestObjectFactory.flushandCloseSession();
loan = (LoanBO) TestObjectFactory.getObject(AccountBO.class, loan
.getAccountId());
loan.setUserContext(TestObjectFactory.getUserContext());
List<TransactionHistoryView> trxnHistlist =loan.getTransactionHistoryView();
assertNotNull("Account TrxnHistoryView list object should not be null",trxnHistlist);
assertTrue("Account TrxnHistoryView list object Size should be greater than zero",trxnHistlist.size()>0);
TestObjectFactory.flushandCloseSession();
accountBO = (LoanBO) TestObjectFactory.getObject(AccountBO.class, loan
.getAccountId());
}
public void testGetPeriodicFeeList(){
AccountFeesEntity accountOneTimeFee = new AccountFeesEntity();
accountOneTimeFee.setAccount(accountBO);
accountOneTimeFee.setAccountFeeAmount(new Money("1.0"));
accountOneTimeFee.setFeeAmount(new Money("1.0"));
FeesBO oneTimeFee = TestObjectFactory.createOneTimeFees("One Time Fee ", 20.0,(short) 2, 5);
accountOneTimeFee.setFees(oneTimeFee);
accountBO.addAccountFees(accountOneTimeFee);
accountPersistence.createOrUpdate(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
assertEquals(1,accountBO.getPeriodicFeeList().size());
}
public void testIsTrxnDateValid() throws Exception{
Calendar calendar = new GregorianCalendar();
calendar.roll(Calendar.DAY_OF_MONTH,10);
java.util.Date trxnDate = new Date(calendar.getTimeInMillis());
if(Configuration.getInstance().getAccountConfig(Short.valueOf("3")).isBackDatedTxnAllowed())
assertTrue(accountBO.isTrxnDateValid(trxnDate));
else
assertFalse(accountBO.isTrxnDateValid(trxnDate));
}
public void testHandleChangeInMeetingSchedule() throws SchedulerException, ServiceException, HibernateException, PersistenceException{
TestObjectFactory.flushandCloseSession();
center=(CenterBO)TestObjectFactory.getObject(CenterBO.class,center.getCustomerId());
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
MeetingBO meeting = center.getCustomerMeeting().getMeeting();
meeting.getMeetingDetails().setRecurAfter(Short.valueOf("2"));
SchedulerIntf scheduler = SchedulerHelper.getScheduler(meeting);
List<java.util.Date> meetingDates = scheduler.getAllDates(accountBO.getApplicableIdsForFutureInstallments().size()+1);
meetingDates.remove(0);
TestObjectFactory.updateObject(center);
center.getCustomerAccount().handleChangeInMeetingSchedule();
accountBO.handleChangeInMeetingSchedule();
HibernateUtil.getTransaction().commit();
HibernateUtil.closeSession();
center=(CenterBO)TestObjectFactory.getObject(CenterBO.class,center.getCustomerId());
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
for(AccountActionDateEntity actionDateEntity : center.getCustomerAccount().getAccountActionDates()){
if(actionDateEntity.getInstallmentId().equals(Short.valueOf("2")))
assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity.getActionDate().getTime()),DateUtils.getDateWithoutTimeStamp(meetingDates.get(0).getTime()));
else if(actionDateEntity.getInstallmentId().equals(Short.valueOf("3")))
assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity.getActionDate().getTime()),DateUtils.getDateWithoutTimeStamp(meetingDates.get(1).getTime()));
}
for(AccountActionDateEntity actionDateEntity : accountBO.getAccountActionDates()){
if(actionDateEntity.getInstallmentId().equals(Short.valueOf("2")))
assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity.getActionDate().getTime()),DateUtils.getDateWithoutTimeStamp(meetingDates.get(0).getTime()));
else if(actionDateEntity.getInstallmentId().equals(Short.valueOf("3")))
assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity.getActionDate().getTime()),DateUtils.getDateWithoutTimeStamp(meetingDates.get(1).getTime()));
}
}
public void testDeleteFutureInstallments() throws HibernateException, ServiceException{
TestObjectFactory.flushandCloseSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
accountBO.deleteFutureInstallments();
HibernateUtil.getTransaction().commit();
HibernateUtil.closeSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
assertEquals(1,accountBO.getAccountActionDates().size());
}
public void testGetTotalPrincipalAmountInArrears() {
Calendar calendar = new GregorianCalendar();
calendar.setTime(DateUtils.getCurrentDateWithoutTimeStamp());
calendar.add(calendar.WEEK_OF_MONTH,-1);
java.sql.Date lastWeekDate = new java.sql.Date(calendar.getTimeInMillis());
Calendar date = new GregorianCalendar();
date.setTime(DateUtils.getCurrentDateWithoutTimeStamp());
date.add(date.WEEK_OF_MONTH,-2);
java.sql.Date twoWeeksBeforeDate = new java.sql.Date(date.getTimeInMillis());
for(AccountActionDateEntity installment : accountBO.getAccountActionDates()){
if(installment.getInstallmentId().intValue()==1){
installment.setActionDate(lastWeekDate);
}
else if(installment.getInstallmentId().intValue()==2){
installment.setActionDate(twoWeeksBeforeDate);
}
}
TestObjectFactory.updateObject(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
assertEquals(new Money("200"),((LoanBO)accountBO).getTotalPrincipalAmountInArrears());
}
public void testUpdatePerformanceHistoryOnAdjustment() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanPerformanceHistoryEntity loanPerfHistory = new LoanPerformanceHistoryEntity();
((LoanBO) accountBO).setPerformanceHistory(loanPerfHistory);
Integer noOfPayments = loanPerfHistory.getNoOfPayments();
TestObjectFactory.updateObject(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO = (AccountBO) HibernateUtil.getSessionTL().get(AccountBO.class, accountBO.getAccountId());
((LoanBO) accountBO).setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
int count = 0;
for(AccountActionDateEntity accountActionDateEntity : accountBO.getAccountActionDates()) {
if(count==5)
break;
accntActionDates.add(accountActionDateEntity);
count++;
}
PaymentData paymentData = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(212 * 5), null, Short
.valueOf("1"), "receiptNum", Short.valueOf("1"),
currentDate,currentDate);
((LoanBO) accountBO).applyPayment(paymentData);
loanPerfHistory = ((LoanBO) accountBO).getPerformanceHistory();
noOfPayments = loanPerfHistory.getNoOfPayments();
TestObjectFactory.updateObject(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO = (AccountBO) HibernateUtil.getSessionTL().get(AccountBO.class, accountBO.getAccountId());
((LoanBO) accountBO).setUserContext(TestObjectFactory.getUserContext());
((LoanBO) accountBO).adjustPmnt("loan account has been adjusted by test code");
TestObjectFactory.updateObject(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO = (AccountBO) HibernateUtil.getSessionTL().get(AccountBO.class, accountBO.getAccountId());
assertEquals(noOfPayments-5, ((LoanBO) accountBO).getPerformanceHistory().getNoOfPayments().intValue());
group = (CustomerBO) HibernateUtil.getSessionTL().get(CustomerBO.class,
group.getCustomerId());
center = (CustomerBO) HibernateUtil.getSessionTL().get(
CustomerBO.class, center.getCustomerId());
}
}
| mifos/test/org/mifos/application/accounts/business/TestAccountBO.java | package org.mifos.application.accounts.business;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException;
import org.mifos.application.accounts.TestAccount;
import org.mifos.application.accounts.loan.business.LoanActivityEntity;
import org.mifos.application.accounts.loan.business.LoanBO;
import org.mifos.application.accounts.loan.business.LoanPerformanceHistoryEntity;
import org.mifos.application.accounts.loan.business.LoanSummaryEntity;
import org.mifos.application.accounts.persistence.service.AccountPersistanceService;
import org.mifos.application.accounts.util.helpers.AccountConstants;
import org.mifos.application.accounts.util.helpers.AccountStates;
import org.mifos.application.accounts.util.helpers.PaymentData;
import org.mifos.application.customer.business.CustomerBO;
import org.mifos.application.customer.center.business.CenterBO;
import org.mifos.application.fees.business.FeesBO;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.framework.components.configuration.business.Configuration;
import org.mifos.framework.components.scheduler.SchedulerException;
import org.mifos.framework.components.scheduler.SchedulerIntf;
import org.mifos.framework.components.scheduler.helpers.SchedulerHelper;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.ServiceException;
import org.mifos.framework.hibernate.helper.HibernateUtil;
import org.mifos.framework.security.util.UserContext;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
public class TestAccountBO extends TestAccount {
public TestAccountBO() {
}
public void testSuccessRemoveFees() {
try {
HibernateUtil.getSessionTL();
HibernateUtil.startTransaction();
UserContext uc = TestObjectFactory.getUserContext();
Set<AccountFeesEntity> accountFeesEntitySet = accountBO
.getAccountFees();
((LoanBO)accountBO).getLoanOffering().setPrinDueLastInst(false);
for(AccountActionDateEntity accountActionDateEntity : accountBO.getAccountActionDates()){
if(accountActionDateEntity.getInstallmentId().equals(Short.valueOf("1")))
accountActionDateEntity.setMiscFee(new Money("20.3"));
}
Iterator itr = accountFeesEntitySet.iterator();
while (itr.hasNext())
accountBO.removeFees(((AccountFeesEntity) itr.next()).getFees()
.getFeeId(), uc.getId());
HibernateUtil.getTransaction().commit();
for (AccountFeesEntity accountFeesEntity : accountFeesEntitySet) {
assertEquals(accountFeesEntity.getFeeStatus(),
AccountConstants.INACTIVE_FEES);
}
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
for (LoanActivityEntity accountNonTrxnEntity : ((LoanBO) accountBO)
.getLoanActivityDetails()) {
assertEquals(loanSummaryEntity.getOriginalFees().subtract(
loanSummaryEntity.getFeesPaid()), accountNonTrxnEntity
.getFeeOutstanding());
assertEquals(loanSummaryEntity.getOriginalPrincipal().subtract(
loanSummaryEntity.getPrincipalPaid()),
accountNonTrxnEntity.getPrincipalOutstanding());
assertEquals(loanSummaryEntity.getOriginalInterest().subtract(
loanSummaryEntity.getInterestPaid()),
accountNonTrxnEntity.getInterestOutstanding());
assertEquals(loanSummaryEntity.getOriginalPenalty().subtract(
loanSummaryEntity.getPenaltyPaid()),
accountNonTrxnEntity.getPenaltyOutstanding());
break;
}
for(AccountActionDateEntity accountActionDate : accountBO.getAccountActionDates()){
if(accountActionDate.getInstallmentId().equals(Short.valueOf("1")))
assertEquals(new Money("133.0"),accountActionDate.getTotalDue());
else if(accountActionDate.getInstallmentId().equals(Short.valueOf("6")))
assertEquals(new Money("111.3"),accountActionDate.getTotalDue());
else
assertEquals(new Money("112.0"),accountActionDate.getTotalDue());
}
} catch (Exception e) {
assertTrue(false);
}
}
public void testFailureRemoveFees() {
try {
HibernateUtil.getSessionTL();
HibernateUtil.startTransaction();
UserContext uc = TestObjectFactory.getUserContext();
Set<AccountFeesEntity> accountFeesEntitySet = accountBO
.getAccountFees();
Iterator itr = accountFeesEntitySet.iterator();
while (itr.hasNext())
accountBO.removeFees(((AccountFeesEntity) itr.next()).getFees()
.getFeeId(), uc.getId());
HibernateUtil.getTransaction().commit();
assert (false);
} catch (Exception e) {
assertTrue(true);
}
}
public void testSuccessUpdateTotalFeeAmount() {
LoanBO loanBO = (LoanBO) accountBO;
LoanSummaryEntity loanSummaryEntity = loanBO.getLoanSummary();
Money orignalFeesAmount = loanSummaryEntity.getOriginalFees();
loanBO.updateTotalFeeAmount(new Money(TestObjectFactory
.getMFICurrency(), "20"));
assertEquals(loanSummaryEntity.getOriginalFees(), (orignalFeesAmount
.subtract(new Money(TestObjectFactory.getMFICurrency(), "20"))));
}
public void testSuccessUpdateAccountActionDateEntity() {
AccountPersistanceService accountPersistanceService = new AccountPersistanceService();
List<Short> installmentIdList;
try {
installmentIdList = accountPersistanceService
.getNextInstallmentList(accountBO.getAccountId());
Set<AccountFeesEntity> accountFeesEntitySet = accountBO
.getAccountFees();
Iterator itr = accountFeesEntitySet.iterator();
while (itr.hasNext()) {
accountBO.updateAccountActionDateEntity(installmentIdList,
((AccountFeesEntity) itr.next()).getFees().getFeeId());
assertTrue(true);
}
} catch (Exception e) {
assertFalse(false);
} finally {
accountPersistanceService = null;
}
}
public void testSuccessUpdateAccountFeesEntity() {
Set<AccountFeesEntity> accountFeesEntitySet = accountBO
.getAccountFees();
Iterator itr = accountFeesEntitySet.iterator();
while (itr.hasNext()) {
AccountFeesEntity accountFeesEntity = (AccountFeesEntity) itr
.next();
accountBO.updateAccountFeesEntity(accountFeesEntity.getFees()
.getFeeId());
assertEquals(accountFeesEntity.getFeeStatus(),
AccountConstants.INACTIVE_FEES);
}
}
public void testGetLastLoanPmntAmnt() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.addAll(loan.getAccountActionDates());
PaymentData paymentData = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(212 * 6), null, Short
.valueOf("1"), "receiptNum", Short.valueOf("1"),
currentDate,currentDate);
loan.applyPayment(paymentData);
TestObjectFactory.updateObject(loan);
TestObjectFactory.flushandCloseSession();
assertEquals(
"The amount returned for the payment should have been 1272",
1272.0, loan.getLastPmntAmnt());
accountBO = (AccountBO) TestObjectFactory.getObject(AccountBO.class,
loan.getAccountId());
}
public void testLoanAdjustment() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
loan.setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.add(loan.getAccountActionDate(Short.valueOf("1")));
PaymentData accountPaymentDataView = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(212), null, Short.valueOf("1"),
"receiptNum", Short.valueOf("1"), currentDate,currentDate);
loan.applyPayment(accountPaymentDataView);
TestObjectFactory.updateObject(loan);
TestObjectFactory.flushandCloseSession();
loan.adjustPmnt("loan account has been adjusted by test code");
TestObjectFactory.updateObject(loan);
assertEquals("The amount returned for the payment should have been 0",
0.0, loan.getLastPmntAmnt());
LoanTrxnDetailEntity lastLoanTrxn = null;
for (AccountTrxnEntity accntTrxn : loan.getLastPmnt().getAccountTrxns()) {
lastLoanTrxn = (LoanTrxnDetailEntity) accntTrxn;
break;
}
AccountActionDateEntity installment = loan
.getAccountActionDate(lastLoanTrxn.getInstallmentId());
assertEquals(
"The installment adjusted should now be marked unpaid(due).",
installment.getPaymentStatus(), AccountConstants.PAYMENT_UNPAID);
}
public void testAdjustmentForClosedAccnt() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
loan.setAccountState(new AccountStateEntity(
AccountStates.LOANACC_OBLIGATIONSMET));
loan.setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.addAll(loan.getAccountActionDates());
PaymentData accountPaymentDataView = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(212 * 6), null, Short
.valueOf("1"), "receiptNum", Short.valueOf("1"),
currentDate,currentDate);
loan.applyPayment(accountPaymentDataView);
TestObjectFactory.updateObject(loan);
try {
loan.adjustPmnt("loan account has been adjusted by test code");
assertTrue(false);
} catch (Exception e) {
assertTrue(true);
}
}
public void testRetrievalOfNullMonetaryValue() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
loan.setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.addAll(loan.getAccountActionDates());
PaymentData accountPaymentDataView = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(0), null, Short.valueOf("1"),
"receiptNum", Short.valueOf("1"), currentDate,currentDate);
loan.applyPayment(accountPaymentDataView);
TestObjectFactory.updateObject(loan);
TestObjectFactory.flushandCloseSession();
loan = (LoanBO) TestObjectFactory.getObject(AccountBO.class, loan
.getAccountId());
Money pmntAmnt = null;
for (AccountPaymentEntity accntPmnt : loan.getAccountPayments()) {
pmntAmnt = accntPmnt.getAmount();
}
TestObjectFactory.flushandCloseSession();
assertEquals(
"Account payment retrieved should be zero with currency MFI currency",
TestObjectFactory.getMoneyForMFICurrency(0), pmntAmnt);
}
public void testGetTransactionHistoryView() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanBO loan = (LoanBO) accountBO;
loan.setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
accntActionDates.addAll(loan.getAccountActionDates());
PaymentData accountPaymentDataView = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(0), null, Short.valueOf("1"),
"receiptNum", Short.valueOf("1"), currentDate,
currentDate);
loan.applyPayment(accountPaymentDataView);
TestObjectFactory.flushandCloseSession();
loan = (LoanBO) TestObjectFactory.getObject(AccountBO.class, loan
.getAccountId());
loan.setUserContext(TestObjectFactory.getUserContext());
List<TransactionHistoryView> trxnHistlist =loan.getTransactionHistoryView();
assertNotNull("Account TrxnHistoryView list object should not be null",trxnHistlist);
assertTrue("Account TrxnHistoryView list object Size should be greater than zero",trxnHistlist.size()>0);
TestObjectFactory.flushandCloseSession();
accountBO = (LoanBO) TestObjectFactory.getObject(AccountBO.class, loan
.getAccountId());
}
public void testGetPeriodicFeeList(){
AccountFeesEntity accountOneTimeFee = new AccountFeesEntity();
accountOneTimeFee.setAccount(accountBO);
accountOneTimeFee.setAccountFeeAmount(new Money("1.0"));
accountOneTimeFee.setFeeAmount(new Money("1.0"));
FeesBO oneTimeFee = TestObjectFactory.createOneTimeFees("One Time Fee ", 20.0,(short) 2, 5);
accountOneTimeFee.setFees(oneTimeFee);
accountBO.addAccountFees(accountOneTimeFee);
accountPersistence.createOrUpdate(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
assertEquals(1,accountBO.getPeriodicFeeList().size());
}
public void testIsTrxnDateValid() throws Exception{
Calendar calendar = new GregorianCalendar();
calendar.roll(Calendar.DAY_OF_MONTH,10);
java.util.Date trxnDate = new Date(calendar.getTimeInMillis());
if(Configuration.getInstance().getAccountConfig(Short.valueOf("3")).isBackDatedTxnAllowed())
assertTrue(accountBO.isTrxnDateValid(trxnDate));
else
assertFalse(accountBO.isTrxnDateValid(trxnDate));
}
public void testHandleChangeInMeetingSchedule() throws SchedulerException, ServiceException, HibernateException, PersistenceException{
TestObjectFactory.flushandCloseSession();
center=(CenterBO)TestObjectFactory.getObject(CenterBO.class,center.getCustomerId());
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
MeetingBO meeting = center.getCustomerMeeting().getMeeting();
meeting.getMeetingDetails().setRecurAfter(Short.valueOf("2"));
SchedulerIntf scheduler = SchedulerHelper.getScheduler(meeting);
List<java.util.Date> meetingDates = scheduler.getAllDates(accountBO.getApplicableIdsForFutureInstallments().size()+1);
meetingDates.remove(0);
TestObjectFactory.updateObject(center);
center.getCustomerAccount().handleChangeInMeetingSchedule();
accountBO.handleChangeInMeetingSchedule();
HibernateUtil.getTransaction().commit();
HibernateUtil.closeSession();
center=(CenterBO)TestObjectFactory.getObject(CenterBO.class,center.getCustomerId());
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
for(AccountActionDateEntity actionDateEntity : center.getCustomerAccount().getAccountActionDates()){
if(actionDateEntity.getInstallmentId().equals(Short.valueOf("2")))
assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity.getActionDate().getTime()),DateUtils.getDateWithoutTimeStamp(meetingDates.get(0).getTime()));
else if(actionDateEntity.getInstallmentId().equals(Short.valueOf("3")))
assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity.getActionDate().getTime()),DateUtils.getDateWithoutTimeStamp(meetingDates.get(1).getTime()));
}
for(AccountActionDateEntity actionDateEntity : accountBO.getAccountActionDates()){
if(actionDateEntity.getInstallmentId().equals(Short.valueOf("2")))
assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity.getActionDate().getTime()),DateUtils.getDateWithoutTimeStamp(meetingDates.get(0).getTime()));
else if(actionDateEntity.getInstallmentId().equals(Short.valueOf("3")))
assertEquals(DateUtils.getDateWithoutTimeStamp(actionDateEntity.getActionDate().getTime()),DateUtils.getDateWithoutTimeStamp(meetingDates.get(1).getTime()));
}
}
public void testDeleteFutureInstallments() throws HibernateException, ServiceException{
TestObjectFactory.flushandCloseSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
accountBO.deleteFutureInstallments();
HibernateUtil.getTransaction().commit();
HibernateUtil.closeSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
assertEquals(1,accountBO.getAccountActionDates().size());
}
public void testGetTotalPrincipalAmountInArrears() {
Calendar calendar = new GregorianCalendar();
calendar.setTime(DateUtils.getCurrentDateWithoutTimeStamp());
calendar.add(calendar.WEEK_OF_MONTH,-1);
java.sql.Date lastWeekDate = new java.sql.Date(calendar.getTimeInMillis());
Calendar date = new GregorianCalendar();
date.setTime(DateUtils.getCurrentDateWithoutTimeStamp());
date.add(date.WEEK_OF_MONTH,-2);
java.sql.Date twoWeeksBeforeDate = new java.sql.Date(date.getTimeInMillis());
for(AccountActionDateEntity installment : accountBO.getAccountActionDates()){
if(installment.getInstallmentId().intValue()==1){
installment.setActionDate(lastWeekDate);
}
else if(installment.getInstallmentId().intValue()==2){
installment.setActionDate(twoWeeksBeforeDate);
}
}
TestObjectFactory.updateObject(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO=(AccountBO)TestObjectFactory.getObject(AccountBO.class,accountBO.getAccountId());
assertEquals(new Money("200"),((LoanBO)accountBO).getTotalPrincipalAmountInArrears());
}
public void testUpdatePerformanceHistoryOnAdjustment() throws Exception {
Date currentDate = new Date(System.currentTimeMillis());
LoanPerformanceHistoryEntity loanPerfHistory = new LoanPerformanceHistoryEntity();
((LoanBO) accountBO).setPerformanceHistory(loanPerfHistory);
Integer noOfPayments = loanPerfHistory.getNoOfPayments();
TestObjectFactory.updateObject(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO = (AccountBO) HibernateUtil.getSessionTL().get(AccountBO.class, accountBO.getAccountId());
((LoanBO) accountBO).setUserContext(TestObjectFactory.getUserContext());
List<AccountActionDateEntity> accntActionDates = new ArrayList<AccountActionDateEntity>();
int count = 0;
for(AccountActionDateEntity accountActionDateEntity : accountBO.getAccountActionDates()) {
if(count==5)
break;
accntActionDates.add(accountActionDateEntity);
count++;
}
PaymentData paymentData = TestObjectFactory
.getLoanAccountPaymentData(accntActionDates, TestObjectFactory
.getMoneyForMFICurrency(212 * 5), null, Short
.valueOf("1"), "receiptNum", Short.valueOf("1"),
currentDate,currentDate);
((LoanBO) accountBO).applyPayment(paymentData);
loanPerfHistory = ((LoanBO) accountBO).getPerformanceHistory();
noOfPayments = loanPerfHistory.getNoOfPayments();
TestObjectFactory.updateObject(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO = (AccountBO) HibernateUtil.getSessionTL().get(AccountBO.class, accountBO.getAccountId());
((LoanBO) accountBO).setUserContext(TestObjectFactory.getUserContext());
((LoanBO) accountBO).adjustPmnt("loan account has been adjusted by test code");
TestObjectFactory.updateObject(accountBO);
TestObjectFactory.flushandCloseSession();
accountBO = (AccountBO) HibernateUtil.getSessionTL().get(AccountBO.class, accountBO.getAccountId());
assertEquals(noOfPayments-5, ((LoanBO) accountBO).getPerformanceHistory().getNoOfPayments().intValue());
group = (CustomerBO) HibernateUtil.getSessionTL().get(CustomerBO.class,
group.getCustomerId());
center = (CustomerBO) HibernateUtil.getSessionTL().get(
CustomerBO.class, center.getCustomerId());
}
}
| Change : Test case was showing inconsistent behaviour due to
order by mapping specified in the hbm for retrieving action dates
. Now test case has been modified to retrieve fresh object after
creation so it will always fetch installments in ascending order
of installment id.
git-svn-id: 6bd94cac40bd5c1df74b384d972046d926de6ffa@10271 a8845c50-7012-0410-95d3-8e1449b9b1e4
| mifos/test/org/mifos/application/accounts/business/TestAccountBO.java | Change : Test case was showing inconsistent behaviour due to order by mapping specified in the hbm for retrieving action dates . Now test case has been modified to retrieve fresh object after creation so it will always fetch installments in ascending order of installment id. |
|
Java | apache-2.0 | ae7e6094d40847ffe0b52793fb2c095487fcada8 | 0 | mreutegg/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,apache/jackrabbit-oak,amit-jain/jackrabbit-oak | /*
* 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.jackrabbit.oak.query;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static org.apache.jackrabbit.oak.query.ast.AstElementFactory.copyElementAndCheckReference;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.oak.api.PropertyValue;
import org.apache.jackrabbit.oak.api.Result.SizePrecision;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.namepath.JcrPathParser;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.index.counter.jmx.NodeCounter;
import org.apache.jackrabbit.oak.plugins.memory.PropertyValues;
import org.apache.jackrabbit.oak.query.QueryOptions.Traversal;
import org.apache.jackrabbit.oak.query.ast.AndImpl;
import org.apache.jackrabbit.oak.query.ast.AstVisitorBase;
import org.apache.jackrabbit.oak.query.ast.BindVariableValueImpl;
import org.apache.jackrabbit.oak.query.ast.ChildNodeImpl;
import org.apache.jackrabbit.oak.query.ast.ChildNodeJoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.CoalesceImpl;
import org.apache.jackrabbit.oak.query.ast.ColumnImpl;
import org.apache.jackrabbit.oak.query.ast.ComparisonImpl;
import org.apache.jackrabbit.oak.query.ast.ConstraintImpl;
import org.apache.jackrabbit.oak.query.ast.DescendantNodeImpl;
import org.apache.jackrabbit.oak.query.ast.DescendantNodeJoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.DynamicOperandImpl;
import org.apache.jackrabbit.oak.query.ast.EquiJoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.FullTextSearchImpl;
import org.apache.jackrabbit.oak.query.ast.FullTextSearchScoreImpl;
import org.apache.jackrabbit.oak.query.ast.InImpl;
import org.apache.jackrabbit.oak.query.ast.JoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.JoinImpl;
import org.apache.jackrabbit.oak.query.ast.JoinType;
import org.apache.jackrabbit.oak.query.ast.LengthImpl;
import org.apache.jackrabbit.oak.query.ast.LiteralImpl;
import org.apache.jackrabbit.oak.query.ast.LowerCaseImpl;
import org.apache.jackrabbit.oak.query.ast.NativeFunctionImpl;
import org.apache.jackrabbit.oak.query.ast.NodeLocalNameImpl;
import org.apache.jackrabbit.oak.query.ast.NodeNameImpl;
import org.apache.jackrabbit.oak.query.ast.NotImpl;
import org.apache.jackrabbit.oak.query.ast.OrImpl;
import org.apache.jackrabbit.oak.query.ast.OrderingImpl;
import org.apache.jackrabbit.oak.query.ast.PropertyExistenceImpl;
import org.apache.jackrabbit.oak.query.ast.PropertyInexistenceImpl;
import org.apache.jackrabbit.oak.query.ast.PropertyValueImpl;
import org.apache.jackrabbit.oak.query.ast.SameNodeImpl;
import org.apache.jackrabbit.oak.query.ast.SameNodeJoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.SelectorImpl;
import org.apache.jackrabbit.oak.query.ast.SimilarImpl;
import org.apache.jackrabbit.oak.query.ast.SourceImpl;
import org.apache.jackrabbit.oak.query.ast.SpellcheckImpl;
import org.apache.jackrabbit.oak.query.ast.SuggestImpl;
import org.apache.jackrabbit.oak.query.ast.UpperCaseImpl;
import org.apache.jackrabbit.oak.query.index.FilterImpl;
import org.apache.jackrabbit.oak.query.index.TraversingIndex;
import org.apache.jackrabbit.oak.query.plan.ExecutionPlan;
import org.apache.jackrabbit.oak.query.plan.SelectorExecutionPlan;
import org.apache.jackrabbit.oak.query.stats.QueryStatsData.QueryExecutionStats;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.jackrabbit.oak.spi.query.Filter.PathRestriction;
import org.apache.jackrabbit.oak.spi.query.QueryConstants;
import org.apache.jackrabbit.oak.spi.query.QueryIndex;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.AdvancedQueryIndex;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.IndexPlan;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.OrderEntry;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.OrderEntry.Order;
import org.apache.jackrabbit.oak.spi.query.QueryIndexProvider;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
/**
* Represents a parsed query.
*/
public class QueryImpl implements Query {
public static final UnsupportedOperationException TOO_MANY_UNION =
new UnsupportedOperationException("Too many union queries");
public final static int MAX_UNION = Integer.getInteger("oak.sql2MaxUnion", 1000);
private static final Logger LOG = LoggerFactory.getLogger(QueryImpl.class);
private final QueryExecutionStats stats;
private boolean potentiallySlowTraversalQueryLogged;
private static final Ordering<QueryIndex> MINIMAL_COST_ORDERING = new Ordering<QueryIndex>() {
@Override
public int compare(QueryIndex left, QueryIndex right) {
return Double.compare(left.getMinimumCost(), right.getMinimumCost());
}
};
SourceImpl source;
private String statement;
final HashMap<String, PropertyValue> bindVariableMap = new HashMap<String, PropertyValue>();
final HashMap<String, Integer> selectorIndexes = new HashMap<String, Integer>();
final ArrayList<SelectorImpl> selectors = new ArrayList<SelectorImpl>();
ConstraintImpl constraint;
/**
* Whether fallback to the traversing index is supported if no other index
* is available. This is enabled by default and can be disabled for testing
* purposes.
*/
private boolean traversalEnabled = true;
/**
* The query option to be used for this query.
*/
private QueryOptions queryOptions = new QueryOptions();
private OrderingImpl[] orderings;
private ColumnImpl[] columns;
/**
* The columns that make a row distinct. This is all columns
* except for "jcr:score".
*/
private boolean[] distinctColumns;
private boolean explain, measure;
private boolean distinct;
private long limit = Long.MAX_VALUE;
private long offset;
private long size = -1;
private boolean prepared;
private ExecutionContext context;
/**
* whether the object has been initialised or not
*/
private boolean init;
private boolean isSortedByIndex;
private final NamePathMapper namePathMapper;
private double estimatedCost;
private final QueryEngineSettings settings;
private boolean warnedHidden;
private boolean isInternal;
private boolean potentiallySlowTraversalQuery;
QueryImpl(String statement, SourceImpl source, ConstraintImpl constraint,
ColumnImpl[] columns, NamePathMapper mapper, QueryEngineSettings settings,
QueryExecutionStats stats) {
this.statement = statement;
this.source = source;
this.constraint = constraint;
this.columns = columns;
this.namePathMapper = mapper;
this.settings = settings;
this.stats = stats;
}
@Override
public void init() {
final QueryImpl query = this;
if (constraint != null) {
// need to do this *before* the visitation below, as the
// simplify() method does not always keep the query reference
// passed in setQuery(). TODO: avoid that mutability concern
constraint = constraint.simplify();
}
new AstVisitorBase() {
@Override
public boolean visit(BindVariableValueImpl node) {
node.setQuery(query);
bindVariableMap.put(node.getBindVariableName(), null);
return true;
}
@Override
public boolean visit(ChildNodeImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(ChildNodeJoinConditionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(CoalesceImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(ColumnImpl node) {
node.setQuery(query);
return true;
}
@Override
public boolean visit(DescendantNodeImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(DescendantNodeJoinConditionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(EquiJoinConditionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(FullTextSearchImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(NativeFunctionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(SimilarImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(SpellcheckImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(SuggestImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(FullTextSearchScoreImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(LiteralImpl node) {
node.setQuery(query);
return true;
}
@Override
public boolean visit(NodeLocalNameImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(NodeNameImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(PropertyExistenceImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(PropertyInexistenceImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(PropertyValueImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(SameNodeImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(SameNodeJoinConditionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(SelectorImpl node) {
String name = node.getSelectorName();
if (selectorIndexes.put(name, selectors.size()) != null) {
throw new IllegalArgumentException("Two selectors with the same name: " + name);
}
selectors.add(node);
node.setQuery(query);
return true;
}
@Override
public boolean visit(LengthImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(UpperCaseImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(LowerCaseImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(ComparisonImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(InImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(AndImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(OrImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(NotImpl node) {
node.setQuery(query);
return super.visit(node);
}
}.visit(this);
source.setQueryConstraint(constraint);
for (ColumnImpl column : columns) {
column.bindSelector(source);
}
distinctColumns = new boolean[columns.length];
for (int i = 0; i < columns.length; i++) {
ColumnImpl c = columns[i];
boolean distinct = true;
if (QueryConstants.JCR_SCORE.equals(c.getPropertyName())) {
distinct = false;
}
distinctColumns[i] = distinct;
}
init = true;
}
@Override
public ColumnImpl[] getColumns() {
return columns;
}
public ConstraintImpl getConstraint() {
return constraint;
}
public OrderingImpl[] getOrderings() {
return orderings;
}
public SourceImpl getSource() {
return source;
}
@Override
public void bindValue(String varName, PropertyValue value) {
bindVariableMap.put(varName, value);
}
@Override
public void setLimit(long limit) {
this.limit = limit;
}
@Override
public void setOffset(long offset) {
this.offset = offset;
}
@Override
public void setExplain(boolean explain) {
this.explain = explain;
}
@Override
public void setMeasure(boolean measure) {
this.measure = measure;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
@Override
public ResultImpl executeQuery() {
return new ResultImpl(this);
}
@Override
public Iterator<ResultRowImpl> getRows() {
prepare();
if (explain) {
String plan = getPlan();
if (measure) {
plan += " cost: { " + getIndexCostInfo() + " }";
}
columns = new ColumnImpl[] { new ColumnImpl("explain", "plan", "plan")};
ResultRowImpl r = new ResultRowImpl(this,
Tree.EMPTY_ARRAY,
new PropertyValue[] { PropertyValues.newString(plan)},
null, null);
return Arrays.asList(r).iterator();
}
if (LOG.isDebugEnabled()) {
logDebug("query execute " + statement);
logDebug("query plan " + getPlan());
}
final RowIterator rowIt = new RowIterator(context.getBaseState());
Comparator<ResultRowImpl> orderBy;
if (isSortedByIndex) {
orderBy = null;
} else {
orderBy = ResultRowImpl.getComparator(orderings);
}
Iterator<ResultRowImpl> it =
FilterIterators.newCombinedFilter(rowIt, distinct, limit, offset, orderBy, settings);
if (orderBy != null) {
// this will force the rows to be read, so that the size is known
it.hasNext();
// we need the size, and there is no other way to get it right now
// but we also have to take limit and offset into account
long read = rowIt.getReadCount();
// we will ignore whatever is behind 'limit+offset'
read = Math.min(saturatedAdd(limit, offset), read);
// and we will skip 'offset' entries
read = Math.max(0, read - offset);
size = read;
}
if (measure) {
// return the measuring iterator delegating the readCounts to the rowIterator
it = new MeasuringIterator(this, it) {
@Override
protected void setColumns(ColumnImpl[] col) {
columns = col;
}
@Override
protected long getReadCount() {
return rowIt.getReadCount();
}
@Override
protected Map<String, Long> getSelectorScanCount() {
Map<String, Long> selectorReadCounts = Maps.newHashMap();
for (SelectorImpl selector : selectors) {
selectorReadCounts.put(selector.getSelectorName(), selector.getScanCount());
}
return selectorReadCounts;
}
};
}
return it;
}
@Override
public boolean isSortedByIndex() {
return isSortedByIndex;
}
private boolean canSortByIndex() {
boolean canSortByIndex = false;
// TODO add issue about order by optimization for multiple selectors
if (orderings != null && selectors.size() == 1) {
IndexPlan plan = selectors.get(0).getExecutionPlan().getIndexPlan();
if (plan != null) {
List<OrderEntry> list = plan.getSortOrder();
if (list != null && list.size() == orderings.length) {
canSortByIndex = true;
for (int i = 0; i < list.size(); i++) {
OrderEntry e = list.get(i);
OrderingImpl o = orderings[i];
DynamicOperandImpl op = o.getOperand();
if (!(op instanceof PropertyValueImpl)) {
// ordered by a function: currently not supported
canSortByIndex = false;
break;
}
// we only have one selector, so no need to check that
// TODO support joins
String pn = ((PropertyValueImpl) op).getPropertyName();
if (!pn.equals(e.getPropertyName())) {
// ordered by another property
canSortByIndex = false;
break;
}
if (o.isDescending() != (e.getOrder() == Order.DESCENDING)) {
// ordered ascending versus descending
canSortByIndex = false;
break;
}
}
}
}
}
return canSortByIndex;
}
@Override
public String getPlan() {
return source.getPlan(context.getBaseState());
}
@Override
public String getIndexCostInfo() {
return source.getIndexCostInfo(context.getBaseState());
}
@Override
public double getEstimatedCost() {
return estimatedCost;
}
@Override
public void prepare() {
if (prepared) {
return;
}
prepared = true;
List<SourceImpl> sources = source.getInnerJoinSelectors();
List<JoinConditionImpl> conditions = source.getInnerJoinConditions();
if (sources.size() <= 1) {
// simple case (no join)
estimatedCost = source.prepare().getEstimatedCost();
isSortedByIndex = canSortByIndex();
return;
}
// use a greedy algorithm
SourceImpl result = null;
Set<SourceImpl> available = new HashSet<SourceImpl>();
// the query is only slow if all possible join orders are slow
// (in theory, due to using the greedy algorithm, a query might be considered
// slow even thought there is a plan that doesn't need to use traversal, but
// only for 3-way and higher joins, and only if traversal is considered very fast)
boolean isPotentiallySlowJoin = true;
while (sources.size() > 0) {
int bestIndex = 0;
double bestCost = Double.POSITIVE_INFINITY;
ExecutionPlan bestPlan = null;
SourceImpl best = null;
for (int i = 0; i < sources.size(); i++) {
SourceImpl test = buildJoin(result, sources.get(i), conditions);
if (test == null) {
// no join condition
continue;
}
ExecutionPlan testPlan = test.prepare();
double cost = testPlan.getEstimatedCost();
if (best == null || cost < bestCost) {
bestPlan = testPlan;
bestCost = cost;
bestIndex = i;
best = test;
}
if (!potentiallySlowTraversalQuery) {
isPotentiallySlowJoin = false;
}
test.unprepare();
}
available.add(sources.remove(bestIndex));
result = best;
best.prepare(bestPlan);
}
potentiallySlowTraversalQuery = isPotentiallySlowJoin;
estimatedCost = result.prepare().getEstimatedCost();
source = result;
isSortedByIndex = canSortByIndex();
}
private static SourceImpl buildJoin(SourceImpl result, SourceImpl last, List<JoinConditionImpl> conditions) {
if (result == null) {
return last;
}
List<SourceImpl> selectors = result.getInnerJoinSelectors();
Set<SourceImpl> oldSelectors = new HashSet<SourceImpl>();
oldSelectors.addAll(selectors);
Set<SourceImpl> newSelectors = new HashSet<SourceImpl>();
newSelectors.addAll(selectors);
newSelectors.add(last);
for (JoinConditionImpl j : conditions) {
// only join conditions can now be evaluated,
// but couldn't be evaluated before
if (!j.canEvaluate(oldSelectors) && j.canEvaluate(newSelectors)) {
JoinImpl join = new JoinImpl(result, last, JoinType.INNER, j);
return join;
}
}
// no join condition was found
return null;
}
/**
* <b>!Test purpose only! <b>
*
* this creates a filter for the given query
*
*/
Filter createFilter(boolean preparing) {
return source.createFilter(preparing);
}
/**
* Abstract decorating iterator for measure queries. The iterator delegates to the underlying actual
* query iterator to lazily execute and return counts.
*/
abstract static class MeasuringIterator extends AbstractIterator<ResultRowImpl> {
private Iterator<ResultRowImpl> delegate;
private Query query;
private List<ResultRowImpl> results;
private boolean init;
MeasuringIterator(Query query, Iterator<ResultRowImpl> delegate) {
this.query = query;
this.delegate = delegate;
results = Lists.newArrayList();
}
@Override
protected ResultRowImpl computeNext() {
if (!init) {
getRows();
}
if (!results.isEmpty()) {
return results.remove(0);
} else {
return endOfData();
}
}
void getRows() {
// run the query
while (delegate.hasNext()) {
delegate.next();
}
ColumnImpl[] columns = new ColumnImpl[] {
new ColumnImpl("measure", "selector", "selector"),
new ColumnImpl("measure", "scanCount", "scanCount")
};
setColumns(columns);
ResultRowImpl r = new ResultRowImpl(query,
Tree.EMPTY_ARRAY,
new PropertyValue[] {
PropertyValues.newString("query"),
PropertyValues.newLong(getReadCount())
},
null, null);
results.add(r);
Map<String, Long> selectorScanCount = getSelectorScanCount();
for (String selector : selectorScanCount.keySet()) {
r = new ResultRowImpl(query,
Tree.EMPTY_ARRAY,
new PropertyValue[] {
PropertyValues.newString(selector),
PropertyValues.newLong(selectorScanCount.get(selector)),
},
null, null);
results.add(r);
}
init = true;
}
/**
* Set the measure specific columns in the query object
* @param columns the measure specific columns
*/
protected abstract void setColumns(ColumnImpl[] columns);
/**
* Retrieve the selector scan count
* @return map of selector to scan count
*/
protected abstract Map<String, Long> getSelectorScanCount();
/**
* Retrieve the query read count
* @return count
*/
protected abstract long getReadCount();
/**
* Retrieves the actual query iterator
* @return the delegate
*/
protected Iterator<ResultRowImpl> getDelegate() {
return delegate;
}
}
/**
* An iterator over result rows.
*/
class RowIterator implements Iterator<ResultRowImpl> {
private final NodeState rootState;
private ResultRowImpl current;
private boolean started, end;
private long rowIndex;
RowIterator(NodeState rootState) {
this.rootState = rootState;
}
public long getReadCount() {
return rowIndex;
}
private void fetchNext() {
if (end) {
return;
}
long nanos = System.nanoTime();
long oldIndex = rowIndex;
if (!started) {
source.execute(rootState);
started = true;
}
while (true) {
if (source.next()) {
if (constraint == null || constraint.evaluate()) {
current = currentRow();
rowIndex++;
break;
}
if (constraint != null && constraint.evaluateStop()) {
current = null;
end = true;
break;
}
} else {
current = null;
end = true;
break;
}
}
nanos = System.nanoTime() - nanos;
stats.read(rowIndex - oldIndex, rowIndex, nanos);
}
@Override
public boolean hasNext() {
if (end) {
return false;
}
if (current == null) {
fetchNext();
}
return !end;
}
@Override
public ResultRowImpl next() {
if (end) {
return null;
}
if (current == null) {
fetchNext();
}
ResultRowImpl r = current;
current = null;
return r;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
ResultRowImpl currentRow() {
int selectorCount = selectors.size();
Tree[] trees = new Tree[selectorCount];
for (int i = 0; i < selectorCount; i++) {
SelectorImpl s = selectors.get(i);
trees[i] = s.currentTree();
}
int columnCount = columns.length;
PropertyValue[] values = new PropertyValue[columnCount];
for (int i = 0; i < columnCount; i++) {
ColumnImpl c = columns[i];
values[i] = c.currentProperty();
}
PropertyValue[] orderValues;
if (orderings == null) {
orderValues = null;
} else {
int size = orderings.length;
orderValues = new PropertyValue[size];
for (int i = 0; i < size; i++) {
orderValues[i] = orderings[i].getOperand().currentProperty();
}
}
return new ResultRowImpl(this, trees, values, distinctColumns, orderValues);
}
@Override
public int getSelectorIndex(String selectorName) {
Integer index = selectorIndexes.get(selectorName);
if (index == null) {
throw new IllegalArgumentException("Unknown selector: " + selectorName);
}
return index;
}
@Override
public int getColumnIndex(String columnName) {
return getColumnIndex(columns, columnName);
}
static int getColumnIndex(ColumnImpl[] columns, String columnName) {
for (int i = 0, size = columns.length; i < size; i++) {
ColumnImpl c = columns[i];
String cn = c.getColumnName();
if (cn != null && cn.equals(columnName)) {
return i;
}
}
return -1;
}
public PropertyValue getBindVariableValue(String bindVariableName) {
PropertyValue v = bindVariableMap.get(bindVariableName);
if (v == null) {
throw new IllegalArgumentException("Bind variable value not set: " + bindVariableName);
}
return v;
}
@Override
public String[] getSelectorNames() {
String[] list = new String[selectors.size()];
for (int i = 0; i < list.length; i++) {
list[i] = selectors.get(i).getSelectorName();
}
// reverse names to that for xpath,
// the first selector is the same as the node iterator
Collections.reverse(Arrays.asList(list));
return list;
}
@Override
public List<String> getBindVariableNames() {
return new ArrayList<String>(bindVariableMap.keySet());
}
@Override
public void setTraversalEnabled(boolean traversalEnabled) {
this.traversalEnabled = traversalEnabled;
}
@Override
public void setQueryOptions(QueryOptions options) {
this.queryOptions = options;
}
public SelectorExecutionPlan getBestSelectorExecutionPlan(FilterImpl filter) {
return getBestSelectorExecutionPlan(context.getBaseState(), filter,
context.getIndexProvider(), traversalEnabled);
}
private SelectorExecutionPlan getBestSelectorExecutionPlan(
NodeState rootState, FilterImpl filter,
QueryIndexProvider indexProvider, boolean traversalEnabled) {
QueryIndex bestIndex = null;
if (LOG.isDebugEnabled()) {
logDebug("cost using filter " + filter);
}
double bestCost = Double.POSITIVE_INFINITY;
IndexPlan bestPlan = null;
// Sort the indexes according to their minimum cost to be able to skip the remaining indexes if the cost of the
// current index is below the minimum cost of the next index.
List<? extends QueryIndex> queryIndexes = MINIMAL_COST_ORDERING
.sortedCopy(indexProvider.getQueryIndexes(rootState));
List<OrderEntry> sortOrder = getSortOrder(filter);
for (int i = 0; i < queryIndexes.size(); i++) {
QueryIndex index = queryIndexes.get(i);
double minCost = index.getMinimumCost();
if (minCost > bestCost) {
// Stop looking if the minimum cost is higher than the current best cost
break;
}
double cost;
String indexName = index.getIndexName();
IndexPlan indexPlan = null;
if (index instanceof AdvancedQueryIndex) {
AdvancedQueryIndex advIndex = (AdvancedQueryIndex) index;
long maxEntryCount = limit;
if (offset > 0) {
if (offset + limit < 0) {
// long overflow
maxEntryCount = Long.MAX_VALUE;
} else {
maxEntryCount = offset + limit;
}
}
List<IndexPlan> ipList = advIndex.getPlans(
filter, sortOrder, rootState);
cost = Double.POSITIVE_INFINITY;
for (IndexPlan p : ipList) {
long entryCount = p.getEstimatedEntryCount();
if (p.getSupportsPathRestriction()) {
entryCount = scaleEntryCount(rootState, filter, entryCount);
}
if (sortOrder == null || p.getSortOrder() != null) {
// if the query is unordered, or
// if the query contains "order by" and the index can sort on that,
// then we don't need to read all entries from the index
entryCount = Math.min(maxEntryCount, entryCount);
}
double c = p.getCostPerExecution() + entryCount * p.getCostPerEntry();
if (LOG.isDebugEnabled()) {
String plan = advIndex.getPlanDescription(p, rootState);
String msg = String.format("cost for [%s] of type (%s) with plan [%s] is %1.2f", p.getPlanName(), indexName, plan, c);
logDebug(msg);
}
if (c < cost) {
cost = c;
indexPlan = p;
}
}
if (indexPlan != null && indexPlan.getPlanName() != null) {
indexName += "[" + indexPlan.getPlanName() + "]";
}
} else {
cost = index.getCost(filter, rootState);
}
if (LOG.isDebugEnabled()) {
logDebug("cost for " + indexName + " is " + cost);
}
if (cost < 0) {
LOG.error("cost below 0 for " + indexName + " is " + cost);
}
if (cost < bestCost) {
bestCost = cost;
bestIndex = index;
bestPlan = indexPlan;
}
}
potentiallySlowTraversalQuery = bestIndex == null;
if (traversalEnabled) {
TraversingIndex traversal = new TraversingIndex();
double cost = traversal.getCost(filter, rootState);
if (LOG.isDebugEnabled()) {
logDebug("cost for " + traversal.getIndexName() + " is " + cost);
}
if (cost < bestCost || bestCost == Double.POSITIVE_INFINITY) {
bestCost = cost;
bestPlan = null;
bestIndex = traversal;
if (potentiallySlowTraversalQuery) {
potentiallySlowTraversalQuery = traversal.isPotentiallySlow(filter, rootState);
}
}
}
return new SelectorExecutionPlan(filter.getSelector(), bestIndex,
bestPlan, bestCost);
}
private long scaleEntryCount(NodeState rootState, FilterImpl filter, long count) {
PathRestriction r = filter.getPathRestriction();
if (r != PathRestriction.ALL_CHILDREN) {
return count;
}
String path = filter.getPath();
if (path.startsWith(JoinConditionImpl.SPECIAL_PATH_PREFIX)) {
// don't know the path currently, could be root
return count;
}
long filterPathCount = NodeCounter.getEstimatedNodeCount(rootState, path, true);
if (filterPathCount < 0) {
// don't know
return count;
}
long totalNodesCount = NodeCounter.getEstimatedNodeCount(rootState, "/", true);
if (totalNodesCount <= 0) {
totalNodesCount = 1;
}
// same logic as for the property index (see ContentMirrorStoreStrategy):
// assume nodes in the index are evenly distributed in the repository (old idea)
long countScaledDown = (long) ((double) count / totalNodesCount * filterPathCount);
// assume 80% of the indexed nodes are in this subtree
long mostNodesFromThisSubtree = (long) (filterPathCount * 0.8);
// count can at most be the assumed subtree size
count = Math.min(count, mostNodesFromThisSubtree);
// this in theory should not have any effect,
// except if the above estimates are incorrect,
// so this is just for safety feature
count = Math.max(count, countScaledDown);
return count;
}
@Override
public boolean isPotentiallySlow() {
return potentiallySlowTraversalQuery;
}
@Override
public void verifyNotPotentiallySlow() {
if (potentiallySlowTraversalQuery) {
QueryOptions.Traversal traversal = queryOptions.traversal;
if (traversal == Traversal.DEFAULT) {
// use the (configured) default
traversal = settings.getFailTraversal() ? Traversal.FAIL : Traversal.WARN;
} else {
// explicitly set in the query
traversal = queryOptions.traversal;
}
String message = "Traversal query (query without index): " + statement + "; consider creating an index";
switch (traversal) {
case DEFAULT:
// not possible (changed to either FAIL or WARN above)
throw new AssertionError();
case OK:
break;
case WARN:
if (!potentiallySlowTraversalQueryLogged) {
LOG.warn(message);
potentiallySlowTraversalQueryLogged = true;
}
break;
case FAIL:
if (!potentiallySlowTraversalQueryLogged) {
LOG.warn(message);
potentiallySlowTraversalQueryLogged = true;
}
throw new IllegalArgumentException(message);
}
}
}
private List<OrderEntry> getSortOrder(FilterImpl filter) {
if (orderings == null) {
return null;
}
ArrayList<OrderEntry> sortOrder = new ArrayList<OrderEntry>();
for (OrderingImpl o : orderings) {
DynamicOperandImpl op = o.getOperand();
OrderEntry e = op.getOrderEntry(filter.getSelector(), o);
if (e == null) {
continue;
}
sortOrder.add(e);
}
if (sortOrder.size() == 0) {
return null;
}
return sortOrder;
}
private void logDebug(String msg) {
if (isInternal) {
LOG.trace(msg);
} else {
LOG.debug(msg);
}
}
@Override
public void setExecutionContext(ExecutionContext context) {
this.context = context;
}
@Override
public void setOrderings(OrderingImpl[] orderings) {
this.orderings = orderings;
}
public NamePathMapper getNamePathMapper() {
return namePathMapper;
}
@Override
public Tree getTree(String path) {
if (NodeStateUtils.isHiddenPath(path)) {
if (!warnedHidden) {
warnedHidden = true;
LOG.warn("Hidden tree traversed: {}", path);
}
return null;
}
return context.getRoot().getTree(path);
}
@Override
public boolean isMeasureOrExplainEnabled() {
return explain || measure;
}
/**
* Validate the path is syntactically correct, and convert it to an Oak
* internal path (including namespace remapping if needed).
*
* @param path the path
* @return the the converted path
*/
public String getOakPath(String path) {
if (path == null) {
return null;
}
if (!JcrPathParser.validate(path)) {
throw new IllegalArgumentException("Invalid path: " + path);
}
String p = namePathMapper.getOakPath(path);
if (p == null) {
throw new IllegalArgumentException("Invalid path or namespace prefix: " + path);
}
return p;
}
@Override
public String toString() {
StringBuilder buff = new StringBuilder();
buff.append("select ");
int i = 0;
for (ColumnImpl c : columns) {
if (i++ > 0) {
buff.append(", ");
}
buff.append(c);
}
buff.append(" from ").append(source);
if (constraint != null) {
buff.append(" where ").append(constraint);
}
if (orderings != null) {
buff.append(" order by ");
i = 0;
for (OrderingImpl o : orderings) {
if (i++ > 0) {
buff.append(", ");
}
buff.append(o);
}
}
return buff.toString();
}
@Override
public long getSize() {
return size;
}
@Override
public long getSize(SizePrecision precision, long max) {
// Note: DISTINCT is ignored
if (size != -1) {
// "order by" was used, so we know the size
return size;
}
return Math.min(limit, source.getSize(precision, max));
}
@Override
public String getStatement() {
return Strings.isNullOrEmpty(statement) ? toString() : statement;
}
public QueryEngineSettings getSettings() {
return settings;
}
@Override
public void setInternal(boolean isInternal) {
this.isInternal = isInternal;
}
public ExecutionContext getExecutionContext() {
return context;
}
/**
* Add two values, but don't let it overflow or underflow.
*
* @param x the first value
* @param y the second value
* @return the sum, or Long.MIN_VALUE for underflow, or Long.MAX_VALUE for
* overflow
*/
public static long saturatedAdd(long x, long y) {
BigInteger min = BigInteger.valueOf(Long.MIN_VALUE);
BigInteger max = BigInteger.valueOf(Long.MAX_VALUE);
BigInteger sum = BigInteger.valueOf(x).add(BigInteger.valueOf(y));
return sum.min(max).max(min).longValue();
}
@Override
public Query buildAlternativeQuery() {
Query result = this;
if (constraint != null) {
Set<ConstraintImpl> unionList;
try {
unionList = constraint.convertToUnion();
} catch (UnsupportedOperationException e) {
// too many union
return this;
}
if (unionList.size() > 1) {
// there are some cases where multiple ORs simplify into a single one. If we get a
// union list of just one we don't really have to UNION anything.
QueryImpl left = null;
Query right = null;
// we have something to do here.
for (ConstraintImpl c : unionList) {
if (right != null) {
right = newAlternativeUnionQuery(left, right);
} else {
// pulling left to the right
if (left != null) {
right = left;
}
}
// cloning original query
left = (QueryImpl) this.copyOf();
// cloning the constraints and assigning to new query
left.constraint = (ConstraintImpl) copyElementAndCheckReference(c);
// re-composing the statement for better debug messages
left.statement = recomposeStatement(left);
}
result = newAlternativeUnionQuery(left, right);
}
}
return result;
}
private static String recomposeStatement(@Nonnull QueryImpl query) {
checkNotNull(query);
String original = query.getStatement();
String origUpper = original.toUpperCase();
StringBuilder recomputed = new StringBuilder();
final String where = " WHERE ";
final String orderBy = " ORDER BY ";
int whereOffset = where.length();
if (query.getConstraint() == null) {
recomputed.append(original);
} else {
recomputed.append(original.substring(0, origUpper.indexOf(where) + whereOffset));
recomputed.append(query.getConstraint());
if (origUpper.indexOf(orderBy) > -1) {
recomputed.append(original.substring(origUpper.indexOf(orderBy)));
}
}
return recomputed.toString();
}
/**
* Convenience method for creating a UnionQueryImpl with proper settings.
*
* @param left the first subquery
* @param right the second subquery
* @return the union query
*/
private UnionQueryImpl newAlternativeUnionQuery(@Nonnull Query left, @Nonnull Query right) {
UnionQueryImpl u = new UnionQueryImpl(
false,
checkNotNull(left, "`left` cannot be null"),
checkNotNull(right, "`right` cannot be null"),
this.settings);
u.setExplain(explain);
u.setMeasure(measure);
u.setInternal(isInternal);
return u;
}
@Override
public Query copyOf() {
if (isInit()) {
throw new IllegalStateException("QueryImpl cannot be cloned once initialised.");
}
List<ColumnImpl> cols = newArrayList();
for (ColumnImpl c : columns) {
cols.add((ColumnImpl) copyElementAndCheckReference(c));
}
QueryImpl copy = new QueryImpl(
this.statement,
(SourceImpl) copyElementAndCheckReference(this.source),
this.constraint,
cols.toArray(new ColumnImpl[0]),
this.namePathMapper,
this.settings,
this.stats);
copy.explain = this.explain;
copy.distinct = this.distinct;
return copy;
}
@Override
public boolean isInit() {
return init;
}
@Override
public boolean isInternal() {
return isInternal;
}
@Override
public boolean containsUnfilteredFullTextCondition() {
return constraint.containsUnfilteredFullTextCondition();
}
public QueryOptions getQueryOptions() {
return queryOptions;
}
public QueryExecutionStats getQueryExecutionStats() {
return stats;
}
}
| oak-core/src/main/java/org/apache/jackrabbit/oak/query/QueryImpl.java | /*
* 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.jackrabbit.oak.query;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static org.apache.jackrabbit.oak.query.ast.AstElementFactory.copyElementAndCheckReference;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.oak.api.PropertyValue;
import org.apache.jackrabbit.oak.api.Result.SizePrecision;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.namepath.JcrPathParser;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.index.counter.jmx.NodeCounter;
import org.apache.jackrabbit.oak.plugins.memory.PropertyValues;
import org.apache.jackrabbit.oak.query.QueryOptions.Traversal;
import org.apache.jackrabbit.oak.query.ast.AndImpl;
import org.apache.jackrabbit.oak.query.ast.AstVisitorBase;
import org.apache.jackrabbit.oak.query.ast.BindVariableValueImpl;
import org.apache.jackrabbit.oak.query.ast.ChildNodeImpl;
import org.apache.jackrabbit.oak.query.ast.ChildNodeJoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.CoalesceImpl;
import org.apache.jackrabbit.oak.query.ast.ColumnImpl;
import org.apache.jackrabbit.oak.query.ast.ComparisonImpl;
import org.apache.jackrabbit.oak.query.ast.ConstraintImpl;
import org.apache.jackrabbit.oak.query.ast.DescendantNodeImpl;
import org.apache.jackrabbit.oak.query.ast.DescendantNodeJoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.DynamicOperandImpl;
import org.apache.jackrabbit.oak.query.ast.EquiJoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.FullTextSearchImpl;
import org.apache.jackrabbit.oak.query.ast.FullTextSearchScoreImpl;
import org.apache.jackrabbit.oak.query.ast.InImpl;
import org.apache.jackrabbit.oak.query.ast.JoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.JoinImpl;
import org.apache.jackrabbit.oak.query.ast.JoinType;
import org.apache.jackrabbit.oak.query.ast.LengthImpl;
import org.apache.jackrabbit.oak.query.ast.LiteralImpl;
import org.apache.jackrabbit.oak.query.ast.LowerCaseImpl;
import org.apache.jackrabbit.oak.query.ast.NativeFunctionImpl;
import org.apache.jackrabbit.oak.query.ast.NodeLocalNameImpl;
import org.apache.jackrabbit.oak.query.ast.NodeNameImpl;
import org.apache.jackrabbit.oak.query.ast.NotImpl;
import org.apache.jackrabbit.oak.query.ast.OrImpl;
import org.apache.jackrabbit.oak.query.ast.OrderingImpl;
import org.apache.jackrabbit.oak.query.ast.PropertyExistenceImpl;
import org.apache.jackrabbit.oak.query.ast.PropertyInexistenceImpl;
import org.apache.jackrabbit.oak.query.ast.PropertyValueImpl;
import org.apache.jackrabbit.oak.query.ast.SameNodeImpl;
import org.apache.jackrabbit.oak.query.ast.SameNodeJoinConditionImpl;
import org.apache.jackrabbit.oak.query.ast.SelectorImpl;
import org.apache.jackrabbit.oak.query.ast.SimilarImpl;
import org.apache.jackrabbit.oak.query.ast.SourceImpl;
import org.apache.jackrabbit.oak.query.ast.SpellcheckImpl;
import org.apache.jackrabbit.oak.query.ast.SuggestImpl;
import org.apache.jackrabbit.oak.query.ast.UpperCaseImpl;
import org.apache.jackrabbit.oak.query.index.FilterImpl;
import org.apache.jackrabbit.oak.query.index.TraversingIndex;
import org.apache.jackrabbit.oak.query.plan.ExecutionPlan;
import org.apache.jackrabbit.oak.query.plan.SelectorExecutionPlan;
import org.apache.jackrabbit.oak.query.stats.QueryStatsData.QueryExecutionStats;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.jackrabbit.oak.spi.query.Filter.PathRestriction;
import org.apache.jackrabbit.oak.spi.query.QueryConstants;
import org.apache.jackrabbit.oak.spi.query.QueryIndex;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.AdvancedQueryIndex;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.IndexPlan;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.OrderEntry;
import org.apache.jackrabbit.oak.spi.query.QueryIndex.OrderEntry.Order;
import org.apache.jackrabbit.oak.spi.query.QueryIndexProvider;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
/**
* Represents a parsed query.
*/
public class QueryImpl implements Query {
public static final UnsupportedOperationException TOO_MANY_UNION =
new UnsupportedOperationException("Too many union queries");
public final static int MAX_UNION = Integer.getInteger("oak.sql2MaxUnion", 1000);
private static final Logger LOG = LoggerFactory.getLogger(QueryImpl.class);
private final QueryExecutionStats stats;
private boolean potentiallySlowTraversalQueryLogged;
private static final Ordering<QueryIndex> MINIMAL_COST_ORDERING = new Ordering<QueryIndex>() {
@Override
public int compare(QueryIndex left, QueryIndex right) {
return Double.compare(left.getMinimumCost(), right.getMinimumCost());
}
};
SourceImpl source;
private String statement;
final HashMap<String, PropertyValue> bindVariableMap = new HashMap<String, PropertyValue>();
final HashMap<String, Integer> selectorIndexes = new HashMap<String, Integer>();
final ArrayList<SelectorImpl> selectors = new ArrayList<SelectorImpl>();
ConstraintImpl constraint;
/**
* Whether fallback to the traversing index is supported if no other index
* is available. This is enabled by default and can be disabled for testing
* purposes.
*/
private boolean traversalEnabled = true;
/**
* The query option to be used for this query.
*/
private QueryOptions queryOptions = new QueryOptions();
private OrderingImpl[] orderings;
private ColumnImpl[] columns;
/**
* The columns that make a row distinct. This is all columns
* except for "jcr:score".
*/
private boolean[] distinctColumns;
private boolean explain, measure;
private boolean distinct;
private long limit = Long.MAX_VALUE;
private long offset;
private long size = -1;
private boolean prepared;
private ExecutionContext context;
/**
* whether the object has been initialised or not
*/
private boolean init;
private boolean isSortedByIndex;
private final NamePathMapper namePathMapper;
private double estimatedCost;
private final QueryEngineSettings settings;
private boolean warnedHidden;
private boolean isInternal;
private boolean potentiallySlowTraversalQuery;
QueryImpl(String statement, SourceImpl source, ConstraintImpl constraint,
ColumnImpl[] columns, NamePathMapper mapper, QueryEngineSettings settings,
QueryExecutionStats stats) {
this.statement = statement;
this.source = source;
this.constraint = constraint;
this.columns = columns;
this.namePathMapper = mapper;
this.settings = settings;
this.stats = stats;
}
@Override
public void init() {
final QueryImpl query = this;
if (constraint != null) {
// need to do this *before* the visitation below, as the
// simplify() method does not always keep the query reference
// passed in setQuery(). TODO: avoid that mutability concern
constraint = constraint.simplify();
}
new AstVisitorBase() {
@Override
public boolean visit(BindVariableValueImpl node) {
node.setQuery(query);
bindVariableMap.put(node.getBindVariableName(), null);
return true;
}
@Override
public boolean visit(ChildNodeImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(ChildNodeJoinConditionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(CoalesceImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(ColumnImpl node) {
node.setQuery(query);
return true;
}
@Override
public boolean visit(DescendantNodeImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(DescendantNodeJoinConditionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(EquiJoinConditionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(FullTextSearchImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(NativeFunctionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(SimilarImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(SpellcheckImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(SuggestImpl node) {
node.setQuery(query);
node.bindSelector(source);
return super.visit(node);
}
@Override
public boolean visit(FullTextSearchScoreImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(LiteralImpl node) {
node.setQuery(query);
return true;
}
@Override
public boolean visit(NodeLocalNameImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(NodeNameImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(PropertyExistenceImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(PropertyInexistenceImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(PropertyValueImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(SameNodeImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(SameNodeJoinConditionImpl node) {
node.setQuery(query);
node.bindSelector(source);
return true;
}
@Override
public boolean visit(SelectorImpl node) {
String name = node.getSelectorName();
if (selectorIndexes.put(name, selectors.size()) != null) {
throw new IllegalArgumentException("Two selectors with the same name: " + name);
}
selectors.add(node);
node.setQuery(query);
return true;
}
@Override
public boolean visit(LengthImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(UpperCaseImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(LowerCaseImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(ComparisonImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(InImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(AndImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(OrImpl node) {
node.setQuery(query);
return super.visit(node);
}
@Override
public boolean visit(NotImpl node) {
node.setQuery(query);
return super.visit(node);
}
}.visit(this);
source.setQueryConstraint(constraint);
for (ColumnImpl column : columns) {
column.bindSelector(source);
}
distinctColumns = new boolean[columns.length];
for (int i = 0; i < columns.length; i++) {
ColumnImpl c = columns[i];
boolean distinct = true;
if (QueryConstants.JCR_SCORE.equals(c.getPropertyName())) {
distinct = false;
}
distinctColumns[i] = distinct;
}
init = true;
}
@Override
public ColumnImpl[] getColumns() {
return columns;
}
public ConstraintImpl getConstraint() {
return constraint;
}
public OrderingImpl[] getOrderings() {
return orderings;
}
public SourceImpl getSource() {
return source;
}
@Override
public void bindValue(String varName, PropertyValue value) {
bindVariableMap.put(varName, value);
}
@Override
public void setLimit(long limit) {
this.limit = limit;
}
@Override
public void setOffset(long offset) {
this.offset = offset;
}
@Override
public void setExplain(boolean explain) {
this.explain = explain;
}
@Override
public void setMeasure(boolean measure) {
this.measure = measure;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
@Override
public ResultImpl executeQuery() {
return new ResultImpl(this);
}
@Override
public Iterator<ResultRowImpl> getRows() {
prepare();
if (explain) {
String plan = getPlan();
if (measure) {
plan += " cost: { " + getIndexCostInfo() + " }";
}
columns = new ColumnImpl[] { new ColumnImpl("explain", "plan", "plan")};
ResultRowImpl r = new ResultRowImpl(this,
Tree.EMPTY_ARRAY,
new PropertyValue[] { PropertyValues.newString(plan)},
null, null);
return Arrays.asList(r).iterator();
}
if (LOG.isDebugEnabled()) {
logDebug("query execute " + statement);
logDebug("query plan " + getPlan());
}
final RowIterator rowIt = new RowIterator(context.getBaseState());
Comparator<ResultRowImpl> orderBy;
if (isSortedByIndex) {
orderBy = null;
} else {
orderBy = ResultRowImpl.getComparator(orderings);
}
Iterator<ResultRowImpl> it =
FilterIterators.newCombinedFilter(rowIt, distinct, limit, offset, orderBy, settings);
if (orderBy != null) {
// this will force the rows to be read, so that the size is known
it.hasNext();
// we need the size, and there is no other way to get it right now
// but we also have to take limit and offset into account
long read = rowIt.getReadCount();
// we will ignore whatever is behind 'limit+offset'
read = Math.min(saturatedAdd(limit, offset), read);
// and we will skip 'offset' entries
read = Math.max(0, read - offset);
size = read;
}
if (measure) {
// return the measuring iterator delegating the readCounts to the rowIterator
it = new MeasuringIterator(this, it) {
@Override
protected void setColumns(ColumnImpl[] col) {
columns = col;
}
@Override
protected long getReadCount() {
return rowIt.getReadCount();
}
@Override
protected Map<String, Long> getSelectorScanCount() {
Map<String, Long> selectorReadCounts = Maps.newHashMap();
for (SelectorImpl selector : selectors) {
selectorReadCounts.put(selector.getSelectorName(), selector.getScanCount());
}
return selectorReadCounts;
}
};
}
return it;
}
@Override
public boolean isSortedByIndex() {
return isSortedByIndex;
}
private boolean canSortByIndex() {
boolean canSortByIndex = false;
// TODO add issue about order by optimization for multiple selectors
if (orderings != null && selectors.size() == 1) {
IndexPlan plan = selectors.get(0).getExecutionPlan().getIndexPlan();
if (plan != null) {
List<OrderEntry> list = plan.getSortOrder();
if (list != null && list.size() == orderings.length) {
canSortByIndex = true;
for (int i = 0; i < list.size(); i++) {
OrderEntry e = list.get(i);
OrderingImpl o = orderings[i];
DynamicOperandImpl op = o.getOperand();
if (!(op instanceof PropertyValueImpl)) {
// ordered by a function: currently not supported
canSortByIndex = false;
break;
}
// we only have one selector, so no need to check that
// TODO support joins
String pn = ((PropertyValueImpl) op).getPropertyName();
if (!pn.equals(e.getPropertyName())) {
// ordered by another property
canSortByIndex = false;
break;
}
if (o.isDescending() != (e.getOrder() == Order.DESCENDING)) {
// ordered ascending versus descending
canSortByIndex = false;
break;
}
}
}
}
}
return canSortByIndex;
}
@Override
public String getPlan() {
return source.getPlan(context.getBaseState());
}
@Override
public String getIndexCostInfo() {
return source.getIndexCostInfo(context.getBaseState());
}
@Override
public double getEstimatedCost() {
return estimatedCost;
}
@Override
public void prepare() {
if (prepared) {
return;
}
prepared = true;
List<SourceImpl> sources = source.getInnerJoinSelectors();
List<JoinConditionImpl> conditions = source.getInnerJoinConditions();
if (sources.size() <= 1) {
// simple case (no join)
estimatedCost = source.prepare().getEstimatedCost();
isSortedByIndex = canSortByIndex();
return;
}
// use a greedy algorithm
SourceImpl result = null;
Set<SourceImpl> available = new HashSet<SourceImpl>();
// the query is only slow if all possible join orders are slow
// (in theory, due to using the greedy algorithm, a query might be considered
// slow even thought there is a plan that doesn't need to use traversal, but
// only for 3-way and higher joins, and only if traversal is considered very fast)
boolean isPotentiallySlowJoin = true;
while (sources.size() > 0) {
int bestIndex = 0;
double bestCost = Double.POSITIVE_INFINITY;
ExecutionPlan bestPlan = null;
SourceImpl best = null;
for (int i = 0; i < sources.size(); i++) {
SourceImpl test = buildJoin(result, sources.get(i), conditions);
if (test == null) {
// no join condition
continue;
}
ExecutionPlan testPlan = test.prepare();
double cost = testPlan.getEstimatedCost();
if (best == null || cost < bestCost) {
bestPlan = testPlan;
bestCost = cost;
bestIndex = i;
best = test;
}
if (!potentiallySlowTraversalQuery) {
isPotentiallySlowJoin = false;
}
test.unprepare();
}
available.add(sources.remove(bestIndex));
result = best;
best.prepare(bestPlan);
}
potentiallySlowTraversalQuery = isPotentiallySlowJoin;
estimatedCost = result.prepare().getEstimatedCost();
source = result;
isSortedByIndex = canSortByIndex();
}
private static SourceImpl buildJoin(SourceImpl result, SourceImpl last, List<JoinConditionImpl> conditions) {
if (result == null) {
return last;
}
List<SourceImpl> selectors = result.getInnerJoinSelectors();
Set<SourceImpl> oldSelectors = new HashSet<SourceImpl>();
oldSelectors.addAll(selectors);
Set<SourceImpl> newSelectors = new HashSet<SourceImpl>();
newSelectors.addAll(selectors);
newSelectors.add(last);
for (JoinConditionImpl j : conditions) {
// only join conditions can now be evaluated,
// but couldn't be evaluated before
if (!j.canEvaluate(oldSelectors) && j.canEvaluate(newSelectors)) {
JoinImpl join = new JoinImpl(result, last, JoinType.INNER, j);
return join;
}
}
// no join condition was found
return null;
}
/**
* <b>!Test purpose only! <b>
*
* this creates a filter for the given query
*
*/
Filter createFilter(boolean preparing) {
return source.createFilter(preparing);
}
/**
* Abstract decorating iterator for measure queries. The iterator delegates to the underlying actual
* query iterator to lazily execute and return counts.
*/
abstract static class MeasuringIterator extends AbstractIterator<ResultRowImpl> {
private Iterator<ResultRowImpl> delegate;
private Query query;
private List<ResultRowImpl> results;
private boolean init;
MeasuringIterator(Query query, Iterator<ResultRowImpl> delegate) {
this.query = query;
this.delegate = delegate;
results = Lists.newArrayList();
}
@Override
protected ResultRowImpl computeNext() {
if (!init) {
getRows();
}
if (!results.isEmpty()) {
return results.remove(0);
} else {
return endOfData();
}
}
void getRows() {
// run the query
while (delegate.hasNext()) {
delegate.next();
}
ColumnImpl[] columns = new ColumnImpl[] {
new ColumnImpl("measure", "selector", "selector"),
new ColumnImpl("measure", "scanCount", "scanCount")
};
setColumns(columns);
ResultRowImpl r = new ResultRowImpl(query,
Tree.EMPTY_ARRAY,
new PropertyValue[] {
PropertyValues.newString("query"),
PropertyValues.newLong(getReadCount())
},
null, null);
results.add(r);
Map<String, Long> selectorScanCount = getSelectorScanCount();
for (String selector : selectorScanCount.keySet()) {
r = new ResultRowImpl(query,
Tree.EMPTY_ARRAY,
new PropertyValue[] {
PropertyValues.newString(selector),
PropertyValues.newLong(selectorScanCount.get(selector)),
},
null, null);
results.add(r);
}
init = true;
}
/**
* Set the measure specific columns in the query object
* @param columns the measure specific columns
*/
protected abstract void setColumns(ColumnImpl[] columns);
/**
* Retrieve the selector scan count
* @return map of selector to scan count
*/
protected abstract Map<String, Long> getSelectorScanCount();
/**
* Retrieve the query read count
* @return count
*/
protected abstract long getReadCount();
/**
* Retrieves the actual query iterator
* @return the delegate
*/
protected Iterator<ResultRowImpl> getDelegate() {
return delegate;
}
}
/**
* An iterator over result rows.
*/
class RowIterator implements Iterator<ResultRowImpl> {
private final NodeState rootState;
private ResultRowImpl current;
private boolean started, end;
private long rowIndex;
RowIterator(NodeState rootState) {
this.rootState = rootState;
}
public long getReadCount() {
return rowIndex;
}
private void fetchNext() {
if (end) {
return;
}
long nanos = System.nanoTime();
long oldIndex = rowIndex;
if (!started) {
source.execute(rootState);
started = true;
}
while (true) {
if (source.next()) {
if (constraint == null || constraint.evaluate()) {
current = currentRow();
rowIndex++;
break;
}
if (constraint != null && constraint.evaluateStop()) {
current = null;
end = true;
break;
}
} else {
current = null;
end = true;
break;
}
}
nanos = System.nanoTime() - nanos;
stats.read(rowIndex - oldIndex, rowIndex, nanos);
}
@Override
public boolean hasNext() {
if (end) {
return false;
}
if (current == null) {
fetchNext();
}
return !end;
}
@Override
public ResultRowImpl next() {
if (end) {
return null;
}
if (current == null) {
fetchNext();
}
ResultRowImpl r = current;
current = null;
return r;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
ResultRowImpl currentRow() {
int selectorCount = selectors.size();
Tree[] trees = new Tree[selectorCount];
for (int i = 0; i < selectorCount; i++) {
SelectorImpl s = selectors.get(i);
trees[i] = s.currentTree();
}
int columnCount = columns.length;
PropertyValue[] values = new PropertyValue[columnCount];
for (int i = 0; i < columnCount; i++) {
ColumnImpl c = columns[i];
values[i] = c.currentProperty();
}
PropertyValue[] orderValues;
if (orderings == null) {
orderValues = null;
} else {
int size = orderings.length;
orderValues = new PropertyValue[size];
for (int i = 0; i < size; i++) {
orderValues[i] = orderings[i].getOperand().currentProperty();
}
}
return new ResultRowImpl(this, trees, values, distinctColumns, orderValues);
}
@Override
public int getSelectorIndex(String selectorName) {
Integer index = selectorIndexes.get(selectorName);
if (index == null) {
throw new IllegalArgumentException("Unknown selector: " + selectorName);
}
return index;
}
@Override
public int getColumnIndex(String columnName) {
return getColumnIndex(columns, columnName);
}
static int getColumnIndex(ColumnImpl[] columns, String columnName) {
for (int i = 0, size = columns.length; i < size; i++) {
ColumnImpl c = columns[i];
String cn = c.getColumnName();
if (cn != null && cn.equals(columnName)) {
return i;
}
}
return -1;
}
public PropertyValue getBindVariableValue(String bindVariableName) {
PropertyValue v = bindVariableMap.get(bindVariableName);
if (v == null) {
throw new IllegalArgumentException("Bind variable value not set: " + bindVariableName);
}
return v;
}
@Override
public String[] getSelectorNames() {
String[] list = new String[selectors.size()];
for (int i = 0; i < list.length; i++) {
list[i] = selectors.get(i).getSelectorName();
}
// reverse names to that for xpath,
// the first selector is the same as the node iterator
Collections.reverse(Arrays.asList(list));
return list;
}
@Override
public List<String> getBindVariableNames() {
return new ArrayList<String>(bindVariableMap.keySet());
}
@Override
public void setTraversalEnabled(boolean traversalEnabled) {
this.traversalEnabled = traversalEnabled;
}
@Override
public void setQueryOptions(QueryOptions options) {
this.queryOptions = options;
}
public SelectorExecutionPlan getBestSelectorExecutionPlan(FilterImpl filter) {
return getBestSelectorExecutionPlan(context.getBaseState(), filter,
context.getIndexProvider(), traversalEnabled);
}
private SelectorExecutionPlan getBestSelectorExecutionPlan(
NodeState rootState, FilterImpl filter,
QueryIndexProvider indexProvider, boolean traversalEnabled) {
QueryIndex bestIndex = null;
if (LOG.isDebugEnabled()) {
logDebug("cost using filter " + filter);
}
double bestCost = Double.POSITIVE_INFINITY;
IndexPlan bestPlan = null;
// Sort the indexes according to their minimum cost to be able to skip the remaining indexes if the cost of the
// current index is below the minimum cost of the next index.
List<? extends QueryIndex> queryIndexes = MINIMAL_COST_ORDERING
.sortedCopy(indexProvider.getQueryIndexes(rootState));
List<OrderEntry> sortOrder = getSortOrder(filter);
for (int i = 0; i < queryIndexes.size(); i++) {
QueryIndex index = queryIndexes.get(i);
double minCost = index.getMinimumCost();
if (minCost > bestCost) {
// Stop looking if the minimum cost is higher than the current best cost
break;
}
double cost;
String indexName = index.getIndexName();
IndexPlan indexPlan = null;
if (index instanceof AdvancedQueryIndex) {
AdvancedQueryIndex advIndex = (AdvancedQueryIndex) index;
long maxEntryCount = limit;
if (offset > 0) {
if (offset + limit < 0) {
// long overflow
maxEntryCount = Long.MAX_VALUE;
} else {
maxEntryCount = offset + limit;
}
}
List<IndexPlan> ipList = advIndex.getPlans(
filter, sortOrder, rootState);
cost = Double.POSITIVE_INFINITY;
for (IndexPlan p : ipList) {
long entryCount = p.getEstimatedEntryCount();
if (p.getSupportsPathRestriction()) {
entryCount = scaleEntryCount(rootState, filter, entryCount);
}
entryCount = Math.min(maxEntryCount, entryCount);
double c = p.getCostPerExecution() + entryCount * p.getCostPerEntry();
if (LOG.isDebugEnabled()) {
String plan = advIndex.getPlanDescription(p, rootState);
String msg = String.format("cost for [%s] of type (%s) with plan [%s] is %1.2f", p.getPlanName(), indexName, plan, c);
logDebug(msg);
}
if (c < cost) {
cost = c;
indexPlan = p;
}
}
if (indexPlan != null && indexPlan.getPlanName() != null) {
indexName += "[" + indexPlan.getPlanName() + "]";
}
} else {
cost = index.getCost(filter, rootState);
}
if (LOG.isDebugEnabled()) {
logDebug("cost for " + indexName + " is " + cost);
}
if (cost < 0) {
LOG.error("cost below 0 for " + indexName + " is " + cost);
}
if (cost < bestCost) {
bestCost = cost;
bestIndex = index;
bestPlan = indexPlan;
}
}
potentiallySlowTraversalQuery = bestIndex == null;
if (traversalEnabled) {
TraversingIndex traversal = new TraversingIndex();
double cost = traversal.getCost(filter, rootState);
if (LOG.isDebugEnabled()) {
logDebug("cost for " + traversal.getIndexName() + " is " + cost);
}
if (cost < bestCost || bestCost == Double.POSITIVE_INFINITY) {
bestCost = cost;
bestPlan = null;
bestIndex = traversal;
if (potentiallySlowTraversalQuery) {
potentiallySlowTraversalQuery = traversal.isPotentiallySlow(filter, rootState);
}
}
}
return new SelectorExecutionPlan(filter.getSelector(), bestIndex,
bestPlan, bestCost);
}
private long scaleEntryCount(NodeState rootState, FilterImpl filter, long count) {
PathRestriction r = filter.getPathRestriction();
if (r != PathRestriction.ALL_CHILDREN) {
return count;
}
String path = filter.getPath();
if (path.startsWith(JoinConditionImpl.SPECIAL_PATH_PREFIX)) {
// don't know the path currently, could be root
return count;
}
long filterPathCount = NodeCounter.getEstimatedNodeCount(rootState, path, true);
if (filterPathCount < 0) {
// don't know
return count;
}
long totalNodesCount = NodeCounter.getEstimatedNodeCount(rootState, "/", true);
if (totalNodesCount <= 0) {
totalNodesCount = 1;
}
// same logic as for the property index (see ContentMirrorStoreStrategy):
// assume nodes in the index are evenly distributed in the repository (old idea)
long countScaledDown = (long) ((double) count / totalNodesCount * filterPathCount);
// assume 80% of the indexed nodes are in this subtree
long mostNodesFromThisSubtree = (long) (filterPathCount * 0.8);
// count can at most be the assumed subtree size
count = Math.min(count, mostNodesFromThisSubtree);
// this in theory should not have any effect,
// except if the above estimates are incorrect,
// so this is just for safety feature
count = Math.max(count, countScaledDown);
return count;
}
@Override
public boolean isPotentiallySlow() {
return potentiallySlowTraversalQuery;
}
@Override
public void verifyNotPotentiallySlow() {
if (potentiallySlowTraversalQuery) {
QueryOptions.Traversal traversal = queryOptions.traversal;
if (traversal == Traversal.DEFAULT) {
// use the (configured) default
traversal = settings.getFailTraversal() ? Traversal.FAIL : Traversal.WARN;
} else {
// explicitly set in the query
traversal = queryOptions.traversal;
}
String message = "Traversal query (query without index): " + statement + "; consider creating an index";
switch (traversal) {
case DEFAULT:
// not possible (changed to either FAIL or WARN above)
throw new AssertionError();
case OK:
break;
case WARN:
if (!potentiallySlowTraversalQueryLogged) {
LOG.warn(message);
potentiallySlowTraversalQueryLogged = true;
}
break;
case FAIL:
if (!potentiallySlowTraversalQueryLogged) {
LOG.warn(message);
potentiallySlowTraversalQueryLogged = true;
}
throw new IllegalArgumentException(message);
}
}
}
private List<OrderEntry> getSortOrder(FilterImpl filter) {
if (orderings == null) {
return null;
}
ArrayList<OrderEntry> sortOrder = new ArrayList<OrderEntry>();
for (OrderingImpl o : orderings) {
DynamicOperandImpl op = o.getOperand();
OrderEntry e = op.getOrderEntry(filter.getSelector(), o);
if (e == null) {
continue;
}
sortOrder.add(e);
}
if (sortOrder.size() == 0) {
return null;
}
return sortOrder;
}
private void logDebug(String msg) {
if (isInternal) {
LOG.trace(msg);
} else {
LOG.debug(msg);
}
}
@Override
public void setExecutionContext(ExecutionContext context) {
this.context = context;
}
@Override
public void setOrderings(OrderingImpl[] orderings) {
this.orderings = orderings;
}
public NamePathMapper getNamePathMapper() {
return namePathMapper;
}
@Override
public Tree getTree(String path) {
if (NodeStateUtils.isHiddenPath(path)) {
if (!warnedHidden) {
warnedHidden = true;
LOG.warn("Hidden tree traversed: {}", path);
}
return null;
}
return context.getRoot().getTree(path);
}
@Override
public boolean isMeasureOrExplainEnabled() {
return explain || measure;
}
/**
* Validate the path is syntactically correct, and convert it to an Oak
* internal path (including namespace remapping if needed).
*
* @param path the path
* @return the the converted path
*/
public String getOakPath(String path) {
if (path == null) {
return null;
}
if (!JcrPathParser.validate(path)) {
throw new IllegalArgumentException("Invalid path: " + path);
}
String p = namePathMapper.getOakPath(path);
if (p == null) {
throw new IllegalArgumentException("Invalid path or namespace prefix: " + path);
}
return p;
}
@Override
public String toString() {
StringBuilder buff = new StringBuilder();
buff.append("select ");
int i = 0;
for (ColumnImpl c : columns) {
if (i++ > 0) {
buff.append(", ");
}
buff.append(c);
}
buff.append(" from ").append(source);
if (constraint != null) {
buff.append(" where ").append(constraint);
}
if (orderings != null) {
buff.append(" order by ");
i = 0;
for (OrderingImpl o : orderings) {
if (i++ > 0) {
buff.append(", ");
}
buff.append(o);
}
}
return buff.toString();
}
@Override
public long getSize() {
return size;
}
@Override
public long getSize(SizePrecision precision, long max) {
// Note: DISTINCT is ignored
if (size != -1) {
// "order by" was used, so we know the size
return size;
}
return Math.min(limit, source.getSize(precision, max));
}
@Override
public String getStatement() {
return Strings.isNullOrEmpty(statement) ? toString() : statement;
}
public QueryEngineSettings getSettings() {
return settings;
}
@Override
public void setInternal(boolean isInternal) {
this.isInternal = isInternal;
}
public ExecutionContext getExecutionContext() {
return context;
}
/**
* Add two values, but don't let it overflow or underflow.
*
* @param x the first value
* @param y the second value
* @return the sum, or Long.MIN_VALUE for underflow, or Long.MAX_VALUE for
* overflow
*/
public static long saturatedAdd(long x, long y) {
BigInteger min = BigInteger.valueOf(Long.MIN_VALUE);
BigInteger max = BigInteger.valueOf(Long.MAX_VALUE);
BigInteger sum = BigInteger.valueOf(x).add(BigInteger.valueOf(y));
return sum.min(max).max(min).longValue();
}
@Override
public Query buildAlternativeQuery() {
Query result = this;
if (constraint != null) {
Set<ConstraintImpl> unionList;
try {
unionList = constraint.convertToUnion();
} catch (UnsupportedOperationException e) {
// too many union
return this;
}
if (unionList.size() > 1) {
// there are some cases where multiple ORs simplify into a single one. If we get a
// union list of just one we don't really have to UNION anything.
QueryImpl left = null;
Query right = null;
// we have something to do here.
for (ConstraintImpl c : unionList) {
if (right != null) {
right = newAlternativeUnionQuery(left, right);
} else {
// pulling left to the right
if (left != null) {
right = left;
}
}
// cloning original query
left = (QueryImpl) this.copyOf();
// cloning the constraints and assigning to new query
left.constraint = (ConstraintImpl) copyElementAndCheckReference(c);
// re-composing the statement for better debug messages
left.statement = recomposeStatement(left);
}
result = newAlternativeUnionQuery(left, right);
}
}
return result;
}
private static String recomposeStatement(@Nonnull QueryImpl query) {
checkNotNull(query);
String original = query.getStatement();
String origUpper = original.toUpperCase();
StringBuilder recomputed = new StringBuilder();
final String where = " WHERE ";
final String orderBy = " ORDER BY ";
int whereOffset = where.length();
if (query.getConstraint() == null) {
recomputed.append(original);
} else {
recomputed.append(original.substring(0, origUpper.indexOf(where) + whereOffset));
recomputed.append(query.getConstraint());
if (origUpper.indexOf(orderBy) > -1) {
recomputed.append(original.substring(origUpper.indexOf(orderBy)));
}
}
return recomputed.toString();
}
/**
* Convenience method for creating a UnionQueryImpl with proper settings.
*
* @param left the first subquery
* @param right the second subquery
* @return the union query
*/
private UnionQueryImpl newAlternativeUnionQuery(@Nonnull Query left, @Nonnull Query right) {
UnionQueryImpl u = new UnionQueryImpl(
false,
checkNotNull(left, "`left` cannot be null"),
checkNotNull(right, "`right` cannot be null"),
this.settings);
u.setExplain(explain);
u.setMeasure(measure);
u.setInternal(isInternal);
return u;
}
@Override
public Query copyOf() {
if (isInit()) {
throw new IllegalStateException("QueryImpl cannot be cloned once initialised.");
}
List<ColumnImpl> cols = newArrayList();
for (ColumnImpl c : columns) {
cols.add((ColumnImpl) copyElementAndCheckReference(c));
}
QueryImpl copy = new QueryImpl(
this.statement,
(SourceImpl) copyElementAndCheckReference(this.source),
this.constraint,
cols.toArray(new ColumnImpl[0]),
this.namePathMapper,
this.settings,
this.stats);
copy.explain = this.explain;
copy.distinct = this.distinct;
return copy;
}
@Override
public boolean isInit() {
return init;
}
@Override
public boolean isInternal() {
return isInternal;
}
@Override
public boolean containsUnfilteredFullTextCondition() {
return constraint.containsUnfilteredFullTextCondition();
}
public QueryOptions getQueryOptions() {
return queryOptions;
}
public QueryExecutionStats getQueryExecutionStats() {
return stats;
}
}
| OAK-4887 Query cost estimation: ordering by an unindexed property not reflected
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1815440 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/main/java/org/apache/jackrabbit/oak/query/QueryImpl.java | OAK-4887 Query cost estimation: ordering by an unindexed property not reflected |
|
Java | apache-2.0 | b53011698af522a04f0aa8ccd2c0602ad9b97492 | 0 | mdogan/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,mesutcelik/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,tombujok/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,dsukhoroslov/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,juanavelez/hazelcast,Donnerbart/hazelcast,tombujok/hazelcast,Donnerbart/hazelcast,tkountis/hazelcast,lmjacksoniii/hazelcast,tufangorel/hazelcast,dbrimley/hazelcast,emre-aydin/hazelcast,mdogan/hazelcast,emrahkocaman/hazelcast,dbrimley/hazelcast,tufangorel/hazelcast,mdogan/hazelcast,emre-aydin/hazelcast,juanavelez/hazelcast,emrahkocaman/hazelcast,lmjacksoniii/hazelcast,mesutcelik/hazelcast | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.nio;
import com.hazelcast.logging.Logger;
import com.hazelcast.util.EmptyStatement;
import com.hazelcast.util.QuickMath;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.UTFDataFormatException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/**
* Class to encode/decode UTF-Strings to and from byte-arrays.
*/
public final class UTFEncoderDecoder {
private static final int STRING_CHUNK_SIZE = 16 * 1024;
private static final UTFEncoderDecoder INSTANCE;
// Because this flag is not set for Non-Buffered Data Output classes
// but results may be compared in unit tests.
// Buffered Data Output may set this flag
// but Non-Buffered Data Output class always set this flag to "false".
// So their results may be different.
private static final boolean ASCII_AWARE =
Boolean.parseBoolean(System.getProperty("hazelcast.nio.asciiaware", "false"));
static {
INSTANCE = buildUTFUtil();
}
private final StringCreator stringCreator;
private final UtfWriter utfWriter;
private final boolean hazelcastEnterpriseActive;
UTFEncoderDecoder(StringCreator stringCreator, UtfWriter utfWriter) {
this(stringCreator, utfWriter, false);
}
UTFEncoderDecoder(StringCreator stringCreator, UtfWriter utfWriter, boolean hazelcastEnterpriseActive) {
this.stringCreator = stringCreator;
this.utfWriter = utfWriter;
this.hazelcastEnterpriseActive = hazelcastEnterpriseActive;
}
public boolean isHazelcastEnterpriseActive() {
return hazelcastEnterpriseActive;
}
public static void writeUTF(final DataOutput out,
final String str,
final byte[] buffer) throws IOException {
INSTANCE.writeUTF0(out, str, buffer);
}
public static String readUTF(final DataInput in,
final byte[] buffer) throws IOException {
return INSTANCE.readUTF0(in, buffer);
}
// ********************************************************************* //
public void writeUTF0(final DataOutput out,
final String str,
final byte[] buffer) throws IOException {
if (!QuickMath.isPowerOfTwo(buffer.length)) {
throw new IllegalArgumentException(
"Size of the buffer has to be power of two, was " + buffer.length);
}
boolean isNull = str == null;
out.writeBoolean(isNull);
if (isNull) {
return;
}
int length = str.length();
out.writeInt(length);
out.writeInt(length);
if (length > 0) {
int chunkSize = (length / STRING_CHUNK_SIZE) + 1;
for (int i = 0; i < chunkSize; i++) {
int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1);
int endIndex = Math.min((i + 1) * STRING_CHUNK_SIZE - 1, length);
utfWriter.writeShortUTF(out, str, beginIndex, endIndex, buffer);
}
}
}
// ********************************************************************* //
interface UtfWriter {
void writeShortUTF(final DataOutput out,
final String str,
final int beginIndex,
final int endIndex,
final byte[] buffer) throws IOException;
}
private abstract static class AbstractCharArrayUtfWriter implements UtfWriter {
//CHECKSTYLE:OFF
@Override
public final void writeShortUTF(final DataOutput out,
final String str,
final int beginIndex,
final int endIndex,
final byte[] buffer) throws IOException {
final boolean isBufferObjectDataOutput = out instanceof BufferObjectDataOutput;
final BufferObjectDataOutput bufferObjectDataOutput =
isBufferObjectDataOutput ? (BufferObjectDataOutput) out : null;
final char[] value = getCharArray(str);
int i;
int c;
int bufferPos = 0;
int utfLength = 0;
int utfLengthLimit;
int pos = 0;
if (isBufferObjectDataOutput) {
// At most, one character can hold 3 bytes
utfLengthLimit = str.length() * 3;
// We save current position of buffer data output.
// Then we write the length of UTF and ASCII state to here
pos = bufferObjectDataOutput.position();
// Moving position explicitly is not good way
// since it may cause overflow exceptions for example "ByteArrayObjectDataOutput".
// So, write dummy data and let DataOutput handle it by expanding or etc ...
bufferObjectDataOutput.writeShort(0);
if (ASCII_AWARE) {
bufferObjectDataOutput.writeBoolean(false);
}
} else {
utfLength = calculateUtf8Length(value, beginIndex, endIndex);
if (utfLength > 65535) {
throw new UTFDataFormatException(
"encoded string too long:" + utfLength + " bytes");
}
utfLengthLimit = utfLength;
out.writeShort(utfLength);
if (ASCII_AWARE) {
// We cannot determine that all characters are ASCII or not without iterating over it
// So, we mark it as not ASCII, so all characters will be checked.
out.writeBoolean(false);
}
}
if (buffer.length >= utfLengthLimit) {
for (i = beginIndex; i < endIndex; i++) {
c = value[i];
if (!(c <= 0x007F && c >= 0x0001)) {
break;
}
buffer[bufferPos++] = (byte) c;
}
for (; i < endIndex; i++) {
c = value[i];
if (c <= 0x007F && c >= 0x0001) {
buffer[bufferPos++] = (byte) c;
} else if (c > 0x07FF) {
buffer[bufferPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
buffer[bufferPos++] = (byte) (0x80 | ((c >> 6) & 0x3F));
buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F));
} else {
buffer[bufferPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F));
}
}
out.write(buffer, 0, bufferPos);
if (isBufferObjectDataOutput) {
utfLength = bufferPos;
}
} else {
for (i = beginIndex; i < endIndex; i++) {
c = value[i];
if (!(c <= 0x007F && c >= 0x0001)) {
break;
}
bufferPos = buffering(buffer, bufferPos, (byte) c, out);
}
if (isBufferObjectDataOutput) {
utfLength = i - beginIndex;
}
for (; i < endIndex; i++) {
c = value[i];
if (c <= 0x007F && c >= 0x0001) {
bufferPos = buffering(buffer, bufferPos, (byte) c, out);
if (isBufferObjectDataOutput) {
utfLength++;
}
} else if (c > 0x07FF) {
bufferPos = buffering(buffer, bufferPos,
(byte) (0xE0 | ((c >> 12) & 0x0F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c >> 6) & 0x3F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c) & 0x3F)), out);
if (isBufferObjectDataOutput) {
utfLength += 3;
}
} else {
bufferPos = buffering(buffer, bufferPos,
(byte) (0xC0 | ((c >> 6) & 0x1F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c) & 0x3F)), out);
if (isBufferObjectDataOutput) {
utfLength += 2;
}
}
}
int length = bufferPos % buffer.length;
out.write(buffer, 0, length == 0 ? buffer.length : length);
}
if (isBufferObjectDataOutput) {
if (utfLength > 65535) {
throw new UTFDataFormatException(
"encoded string too long:" + utfLength + " bytes");
}
// Write the length of UTF to saved position before
bufferObjectDataOutput.writeShort(pos, utfLength);
// Write the ASCII status of UTF to saved position before
if (ASCII_AWARE) {
bufferObjectDataOutput.writeBoolean(pos + 2, utfLength == str.length());
}
}
}
protected abstract boolean isAvailable();
protected abstract char[] getCharArray(String str);
//CHECKSTYLE:ON
}
static class UnsafeBasedCharArrayUtfWriter extends AbstractCharArrayUtfWriter {
private static final sun.misc.Unsafe UNSAFE = UnsafeHelper.UNSAFE;
private static final long VALUE_FIELD_OFFSET;
static {
long offset = -1;
if (UnsafeHelper.UNSAFE_AVAILABLE) {
try {
offset = UNSAFE.objectFieldOffset(String.class.getDeclaredField("value"));
} catch (Throwable t) {
EmptyStatement.ignore(t);
}
}
VALUE_FIELD_OFFSET = offset;
}
@Override
public boolean isAvailable() {
return UnsafeHelper.UNSAFE_AVAILABLE && VALUE_FIELD_OFFSET != -1;
}
@Override
protected char[] getCharArray(String str) {
char[] chars = (char[]) UNSAFE.getObject(str, VALUE_FIELD_OFFSET);
if (chars.length > str.length()) {
// substring detected!
// jdk6 substring shares the same value array
// with the original string (this is not the case for jdk7+)
// we need to get copy of substring array
chars = str.toCharArray();
}
return chars;
}
}
static class ReflectionBasedCharArrayUtfWriter extends AbstractCharArrayUtfWriter {
private static final Field VALUE_FIELD;
static {
Field field;
try {
field = String.class.getDeclaredField("value");
field.setAccessible(true);
} catch (Throwable t) {
EmptyStatement.ignore(t);
field = null;
}
VALUE_FIELD = field;
}
@Override
public boolean isAvailable() {
return VALUE_FIELD != null;
}
@Override
protected char[] getCharArray(String str) {
try {
char[] chars = (char[]) VALUE_FIELD.get(str);
if (chars.length > str.length()) {
// substring detected!
// jdk6 substring shares the same value array
// with the original string (this is not the case for jdk7+)
// we need to get copy of substring array
chars = str.toCharArray();
}
return chars;
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
static class StringBasedUtfWriter implements UtfWriter {
//CHECKSTYLE:OFF
@Override
public void writeShortUTF(final DataOutput out,
final String str,
final int beginIndex,
final int endIndex,
final byte[] buffer) throws IOException {
final boolean isBufferObjectDataOutput = out instanceof BufferObjectDataOutput;
final BufferObjectDataOutput bufferObjectDataOutput =
isBufferObjectDataOutput ? (BufferObjectDataOutput) out : null;
int i;
int c;
int bufferPos = 0;
int utfLength = 0;
int utfLengthLimit;
int pos = 0;
if (isBufferObjectDataOutput) {
// At most, one character can hold 3 bytes
utfLengthLimit = str.length() * 3;
// We save current position of buffer data output.
// Then we write the length of UTF and ASCII state to here
pos = bufferObjectDataOutput.position();
// Moving position explicitly is not good way
// since it may cause overflow exceptions for example "ByteArrayObjectDataOutput".
// So, write dummy data and let DataOutput handle it by expanding or etc ...
bufferObjectDataOutput.writeShort(0);
if (ASCII_AWARE) {
bufferObjectDataOutput.writeBoolean(false);
}
} else {
utfLength = calculateUtf8Length(str, beginIndex, endIndex);
if (utfLength > 65535) {
throw new UTFDataFormatException(
"encoded string too long:" + utfLength + " bytes");
}
utfLengthLimit = utfLength;
out.writeShort(utfLength);
if (ASCII_AWARE) {
// We cannot determine that all characters are ASCII or not without iterating over it
// So, we mark it as not ASCII, so all characters will be checked.
out.writeBoolean(false);
}
}
if (buffer.length >= utfLengthLimit) {
for (i = beginIndex; i < endIndex; i++) {
c = str.charAt(i);
if (!(c <= 0x007F && c >= 0x0001)) {
break;
}
buffer[bufferPos++] = (byte) c;
}
for (; i < endIndex; i++) {
c = str.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
// 0x0001 <= X <= 0x007F
buffer[bufferPos++] = (byte) c;
} else if (c > 0x07FF) {
// 0x007F < X <= 0x7FFF
buffer[bufferPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
buffer[bufferPos++] = (byte) (0x80 | ((c >> 6) & 0x3F));
buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F));
} else {
// X == 0 or 0x007F < X < 0x7FFF
buffer[bufferPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F));
}
}
out.write(buffer, 0, bufferPos);
if (isBufferObjectDataOutput) {
utfLength = bufferPos;
}
} else {
for (i = beginIndex; i < endIndex; i++) {
c = str.charAt(i);
if (!(c <= 0x007F && c >= 0x0001)) {
break;
}
bufferPos = buffering(buffer, bufferPos, (byte) c, out);
}
if (isBufferObjectDataOutput) {
utfLength = i - beginIndex;
}
for (; i < endIndex; i++) {
c = str.charAt(i);
if (c <= 0x007F && c >= 0x0001) {
// 0x0001 <= X <= 0x007F
bufferPos = buffering(buffer, bufferPos, (byte) c, out);
if (isBufferObjectDataOutput) {
utfLength++;
}
} else if (c > 0x07FF) {
// 0x007F < X <= 0x7FFF
bufferPos = buffering(buffer, bufferPos,
(byte) (0xE0 | ((c >> 12) & 0x0F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c >> 6) & 0x3F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c) & 0x3F)), out);
if (isBufferObjectDataOutput) {
utfLength += 3;
}
} else {
// X == 0 or 0x007F < X < 0x7FFF
bufferPos = buffering(buffer, bufferPos,
(byte) (0xC0 | ((c >> 6) & 0x1F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c) & 0x3F)), out);
if (isBufferObjectDataOutput) {
utfLength += 2;
}
}
}
int length = bufferPos % buffer.length;
out.write(buffer, 0, length == 0 ? buffer.length : length);
}
if (isBufferObjectDataOutput) {
if (utfLength > 65535) {
throw new UTFDataFormatException(
"encoded string too long:" + utfLength + " bytes");
}
// Write the length of UTF to saved position before
bufferObjectDataOutput.writeShort(pos, utfLength);
// Write the ASCII status of UTF to saved position before
if (ASCII_AWARE) {
bufferObjectDataOutput.writeBoolean(pos + 2, utfLength == str.length());
}
}
}
//CHECKSTYLE:ON
}
// ********************************************************************* //
public String readUTF0(final DataInput in, final byte[] buffer) throws IOException {
if (!QuickMath.isPowerOfTwo(buffer.length)) {
throw new IllegalArgumentException(
"Size of the buffer has to be power of two, was " + buffer.length);
}
boolean isNull = in.readBoolean();
if (isNull) {
return null;
}
int length = in.readInt();
int lengthCheck = in.readInt();
if (length != lengthCheck) {
throw new UTFDataFormatException(
"Length check failed, maybe broken bytestream or wrong stream position");
}
final char[] data = new char[length];
if (length > 0) {
int chunkSize = length / STRING_CHUNK_SIZE + 1;
for (int i = 0; i < chunkSize; i++) {
int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1);
readShortUTF(in, data, beginIndex, buffer);
}
}
return stringCreator.buildString(data);
}
//CHECKSTYLE:OFF
private void readShortUTF(final DataInput in,
final char[] data,
final int beginIndex,
final byte[] buffer) throws IOException {
final int utfLength = in.readShort() & 0xFFFF;
final boolean allAscii = ASCII_AWARE ? in.readBoolean() : false;
// buffer[0] is used to hold read data
// so actual useful length of buffer is as "length - 1"
final int minUtfLenght = Math.min(utfLength, buffer.length - 1);
final int bufferLimit = minUtfLenght + 1;
int readCount = 0;
// We use buffer[0] to hold read data, so position starts from 1
int bufferPos = 1;
int c1 = 0;
int c2 = 0;
int c3 = 0;
int cTemp = 0;
int charArrCount = beginIndex;
// The first readable data is at 1. index since 0. index is used to hold read data.
in.readFully(buffer, 1, minUtfLenght);
if (allAscii) {
while (bufferPos != bufferLimit) {
data[charArrCount++] = (char)(buffer[bufferPos++] & 0xFF);
}
for (readCount = bufferPos - 1; readCount < utfLength; readCount++) {
bufferPos = buffered(buffer, bufferPos, utfLength, readCount, in);
data[charArrCount++] = (char) (buffer[0] & 0xFF);
}
} else {
c1 = buffer[bufferPos++] & 0xFF;
while (bufferPos != bufferLimit) {
if (c1 > 127) {
break;
}
data[charArrCount++] = (char) c1;
c1 = buffer[bufferPos++] & 0xFF;
}
bufferPos--;
readCount = bufferPos - 1;
while (readCount < utfLength) {
bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in);
c1 = buffer[0] & 0xFF;
cTemp = c1 >> 4;
if (cTemp >> 3 == 0) {
// ((cTemp & 0xF8) == 0) or (cTemp <= 7 && cTemp >= 0)
/* 0xxxxxxx */
data[charArrCount++] = (char) c1;
} else if (cTemp == 12 || cTemp == 13) {
/* 110x xxxx 10xx xxxx */
if (readCount + 1 > utfLength) {
throw new UTFDataFormatException(
"malformed input: partial character at end");
}
bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in);
c2 = buffer[0] & 0xFF;
if ((c2 & 0xC0) != 0x80) {
throw new UTFDataFormatException(
"malformed input around byte " + beginIndex + readCount + 1);
}
data[charArrCount++] = (char) (((c1 & 0x1F) << 6) | (c2 & 0x3F));
} else if (cTemp == 14) {
/* 1110 xxxx 10xx xxxx 10xx xxxx */
if (readCount + 2 > utfLength) {
throw new UTFDataFormatException(
"malformed input: partial character at end");
}
bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in);
c2 = buffer[0] & 0xFF;
bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in);
c3 = buffer[0] & 0xFF;
if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80)) {
throw new UTFDataFormatException(
"malformed input around byte " + (beginIndex + readCount + 1));
}
data[charArrCount++] = (char) (((c1 & 0x0F) << 12)
| ((c2 & 0x3F) << 6) | ((c3 & 0x3F)));
} else {
/* 10xx xxxx, 1111 xxxx */
throw new UTFDataFormatException(
"malformed input around byte " + (beginIndex + readCount));
}
}
}
}
//CHECKSTYLE:ON
// ********************************************************************* //
private static int calculateUtf8Length(final char[] value,
final int beginIndex,
final int endIndex) {
int utfLength = 0;
for (int i = beginIndex; i < endIndex; i++) {
int c = value[i];
if (c <= 0x007F && c >= 0x0001) {
utfLength += 1;
} else if (c > 0x07FF) {
utfLength += 3;
} else {
utfLength += 2;
}
}
return utfLength;
}
private static int calculateUtf8Length(final String str,
final int beginIndex,
final int endIndex) {
int utfLength = 0;
for (int i = beginIndex; i < endIndex; i++) {
int c = str.charAt(i);
if (c <= 0x007F && c >= 0x0001) {
utfLength += 1;
} else if (c > 0x07FF) {
utfLength += 3;
} else {
utfLength += 2;
}
}
return utfLength;
}
private static int buffering(final byte[] buffer,
final int pos,
final byte value,
final DataOutput out) throws IOException {
try {
buffer[pos] = value;
return pos + 1;
} catch (ArrayIndexOutOfBoundsException e) {
// Array bounds check by programmatically is not needed like
// "if (pos < buffer.length)".
// JVM checks instead of us, so it is unnecessary.
out.write(buffer, 0, buffer.length);
buffer[0] = value;
return 1;
}
}
private int buffered(final byte[] buffer,
final int pos,
final int utfLength,
final int readCount,
final DataInput in) throws IOException {
try {
// 0. index of buffer is used to hold read data
// so copy read data to there.
buffer[0] = buffer[pos];
return pos + 1;
} catch (ArrayIndexOutOfBoundsException e) {
// Array bounds check by programmatically is not needed like
// "if (pos < buffer.length)".
// JVM checks instead of us, so it is unnecessary.
in.readFully(buffer, 1,
Math.min(buffer.length - 1, utfLength - readCount));
// The first readable data is at 1. index since 0. index is used to
// hold read data.
// So the next one will be 2. index.
buffer[0] = buffer[1];
return 2;
}
}
private static boolean useOldStringConstructor() {
try {
Class<String> clazz = String.class;
clazz.getDeclaredConstructor(int.class, int.class, char[].class);
return true;
} catch (Throwable t) {
Logger.getLogger(UTFEncoderDecoder.class).
finest("Old String constructor doesn't seem available", t);
}
return false;
}
private static UTFEncoderDecoder buildUTFUtil() {
UtfWriter utfWriter = createUtfWriter();
StringCreator stringCreator = createStringCreator();
return new UTFEncoderDecoder(stringCreator, utfWriter, false);
}
static StringCreator createStringCreator() {
boolean fastStringEnabled = Boolean.parseBoolean(System.getProperty("hazelcast.nio.faststring", "true"));
return createStringCreator(fastStringEnabled);
}
static StringCreator createStringCreator(boolean fastStringEnabled) {
return fastStringEnabled ? buildFastStringCreator() : new DefaultStringCreator();
}
static UtfWriter createUtfWriter() {
// Try Unsafe based implementation
UnsafeBasedCharArrayUtfWriter unsafeBasedUtfWriter = new UnsafeBasedCharArrayUtfWriter();
if (unsafeBasedUtfWriter.isAvailable()) {
return unsafeBasedUtfWriter;
}
// If Unsafe based implementation is not available for usage
// Try Reflection based implementation
ReflectionBasedCharArrayUtfWriter reflectionBasedUtfWriter = new ReflectionBasedCharArrayUtfWriter();
if (reflectionBasedUtfWriter.isAvailable()) {
return reflectionBasedUtfWriter;
}
// If Reflection based implementation is not available for usage
return new StringBasedUtfWriter();
}
private static StringCreator buildFastStringCreator() {
try {
// Give access to the package private String constructor
Constructor<String> constructor;
if (UTFEncoderDecoder.useOldStringConstructor()) {
constructor =
String.class.getDeclaredConstructor(int.class, int.class, char[].class);
} else {
constructor =
String.class.getDeclaredConstructor(char[].class, boolean.class);
}
if (constructor != null) {
constructor.setAccessible(true);
return new FastStringCreator(constructor);
}
} catch (Throwable t) {
Logger.
getLogger(UTFEncoderDecoder.class).
finest("No fast string creator seems to available, falling back to reflection", t);
}
return null;
}
interface StringCreator {
String buildString(final char[] chars);
}
private static class DefaultStringCreator implements StringCreator {
@Override
public String buildString(final char[] chars) {
return new String(chars);
}
}
private static class FastStringCreator implements StringCreator {
private final Constructor<String> constructor;
private final boolean useOldStringConstructor;
public FastStringCreator(Constructor<String> constructor) {
this.constructor = constructor;
this.useOldStringConstructor = constructor.getParameterTypes().length == 3;
}
@Override
public String buildString(final char[] chars) {
try {
if (useOldStringConstructor) {
return constructor.newInstance(0, chars.length, chars);
} else {
return constructor.newInstance(chars, Boolean.TRUE);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| hazelcast/src/main/java/com/hazelcast/nio/UTFEncoderDecoder.java | /*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.nio;
import com.hazelcast.logging.Logger;
import com.hazelcast.util.EmptyStatement;
import com.hazelcast.util.QuickMath;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.UTFDataFormatException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Class to encode/decode UTF-Strings to and from byte-arrays.
*/
public final class UTFEncoderDecoder {
private static final int STRING_CHUNK_SIZE = 16 * 1024;
private static final UTFEncoderDecoder INSTANCE;
// Because this flag is not set for Non-Buffered Data Output classes
// but results may be compared in unit tests.
// Buffered Data Output may set this flag
// but Non-Buffered Data Output class always set this flag to "false".
// So their results may be different.
private static final boolean ASCII_AWARE =
Boolean.parseBoolean(System.getProperty("hazelcast.nio.asciiaware", "false"));
static {
INSTANCE = buildUTFUtil();
}
private final StringCreator stringCreator;
private final UtfWriter utfWriter;
private final boolean hazelcastEnterpriseActive;
UTFEncoderDecoder(StringCreator stringCreator, UtfWriter utfWriter) {
this(stringCreator, utfWriter, false);
}
UTFEncoderDecoder(StringCreator stringCreator, UtfWriter utfWriter, boolean hazelcastEnterpriseActive) {
this.stringCreator = stringCreator;
this.utfWriter = utfWriter;
this.hazelcastEnterpriseActive = hazelcastEnterpriseActive;
}
public boolean isHazelcastEnterpriseActive() {
return hazelcastEnterpriseActive;
}
public static void writeUTF(final DataOutput out,
final String str,
final byte[] buffer) throws IOException {
INSTANCE.writeUTF0(out, str, buffer);
}
public static String readUTF(final DataInput in,
final byte[] buffer) throws IOException {
return INSTANCE.readUTF0(in, buffer);
}
// ********************************************************************* //
public void writeUTF0(final DataOutput out,
final String str,
final byte[] buffer) throws IOException {
if (!QuickMath.isPowerOfTwo(buffer.length)) {
throw new IllegalArgumentException(
"Size of the buffer has to be power of two, was " + buffer.length);
}
boolean isNull = str == null;
out.writeBoolean(isNull);
if (isNull) {
return;
}
int length = str.length();
out.writeInt(length);
out.writeInt(length);
if (length > 0) {
int chunkSize = (length / STRING_CHUNK_SIZE) + 1;
for (int i = 0; i < chunkSize; i++) {
int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1);
int endIndex = Math.min((i + 1) * STRING_CHUNK_SIZE - 1, length);
utfWriter.writeShortUTF(out, str, beginIndex, endIndex, buffer);
}
}
}
// ********************************************************************* //
interface UtfWriter {
void writeShortUTF(final DataOutput out,
final String str,
final int beginIndex,
final int endIndex,
final byte[] buffer) throws IOException;
}
private abstract static class AbstractCharArrayUtfWriter implements UtfWriter {
//CHECKSTYLE:OFF
@Override
public final void writeShortUTF(final DataOutput out,
final String str,
final int beginIndex,
final int endIndex,
final byte[] buffer) throws IOException {
final boolean isBufferObjectDataOutput = out instanceof BufferObjectDataOutput;
final BufferObjectDataOutput bufferObjectDataOutput =
isBufferObjectDataOutput ? (BufferObjectDataOutput) out : null;
final char[] value = getCharArray(str);
int i;
int c;
int bufferPos = 0;
int utfLength = 0;
int utfLengthLimit;
int pos = 0;
if (isBufferObjectDataOutput) {
// At most, one character can hold 3 bytes
utfLengthLimit = str.length() * 3;
// We save current position of buffer data output.
// Then we write the length of UTF and ASCII state to here
pos = bufferObjectDataOutput.position();
// Moving position explicitly is not good way
// since it may cause overflow exceptions for example "ByteArrayObjectDataOutput".
// So, write dummy data and let DataOutput handle it by expanding or etc ...
bufferObjectDataOutput.writeShort(0);
if (ASCII_AWARE) {
bufferObjectDataOutput.writeBoolean(false);
}
} else {
utfLength = calculateUtf8Length(value, beginIndex, endIndex);
if (utfLength > 65535) {
throw new UTFDataFormatException(
"encoded string too long:" + utfLength + " bytes");
}
utfLengthLimit = utfLength;
out.writeShort(utfLength);
if (ASCII_AWARE) {
// We cannot determine that all characters are ASCII or not without iterating over it
// So, we mark it as not ASCII, so all characters will be checked.
out.writeBoolean(false);
}
}
if (buffer.length >= utfLengthLimit) {
for (i = beginIndex; i < endIndex; i++) {
c = value[i];
if (!(c <= 0x007F && c >= 0x0001)) {
break;
}
buffer[bufferPos++] = (byte) c;
}
for (; i < endIndex; i++) {
c = value[i];
if (c <= 0x007F && c >= 0x0001) {
buffer[bufferPos++] = (byte) c;
} else if (c > 0x07FF) {
buffer[bufferPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
buffer[bufferPos++] = (byte) (0x80 | ((c >> 6) & 0x3F));
buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F));
} else {
buffer[bufferPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F));
}
}
out.write(buffer, 0, bufferPos);
if (isBufferObjectDataOutput) {
utfLength = bufferPos;
}
} else {
for (i = beginIndex; i < endIndex; i++) {
c = value[i];
if (!(c <= 0x007F && c >= 0x0001)) {
break;
}
bufferPos = buffering(buffer, bufferPos, (byte) c, out);
}
if (isBufferObjectDataOutput) {
utfLength = i - beginIndex;
}
for (; i < endIndex; i++) {
c = value[i];
if (c <= 0x007F && c >= 0x0001) {
bufferPos = buffering(buffer, bufferPos, (byte) c, out);
if (isBufferObjectDataOutput) {
utfLength++;
}
} else if (c > 0x07FF) {
bufferPos = buffering(buffer, bufferPos,
(byte) (0xE0 | ((c >> 12) & 0x0F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c >> 6) & 0x3F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c) & 0x3F)), out);
if (isBufferObjectDataOutput) {
utfLength += 3;
}
} else {
bufferPos = buffering(buffer, bufferPos,
(byte) (0xC0 | ((c >> 6) & 0x1F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c) & 0x3F)), out);
if (isBufferObjectDataOutput) {
utfLength += 2;
}
}
}
int length = bufferPos % buffer.length;
out.write(buffer, 0, length == 0 ? buffer.length : length);
}
if (isBufferObjectDataOutput) {
if (utfLength > 65535) {
throw new UTFDataFormatException(
"encoded string too long:" + utfLength + " bytes");
}
// Write the length of UTF to saved position before
bufferObjectDataOutput.writeShort(pos, utfLength);
// Write the ASCII status of UTF to saved position before
if (ASCII_AWARE) {
bufferObjectDataOutput.writeBoolean(pos + 2, utfLength == str.length());
}
}
}
protected abstract boolean isAvailable();
protected abstract char[] getCharArray(String str);
//CHECKSTYLE:ON
}
static class UnsafeBasedCharArrayUtfWriter extends AbstractCharArrayUtfWriter {
private static final sun.misc.Unsafe UNSAFE = UnsafeHelper.UNSAFE;
private static final long VALUE_FIELD_OFFSET;
static {
long offset = -1;
if (UnsafeHelper.UNSAFE_AVAILABLE) {
try {
offset = UNSAFE.objectFieldOffset(String.class.getDeclaredField("value"));
} catch (Throwable t) {
EmptyStatement.ignore(t);
}
}
VALUE_FIELD_OFFSET = offset;
}
@Override
public boolean isAvailable() {
return UnsafeHelper.UNSAFE_AVAILABLE && VALUE_FIELD_OFFSET != -1;
}
@Override
protected char[] getCharArray(String str) {
char[] chars = (char[]) UNSAFE.getObject(str, VALUE_FIELD_OFFSET);
if (chars.length > str.length()) {
// substring detected!
// jdk6 substring shares the same value array
// with the original string (this is not the case for jdk7+)
// we need to get copy of substring array
chars = str.toCharArray();
}
return chars;
}
}
static class ReflectionBasedCharArrayUtfWriter extends AbstractCharArrayUtfWriter {
private static final Field VALUE_FIELD;
static {
Field field;
try {
field = String.class.getDeclaredField("value");
field.setAccessible(true);
} catch (Throwable t) {
EmptyStatement.ignore(t);
field = null;
}
VALUE_FIELD = field;
}
@Override
public boolean isAvailable() {
return VALUE_FIELD != null;
}
@Override
protected char[] getCharArray(String str) {
try {
char[] chars = (char[]) VALUE_FIELD.get(str);
if (chars.length > str.length()) {
// substring detected!
// jdk6 substring shares the same value array
// with the original string (this is not the case for jdk7+)
// we need to get copy of substring array
chars = str.toCharArray();
}
return chars;
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
}
static class StringBasedUtfWriter implements UtfWriter {
//CHECKSTYLE:OFF
@Override
public void writeShortUTF(final DataOutput out,
final String str,
final int beginIndex,
final int endIndex,
final byte[] buffer) throws IOException {
final boolean isBufferObjectDataOutput = out instanceof BufferObjectDataOutput;
final BufferObjectDataOutput bufferObjectDataOutput =
isBufferObjectDataOutput ? (BufferObjectDataOutput) out : null;
int i;
int c;
int bufferPos = 0;
int utfLength = 0;
int utfLengthLimit;
int pos = 0;
if (isBufferObjectDataOutput) {
// At most, one character can hold 3 bytes
utfLengthLimit = str.length() * 3;
// We save current position of buffer data output.
// Then we write the length of UTF and ASCII state to here
pos = bufferObjectDataOutput.position();
// Moving position explicitly is not good way
// since it may cause overflow exceptions for example "ByteArrayObjectDataOutput".
// So, write dummy data and let DataOutput handle it by expanding or etc ...
bufferObjectDataOutput.writeShort(0);
if (ASCII_AWARE) {
bufferObjectDataOutput.writeBoolean(false);
}
} else {
utfLength = calculateUtf8Length(str, beginIndex, endIndex);
if (utfLength > 65535) {
throw new UTFDataFormatException(
"encoded string too long:" + utfLength + " bytes");
}
utfLengthLimit = utfLength;
out.writeShort(utfLength);
if (ASCII_AWARE) {
// We cannot determine that all characters are ASCII or not without iterating over it
// So, we mark it as not ASCII, so all characters will be checked.
out.writeBoolean(false);
}
}
if (buffer.length >= utfLengthLimit) {
for (i = beginIndex; i < endIndex; i++) {
c = str.charAt(i);
if (!(c <= 0x007F && c >= 0x0001)) {
break;
}
buffer[bufferPos++] = (byte) c;
}
for (; i < endIndex; i++) {
c = str.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
// 0x0001 <= X <= 0x007F
buffer[bufferPos++] = (byte) c;
} else if (c > 0x07FF) {
// 0x007F < X <= 0x7FFF
buffer[bufferPos++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
buffer[bufferPos++] = (byte) (0x80 | ((c >> 6) & 0x3F));
buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F));
} else {
// X == 0 or 0x007F < X < 0x7FFF
buffer[bufferPos++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
buffer[bufferPos++] = (byte) (0x80 | ((c) & 0x3F));
}
}
out.write(buffer, 0, bufferPos);
if (isBufferObjectDataOutput) {
utfLength = bufferPos;
}
} else {
for (i = beginIndex; i < endIndex; i++) {
c = str.charAt(i);
if (!(c <= 0x007F && c >= 0x0001)) {
break;
}
bufferPos = buffering(buffer, bufferPos, (byte) c, out);
}
if (isBufferObjectDataOutput) {
utfLength = i - beginIndex;
}
for (; i < endIndex; i++) {
c = str.charAt(i);
if (c <= 0x007F && c >= 0x0001) {
// 0x0001 <= X <= 0x007F
bufferPos = buffering(buffer, bufferPos, (byte) c, out);
if (isBufferObjectDataOutput) {
utfLength++;
}
} else if (c > 0x07FF) {
// 0x007F < X <= 0x7FFF
bufferPos = buffering(buffer, bufferPos,
(byte) (0xE0 | ((c >> 12) & 0x0F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c >> 6) & 0x3F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c) & 0x3F)), out);
if (isBufferObjectDataOutput) {
utfLength += 3;
}
} else {
// X == 0 or 0x007F < X < 0x7FFF
bufferPos = buffering(buffer, bufferPos,
(byte) (0xC0 | ((c >> 6) & 0x1F)), out);
bufferPos = buffering(buffer, bufferPos,
(byte) (0x80 | ((c) & 0x3F)), out);
if (isBufferObjectDataOutput) {
utfLength += 2;
}
}
}
int length = bufferPos % buffer.length;
out.write(buffer, 0, length == 0 ? buffer.length : length);
}
if (isBufferObjectDataOutput) {
if (utfLength > 65535) {
throw new UTFDataFormatException(
"encoded string too long:" + utfLength + " bytes");
}
// Write the length of UTF to saved position before
bufferObjectDataOutput.writeShort(pos, utfLength);
// Write the ASCII status of UTF to saved position before
if (ASCII_AWARE) {
bufferObjectDataOutput.writeBoolean(pos + 2, utfLength == str.length());
}
}
}
//CHECKSTYLE:ON
}
// ********************************************************************* //
public String readUTF0(final DataInput in, final byte[] buffer) throws IOException {
if (!QuickMath.isPowerOfTwo(buffer.length)) {
throw new IllegalArgumentException(
"Size of the buffer has to be power of two, was " + buffer.length);
}
boolean isNull = in.readBoolean();
if (isNull) {
return null;
}
int length = in.readInt();
int lengthCheck = in.readInt();
if (length != lengthCheck) {
throw new UTFDataFormatException(
"Length check failed, maybe broken bytestream or wrong stream position");
}
final char[] data = new char[length];
if (length > 0) {
int chunkSize = length / STRING_CHUNK_SIZE + 1;
for (int i = 0; i < chunkSize; i++) {
int beginIndex = Math.max(0, i * STRING_CHUNK_SIZE - 1);
readShortUTF(in, data, beginIndex, buffer);
}
}
return stringCreator.buildString(data);
}
//CHECKSTYLE:OFF
private void readShortUTF(final DataInput in,
final char[] data,
final int beginIndex,
final byte[] buffer) throws IOException {
final int utfLength = in.readShort() & 0xFFFF;
final boolean allAscii = ASCII_AWARE ? in.readBoolean() : false;
// buffer[0] is used to hold read data
// so actual useful length of buffer is as "length - 1"
final int minUtfLenght = Math.min(utfLength, buffer.length - 1);
final int bufferLimit = minUtfLenght + 1;
int readCount = 0;
// We use buffer[0] to hold read data, so position starts from 1
int bufferPos = 1;
int c1 = 0;
int c2 = 0;
int c3 = 0;
int cTemp = 0;
int charArrCount = beginIndex;
// The first readable data is at 1. index since 0. index is used to hold read data.
in.readFully(buffer, 1, minUtfLenght);
if (allAscii) {
while (bufferPos != bufferLimit) {
data[charArrCount++] = (char)(buffer[bufferPos++] & 0xFF);
}
for (readCount = bufferPos - 1; readCount < utfLength; readCount++) {
bufferPos = buffered(buffer, bufferPos, utfLength, readCount, in);
data[charArrCount++] = (char) (buffer[0] & 0xFF);
}
} else {
c1 = buffer[bufferPos++] & 0xFF;
while (bufferPos != bufferLimit) {
if (c1 > 127) {
break;
}
data[charArrCount++] = (char) c1;
c1 = buffer[bufferPos++] & 0xFF;
}
bufferPos--;
readCount = bufferPos - 1;
while (readCount < utfLength) {
bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in);
c1 = buffer[0] & 0xFF;
cTemp = c1 >> 4;
if (cTemp >> 3 == 0) {
// ((cTemp & 0xF8) == 0) or (cTemp <= 7 && cTemp >= 0)
/* 0xxxxxxx */
data[charArrCount++] = (char) c1;
} else if (cTemp == 12 || cTemp == 13) {
/* 110x xxxx 10xx xxxx */
if (readCount + 1 > utfLength) {
throw new UTFDataFormatException(
"malformed input: partial character at end");
}
bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in);
c2 = buffer[0] & 0xFF;
if ((c2 & 0xC0) != 0x80) {
throw new UTFDataFormatException(
"malformed input around byte " + beginIndex + readCount + 1);
}
data[charArrCount++] = (char) (((c1 & 0x1F) << 6) | (c2 & 0x3F));
} else if (cTemp == 14) {
/* 1110 xxxx 10xx xxxx 10xx xxxx */
if (readCount + 2 > utfLength) {
throw new UTFDataFormatException(
"malformed input: partial character at end");
}
bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in);
c2 = buffer[0] & 0xFF;
bufferPos = buffered(buffer, bufferPos, utfLength, readCount++, in);
c3 = buffer[0] & 0xFF;
if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80)) {
throw new UTFDataFormatException(
"malformed input around byte " + (beginIndex + readCount + 1));
}
data[charArrCount++] = (char) (((c1 & 0x0F) << 12)
| ((c2 & 0x3F) << 6) | ((c3 & 0x3F)));
} else {
/* 10xx xxxx, 1111 xxxx */
throw new UTFDataFormatException(
"malformed input around byte " + (beginIndex + readCount));
}
}
}
}
//CHECKSTYLE:ON
// ********************************************************************* //
private static int calculateUtf8Length(final char[] value,
final int beginIndex,
final int endIndex) {
int utfLength = 0;
for (int i = beginIndex; i < endIndex; i++) {
int c = value[i];
if (c <= 0x007F && c >= 0x0001) {
utfLength += 1;
} else if (c > 0x07FF) {
utfLength += 3;
} else {
utfLength += 2;
}
}
return utfLength;
}
private static int calculateUtf8Length(final String str,
final int beginIndex,
final int endIndex) {
int utfLength = 0;
for (int i = beginIndex; i < endIndex; i++) {
int c = str.charAt(i);
if (c <= 0x007F && c >= 0x0001) {
utfLength += 1;
} else if (c > 0x07FF) {
utfLength += 3;
} else {
utfLength += 2;
}
}
return utfLength;
}
private static int buffering(final byte[] buffer,
final int pos,
final byte value,
final DataOutput out) throws IOException {
try {
buffer[pos] = value;
return pos + 1;
} catch (ArrayIndexOutOfBoundsException e) {
// Array bounds check by programmatically is not needed like
// "if (pos < buffer.length)".
// JVM checks instead of us, so it is unnecessary.
out.write(buffer, 0, buffer.length);
buffer[0] = value;
return 1;
}
}
private int buffered(final byte[] buffer,
final int pos,
final int utfLength,
final int readCount,
final DataInput in) throws IOException {
try {
// 0. index of buffer is used to hold read data
// so copy read data to there.
buffer[0] = buffer[pos];
return pos + 1;
} catch (ArrayIndexOutOfBoundsException e) {
// Array bounds check by programmatically is not needed like
// "if (pos < buffer.length)".
// JVM checks instead of us, so it is unnecessary.
in.readFully(buffer, 1,
Math.min(buffer.length - 1, utfLength - readCount));
// The first readable data is at 1. index since 0. index is used to
// hold read data.
// So the next one will be 2. index.
buffer[0] = buffer[1];
return 2;
}
}
private static boolean useOldStringConstructor() {
try {
Class<String> clazz = String.class;
clazz.getDeclaredConstructor(int.class, int.class, char[].class);
return true;
} catch (Throwable t) {
Logger.getLogger(UTFEncoderDecoder.class).
finest("Old String constructor doesn't seem available", t);
}
return false;
}
private static UTFEncoderDecoder buildUTFUtil() {
UtfWriter utfWriter = createUtfWriter();
try {
Class<?> clazz = Class.forName("com.hazelcast.nio.utf8.EnterpriseStringCreator");
Method method = clazz.getDeclaredMethod("findBestStringCreator");
return new UTFEncoderDecoder((StringCreator) method.invoke(clazz), utfWriter, true);
} catch (Throwable t) {
Logger.getLogger(UTFEncoderDecoder.class).
finest("EnterpriseStringCreator not available on classpath", t);
}
StringCreator stringCreator = createStringCreator();
return new UTFEncoderDecoder(stringCreator, utfWriter, false);
}
static StringCreator createStringCreator() {
boolean fastStringEnabled = Boolean.parseBoolean(System.getProperty("hazelcast.nio.faststring", "true"));
return createStringCreator(fastStringEnabled);
}
static StringCreator createStringCreator(boolean fastStringEnabled) {
return fastStringEnabled ? buildFastStringCreator() : new DefaultStringCreator();
}
static UtfWriter createUtfWriter() {
// Try Unsafe based implementation
UnsafeBasedCharArrayUtfWriter unsafeBasedUtfWriter = new UnsafeBasedCharArrayUtfWriter();
if (unsafeBasedUtfWriter.isAvailable()) {
return unsafeBasedUtfWriter;
}
// If Unsafe based implementation is not available for usage
// Try Reflection based implementation
ReflectionBasedCharArrayUtfWriter reflectionBasedUtfWriter = new ReflectionBasedCharArrayUtfWriter();
if (reflectionBasedUtfWriter.isAvailable()) {
return reflectionBasedUtfWriter;
}
// If Reflection based implementation is not available for usage
return new StringBasedUtfWriter();
}
private static StringCreator buildFastStringCreator() {
try {
// Give access to the package private String constructor
Constructor<String> constructor;
if (UTFEncoderDecoder.useOldStringConstructor()) {
constructor =
String.class.getDeclaredConstructor(int.class, int.class, char[].class);
} else {
constructor =
String.class.getDeclaredConstructor(char[].class, boolean.class);
}
if (constructor != null) {
constructor.setAccessible(true);
return new FastStringCreator(constructor);
}
} catch (Throwable t) {
Logger.
getLogger(UTFEncoderDecoder.class).
finest("No fast string creator seems to available, falling back to reflection", t);
}
return null;
}
interface StringCreator {
String buildString(final char[] chars);
}
private static class DefaultStringCreator implements StringCreator {
@Override
public String buildString(final char[] chars) {
return new String(chars);
}
}
private static class FastStringCreator implements StringCreator {
private final Constructor<String> constructor;
private final boolean useOldStringConstructor;
public FastStringCreator(Constructor<String> constructor) {
this.constructor = constructor;
this.useOldStringConstructor = constructor.getParameterTypes().length == 3;
}
@Override
public String buildString(final char[] chars) {
try {
if (useOldStringConstructor) {
return constructor.newInstance(0, chars.length, chars);
} else {
return constructor.newInstance(chars, Boolean.TRUE);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| Fixes #3819
| hazelcast/src/main/java/com/hazelcast/nio/UTFEncoderDecoder.java | Fixes #3819 |
|
Java | apache-2.0 | 08fb95375c30d31a449b7e59d3780c019ea6bf50 | 0 | ouyangfeng/picasso,longshun/picasso,Yestioured/picasso,zmywly8866/picasso,david-wei/picasso,lgx0955/picasso,litl/picasso,jrlinforce/picasso,iamyuiwong/picasso,B-A-Ismail/picasso,Jalsoncc/picasso,square/picasso,joansmith/picasso,lncosie/picasso,y97524027/picasso,lypdemo/picasso,litl/picasso,ackimwilliams/picasso,bossvn/picasso,309746069/picasso,falcon2010/picasso,fromsatellite/picasso,janzoner/picasso,lixiaoyu/picasso,jiasonwang/picasso,Papuh/picasso,sahilk2579/picasso,AKiniyalocts/picasso,wangjun/picasso,laysionqet/picasso,JohnTsaiAndroid/picasso,wanjingyan001/picasso,Groxx/picasso,siwangqishiq/picasso,stateofzhao/picasso,tanyixiu/picasso,n0x3u5/picasso,Algarode/picasso,zcwk/picasso,Gary111/picasso,joansmith/picasso,fromsatellite/picasso,wangziqiang/picasso,xubuhang/picasso,joansmith/picasso,lxhxhlw/picasso,B-A-Ismail/picasso,square/picasso,tikiet/picasso,xubuhang/picasso,fhchina/picasso,yauma/picasso,recoilme/picasso,myroid/picasso,perrystreetsoftware/picasso,lichblitz/picasso,JGeovani/picasso,laysionqet/picasso,paras23brahimi/picasso,BinGoBinBin/picasso,sbp5151/picasso,ribbon-xx/picasso,libinbensin/picasso,b-cuts/picasso,hw-beijing/picasso,renatohsc/picasso,zhenguo/picasso,CJstar/picasso,MaTriXy/picasso,ackimwilliams/picasso,sahilk2579/picasso,CJstar/picasso,huanting/picasso,AKiniyalocts/picasso,Faner007/picasso,amikey/picasso,MaTriXy/picasso,thangtc/picasso,yauma/picasso,square/picasso,junenn/picasso,xubuhang/picasso,szucielgp/picasso,hw-beijing/picasso,lichblitz/picasso,siwangqishiq/picasso,shenyiyangvip/picasso,v7lin/picasso,3meters/picasso,v7lin/picasso,siwangqishiq/picasso,juner122king/picasso,hw-beijing/picasso,david-wei/picasso,lnylny/picasso,chwnFlyPig/picasso,libinbensin/picasso,Algarode/picasso,y97524027/picasso,myroid/picasso,2017398956/picasso,huihui4045/picasso,chwnFlyPig/picasso,squadrun/picasso,JGeovani/picasso,Pannarrow/picasso,colonsong/picasso,yulongxiao/picasso,qingsong-xu/picasso,HasanAliKaraca/picasso,HossainKhademian/Picasso,zhenguo/picasso,NightlyNexus/picasso,falcon2010/picasso,jrlinforce/picasso,zmywly8866/picasso,tha022/picasso,litl/picasso,3meters/picasso,liuguangli/picasso,3meters/picasso,309746069/picasso,yauma/picasso,Shinelw/picasso,zhenguo/picasso,Papuh/picasso,phileo/picasso,lypdemo/picasso,MaiMohamedMahmoud/picasso,ribbon-xx/picasso,tha022/picasso,stateofzhao/picasso,BinGoBinBin/picasso,square/picasso,xgame92/picasso,ouyangfeng/picasso,mullender/picasso,recoilme/picasso,b-cuts/picasso,tha022/picasso,andyao/picasso,B-A-Ismail/picasso,CJstar/picasso,sahilk2579/picasso,junenn/picasso,Fablic/picasso,sowrabh/picasso,amikey/picasso,shenyiyangvip/picasso,BinGoBinBin/picasso,squadrun/picasso,mullender/picasso,lnylny/picasso,lgx0955/picasso,v7lin/picasso,wangziqiang/picasso,Faner007/picasso,ouyangfeng/picasso,NightlyNexus/picasso,perrystreetsoftware/picasso,ruhaly/picasso,Faner007/picasso,yoube/picasso,Gary111/picasso,yoube/picasso,pacificIT/picasso,jiasonwang/picasso,liuguangli/picasso,ajju4455/picasso,david-wei/picasso,lxhxhlw/picasso,iamyuiwong/picasso,huihui4045/picasso,sowrabh/picasso,libinbensin/picasso,colonsong/picasso,tanyixiu/picasso,HossainKhademian/Picasso,Shinelw/picasso,yoyoyohamapi/picasso,longshun/picasso,riezkykenzie/picasso,wangjun/picasso,Jalsoncc/picasso,mullender/picasso,ackimwilliams/picasso,Pannarrow/picasso,szucielgp/picasso,paras23brahimi/picasso,lncosie/picasso,qingsong-xu/picasso,02110917/picasso,futurobot/picasso,fhchina/picasso,msandroid/picasso,Gary111/picasso,Shinelw/picasso,renatohsc/picasso,stateofzhao/picasso,janzoner/picasso,laysionqet/picasso,RobertHale/picasso,thangtc/picasso,iamyuiwong/picasso,huanting/picasso,Fablic/picasso,b-cuts/picasso,xgame92/picasso,futurobot/picasso,amikey/picasso,msandroid/picasso,JohnTsaiAndroid/picasso,yoube/picasso,wangziqiang/picasso,yulongxiao/picasso,bossvn/picasso,tikiet/picasso,bossvn/picasso,hgl888/picasso,yoyoyohamapi/picasso,ajju4455/picasso,sowrabh/picasso,perrystreetsoftware/picasso,309746069/picasso,wangjun/picasso,Jalsoncc/picasso,hgl888/picasso,pacificIT/picasso,Pannarrow/picasso,HasanAliKaraca/picasso,lnylny/picasso,Yestioured/picasso,shenyiyangvip/picasso,jrlinforce/picasso,colonsong/picasso,gkmbinh/picasso,RobertHale/picasso,liuguangli/picasso,paras23brahimi/picasso,pacificIT/picasso,chRyNaN/PicassoBase64,lichblitz/picasso,yoyoyohamapi/picasso,zcwk/picasso,yulongxiao/picasso,MaiMohamedMahmoud/picasso,squadrun/picasso,2017398956/picasso,Fablic/picasso,JGeovani/picasso,juner122king/picasso,02110917/picasso,MaiMohamedMahmoud/picasso,myroid/picasso,msandroid/picasso,tikiet/picasso,lixiaoyu/picasso,thangtc/picasso,RobertHale/picasso,fromsatellite/picasso,lypdemo/picasso,lixiaoyu/picasso,fhchina/picasso,Papuh/picasso,gkmbinh/picasso,lgx0955/picasso,kaoree/picasso,MaTriXy/picasso,zcwk/picasso,riezkykenzie/picasso,ruhaly/picasso,jiasonwang/picasso,hgl888/picasso,xgame92/picasso,wanyueLei/picasso,viacheslavokolitiy/picasso,wanyueLei/picasso,n0x3u5/picasso,longshun/picasso,sbp5151/picasso,junenn/picasso,juner122king/picasso,chRyNaN/PicassoBase64,zmywly8866/picasso,wanjingyan001/picasso,wanyueLei/picasso,totomac/picasso,chwnFlyPig/picasso,Yestioured/picasso,sbp5151/picasso,wanjingyan001/picasso,totomac/picasso,riezkykenzie/picasso,viacheslavokolitiy/picasso,recoilme/picasso,gkmbinh/picasso,viacheslavokolitiy/picasso,kaoree/picasso,y97524027/picasso,renatohsc/picasso,AKiniyalocts/picasso,huanting/picasso,kaoree/picasso,ajju4455/picasso,lncosie/picasso,totomac/picasso,2017398956/picasso,NightlyNexus/picasso,chRyNaN/PicassoBase64,ruhaly/picasso,huihui4045/picasso,lxhxhlw/picasso,andyao/picasso,phileo/picasso,andyao/picasso,ribbon-xx/picasso,JohnTsaiAndroid/picasso,qingsong-xu/picasso,n0x3u5/picasso,falcon2010/picasso,szucielgp/picasso,tanyixiu/picasso,HasanAliKaraca/picasso,phileo/picasso,janzoner/picasso,Groxx/picasso,Algarode/picasso | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.widget.ImageView;
import android.widget.RemoteViews;
import java.io.File;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
import static com.squareup.picasso.Action.RequestWeakReference;
import static com.squareup.picasso.Dispatcher.HUNTER_BATCH_COMPLETE;
import static com.squareup.picasso.Dispatcher.REQUEST_BATCH_RESUME;
import static com.squareup.picasso.Dispatcher.REQUEST_GCED;
import static com.squareup.picasso.Picasso.LoadedFrom.MEMORY;
import static com.squareup.picasso.Utils.OWNER_MAIN;
import static com.squareup.picasso.Utils.THREAD_PREFIX;
import static com.squareup.picasso.Utils.VERB_CANCELED;
import static com.squareup.picasso.Utils.VERB_COMPLETED;
import static com.squareup.picasso.Utils.VERB_ERRORED;
import static com.squareup.picasso.Utils.VERB_RESUMED;
import static com.squareup.picasso.Utils.checkMain;
import static com.squareup.picasso.Utils.log;
/**
* Image downloading, transformation, and caching manager.
* <p>
* Use {@link #with(android.content.Context)} for the global singleton instance or construct your
* own instance with {@link Builder}.
*/
public class Picasso {
/** Callbacks for Picasso events. */
public interface Listener {
/**
* Invoked when an image has failed to load. This is useful for reporting image failures to a
* remote analytics service, for example.
*/
void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception);
}
/**
* A transformer that is called immediately before every request is submitted. This can be used to
* modify any information about a request.
* <p>
* For example, if you use a CDN you can change the hostname for the image based on the current
* location of the user in order to get faster download speeds.
* <p>
* <b>NOTE:</b> This is a beta feature. The API is subject to change in a backwards incompatible
* way at any time.
*/
public interface RequestTransformer {
/**
* Transform a request before it is submitted to be processed.
*
* @return The original request or a new request to replace it. Must not be null.
*/
Request transformRequest(Request request);
/** A {@link RequestTransformer} which returns the original request. */
RequestTransformer IDENTITY = new RequestTransformer() {
@Override public Request transformRequest(Request request) {
return request;
}
};
}
/**
* The priority of a request.
*
* @see RequestCreator#priority(Priority)
*/
public enum Priority {
LOW,
NORMAL,
HIGH
}
static final String TAG = "Picasso";
static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case HUNTER_BATCH_COMPLETE: {
@SuppressWarnings("unchecked") List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;
//noinspection ForLoopReplaceableByForEach
for (int i = 0, n = batch.size(); i < n; i++) {
BitmapHunter hunter = batch.get(i);
hunter.picasso.complete(hunter);
}
break;
}
case REQUEST_GCED: {
Action action = (Action) msg.obj;
if (action.getPicasso().loggingEnabled) {
log(OWNER_MAIN, VERB_CANCELED, action.request.logId(), "target got garbage collected");
}
action.picasso.cancelExistingRequest(action.getTarget());
break;
}
case REQUEST_BATCH_RESUME:
@SuppressWarnings("unchecked") List<Action> batch = (List<Action>) msg.obj;
for (int i = 0, n = batch.size(); i < n; i++) {
Action action = batch.get(i);
action.picasso.resumeAction(action);
}
break;
default:
throw new AssertionError("Unknown handler message received: " + msg.what);
}
}
};
static Picasso singleton = null;
private final Listener listener;
private final RequestTransformer requestTransformer;
private final CleanupThread cleanupThread;
private final List<RequestHandler> requestHandlers;
final Context context;
final Dispatcher dispatcher;
final Cache cache;
final Stats stats;
final Map<Object, Action> targetToAction;
final Map<ImageView, DeferredRequestCreator> targetToDeferredRequestCreator;
final ReferenceQueue<Object> referenceQueue;
boolean indicatorsEnabled;
volatile boolean loggingEnabled;
boolean shutdown;
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers,
Stats stats, boolean indicatorsEnabled, boolean loggingEnabled) {
this.context = context;
this.dispatcher = dispatcher;
this.cache = cache;
this.listener = listener;
this.requestTransformer = requestTransformer;
int builtInHandlers = 7; // Adjust this as internal handlers are added or removed.
int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
List<RequestHandler> allRequestHandlers =
new ArrayList<RequestHandler>(builtInHandlers + extraCount);
// ResourceRequestHandler needs to be the first in the list to avoid
// forcing other RequestHandlers to perform null checks on request.uri
// to cover the (request.resourceId != 0) case.
allRequestHandlers.add(new ResourceRequestHandler(context));
if (extraRequestHandlers != null) {
allRequestHandlers.addAll(extraRequestHandlers);
}
allRequestHandlers.add(new ContactsPhotoRequestHandler(context));
allRequestHandlers.add(new MediaStoreRequestHandler(context));
allRequestHandlers.add(new ContentStreamRequestHandler(context));
allRequestHandlers.add(new AssetRequestHandler(context));
allRequestHandlers.add(new FileRequestHandler(context));
allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
requestHandlers = Collections.unmodifiableList(allRequestHandlers);
this.stats = stats;
this.targetToAction = new WeakHashMap<Object, Action>();
this.targetToDeferredRequestCreator = new WeakHashMap<ImageView, DeferredRequestCreator>();
this.indicatorsEnabled = indicatorsEnabled;
this.loggingEnabled = loggingEnabled;
this.referenceQueue = new ReferenceQueue<Object>();
this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
this.cleanupThread.start();
}
/** Cancel any existing requests for the specified target {@link ImageView}. */
public void cancelRequest(ImageView view) {
cancelExistingRequest(view);
}
/** Cancel any existing requests for the specified {@link Target} instance. */
public void cancelRequest(Target target) {
cancelExistingRequest(target);
}
/**
* Cancel any existing requests for the specified {@link RemoteViews} target with the given {@code
* viewId}.
*/
public void cancelRequest(RemoteViews remoteViews, int viewId) {
cancelExistingRequest(new RemoteViewsAction.RemoteViewsTarget(remoteViews, viewId));
}
/**
* Cancel any existing requests with given tag. You can set a tag
* on new requests with {@link RequestCreator#tag(Object)}.
*
* @see RequestCreator#tag(Object)
*/
public void cancelTag(Object tag) {
checkMain();
List<Action> actions = new ArrayList<Action>(targetToAction.values());
for (int i = 0, n = actions.size(); i < n; i++) {
Action action = actions.get(i);
if (action.getTag().equals(tag)) {
cancelExistingRequest(action.getTarget());
}
}
}
/**
* Pause existing requests with the given tag. Use {@link #resumeTag(Object)}
* to resume requests with the given tag.
*
* @see #resumeTag(Object)
* @see RequestCreator#tag(Object)
*/
public void pauseTag(Object tag) {
dispatcher.dispatchPauseTag(tag);
}
/**
* Resume paused requests with the given tag. Use {@link #pauseTag(Object)}
* to pause requests with the given tag.
*
* @see #pauseTag(Object)
* @see RequestCreator#tag(Object)
*/
public void resumeTag(Object tag) {
dispatcher.dispatchResumeTag(tag);
}
/**
* Start an image request using the specified URI.
* <p>
* Passing {@code null} as a {@code uri} will not trigger any request but will set a placeholder,
* if one is specified.
*
* @see #load(File)
* @see #load(String)
* @see #load(int)
*/
public RequestCreator load(Uri uri) {
return new RequestCreator(this, uri, 0);
}
/**
* Start an image request using the specified path. This is a convenience method for calling
* {@link #load(Uri)}.
* <p>
* This path may be a remote URL, file resource (prefixed with {@code file:}), content resource
* (prefixed with {@code content:}), or android resource (prefixed with {@code
* android.resource:}.
* <p>
* Passing {@code null} as a {@code path} will not trigger any request but will set a
* placeholder, if one is specified.
*
* @see #load(Uri)
* @see #load(File)
* @see #load(int)
* @throws IllegalArgumentException if {@code path} is empty or blank string.
*/
public RequestCreator load(String path) {
if (path == null) {
return new RequestCreator(this, null, 0);
}
if (path.trim().length() == 0) {
throw new IllegalArgumentException("Path must not be empty.");
}
return load(Uri.parse(path));
}
/**
* Start an image request using the specified image file. This is a convenience method for
* calling {@link #load(Uri)}.
* <p>
* Passing {@code null} as a {@code file} will not trigger any request but will set a
* placeholder, if one is specified.
* <p>
* Equivalent to calling {@link #load(Uri) load(Uri.fromFile(file))}.
*
* @see #load(Uri)
* @see #load(String)
* @see #load(int)
*/
public RequestCreator load(File file) {
if (file == null) {
return new RequestCreator(this, null, 0);
}
return load(Uri.fromFile(file));
}
/**
* Start an image request using the specified drawable resource ID.
*
* @see #load(Uri)
* @see #load(String)
* @see #load(File)
*/
public RequestCreator load(int resourceId) {
if (resourceId == 0) {
throw new IllegalArgumentException("Resource ID must not be zero.");
}
return new RequestCreator(this, null, resourceId);
}
/**
* {@code true} if debug display, logging, and statistics are enabled.
* <p>
* @deprecated Use {@link #areIndicatorsEnabled()} and {@link #isLoggingEnabled()} instead.
*/
@SuppressWarnings("UnusedDeclaration") @Deprecated public boolean isDebugging() {
return areIndicatorsEnabled() && isLoggingEnabled();
}
/**
* Toggle whether debug display, logging, and statistics are enabled.
* <p>
* @deprecated Use {@link #setIndicatorsEnabled(boolean)} and {@link #setLoggingEnabled(boolean)}
* instead.
*/
@SuppressWarnings("UnusedDeclaration") @Deprecated public void setDebugging(boolean debugging) {
setIndicatorsEnabled(debugging);
}
/** Toggle whether to display debug indicators on images. */
@SuppressWarnings("UnusedDeclaration") public void setIndicatorsEnabled(boolean enabled) {
indicatorsEnabled = enabled;
}
/** {@code true} if debug indicators should are displayed on images. */
@SuppressWarnings("UnusedDeclaration") public boolean areIndicatorsEnabled() {
return indicatorsEnabled;
}
/**
* Toggle whether debug logging is enabled.
* <p>
* <b>WARNING:</b> Enabling this will result in excessive object allocation. This should be only
* be used for debugging Picasso behavior. Do NOT pass {@code BuildConfig.DEBUG}.
*/
public void setLoggingEnabled(boolean enabled) {
loggingEnabled = enabled;
}
/** {@code true} if debug logging is enabled. */
public boolean isLoggingEnabled() {
return loggingEnabled;
}
/**
* Creates a {@link StatsSnapshot} of the current stats for this instance.
* <p>
* <b>NOTE:</b> The snapshot may not always be completely up-to-date if requests are still in
* progress.
*/
@SuppressWarnings("UnusedDeclaration") public StatsSnapshot getSnapshot() {
return stats.createSnapshot();
}
/** Stops this instance from accepting further requests. */
public void shutdown() {
if (this == singleton) {
throw new UnsupportedOperationException("Default singleton instance cannot be shutdown.");
}
if (shutdown) {
return;
}
cache.clear();
cleanupThread.shutdown();
stats.shutdown();
dispatcher.shutdown();
for (DeferredRequestCreator deferredRequestCreator : targetToDeferredRequestCreator.values()) {
deferredRequestCreator.cancel();
}
targetToDeferredRequestCreator.clear();
shutdown = true;
}
List<RequestHandler> getRequestHandlers() {
return requestHandlers;
}
Request transformRequest(Request request) {
Request transformed = requestTransformer.transformRequest(request);
if (transformed == null) {
throw new IllegalStateException("Request transformer "
+ requestTransformer.getClass().getCanonicalName()
+ " returned null for "
+ request);
}
return transformed;
}
void defer(ImageView view, DeferredRequestCreator request) {
targetToDeferredRequestCreator.put(view, request);
}
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
if (target != null && targetToAction.get(target) != action) {
// This will also check we are on the main thread.
cancelExistingRequest(target);
targetToAction.put(target, action);
}
submit(action);
}
void submit(Action action) {
dispatcher.dispatchSubmit(action);
}
Bitmap quickMemoryCacheCheck(String key) {
Bitmap cached = cache.get(key);
if (cached != null) {
stats.dispatchCacheHit();
} else {
stats.dispatchCacheMiss();
}
return cached;
}
void complete(BitmapHunter hunter) {
Action single = hunter.getAction();
List<Action> joined = hunter.getActions();
boolean hasMultiple = joined != null && !joined.isEmpty();
boolean shouldDeliver = single != null || hasMultiple;
if (!shouldDeliver) {
return;
}
Uri uri = hunter.getData().uri;
Exception exception = hunter.getException();
Bitmap result = hunter.getResult();
LoadedFrom from = hunter.getLoadedFrom();
if (single != null) {
deliverAction(result, from, single);
}
if (hasMultiple) {
//noinspection ForLoopReplaceableByForEach
for (int i = 0, n = joined.size(); i < n; i++) {
Action join = joined.get(i);
deliverAction(result, from, join);
}
}
if (listener != null && exception != null) {
listener.onImageLoadFailed(this, uri, exception);
}
}
void resumeAction(Action action) {
Bitmap bitmap = null;
if (!action.skipCache) {
bitmap = quickMemoryCacheCheck(action.getKey());
}
if (bitmap != null) {
// Resumed action is cached, complete immediately.
deliverAction(bitmap, MEMORY, action);
if (loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + MEMORY);
}
} else {
// Re-submit the action to the executor.
enqueueAndSubmit(action);
if (loggingEnabled) {
log(OWNER_MAIN, VERB_RESUMED, action.request.logId());
}
}
}
private void deliverAction(Bitmap result, LoadedFrom from, Action action) {
if (action.isCancelled()) {
return;
}
if (!action.willReplay()) {
targetToAction.remove(action.getTarget());
}
if (result != null) {
if (from == null) {
throw new AssertionError("LoadedFrom cannot be null.");
}
action.complete(result, from);
if (loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
}
} else {
action.error();
if (loggingEnabled) {
log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
}
}
}
private void cancelExistingRequest(Object target) {
checkMain();
Action action = targetToAction.remove(target);
if (action != null) {
action.cancel();
dispatcher.dispatchCancel(action);
}
if (target instanceof ImageView) {
ImageView targetImageView = (ImageView) target;
DeferredRequestCreator deferredRequestCreator =
targetToDeferredRequestCreator.remove(targetImageView);
if (deferredRequestCreator != null) {
deferredRequestCreator.cancel();
}
}
}
private static class CleanupThread extends Thread {
private final ReferenceQueue<?> referenceQueue;
private final Handler handler;
CleanupThread(ReferenceQueue<?> referenceQueue, Handler handler) {
this.referenceQueue = referenceQueue;
this.handler = handler;
setDaemon(true);
setName(THREAD_PREFIX + "refQueue");
}
@Override public void run() {
Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND);
while (true) {
try {
RequestWeakReference<?> remove = (RequestWeakReference<?>) referenceQueue.remove();
handler.sendMessage(handler.obtainMessage(REQUEST_GCED, remove.action));
} catch (InterruptedException e) {
break;
} catch (final Exception e) {
handler.post(new Runnable() {
@Override public void run() {
throw new RuntimeException(e);
}
});
break;
}
}
}
void shutdown() {
interrupt();
}
}
/**
* The global default {@link Picasso} instance.
* <p>
* This instance is automatically initialized with defaults that are suitable to most
* implementations.
* <ul>
* <li>LRU memory cache of 15% the available application RAM</li>
* <li>Disk cache of 2% storage space up to 50MB but no less than 5MB. (Note: this is only
* available on API 14+ <em>or</em> if you are using a standalone library that provides a disk
* cache on all API levels like OkHttp)</li>
* <li>Three download threads for disk and network access.</li>
* </ul>
* <p>
* If these settings do not meet the requirements of your application you can construct your own
* with full control over the configuration by using {@link Picasso.Builder} to create a
* {@link Picasso} instance. You can either use this directly or by setting it as the global
* instance with {@link #setSingletonInstance}.
*/
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}
/**
* Set the global instance returned from {@link #with}.
* <p>
* This method must be called before any calls to {@link #with} and may only be called once.
*/
public static void setSingletonInstance(Picasso picasso) {
synchronized (Picasso.class) {
if (singleton != null) {
throw new IllegalStateException("Singleton instance already exists.");
}
singleton = picasso;
}
}
/** Fluent API for creating {@link Picasso} instances. */
@SuppressWarnings("UnusedDeclaration") // Public API.
public static class Builder {
private final Context context;
private Downloader downloader;
private ExecutorService service;
private Cache cache;
private Listener listener;
private RequestTransformer transformer;
private List<RequestHandler> requestHandlers;
private boolean indicatorsEnabled;
private boolean loggingEnabled;
/** Start building a new {@link Picasso} instance. */
public Builder(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context must not be null.");
}
this.context = context.getApplicationContext();
}
/** Specify the {@link Downloader} that will be used for downloading images. */
public Builder downloader(Downloader downloader) {
if (downloader == null) {
throw new IllegalArgumentException("Downloader must not be null.");
}
if (this.downloader != null) {
throw new IllegalStateException("Downloader already set.");
}
this.downloader = downloader;
return this;
}
/**
* Specify the executor service for loading images in the background.
* <p>
* Note: Calling {@link Picasso#shutdown() shutdown()} will not shutdown supplied executors.
*/
public Builder executor(ExecutorService executorService) {
if (executorService == null) {
throw new IllegalArgumentException("Executor service must not be null.");
}
if (this.service != null) {
throw new IllegalStateException("Executor service already set.");
}
this.service = executorService;
return this;
}
/** Specify the memory cache used for the most recent images. */
public Builder memoryCache(Cache memoryCache) {
if (memoryCache == null) {
throw new IllegalArgumentException("Memory cache must not be null.");
}
if (this.cache != null) {
throw new IllegalStateException("Memory cache already set.");
}
this.cache = memoryCache;
return this;
}
/** Specify a listener for interesting events. */
public Builder listener(Listener listener) {
if (listener == null) {
throw new IllegalArgumentException("Listener must not be null.");
}
if (this.listener != null) {
throw new IllegalStateException("Listener already set.");
}
this.listener = listener;
return this;
}
/**
* Specify a transformer for all incoming requests.
* <p>
* <b>NOTE:</b> This is a beta feature. The API is subject to change in a backwards incompatible
* way at any time.
*/
public Builder requestTransformer(RequestTransformer transformer) {
if (transformer == null) {
throw new IllegalArgumentException("Transformer must not be null.");
}
if (this.transformer != null) {
throw new IllegalStateException("Transformer already set.");
}
this.transformer = transformer;
return this;
}
/** Register a {@link RequestHandler}. */
public Builder addRequestHandler(RequestHandler requestHandler) {
if (requestHandler == null) {
throw new IllegalArgumentException("RequestHandler must not be null.");
}
if (requestHandlers == null) {
requestHandlers = new ArrayList<RequestHandler>();
}
if (requestHandlers.contains(requestHandler)) {
throw new IllegalStateException("RequestHandler already registered.");
}
requestHandlers.add(requestHandler);
return this;
}
/**
* @deprecated Use {@link #indicatorsEnabled(boolean)} instead.
* Whether debugging is enabled or not.
*/
@Deprecated public Builder debugging(boolean debugging) {
return indicatorsEnabled(debugging);
}
/** Toggle whether to display debug indicators on images. */
public Builder indicatorsEnabled(boolean enabled) {
this.indicatorsEnabled = enabled;
return this;
}
/**
* Toggle whether debug logging is enabled.
* <p>
* <b>WARNING:</b> Enabling this will result in excessive object allocation. This should be only
* be used for debugging purposes. Do NOT pass {@code BuildConfig.DEBUG}.
*/
public Builder loggingEnabled(boolean enabled) {
this.loggingEnabled = enabled;
return this;
}
/** Create the {@link Picasso} instance. */
public Picasso build() {
Context context = this.context;
if (downloader == null) {
downloader = Utils.createDefaultDownloader(context);
}
if (cache == null) {
cache = new LruCache(context);
}
if (service == null) {
service = new PicassoExecutorService();
}
if (transformer == null) {
transformer = RequestTransformer.IDENTITY;
}
Stats stats = new Stats(cache);
Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
return new Picasso(context, dispatcher, cache, listener, transformer,
requestHandlers, stats, indicatorsEnabled, loggingEnabled);
}
}
/** Describes where the image was loaded from. */
public enum LoadedFrom {
MEMORY(Color.GREEN),
DISK(Color.BLUE),
NETWORK(Color.RED);
final int debugColor;
private LoadedFrom(int debugColor) {
this.debugColor = debugColor;
}
}
}
| picasso/src/main/java/com/squareup/picasso/Picasso.java | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.widget.ImageView;
import android.widget.RemoteViews;
import java.io.File;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
import static com.squareup.picasso.Action.RequestWeakReference;
import static com.squareup.picasso.Dispatcher.HUNTER_BATCH_COMPLETE;
import static com.squareup.picasso.Dispatcher.REQUEST_BATCH_RESUME;
import static com.squareup.picasso.Dispatcher.REQUEST_GCED;
import static com.squareup.picasso.Picasso.LoadedFrom.MEMORY;
import static com.squareup.picasso.Utils.OWNER_MAIN;
import static com.squareup.picasso.Utils.THREAD_PREFIX;
import static com.squareup.picasso.Utils.VERB_CANCELED;
import static com.squareup.picasso.Utils.VERB_COMPLETED;
import static com.squareup.picasso.Utils.VERB_ERRORED;
import static com.squareup.picasso.Utils.VERB_RESUMED;
import static com.squareup.picasso.Utils.checkMain;
import static com.squareup.picasso.Utils.log;
/**
* Image downloading, transformation, and caching manager.
* <p>
* Use {@link #with(android.content.Context)} for the global singleton instance or construct your
* own instance with {@link Builder}.
*/
public class Picasso {
/** Callbacks for Picasso events. */
public interface Listener {
/**
* Invoked when an image has failed to load. This is useful for reporting image failures to a
* remote analytics service, for example.
*/
void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception);
}
/**
* A transformer that is called immediately before every request is submitted. This can be used to
* modify any information about a request.
* <p>
* For example, if you use a CDN you can change the hostname for the image based on the current
* location of the user in order to get faster download speeds.
* <p>
* <b>NOTE:</b> This is a beta feature. The API is subject to change in a backwards incompatible
* way at any time.
*/
public interface RequestTransformer {
/**
* Transform a request before it is submitted to be processed.
*
* @return The original request or a new request to replace it. Must not be null.
*/
Request transformRequest(Request request);
/** A {@link RequestTransformer} which returns the original request. */
RequestTransformer IDENTITY = new RequestTransformer() {
@Override public Request transformRequest(Request request) {
return request;
}
};
}
/**
* The priority of a request.
*
* @see RequestCreator#priority(Priority)
*/
public enum Priority {
LOW,
NORMAL,
HIGH
}
static final String TAG = "Picasso";
static final Handler HANDLER = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case HUNTER_BATCH_COMPLETE: {
@SuppressWarnings("unchecked") List<BitmapHunter> batch = (List<BitmapHunter>) msg.obj;
//noinspection ForLoopReplaceableByForEach
for (int i = 0, n = batch.size(); i < n; i++) {
BitmapHunter hunter = batch.get(i);
hunter.picasso.complete(hunter);
}
break;
}
case REQUEST_GCED: {
Action action = (Action) msg.obj;
if (action.getPicasso().loggingEnabled) {
log(OWNER_MAIN, VERB_CANCELED, action.request.logId(), "target got garbage collected");
}
action.picasso.cancelExistingRequest(action.getTarget());
break;
}
case REQUEST_BATCH_RESUME:
@SuppressWarnings("unchecked") List<Action> batch = (List<Action>) msg.obj;
for (int i = 0, n = batch.size(); i < n; i++) {
Action action = batch.get(i);
action.picasso.resumeAction(action);
}
break;
default:
throw new AssertionError("Unknown handler message received: " + msg.what);
}
}
};
static Picasso singleton = null;
private final Listener listener;
private final RequestTransformer requestTransformer;
private final CleanupThread cleanupThread;
private final List<RequestHandler> requestHandlers;
final Context context;
final Dispatcher dispatcher;
final Cache cache;
final Stats stats;
final Map<Object, Action> targetToAction;
final Map<ImageView, DeferredRequestCreator> targetToDeferredRequestCreator;
final ReferenceQueue<Object> referenceQueue;
boolean indicatorsEnabled;
volatile boolean loggingEnabled;
boolean shutdown;
Picasso(Context context, Dispatcher dispatcher, Cache cache, Listener listener,
RequestTransformer requestTransformer, List<RequestHandler> extraRequestHandlers,
Stats stats, boolean indicatorsEnabled, boolean loggingEnabled) {
this.context = context;
this.dispatcher = dispatcher;
this.cache = cache;
this.listener = listener;
this.requestTransformer = requestTransformer;
int builtInHandlers = 7; // Adjust this as internal handlers are added or removed.
int extraCount = (extraRequestHandlers != null ? extraRequestHandlers.size() : 0);
List<RequestHandler> allRequestHandlers =
new ArrayList<RequestHandler>(builtInHandlers + extraCount);
// ResourceRequestHandler needs to be the first in the list to avoid
// forcing other RequestHandlers to perform null checks on request.uri
// to cover the (request.resourceId != 0) case.
allRequestHandlers.add(new ResourceRequestHandler(context));
if (extraRequestHandlers != null) {
allRequestHandlers.addAll(extraRequestHandlers);
}
allRequestHandlers.add(new ContactsPhotoRequestHandler(context));
allRequestHandlers.add(new MediaStoreRequestHandler(context));
allRequestHandlers.add(new ContentStreamRequestHandler(context));
allRequestHandlers.add(new AssetRequestHandler(context));
allRequestHandlers.add(new FileRequestHandler(context));
allRequestHandlers.add(new NetworkRequestHandler(dispatcher.downloader, stats));
requestHandlers = Collections.unmodifiableList(allRequestHandlers);
this.stats = stats;
this.targetToAction = new WeakHashMap<Object, Action>();
this.targetToDeferredRequestCreator = new WeakHashMap<ImageView, DeferredRequestCreator>();
this.indicatorsEnabled = indicatorsEnabled;
this.loggingEnabled = loggingEnabled;
this.referenceQueue = new ReferenceQueue<Object>();
this.cleanupThread = new CleanupThread(referenceQueue, HANDLER);
this.cleanupThread.start();
}
/** Cancel any existing requests for the specified target {@link ImageView}. */
public void cancelRequest(ImageView view) {
cancelExistingRequest(view);
}
/** Cancel any existing requests for the specified {@link Target} instance. */
public void cancelRequest(Target target) {
cancelExistingRequest(target);
}
/**
* Cancel any existing requests for the specified {@link RemoteViews} target with the given {@code
* viewId}.
*/
public void cancelRequest(RemoteViews remoteViews, int viewId) {
cancelExistingRequest(new RemoteViewsAction.RemoteViewsTarget(remoteViews, viewId));
}
/**
* Cancel any existing requests with given tag. You can set a tag
* on new requests with {@link RequestCreator#tag(Object)}.
*
* @see RequestCreator#tag(Object)
*/
public void cancelTag(Object tag) {
checkMain();
List<Action> actions = new ArrayList<Action>(targetToAction.values());
for (int i = 0, n = actions.size(); i < n; i++) {
Action action = actions.get(i);
if (action.getTag().equals(tag)) {
cancelExistingRequest(action.getTarget());
}
}
}
/**
* Pause existing requests with the given tag. Use {@link #resumeTag(Object)}
* to resume requests with the given tag.
*
* @see #resumeTag(Object)
* @see RequestCreator#tag(Object)
*/
public void pauseTag(Object tag) {
dispatcher.dispatchPauseTag(tag);
}
/**
* Resume paused requests with the given tag. Use {@link #pauseTag(Object)}
* to pause requests with the given tag.
*
* @see #pauseTag(Object)
* @see RequestCreator#tag(Object)
*/
public void resumeTag(Object tag) {
dispatcher.dispatchResumeTag(tag);
}
/**
* Start an image request using the specified URI.
* <p>
* Passing {@code null} as a {@code uri} will not trigger any request but will set a placeholder,
* if one is specified.
*
* @see #load(File)
* @see #load(String)
* @see #load(int)
*/
public RequestCreator load(Uri uri) {
return new RequestCreator(this, uri, 0);
}
/**
* Start an image request using the specified path. This is a convenience method for calling
* {@link #load(Uri)}.
* <p>
* This path may be a remote URL, file resource (prefixed with {@code file:}), content resource
* (prefixed with {@code content:}), or android resource (prefixed with {@code
* android.resource:}.
* <p>
* Passing {@code null} as a {@code path} will not trigger any request but will set a
* placeholder, if one is specified.
*
* @see #load(Uri)
* @see #load(File)
* @see #load(int)
* @throws IllegalArgumentException if {@code path} is empty or blank string.
*/
public RequestCreator load(String path) {
if (path == null) {
return new RequestCreator(this, null, 0);
}
if (path.trim().length() == 0) {
throw new IllegalArgumentException("Path must not be empty.");
}
return load(Uri.parse(path));
}
/**
* Start an image request using the specified image file. This is a convenience method for
* calling {@link #load(Uri)}.
* <p>
* Passing {@code null} as a {@code file} will not trigger any request but will set a
* placeholder, if one is specified.
* <p>
* Equivalent to calling {@link #load(Uri) load(Uri.fromFile(file))}.
*
* @see #load(Uri)
* @see #load(String)
* @see #load(int)
*/
public RequestCreator load(File file) {
if (file == null) {
return new RequestCreator(this, null, 0);
}
return load(Uri.fromFile(file));
}
/**
* Start an image request using the specified drawable resource ID.
*
* @see #load(Uri)
* @see #load(String)
* @see #load(File)
*/
public RequestCreator load(int resourceId) {
if (resourceId == 0) {
throw new IllegalArgumentException("Resource ID must not be zero.");
}
return new RequestCreator(this, null, resourceId);
}
/**
* {@code true} if debug display, logging, and statistics are enabled.
* <p>
* @deprecated Use {@link #areIndicatorsEnabled()} and {@link #isLoggingEnabled()} instead.
*/
@SuppressWarnings("UnusedDeclaration") @Deprecated public boolean isDebugging() {
return areIndicatorsEnabled() && isLoggingEnabled();
}
/**
* Toggle whether debug display, logging, and statistics are enabled.
* <p>
* @deprecated Use {@link #setIndicatorsEnabled(boolean)} and {@link #setLoggingEnabled(boolean)}
* instead.
*/
@SuppressWarnings("UnusedDeclaration") @Deprecated public void setDebugging(boolean debugging) {
setIndicatorsEnabled(debugging);
}
/** Toggle whether to display debug indicators on images. */
@SuppressWarnings("UnusedDeclaration") public void setIndicatorsEnabled(boolean enabled) {
indicatorsEnabled = enabled;
}
/** {@code true} if debug indicators should are displayed on images. */
@SuppressWarnings("UnusedDeclaration") public boolean areIndicatorsEnabled() {
return indicatorsEnabled;
}
/**
* Toggle whether debug logging is enabled.
* <p>
* <b>WARNING:</b> Enabling this will result in excessive object allocation. This should be only
* be used for debugging Picasso behavior. Do NOT pass {@code BuildConfig.DEBUG}.
*/
public void setLoggingEnabled(boolean enabled) {
loggingEnabled = enabled;
}
/** {@code true} if debug logging is enabled. */
public boolean isLoggingEnabled() {
return loggingEnabled;
}
/**
* Creates a {@link StatsSnapshot} of the current stats for this instance.
* <p>
* <b>NOTE:</b> The snapshot may not always be completely up-to-date if requests are still in
* progress.
*/
@SuppressWarnings("UnusedDeclaration") public StatsSnapshot getSnapshot() {
return stats.createSnapshot();
}
/** Stops this instance from accepting further requests. */
public void shutdown() {
if (this == singleton) {
throw new UnsupportedOperationException("Default singleton instance cannot be shutdown.");
}
if (shutdown) {
return;
}
cache.clear();
cleanupThread.shutdown();
stats.shutdown();
dispatcher.shutdown();
for (DeferredRequestCreator deferredRequestCreator : targetToDeferredRequestCreator.values()) {
deferredRequestCreator.cancel();
}
targetToDeferredRequestCreator.clear();
shutdown = true;
}
List<RequestHandler> getRequestHandlers() {
return requestHandlers;
}
Request transformRequest(Request request) {
Request transformed = requestTransformer.transformRequest(request);
if (transformed == null) {
throw new IllegalStateException("Request transformer "
+ requestTransformer.getClass().getCanonicalName()
+ " returned null for "
+ request);
}
return transformed;
}
void defer(ImageView view, DeferredRequestCreator request) {
targetToDeferredRequestCreator.put(view, request);
}
void enqueueAndSubmit(Action action) {
Object target = action.getTarget();
if (target != null && targetToAction.get(target) != action) {
// This will also check we are on the main thread.
cancelExistingRequest(target);
targetToAction.put(target, action);
}
submit(action);
}
void submit(Action action) {
dispatcher.dispatchSubmit(action);
}
Bitmap quickMemoryCacheCheck(String key) {
Bitmap cached = cache.get(key);
if (cached != null) {
stats.dispatchCacheHit();
} else {
stats.dispatchCacheMiss();
}
return cached;
}
void complete(BitmapHunter hunter) {
Action single = hunter.getAction();
List<Action> joined = hunter.getActions();
boolean hasMultiple = joined != null && !joined.isEmpty();
boolean shouldDeliver = single != null || hasMultiple;
if (!shouldDeliver) {
return;
}
Uri uri = hunter.getData().uri;
Exception exception = hunter.getException();
Bitmap result = hunter.getResult();
LoadedFrom from = hunter.getLoadedFrom();
if (single != null) {
deliverAction(result, from, single);
}
if (hasMultiple) {
//noinspection ForLoopReplaceableByForEach
for (int i = 0, n = joined.size(); i < n; i++) {
Action join = joined.get(i);
deliverAction(result, from, join);
}
}
if (listener != null && exception != null) {
listener.onImageLoadFailed(this, uri, exception);
}
}
void resumeAction(Action action) {
Bitmap bitmap = null;
if (!action.skipCache) {
bitmap = quickMemoryCacheCheck(action.getKey());
}
if (bitmap != null) {
// Resumed action is cached, complete immediately.
deliverAction(bitmap, MEMORY, action);
if (loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + MEMORY);
}
} else {
// Re-submit the action to the executor.
enqueueAndSubmit(action);
if (loggingEnabled) {
log(OWNER_MAIN, VERB_RESUMED, action.request.logId());
}
}
}
private void deliverAction(Bitmap result, LoadedFrom from, Action action) {
if (action.isCancelled()) {
return;
}
if (!action.willReplay()) {
targetToAction.remove(action.getTarget());
}
if (result != null) {
if (from == null) {
throw new AssertionError("LoadedFrom cannot be null.");
}
action.complete(result, from);
if (loggingEnabled) {
log(OWNER_MAIN, VERB_COMPLETED, action.request.logId(), "from " + from);
}
} else {
action.error();
if (loggingEnabled) {
log(OWNER_MAIN, VERB_ERRORED, action.request.logId());
}
}
}
private void cancelExistingRequest(Object target) {
checkMain();
Action action = targetToAction.remove(target);
if (action != null) {
action.cancel();
dispatcher.dispatchCancel(action);
}
if (target instanceof ImageView) {
ImageView targetImageView = (ImageView) target;
DeferredRequestCreator deferredRequestCreator =
targetToDeferredRequestCreator.remove(targetImageView);
if (deferredRequestCreator != null) {
deferredRequestCreator.cancel();
}
}
}
private static class CleanupThread extends Thread {
private final ReferenceQueue<?> referenceQueue;
private final Handler handler;
CleanupThread(ReferenceQueue<?> referenceQueue, Handler handler) {
this.referenceQueue = referenceQueue;
this.handler = handler;
setDaemon(true);
setName(THREAD_PREFIX + "refQueue");
}
@Override public void run() {
Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND);
while (true) {
try {
RequestWeakReference<?> remove = (RequestWeakReference<?>) referenceQueue.remove();
handler.sendMessage(handler.obtainMessage(REQUEST_GCED, remove.action));
} catch (InterruptedException e) {
break;
} catch (final Exception e) {
handler.post(new Runnable() {
@Override public void run() {
throw new RuntimeException(e);
}
});
break;
}
}
}
void shutdown() {
interrupt();
}
}
/**
* The global default {@link Picasso} instance.
* <p>
* This instance is automatically initialized with defaults that are suitable to most
* implementations.
* <ul>
* <li>LRU memory cache of 15% the available application RAM</li>
* <li>Disk cache of 2% storage space up to 50MB but no less than 5MB. (Note: this is only
* available on API 14+ <em>or</em> if you are using a standalone library that provides a disk
* cache on all API levels like OkHttp)</li>
* <li>Three download threads for disk and network access.</li>
* </ul>
* <p>
* If these settings do not meet the requirements of your application you can construct your own
* with full control over the configuration by using {@link Picasso.Builder} to create a
* {@link Picasso} instance. You can either use this directly or by setting it as the global
* instance with {@link #setSingletonInstance}.
*/
public static Picasso with(Context context) {
if (singleton == null) {
synchronized (Picasso.class) {
if (singleton == null) {
singleton = new Builder(context).build();
}
}
}
return singleton;
}
/**
* Set the global instance returned from {@link #with}.
* <p>
* This method must be called before any calls to {@link #with} and may only be called once.
*/
public static void setSingletonInstance(Picasso picasso) {
synchronized (Picasso.class) {
if (singleton != null) {
throw new IllegalStateException("Singleton instance already exists.");
}
singleton = picasso;
}
}
/** Fluent API for creating {@link Picasso} instances. */
@SuppressWarnings("UnusedDeclaration") // Public API.
public static class Builder {
private final Context context;
private Downloader downloader;
private ExecutorService service;
private Cache cache;
private Listener listener;
private RequestTransformer transformer;
private List<RequestHandler> requestHandlers;
private boolean indicatorsEnabled;
private boolean loggingEnabled;
/** Start building a new {@link Picasso} instance. */
public Builder(Context context) {
if (context == null) {
throw new IllegalArgumentException("Context must not be null.");
}
this.context = context.getApplicationContext();
}
/** Specify the {@link Downloader} that will be used for downloading images. */
public Builder downloader(Downloader downloader) {
if (downloader == null) {
throw new IllegalArgumentException("Downloader must not be null.");
}
if (this.downloader != null) {
throw new IllegalStateException("Downloader already set.");
}
this.downloader = downloader;
return this;
}
/**
* Specify the executor service for loading images in the background.
* <p>
* Note: Calling {@link Picasso#shutdown() shutdown()} will not shutdown supplied executors.
*/
public Builder executor(ExecutorService executorService) {
if (executorService == null) {
throw new IllegalArgumentException("Executor service must not be null.");
}
if (this.service != null) {
throw new IllegalStateException("Executor service already set.");
}
this.service = executorService;
return this;
}
/** Specify the memory cache used for the most recent images. */
public Builder memoryCache(Cache memoryCache) {
if (memoryCache == null) {
throw new IllegalArgumentException("Memory cache must not be null.");
}
if (this.cache != null) {
throw new IllegalStateException("Memory cache already set.");
}
this.cache = memoryCache;
return this;
}
/** Specify a listener for interesting events. */
public Builder listener(Listener listener) {
if (listener == null) {
throw new IllegalArgumentException("Listener must not be null.");
}
if (this.listener != null) {
throw new IllegalStateException("Listener already set.");
}
this.listener = listener;
return this;
}
/**
* Specify a transformer for all incoming requests.
* <p>
* <b>NOTE:</b> This is a beta feature. The API is subject to change in a backwards incompatible
* way at any time.
*/
public Builder requestTransformer(RequestTransformer transformer) {
if (transformer == null) {
throw new IllegalArgumentException("Transformer must not be null.");
}
if (this.transformer != null) {
throw new IllegalStateException("Transformer already set.");
}
this.transformer = transformer;
return this;
}
/** Register a {@link RequestHandler}. */
public Builder addRequestHandler(RequestHandler requestHandler) {
if (requestHandler == null) {
throw new IllegalArgumentException("RequestHandler must not be null.");
}
if (requestHandlers == null) {
requestHandlers = new ArrayList<RequestHandler>();
}
if (requestHandlers.contains(requestHandler)) {
throw new IllegalStateException("RequestHandler already registered.");
}
requestHandlers.add(requestHandler);
return this;
}
/**
* @deprecated Use {@link #indicatorsEnabled(boolean)} instead.
* Whether debugging is enabled or not.
*/
@Deprecated public Builder debugging(boolean debugging) {
return indicatorsEnabled(debugging);
}
/** Toggle whether to display debug indicators on images. */
public Builder indicatorsEnabled(boolean enabled) {
this.indicatorsEnabled = enabled;
return this;
}
/**
* Toggle whether debug logging is enabled.
* <p>
* <b>WARNING:</b> Enabling this will result in excessive object allocation. This should be only
* be used for debugging purposes. Do NOT pass {@code BuildConfig.DEBUG}.
*/
public Builder loggingEnabled(boolean enabled) {
this.loggingEnabled = enabled;
return this;
}
/** Create the {@link Picasso} instance. */
public Picasso build() {
Context context = this.context;
if (downloader == null) {
downloader = Utils.createDefaultDownloader(context);
}
if (cache == null) {
cache = new LruCache(context);
}
if (service == null) {
service = new PicassoExecutorService();
}
if (transformer == null) {
transformer = RequestTransformer.IDENTITY;
}
Stats stats = new Stats(cache);
Dispatcher dispatcher = new Dispatcher(context, service, HANDLER, downloader, cache, stats);
return new Picasso(context, dispatcher, cache, listener, transformer,
requestHandlers, stats, indicatorsEnabled, loggingEnabled);
}
}
/** Describes where the image was loaded from. */
public enum LoadedFrom {
MEMORY(Color.GREEN),
DISK(Color.YELLOW),
NETWORK(Color.RED);
final int debugColor;
private LoadedFrom(int debugColor) {
this.debugColor = debugColor;
}
}
}
| Using colourblind friendly LoadedFrom indicators
Colours can now be differentiated easily be colourblind folk. | picasso/src/main/java/com/squareup/picasso/Picasso.java | Using colourblind friendly LoadedFrom indicators |
|
Java | apache-2.0 | db69d90d63f28bed1918518435a6d7cac86a5b97 | 0 | daradurvs/ignite,apache/ignite,SharplEr/ignite,ascherbakoff/ignite,vladisav/ignite,SomeFire/ignite,StalkXT/ignite,ascherbakoff/ignite,apache/ignite,BiryukovVA/ignite,psadusumilli/ignite,nizhikov/ignite,chandresh-pancholi/ignite,voipp/ignite,nizhikov/ignite,ilantukh/ignite,nizhikov/ignite,StalkXT/ignite,ascherbakoff/ignite,nizhikov/ignite,ptupitsyn/ignite,NSAmelchev/ignite,shroman/ignite,apache/ignite,samaitra/ignite,andrey-kuznetsov/ignite,alexzaitzev/ignite,psadusumilli/ignite,xtern/ignite,daradurvs/ignite,apache/ignite,daradurvs/ignite,vladisav/ignite,apache/ignite,psadusumilli/ignite,samaitra/ignite,sk0x50/ignite,samaitra/ignite,shroman/ignite,psadusumilli/ignite,vladisav/ignite,irudyak/ignite,vladisav/ignite,xtern/ignite,SharplEr/ignite,ilantukh/ignite,irudyak/ignite,SomeFire/ignite,BiryukovVA/ignite,irudyak/ignite,SomeFire/ignite,chandresh-pancholi/ignite,xtern/ignite,irudyak/ignite,voipp/ignite,BiryukovVA/ignite,shroman/ignite,irudyak/ignite,ilantukh/ignite,ilantukh/ignite,ilantukh/ignite,vladisav/ignite,vladisav/ignite,psadusumilli/ignite,sk0x50/ignite,ptupitsyn/ignite,voipp/ignite,endian675/ignite,nizhikov/ignite,shroman/ignite,alexzaitzev/ignite,endian675/ignite,amirakhmedov/ignite,SharplEr/ignite,xtern/ignite,amirakhmedov/ignite,alexzaitzev/ignite,sk0x50/ignite,ilantukh/ignite,samaitra/ignite,voipp/ignite,ascherbakoff/ignite,psadusumilli/ignite,amirakhmedov/ignite,StalkXT/ignite,psadusumilli/ignite,samaitra/ignite,endian675/ignite,irudyak/ignite,samaitra/ignite,sk0x50/ignite,andrey-kuznetsov/ignite,voipp/ignite,StalkXT/ignite,apache/ignite,SharplEr/ignite,alexzaitzev/ignite,ilantukh/ignite,SomeFire/ignite,chandresh-pancholi/ignite,vladisav/ignite,BiryukovVA/ignite,shroman/ignite,ptupitsyn/ignite,irudyak/ignite,apache/ignite,ptupitsyn/ignite,ptupitsyn/ignite,samaitra/ignite,psadusumilli/ignite,BiryukovVA/ignite,daradurvs/ignite,StalkXT/ignite,amirakhmedov/ignite,NSAmelchev/ignite,NSAmelchev/ignite,alexzaitzev/ignite,amirakhmedov/ignite,NSAmelchev/ignite,xtern/ignite,xtern/ignite,chandresh-pancholi/ignite,endian675/ignite,shroman/ignite,sk0x50/ignite,shroman/ignite,chandresh-pancholi/ignite,daradurvs/ignite,alexzaitzev/ignite,SharplEr/ignite,apache/ignite,SomeFire/ignite,nizhikov/ignite,andrey-kuznetsov/ignite,alexzaitzev/ignite,chandresh-pancholi/ignite,NSAmelchev/ignite,amirakhmedov/ignite,vladisav/ignite,BiryukovVA/ignite,sk0x50/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,samaitra/ignite,ptupitsyn/ignite,StalkXT/ignite,endian675/ignite,andrey-kuznetsov/ignite,nizhikov/ignite,samaitra/ignite,sk0x50/ignite,amirakhmedov/ignite,daradurvs/ignite,ptupitsyn/ignite,SomeFire/ignite,irudyak/ignite,endian675/ignite,StalkXT/ignite,xtern/ignite,alexzaitzev/ignite,BiryukovVA/ignite,andrey-kuznetsov/ignite,sk0x50/ignite,SomeFire/ignite,andrey-kuznetsov/ignite,xtern/ignite,ilantukh/ignite,ptupitsyn/ignite,shroman/ignite,xtern/ignite,apache/ignite,SomeFire/ignite,voipp/ignite,endian675/ignite,NSAmelchev/ignite,shroman/ignite,nizhikov/ignite,alexzaitzev/ignite,SomeFire/ignite,samaitra/ignite,SharplEr/ignite,voipp/ignite,voipp/ignite,ascherbakoff/ignite,ascherbakoff/ignite,chandresh-pancholi/ignite,daradurvs/ignite,BiryukovVA/ignite,ptupitsyn/ignite,daradurvs/ignite,ascherbakoff/ignite,andrey-kuznetsov/ignite,ptupitsyn/ignite,SharplEr/ignite,ascherbakoff/ignite,sk0x50/ignite,NSAmelchev/ignite,daradurvs/ignite,BiryukovVA/ignite,amirakhmedov/ignite,andrey-kuznetsov/ignite,SomeFire/ignite,voipp/ignite,ilantukh/ignite,NSAmelchev/ignite,NSAmelchev/ignite,ilantukh/ignite,StalkXT/ignite,SharplEr/ignite,andrey-kuznetsov/ignite,StalkXT/ignite,irudyak/ignite,daradurvs/ignite,SharplEr/ignite,chandresh-pancholi/ignite,BiryukovVA/ignite,amirakhmedov/ignite,ascherbakoff/ignite,shroman/ignite,nizhikov/ignite,endian675/ignite | /*
* 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.ignite.internal.processors.cache.persistence.wal;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.file.Files;
import java.sql.Time;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.WALMode;
import org.apache.ignite.events.EventType;
import org.apache.ignite.events.WalSegmentArchivedEvent;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.IgnitionEx;
import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager;
import org.apache.ignite.internal.pagemem.wal.IgniteWriteAheadLogManager;
import org.apache.ignite.internal.pagemem.wal.StorageException;
import org.apache.ignite.internal.pagemem.wal.WALIterator;
import org.apache.ignite.internal.pagemem.wal.WALPointer;
import org.apache.ignite.internal.pagemem.wal.record.CheckpointRecord;
import org.apache.ignite.internal.pagemem.wal.record.MarshalledRecord;
import org.apache.ignite.internal.pagemem.wal.record.SwitchSegmentRecord;
import org.apache.ignite.internal.pagemem.wal.record.WALRecord;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.GridCacheSharedManagerAdapter;
import org.apache.ignite.internal.processors.cache.persistence.DataStorageMetricsImpl;
import org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIO;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory;
import org.apache.ignite.internal.processors.cache.persistence.filename.PdsFolderSettings;
import org.apache.ignite.internal.processors.cache.persistence.wal.crc.PureJavaCrc32;
import org.apache.ignite.internal.processors.cache.persistence.wal.record.HeaderRecord;
import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordSerializer;
import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordSerializerFactory;
import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordSerializerFactoryImpl;
import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordV1Serializer;
import org.apache.ignite.internal.processors.timeout.GridTimeoutObject;
import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor;
import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.typedef.CIX1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.lang.IgniteUuid;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jsr166.ConcurrentHashMap8;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_WAL_SERIALIZER_VERSION;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_WAL_MMAP;
import static org.apache.ignite.configuration.WALMode.LOG_ONLY;
import static org.apache.ignite.internal.pagemem.wal.record.WALRecord.RecordType.SWITCH_SEGMENT_RECORD;
import static org.apache.ignite.internal.processors.cache.persistence.wal.SegmentedRingByteBuffer.BufferMode.DIRECT;
import static org.apache.ignite.internal.util.IgniteUtils.findField;
import static org.apache.ignite.internal.util.IgniteUtils.findNonPublicMethod;
/**
* File WAL manager.
*/
public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter implements IgniteWriteAheadLogManager {
/** {@link MappedByteBuffer#force0(java.io.FileDescriptor, long, long)}. */
private static final Method force0 = findNonPublicMethod(
MappedByteBuffer.class, "force0",
java.io.FileDescriptor.class, long.class, long.class
);
/** {@link MappedByteBuffer#mappingOffset()}. */
private static final Method mappingOffset = findNonPublicMethod(MappedByteBuffer.class, "mappingOffset");
/** {@link MappedByteBuffer#mappingAddress(long)}. */
private static final Method mappingAddress = findNonPublicMethod(
MappedByteBuffer.class, "mappingAddress", long.class
);
/** {@link MappedByteBuffer#fd} */
private static final Field fd = findField(MappedByteBuffer.class, "fd");
/** Page size. */
private static final int PAGE_SIZE = GridUnsafe.pageSize();
/** */
private static final FileDescriptor[] EMPTY_DESCRIPTORS = new FileDescriptor[0];
/** WAL segment file extension. */
private static final String WAL_SEGMENT_FILE_EXT = ".wal";
/** */
private static final byte[] FILL_BUF = new byte[1024 * 1024];
/** Pattern for segment file names */
private static final Pattern WAL_NAME_PATTERN = Pattern.compile("\\d{16}\\.wal");
/** */
private static final Pattern WAL_TEMP_NAME_PATTERN = Pattern.compile("\\d{16}\\.wal\\.tmp");
/** WAL segment file filter, see {@link #WAL_NAME_PATTERN} */
public static final FileFilter WAL_SEGMENT_FILE_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && WAL_NAME_PATTERN.matcher(file.getName()).matches();
}
};
/** */
private static final FileFilter WAL_SEGMENT_TEMP_FILE_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && WAL_TEMP_NAME_PATTERN.matcher(file.getName()).matches();
}
};
/** */
private static final Pattern WAL_SEGMENT_FILE_COMPACTED_PATTERN = Pattern.compile("\\d{16}\\.wal\\.zip");
/** WAL segment file filter, see {@link #WAL_NAME_PATTERN} */
public static final FileFilter WAL_SEGMENT_COMPACTED_OR_RAW_FILE_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && (WAL_NAME_PATTERN.matcher(file.getName()).matches() ||
WAL_SEGMENT_FILE_COMPACTED_PATTERN.matcher(file.getName()).matches());
}
};
/** */
private static final Pattern WAL_SEGMENT_TEMP_FILE_COMPACTED_PATTERN = Pattern.compile("\\d{16}\\.wal\\.zip\\.tmp");
/** */
private static final FileFilter WAL_SEGMENT_FILE_COMPACTED_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && WAL_SEGMENT_FILE_COMPACTED_PATTERN.matcher(file.getName()).matches();
}
};
/** */
private static final FileFilter WAL_SEGMENT_TEMP_FILE_COMPACTED_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && WAL_SEGMENT_TEMP_FILE_COMPACTED_PATTERN.matcher(file.getName()).matches();
}
};
/** Latest serializer version to use. */
private static final int LATEST_SERIALIZER_VERSION = 2;
/** Buffer size. */
private static final int BUF_SIZE = 1024 * 1024;
/** Use mapped byte buffer. */
private static boolean mmap = IgniteSystemProperties.getBoolean(IGNITE_WAL_MMAP, true);
/** {@link FileWriteHandle#written} atomic field updater. */
private static final AtomicLongFieldUpdater<FileWriteHandle> WRITTEN_UPD =
AtomicLongFieldUpdater.newUpdater(FileWriteHandle.class, "written");
/** Interrupted flag. */
private final ThreadLocal<Boolean> interrupted = new ThreadLocal<Boolean>() {
@Override protected Boolean initialValue() {
return false;
}
};
/** */
private final boolean alwaysWriteFullPages;
/** WAL segment size in bytes */
private final long maxWalSegmentSize;
/** */
private final WALMode mode;
/** WAL flush frequency. Makes sense only for {@link WALMode#BACKGROUND} log WALMode. */
private final long flushFreq;
/** Fsync delay. */
private final long fsyncDelay;
/** */
private final DataStorageConfiguration dsCfg;
/** Events service */
private final GridEventStorageManager evt;
/** */
private IgniteConfiguration igCfg;
/** Persistence metrics tracker. */
private DataStorageMetricsImpl metrics;
/** */
private File walWorkDir;
/** WAL archive directory (including consistent ID as subfolder) */
private File walArchiveDir;
/** Serializer of latest version, used to read header record and for write records */
private RecordSerializer serializer;
/** Serializer latest version to use. */
private final int serializerVer =
IgniteSystemProperties.getInteger(IGNITE_WAL_SERIALIZER_VERSION, LATEST_SERIALIZER_VERSION);
/** Latest segment cleared by {@link #truncate(WALPointer)}. */
private volatile long lastTruncatedArchiveIdx = -1L;
/** Factory to provide I/O interfaces for read/write operations with files */
private final FileIOFactory ioFactory;
/** Updater for {@link #currHnd}, used for verify there are no concurrent update for current log segment handle */
private static final AtomicReferenceFieldUpdater<FileWriteAheadLogManager, FileWriteHandle> CURR_HND_UPD =
AtomicReferenceFieldUpdater.newUpdater(FileWriteAheadLogManager.class, FileWriteHandle.class, "currHnd");
/** */
private volatile FileArchiver archiver;
/** Compressor. */
private volatile FileCompressor compressor;
/** Decompressor. */
private volatile FileDecompressor decompressor;
/** */
private final ThreadLocal<WALPointer> lastWALPtr = new ThreadLocal<>();
/** Current log segment handle */
private volatile FileWriteHandle currHnd;
/** Environment failure. */
private volatile Throwable envFailed;
/**
* Positive (non-0) value indicates WAL can be archived even if not complete<br>
* See {@link DataStorageConfiguration#setWalAutoArchiveAfterInactivity(long)}<br>
*/
private final long walAutoArchiveAfterInactivity;
/**
* Container with last WAL record logged timestamp.<br> Zero value means there was no records logged to current
* segment, skip possible archiving for this case<br> Value is filled only for case {@link
* #walAutoArchiveAfterInactivity} > 0<br>
*/
private AtomicLong lastRecordLoggedMs = new AtomicLong();
/**
* Cancellable task for {@link WALMode#BACKGROUND}, should be cancelled at shutdown Null for non background modes
*/
@Nullable private volatile GridTimeoutProcessor.CancelableTask backgroundFlushSchedule;
/**
* Reference to the last added next archive timeout check object. Null if mode is not enabled. Should be cancelled
* at shutdown
*/
@Nullable private volatile GridTimeoutObject nextAutoArchiveTimeoutObj;
/** WAL writer worker. */
private WALWriter walWriter;
/**
* @param ctx Kernal context.
*/
public FileWriteAheadLogManager(@NotNull final GridKernalContext ctx) {
igCfg = ctx.config();
DataStorageConfiguration dsCfg = igCfg.getDataStorageConfiguration();
assert dsCfg != null;
this.dsCfg = dsCfg;
maxWalSegmentSize = dsCfg.getWalSegmentSize();
mode = dsCfg.getWalMode();
flushFreq = dsCfg.getWalFlushFrequency();
fsyncDelay = dsCfg.getWalFsyncDelayNanos();
alwaysWriteFullPages = dsCfg.isAlwaysWriteFullPages();
ioFactory = dsCfg.getFileIOFactory();
walAutoArchiveAfterInactivity = dsCfg.getWalAutoArchiveAfterInactivity();
evt = ctx.event();
}
/** {@inheritDoc} */
@Override public void start0() throws IgniteCheckedException {
if (!cctx.kernalContext().clientNode()) {
final PdsFolderSettings resolveFolders = cctx.kernalContext().pdsFolderResolver().resolveFolders();
checkWalConfiguration();
walWorkDir = initDirectory(
dsCfg.getWalPath(),
DataStorageConfiguration.DFLT_WAL_PATH,
resolveFolders.folderName(),
"write ahead log work directory"
);
walArchiveDir = initDirectory(
dsCfg.getWalArchivePath(),
DataStorageConfiguration.DFLT_WAL_ARCHIVE_PATH,
resolveFolders.folderName(),
"write ahead log archive directory"
);
serializer = new RecordSerializerFactoryImpl(cctx).createSerializer(serializerVer);
GridCacheDatabaseSharedManager dbMgr = (GridCacheDatabaseSharedManager)cctx.database();
metrics = dbMgr.persistentStoreMetricsImpl();
checkOrPrepareFiles();
IgniteBiTuple<Long, Long> tup = scanMinMaxArchiveIndices();
lastTruncatedArchiveIdx = tup == null ? -1 : tup.get1() - 1;
archiver = new FileArchiver(tup == null ? -1 : tup.get2());
if (dsCfg.isWalCompactionEnabled()) {
compressor = new FileCompressor();
decompressor = new FileDecompressor();
}
if (mode != WALMode.NONE) {
if (log.isInfoEnabled())
log.info("Started write-ahead log manager [mode=" + mode + ']');
}
else
U.quietAndWarn(log, "Started write-ahead log manager in NONE mode, persisted data may be lost in " +
"a case of unexpected node failure. Make sure to deactivate the cluster before shutdown.");
}
}
/**
* @throws IgniteCheckedException if WAL store path is configured and archive path isn't (or vice versa)
*/
private void checkWalConfiguration() throws IgniteCheckedException {
if (dsCfg.getWalPath() == null ^ dsCfg.getWalArchivePath() == null) {
throw new IgniteCheckedException(
"Properties should be either both specified or both null " +
"[walStorePath = " + dsCfg.getWalPath() +
", walArchivePath = " + dsCfg.getWalArchivePath() + "]"
);
}
}
/** {@inheritDoc} */
@Override protected void stop0(boolean cancel) {
final GridTimeoutProcessor.CancelableTask schedule = backgroundFlushSchedule;
if (schedule != null)
schedule.close();
final GridTimeoutObject timeoutObj = nextAutoArchiveTimeoutObj;
if (timeoutObj != null)
cctx.time().removeTimeoutObject(timeoutObj);
final FileWriteHandle currHnd = currentHandle();
try {
if (mode == WALMode.BACKGROUND) {
if (currHnd != null)
currHnd.flush(null);
}
if (currHnd != null)
currHnd.close(false);
if (walWriter != null)
walWriter.shutdown();
if (archiver != null)
archiver.shutdown();
if (compressor != null)
compressor.shutdown();
if (decompressor != null)
decompressor.shutdown();
}
catch (Exception e) {
U.error(log, "Failed to gracefully close WAL segment: " + this.currHnd.fileIO, e);
}
}
/** {@inheritDoc} */
@Override public void onActivate(GridKernalContext kctx) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Activated file write ahead log manager [nodeId=" + cctx.localNodeId() +
" topVer=" + cctx.discovery().topologyVersionEx() + " ]");
start0();
if (!cctx.kernalContext().clientNode()) {
assert archiver != null;
archiver.start();
if (compressor != null)
compressor.start();
if (decompressor != null)
decompressor.start();
}
}
/** {@inheritDoc} */
@Override public void onDeActivate(GridKernalContext kctx) {
if (log.isDebugEnabled())
log.debug("DeActivate file write ahead log [nodeId=" + cctx.localNodeId() +
" topVer=" + cctx.discovery().topologyVersionEx() + " ]");
stop0(true);
currHnd = null;
}
/** {@inheritDoc} */
@Override public boolean isAlwaysWriteFullPages() {
return alwaysWriteFullPages;
}
/** {@inheritDoc} */
@Override public boolean isFullSync() {
return mode == WALMode.DEFAULT;
}
/** {@inheritDoc} */
@Override public void resumeLogging(WALPointer lastPtr) throws IgniteCheckedException {
try {
assert currHnd == null;
assert lastPtr == null || lastPtr instanceof FileWALPointer;
FileWALPointer filePtr = (FileWALPointer)lastPtr;
walWriter = new WALWriter();
if (!mmap)
walWriter.start();
currHnd = restoreWriteHandle(filePtr);
// For new handle write serializer version to it.
if (filePtr == null)
currHnd.writeHeader();
if (currHnd.serializer.version() != serializer.version()) {
if (log.isInfoEnabled())
log.info("Record serializer version change detected, will start logging with a new WAL record " +
"serializer to a new WAL segment [curFile=" + currHnd + ", newVer=" + serializer.version() +
", oldVer=" + currHnd.serializer.version() + ']');
rollOver(currHnd);
}
currHnd.resume = false;
if (mode == WALMode.BACKGROUND) {
backgroundFlushSchedule = cctx.time().schedule(new Runnable() {
@Override public void run() {
doFlush();
}
}, flushFreq, flushFreq);
}
if (walAutoArchiveAfterInactivity > 0)
scheduleNextInactivityPeriodElapsedCheck();
}
catch (StorageException e) {
throw new IgniteCheckedException(e);
}
}
/**
* Schedules next check of inactivity period expired. Based on current record update timestamp. At timeout method
* does check of inactivity period and schedules new launch.
*/
private void scheduleNextInactivityPeriodElapsedCheck() {
final long lastRecMs = lastRecordLoggedMs.get();
final long nextPossibleAutoArchive = (lastRecMs <= 0 ? U.currentTimeMillis() : lastRecMs) + walAutoArchiveAfterInactivity;
if (log.isDebugEnabled())
log.debug("Schedule WAL rollover check at " + new Time(nextPossibleAutoArchive).toString());
nextAutoArchiveTimeoutObj = new GridTimeoutObject() {
private final IgniteUuid id = IgniteUuid.randomUuid();
@Override public IgniteUuid timeoutId() {
return id;
}
@Override public long endTime() {
return nextPossibleAutoArchive;
}
@Override public void onTimeout() {
if (log.isDebugEnabled())
log.debug("Checking if WAL rollover required (" + new Time(U.currentTimeMillis()).toString() + ")");
checkWalRolloverRequiredDuringInactivityPeriod();
scheduleNextInactivityPeriodElapsedCheck();
}
};
cctx.time().addTimeoutObject(nextAutoArchiveTimeoutObj);
}
/**
* @return Latest serializer version.
*/
public int serializerVersion() {
return serializerVer;
}
/**
* Checks if there was elapsed significant period of inactivity. If WAL auto-archive is enabled using
* {@link #walAutoArchiveAfterInactivity} > 0 this method will activate roll over by timeout.<br>
*/
private void checkWalRolloverRequiredDuringInactivityPeriod() {
if (walAutoArchiveAfterInactivity <= 0)
return; // feature not configured, nothing to do
final long lastRecMs = lastRecordLoggedMs.get();
if (lastRecMs == 0)
return; //no records were logged to current segment, does not consider inactivity
final long elapsedMs = U.currentTimeMillis() - lastRecMs;
if (elapsedMs <= walAutoArchiveAfterInactivity)
return; // not enough time elapsed since last write
if (!lastRecordLoggedMs.compareAndSet(lastRecMs, 0))
return; // record write occurred concurrently
final FileWriteHandle handle = currentHandle();
try {
handle.buf.close();
rollOver(handle);
}
catch (IgniteCheckedException e) {
U.error(log, "Unable to perform segment rollover: " + e.getMessage(), e);
handle.invalidateEnvironment(e);
}
}
/** {@inheritDoc} */
@SuppressWarnings("TooBroadScope")
@Override public WALPointer log(WALRecord rec) throws IgniteCheckedException, StorageException {
if (serializer == null || mode == WALMode.NONE)
return null;
FileWriteHandle currWrHandle = currentHandle();
// Logging was not resumed yet.
if (currWrHandle == null)
return null;
// Need to calculate record size first.
rec.size(serializer.size(rec));
for (; ; currWrHandle = rollOver(currWrHandle)) {
WALPointer ptr = currWrHandle.addRecord(rec);
if (ptr != null) {
metrics.onWalRecordLogged();
lastWALPtr.set(ptr);
if (walAutoArchiveAfterInactivity > 0)
lastRecordLoggedMs.set(U.currentTimeMillis());
return ptr;
}
checkEnvironment();
if (isStopping())
throw new IgniteCheckedException("Stopping.");
}
}
/** {@inheritDoc} */
@Override public void fsync(WALPointer ptr) throws IgniteCheckedException, StorageException {
if (serializer == null || mode == WALMode.NONE)
return;
FileWriteHandle cur = currentHandle();
// WAL manager was not started (client node).
if (cur == null)
return;
FileWALPointer filePtr = (FileWALPointer)(ptr == null ? lastWALPtr.get() : ptr);
if (mode == WALMode.BACKGROUND)
return;
if (mode == LOG_ONLY) {
cur.flushOrWait(filePtr);
return;
}
// No need to sync if was rolled over.
if (filePtr != null && !cur.needFsync(filePtr))
return;
cur.fsync(filePtr);
}
/** {@inheritDoc} */
@Override public WALIterator replay(WALPointer start) throws IgniteCheckedException, StorageException {
assert start == null || start instanceof FileWALPointer : "Invalid start pointer: " + start;
FileWriteHandle hnd = currentHandle();
FileWALPointer end = null;
if (hnd != null)
end = hnd.position();
return new RecordsIterator(
cctx,
walWorkDir,
walArchiveDir,
(FileWALPointer)start,
end,
dsCfg,
new RecordSerializerFactoryImpl(cctx),
ioFactory,
archiver,
decompressor,
log
);
}
/** {@inheritDoc} */
@Override public boolean reserve(WALPointer start) throws IgniteCheckedException {
assert start != null && start instanceof FileWALPointer : "Invalid start pointer: " + start;
if (mode == WALMode.NONE)
return false;
FileArchiver archiver0 = archiver;
if (archiver0 == null)
throw new IgniteCheckedException("Could not reserve WAL segment: archiver == null");
archiver0.reserve(((FileWALPointer)start).index());
if (!hasIndex(((FileWALPointer)start).index())) {
archiver0.release(((FileWALPointer)start).index());
return false;
}
return true;
}
/** {@inheritDoc} */
@Override public void release(WALPointer start) throws IgniteCheckedException {
assert start != null && start instanceof FileWALPointer : "Invalid start pointer: " + start;
if (mode == WALMode.NONE)
return;
FileArchiver archiver0 = archiver;
if (archiver0 == null)
throw new IgniteCheckedException("Could not release WAL segment: archiver == null");
archiver0.release(((FileWALPointer)start).index());
}
/**
* @param absIdx Absolulte index to check.
* @return {@code true} if has this index.
*/
private boolean hasIndex(long absIdx) {
String segmentName = FileDescriptor.fileName(absIdx);
String zipSegmentName = FileDescriptor.fileName(absIdx) + ".zip";
boolean inArchive = new File(walArchiveDir, segmentName).exists() ||
new File(walArchiveDir, zipSegmentName).exists();
if (inArchive)
return true;
if (absIdx <= lastArchivedIndex())
return false;
FileWriteHandle cur = currHnd;
return cur != null && cur.idx >= absIdx;
}
/** {@inheritDoc} */
@Override public int truncate(WALPointer ptr) {
if (ptr == null)
return 0;
assert ptr instanceof FileWALPointer : ptr;
// File pointer bound: older entries will be deleted from archive
FileWALPointer fPtr = (FileWALPointer)ptr;
FileDescriptor[] descs = scan(walArchiveDir.listFiles(WAL_SEGMENT_COMPACTED_OR_RAW_FILE_FILTER));
int deleted = 0;
FileArchiver archiver0 = archiver;
for (FileDescriptor desc : descs) {
// Do not delete reserved or locked segment and any segment after it.
if (archiver0 != null && archiver0.reserved(desc.idx))
return deleted;
// We need to leave at least one archived segment to correctly determine the archive index.
if (desc.idx + 1 < fPtr.index()) {
if (!desc.file.delete())
U.warn(log, "Failed to remove obsolete WAL segment (make sure the process has enough rights): " +
desc.file.getAbsolutePath());
else
deleted++;
// Bump up the oldest archive segment index.
if (lastTruncatedArchiveIdx < desc.idx)
lastTruncatedArchiveIdx = desc.idx;
}
}
return deleted;
}
/** {@inheritDoc} */
@Override public void allowCompressionUntil(WALPointer ptr) {
if (compressor != null)
compressor.allowCompressionUntil(((FileWALPointer)ptr).index());
}
/** {@inheritDoc} */
@Override public int walArchiveSegments() {
long lastTruncated = lastTruncatedArchiveIdx;
long lastArchived = archiver.lastArchivedAbsoluteIndex();
if (lastArchived == -1)
return 0;
int res = (int)(lastArchived - lastTruncated);
return res >= 0 ? res : 0;
}
/** {@inheritDoc} */
@Override public boolean reserved(WALPointer ptr) {
FileWALPointer fPtr = (FileWALPointer)ptr;
FileArchiver archiver0 = archiver;
return archiver0 != null && archiver0.reserved(fPtr.index());
}
/**
* Lists files in archive directory and returns the index of last archived file.
*
* @return The absolute index of last archived file.
*/
private long lastArchivedIndex() {
long lastIdx = -1;
for (File file : walArchiveDir.listFiles(WAL_SEGMENT_COMPACTED_OR_RAW_FILE_FILTER)) {
try {
long idx = Long.parseLong(file.getName().substring(0, 16));
lastIdx = Math.max(lastIdx, idx);
}
catch (NumberFormatException | IndexOutOfBoundsException ignore) {
}
}
return lastIdx;
}
/**
* Lists files in archive directory and returns the indices of least and last archived files.
* In case of holes, first segment after last "hole" is considered as minimum.
* Example: minimum(0, 1, 10, 11, 20, 21, 22) should be 20
*
* @return The absolute indices of min and max archived files.
*/
private IgniteBiTuple<Long, Long> scanMinMaxArchiveIndices() {
TreeSet<Long> archiveIndices = new TreeSet<>();
for (File file : walArchiveDir.listFiles(WAL_SEGMENT_COMPACTED_OR_RAW_FILE_FILTER)) {
try {
long idx = Long.parseLong(file.getName().substring(0, 16));
archiveIndices.add(idx);
}
catch (NumberFormatException | IndexOutOfBoundsException ignore) {
// No-op.
}
}
if (archiveIndices.isEmpty())
return null;
else {
Long min = archiveIndices.first();
Long max = archiveIndices.last();
if (max - min == archiveIndices.size() - 1)
return F.t(min, max); // Short path.
for (Long idx : archiveIndices.descendingSet()) {
if (!archiveIndices.contains(idx - 1))
return F.t(idx, max);
}
throw new IllegalStateException("Should never happen if TreeSet is valid.");
}
}
/**
* Creates a directory specified by the given arguments.
*
* @param cfg Configured directory path, may be {@code null}.
* @param defDir Default directory path, will be used if cfg is {@code null}.
* @param consId Local node consistent ID.
* @param msg File description to print out on successful initialization.
* @return Initialized directory.
* @throws IgniteCheckedException If failed to initialize directory.
*/
private File initDirectory(String cfg, String defDir, String consId, String msg) throws IgniteCheckedException {
File dir;
if (cfg != null) {
File workDir0 = new File(cfg);
dir = workDir0.isAbsolute() ?
new File(workDir0, consId) :
new File(U.resolveWorkDirectory(igCfg.getWorkDirectory(), cfg, false), consId);
}
else
dir = new File(U.resolveWorkDirectory(igCfg.getWorkDirectory(), defDir, false), consId);
U.ensureDirectory(dir, msg, log);
return dir;
}
/**
* @return Current log segment handle.
*/
private FileWriteHandle currentHandle() {
return currHnd;
}
/**
* @param cur Handle that failed to fit the given entry.
* @return Handle that will fit the entry.
*/
private FileWriteHandle rollOver(FileWriteHandle cur) throws StorageException, IgniteCheckedException {
FileWriteHandle hnd = currentHandle();
if (hnd != cur)
return hnd;
if (hnd.close(true)) {
FileWriteHandle next = initNextWriteHandle(cur);
next.writeHeader();
boolean swapped = CURR_HND_UPD.compareAndSet(this, hnd, next);
assert swapped : "Concurrent updates on rollover are not allowed";
if (walAutoArchiveAfterInactivity > 0)
lastRecordLoggedMs.set(0);
// Let other threads to proceed with new segment.
hnd.signalNextAvailable();
}
else
hnd.awaitNext();
return currentHandle();
}
/**
* @param lastReadPtr Last read WAL file pointer.
* @return Initialized file write handle.
* @throws IgniteCheckedException If failed to initialize WAL write handle.
*/
private FileWriteHandle restoreWriteHandle(FileWALPointer lastReadPtr) throws IgniteCheckedException {
long absIdx = lastReadPtr == null ? 0 : lastReadPtr.index();
long segNo = absIdx % dsCfg.getWalSegments();
File curFile = new File(walWorkDir, FileDescriptor.fileName(segNo));
int off = lastReadPtr == null ? 0 : lastReadPtr.fileOffset();
int len = lastReadPtr == null ? 0 : lastReadPtr.length();
try {
FileIO fileIO = ioFactory.create(curFile);
try {
int serVer = serializerVer;
// If we have existing segment, try to read version from it.
if (lastReadPtr != null) {
try {
serVer = readSerializerVersionAndCompactedFlag(fileIO).get1();
}
catch (SegmentEofException | EOFException ignore) {
serVer = serializerVer;
}
}
RecordSerializer ser = new RecordSerializerFactoryImpl(cctx).createSerializer(serVer);
if (log.isInfoEnabled())
log.info("Resuming logging to WAL segment [file=" + curFile.getAbsolutePath() +
", offset=" + off + ", ver=" + serVer + ']');
SegmentedRingByteBuffer rbuf;
if (mmap) {
try {
MappedByteBuffer buf = fileIO.map((int)maxWalSegmentSize);
rbuf = new SegmentedRingByteBuffer(buf, metrics);
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
}
else
rbuf = new SegmentedRingByteBuffer(dsCfg.getWalBufferSize(), maxWalSegmentSize, DIRECT, metrics);
if (lastReadPtr != null)
rbuf.init(lastReadPtr.fileOffset() + lastReadPtr.length());
FileWriteHandle hnd = new FileWriteHandle(
fileIO,
absIdx,
cctx.igniteInstanceName(),
off + len,
true,
ser,
rbuf);
archiver.currentWalIndex(absIdx);
return hnd;
}
catch (IgniteCheckedException | IOException e) {
fileIO.close();
throw e;
}
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to restore WAL write handle: " + curFile.getAbsolutePath(), e);
}
}
/**
* Fills the file header for a new segment. Calling this method signals we are done with the segment and it can be
* archived. If we don't have prepared file yet and achiever is busy this method blocks
*
* @param cur Current file write handle released by WAL writer
* @return Initialized file handle.
* @throws StorageException If IO exception occurred.
* @throws IgniteCheckedException If failed.
*/
private FileWriteHandle initNextWriteHandle(FileWriteHandle cur) throws StorageException, IgniteCheckedException {
try {
File nextFile = pollNextFile(cur.idx);
if (log.isDebugEnabled())
log.debug("Switching to a new WAL segment: " + nextFile.getAbsolutePath());
SegmentedRingByteBuffer rbuf = null;
FileIO fileIO = null;
FileWriteHandle hnd;
boolean interrupted = this.interrupted.get();
while (true) {
try {
fileIO = ioFactory.create(nextFile);
if (mmap) {
try {
MappedByteBuffer buf = fileIO.map((int)maxWalSegmentSize);
rbuf = new SegmentedRingByteBuffer(buf, metrics);
}
catch (IOException e) {
if (e instanceof ClosedByInterruptException)
throw e;
else
throw new IgniteCheckedException(e);
}
}
else
rbuf = cur.buf.reset();
hnd = new FileWriteHandle(
fileIO,
cur.idx + 1,
cctx.igniteInstanceName(),
0,
false,
serializer,
rbuf);
if (interrupted)
Thread.currentThread().interrupt();
break;
}
catch (ClosedByInterruptException e) {
interrupted = true;
Thread.interrupted();
if (fileIO != null) {
try {
fileIO.close();
}
catch (IOException ignored) {
// No-op.
}
fileIO = null;
}
if (rbuf != null) {
rbuf.free();
rbuf = null;
}
}
finally {
this.interrupted.set(false);
}
}
return hnd;
}
catch (IOException e) {
throw new StorageException(e);
}
}
/**
* Deletes temp files, creates and prepares new; Creates first segment if necessary
*/
private void checkOrPrepareFiles() throws IgniteCheckedException {
// Clean temp files.
{
File[] tmpFiles = walWorkDir.listFiles(WAL_SEGMENT_TEMP_FILE_FILTER);
if (!F.isEmpty(tmpFiles)) {
for (File tmp : tmpFiles) {
boolean deleted = tmp.delete();
if (!deleted)
throw new IgniteCheckedException("Failed to delete previously created temp file " +
"(make sure Ignite process has enough rights): " + tmp.getAbsolutePath());
}
}
}
File[] allFiles = walWorkDir.listFiles(WAL_SEGMENT_FILE_FILTER);
if (allFiles.length != 0 && allFiles.length > dsCfg.getWalSegments())
throw new IgniteCheckedException("Failed to initialize wal (work directory contains " +
"incorrect number of segments) [cur=" + allFiles.length + ", expected=" + dsCfg.getWalSegments() + ']');
// Allocate the first segment synchronously. All other segments will be allocated by archiver in background.
if (allFiles.length == 0) {
File first = new File(walWorkDir, FileDescriptor.fileName(0));
createFile(first);
}
else
checkFiles(0, false, null);
}
/**
* Clears the file with zeros.
*
* @param file File to format.
*/
private void formatFile(File file) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Formatting file [exists=" + file.exists() + ", file=" + file.getAbsolutePath() + ']');
try (FileIO fileIO = ioFactory.create(file, CREATE, READ, WRITE)) {
int left = dsCfg.getWalSegmentSize();
if (mode == WALMode.DEFAULT) {
while (left > 0) {
int toWrite = Math.min(FILL_BUF.length, left);
fileIO.write(FILL_BUF, 0, toWrite);
left -= toWrite;
}
fileIO.force();
}
else
fileIO.clear();
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to format WAL segment file: " + file.getAbsolutePath(), e);
}
}
/**
* Creates a file atomically with temp file.
*
* @param file File to create.
* @throws IgniteCheckedException If failed.
*/
private void createFile(File file) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Creating new file [exists=" + file.exists() + ", file=" + file.getAbsolutePath() + ']');
File tmp = new File(file.getParent(), file.getName() + ".tmp");
formatFile(tmp);
try {
Files.move(tmp.toPath(), file.toPath());
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to move temp file to a regular WAL segment file: " +
file.getAbsolutePath(), e);
}
if (log.isDebugEnabled())
log.debug("Created WAL segment [file=" + file.getAbsolutePath() + ", size=" + file.length() + ']');
}
/**
* Retrieves next available file to write WAL data, waiting if necessary for a segment to become available.
*
* @param curIdx Current absolute WAL segment index.
* @return File ready for use as new WAL segment.
* @throws IgniteCheckedException If failed.
*/
private File pollNextFile(long curIdx) throws IgniteCheckedException {
// Signal to archiver that we are done with the segment and it can be archived.
long absNextIdx = archiver.nextAbsoluteSegmentIndex(curIdx);
long segmentIdx = absNextIdx % dsCfg.getWalSegments();
return new File(walWorkDir, FileDescriptor.fileName(segmentIdx));
}
/**
* @return Sorted WAL files descriptors.
*/
public static FileDescriptor[] scan(File[] allFiles) {
if (allFiles == null)
return EMPTY_DESCRIPTORS;
FileDescriptor[] descs = new FileDescriptor[allFiles.length];
for (int i = 0; i < allFiles.length; i++) {
File f = allFiles[i];
descs[i] = new FileDescriptor(f);
}
Arrays.sort(descs);
return descs;
}
/**
* @throws StorageException If environment is no longer valid and we missed a WAL write.
*/
private void checkEnvironment() throws StorageException {
if (envFailed != null)
throw new StorageException("Failed to flush WAL buffer (environment was invalidated by a " +
"previous error)", envFailed);
}
/**
* File archiver operates on absolute segment indexes. For any given absolute segment index N we can calculate the
* work WAL segment: S(N) = N % dsCfg.walSegments. When a work segment is finished, it is given to the archiver. If
* the absolute index of last archived segment is denoted by A and the absolute index of next segment we want to
* write is denoted by W, then we can allow write to S(W) if W - A <= walSegments. <br>
*
* Monitor of current object is used for notify on: <ul> <li>exception occurred ({@link
* FileArchiver#cleanErr}!=null)</li> <li>stopping thread ({@link FileArchiver#stopped}==true)</li> <li>current file
* index changed ({@link FileArchiver#curAbsWalIdx})</li> <li>last archived file index was changed ({@link
* FileArchiver#lastAbsArchivedIdx})</li> <li>some WAL index was removed from {@link FileArchiver#locked} map</li>
* </ul>
*/
private class FileArchiver extends Thread {
/** Exception which occurred during initial creation of files or during archiving WAL segment */
private IgniteCheckedException cleanErr;
/**
* Absolute current segment index WAL Manager writes to. Guarded by <code>this</code>. Incremented during
* rollover. Also may be directly set if WAL is resuming logging after start.
*/
private long curAbsWalIdx = -1;
/** Last archived file index (absolute, 0-based). Guarded by <code>this</code>. */
private volatile long lastAbsArchivedIdx = -1;
/** current thread stopping advice */
private volatile boolean stopped;
/** */
private NavigableMap<Long, Integer> reserved = new TreeMap<>();
/**
* Maps absolute segment index to locks counter. Lock on segment protects from archiving segment and may come
* from {@link RecordsIterator} during WAL replay. Map itself is guarded by <code>this</code>.
*/
private Map<Long, Integer> locked = new HashMap<>();
/**
*
*/
private FileArchiver(long lastAbsArchivedIdx) {
super("wal-file-archiver%" + cctx.igniteInstanceName());
this.lastAbsArchivedIdx = lastAbsArchivedIdx;
}
/**
* @return Last archived segment absolute index.
*/
private long lastArchivedAbsoluteIndex() {
return lastAbsArchivedIdx;
}
/**
* @throws IgniteInterruptedCheckedException If failed to wait for thread shutdown.
*/
private void shutdown() throws IgniteInterruptedCheckedException {
synchronized (this) {
stopped = true;
notifyAll();
}
U.join(this);
}
/**
* @param curAbsWalIdx Current absolute WAL segment index.
*/
private void currentWalIndex(long curAbsWalIdx) {
synchronized (this) {
this.curAbsWalIdx = curAbsWalIdx;
notifyAll();
}
}
/**
* @param absIdx Index for reservation.
*/
private synchronized void reserve(long absIdx) {
Integer cur = reserved.get(absIdx);
if (cur == null)
reserved.put(absIdx, 1);
else
reserved.put(absIdx, cur + 1);
}
/**
* Check if WAL segment locked or reserved
*
* @param absIdx Index for check reservation.
* @return {@code True} if index is reserved.
*/
private synchronized boolean reserved(long absIdx) {
return locked.containsKey(absIdx) || reserved.floorKey(absIdx) != null;
}
/**
* @param absIdx Reserved index.
*/
private synchronized void release(long absIdx) {
Integer cur = reserved.get(absIdx);
assert cur != null && cur >= 1 : cur;
if (cur == 1)
reserved.remove(absIdx);
else
reserved.put(absIdx, cur - 1);
}
/** {@inheritDoc} */
@Override public void run() {
try {
allocateRemainingFiles();
}
catch (IgniteCheckedException e) {
synchronized (this) {
// Stop the thread and report to starter.
cleanErr = e;
notifyAll();
return;
}
}
try {
synchronized (this) {
while (curAbsWalIdx == -1 && !stopped)
wait();
if (curAbsWalIdx != 0 && lastAbsArchivedIdx == -1)
changeLastArchivedIndexAndWakeupCompressor(curAbsWalIdx - 1);
}
while (!Thread.currentThread().isInterrupted() && !stopped) {
long toArchive;
synchronized (this) {
assert lastAbsArchivedIdx <= curAbsWalIdx : "lastArchived=" + lastAbsArchivedIdx +
", current=" + curAbsWalIdx;
while (lastAbsArchivedIdx >= curAbsWalIdx - 1 && !stopped)
wait();
toArchive = lastAbsArchivedIdx + 1;
}
if (stopped)
break;
try {
final SegmentArchiveResult res = archiveSegment(toArchive);
synchronized (this) {
while (locked.containsKey(toArchive) && !stopped)
wait();
}
// Firstly, format working file
if (!stopped)
formatFile(res.getOrigWorkFile());
synchronized (this) {
// Then increase counter to allow rollover on clean working file
changeLastArchivedIndexAndWakeupCompressor(toArchive);
notifyAll();
}
if (evt.isRecordable(EventType.EVT_WAL_SEGMENT_ARCHIVED))
evt.record(new WalSegmentArchivedEvent(cctx.discovery().localNode(),
res.getAbsIdx(), res.getDstArchiveFile()));
}
catch (IgniteCheckedException e) {
synchronized (this) {
cleanErr = e;
notifyAll();
}
}
}
}
catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
}
}
/**
* @param idx Index.
*/
private void changeLastArchivedIndexAndWakeupCompressor(long idx) {
lastAbsArchivedIdx = idx;
if (compressor != null)
compressor.onNextSegmentArchived();
}
/**
* Gets the absolute index of the next WAL segment available to write. Blocks till there are available file to
* write
*
* @param curIdx Current absolute index that we want to increment.
* @return Next index (curWalSegmIdx+1) when it is ready to be written.
* @throws IgniteCheckedException If failed (if interrupted or if exception occurred in the archiver thread).
*/
private long nextAbsoluteSegmentIndex(long curIdx) throws IgniteCheckedException {
synchronized (this) {
if (cleanErr != null)
throw cleanErr;
assert curIdx == curAbsWalIdx;
curAbsWalIdx++;
// Notify archiver thread.
notifyAll();
while (curAbsWalIdx - lastAbsArchivedIdx > dsCfg.getWalSegments() && cleanErr == null) {
try {
wait();
}
catch (InterruptedException e) {
interrupted.set(true);
}
}
return curAbsWalIdx;
}
}
/**
* @param absIdx Segment absolute index.
* @return <ul><li>{@code True} if can read, no lock is held, </li><li>{@code false} if work segment, need
* release segment later, use {@link #releaseWorkSegment} for unlock</li> </ul>
*/
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
private boolean checkCanReadArchiveOrReserveWorkSegment(long absIdx) {
synchronized (this) {
if (lastAbsArchivedIdx >= absIdx) {
if (log.isDebugEnabled())
log.debug("Not needed to reserve WAL segment: absIdx=" + absIdx + ";" +
" lastAbsArchivedIdx=" + lastAbsArchivedIdx);
return true;
}
Integer cur = locked.get(absIdx);
cur = cur == null ? 1 : cur + 1;
locked.put(absIdx, cur);
if (log.isDebugEnabled())
log.debug("Reserved work segment [absIdx=" + absIdx + ", pins=" + cur + ']');
return false;
}
}
/**
* @param absIdx Segment absolute index.
*/
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
private void releaseWorkSegment(long absIdx) {
synchronized (this) {
Integer cur = locked.get(absIdx);
assert cur != null && cur > 0 : "WAL Segment with Index " + absIdx + " is not locked;" +
" lastAbsArchivedIdx = " + lastAbsArchivedIdx;
if (cur == 1) {
locked.remove(absIdx);
if (log.isDebugEnabled())
log.debug("Fully released work segment (ready to archive) [absIdx=" + absIdx + ']');
}
else {
locked.put(absIdx, cur - 1);
if (log.isDebugEnabled())
log.debug("Partially released work segment [absIdx=" + absIdx + ", pins=" + (cur - 1) + ']');
}
notifyAll();
}
}
/**
* Moves WAL segment from work folder to archive folder. Temp file is used to do movement
*
* @param absIdx Absolute index to archive.
*/
private SegmentArchiveResult archiveSegment(long absIdx) throws IgniteCheckedException {
long segIdx = absIdx % dsCfg.getWalSegments();
File origFile = new File(walWorkDir, FileDescriptor.fileName(segIdx));
String name = FileDescriptor.fileName(absIdx);
File dstTmpFile = new File(walArchiveDir, name + ".tmp");
File dstFile = new File(walArchiveDir, name);
if (log.isDebugEnabled())
log.debug("Starting to copy WAL segment [absIdx=" + absIdx + ", segIdx=" + segIdx +
", origFile=" + origFile.getAbsolutePath() + ", dstFile=" + dstFile.getAbsolutePath() + ']');
try {
Files.deleteIfExists(dstTmpFile.toPath());
Files.copy(origFile.toPath(), dstTmpFile.toPath());
Files.move(dstTmpFile.toPath(), dstFile.toPath());
if (mode == WALMode.DEFAULT) {
try (FileIO f0 = ioFactory.create(dstFile, CREATE, READ, WRITE)) {
f0.force();
}
}
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to archive WAL segment [" +
"srcFile=" + origFile.getAbsolutePath() +
", dstFile=" + dstTmpFile.getAbsolutePath() + ']', e);
}
if (log.isDebugEnabled())
log.debug("Copied file [src=" + origFile.getAbsolutePath() +
", dst=" + dstFile.getAbsolutePath() + ']');
return new SegmentArchiveResult(absIdx, origFile, dstFile);
}
/**
*
*/
private boolean checkStop() {
return stopped;
}
/**
* Background creation of all segments except first. First segment was created in main thread by {@link
* FileWriteAheadLogManager#checkOrPrepareFiles()}
*/
private void allocateRemainingFiles() throws IgniteCheckedException {
checkFiles(1, true, new IgnitePredicate<Integer>() {
@Override public boolean apply(Integer integer) {
return !checkStop();
}
});
}
}
/**
* Responsible for compressing WAL archive segments.
* Also responsible for deleting raw copies of already compressed WAL archive segments if they are not reserved.
*/
private class FileCompressor extends Thread {
/** Current thread stopping advice. */
private volatile boolean stopped;
/** Last successfully compressed segment. */
private volatile long lastCompressedIdx = -1L;
/** All segments prior to this (inclusive) can be compressed. */
private volatile long lastAllowedToCompressIdx = -1L;
/**
*
*/
FileCompressor() {
super("wal-file-compressor%" + cctx.igniteInstanceName());
}
/**
*
*/
private void init() {
File[] toDel = walArchiveDir.listFiles(WAL_SEGMENT_TEMP_FILE_COMPACTED_FILTER);
for (File f : toDel) {
if (stopped)
return;
f.delete();
}
FileDescriptor[] alreadyCompressed = scan(walArchiveDir.listFiles(WAL_SEGMENT_FILE_COMPACTED_FILTER));
if (alreadyCompressed.length > 0)
lastCompressedIdx = alreadyCompressed[alreadyCompressed.length - 1].getIdx();
}
/**
* @param lastCpStartIdx Segment index to allow compression until (exclusively).
*/
synchronized void allowCompressionUntil(long lastCpStartIdx) {
lastAllowedToCompressIdx = lastCpStartIdx - 1;
notify();
}
/**
* Callback for waking up compressor when new segment is archived.
*/
synchronized void onNextSegmentArchived() {
notify();
}
/**
* Pessimistically tries to reserve segment for compression in order to avoid concurrent truncation.
* Waits if there's no segment to archive right now.
*/
private long tryReserveNextSegmentOrWait() throws InterruptedException, IgniteCheckedException {
long segmentToCompress = lastCompressedIdx + 1;
synchronized (this) {
while (segmentToCompress > Math.min(lastAllowedToCompressIdx, archiver.lastArchivedAbsoluteIndex())) {
wait();
if (stopped)
return -1;
}
}
segmentToCompress = Math.max(segmentToCompress, lastTruncatedArchiveIdx + 1);
boolean reserved = reserve(new FileWALPointer(segmentToCompress, 0, 0));
return reserved ? segmentToCompress : -1;
}
/**
*
*/
private void deleteObsoleteRawSegments() {
FileDescriptor[] descs = scan(walArchiveDir.listFiles(WAL_SEGMENT_FILE_FILTER));
FileArchiver archiver0 = archiver;
for (FileDescriptor desc : descs) {
// Do not delete reserved or locked segment and any segment after it.
if (archiver0 != null && archiver0.reserved(desc.idx))
return;
if (desc.idx < lastCompressedIdx) {
if (!desc.file.delete())
U.warn(log, "Failed to remove obsolete WAL segment (make sure the process has enough rights): " +
desc.file.getAbsolutePath() + ", exists: " + desc.file.exists());
}
}
}
/** {@inheritDoc} */
@Override public void run() {
init();
while (!Thread.currentThread().isInterrupted() && !stopped) {
try {
deleteObsoleteRawSegments();
long nextSegment = tryReserveNextSegmentOrWait();
if (nextSegment == -1)
continue;
File tmpZip = new File(walArchiveDir, FileDescriptor.fileName(nextSegment) + ".zip" + ".tmp");
File zip = new File(walArchiveDir, FileDescriptor.fileName(nextSegment) + ".zip");
File raw = new File(walArchiveDir, FileDescriptor.fileName(nextSegment));
if (!Files.exists(raw.toPath()))
throw new IgniteCheckedException("WAL archive segment is missing: " + raw);
compressSegmentToFile(nextSegment, raw, tmpZip);
Files.move(tmpZip.toPath(), zip.toPath());
if (mode == WALMode.DEFAULT) {
try (FileIO f0 = ioFactory.create(zip, CREATE, READ, WRITE)) {
f0.force();
}
}
lastCompressedIdx = nextSegment;
}
catch (IgniteCheckedException | IOException e) {
U.error(log, "Unexpected error during WAL compression", e);
FileWriteHandle handle = currentHandle();
if (handle != null)
handle.invalidateEnvironment(e);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/**
* @param nextSegment Next segment absolute idx.
* @param raw Raw file.
* @param zip Zip file.
*/
private void compressSegmentToFile(long nextSegment, File raw, File zip)
throws IOException, IgniteCheckedException {
int segmentSerializerVer;
try (FileIO fileIO = ioFactory.create(raw)) {
IgniteBiTuple<Integer, Boolean> tup = readSerializerVersionAndCompactedFlag(fileIO);
segmentSerializerVer = tup.get1();
}
try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip)))) {
zos.putNextEntry(new ZipEntry(""));
ByteBuffer buf = ByteBuffer.allocate(RecordV1Serializer.HEADER_RECORD_SIZE);
buf.order(ByteOrder.nativeOrder());
zos.write(prepareSerializerVersionBuffer(nextSegment, segmentSerializerVer, true, buf).array());
final CIX1<WALRecord> appendToZipC = new CIX1<WALRecord>() {
@Override public void applyx(WALRecord record) throws IgniteCheckedException {
final MarshalledRecord marshRec = (MarshalledRecord)record;
try {
zos.write(marshRec.buffer().array(), 0, marshRec.buffer().remaining());
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
}
};
try (SingleSegmentLogicalRecordsIterator iter = new SingleSegmentLogicalRecordsIterator(
log, cctx, ioFactory, BUF_SIZE, nextSegment, walArchiveDir, appendToZipC)) {
while (iter.hasNextX())
iter.nextX();
}
}
finally {
release(new FileWALPointer(nextSegment, 0, 0));
}
}
/**
* @throws IgniteInterruptedCheckedException If failed to wait for thread shutdown.
*/
private void shutdown() throws IgniteInterruptedCheckedException {
synchronized (this) {
stopped = true;
notifyAll();
}
U.join(this);
}
}
/**
* Responsible for decompressing previously compressed segments of WAL archive if they are needed for replay.
*/
private class FileDecompressor extends Thread {
/** Current thread stopping advice. */
private volatile boolean stopped;
/** Decompression futures. */
private Map<Long, GridFutureAdapter<Void>> decompressionFutures = new HashMap<>();
/** Segments queue. */
private PriorityBlockingQueue<Long> segmentsQueue = new PriorityBlockingQueue<>();
/** Byte array for draining data. */
private byte[] arr = new byte[BUF_SIZE];
/**
*
*/
FileDecompressor() {
super("wal-file-decompressor%" + cctx.igniteInstanceName());
}
/** {@inheritDoc} */
@Override public void run() {
while (!Thread.currentThread().isInterrupted() && !stopped) {
try {
long segmentToDecompress = segmentsQueue.take();
if (stopped)
break;
File zip = new File(walArchiveDir, FileDescriptor.fileName(segmentToDecompress) + ".zip");
File unzipTmp = new File(walArchiveDir, FileDescriptor.fileName(segmentToDecompress) + ".tmp");
File unzip = new File(walArchiveDir, FileDescriptor.fileName(segmentToDecompress));
try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zip)));
FileIO io = ioFactory.create(unzipTmp)) {
zis.getNextEntry();
int bytesRead;
while ((bytesRead = zis.read(arr)) > 0)
io.write(arr, 0, bytesRead);
}
Files.move(unzipTmp.toPath(), unzip.toPath());
synchronized (this) {
decompressionFutures.remove(segmentToDecompress).onDone();
}
}
catch (InterruptedException e){
Thread.currentThread().interrupt();
}
catch (IOException e) {
U.error(log, "Unexpected error during WAL decompression", e);
FileWriteHandle handle = currentHandle();
if (handle != null)
handle.invalidateEnvironment(e);
}
}
}
/**
* Asynchronously decompresses WAL segment which is present only in .zip file.
*
* @return Future which is completed once file is decompressed.
*/
synchronized IgniteInternalFuture<Void> decompressFile(long idx) {
if (decompressionFutures.containsKey(idx))
return decompressionFutures.get(idx);
File f = new File(walArchiveDir, FileDescriptor.fileName(idx));
if (f.exists())
return new GridFinishedFuture<>();
segmentsQueue.put(idx);
GridFutureAdapter<Void> res = new GridFutureAdapter<>();
decompressionFutures.put(idx, res);
return res;
}
/**
* @throws IgniteInterruptedCheckedException If failed to wait for thread shutdown.
*/
private void shutdown() throws IgniteInterruptedCheckedException {
synchronized (this) {
stopped = true;
// Put fake -1 to wake thread from queue.take()
segmentsQueue.put(-1L);
}
U.join(this);
}
}
/**
* Validate files depending on {@link DataStorageConfiguration#getWalSegments()} and create if need. Check end
* when exit condition return false or all files are passed.
*
* @param startWith Start with.
* @param create Flag create file.
* @param p Predicate Exit condition.
* @throws IgniteCheckedException if validation or create file fail.
*/
private void checkFiles(int startWith, boolean create, IgnitePredicate<Integer> p) throws IgniteCheckedException {
for (int i = startWith; i < dsCfg.getWalSegments() && (p == null || p.apply(i)); i++) {
File checkFile = new File(walWorkDir, FileDescriptor.fileName(i));
if (checkFile.exists()) {
if (checkFile.isDirectory())
throw new IgniteCheckedException("Failed to initialize WAL log segment (a directory with " +
"the same name already exists): " + checkFile.getAbsolutePath());
else if (checkFile.length() != dsCfg.getWalSegmentSize() && mode == WALMode.DEFAULT)
throw new IgniteCheckedException("Failed to initialize WAL log segment " +
"(WAL segment size change is not supported):" + checkFile.getAbsolutePath());
}
else if (create)
createFile(checkFile);
}
}
/**
* Reads record serializer version from provided {@code io} along with compacted flag.
* NOTE: Method mutates position of {@code io}.
*
* @param io I/O interface for file.
* @return Serializer version stored in the file.
* @throws IgniteCheckedException If failed to read serializer version.
*/
static IgniteBiTuple<Integer, Boolean> readSerializerVersionAndCompactedFlag(FileIO io)
throws IgniteCheckedException, IOException {
try (ByteBufferExpander buf = new ByteBufferExpander(RecordV1Serializer.HEADER_RECORD_SIZE, ByteOrder.nativeOrder())) {
FileInput in = new FileInput(io, buf);
in.ensure(RecordV1Serializer.HEADER_RECORD_SIZE);
int recordType = in.readUnsignedByte();
if (recordType == WALRecord.RecordType.STOP_ITERATION_RECORD_TYPE)
throw new SegmentEofException("Reached logical end of the segment", null);
WALRecord.RecordType type = WALRecord.RecordType.fromOrdinal(recordType - 1);
if (type != WALRecord.RecordType.HEADER_RECORD)
throw new IOException("Can't read serializer version", null);
// Read file pointer.
FileWALPointer ptr = RecordV1Serializer.readPosition(in);
assert ptr.fileOffset() == 0 : "Header record should be placed at the beginning of file " + ptr;
long hdrMagicNum = in.readLong();
boolean compacted;
if (hdrMagicNum == HeaderRecord.REGULAR_MAGIC)
compacted = false;
else if (hdrMagicNum == HeaderRecord.COMPACTED_MAGIC)
compacted = true;
else {
throw new IOException("Magic is corrupted [exp=" + U.hexLong(HeaderRecord.REGULAR_MAGIC) +
", actual=" + U.hexLong(hdrMagicNum) + ']');
}
// Read serializer version.
int ver = in.readInt();
// Read and skip CRC.
in.readInt();
return new IgniteBiTuple<>(ver, compacted);
}
}
/**
* Needs only for WAL compaction.
*
* @param idx Index.
* @param ver Version.
* @param compacted Compacted flag.
*/
@NotNull private static ByteBuffer prepareSerializerVersionBuffer(long idx, int ver, boolean compacted, ByteBuffer buf) {
// Write record type.
buf.put((byte) (WALRecord.RecordType.HEADER_RECORD.ordinal() + 1));
// Write position.
RecordV1Serializer.putPosition(buf, new FileWALPointer(idx, 0, 0));
// Place magic number.
buf.putLong(compacted ? HeaderRecord.COMPACTED_MAGIC : HeaderRecord.REGULAR_MAGIC);
// Place serializer version.
buf.putInt(ver);
// Place CRC if needed.
if (!RecordV1Serializer.skipCrc) {
int curPos = buf.position();
buf.position(0);
// This call will move buffer position to the end of the record again.
int crcVal = PureJavaCrc32.calcCrc32(buf, curPos);
buf.putInt(crcVal);
}
else
buf.putInt(0);
// Write header record through io.
buf.position(0);
return buf;
}
/**
* WAL file descriptor.
*/
public static class FileDescriptor implements Comparable<FileDescriptor> {
/** */
protected final File file;
/** Absolute WAL segment file index */
protected final long idx;
/**
* Creates file descriptor. Index is restored from file name
*
* @param file WAL segment file.
*/
public FileDescriptor(@NotNull File file) {
this(file, null);
}
/**
* @param file WAL segment file.
* @param idx Absolute WAL segment file index. For null value index is restored from file name
*/
public FileDescriptor(@NotNull File file, @Nullable Long idx) {
this.file = file;
String fileName = file.getName();
assert fileName.contains(WAL_SEGMENT_FILE_EXT);
this.idx = idx == null ? Long.parseLong(fileName.substring(0, 16)) : idx;
}
/**
* @param segment Segment index.
* @return Segment file name.
*/
public static String fileName(long segment) {
SB b = new SB();
String segmentStr = Long.toString(segment);
for (int i = segmentStr.length(); i < 16; i++)
b.a('0');
b.a(segmentStr).a(WAL_SEGMENT_FILE_EXT);
return b.toString();
}
/** {@inheritDoc} */
@Override public int compareTo(@NotNull FileDescriptor o) {
return Long.compare(idx, o.idx);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof FileDescriptor))
return false;
FileDescriptor that = (FileDescriptor)o;
return idx == that.idx;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return (int)(idx ^ (idx >>> 32));
}
/**
* @return Absolute WAL segment file index
*/
public long getIdx() {
return idx;
}
/**
* @return absolute pathname string of this file descriptor pathname.
*/
public String getAbsolutePath() {
return file.getAbsolutePath();
}
}
/**
*
*/
private abstract static class FileHandle {
/** I/O interface for read/write operations with file */
FileIO fileIO;
/** Absolute WAL segment file index (incremental counter) */
protected final long idx;
/** */
protected String gridName;
/**
* @param fileIO I/O interface for read/write operations of FileHandle.
* @param idx Absolute WAL segment file index (incremental counter).
*/
private FileHandle(FileIO fileIO, long idx, String gridName) {
this.fileIO = fileIO;
this.idx = idx;
this.gridName = gridName;
}
}
/**
*
*/
public static class ReadFileHandle extends FileHandle {
/** Entry serializer. */
RecordSerializer ser;
/** */
FileInput in;
/**
* <code>true</code> if this file handle came from work directory. <code>false</code> if this file handle came
* from archive directory.
*/
private boolean workDir;
/**
* @param fileIO I/O interface for read/write operations of FileHandle.
* @param idx Absolute WAL segment file index (incremental counter).
* @param ser Entry serializer.
* @param in File input.
*/
ReadFileHandle(
FileIO fileIO,
long idx,
String gridName,
RecordSerializer ser,
FileInput in
) {
super(fileIO, idx, gridName);
this.ser = ser;
this.in = in;
}
/**
* @throws IgniteCheckedException If failed to close the WAL segment file.
*/
public void close() throws IgniteCheckedException {
try {
fileIO.close();
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
}
}
/**
* File handle for one log segment.
*/
@SuppressWarnings("SignalWithoutCorrespondingAwait")
private class FileWriteHandle extends FileHandle {
/** */
private final RecordSerializer serializer;
/** Created on resume logging. */
private volatile boolean resume;
/**
* Position in current file after the end of last written record (incremented after file channel write
* operation)
*/
volatile long written;
/** */
private volatile long lastFsyncPos;
/** Stop guard to provide warranty that only one thread will be successful in calling {@link #close(boolean)} */
private final AtomicBoolean stop = new AtomicBoolean(false);
/** */
private final Lock lock = new ReentrantLock();
/** Condition activated each time writeBuffer() completes. Used to wait previously flushed write to complete */
private final Condition writeComplete = lock.newCondition();
/** Condition for timed wait of several threads, see {@link DataStorageConfiguration#getWalFsyncDelayNanos()} */
private final Condition fsync = lock.newCondition();
/**
* Next segment available condition. Protection from "spurious wakeup" is provided by predicate {@link
* #fileIO}=<code>null</code>
*/
private final Condition nextSegment = lock.newCondition();
/** Buffer. */
private final SegmentedRingByteBuffer buf;
/**
* @param fileIO I/O file interface to use
* @param idx Absolute WAL segment file index for easy access.
* @param pos Position.
* @param resume Created on resume logging flag.
* @param serializer Serializer.
* @param buf Buffer.
* @throws IOException If failed.
*/
private FileWriteHandle(
FileIO fileIO,
long idx,
String gridName,
long pos,
boolean resume,
RecordSerializer serializer,
SegmentedRingByteBuffer buf
) throws IOException {
super(fileIO, idx, gridName);
assert serializer != null;
if (!mmap)
fileIO.position(pos);
this.serializer = serializer;
written = pos;
lastFsyncPos = pos;
this.resume = resume;
this.buf = buf;
}
/**
* Write serializer version to current handle.
*/
public void writeHeader() {
SegmentedRingByteBuffer.WriteSegment seg = buf.offer(RecordV1Serializer.HEADER_RECORD_SIZE);
assert seg != null && seg.position() > 0;
prepareSerializerVersionBuffer(idx, serializerVersion(), false, seg.buffer());
seg.release();
}
/**
* @param rec Record to be added to write queue.
* @return Pointer or null if roll over to next segment is required or already started by other thread.
* @throws StorageException If failed.
* @throws IgniteCheckedException If failed.
*/
@Nullable private WALPointer addRecord(WALRecord rec) throws StorageException, IgniteCheckedException {
assert rec.size() > 0 : rec;
for (;;) {
checkEnvironment();
SegmentedRingByteBuffer.WriteSegment seg;
// Buffer can be in open state in case of resuming with different serializer version.
if (rec.type() == SWITCH_SEGMENT_RECORD && !currHnd.resume)
seg = buf.offerSafe(rec.size());
else
seg = buf.offer(rec.size());
FileWALPointer ptr = null;
if (seg != null) {
try {
int pos = (int)(seg.position() - rec.size());
ByteBuffer buf = seg.buffer();
if (buf == null || (stop.get() && rec.type() != SWITCH_SEGMENT_RECORD))
return null; // Can not write to this segment, need to switch to the next one.
ptr = new FileWALPointer(idx, pos, rec.size());
rec.position(ptr);
fillBuffer(buf, rec);
if (mmap) {
// written field must grow only, but segment with greater position can be serialized
// earlier than segment with smaller position.
while (true) {
long written0 = written;
if (seg.position() > written0) {
if (WRITTEN_UPD.compareAndSet(this, written0, seg.position()))
break;
}
else
break;
}
}
return ptr;
}
finally {
seg.release();
if (mode == WALMode.BACKGROUND && rec instanceof CheckpointRecord)
flushOrWait(ptr);
}
}
else
walWriter.flushAll();
}
}
/**
* Flush or wait for concurrent flush completion.
*
* @param ptr Pointer.
* @throws IgniteCheckedException If failed.
*/
private void flushOrWait(FileWALPointer ptr) throws IgniteCheckedException {
if (ptr != null) {
// If requested obsolete file index, it must be already flushed by close.
if (ptr.index() != idx)
return;
}
flush(ptr);
}
/**
* @param ptr Pointer.
* @throws IgniteCheckedException If failed.
* @throws StorageException If failed.
*/
private void flush(FileWALPointer ptr) throws IgniteCheckedException, StorageException {
if (ptr == null) { // Unconditional flush.
walWriter.flushAll();
return;
}
assert ptr.index() == idx;
walWriter.flushBuffer(ptr.fileOffset());
}
/**
* @param buf Buffer.
* @param rec WAL record.
* @throws IgniteCheckedException If failed.
*/
private void fillBuffer(ByteBuffer buf, WALRecord rec) throws IgniteCheckedException {
try {
serializer.writeRecord(rec, buf);
}
catch (RuntimeException e) {
throw new IllegalStateException("Failed to write record: " + rec, e);
}
}
/**
* Non-blocking check if this pointer needs to be sync'ed.
*
* @param ptr WAL pointer to check.
* @return {@code False} if this pointer has been already sync'ed.
*/
private boolean needFsync(FileWALPointer ptr) {
// If index has changed, it means that the log was rolled over and already sync'ed.
// If requested position is smaller than last sync'ed, it also means all is good.
// If position is equal, then our record is the last not synced.
return idx == ptr.index() && lastFsyncPos <= ptr.fileOffset();
}
/**
* @return Pointer to the end of the last written record (probably not fsync-ed).
*/
private FileWALPointer position() {
lock.lock();
try {
return new FileWALPointer(idx, (int)written, 0);
}
finally {
lock.unlock();
}
}
/**
* @param ptr Pointer to sync.
* @throws StorageException If failed.
*/
private void fsync(FileWALPointer ptr) throws StorageException, IgniteCheckedException {
lock.lock();
try {
if (ptr != null) {
if (!needFsync(ptr))
return;
if (fsyncDelay > 0 && !this.stop.get()) {
// Delay fsync to collect as many updates as possible: trade latency for throughput.
U.await(fsync, fsyncDelay, TimeUnit.NANOSECONDS);
if (!needFsync(ptr))
return;
}
}
flushOrWait(ptr);
if (this.stop.get())
return;
long lastFsyncPos0 = lastFsyncPos;
long written0 = written;
if (lastFsyncPos0 != written0) {
// Fsync position must be behind.
assert lastFsyncPos0 < written0 : "lastFsyncPos=" + lastFsyncPos0 + ", written=" + written0;
boolean metricsEnabled = metrics.metricsEnabled();
long start = metricsEnabled ? System.nanoTime() : 0;
if (mmap) {
long pos = ptr == null ? -1 : ptr.fileOffset();
List<SegmentedRingByteBuffer.ReadSegment> segs = buf.poll(pos);
if (segs != null) {
assert segs.size() == 1;
SegmentedRingByteBuffer.ReadSegment seg = segs.get(0);
int off = seg.buffer().position();
int len = seg.buffer().limit() - off;
fsync((MappedByteBuffer)buf.buf, off, len);
seg.release();
}
}
else
walWriter.force();
lastFsyncPos = written;
if (fsyncDelay > 0)
fsync.signalAll();
long end = metricsEnabled ? System.nanoTime() : 0;
if (metricsEnabled)
metrics.onFsync(end - start);
}
}
finally {
lock.unlock();
}
}
/**
* @param buf Mapped byte buffer..
* @param off Offset.
* @param len Length.
*/
private void fsync(MappedByteBuffer buf, int off, int len) throws IgniteCheckedException {
try {
long mappedOff = (Long)mappingOffset.invoke(buf);
assert mappedOff == 0 : mappedOff;
long addr = (Long)mappingAddress.invoke(buf, mappedOff);
long delta = (addr + off) % PAGE_SIZE;
long alignedAddr = (addr + off) - delta;
force0.invoke(buf, fd.get(buf), alignedAddr, len + delta);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new IgniteCheckedException(e);
}
}
/**
* @return {@code true} If this thread actually closed the segment.
* @throws IgniteCheckedException If failed.
* @throws StorageException If failed.
*/
private boolean close(boolean rollOver) throws IgniteCheckedException, StorageException {
if (stop.compareAndSet(false, true)) {
try {
lock.lock();
flushOrWait(null);
try {
RecordSerializer backwardSerializer = new RecordSerializerFactoryImpl(cctx)
.createSerializer(serializerVer);
SwitchSegmentRecord segmentRecord = new SwitchSegmentRecord();
int switchSegmentRecSize = backwardSerializer.size(segmentRecord);
if (rollOver && written < (maxWalSegmentSize - switchSegmentRecSize)) {
segmentRecord.size(switchSegmentRecSize);
WALPointer segRecPtr = addRecord(segmentRecord);
if (segRecPtr != null)
fsync((FileWALPointer)segRecPtr);
}
if (mmap) {
List<SegmentedRingByteBuffer.ReadSegment> segs = buf.poll(maxWalSegmentSize);
if (segs != null) {
assert segs.size() == 1;
segs.get(0).release();
}
}
// Do the final fsync.
if (mode == WALMode.DEFAULT) {
if (mmap)
((MappedByteBuffer)buf.buf).force();
else
fileIO.force();
lastFsyncPos = written;
}
if (mmap) {
try {
fileIO.close();
}
catch (IOException e) {
// No-op.
}
}
else {
walWriter.close();
if (!rollOver)
buf.free();
}
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
if (log.isDebugEnabled())
log.debug("Closed WAL write handle [idx=" + idx + "]");
return true;
}
finally {
if (mmap)
buf.free();
lock.unlock();
}
}
else
return false;
}
/**
* Signals next segment available to wake up other worker threads waiting for WAL to write
*/
private void signalNextAvailable() {
lock.lock();
try {
assert envFailed != null || written == lastFsyncPos || mode != WALMode.DEFAULT :
"fsync [written=" + written + ", lastFsync=" + lastFsyncPos + ", idx=" + idx + ']';
fileIO = null;
nextSegment.signalAll();
}
finally {
lock.unlock();
}
}
/**
* @throws IgniteCheckedException If failed.
*/
private void awaitNext() throws IgniteCheckedException {
lock.lock();
try {
while (fileIO != null)
U.awaitQuiet(nextSegment);
}
finally {
lock.unlock();
}
}
/**
* @param e Exception to set as a cause for all further operations.
*/
private void invalidateEnvironment(Throwable e) {
lock.lock();
try {
invalidateEnvironmentLocked(e);
}
finally {
writeComplete.signalAll();
lock.unlock();
}
}
/**
* @param e Exception to set as a cause for all further operations.
*/
private void invalidateEnvironmentLocked(Throwable e) {
if (envFailed == null) {
envFailed = e;
U.error(log, "IO error encountered while running WAL flush. All further operations " +
" will be failed and local node will be stopped.", e);
new Thread() {
@Override public void run() {
IgnitionEx.stop(gridName, true, true);
}
}.start();
}
}
/**
* @return Safely reads current position of the file channel as String. Will return "null" if channel is null.
*/
private String safePosition() {
FileIO io = this.fileIO;
if (io == null)
return "null";
try {
return String.valueOf(io.position());
}
catch (IOException e) {
return "{Failed to read channel position: " + e.getMessage() + '}';
}
}
}
/**
* Iterator over WAL-log.
*/
private static class RecordsIterator extends AbstractWalRecordsIterator {
/** */
private static final long serialVersionUID = 0L;
/** */
private final File walWorkDir;
/** */
private final File walArchiveDir;
/** */
private final FileArchiver archiver;
/** */
private final FileDecompressor decompressor;
/** */
private final DataStorageConfiguration psCfg;
/** Optional start pointer. */
@Nullable
private FileWALPointer start;
/** Optional end pointer. */
@Nullable
private FileWALPointer end;
/**
* @param cctx Shared context.
* @param walWorkDir WAL work dir.
* @param walArchiveDir WAL archive dir.
* @param start Optional start pointer.
* @param end Optional end pointer.
* @param psCfg Database configuration.
* @param serializerFactory Serializer factory.
* @param archiver Archiver.
* @param decompressor Decompressor.
*@param log Logger @throws IgniteCheckedException If failed to initialize WAL segment.
*/
private RecordsIterator(
GridCacheSharedContext cctx,
File walWorkDir,
File walArchiveDir,
@Nullable FileWALPointer start,
@Nullable FileWALPointer end,
DataStorageConfiguration psCfg,
@NotNull RecordSerializerFactory serializerFactory,
FileIOFactory ioFactory,
FileArchiver archiver,
FileDecompressor decompressor,
IgniteLogger log
) throws IgniteCheckedException {
super(log,
cctx,
serializerFactory,
ioFactory,
psCfg.getWalRecordIteratorBufferSize());
this.walWorkDir = walWorkDir;
this.walArchiveDir = walArchiveDir;
this.psCfg = psCfg;
this.archiver = archiver;
this.start = start;
this.end = end;
this.decompressor = decompressor;
init();
advance();
}
/** {@inheritDoc} */
@Override protected ReadFileHandle initReadHandle(
@NotNull FileDescriptor desc,
@Nullable FileWALPointer start
) throws IgniteCheckedException, FileNotFoundException {
if (decompressor != null && !desc.file.exists()) {
FileDescriptor zipFile = new FileDescriptor(
new File(walArchiveDir, FileDescriptor.fileName(desc.getIdx()) + ".zip"));
if (!zipFile.file.exists()) {
throw new FileNotFoundException("Both compressed and raw segment files are missing in archive " +
"[segmentIdx=" + desc.idx + "]");
}
decompressor.decompressFile(desc.idx).get();
}
return super.initReadHandle(desc, start);
}
/** {@inheritDoc} */
@Override protected void onClose() throws IgniteCheckedException {
super.onClose();
curRec = null;
final ReadFileHandle handle = closeCurrentWalSegment();
if (handle != null && handle.workDir)
releaseWorkSegment(curWalSegmIdx);
curWalSegmIdx = Integer.MAX_VALUE;
}
/**
* @throws IgniteCheckedException If failed to initialize first file handle.
*/
private void init() throws IgniteCheckedException {
FileDescriptor[] descs = loadFileDescriptors(walArchiveDir);
if (start != null) {
if (!F.isEmpty(descs)) {
if (descs[0].idx > start.index())
throw new IgniteCheckedException("WAL history is too short " +
"[descs=" + Arrays.asList(descs) + ", start=" + start + ']');
for (FileDescriptor desc : descs) {
if (desc.idx == start.index()) {
curWalSegmIdx = start.index();
break;
}
}
if (curWalSegmIdx == -1) {
long lastArchived = descs[descs.length - 1].idx;
if (lastArchived > start.index())
throw new IgniteCheckedException("WAL history is corrupted (segment is missing): " + start);
// This pointer may be in work files because archiver did not
// copy the file yet, check that it is not too far forward.
curWalSegmIdx = start.index();
}
}
else {
// This means that whole checkpoint history fits in one segment in WAL work directory.
// Will start from this index right away.
curWalSegmIdx = start.index();
}
}
else
curWalSegmIdx = !F.isEmpty(descs) ? descs[0].idx : 0;
curWalSegmIdx--;
if (log.isDebugEnabled())
log.debug("Initialized WAL cursor [start=" + start + ", end=" + end + ", curWalSegmIdx=" + curWalSegmIdx + ']');
}
/** {@inheritDoc} */
@Override protected ReadFileHandle advanceSegment(
@Nullable final ReadFileHandle curWalSegment) throws IgniteCheckedException {
if (curWalSegment != null) {
curWalSegment.close();
if (curWalSegment.workDir)
releaseWorkSegment(curWalSegment.idx);
}
// We are past the end marker.
if (end != null && curWalSegmIdx + 1 > end.index())
return null; //stop iteration
curWalSegmIdx++;
FileDescriptor fd;
boolean readArchive = canReadArchiveOrReserveWork(curWalSegmIdx);
if (readArchive)
fd = new FileDescriptor(new File(walArchiveDir, FileDescriptor.fileName(curWalSegmIdx)));
else {
long workIdx = curWalSegmIdx % psCfg.getWalSegments();
fd = new FileDescriptor(
new File(walWorkDir, FileDescriptor.fileName(workIdx)),
curWalSegmIdx);
}
if (log.isDebugEnabled())
log.debug("Reading next file [absIdx=" + curWalSegmIdx + ", file=" + fd.file.getAbsolutePath() + ']');
ReadFileHandle nextHandle;
try {
nextHandle = initReadHandle(fd, start != null && curWalSegmIdx == start.index() ? start : null);
}
catch (FileNotFoundException e) {
if (readArchive)
throw new IgniteCheckedException("Missing WAL segment in the archive", e);
else
nextHandle = null;
}
if (nextHandle == null) {
if (!readArchive)
releaseWorkSegment(curWalSegmIdx);
}
else
nextHandle.workDir = !readArchive;
curRec = null;
return nextHandle;
}
/**
* @param absIdx Absolute index to check.
* @return <ul><li> {@code True} if we can safely read the archive, </li> <li>{@code false} if the segment has
* not been archived yet. In this case the corresponding work segment is reserved (will not be deleted until
* release). Use {@link #releaseWorkSegment} for unlock </li></ul>
*/
private boolean canReadArchiveOrReserveWork(long absIdx) {
return archiver != null && archiver.checkCanReadArchiveOrReserveWorkSegment(absIdx);
}
/**
* @param absIdx Absolute index to release.
*/
private void releaseWorkSegment(long absIdx) {
if (archiver != null)
archiver.releaseWorkSegment(absIdx);
}
}
/**
* Flushes current file handle for {@link WALMode#BACKGROUND} WALMode. Called periodically from scheduler.
*/
private void doFlush() {
FileWriteHandle hnd = currentHandle();
try {
hnd.flush(null);
}
catch (Exception e) {
U.warn(log, "Failed to flush WAL record queue", e);
}
}
/**
* WAL writer worker.
*/
class WALWriter extends Thread {
/** Unconditional flush. */
private static final long UNCONDITIONAL_FLUSH = -1L;
/** File close. */
private static final long FILE_CLOSE = -2L;
/** File force. */
private static final long FILE_FORCE = -3L;
/** Shutdown. */
private volatile boolean shutdown;
/** Err. */
private volatile Throwable err;
//TODO: replace with GC free data structure.
/** Parked threads. */
final Map<Thread, Long> waiters = new ConcurrentHashMap8<>();
/**
* Default constructor.
*/
WALWriter() {
super("wal-write-worker%" + cctx.igniteInstanceName());
}
/** {@inheritDoc} */
@Override public void run() {
while (!shutdown && !Thread.currentThread().isInterrupted()) {
while (waiters.isEmpty()) {
if (!shutdown)
LockSupport.park();
else {
unparkWaiters(Long.MAX_VALUE);
return;
}
}
Long pos = null;
for (Long val : waiters.values()) {
if (val > Long.MIN_VALUE)
pos = val;
}
if (pos == null)
continue;
else if (pos < UNCONDITIONAL_FLUSH) {
try {
assert pos == FILE_CLOSE || pos == FILE_FORCE : pos;
if (pos == FILE_CLOSE)
currHnd.fileIO.close();
else if (pos == FILE_FORCE)
currHnd.fileIO.force();
}
catch (IOException e) {
log.error("Exception in WAL writer thread: ", e);
err = e;
unparkWaiters(Long.MAX_VALUE);
return;
}
unparkWaiters(pos);
}
List<SegmentedRingByteBuffer.ReadSegment> segs = currentHandle().buf.poll(pos);
if (segs == null) {
unparkWaiters(pos);
continue;
}
for (int i = 0; i < segs.size(); i++) {
SegmentedRingByteBuffer.ReadSegment seg = segs.get(i);
try {
writeBuffer(seg.position(), seg.buffer());
}
catch (Throwable e) {
log.error("Exception in WAL writer thread: ", e);
err = e;
}
finally {
seg.release();
long p = pos <= UNCONDITIONAL_FLUSH || err != null ? Long.MAX_VALUE : currentHandle().written;
unparkWaiters(p);
}
}
}
unparkWaiters(Long.MAX_VALUE);
}
/**
* Shutdowns thread.
*/
public void shutdown() throws IgniteInterruptedCheckedException {
shutdown = true;
LockSupport.unpark(this);
U.join(this);
}
/**
* Unparks waiting threads.
*
* @param pos Pos.
*/
private void unparkWaiters(long pos) {
assert pos > Long.MIN_VALUE : pos;
for (Map.Entry<Thread, Long> e : waiters.entrySet()) {
Long val = e.getValue();
if (val <= pos) {
if (val != Long.MIN_VALUE)
waiters.put(e.getKey(), Long.MIN_VALUE);
LockSupport.unpark(e.getKey());
}
}
}
/**
* Forces all made changes to the file.
*/
void force() throws IgniteCheckedException {
flushBuffer(FILE_FORCE);
}
/**
* Closes file.
*/
void close() throws IgniteCheckedException {
flushBuffer(FILE_CLOSE);
}
/**
* Flushes all data from the buffer.
*/
void flushAll() throws IgniteCheckedException {
flushBuffer(UNCONDITIONAL_FLUSH);
}
/**
* @param expPos Expected position.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
void flushBuffer(long expPos) throws StorageException, IgniteCheckedException {
if (mmap)
return;
Throwable err = walWriter.err;
if (err != null)
currentHandle().invalidateEnvironment(err);
if (expPos == UNCONDITIONAL_FLUSH)
expPos = (currentHandle().buf.tail());
Thread t = Thread.currentThread();
waiters.put(t, expPos);
LockSupport.unpark(walWriter);
while (true) {
Long val = waiters.get(t);
assert val != null : "Only this thread can remove thread from waiters";
if (val == Long.MIN_VALUE) {
waiters.remove(t);
return;
}
else
LockSupport.park();
}
}
/**
* @param pos Position in file to start write from. May be checked against actual position to wait previous
* writes to complete
* @param buf Buffer to write to file
* @throws StorageException If failed.
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("TooBroadScope")
private void writeBuffer(long pos, ByteBuffer buf) throws StorageException, IgniteCheckedException {
FileWriteHandle hdl = currentHandle();
assert hdl.fileIO != null : "Writing to a closed segment.";
checkEnvironment();
long lastLogged = U.currentTimeMillis();
long logBackoff = 2_000;
// If we were too fast, need to wait previous writes to complete.
while (hdl.written != pos) {
assert hdl.written < pos : "written = " + hdl.written + ", pos = " + pos; // No one can write further than we are now.
// Permutation occurred between blocks write operations.
// Order of acquiring lock is not the same as order of write.
long now = U.currentTimeMillis();
if (now - lastLogged >= logBackoff) {
if (logBackoff < 60 * 60_000)
logBackoff *= 2;
U.warn(log, "Still waiting for a concurrent write to complete [written=" + hdl.written +
", pos=" + pos + ", lastFsyncPos=" + hdl.lastFsyncPos + ", stop=" + hdl.stop.get() +
", actualPos=" + hdl.safePosition() + ']');
lastLogged = now;
}
checkEnvironment();
}
// Do the write.
int size = buf.remaining();
assert size > 0 : size;
try {
assert hdl.written == hdl.fileIO.position();
do {
hdl.fileIO.write(buf);
}
while (buf.hasRemaining());
hdl.written += size;
metrics.onWalBytesWritten(size);
assert hdl.written == hdl.fileIO.position();
}
catch (IOException e) {
hdl.invalidateEnvironmentLocked(e);
throw new StorageException(e);
}
}
}
}
| modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/FileWriteAheadLogManager.java | /*
* 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.ignite.internal.processors.cache.persistence.wal;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.file.Files;
import java.sql.Time;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.WALMode;
import org.apache.ignite.events.EventType;
import org.apache.ignite.events.WalSegmentArchivedEvent;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.IgnitionEx;
import org.apache.ignite.internal.managers.eventstorage.GridEventStorageManager;
import org.apache.ignite.internal.pagemem.wal.IgniteWriteAheadLogManager;
import org.apache.ignite.internal.pagemem.wal.StorageException;
import org.apache.ignite.internal.pagemem.wal.WALIterator;
import org.apache.ignite.internal.pagemem.wal.WALPointer;
import org.apache.ignite.internal.pagemem.wal.record.CheckpointRecord;
import org.apache.ignite.internal.pagemem.wal.record.MarshalledRecord;
import org.apache.ignite.internal.pagemem.wal.record.SwitchSegmentRecord;
import org.apache.ignite.internal.pagemem.wal.record.WALRecord;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.GridCacheSharedManagerAdapter;
import org.apache.ignite.internal.processors.cache.persistence.DataStorageMetricsImpl;
import org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIO;
import org.apache.ignite.internal.processors.cache.persistence.file.FileIOFactory;
import org.apache.ignite.internal.processors.cache.persistence.filename.PdsFolderSettings;
import org.apache.ignite.internal.processors.cache.persistence.wal.crc.PureJavaCrc32;
import org.apache.ignite.internal.processors.cache.persistence.wal.record.HeaderRecord;
import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordSerializer;
import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordSerializerFactory;
import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordSerializerFactoryImpl;
import org.apache.ignite.internal.processors.cache.persistence.wal.serializer.RecordV1Serializer;
import org.apache.ignite.internal.processors.timeout.GridTimeoutObject;
import org.apache.ignite.internal.processors.timeout.GridTimeoutProcessor;
import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.typedef.CIX1;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.SB;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiTuple;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.lang.IgniteUuid;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jsr166.ConcurrentHashMap8;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_WAL_SERIALIZER_VERSION;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_WAL_MMAP;
import static org.apache.ignite.configuration.WALMode.LOG_ONLY;
import static org.apache.ignite.internal.pagemem.wal.record.WALRecord.RecordType.SWITCH_SEGMENT_RECORD;
import static org.apache.ignite.internal.processors.cache.persistence.wal.SegmentedRingByteBuffer.BufferMode.DIRECT;
import static org.apache.ignite.internal.util.IgniteUtils.findField;
import static org.apache.ignite.internal.util.IgniteUtils.findNonPublicMethod;
/**
* File WAL manager.
*/
public class FileWriteAheadLogManager extends GridCacheSharedManagerAdapter implements IgniteWriteAheadLogManager {
/** {@link MappedByteBuffer#force0(java.io.FileDescriptor, long, long)}. */
private static final Method force0 = findNonPublicMethod(
MappedByteBuffer.class, "force0",
java.io.FileDescriptor.class, long.class, long.class
);
/** {@link MappedByteBuffer#mappingOffset()}. */
private static final Method mappingOffset = findNonPublicMethod(MappedByteBuffer.class, "mappingOffset");
/** {@link MappedByteBuffer#mappingAddress(long)}. */
private static final Method mappingAddress = findNonPublicMethod(
MappedByteBuffer.class, "mappingAddress", long.class
);
/** {@link MappedByteBuffer#fd} */
private static final Field fd = findField(MappedByteBuffer.class, "fd");
/** Page size. */
private static final int PAGE_SIZE = GridUnsafe.pageSize();
/** */
private static final FileDescriptor[] EMPTY_DESCRIPTORS = new FileDescriptor[0];
/** WAL segment file extension. */
private static final String WAL_SEGMENT_FILE_EXT = ".wal";
/** */
private static final byte[] FILL_BUF = new byte[1024 * 1024];
/** Pattern for segment file names */
private static final Pattern WAL_NAME_PATTERN = Pattern.compile("\\d{16}\\.wal");
/** */
private static final Pattern WAL_TEMP_NAME_PATTERN = Pattern.compile("\\d{16}\\.wal\\.tmp");
/** WAL segment file filter, see {@link #WAL_NAME_PATTERN} */
public static final FileFilter WAL_SEGMENT_FILE_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && WAL_NAME_PATTERN.matcher(file.getName()).matches();
}
};
/** */
private static final FileFilter WAL_SEGMENT_TEMP_FILE_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && WAL_TEMP_NAME_PATTERN.matcher(file.getName()).matches();
}
};
/** */
private static final Pattern WAL_SEGMENT_FILE_COMPACTED_PATTERN = Pattern.compile("\\d{16}\\.wal\\.zip");
/** WAL segment file filter, see {@link #WAL_NAME_PATTERN} */
public static final FileFilter WAL_SEGMENT_COMPACTED_OR_RAW_FILE_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && (WAL_NAME_PATTERN.matcher(file.getName()).matches() ||
WAL_SEGMENT_FILE_COMPACTED_PATTERN.matcher(file.getName()).matches());
}
};
/** */
private static final Pattern WAL_SEGMENT_TEMP_FILE_COMPACTED_PATTERN = Pattern.compile("\\d{16}\\.wal\\.zip\\.tmp");
/** */
private static final FileFilter WAL_SEGMENT_FILE_COMPACTED_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && WAL_SEGMENT_FILE_COMPACTED_PATTERN.matcher(file.getName()).matches();
}
};
/** */
private static final FileFilter WAL_SEGMENT_TEMP_FILE_COMPACTED_FILTER = new FileFilter() {
@Override public boolean accept(File file) {
return !file.isDirectory() && WAL_SEGMENT_TEMP_FILE_COMPACTED_PATTERN.matcher(file.getName()).matches();
}
};
/** Latest serializer version to use. */
private static final int LATEST_SERIALIZER_VERSION = 2;
/** Buffer size. */
private static final int BUF_SIZE = 1024 * 1024;
/** Use mapped byte buffer. */
private static boolean mmap = IgniteSystemProperties.getBoolean(IGNITE_WAL_MMAP, true);
/** Interrupted flag. */
private final ThreadLocal<Boolean> interrupted = new ThreadLocal<Boolean>() {
@Override protected Boolean initialValue() {
return false;
}
};
/** */
private final boolean alwaysWriteFullPages;
/** WAL segment size in bytes */
private final long maxWalSegmentSize;
/** */
private final WALMode mode;
/** WAL flush frequency. Makes sense only for {@link WALMode#BACKGROUND} log WALMode. */
private final long flushFreq;
/** Fsync delay. */
private final long fsyncDelay;
/** */
private final DataStorageConfiguration dsCfg;
/** Events service */
private final GridEventStorageManager evt;
/** */
private IgniteConfiguration igCfg;
/** Persistence metrics tracker. */
private DataStorageMetricsImpl metrics;
/** */
private File walWorkDir;
/** WAL archive directory (including consistent ID as subfolder) */
private File walArchiveDir;
/** Serializer of latest version, used to read header record and for write records */
private RecordSerializer serializer;
/** Serializer latest version to use. */
private final int serializerVer =
IgniteSystemProperties.getInteger(IGNITE_WAL_SERIALIZER_VERSION, LATEST_SERIALIZER_VERSION);
/** Latest segment cleared by {@link #truncate(WALPointer)}. */
private volatile long lastTruncatedArchiveIdx = -1L;
/** Factory to provide I/O interfaces for read/write operations with files */
private final FileIOFactory ioFactory;
/** Updater for {@link #currHnd}, used for verify there are no concurrent update for current log segment handle */
private static final AtomicReferenceFieldUpdater<FileWriteAheadLogManager, FileWriteHandle> CURR_HND_UPD =
AtomicReferenceFieldUpdater.newUpdater(FileWriteAheadLogManager.class, FileWriteHandle.class, "currHnd");
/** */
private volatile FileArchiver archiver;
/** Compressor. */
private volatile FileCompressor compressor;
/** Decompressor. */
private volatile FileDecompressor decompressor;
/** */
private final ThreadLocal<WALPointer> lastWALPtr = new ThreadLocal<>();
/** Current log segment handle */
private volatile FileWriteHandle currHnd;
/** Environment failure. */
private volatile Throwable envFailed;
/**
* Positive (non-0) value indicates WAL can be archived even if not complete<br>
* See {@link DataStorageConfiguration#setWalAutoArchiveAfterInactivity(long)}<br>
*/
private final long walAutoArchiveAfterInactivity;
/**
* Container with last WAL record logged timestamp.<br> Zero value means there was no records logged to current
* segment, skip possible archiving for this case<br> Value is filled only for case {@link
* #walAutoArchiveAfterInactivity} > 0<br>
*/
private AtomicLong lastRecordLoggedMs = new AtomicLong();
/**
* Cancellable task for {@link WALMode#BACKGROUND}, should be cancelled at shutdown Null for non background modes
*/
@Nullable private volatile GridTimeoutProcessor.CancelableTask backgroundFlushSchedule;
/**
* Reference to the last added next archive timeout check object. Null if mode is not enabled. Should be cancelled
* at shutdown
*/
@Nullable private volatile GridTimeoutObject nextAutoArchiveTimeoutObj;
/** WAL writer worker. */
private WALWriter walWriter;
/**
* @param ctx Kernal context.
*/
public FileWriteAheadLogManager(@NotNull final GridKernalContext ctx) {
igCfg = ctx.config();
DataStorageConfiguration dsCfg = igCfg.getDataStorageConfiguration();
assert dsCfg != null;
this.dsCfg = dsCfg;
maxWalSegmentSize = dsCfg.getWalSegmentSize();
mode = dsCfg.getWalMode();
flushFreq = dsCfg.getWalFlushFrequency();
fsyncDelay = dsCfg.getWalFsyncDelayNanos();
alwaysWriteFullPages = dsCfg.isAlwaysWriteFullPages();
ioFactory = dsCfg.getFileIOFactory();
walAutoArchiveAfterInactivity = dsCfg.getWalAutoArchiveAfterInactivity();
evt = ctx.event();
}
/** {@inheritDoc} */
@Override public void start0() throws IgniteCheckedException {
if (!cctx.kernalContext().clientNode()) {
final PdsFolderSettings resolveFolders = cctx.kernalContext().pdsFolderResolver().resolveFolders();
checkWalConfiguration();
walWorkDir = initDirectory(
dsCfg.getWalPath(),
DataStorageConfiguration.DFLT_WAL_PATH,
resolveFolders.folderName(),
"write ahead log work directory"
);
walArchiveDir = initDirectory(
dsCfg.getWalArchivePath(),
DataStorageConfiguration.DFLT_WAL_ARCHIVE_PATH,
resolveFolders.folderName(),
"write ahead log archive directory"
);
serializer = new RecordSerializerFactoryImpl(cctx).createSerializer(serializerVer);
GridCacheDatabaseSharedManager dbMgr = (GridCacheDatabaseSharedManager)cctx.database();
metrics = dbMgr.persistentStoreMetricsImpl();
checkOrPrepareFiles();
IgniteBiTuple<Long, Long> tup = scanMinMaxArchiveIndices();
lastTruncatedArchiveIdx = tup == null ? -1 : tup.get1() - 1;
archiver = new FileArchiver(tup == null ? -1 : tup.get2());
if (dsCfg.isWalCompactionEnabled()) {
compressor = new FileCompressor();
decompressor = new FileDecompressor();
}
if (mode != WALMode.NONE) {
if (log.isInfoEnabled())
log.info("Started write-ahead log manager [mode=" + mode + ']');
}
else
U.quietAndWarn(log, "Started write-ahead log manager in NONE mode, persisted data may be lost in " +
"a case of unexpected node failure. Make sure to deactivate the cluster before shutdown.");
}
}
/**
* @throws IgniteCheckedException if WAL store path is configured and archive path isn't (or vice versa)
*/
private void checkWalConfiguration() throws IgniteCheckedException {
if (dsCfg.getWalPath() == null ^ dsCfg.getWalArchivePath() == null) {
throw new IgniteCheckedException(
"Properties should be either both specified or both null " +
"[walStorePath = " + dsCfg.getWalPath() +
", walArchivePath = " + dsCfg.getWalArchivePath() + "]"
);
}
}
/** {@inheritDoc} */
@Override protected void stop0(boolean cancel) {
final GridTimeoutProcessor.CancelableTask schedule = backgroundFlushSchedule;
if (schedule != null)
schedule.close();
final GridTimeoutObject timeoutObj = nextAutoArchiveTimeoutObj;
if (timeoutObj != null)
cctx.time().removeTimeoutObject(timeoutObj);
final FileWriteHandle currHnd = currentHandle();
try {
if (mode == WALMode.BACKGROUND) {
if (currHnd != null)
currHnd.flush(null);
}
if (currHnd != null)
currHnd.close(false);
if (walWriter != null)
walWriter.shutdown();
if (archiver != null)
archiver.shutdown();
if (compressor != null)
compressor.shutdown();
if (decompressor != null)
decompressor.shutdown();
}
catch (Exception e) {
U.error(log, "Failed to gracefully close WAL segment: " + this.currHnd.fileIO, e);
}
}
/** {@inheritDoc} */
@Override public void onActivate(GridKernalContext kctx) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Activated file write ahead log manager [nodeId=" + cctx.localNodeId() +
" topVer=" + cctx.discovery().topologyVersionEx() + " ]");
start0();
if (!cctx.kernalContext().clientNode()) {
assert archiver != null;
archiver.start();
if (compressor != null)
compressor.start();
if (decompressor != null)
decompressor.start();
}
}
/** {@inheritDoc} */
@Override public void onDeActivate(GridKernalContext kctx) {
if (log.isDebugEnabled())
log.debug("DeActivate file write ahead log [nodeId=" + cctx.localNodeId() +
" topVer=" + cctx.discovery().topologyVersionEx() + " ]");
stop0(true);
currHnd = null;
}
/** {@inheritDoc} */
@Override public boolean isAlwaysWriteFullPages() {
return alwaysWriteFullPages;
}
/** {@inheritDoc} */
@Override public boolean isFullSync() {
return mode == WALMode.DEFAULT;
}
/** {@inheritDoc} */
@Override public void resumeLogging(WALPointer lastPtr) throws IgniteCheckedException {
try {
assert currHnd == null;
assert lastPtr == null || lastPtr instanceof FileWALPointer;
FileWALPointer filePtr = (FileWALPointer)lastPtr;
walWriter = new WALWriter();
if (!mmap)
walWriter.start();
currHnd = restoreWriteHandle(filePtr);
// For new handle write serializer version to it.
if (filePtr == null)
currHnd.writeHeader();
if (currHnd.serializer.version() != serializer.version()) {
if (log.isInfoEnabled())
log.info("Record serializer version change detected, will start logging with a new WAL record " +
"serializer to a new WAL segment [curFile=" + currHnd + ", newVer=" + serializer.version() +
", oldVer=" + currHnd.serializer.version() + ']');
rollOver(currHnd);
}
currHnd.resume = false;
if (mode == WALMode.BACKGROUND) {
backgroundFlushSchedule = cctx.time().schedule(new Runnable() {
@Override public void run() {
doFlush();
}
}, flushFreq, flushFreq);
}
if (walAutoArchiveAfterInactivity > 0)
scheduleNextInactivityPeriodElapsedCheck();
}
catch (StorageException e) {
throw new IgniteCheckedException(e);
}
}
/**
* Schedules next check of inactivity period expired. Based on current record update timestamp. At timeout method
* does check of inactivity period and schedules new launch.
*/
private void scheduleNextInactivityPeriodElapsedCheck() {
final long lastRecMs = lastRecordLoggedMs.get();
final long nextPossibleAutoArchive = (lastRecMs <= 0 ? U.currentTimeMillis() : lastRecMs) + walAutoArchiveAfterInactivity;
if (log.isDebugEnabled())
log.debug("Schedule WAL rollover check at " + new Time(nextPossibleAutoArchive).toString());
nextAutoArchiveTimeoutObj = new GridTimeoutObject() {
private final IgniteUuid id = IgniteUuid.randomUuid();
@Override public IgniteUuid timeoutId() {
return id;
}
@Override public long endTime() {
return nextPossibleAutoArchive;
}
@Override public void onTimeout() {
if (log.isDebugEnabled())
log.debug("Checking if WAL rollover required (" + new Time(U.currentTimeMillis()).toString() + ")");
checkWalRolloverRequiredDuringInactivityPeriod();
scheduleNextInactivityPeriodElapsedCheck();
}
};
cctx.time().addTimeoutObject(nextAutoArchiveTimeoutObj);
}
/**
* @return Latest serializer version.
*/
public int serializerVersion() {
return serializerVer;
}
/**
* Checks if there was elapsed significant period of inactivity. If WAL auto-archive is enabled using
* {@link #walAutoArchiveAfterInactivity} > 0 this method will activate roll over by timeout.<br>
*/
private void checkWalRolloverRequiredDuringInactivityPeriod() {
if (walAutoArchiveAfterInactivity <= 0)
return; // feature not configured, nothing to do
final long lastRecMs = lastRecordLoggedMs.get();
if (lastRecMs == 0)
return; //no records were logged to current segment, does not consider inactivity
final long elapsedMs = U.currentTimeMillis() - lastRecMs;
if (elapsedMs <= walAutoArchiveAfterInactivity)
return; // not enough time elapsed since last write
if (!lastRecordLoggedMs.compareAndSet(lastRecMs, 0))
return; // record write occurred concurrently
final FileWriteHandle handle = currentHandle();
try {
handle.buf.close();
rollOver(handle);
}
catch (IgniteCheckedException e) {
U.error(log, "Unable to perform segment rollover: " + e.getMessage(), e);
handle.invalidateEnvironment(e);
}
}
/** {@inheritDoc} */
@SuppressWarnings("TooBroadScope")
@Override public WALPointer log(WALRecord rec) throws IgniteCheckedException, StorageException {
if (serializer == null || mode == WALMode.NONE)
return null;
FileWriteHandle currWrHandle = currentHandle();
// Logging was not resumed yet.
if (currWrHandle == null)
return null;
// Need to calculate record size first.
rec.size(serializer.size(rec));
for (; ; currWrHandle = rollOver(currWrHandle)) {
WALPointer ptr = currWrHandle.addRecord(rec);
if (ptr != null) {
metrics.onWalRecordLogged();
lastWALPtr.set(ptr);
if (walAutoArchiveAfterInactivity > 0)
lastRecordLoggedMs.set(U.currentTimeMillis());
return ptr;
}
checkEnvironment();
if (isStopping())
throw new IgniteCheckedException("Stopping.");
}
}
/** {@inheritDoc} */
@Override public void fsync(WALPointer ptr) throws IgniteCheckedException, StorageException {
if (serializer == null || mode == WALMode.NONE)
return;
FileWriteHandle cur = currentHandle();
// WAL manager was not started (client node).
if (cur == null)
return;
FileWALPointer filePtr = (FileWALPointer)(ptr == null ? lastWALPtr.get() : ptr);
if (mode == WALMode.BACKGROUND)
return;
if (mode == LOG_ONLY) {
cur.flushOrWait(filePtr);
return;
}
// No need to sync if was rolled over.
if (filePtr != null && !cur.needFsync(filePtr))
return;
cur.fsync(filePtr);
}
/** {@inheritDoc} */
@Override public WALIterator replay(WALPointer start) throws IgniteCheckedException, StorageException {
assert start == null || start instanceof FileWALPointer : "Invalid start pointer: " + start;
FileWriteHandle hnd = currentHandle();
FileWALPointer end = null;
if (hnd != null)
end = hnd.position();
return new RecordsIterator(
cctx,
walWorkDir,
walArchiveDir,
(FileWALPointer)start,
end,
dsCfg,
new RecordSerializerFactoryImpl(cctx),
ioFactory,
archiver,
decompressor,
log
);
}
/** {@inheritDoc} */
@Override public boolean reserve(WALPointer start) throws IgniteCheckedException {
assert start != null && start instanceof FileWALPointer : "Invalid start pointer: " + start;
if (mode == WALMode.NONE)
return false;
FileArchiver archiver0 = archiver;
if (archiver0 == null)
throw new IgniteCheckedException("Could not reserve WAL segment: archiver == null");
archiver0.reserve(((FileWALPointer)start).index());
if (!hasIndex(((FileWALPointer)start).index())) {
archiver0.release(((FileWALPointer)start).index());
return false;
}
return true;
}
/** {@inheritDoc} */
@Override public void release(WALPointer start) throws IgniteCheckedException {
assert start != null && start instanceof FileWALPointer : "Invalid start pointer: " + start;
if (mode == WALMode.NONE)
return;
FileArchiver archiver0 = archiver;
if (archiver0 == null)
throw new IgniteCheckedException("Could not release WAL segment: archiver == null");
archiver0.release(((FileWALPointer)start).index());
}
/**
* @param absIdx Absolulte index to check.
* @return {@code true} if has this index.
*/
private boolean hasIndex(long absIdx) {
String segmentName = FileDescriptor.fileName(absIdx);
String zipSegmentName = FileDescriptor.fileName(absIdx) + ".zip";
boolean inArchive = new File(walArchiveDir, segmentName).exists() ||
new File(walArchiveDir, zipSegmentName).exists();
if (inArchive)
return true;
if (absIdx <= lastArchivedIndex())
return false;
FileWriteHandle cur = currHnd;
return cur != null && cur.idx >= absIdx;
}
/** {@inheritDoc} */
@Override public int truncate(WALPointer ptr) {
if (ptr == null)
return 0;
assert ptr instanceof FileWALPointer : ptr;
// File pointer bound: older entries will be deleted from archive
FileWALPointer fPtr = (FileWALPointer)ptr;
FileDescriptor[] descs = scan(walArchiveDir.listFiles(WAL_SEGMENT_COMPACTED_OR_RAW_FILE_FILTER));
int deleted = 0;
FileArchiver archiver0 = archiver;
for (FileDescriptor desc : descs) {
// Do not delete reserved or locked segment and any segment after it.
if (archiver0 != null && archiver0.reserved(desc.idx))
return deleted;
// We need to leave at least one archived segment to correctly determine the archive index.
if (desc.idx + 1 < fPtr.index()) {
if (!desc.file.delete())
U.warn(log, "Failed to remove obsolete WAL segment (make sure the process has enough rights): " +
desc.file.getAbsolutePath());
else
deleted++;
// Bump up the oldest archive segment index.
if (lastTruncatedArchiveIdx < desc.idx)
lastTruncatedArchiveIdx = desc.idx;
}
}
return deleted;
}
/** {@inheritDoc} */
@Override public void allowCompressionUntil(WALPointer ptr) {
if (compressor != null)
compressor.allowCompressionUntil(((FileWALPointer)ptr).index());
}
/** {@inheritDoc} */
@Override public int walArchiveSegments() {
long lastTruncated = lastTruncatedArchiveIdx;
long lastArchived = archiver.lastArchivedAbsoluteIndex();
if (lastArchived == -1)
return 0;
int res = (int)(lastArchived - lastTruncated);
return res >= 0 ? res : 0;
}
/** {@inheritDoc} */
@Override public boolean reserved(WALPointer ptr) {
FileWALPointer fPtr = (FileWALPointer)ptr;
FileArchiver archiver0 = archiver;
return archiver0 != null && archiver0.reserved(fPtr.index());
}
/**
* Lists files in archive directory and returns the index of last archived file.
*
* @return The absolute index of last archived file.
*/
private long lastArchivedIndex() {
long lastIdx = -1;
for (File file : walArchiveDir.listFiles(WAL_SEGMENT_COMPACTED_OR_RAW_FILE_FILTER)) {
try {
long idx = Long.parseLong(file.getName().substring(0, 16));
lastIdx = Math.max(lastIdx, idx);
}
catch (NumberFormatException | IndexOutOfBoundsException ignore) {
}
}
return lastIdx;
}
/**
* Lists files in archive directory and returns the indices of least and last archived files.
* In case of holes, first segment after last "hole" is considered as minimum.
* Example: minimum(0, 1, 10, 11, 20, 21, 22) should be 20
*
* @return The absolute indices of min and max archived files.
*/
private IgniteBiTuple<Long, Long> scanMinMaxArchiveIndices() {
TreeSet<Long> archiveIndices = new TreeSet<>();
for (File file : walArchiveDir.listFiles(WAL_SEGMENT_COMPACTED_OR_RAW_FILE_FILTER)) {
try {
long idx = Long.parseLong(file.getName().substring(0, 16));
archiveIndices.add(idx);
}
catch (NumberFormatException | IndexOutOfBoundsException ignore) {
// No-op.
}
}
if (archiveIndices.isEmpty())
return null;
else {
Long min = archiveIndices.first();
Long max = archiveIndices.last();
if (max - min == archiveIndices.size() - 1)
return F.t(min, max); // Short path.
for (Long idx : archiveIndices.descendingSet()) {
if (!archiveIndices.contains(idx - 1))
return F.t(idx, max);
}
throw new IllegalStateException("Should never happen if TreeSet is valid.");
}
}
/**
* Creates a directory specified by the given arguments.
*
* @param cfg Configured directory path, may be {@code null}.
* @param defDir Default directory path, will be used if cfg is {@code null}.
* @param consId Local node consistent ID.
* @param msg File description to print out on successful initialization.
* @return Initialized directory.
* @throws IgniteCheckedException If failed to initialize directory.
*/
private File initDirectory(String cfg, String defDir, String consId, String msg) throws IgniteCheckedException {
File dir;
if (cfg != null) {
File workDir0 = new File(cfg);
dir = workDir0.isAbsolute() ?
new File(workDir0, consId) :
new File(U.resolveWorkDirectory(igCfg.getWorkDirectory(), cfg, false), consId);
}
else
dir = new File(U.resolveWorkDirectory(igCfg.getWorkDirectory(), defDir, false), consId);
U.ensureDirectory(dir, msg, log);
return dir;
}
/**
* @return Current log segment handle.
*/
private FileWriteHandle currentHandle() {
return currHnd;
}
/**
* @param cur Handle that failed to fit the given entry.
* @return Handle that will fit the entry.
*/
private FileWriteHandle rollOver(FileWriteHandle cur) throws StorageException, IgniteCheckedException {
FileWriteHandle hnd = currentHandle();
if (hnd != cur)
return hnd;
if (hnd.close(true)) {
FileWriteHandle next = initNextWriteHandle(cur);
next.writeHeader();
boolean swapped = CURR_HND_UPD.compareAndSet(this, hnd, next);
assert swapped : "Concurrent updates on rollover are not allowed";
if (walAutoArchiveAfterInactivity > 0)
lastRecordLoggedMs.set(0);
// Let other threads to proceed with new segment.
hnd.signalNextAvailable();
}
else
hnd.awaitNext();
return currentHandle();
}
/**
* @param lastReadPtr Last read WAL file pointer.
* @return Initialized file write handle.
* @throws IgniteCheckedException If failed to initialize WAL write handle.
*/
private FileWriteHandle restoreWriteHandle(FileWALPointer lastReadPtr) throws IgniteCheckedException {
long absIdx = lastReadPtr == null ? 0 : lastReadPtr.index();
long segNo = absIdx % dsCfg.getWalSegments();
File curFile = new File(walWorkDir, FileDescriptor.fileName(segNo));
int off = lastReadPtr == null ? 0 : lastReadPtr.fileOffset();
int len = lastReadPtr == null ? 0 : lastReadPtr.length();
try {
FileIO fileIO = ioFactory.create(curFile);
try {
int serVer = serializerVer;
// If we have existing segment, try to read version from it.
if (lastReadPtr != null) {
try {
serVer = readSerializerVersionAndCompactedFlag(fileIO).get1();
}
catch (SegmentEofException | EOFException ignore) {
serVer = serializerVer;
}
}
RecordSerializer ser = new RecordSerializerFactoryImpl(cctx).createSerializer(serVer);
if (log.isInfoEnabled())
log.info("Resuming logging to WAL segment [file=" + curFile.getAbsolutePath() +
", offset=" + off + ", ver=" + serVer + ']');
SegmentedRingByteBuffer rbuf;
if (mmap) {
try {
MappedByteBuffer buf = fileIO.map((int)maxWalSegmentSize);
rbuf = new SegmentedRingByteBuffer(buf, metrics);
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
}
else
rbuf = new SegmentedRingByteBuffer(dsCfg.getWalBufferSize(), maxWalSegmentSize, DIRECT, metrics);
if (lastReadPtr != null)
rbuf.init(lastReadPtr.fileOffset() + lastReadPtr.length());
FileWriteHandle hnd = new FileWriteHandle(
fileIO,
absIdx,
cctx.igniteInstanceName(),
off + len,
true,
ser,
rbuf);
archiver.currentWalIndex(absIdx);
return hnd;
}
catch (IgniteCheckedException | IOException e) {
fileIO.close();
throw e;
}
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to restore WAL write handle: " + curFile.getAbsolutePath(), e);
}
}
/**
* Fills the file header for a new segment. Calling this method signals we are done with the segment and it can be
* archived. If we don't have prepared file yet and achiever is busy this method blocks
*
* @param cur Current file write handle released by WAL writer
* @return Initialized file handle.
* @throws StorageException If IO exception occurred.
* @throws IgniteCheckedException If failed.
*/
private FileWriteHandle initNextWriteHandle(FileWriteHandle cur) throws StorageException, IgniteCheckedException {
try {
File nextFile = pollNextFile(cur.idx);
if (log.isDebugEnabled())
log.debug("Switching to a new WAL segment: " + nextFile.getAbsolutePath());
SegmentedRingByteBuffer rbuf = null;
FileIO fileIO = null;
FileWriteHandle hnd;
boolean interrupted = this.interrupted.get();
while (true) {
try {
fileIO = ioFactory.create(nextFile);
if (mmap) {
try {
MappedByteBuffer buf = fileIO.map((int)maxWalSegmentSize);
rbuf = new SegmentedRingByteBuffer(buf, metrics);
}
catch (IOException e) {
if (e instanceof ClosedByInterruptException)
throw e;
else
throw new IgniteCheckedException(e);
}
}
else
rbuf = cur.buf.reset();
hnd = new FileWriteHandle(
fileIO,
cur.idx + 1,
cctx.igniteInstanceName(),
0,
false,
serializer,
rbuf);
if (interrupted)
Thread.currentThread().interrupt();
break;
}
catch (ClosedByInterruptException e) {
interrupted = true;
Thread.interrupted();
if (fileIO != null) {
try {
fileIO.close();
}
catch (IOException ignored) {
// No-op.
}
fileIO = null;
}
if (rbuf != null) {
rbuf.free();
rbuf = null;
}
}
finally {
this.interrupted.set(false);
}
}
return hnd;
}
catch (IOException e) {
throw new StorageException(e);
}
}
/**
* Deletes temp files, creates and prepares new; Creates first segment if necessary
*/
private void checkOrPrepareFiles() throws IgniteCheckedException {
// Clean temp files.
{
File[] tmpFiles = walWorkDir.listFiles(WAL_SEGMENT_TEMP_FILE_FILTER);
if (!F.isEmpty(tmpFiles)) {
for (File tmp : tmpFiles) {
boolean deleted = tmp.delete();
if (!deleted)
throw new IgniteCheckedException("Failed to delete previously created temp file " +
"(make sure Ignite process has enough rights): " + tmp.getAbsolutePath());
}
}
}
File[] allFiles = walWorkDir.listFiles(WAL_SEGMENT_FILE_FILTER);
if (allFiles.length != 0 && allFiles.length > dsCfg.getWalSegments())
throw new IgniteCheckedException("Failed to initialize wal (work directory contains " +
"incorrect number of segments) [cur=" + allFiles.length + ", expected=" + dsCfg.getWalSegments() + ']');
// Allocate the first segment synchronously. All other segments will be allocated by archiver in background.
if (allFiles.length == 0) {
File first = new File(walWorkDir, FileDescriptor.fileName(0));
createFile(first);
}
else
checkFiles(0, false, null);
}
/**
* Clears the file with zeros.
*
* @param file File to format.
*/
private void formatFile(File file) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Formatting file [exists=" + file.exists() + ", file=" + file.getAbsolutePath() + ']');
try (FileIO fileIO = ioFactory.create(file, CREATE, READ, WRITE)) {
int left = dsCfg.getWalSegmentSize();
if (mode == WALMode.DEFAULT) {
while (left > 0) {
int toWrite = Math.min(FILL_BUF.length, left);
fileIO.write(FILL_BUF, 0, toWrite);
left -= toWrite;
}
fileIO.force();
}
else
fileIO.clear();
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to format WAL segment file: " + file.getAbsolutePath(), e);
}
}
/**
* Creates a file atomically with temp file.
*
* @param file File to create.
* @throws IgniteCheckedException If failed.
*/
private void createFile(File file) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Creating new file [exists=" + file.exists() + ", file=" + file.getAbsolutePath() + ']');
File tmp = new File(file.getParent(), file.getName() + ".tmp");
formatFile(tmp);
try {
Files.move(tmp.toPath(), file.toPath());
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to move temp file to a regular WAL segment file: " +
file.getAbsolutePath(), e);
}
if (log.isDebugEnabled())
log.debug("Created WAL segment [file=" + file.getAbsolutePath() + ", size=" + file.length() + ']');
}
/**
* Retrieves next available file to write WAL data, waiting if necessary for a segment to become available.
*
* @param curIdx Current absolute WAL segment index.
* @return File ready for use as new WAL segment.
* @throws IgniteCheckedException If failed.
*/
private File pollNextFile(long curIdx) throws IgniteCheckedException {
// Signal to archiver that we are done with the segment and it can be archived.
long absNextIdx = archiver.nextAbsoluteSegmentIndex(curIdx);
long segmentIdx = absNextIdx % dsCfg.getWalSegments();
return new File(walWorkDir, FileDescriptor.fileName(segmentIdx));
}
/**
* @return Sorted WAL files descriptors.
*/
public static FileDescriptor[] scan(File[] allFiles) {
if (allFiles == null)
return EMPTY_DESCRIPTORS;
FileDescriptor[] descs = new FileDescriptor[allFiles.length];
for (int i = 0; i < allFiles.length; i++) {
File f = allFiles[i];
descs[i] = new FileDescriptor(f);
}
Arrays.sort(descs);
return descs;
}
/**
* @throws StorageException If environment is no longer valid and we missed a WAL write.
*/
private void checkEnvironment() throws StorageException {
if (envFailed != null)
throw new StorageException("Failed to flush WAL buffer (environment was invalidated by a " +
"previous error)", envFailed);
}
/**
* File archiver operates on absolute segment indexes. For any given absolute segment index N we can calculate the
* work WAL segment: S(N) = N % dsCfg.walSegments. When a work segment is finished, it is given to the archiver. If
* the absolute index of last archived segment is denoted by A and the absolute index of next segment we want to
* write is denoted by W, then we can allow write to S(W) if W - A <= walSegments. <br>
*
* Monitor of current object is used for notify on: <ul> <li>exception occurred ({@link
* FileArchiver#cleanErr}!=null)</li> <li>stopping thread ({@link FileArchiver#stopped}==true)</li> <li>current file
* index changed ({@link FileArchiver#curAbsWalIdx})</li> <li>last archived file index was changed ({@link
* FileArchiver#lastAbsArchivedIdx})</li> <li>some WAL index was removed from {@link FileArchiver#locked} map</li>
* </ul>
*/
private class FileArchiver extends Thread {
/** Exception which occurred during initial creation of files or during archiving WAL segment */
private IgniteCheckedException cleanErr;
/**
* Absolute current segment index WAL Manager writes to. Guarded by <code>this</code>. Incremented during
* rollover. Also may be directly set if WAL is resuming logging after start.
*/
private long curAbsWalIdx = -1;
/** Last archived file index (absolute, 0-based). Guarded by <code>this</code>. */
private volatile long lastAbsArchivedIdx = -1;
/** current thread stopping advice */
private volatile boolean stopped;
/** */
private NavigableMap<Long, Integer> reserved = new TreeMap<>();
/**
* Maps absolute segment index to locks counter. Lock on segment protects from archiving segment and may come
* from {@link RecordsIterator} during WAL replay. Map itself is guarded by <code>this</code>.
*/
private Map<Long, Integer> locked = new HashMap<>();
/**
*
*/
private FileArchiver(long lastAbsArchivedIdx) {
super("wal-file-archiver%" + cctx.igniteInstanceName());
this.lastAbsArchivedIdx = lastAbsArchivedIdx;
}
/**
* @return Last archived segment absolute index.
*/
private long lastArchivedAbsoluteIndex() {
return lastAbsArchivedIdx;
}
/**
* @throws IgniteInterruptedCheckedException If failed to wait for thread shutdown.
*/
private void shutdown() throws IgniteInterruptedCheckedException {
synchronized (this) {
stopped = true;
notifyAll();
}
U.join(this);
}
/**
* @param curAbsWalIdx Current absolute WAL segment index.
*/
private void currentWalIndex(long curAbsWalIdx) {
synchronized (this) {
this.curAbsWalIdx = curAbsWalIdx;
notifyAll();
}
}
/**
* @param absIdx Index for reservation.
*/
private synchronized void reserve(long absIdx) {
Integer cur = reserved.get(absIdx);
if (cur == null)
reserved.put(absIdx, 1);
else
reserved.put(absIdx, cur + 1);
}
/**
* Check if WAL segment locked or reserved
*
* @param absIdx Index for check reservation.
* @return {@code True} if index is reserved.
*/
private synchronized boolean reserved(long absIdx) {
return locked.containsKey(absIdx) || reserved.floorKey(absIdx) != null;
}
/**
* @param absIdx Reserved index.
*/
private synchronized void release(long absIdx) {
Integer cur = reserved.get(absIdx);
assert cur != null && cur >= 1 : cur;
if (cur == 1)
reserved.remove(absIdx);
else
reserved.put(absIdx, cur - 1);
}
/** {@inheritDoc} */
@Override public void run() {
try {
allocateRemainingFiles();
}
catch (IgniteCheckedException e) {
synchronized (this) {
// Stop the thread and report to starter.
cleanErr = e;
notifyAll();
return;
}
}
try {
synchronized (this) {
while (curAbsWalIdx == -1 && !stopped)
wait();
if (curAbsWalIdx != 0 && lastAbsArchivedIdx == -1)
changeLastArchivedIndexAndWakeupCompressor(curAbsWalIdx - 1);
}
while (!Thread.currentThread().isInterrupted() && !stopped) {
long toArchive;
synchronized (this) {
assert lastAbsArchivedIdx <= curAbsWalIdx : "lastArchived=" + lastAbsArchivedIdx +
", current=" + curAbsWalIdx;
while (lastAbsArchivedIdx >= curAbsWalIdx - 1 && !stopped)
wait();
toArchive = lastAbsArchivedIdx + 1;
}
if (stopped)
break;
try {
final SegmentArchiveResult res = archiveSegment(toArchive);
synchronized (this) {
while (locked.containsKey(toArchive) && !stopped)
wait();
}
// Firstly, format working file
if (!stopped)
formatFile(res.getOrigWorkFile());
synchronized (this) {
// Then increase counter to allow rollover on clean working file
changeLastArchivedIndexAndWakeupCompressor(toArchive);
notifyAll();
}
if (evt.isRecordable(EventType.EVT_WAL_SEGMENT_ARCHIVED))
evt.record(new WalSegmentArchivedEvent(cctx.discovery().localNode(),
res.getAbsIdx(), res.getDstArchiveFile()));
}
catch (IgniteCheckedException e) {
synchronized (this) {
cleanErr = e;
notifyAll();
}
}
}
}
catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
}
}
/**
* @param idx Index.
*/
private void changeLastArchivedIndexAndWakeupCompressor(long idx) {
lastAbsArchivedIdx = idx;
if (compressor != null)
compressor.onNextSegmentArchived();
}
/**
* Gets the absolute index of the next WAL segment available to write. Blocks till there are available file to
* write
*
* @param curIdx Current absolute index that we want to increment.
* @return Next index (curWalSegmIdx+1) when it is ready to be written.
* @throws IgniteCheckedException If failed (if interrupted or if exception occurred in the archiver thread).
*/
private long nextAbsoluteSegmentIndex(long curIdx) throws IgniteCheckedException {
synchronized (this) {
if (cleanErr != null)
throw cleanErr;
assert curIdx == curAbsWalIdx;
curAbsWalIdx++;
// Notify archiver thread.
notifyAll();
while (curAbsWalIdx - lastAbsArchivedIdx > dsCfg.getWalSegments() && cleanErr == null) {
try {
wait();
}
catch (InterruptedException e) {
interrupted.set(true);
}
}
return curAbsWalIdx;
}
}
/**
* @param absIdx Segment absolute index.
* @return <ul><li>{@code True} if can read, no lock is held, </li><li>{@code false} if work segment, need
* release segment later, use {@link #releaseWorkSegment} for unlock</li> </ul>
*/
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
private boolean checkCanReadArchiveOrReserveWorkSegment(long absIdx) {
synchronized (this) {
if (lastAbsArchivedIdx >= absIdx) {
if (log.isDebugEnabled())
log.debug("Not needed to reserve WAL segment: absIdx=" + absIdx + ";" +
" lastAbsArchivedIdx=" + lastAbsArchivedIdx);
return true;
}
Integer cur = locked.get(absIdx);
cur = cur == null ? 1 : cur + 1;
locked.put(absIdx, cur);
if (log.isDebugEnabled())
log.debug("Reserved work segment [absIdx=" + absIdx + ", pins=" + cur + ']');
return false;
}
}
/**
* @param absIdx Segment absolute index.
*/
@SuppressWarnings("NonPrivateFieldAccessedInSynchronizedContext")
private void releaseWorkSegment(long absIdx) {
synchronized (this) {
Integer cur = locked.get(absIdx);
assert cur != null && cur > 0 : "WAL Segment with Index " + absIdx + " is not locked;" +
" lastAbsArchivedIdx = " + lastAbsArchivedIdx;
if (cur == 1) {
locked.remove(absIdx);
if (log.isDebugEnabled())
log.debug("Fully released work segment (ready to archive) [absIdx=" + absIdx + ']');
}
else {
locked.put(absIdx, cur - 1);
if (log.isDebugEnabled())
log.debug("Partially released work segment [absIdx=" + absIdx + ", pins=" + (cur - 1) + ']');
}
notifyAll();
}
}
/**
* Moves WAL segment from work folder to archive folder. Temp file is used to do movement
*
* @param absIdx Absolute index to archive.
*/
private SegmentArchiveResult archiveSegment(long absIdx) throws IgniteCheckedException {
long segIdx = absIdx % dsCfg.getWalSegments();
File origFile = new File(walWorkDir, FileDescriptor.fileName(segIdx));
String name = FileDescriptor.fileName(absIdx);
File dstTmpFile = new File(walArchiveDir, name + ".tmp");
File dstFile = new File(walArchiveDir, name);
if (log.isDebugEnabled())
log.debug("Starting to copy WAL segment [absIdx=" + absIdx + ", segIdx=" + segIdx +
", origFile=" + origFile.getAbsolutePath() + ", dstFile=" + dstFile.getAbsolutePath() + ']');
try {
Files.deleteIfExists(dstTmpFile.toPath());
Files.copy(origFile.toPath(), dstTmpFile.toPath());
Files.move(dstTmpFile.toPath(), dstFile.toPath());
if (mode == WALMode.DEFAULT) {
try (FileIO f0 = ioFactory.create(dstFile, CREATE, READ, WRITE)) {
f0.force();
}
}
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to archive WAL segment [" +
"srcFile=" + origFile.getAbsolutePath() +
", dstFile=" + dstTmpFile.getAbsolutePath() + ']', e);
}
if (log.isDebugEnabled())
log.debug("Copied file [src=" + origFile.getAbsolutePath() +
", dst=" + dstFile.getAbsolutePath() + ']');
return new SegmentArchiveResult(absIdx, origFile, dstFile);
}
/**
*
*/
private boolean checkStop() {
return stopped;
}
/**
* Background creation of all segments except first. First segment was created in main thread by {@link
* FileWriteAheadLogManager#checkOrPrepareFiles()}
*/
private void allocateRemainingFiles() throws IgniteCheckedException {
checkFiles(1, true, new IgnitePredicate<Integer>() {
@Override public boolean apply(Integer integer) {
return !checkStop();
}
});
}
}
/**
* Responsible for compressing WAL archive segments.
* Also responsible for deleting raw copies of already compressed WAL archive segments if they are not reserved.
*/
private class FileCompressor extends Thread {
/** Current thread stopping advice. */
private volatile boolean stopped;
/** Last successfully compressed segment. */
private volatile long lastCompressedIdx = -1L;
/** All segments prior to this (inclusive) can be compressed. */
private volatile long lastAllowedToCompressIdx = -1L;
/**
*
*/
FileCompressor() {
super("wal-file-compressor%" + cctx.igniteInstanceName());
}
/**
*
*/
private void init() {
File[] toDel = walArchiveDir.listFiles(WAL_SEGMENT_TEMP_FILE_COMPACTED_FILTER);
for (File f : toDel) {
if (stopped)
return;
f.delete();
}
FileDescriptor[] alreadyCompressed = scan(walArchiveDir.listFiles(WAL_SEGMENT_FILE_COMPACTED_FILTER));
if (alreadyCompressed.length > 0)
lastCompressedIdx = alreadyCompressed[alreadyCompressed.length - 1].getIdx();
}
/**
* @param lastCpStartIdx Segment index to allow compression until (exclusively).
*/
synchronized void allowCompressionUntil(long lastCpStartIdx) {
lastAllowedToCompressIdx = lastCpStartIdx - 1;
notify();
}
/**
* Callback for waking up compressor when new segment is archived.
*/
synchronized void onNextSegmentArchived() {
notify();
}
/**
* Pessimistically tries to reserve segment for compression in order to avoid concurrent truncation.
* Waits if there's no segment to archive right now.
*/
private long tryReserveNextSegmentOrWait() throws InterruptedException, IgniteCheckedException {
long segmentToCompress = lastCompressedIdx + 1;
synchronized (this) {
while (segmentToCompress > Math.min(lastAllowedToCompressIdx, archiver.lastArchivedAbsoluteIndex())) {
wait();
if (stopped)
return -1;
}
}
segmentToCompress = Math.max(segmentToCompress, lastTruncatedArchiveIdx + 1);
boolean reserved = reserve(new FileWALPointer(segmentToCompress, 0, 0));
return reserved ? segmentToCompress : -1;
}
/**
*
*/
private void deleteObsoleteRawSegments() {
FileDescriptor[] descs = scan(walArchiveDir.listFiles(WAL_SEGMENT_FILE_FILTER));
FileArchiver archiver0 = archiver;
for (FileDescriptor desc : descs) {
// Do not delete reserved or locked segment and any segment after it.
if (archiver0 != null && archiver0.reserved(desc.idx))
return;
if (desc.idx < lastCompressedIdx) {
if (!desc.file.delete())
U.warn(log, "Failed to remove obsolete WAL segment (make sure the process has enough rights): " +
desc.file.getAbsolutePath() + ", exists: " + desc.file.exists());
}
}
}
/** {@inheritDoc} */
@Override public void run() {
init();
while (!Thread.currentThread().isInterrupted() && !stopped) {
try {
deleteObsoleteRawSegments();
long nextSegment = tryReserveNextSegmentOrWait();
if (nextSegment == -1)
continue;
File tmpZip = new File(walArchiveDir, FileDescriptor.fileName(nextSegment) + ".zip" + ".tmp");
File zip = new File(walArchiveDir, FileDescriptor.fileName(nextSegment) + ".zip");
File raw = new File(walArchiveDir, FileDescriptor.fileName(nextSegment));
if (!Files.exists(raw.toPath()))
throw new IgniteCheckedException("WAL archive segment is missing: " + raw);
compressSegmentToFile(nextSegment, raw, tmpZip);
Files.move(tmpZip.toPath(), zip.toPath());
if (mode == WALMode.DEFAULT) {
try (FileIO f0 = ioFactory.create(zip, CREATE, READ, WRITE)) {
f0.force();
}
}
lastCompressedIdx = nextSegment;
}
catch (IgniteCheckedException | IOException e) {
U.error(log, "Unexpected error during WAL compression", e);
FileWriteHandle handle = currentHandle();
if (handle != null)
handle.invalidateEnvironment(e);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/**
* @param nextSegment Next segment absolute idx.
* @param raw Raw file.
* @param zip Zip file.
*/
private void compressSegmentToFile(long nextSegment, File raw, File zip)
throws IOException, IgniteCheckedException {
int segmentSerializerVer;
try (FileIO fileIO = ioFactory.create(raw)) {
IgniteBiTuple<Integer, Boolean> tup = readSerializerVersionAndCompactedFlag(fileIO);
segmentSerializerVer = tup.get1();
}
try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip)))) {
zos.putNextEntry(new ZipEntry(""));
ByteBuffer buf = ByteBuffer.allocate(RecordV1Serializer.HEADER_RECORD_SIZE);
buf.order(ByteOrder.nativeOrder());
zos.write(prepareSerializerVersionBuffer(nextSegment, segmentSerializerVer, true, buf).array());
final CIX1<WALRecord> appendToZipC = new CIX1<WALRecord>() {
@Override public void applyx(WALRecord record) throws IgniteCheckedException {
final MarshalledRecord marshRec = (MarshalledRecord)record;
try {
zos.write(marshRec.buffer().array(), 0, marshRec.buffer().remaining());
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
}
};
try (SingleSegmentLogicalRecordsIterator iter = new SingleSegmentLogicalRecordsIterator(
log, cctx, ioFactory, BUF_SIZE, nextSegment, walArchiveDir, appendToZipC)) {
while (iter.hasNextX())
iter.nextX();
}
}
finally {
release(new FileWALPointer(nextSegment, 0, 0));
}
}
/**
* @throws IgniteInterruptedCheckedException If failed to wait for thread shutdown.
*/
private void shutdown() throws IgniteInterruptedCheckedException {
synchronized (this) {
stopped = true;
notifyAll();
}
U.join(this);
}
}
/**
* Responsible for decompressing previously compressed segments of WAL archive if they are needed for replay.
*/
private class FileDecompressor extends Thread {
/** Current thread stopping advice. */
private volatile boolean stopped;
/** Decompression futures. */
private Map<Long, GridFutureAdapter<Void>> decompressionFutures = new HashMap<>();
/** Segments queue. */
private PriorityBlockingQueue<Long> segmentsQueue = new PriorityBlockingQueue<>();
/** Byte array for draining data. */
private byte[] arr = new byte[BUF_SIZE];
/**
*
*/
FileDecompressor() {
super("wal-file-decompressor%" + cctx.igniteInstanceName());
}
/** {@inheritDoc} */
@Override public void run() {
while (!Thread.currentThread().isInterrupted() && !stopped) {
try {
long segmentToDecompress = segmentsQueue.take();
if (stopped)
break;
File zip = new File(walArchiveDir, FileDescriptor.fileName(segmentToDecompress) + ".zip");
File unzipTmp = new File(walArchiveDir, FileDescriptor.fileName(segmentToDecompress) + ".tmp");
File unzip = new File(walArchiveDir, FileDescriptor.fileName(segmentToDecompress));
try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zip)));
FileIO io = ioFactory.create(unzipTmp)) {
zis.getNextEntry();
int bytesRead;
while ((bytesRead = zis.read(arr)) > 0)
io.write(arr, 0, bytesRead);
}
Files.move(unzipTmp.toPath(), unzip.toPath());
synchronized (this) {
decompressionFutures.remove(segmentToDecompress).onDone();
}
}
catch (InterruptedException e){
Thread.currentThread().interrupt();
}
catch (IOException e) {
U.error(log, "Unexpected error during WAL decompression", e);
FileWriteHandle handle = currentHandle();
if (handle != null)
handle.invalidateEnvironment(e);
}
}
}
/**
* Asynchronously decompresses WAL segment which is present only in .zip file.
*
* @return Future which is completed once file is decompressed.
*/
synchronized IgniteInternalFuture<Void> decompressFile(long idx) {
if (decompressionFutures.containsKey(idx))
return decompressionFutures.get(idx);
File f = new File(walArchiveDir, FileDescriptor.fileName(idx));
if (f.exists())
return new GridFinishedFuture<>();
segmentsQueue.put(idx);
GridFutureAdapter<Void> res = new GridFutureAdapter<>();
decompressionFutures.put(idx, res);
return res;
}
/**
* @throws IgniteInterruptedCheckedException If failed to wait for thread shutdown.
*/
private void shutdown() throws IgniteInterruptedCheckedException {
synchronized (this) {
stopped = true;
// Put fake -1 to wake thread from queue.take()
segmentsQueue.put(-1L);
}
U.join(this);
}
}
/**
* Validate files depending on {@link DataStorageConfiguration#getWalSegments()} and create if need. Check end
* when exit condition return false or all files are passed.
*
* @param startWith Start with.
* @param create Flag create file.
* @param p Predicate Exit condition.
* @throws IgniteCheckedException if validation or create file fail.
*/
private void checkFiles(int startWith, boolean create, IgnitePredicate<Integer> p) throws IgniteCheckedException {
for (int i = startWith; i < dsCfg.getWalSegments() && (p == null || p.apply(i)); i++) {
File checkFile = new File(walWorkDir, FileDescriptor.fileName(i));
if (checkFile.exists()) {
if (checkFile.isDirectory())
throw new IgniteCheckedException("Failed to initialize WAL log segment (a directory with " +
"the same name already exists): " + checkFile.getAbsolutePath());
else if (checkFile.length() != dsCfg.getWalSegmentSize() && mode == WALMode.DEFAULT)
throw new IgniteCheckedException("Failed to initialize WAL log segment " +
"(WAL segment size change is not supported):" + checkFile.getAbsolutePath());
}
else if (create)
createFile(checkFile);
}
}
/**
* Reads record serializer version from provided {@code io} along with compacted flag.
* NOTE: Method mutates position of {@code io}.
*
* @param io I/O interface for file.
* @return Serializer version stored in the file.
* @throws IgniteCheckedException If failed to read serializer version.
*/
static IgniteBiTuple<Integer, Boolean> readSerializerVersionAndCompactedFlag(FileIO io)
throws IgniteCheckedException, IOException {
try (ByteBufferExpander buf = new ByteBufferExpander(RecordV1Serializer.HEADER_RECORD_SIZE, ByteOrder.nativeOrder())) {
FileInput in = new FileInput(io, buf);
in.ensure(RecordV1Serializer.HEADER_RECORD_SIZE);
int recordType = in.readUnsignedByte();
if (recordType == WALRecord.RecordType.STOP_ITERATION_RECORD_TYPE)
throw new SegmentEofException("Reached logical end of the segment", null);
WALRecord.RecordType type = WALRecord.RecordType.fromOrdinal(recordType - 1);
if (type != WALRecord.RecordType.HEADER_RECORD)
throw new IOException("Can't read serializer version", null);
// Read file pointer.
FileWALPointer ptr = RecordV1Serializer.readPosition(in);
assert ptr.fileOffset() == 0 : "Header record should be placed at the beginning of file " + ptr;
long hdrMagicNum = in.readLong();
boolean compacted;
if (hdrMagicNum == HeaderRecord.REGULAR_MAGIC)
compacted = false;
else if (hdrMagicNum == HeaderRecord.COMPACTED_MAGIC)
compacted = true;
else {
throw new IOException("Magic is corrupted [exp=" + U.hexLong(HeaderRecord.REGULAR_MAGIC) +
", actual=" + U.hexLong(hdrMagicNum) + ']');
}
// Read serializer version.
int ver = in.readInt();
// Read and skip CRC.
in.readInt();
return new IgniteBiTuple<>(ver, compacted);
}
}
/**
* Needs only for WAL compaction.
*
* @param idx Index.
* @param ver Version.
* @param compacted Compacted flag.
*/
@NotNull private static ByteBuffer prepareSerializerVersionBuffer(long idx, int ver, boolean compacted, ByteBuffer buf) {
// Write record type.
buf.put((byte) (WALRecord.RecordType.HEADER_RECORD.ordinal() + 1));
// Write position.
RecordV1Serializer.putPosition(buf, new FileWALPointer(idx, 0, 0));
// Place magic number.
buf.putLong(compacted ? HeaderRecord.COMPACTED_MAGIC : HeaderRecord.REGULAR_MAGIC);
// Place serializer version.
buf.putInt(ver);
// Place CRC if needed.
if (!RecordV1Serializer.skipCrc) {
int curPos = buf.position();
buf.position(0);
// This call will move buffer position to the end of the record again.
int crcVal = PureJavaCrc32.calcCrc32(buf, curPos);
buf.putInt(crcVal);
}
else
buf.putInt(0);
// Write header record through io.
buf.position(0);
return buf;
}
/**
* WAL file descriptor.
*/
public static class FileDescriptor implements Comparable<FileDescriptor> {
/** */
protected final File file;
/** Absolute WAL segment file index */
protected final long idx;
/**
* Creates file descriptor. Index is restored from file name
*
* @param file WAL segment file.
*/
public FileDescriptor(@NotNull File file) {
this(file, null);
}
/**
* @param file WAL segment file.
* @param idx Absolute WAL segment file index. For null value index is restored from file name
*/
public FileDescriptor(@NotNull File file, @Nullable Long idx) {
this.file = file;
String fileName = file.getName();
assert fileName.contains(WAL_SEGMENT_FILE_EXT);
this.idx = idx == null ? Long.parseLong(fileName.substring(0, 16)) : idx;
}
/**
* @param segment Segment index.
* @return Segment file name.
*/
public static String fileName(long segment) {
SB b = new SB();
String segmentStr = Long.toString(segment);
for (int i = segmentStr.length(); i < 16; i++)
b.a('0');
b.a(segmentStr).a(WAL_SEGMENT_FILE_EXT);
return b.toString();
}
/** {@inheritDoc} */
@Override public int compareTo(@NotNull FileDescriptor o) {
return Long.compare(idx, o.idx);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof FileDescriptor))
return false;
FileDescriptor that = (FileDescriptor)o;
return idx == that.idx;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return (int)(idx ^ (idx >>> 32));
}
/**
* @return Absolute WAL segment file index
*/
public long getIdx() {
return idx;
}
/**
* @return absolute pathname string of this file descriptor pathname.
*/
public String getAbsolutePath() {
return file.getAbsolutePath();
}
}
/**
*
*/
private abstract static class FileHandle {
/** I/O interface for read/write operations with file */
FileIO fileIO;
/** Absolute WAL segment file index (incremental counter) */
protected final long idx;
/** */
protected String gridName;
/**
* @param fileIO I/O interface for read/write operations of FileHandle.
* @param idx Absolute WAL segment file index (incremental counter).
*/
private FileHandle(FileIO fileIO, long idx, String gridName) {
this.fileIO = fileIO;
this.idx = idx;
this.gridName = gridName;
}
}
/**
*
*/
public static class ReadFileHandle extends FileHandle {
/** Entry serializer. */
RecordSerializer ser;
/** */
FileInput in;
/**
* <code>true</code> if this file handle came from work directory. <code>false</code> if this file handle came
* from archive directory.
*/
private boolean workDir;
/**
* @param fileIO I/O interface for read/write operations of FileHandle.
* @param idx Absolute WAL segment file index (incremental counter).
* @param ser Entry serializer.
* @param in File input.
*/
ReadFileHandle(
FileIO fileIO,
long idx,
String gridName,
RecordSerializer ser,
FileInput in
) {
super(fileIO, idx, gridName);
this.ser = ser;
this.in = in;
}
/**
* @throws IgniteCheckedException If failed to close the WAL segment file.
*/
public void close() throws IgniteCheckedException {
try {
fileIO.close();
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
}
}
/**
* File handle for one log segment.
*/
@SuppressWarnings("SignalWithoutCorrespondingAwait")
private class FileWriteHandle extends FileHandle {
/** */
private final RecordSerializer serializer;
/** Created on resume logging. */
private volatile boolean resume;
/**
* Position in current file after the end of last written record (incremented after file channel write
* operation)
*/
private volatile long written;
/** */
private volatile long lastFsyncPos;
/** Stop guard to provide warranty that only one thread will be successful in calling {@link #close(boolean)} */
private final AtomicBoolean stop = new AtomicBoolean(false);
/** */
private final Lock lock = new ReentrantLock();
/** Condition activated each time writeBuffer() completes. Used to wait previously flushed write to complete */
private final Condition writeComplete = lock.newCondition();
/** Condition for timed wait of several threads, see {@link DataStorageConfiguration#getWalFsyncDelayNanos()} */
private final Condition fsync = lock.newCondition();
/**
* Next segment available condition. Protection from "spurious wakeup" is provided by predicate {@link
* #fileIO}=<code>null</code>
*/
private final Condition nextSegment = lock.newCondition();
/** Buffer. */
private final SegmentedRingByteBuffer buf;
/**
* @param fileIO I/O file interface to use
* @param idx Absolute WAL segment file index for easy access.
* @param pos Position.
* @param resume Created on resume logging flag.
* @param serializer Serializer.
* @param buf Buffer.
* @throws IOException If failed.
*/
private FileWriteHandle(
FileIO fileIO,
long idx,
String gridName,
long pos,
boolean resume,
RecordSerializer serializer,
SegmentedRingByteBuffer buf
) throws IOException {
super(fileIO, idx, gridName);
assert serializer != null;
if (!mmap)
fileIO.position(pos);
this.serializer = serializer;
written = pos;
lastFsyncPos = pos;
this.resume = resume;
this.buf = buf;
}
/**
* Write serializer version to current handle.
*/
public void writeHeader() {
SegmentedRingByteBuffer.WriteSegment seg = buf.offer(RecordV1Serializer.HEADER_RECORD_SIZE);
assert seg != null && seg.position() > 0;
prepareSerializerVersionBuffer(idx, serializerVersion(), false, seg.buffer());
seg.release();
}
/**
* @param rec Record to be added to write queue.
* @return Pointer or null if roll over to next segment is required or already started by other thread.
* @throws StorageException If failed.
* @throws IgniteCheckedException If failed.
*/
@Nullable private WALPointer addRecord(WALRecord rec) throws StorageException, IgniteCheckedException {
assert rec.size() > 0 : rec;
for (;;) {
checkEnvironment();
SegmentedRingByteBuffer.WriteSegment seg;
// Buffer can be in open state in case of resuming with different serializer version.
if (rec.type() == SWITCH_SEGMENT_RECORD && !currHnd.resume)
seg = buf.offerSafe(rec.size());
else
seg = buf.offer(rec.size());
FileWALPointer ptr = null;
if (seg != null) {
try {
int pos = (int)(seg.position() - rec.size());
ByteBuffer buf = seg.buffer();
if (buf == null || (stop.get() && rec.type() != SWITCH_SEGMENT_RECORD))
return null; // Can not write to this segment, need to switch to the next one.
ptr = new FileWALPointer(idx, pos, rec.size());
rec.position(ptr);
fillBuffer(buf, rec);
if (mmap)
written = seg.position();
return ptr;
}
finally {
seg.release();
if (mode == WALMode.BACKGROUND && rec instanceof CheckpointRecord)
flushOrWait(ptr);
}
}
else
walWriter.flushAll();
}
}
/**
* Flush or wait for concurrent flush completion.
*
* @param ptr Pointer.
* @throws IgniteCheckedException If failed.
*/
private void flushOrWait(FileWALPointer ptr) throws IgniteCheckedException {
if (ptr != null) {
// If requested obsolete file index, it must be already flushed by close.
if (ptr.index() != idx)
return;
}
flush(ptr);
}
/**
* @param ptr Pointer.
* @throws IgniteCheckedException If failed.
* @throws StorageException If failed.
*/
private void flush(FileWALPointer ptr) throws IgniteCheckedException, StorageException {
if (ptr == null) { // Unconditional flush.
walWriter.flushAll();
return;
}
assert ptr.index() == idx;
walWriter.flushBuffer(ptr.fileOffset());
}
/**
* @param buf Buffer.
* @param rec WAL record.
* @throws IgniteCheckedException If failed.
*/
private void fillBuffer(ByteBuffer buf, WALRecord rec) throws IgniteCheckedException {
try {
serializer.writeRecord(rec, buf);
}
catch (RuntimeException e) {
throw new IllegalStateException("Failed to write record: " + rec, e);
}
}
/**
* Non-blocking check if this pointer needs to be sync'ed.
*
* @param ptr WAL pointer to check.
* @return {@code False} if this pointer has been already sync'ed.
*/
private boolean needFsync(FileWALPointer ptr) {
// If index has changed, it means that the log was rolled over and already sync'ed.
// If requested position is smaller than last sync'ed, it also means all is good.
// If position is equal, then our record is the last not synced.
return idx == ptr.index() && lastFsyncPos <= ptr.fileOffset();
}
/**
* @return Pointer to the end of the last written record (probably not fsync-ed).
*/
private FileWALPointer position() {
lock.lock();
try {
return new FileWALPointer(idx, (int)written, 0);
}
finally {
lock.unlock();
}
}
/**
* @param ptr Pointer to sync.
* @throws StorageException If failed.
*/
private void fsync(FileWALPointer ptr) throws StorageException, IgniteCheckedException {
lock.lock();
try {
if (ptr != null) {
if (!needFsync(ptr))
return;
if (fsyncDelay > 0 && !this.stop.get()) {
// Delay fsync to collect as many updates as possible: trade latency for throughput.
U.await(fsync, fsyncDelay, TimeUnit.NANOSECONDS);
if (!needFsync(ptr))
return;
}
}
flushOrWait(ptr);
if (this.stop.get())
return;
if (lastFsyncPos != written) {
assert lastFsyncPos < written; // Fsync position must be behind.
boolean metricsEnabled = metrics.metricsEnabled();
long start = metricsEnabled ? System.nanoTime() : 0;
if (mmap) {
long pos = ptr == null ? -1 : ptr.fileOffset();
List<SegmentedRingByteBuffer.ReadSegment> segs = buf.poll(pos);
if (segs != null) {
assert segs.size() == 1;
SegmentedRingByteBuffer.ReadSegment seg = segs.get(0);
int off = seg.buffer().position();
int len = seg.buffer().limit() - off;
fsync((MappedByteBuffer)buf.buf, off, len);
seg.release();
}
}
else
walWriter.force();
lastFsyncPos = written;
if (fsyncDelay > 0)
fsync.signalAll();
long end = metricsEnabled ? System.nanoTime() : 0;
if (metricsEnabled)
metrics.onFsync(end - start);
}
}
finally {
lock.unlock();
}
}
/**
* @param buf Mapped byte buffer..
* @param off Offset.
* @param len Length.
*/
private void fsync(MappedByteBuffer buf, int off, int len) throws IgniteCheckedException {
try {
long mappedOff = (Long)mappingOffset.invoke(buf);
assert mappedOff == 0 : mappedOff;
long addr = (Long)mappingAddress.invoke(buf, mappedOff);
long delta = (addr + off) % PAGE_SIZE;
long alignedAddr = (addr + off) - delta;
force0.invoke(buf, fd.get(buf), alignedAddr, len + delta);
}
catch (IllegalAccessException | InvocationTargetException e) {
throw new IgniteCheckedException(e);
}
}
/**
* @return {@code true} If this thread actually closed the segment.
* @throws IgniteCheckedException If failed.
* @throws StorageException If failed.
*/
private boolean close(boolean rollOver) throws IgniteCheckedException, StorageException {
if (stop.compareAndSet(false, true)) {
try {
lock.lock();
flushOrWait(null);
try {
RecordSerializer backwardSerializer = new RecordSerializerFactoryImpl(cctx)
.createSerializer(serializerVer);
SwitchSegmentRecord segmentRecord = new SwitchSegmentRecord();
int switchSegmentRecSize = backwardSerializer.size(segmentRecord);
if (rollOver && written < (maxWalSegmentSize - switchSegmentRecSize)) {
segmentRecord.size(switchSegmentRecSize);
WALPointer segRecPtr = addRecord(segmentRecord);
if (segRecPtr != null)
fsync((FileWALPointer)segRecPtr);
}
if (mmap) {
List<SegmentedRingByteBuffer.ReadSegment> segs = buf.poll(maxWalSegmentSize);
if (segs != null) {
assert segs.size() == 1;
segs.get(0).release();
}
}
// Do the final fsync.
if (mode == WALMode.DEFAULT) {
if (mmap)
((MappedByteBuffer)buf.buf).force();
else
fileIO.force();
lastFsyncPos = written;
}
if (mmap) {
try {
fileIO.close();
}
catch (IOException e) {
// No-op.
}
}
else {
walWriter.close();
if (!rollOver)
buf.free();
}
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
if (log.isDebugEnabled())
log.debug("Closed WAL write handle [idx=" + idx + "]");
return true;
}
finally {
if (mmap)
buf.free();
lock.unlock();
}
}
else
return false;
}
/**
* Signals next segment available to wake up other worker threads waiting for WAL to write
*/
private void signalNextAvailable() {
lock.lock();
try {
assert envFailed != null || written == lastFsyncPos || mode != WALMode.DEFAULT :
"fsync [written=" + written + ", lastFsync=" + lastFsyncPos + ", idx=" + idx + ']';
fileIO = null;
nextSegment.signalAll();
}
finally {
lock.unlock();
}
}
/**
* @throws IgniteCheckedException If failed.
*/
private void awaitNext() throws IgniteCheckedException {
lock.lock();
try {
while (fileIO != null)
U.awaitQuiet(nextSegment);
}
finally {
lock.unlock();
}
}
/**
* @param e Exception to set as a cause for all further operations.
*/
private void invalidateEnvironment(Throwable e) {
lock.lock();
try {
invalidateEnvironmentLocked(e);
}
finally {
writeComplete.signalAll();
lock.unlock();
}
}
/**
* @param e Exception to set as a cause for all further operations.
*/
private void invalidateEnvironmentLocked(Throwable e) {
if (envFailed == null) {
envFailed = e;
U.error(log, "IO error encountered while running WAL flush. All further operations " +
" will be failed and local node will be stopped.", e);
new Thread() {
@Override public void run() {
IgnitionEx.stop(gridName, true, true);
}
}.start();
}
}
/**
* @return Safely reads current position of the file channel as String. Will return "null" if channel is null.
*/
private String safePosition() {
FileIO io = this.fileIO;
if (io == null)
return "null";
try {
return String.valueOf(io.position());
}
catch (IOException e) {
return "{Failed to read channel position: " + e.getMessage() + '}';
}
}
}
/**
* Iterator over WAL-log.
*/
private static class RecordsIterator extends AbstractWalRecordsIterator {
/** */
private static final long serialVersionUID = 0L;
/** */
private final File walWorkDir;
/** */
private final File walArchiveDir;
/** */
private final FileArchiver archiver;
/** */
private final FileDecompressor decompressor;
/** */
private final DataStorageConfiguration psCfg;
/** Optional start pointer. */
@Nullable
private FileWALPointer start;
/** Optional end pointer. */
@Nullable
private FileWALPointer end;
/**
* @param cctx Shared context.
* @param walWorkDir WAL work dir.
* @param walArchiveDir WAL archive dir.
* @param start Optional start pointer.
* @param end Optional end pointer.
* @param psCfg Database configuration.
* @param serializerFactory Serializer factory.
* @param archiver Archiver.
* @param decompressor Decompressor.
*@param log Logger @throws IgniteCheckedException If failed to initialize WAL segment.
*/
private RecordsIterator(
GridCacheSharedContext cctx,
File walWorkDir,
File walArchiveDir,
@Nullable FileWALPointer start,
@Nullable FileWALPointer end,
DataStorageConfiguration psCfg,
@NotNull RecordSerializerFactory serializerFactory,
FileIOFactory ioFactory,
FileArchiver archiver,
FileDecompressor decompressor,
IgniteLogger log
) throws IgniteCheckedException {
super(log,
cctx,
serializerFactory,
ioFactory,
psCfg.getWalRecordIteratorBufferSize());
this.walWorkDir = walWorkDir;
this.walArchiveDir = walArchiveDir;
this.psCfg = psCfg;
this.archiver = archiver;
this.start = start;
this.end = end;
this.decompressor = decompressor;
init();
advance();
}
/** {@inheritDoc} */
@Override protected ReadFileHandle initReadHandle(
@NotNull FileDescriptor desc,
@Nullable FileWALPointer start
) throws IgniteCheckedException, FileNotFoundException {
if (decompressor != null && !desc.file.exists()) {
FileDescriptor zipFile = new FileDescriptor(
new File(walArchiveDir, FileDescriptor.fileName(desc.getIdx()) + ".zip"));
if (!zipFile.file.exists()) {
throw new FileNotFoundException("Both compressed and raw segment files are missing in archive " +
"[segmentIdx=" + desc.idx + "]");
}
decompressor.decompressFile(desc.idx).get();
}
return super.initReadHandle(desc, start);
}
/** {@inheritDoc} */
@Override protected void onClose() throws IgniteCheckedException {
super.onClose();
curRec = null;
final ReadFileHandle handle = closeCurrentWalSegment();
if (handle != null && handle.workDir)
releaseWorkSegment(curWalSegmIdx);
curWalSegmIdx = Integer.MAX_VALUE;
}
/**
* @throws IgniteCheckedException If failed to initialize first file handle.
*/
private void init() throws IgniteCheckedException {
FileDescriptor[] descs = loadFileDescriptors(walArchiveDir);
if (start != null) {
if (!F.isEmpty(descs)) {
if (descs[0].idx > start.index())
throw new IgniteCheckedException("WAL history is too short " +
"[descs=" + Arrays.asList(descs) + ", start=" + start + ']');
for (FileDescriptor desc : descs) {
if (desc.idx == start.index()) {
curWalSegmIdx = start.index();
break;
}
}
if (curWalSegmIdx == -1) {
long lastArchived = descs[descs.length - 1].idx;
if (lastArchived > start.index())
throw new IgniteCheckedException("WAL history is corrupted (segment is missing): " + start);
// This pointer may be in work files because archiver did not
// copy the file yet, check that it is not too far forward.
curWalSegmIdx = start.index();
}
}
else {
// This means that whole checkpoint history fits in one segment in WAL work directory.
// Will start from this index right away.
curWalSegmIdx = start.index();
}
}
else
curWalSegmIdx = !F.isEmpty(descs) ? descs[0].idx : 0;
curWalSegmIdx--;
if (log.isDebugEnabled())
log.debug("Initialized WAL cursor [start=" + start + ", end=" + end + ", curWalSegmIdx=" + curWalSegmIdx + ']');
}
/** {@inheritDoc} */
@Override protected ReadFileHandle advanceSegment(
@Nullable final ReadFileHandle curWalSegment) throws IgniteCheckedException {
if (curWalSegment != null) {
curWalSegment.close();
if (curWalSegment.workDir)
releaseWorkSegment(curWalSegment.idx);
}
// We are past the end marker.
if (end != null && curWalSegmIdx + 1 > end.index())
return null; //stop iteration
curWalSegmIdx++;
FileDescriptor fd;
boolean readArchive = canReadArchiveOrReserveWork(curWalSegmIdx);
if (readArchive)
fd = new FileDescriptor(new File(walArchiveDir, FileDescriptor.fileName(curWalSegmIdx)));
else {
long workIdx = curWalSegmIdx % psCfg.getWalSegments();
fd = new FileDescriptor(
new File(walWorkDir, FileDescriptor.fileName(workIdx)),
curWalSegmIdx);
}
if (log.isDebugEnabled())
log.debug("Reading next file [absIdx=" + curWalSegmIdx + ", file=" + fd.file.getAbsolutePath() + ']');
ReadFileHandle nextHandle;
try {
nextHandle = initReadHandle(fd, start != null && curWalSegmIdx == start.index() ? start : null);
}
catch (FileNotFoundException e) {
if (readArchive)
throw new IgniteCheckedException("Missing WAL segment in the archive", e);
else
nextHandle = null;
}
if (nextHandle == null) {
if (!readArchive)
releaseWorkSegment(curWalSegmIdx);
}
else
nextHandle.workDir = !readArchive;
curRec = null;
return nextHandle;
}
/**
* @param absIdx Absolute index to check.
* @return <ul><li> {@code True} if we can safely read the archive, </li> <li>{@code false} if the segment has
* not been archived yet. In this case the corresponding work segment is reserved (will not be deleted until
* release). Use {@link #releaseWorkSegment} for unlock </li></ul>
*/
private boolean canReadArchiveOrReserveWork(long absIdx) {
return archiver != null && archiver.checkCanReadArchiveOrReserveWorkSegment(absIdx);
}
/**
* @param absIdx Absolute index to release.
*/
private void releaseWorkSegment(long absIdx) {
if (archiver != null)
archiver.releaseWorkSegment(absIdx);
}
}
/**
* Flushes current file handle for {@link WALMode#BACKGROUND} WALMode. Called periodically from scheduler.
*/
private void doFlush() {
FileWriteHandle hnd = currentHandle();
try {
hnd.flush(null);
}
catch (Exception e) {
U.warn(log, "Failed to flush WAL record queue", e);
}
}
/**
* WAL writer worker.
*/
class WALWriter extends Thread {
/** Unconditional flush. */
private static final long UNCONDITIONAL_FLUSH = -1L;
/** File close. */
private static final long FILE_CLOSE = -2L;
/** File force. */
private static final long FILE_FORCE = -3L;
/** Shutdown. */
private volatile boolean shutdown;
/** Err. */
private volatile Throwable err;
//TODO: replace with GC free data structure.
/** Parked threads. */
final Map<Thread, Long> waiters = new ConcurrentHashMap8<>();
/**
* Default constructor.
*/
WALWriter() {
super("wal-write-worker%" + cctx.igniteInstanceName());
}
/** {@inheritDoc} */
@Override public void run() {
while (!shutdown && !Thread.currentThread().isInterrupted()) {
while (waiters.isEmpty()) {
if (!shutdown)
LockSupport.park();
else {
unparkWaiters(Long.MAX_VALUE);
return;
}
}
Long pos = null;
for (Long val : waiters.values()) {
if (val > Long.MIN_VALUE)
pos = val;
}
if (pos == null)
continue;
else if (pos < UNCONDITIONAL_FLUSH) {
try {
assert pos == FILE_CLOSE || pos == FILE_FORCE : pos;
if (pos == FILE_CLOSE)
currHnd.fileIO.close();
else if (pos == FILE_FORCE)
currHnd.fileIO.force();
}
catch (IOException e) {
log.error("Exception in WAL writer thread: ", e);
err = e;
unparkWaiters(Long.MAX_VALUE);
return;
}
unparkWaiters(pos);
}
List<SegmentedRingByteBuffer.ReadSegment> segs = currentHandle().buf.poll(pos);
if (segs == null) {
unparkWaiters(pos);
continue;
}
for (int i = 0; i < segs.size(); i++) {
SegmentedRingByteBuffer.ReadSegment seg = segs.get(i);
try {
writeBuffer(seg.position(), seg.buffer());
}
catch (Throwable e) {
log.error("Exception in WAL writer thread: ", e);
err = e;
}
finally {
seg.release();
long p = pos <= UNCONDITIONAL_FLUSH || err != null ? Long.MAX_VALUE : currentHandle().written;
unparkWaiters(p);
}
}
}
unparkWaiters(Long.MAX_VALUE);
}
/**
* Shutdowns thread.
*/
public void shutdown() throws IgniteInterruptedCheckedException {
shutdown = true;
LockSupport.unpark(this);
U.join(this);
}
/**
* Unparks waiting threads.
*
* @param pos Pos.
*/
private void unparkWaiters(long pos) {
assert pos > Long.MIN_VALUE : pos;
for (Map.Entry<Thread, Long> e : waiters.entrySet()) {
Long val = e.getValue();
if (val <= pos) {
if (val != Long.MIN_VALUE)
waiters.put(e.getKey(), Long.MIN_VALUE);
LockSupport.unpark(e.getKey());
}
}
}
/**
* Forces all made changes to the file.
*/
void force() throws IgniteCheckedException {
flushBuffer(FILE_FORCE);
}
/**
* Closes file.
*/
void close() throws IgniteCheckedException {
flushBuffer(FILE_CLOSE);
}
/**
* Flushes all data from the buffer.
*/
void flushAll() throws IgniteCheckedException {
flushBuffer(UNCONDITIONAL_FLUSH);
}
/**
* @param expPos Expected position.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
void flushBuffer(long expPos) throws StorageException, IgniteCheckedException {
if (mmap)
return;
Throwable err = walWriter.err;
if (err != null)
currentHandle().invalidateEnvironment(err);
if (expPos == UNCONDITIONAL_FLUSH)
expPos = (currentHandle().buf.tail());
Thread t = Thread.currentThread();
waiters.put(t, expPos);
LockSupport.unpark(walWriter);
while (true) {
Long val = waiters.get(t);
assert val != null : "Only this thread can remove thread from waiters";
if (val == Long.MIN_VALUE) {
waiters.remove(t);
return;
}
else
LockSupport.park();
}
}
/**
* @param pos Position in file to start write from. May be checked against actual position to wait previous
* writes to complete
* @param buf Buffer to write to file
* @throws StorageException If failed.
* @throws IgniteCheckedException If failed.
*/
@SuppressWarnings("TooBroadScope")
private void writeBuffer(long pos, ByteBuffer buf) throws StorageException, IgniteCheckedException {
FileWriteHandle hdl = currentHandle();
assert hdl.fileIO != null : "Writing to a closed segment.";
checkEnvironment();
long lastLogged = U.currentTimeMillis();
long logBackoff = 2_000;
// If we were too fast, need to wait previous writes to complete.
while (hdl.written != pos) {
assert hdl.written < pos : "written = " + hdl.written + ", pos = " + pos; // No one can write further than we are now.
// Permutation occurred between blocks write operations.
// Order of acquiring lock is not the same as order of write.
long now = U.currentTimeMillis();
if (now - lastLogged >= logBackoff) {
if (logBackoff < 60 * 60_000)
logBackoff *= 2;
U.warn(log, "Still waiting for a concurrent write to complete [written=" + hdl.written +
", pos=" + pos + ", lastFsyncPos=" + hdl.lastFsyncPos + ", stop=" + hdl.stop.get() +
", actualPos=" + hdl.safePosition() + ']');
lastLogged = now;
}
checkEnvironment();
}
// Do the write.
int size = buf.remaining();
assert size > 0 : size;
try {
assert hdl.written == hdl.fileIO.position();
do {
hdl.fileIO.write(buf);
}
while (buf.hasRemaining());
hdl.written += size;
metrics.onWalBytesWritten(size);
assert hdl.written == hdl.fileIO.position();
}
catch (IOException e) {
hdl.invalidateEnvironmentLocked(e);
throw new StorageException(e);
}
}
}
}
| ignite-7412 Fixed race in WAL manager with mmap enabled
| modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/wal/FileWriteAheadLogManager.java | ignite-7412 Fixed race in WAL manager with mmap enabled |
|
Java | apache-2.0 | 885758454fb907f21a9aefa9879f07db89d0cf2b | 0 | javydreamercsw/validation-manager | package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import com.validation.manager.core.DataBaseManager;
import com.validation.manager.core.db.Requirement;
import com.validation.manager.core.db.RequirementSpec;
import com.validation.manager.core.db.RequirementSpecNode;
import com.validation.manager.core.db.controller.RequirementSpecJpaController;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.ToolTipManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
/**
*
* @author Javier A. Ortiz Bultron <[email protected]>
*/
public class RequirementSelectionDialog extends javax.swing.JDialog {
private List<Requirement> requirements = new ArrayList<Requirement>();
private final DefaultMutableTreeNode top =
new DefaultMutableTreeNode("Available Requirements");
/**
* Creates new form RequirementSelectionDialog
*/
public RequirementSelectionDialog(java.awt.Frame parent, boolean modal,
List<Requirement> initial) {
super(parent, modal);
initComponents();
ToolTipManager.sharedInstance().registerComponent(source);
source.setCellRenderer(new InternalRenderer());
source.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
populateNodes();
selection.setModel(new DefaultListModel() {
@Override
public void addElement(Object obj) {
requirements.add((Requirement) obj);
super.addElement(obj);
}
@Override
public int getSize() {
return requirements.size();
}
@Override
public Object getElementAt(int i) {
return requirements.get(i);
}
});
selection.setCellRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
return new JLabel(((Requirement) ((DefaultListModel) selection.getModel()).getElementAt(index)).getUniqueId());
}
});
for (Requirement requirement : initial) {
((DefaultListModel) selection.getModel()).addElement(requirement);
}
}
/**
* 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() {
ok = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
source = new JTree(top);
jScrollPane4 = new javax.swing.JScrollPane();
selection = new javax.swing.JList();
add = new javax.swing.JButton();
remove = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.openide.awt.Mnemonics.setLocalizedText(ok, org.openide.util.NbBundle.getMessage(RequirementSelectionDialog.class, "RequirementSelectionDialog.ok.text")); // NOI18N
ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okActionPerformed(evt);
}
});
jScrollPane3.setViewportView(source);
selection.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
selection.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
selectionValueChanged(evt);
}
});
jScrollPane4.setViewportView(selection);
org.openide.awt.Mnemonics.setLocalizedText(add, org.openide.util.NbBundle.getMessage(RequirementSelectionDialog.class, "RequirementSelectionDialog.add.text")); // NOI18N
add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(remove, org.openide.util.NbBundle.getMessage(RequirementSelectionDialog.class, "RequirementSelectionDialog.remove.text")); // NOI18N
remove.setEnabled(false);
remove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(ok))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(remove)
.addGroup(layout.createSequentialGroup()
.addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addGap(132, 132, 132)
.addComponent(add)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(remove)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 175, Short.MAX_VALUE)))
.addComponent(ok))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed
setVisible(false);
}//GEN-LAST:event_okActionPerformed
private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
TreePath[] paths = source.getSelectionPaths();
for (TreePath tp : paths) {
Object value = tp.getLastPathComponent();
if (((DefaultMutableTreeNode) value).getUserObject() instanceof Requirement) {
Requirement requirement = (Requirement) ((DefaultMutableTreeNode) value).getUserObject();
if (!requirements.contains(requirement)) {
((DefaultListModel) selection.getModel()).addElement(requirement);
}
}
}
}//GEN-LAST:event_addActionPerformed
private void selectionValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_selectionValueChanged
// Enable remove button when item is selected
remove.setEnabled(selection.getSelectedValues().length > 0);
}//GEN-LAST:event_selectionValueChanged
private void removeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeActionPerformed
for (Object value : selection.getSelectedValues()) {
Requirement req = (Requirement) ((DefaultMutableTreeNode) value).getUserObject();
((DefaultListModel) selection.getModel()).removeElement(req);
}
}//GEN-LAST:event_removeActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton add;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JButton ok;
private javax.swing.JButton remove;
private javax.swing.JList selection;
private javax.swing.JTree source;
// End of variables declaration//GEN-END:variables
/**
* @return the requirements
*/
public List<Requirement> getRequirements() {
return requirements;
}
private void populateNodes() {
List<RequirementSpec> specs = new RequirementSpecJpaController(
DataBaseManager.getEntityManagerFactory())
.findRequirementSpecEntities();
for (Iterator<RequirementSpec> it = specs.iterator(); it.hasNext();) {
RequirementSpec spec = it.next();
DefaultMutableTreeNode node =
new DefaultMutableTreeNode(spec);
for (Iterator<RequirementSpecNode> it2 =
spec.getRequirementSpecNodeList().iterator(); it2.hasNext();) {
RequirementSpecNode rsn = it2.next();
for (Iterator<Requirement> it3 =
rsn.getRequirementList().iterator(); it3.hasNext();) {
Requirement req = it3.next();
DefaultMutableTreeNode r =
new DefaultMutableTreeNode(req);
node.add(r);
}
}
top.add(node);
}
}
private class InternalRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
if (((DefaultMutableTreeNode) value).getUserObject() instanceof RequirementSpec) {
RequirementSpec spec = (RequirementSpec) ((DefaultMutableTreeNode) value).getUserObject();
// setIcon(tutorialIcon);
setToolTipText("Requirement Specification");
return new JLabel(spec.getName());
} else if (((DefaultMutableTreeNode) value).getUserObject() instanceof Requirement) {
Requirement req = (Requirement) ((DefaultMutableTreeNode) value).getUserObject();
// setIcon(tutorialIcon);
setToolTipText("Requirement");
return new JLabel(req.getUniqueId());
} else {
setToolTipText(null); //no tool tip
}
return this;
}
}
}
| Client/Client-UI/src/main/java/net/sourceforge/javydreamercsw/client/ui/nodes/actions/RequirementSelectionDialog.java | package net.sourceforge.javydreamercsw.client.ui.nodes.actions;
import com.validation.manager.core.DataBaseManager;
import com.validation.manager.core.db.Requirement;
import com.validation.manager.core.db.RequirementSpec;
import com.validation.manager.core.db.RequirementSpecNode;
import com.validation.manager.core.db.controller.RequirementSpecJpaController;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.ToolTipManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
/**
*
* @author Javier A. Ortiz Bultron <[email protected]>
*/
public class RequirementSelectionDialog extends javax.swing.JDialog {
private List<Requirement> requirements = new ArrayList<Requirement>();
private final DefaultMutableTreeNode top =
new DefaultMutableTreeNode("Available Requirements");
/**
* Creates new form RequirementSelectionDialog
*/
public RequirementSelectionDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
ToolTipManager.sharedInstance().registerComponent(source);
source.setCellRenderer(new InternalRenderer());
source.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
populateNodes();
selection.setModel(new DefaultListModel() {
@Override
public void addElement(Object obj) {
requirements.add((Requirement) obj);
super.addElement(obj);
}
@Override
public int getSize() {
return requirements.size();
}
@Override
public Object getElementAt(int i) {
return requirements.get(i);
}
});
selection.setCellRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
return new JLabel(((Requirement) ((DefaultListModel) selection.getModel()).getElementAt(index)).getUniqueId());
}
});
}
/**
* 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() {
ok = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
source = new JTree(top);
jScrollPane4 = new javax.swing.JScrollPane();
selection = new javax.swing.JList();
add = new javax.swing.JButton();
remove = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.openide.awt.Mnemonics.setLocalizedText(ok, org.openide.util.NbBundle.getMessage(RequirementSelectionDialog.class, "RequirementSelectionDialog.ok.text")); // NOI18N
ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okActionPerformed(evt);
}
});
jScrollPane3.setViewportView(source);
selection.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
selection.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
selectionValueChanged(evt);
}
});
jScrollPane4.setViewportView(selection);
org.openide.awt.Mnemonics.setLocalizedText(add, org.openide.util.NbBundle.getMessage(RequirementSelectionDialog.class, "RequirementSelectionDialog.add.text")); // NOI18N
add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(remove, org.openide.util.NbBundle.getMessage(RequirementSelectionDialog.class, "RequirementSelectionDialog.remove.text")); // NOI18N
remove.setEnabled(false);
remove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(ok))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(remove)
.addGroup(layout.createSequentialGroup()
.addComponent(add, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addGap(132, 132, 132)
.addComponent(add)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(remove)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 175, Short.MAX_VALUE)))
.addComponent(ok))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed
setVisible(false);
}//GEN-LAST:event_okActionPerformed
private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
TreePath[] paths = source.getSelectionPaths();
for (TreePath tp : paths) {
Object value = tp.getLastPathComponent();
if (((DefaultMutableTreeNode) value).getUserObject() instanceof Requirement) {
Requirement requirement = (Requirement) ((DefaultMutableTreeNode) value).getUserObject();
if (!requirements.contains(requirement)) {
((DefaultListModel) selection.getModel()).addElement(requirement);
}
}
}
}//GEN-LAST:event_addActionPerformed
private void selectionValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_selectionValueChanged
// Enable remove button when item is selected
remove.setEnabled(selection.getSelectedValues().length > 0);
}//GEN-LAST:event_selectionValueChanged
private void removeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeActionPerformed
for (Object value : selection.getSelectedValues()) {
Requirement req = (Requirement) ((DefaultMutableTreeNode) value).getUserObject();
((DefaultListModel) selection.getModel()).removeElement(req);
}
}//GEN-LAST:event_removeActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton add;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JButton ok;
private javax.swing.JButton remove;
private javax.swing.JList selection;
private javax.swing.JTree source;
// End of variables declaration//GEN-END:variables
/**
* @return the requirements
*/
public List<Requirement> getRequirements() {
return requirements;
}
private void populateNodes() {
List<RequirementSpec> specs = new RequirementSpecJpaController(
DataBaseManager.getEntityManagerFactory())
.findRequirementSpecEntities();
for (Iterator<RequirementSpec> it = specs.iterator(); it.hasNext();) {
RequirementSpec spec = it.next();
DefaultMutableTreeNode node =
new DefaultMutableTreeNode(spec);
for (Iterator<RequirementSpecNode> it2 =
spec.getRequirementSpecNodeList().iterator(); it2.hasNext();) {
RequirementSpecNode rsn = it2.next();
for (Iterator<Requirement> it3 =
rsn.getRequirementList().iterator(); it3.hasNext();) {
Requirement req = it3.next();
DefaultMutableTreeNode r =
new DefaultMutableTreeNode(req);
node.add(r);
}
}
top.add(node);
}
}
private class InternalRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
if (((DefaultMutableTreeNode) value).getUserObject() instanceof RequirementSpec) {
RequirementSpec spec = (RequirementSpec) ((DefaultMutableTreeNode) value).getUserObject();
// setIcon(tutorialIcon);
setToolTipText("Requirement Specification");
return new JLabel(spec.getName());
} else if (((DefaultMutableTreeNode) value).getUserObject() instanceof Requirement) {
Requirement req = (Requirement) ((DefaultMutableTreeNode) value).getUserObject();
// setIcon(tutorialIcon);
setToolTipText("Requirement");
return new JLabel(req.getUniqueId());
} else {
setToolTipText(null); //no tool tip
}
return this;
}
}
}
| If editing, populate linked requirements by default.
| Client/Client-UI/src/main/java/net/sourceforge/javydreamercsw/client/ui/nodes/actions/RequirementSelectionDialog.java | If editing, populate linked requirements by default. |
|
Java | apache-2.0 | 994c13afad3f7420a6287194247ecafdd9142329 | 0 | kai0masanari/Forcelayout,kai0masanari/Forcelayout | package jp.kai.forcelayout;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.view.Display;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by kai on 2016/09/03.
*/
public class Forcelayout extends View{
private static Properties properties = null;
private static Context mContext = null;
private static ViewGroup mView;
private static HashMap<String, ImageView> nodeslist = new HashMap<>();
public static Properties.Node[] nodes = new Properties.Node[200];
public static Properties.Edge[] edges = new Properties.Edge[500];
static ArrayList<String> nodename_array = new ArrayList<String>();
static ArrayList<Bitmap> nodebitmap_array = new ArrayList<>();
private static ArrayList<String> convertlist = new ArrayList<>();;
private static int nedges = 0;
private static float display_width;
private static float display_height;
private static int nodeindex = 0; //実際のノードの数
private int targetnode = -1;
public Forcelayout(Context context) {
super(context);
mContext = context;
mView = new LinearLayout(context.getApplicationContext());
nodename_array.clear();
nodebitmap_array.clear();
convertlist.clear();
nedges = 0;
}
public static Properties with(Context context){
mContext = context;
properties = new Properties(context);
return properties.prepare();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int touch_x = (int)event.getX();
int touch_y = (int)event.getY();
Log.d("TouchEvent","X:"+touch_x+" Y:"+touch_y);
switch ( event.getAction() ) {
case MotionEvent.ACTION_DOWN:
for(int i=0; i< nodeindex; i++){
if((nodes[i].x + nodes[i].width >= touch_x && nodes[i].x <= touch_x)
&& (nodes[i].y + nodes[i].height >= touch_y && nodes[i].y <= touch_y)){
targetnode = i;
}
}
break;
case MotionEvent.ACTION_MOVE:
if(targetnode != -1){
nodes[targetnode].x = touch_x-nodes[targetnode].width/2;
nodes[targetnode].y = touch_y-nodes[targetnode].height/2;
}
break;
case MotionEvent.ACTION_UP:
targetnode = -1;
break;
case MotionEvent.ACTION_CANCEL:
targetnode = -1;
break;
}
return true;
}
// 描画処理を記述
@Override
protected void dispatchDraw(Canvas canvas) {
Paint paint = new Paint();
if(edges.length != 0){
for (int i = 0 ; i < nedges-1 ; i++) {
if (edges[i].group) {
Properties.Edge e = edges[i];
float x1 = (float) (nodes[e.from].x + nodes[e.from].width/2);
float y1 = (float) (nodes[e.from].y + nodes[e.from].height/2);
float x2 = (float) (nodes[e.to].x + nodes[e.to].width/2);
float y2 = (float) (nodes[e.to].y + nodes[e.to].height/2);
//int len = (int) Math.abs(Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) - e.len);
paint.setStrokeWidth(5);
float[] pts = {x1, y1, x2, y2};
canvas.drawLines(pts, paint);
}
}
}
for (final String str : nodeslist.keySet()) {
if(convertlist.indexOf(str) == -1) {
Bitmap _bitmap = ((BitmapDrawable) nodeslist.get(str).getDrawable()).getBitmap();
nodebitmap_array.add(getCroppedBitmap(_bitmap, 5));
convertlist.add(str);
}
}
for(int i=0; i<convertlist.size(); i++){
canvas.drawBitmap(nodebitmap_array.get(i), (int)nodes[i].x, (int)nodes[i].y, paint);
paint.setTextSize (30);
canvas.drawText(nodes[i].nodename, (int)(nodes[i].x+nodes[i].width), (int)(nodes[i].y+nodes[i].height+30), paint);
}
if(nedges != 0) {
properties.relax();
}
invalidate();
}
public Bitmap getCroppedBitmap(Bitmap bitmap, int round) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
final Rect rect = new Rect(0, 0, width, height);
final RectF rectf = new RectF(0, 0, width, height);
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawRoundRect(rectf, width / round, height / round, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static class Properties{
private static Context mContext;
//画面関連
//TODO ゆくゆくはばねモデルの表示領域も指定できるようにし、それに対応させたい。
private static float nodearea_width; //実際のノードの範囲
private static float nodearea_height;
private static int reduction = 30;
//ノード関連
private static int screenX = 0;
private static int screenY = 0;
private static int targetLocalX = 0; //ドラッグ時の座標保存
private static int targetLocalY = 0;
//TODO Nodeクラスにドラッグ判定も追加すること
private static boolean dragging = false; //ドラッグ中かの判定
//ばねモデルのパラメータ
private static double bounce = 0.008; //ばね定数
private static double attenuation = 0.8;//0.9; //減衰定数
private static double coulomb = 680; //クーロン
public Properties(Context context){
mContext = context;
}
private Properties prepare(){
Display mDisplay = getDisplayMetrics(mContext);
display_width = mDisplay.getWidth();
display_height = mDisplay.getHeight();
return this;
}
//ノードのセッター
public Properties setnodes(final HashMap<String, Integer> nodemaps){
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
for (final String str : nodemaps.keySet()) {
// ビットマップ作成オブジェクトの設定
BitmapFactory.Options bmfOptions = new BitmapFactory.Options();
// 画像を1/?サイズに縮小する
bmfOptions.inSampleSize = reduction;
// メモリの解放
bmfOptions.inPurgeable = true;
final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), nodemaps.get(str), bmfOptions);
// 画像の元サイズ 取得
//TODO 元サイズに応じて縮小サイズを動的に変えること
final int imgheight = bmfOptions.outHeight;
final int imgwidth = bmfOptions.outWidth;
//ノード
ImageView nodeimage = new ImageView(mContext);
nodeimage.setImageBitmap(bitmap);
nodearea_width = display_width - (int)(imgwidth);
nodearea_height = display_height - (int)(imgheight);
double imgwidth_d = (double)(imgwidth/reduction);
addNode(str, nodeindex, imgwidth, imgheight);
nodeimage.setTranslationX((float) nodes[nodeindex].x);
nodeimage.setTranslationY((float) nodes[nodeindex].y);
mView.addView(nodeimage, new ViewGroup.LayoutParams(WC, WC));
nodename_array.add(str);
//TODO TextViewとImageViewのコンテナを作って管理すること
nodeslist.put(str,nodeimage);
nodeslist.get(str).setOnTouchListener(Touchlistener);
nodeindex++;
}
}
});
return this;
}
//リンクのセッター
public Properties setlinks(final HashMap<String, String> linkmaps){
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
for(int i=0; i < nodename_array.size()-1;i++){
for(int j=i+1; j<nodename_array.size(); j++){
if(i != j) {
addEdge(i, j);
}
}
}
for (final String str : linkmaps.keySet()) {
for(int i=0; i<nedges-1; i++){
if ((edges[i].from == nodename_array.indexOf(str) && edges[i].to == nodename_array.indexOf(linkmaps.get(str))) ||
(edges[i].to == nodename_array.indexOf(str) && edges[i].from == nodename_array.indexOf(linkmaps.get(str)))){
edges[i].group = true;
Log.d("setLinks","from:"+str+" to:"+linkmaps.get(str));
}
}
}
}
});
return this;
}
//ノードクラス
public static class Node{
String nodename;
double x;
double y;
double width;
double height;
double dx;
double dy;
}
//リンククラス
public static class Edge {
int from;
int to;
double len;
boolean group;
}
//ノードの追加
public static void addNode(String lbl, int index, int width, int height){
//System.out.println(lbl);
Node n = new Node();
n.x = (nodearea_width)*Math.random();
n.y = (nodearea_height-10)*(Math.random())+10;
n.nodename = lbl;
n.width = width;
n.height = height;
n.dx = 0;
n.dy = 0;
nodes[index] = n;
}
//リンクの追加
public static void addEdge(int from, int to){
Edge e = new Edge();
e.from = from;
e.to = to;
e.len = 0;
e.group = false;
edges[nedges++] = e;
}
//ばねの動作
public void relax(){
if(nedges != 0){
for(int i=0; i<nodeindex; i++){
double fx = 0,fy = 0;
for(int j=0; j<nodeindex; j++){
double distX = (int)((nodes[i].x + nodes[i].width/2) - (nodes[j].x + nodes[j].width/2));
double distY = (int)((nodes[i].y + nodes[i].height/2) - (nodes[j].y + nodes[j].height/2));
double rsq = distX * distX + distY *distY;
int rsq_round = (int)rsq*100;
rsq = rsq_round/100;
double coulombdist_x = coulomb * distX;
double coulombdist_y = coulomb * distY;
int coulombdist_round_x = (int)coulombdist_x*100;
int coulombdist_round_y = (int)coulombdist_y*100;
coulombdist_x = coulombdist_round_x/100;
coulombdist_y = coulombdist_round_y/100;
boolean isgroup = false;
for(int k=0; k<nedges;k++){
if(edges[k].to == nodename_array.indexOf(nodes[i])){
isgroup = edges[k].group;
break;
}
}
if(rsq != 0 && !isgroup) {
fx += (coulombdist_x / rsq) ;
fy += coulombdist_y / rsq ;
}
}
//target node
for(int j=0; j<nedges-1; j++){
double distX=0,distY=0;
if(i == edges[j].from ){
distX = nodes[edges[j].to].x - nodes[i].x;
distY = nodes[edges[j].to].y - nodes[i].y;
} else if( i== edges[j].to){
distX = nodes[edges[j].from].x - nodes[i].x;
distY = nodes[edges[j].from].y - nodes[i].y;
}
fx += bounce *distX*1.1;
fy += bounce *distY*1.1;
}
//速度の算出
nodes[i].dx = (nodes[i].dx + fx) * attenuation;
nodes[i].dy = (nodes[i].dy + fy) * attenuation;
//速度をもとに収束させてく
if(nodes[i].x < display_width - nodes[i].width && nodes[i].x > 0) {
nodes[i].x += nodes[i].dx;
}
//速度をもとに収束させてく
if(nodes[i].y < display_height - nodes[i].height && nodes[i].y > 0) {
nodes[i].y += nodes[i].dy;
}
}
}
}
//2点から距離を求める
private double get_distance(double c_position_x, double c_position_y, double b_position_x, double b_position_y){
double distance = Math.sqrt(Math.pow(c_position_x - b_position_x, 2)+Math.pow(c_position_y - b_position_y, 2));
return distance;
}
//display size
public static final Display getDisplayMetrics(Context context) {
WindowManager winMan = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display disp = winMan.getDefaultDisplay();
//DisplayMetrics dispMet = new DisplayMetrics();
//disp.getMetrics(dispMet);
return disp;
}
private static float[] getSize(ImageView img) {
Rect rect = img.getDrawable().getBounds();
float scaleX = (float) img.getWidth() / (float) rect.width();
float scaleY = (float) img.getHeight() / (float) rect.height();
float scale = Math.min(scaleX, scaleY);
float width = scale * rect.width();
float height = scale * rect.height();
return new float[] {width, height};
}
//listener
private static OnTouchListener Touchlistener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int)event.getRawX();
int y = (int)event.getRawY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
targetLocalX = v.getLeft();
targetLocalY = v.getTop();
screenX = x;
screenY = y;
break;
case MotionEvent.ACTION_MOVE:
int diffX = screenX - x;
int diffY = screenY - y;
targetLocalX -= diffX;
targetLocalY -= diffY;
v.layout(targetLocalX,
targetLocalY,
targetLocalX + v.getWidth(),
targetLocalY + v.getHeight());
screenX = x;
screenY = y;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
};
}
}
| forcelayout/src/main/java/jp/kai/forcelayout/Forcelayout.java | package jp.kai.forcelayout;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.view.Display;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by kai on 2016/09/03.
*/
public class Forcelayout extends View{
private static Properties properties = null;
private static Context mContext = null;
private static ViewGroup mView;
private static HashMap<String, ImageView> nodeslist = new HashMap<>();
public static Properties.Node[] nodes = new Properties.Node[200];
public static Properties.Edge[] edges = new Properties.Edge[500];
static ArrayList<String> nodename_array = new ArrayList<String>();
static ArrayList<Bitmap> nodebitmap_array = new ArrayList<>();
private static ArrayList<String> convertlist = new ArrayList<>();;
private static int nedges = 0;
private static float display_width;
private static float display_height;
private static int nodeindex = 0; //実際のノードの数
public Forcelayout(Context context) {
super(context);
//setWillNotDraw(false);
mContext = context;
mView = new LinearLayout(context.getApplicationContext());
nodename_array.clear();
nodebitmap_array.clear();
convertlist.clear();
nedges = 0;
}
public static Properties with(Context context){
mContext = context;
properties = new Properties(context);
return properties.prepare();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int targetnode = -1;
int touch_x = (int)event.getX();
int touch_y = (int)event.getY();
Log.d("TouchEvent","X:"+touch_x+" Y:"+touch_y);
switch ( event.getAction() ) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
for(int i=0; i< nodeindex; i++){
if((nodes[i].x + nodes[i].width >= touch_x && nodes[i].x <= touch_x)
&& (nodes[i].y + nodes[i].height >= touch_y && nodes[i].y <= touch_y)){
targetnode = i;
}
}
if(targetnode != -1){
nodes[targetnode].x = touch_x-nodes[targetnode].width/2;
nodes[targetnode].y = touch_y-nodes[targetnode].height/2;
}
break;
case MotionEvent.ACTION_UP:
targetnode = -1;
break;
case MotionEvent.ACTION_CANCEL:
targetnode = -1;
break;
}
return true;
}
// 描画処理を記述
@Override
protected void dispatchDraw(Canvas canvas) {
Paint paint = new Paint();
if(edges.length != 0){
for (int i = 0 ; i < nedges-1 ; i++) {
if (edges[i].group) {
Properties.Edge e = edges[i];
float x1 = (float) (nodes[e.from].x + nodes[e.from].width/2);
float y1 = (float) (nodes[e.from].y + nodes[e.from].height/2);
float x2 = (float) (nodes[e.to].x + nodes[e.to].width/2);
float y2 = (float) (nodes[e.to].y + nodes[e.to].height/2);
//int len = (int) Math.abs(Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) - e.len);
paint.setStrokeWidth(5);
float[] pts = {x1, y1, x2, y2};
canvas.drawLines(pts, paint);
}
}
}
for (final String str : nodeslist.keySet()) {
if(convertlist.indexOf(str) == -1) {
Bitmap _bitmap = ((BitmapDrawable) nodeslist.get(str).getDrawable()).getBitmap();
nodebitmap_array.add(getCroppedBitmap(_bitmap, 5));
convertlist.add(str);
}
}
for(int i=0; i<convertlist.size(); i++){
canvas.drawBitmap(nodebitmap_array.get(i), (int)nodes[i].x, (int)nodes[i].y, paint);
paint.setTextSize (30);
canvas.drawText(nodes[i].nodename, (int)(nodes[i].x+nodes[i].width), (int)(nodes[i].y+nodes[i].height+30), paint);
}
if(nedges != 0) {
properties.relax();
}
invalidate();
}
public Bitmap getCroppedBitmap(Bitmap bitmap, int round) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
final Rect rect = new Rect(0, 0, width, height);
final RectF rectf = new RectF(0, 0, width, height);
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawRoundRect(rectf, width / round, height / round, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static class Properties{
private static Context mContext;
//画面関連
//TODO ゆくゆくはばねモデルの表示領域も指定できるようにし、それに対応させたい。
private static float nodearea_width; //実際のノードの範囲
private static float nodearea_height;
private static int reduction = 30;
//ノード関連
private static int screenX = 0;
private static int screenY = 0;
private static int targetLocalX = 0; //ドラッグ時の座標保存
private static int targetLocalY = 0;
//TODO Nodeクラスにドラッグ判定も追加すること
private static boolean dragging = false; //ドラッグ中かの判定
//ばねモデルのパラメータ
private static double bounce = 0.008; //ばね定数
private static double attenuation = 0.8;//0.9; //減衰定数
private static double coulomb = 680; //クーロン
public Properties(Context context){
mContext = context;
}
private Properties prepare(){
Display mDisplay = getDisplayMetrics(mContext);
display_width = mDisplay.getWidth();
display_height = mDisplay.getHeight();
return this;
}
//ノードのセッター
public Properties setnodes(final HashMap<String, Integer> nodemaps){
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
for (final String str : nodemaps.keySet()) {
// ビットマップ作成オブジェクトの設定
BitmapFactory.Options bmfOptions = new BitmapFactory.Options();
// 画像を1/?サイズに縮小する
bmfOptions.inSampleSize = reduction;
// メモリの解放
bmfOptions.inPurgeable = true;
final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), nodemaps.get(str), bmfOptions);
// 画像の元サイズ 取得
//TODO 元サイズに応じて縮小サイズを動的に変えること
final int imgheight = bmfOptions.outHeight;
final int imgwidth = bmfOptions.outWidth;
//ノード
ImageView nodeimage = new ImageView(mContext);
nodeimage.setImageBitmap(bitmap);
nodearea_width = display_width - (int)(imgwidth);
nodearea_height = display_height - (int)(imgheight);
double imgwidth_d = (double)(imgwidth/reduction);
addNode(str, nodeindex, imgwidth, imgheight);
nodeimage.setTranslationX((float) nodes[nodeindex].x);
nodeimage.setTranslationY((float) nodes[nodeindex].y);
mView.addView(nodeimage, new ViewGroup.LayoutParams(WC, WC));
nodename_array.add(str);
//TODO TextViewとImageViewのコンテナを作って管理すること
nodeslist.put(str,nodeimage);
nodeslist.get(str).setOnTouchListener(Touchlistener);
nodeindex++;
}
}
});
return this;
}
//リンクのセッター
public Properties setlinks(final HashMap<String, String> linkmaps){
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
for(int i=0; i < nodename_array.size()-1;i++){
for(int j=i+1; j<nodename_array.size(); j++){
if(i != j) {
addEdge(i, j);
}
}
}
for (final String str : linkmaps.keySet()) {
for(int i=0; i<nedges-1; i++){
if ((edges[i].from == nodename_array.indexOf(str) && edges[i].to == nodename_array.indexOf(linkmaps.get(str))) ||
(edges[i].to == nodename_array.indexOf(str) && edges[i].from == nodename_array.indexOf(linkmaps.get(str)))){
edges[i].group = true;
Log.d("setLinks","from:"+str+" to:"+linkmaps.get(str));
}
}
}
}
});
return this;
}
//ノードクラス
public static class Node{
String nodename;
double x;
double y;
double width;
double height;
double dx;
double dy;
}
//リンククラス
public static class Edge {
int from;
int to;
double len;
boolean group;
}
//ノードの追加
public static void addNode(String lbl, int index, int width, int height){
//System.out.println(lbl);
Node n = new Node();
n.x = (nodearea_width)*Math.random();
n.y = (nodearea_height-10)*(Math.random())+10;
n.nodename = lbl;
n.width = width;
n.height = height;
n.dx = 0;
n.dy = 0;
nodes[index] = n;
}
//リンクの追加
public static void addEdge(int from, int to){
Edge e = new Edge();
e.from = from;
e.to = to;
e.len = 0;
e.group = false;
edges[nedges++] = e;
}
//ばねの動作
public void relax(){
if(nedges != 0){
for(int i=0; i<nodeindex; i++){
double fx = 0,fy = 0;
for(int j=0; j<nodeindex; j++){
double distX = (int)((nodes[i].x + nodes[i].width/2) - (nodes[j].x + nodes[j].width/2));
double distY = (int)((nodes[i].y + nodes[i].height/2) - (nodes[j].y + nodes[j].height/2));
double rsq = distX * distX + distY *distY;
int rsq_round = (int)rsq*100;
rsq = rsq_round/100;
double coulombdist_x = coulomb * distX;
double coulombdist_y = coulomb * distY;
int coulombdist_round_x = (int)coulombdist_x*100;
int coulombdist_round_y = (int)coulombdist_y*100;
coulombdist_x = coulombdist_round_x/100;
coulombdist_y = coulombdist_round_y/100;
boolean isgroup = false;
for(int k=0; k<nedges;k++){
if(edges[k].to == nodename_array.indexOf(nodes[i])){
isgroup = edges[k].group;
break;
}
}
if(rsq != 0 && !isgroup) {
fx += (coulombdist_x / rsq) ;
fy += coulombdist_y / rsq ;
}
}
//target node
for(int j=0; j<nedges-1; j++){
double distX=0,distY=0;
if(i == edges[j].from ){
distX = nodes[edges[j].to].x - nodes[i].x;
distY = nodes[edges[j].to].y - nodes[i].y;
} else if( i== edges[j].to){
distX = nodes[edges[j].from].x - nodes[i].x;
distY = nodes[edges[j].from].y - nodes[i].y;
}
fx += bounce *distX*1.1;
fy += bounce *distY*1.1;
}
//速度の算出
nodes[i].dx = (nodes[i].dx + fx) * attenuation;
nodes[i].dy = (nodes[i].dy + fy) * attenuation;
//速度をもとに収束させてく
if(nodes[i].x < display_width && nodes[i].x > 0) {
nodes[i].x += nodes[i].dx;
}
//速度をもとに収束させてく
if(nodes[i].y < display_height && nodes[i].x > 0) {
nodes[i].y += nodes[i].dy;
}
}
}
}
//2点から距離を求める
private double get_distance(double c_position_x, double c_position_y, double b_position_x, double b_position_y){
double distance = Math.sqrt(Math.pow(c_position_x - b_position_x, 2)+Math.pow(c_position_y - b_position_y, 2));
return distance;
}
//display size
public static final Display getDisplayMetrics(Context context) {
WindowManager winMan = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display disp = winMan.getDefaultDisplay();
//DisplayMetrics dispMet = new DisplayMetrics();
//disp.getMetrics(dispMet);
return disp;
}
private static float[] getSize(ImageView img) {
Rect rect = img.getDrawable().getBounds();
float scaleX = (float) img.getWidth() / (float) rect.width();
float scaleY = (float) img.getHeight() / (float) rect.height();
float scale = Math.min(scaleX, scaleY);
float width = scale * rect.width();
float height = scale * rect.height();
return new float[] {width, height};
}
//listener
private static OnTouchListener Touchlistener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int)event.getRawX();
int y = (int)event.getRawY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
targetLocalX = v.getLeft();
targetLocalY = v.getTop();
screenX = x;
screenY = y;
break;
case MotionEvent.ACTION_MOVE:
int diffX = screenX - x;
int diffY = screenY - y;
targetLocalX -= diffX;
targetLocalY -= diffY;
v.layout(targetLocalX,
targetLocalY,
targetLocalX + v.getWidth(),
targetLocalY + v.getHeight());
screenX = x;
screenY = y;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
};
}
}
| builderとのマージ。一部書き間違え修正。
| forcelayout/src/main/java/jp/kai/forcelayout/Forcelayout.java | builderとのマージ。一部書き間違え修正。 |
|
Java | apache-2.0 | 65258719298d175644187278db0afb9e25e8ed1d | 0 | sculptor/sculptor,sculptor/sculptor,sculptor/sculptor | /*
* Copyright 2009 The Fornax Project Team, including the original
* author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sculptor.framework.accessimpl.jpa;
import org.sculptor.framework.accessapi.ConditionalCriteria;
import org.sculptor.framework.accessapi.ConditionalCriteria.Operator;
import org.sculptor.framework.accessapi.FindByConditionAccess2;
import org.sculptor.framework.domain.LeafProperty;
import org.sculptor.framework.domain.Property;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.FetchParent;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* <p>
* Implementation of Access command FindByConditionAccess.
* </p>
* <p>
* Command design pattern.
* </p>
*/
public class JpaFindByConditionAccessImplGeneric<T,R>
extends JpaCriteriaQueryAccessBase<T,R> implements FindByConditionAccess2<R> {
private List<ConditionalCriteria> conditionalCriterias = new ArrayList<ConditionalCriteria>();
public JpaFindByConditionAccessImplGeneric() {
super();
}
public JpaFindByConditionAccessImplGeneric(Class<T> type) {
super(type);
}
public JpaFindByConditionAccessImplGeneric(Class<T> type, Class<R> resultType) {
super(type, resultType);
}
public void setCondition(List<ConditionalCriteria> criteria) {
conditionalCriterias=criteria;
}
public void addCondition(ConditionalCriteria criteria) {
conditionalCriterias.add(criteria);
}
public List<R> getResult() {
return getListResult();
}
@Override
protected List<Predicate> preparePredicates() {
List<Predicate> predicates = new ArrayList<Predicate>();
for (ConditionalCriteria criteria : conditionalCriterias) {
Predicate predicate = preparePredicate(criteria);
if (predicate != null) {
predicates.add(predicate);
}
}
return predicates;
}
@Override
protected void prepareConfig(QueryConfig config) {
config.setDistinct(false);
}
@SuppressWarnings("unchecked")
protected void prepareSelect(CriteriaQuery<R> criteriaQuery, Root<T> root, QueryConfig config) {
List<Selection<?>> selections = new ArrayList<Selection<?>>();
for (ConditionalCriteria criteria : conditionalCriterias) {
Selection<?> selection = null;
if (Operator.Select.equals(criteria.getOperator())) {
selection = getExpression(criteria, root);
} else if (Operator.Max.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().max(getExpression(criteria, root));
} else if (Operator.Min.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().min(getExpression(criteria, root));
} else if (Operator.Avg.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().avg(getExpression(criteria,root));
} else if (Operator.Sum.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().sum(getExpression(criteria, root));
} else if (Operator.SumAsLong.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().sumAsLong(getExpression(criteria, root).as(Integer.class));
} else if (Operator.SumAsDouble.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().sumAsDouble(getExpression(criteria, root).as(Float.class));
} else if (Operator.Count.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().count(getExpression(criteria, root)).as(Long.class);
} else if (Operator.CountDistinct.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().countDistinct(getExpression(criteria, root)).as(Long.class);
}
if (selection != null) {
if (criteria.getPropertyAlias() != null) {
selection.alias(criteria.getPropertyAlias());
}
selections.add(selection);
}
}
if (!selections.isEmpty()) {
setFetchEager(null);
criteriaQuery.multiselect(selections);
}
}
private Expression<? extends Number> getExpression(ConditionalCriteria criteria, Root<T> root) {
CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
Expression<? extends Number> result = (Expression<? extends Number>) getPath(root, criteria.getPropertyFullName());
if (criteria.getFirstOperant() instanceof ConditionalCriteria.Function) {
ConditionalCriteria.Function function = (ConditionalCriteria.Function) criteria.getFirstOperant();
if (ConditionalCriteria.Function.hour.equals(function)) {
result = criteriaBuilder.function("hour", Integer.class, result);
} else if (ConditionalCriteria.Function.day.equals(function)) {
result = criteriaBuilder.function("day", Integer.class, result);
} else if (ConditionalCriteria.Function.month.equals(function)) {
result = criteriaBuilder.function("month", Integer.class, result);
} else if (ConditionalCriteria.Function.year.equals(function)) {
result = criteriaBuilder.function("year", Integer.class, result);
} else if (ConditionalCriteria.Function.week.equals(function)) {
result = criteriaBuilder.function("week", Integer.class, result);
} else if (ConditionalCriteria.Function.quarter.equals(function)) {
result = criteriaBuilder.function("quarter", Integer.class, result);
} else if (ConditionalCriteria.Function.dayOfWeek.equals(function)) {
result = criteriaBuilder.function("dow", Integer.class, result);
} else if (ConditionalCriteria.Function.dayOfYear.equals(function)) {
result = criteriaBuilder.function("doy", Integer.class, result);
}
}
return result;
}
@Override
protected void prepareFetch(Root<T> root, QueryConfig config) {
// Extract eager field names
List<String> eagerProperties = new ArrayList<>();
Property<?>[] fetchEager = getFetchEager();
if (fetchEager != null) {
for (Property p : getFetchEager()) {
String propFullName = p instanceof LeafProperty<?> ? ((LeafProperty<?>) p).getEmbeddedName() : p.getName();
eagerProperties.add(propFullName);
}
}
// Apply eager from criteria
for (ConditionalCriteria criteria : conditionalCriterias) {
if (Operator.FetchEager.equals(criteria.getOperator())) {
// TODO: this is not tested
String[] split = criteria.getPropertyFullName().split("\\.");
FetchParent parent = root;
for (String s : split) {
parent = parent.fetch(s, JoinType.LEFT);
}
// Remove fields which are overridden in criteria
eagerProperties.remove(criteria.getPropertyFullName());
} else if (Operator.FetchLazy.equals(criteria.getOperator())) {
// TODO: fetchLazy is not supported actually
}
}
// Apply eager unspecified in criteria
for (String eager : eagerProperties) {
String[] split = eager.split("\\.");
FetchParent parent = root;
for (String s : split) {
parent = parent.fetch(s, JoinType.LEFT);
}
}
}
@Override
protected void prepareOrderBy(CriteriaQuery<R> criteriaQuery, Root<T> root, QueryConfig config) {
List<Order> orderByList = new ArrayList<Order>();
for (ConditionalCriteria criteria : conditionalCriterias) {
if (Operator.OrderAsc.equals(criteria.getOperator())) {
if (config.isDistinct()) {
// for distinct select, sort column have to be in fetch columns - otherwise DB error
orderByList.add(getCriteriaBuilder().asc(getFetchPath(root, criteria)));
} else {
orderByList.add(getCriteriaBuilder().asc(getPath(root, criteria.getPropertyFullName())));
}
} else if (Operator.OrderDesc.equals(criteria.getOperator())) {
if (config.isDistinct()) {
// for distinct select, sort column have to be in fetch columns - otherwise DB error
orderByList.add(getCriteriaBuilder().desc(getFetchPath(root, criteria)));
} else {
orderByList.add(getCriteriaBuilder().desc(getPath(root, criteria.getPropertyFullName())));
}
}
}
if (!orderByList.isEmpty()) {
criteriaQuery.orderBy(orderByList);
}
}
private Path getFetchPath(Root<T> root, ConditionalCriteria criteria) {
FetchParent from = root;
for (int i = 0; i < criteria.getPropertyPath().length; i++) {
String stringPath = criteria.getPropertyPath()[i];
Set<Fetch<?, ?>> fetches = from.getFetches();
boolean found = false;
for (Fetch<?, ?> fetch : fetches) {
if (fetch.getAttribute().getName().equals(stringPath)) {
from = (FetchParent) fetch;
found = true;
break;
}
}
if (!found) {
from = from.fetch(stringPath, JoinType.LEFT);
}
}
return ((Path) from).get(criteria.getPropertyName());
}
@Override
protected void prepareGroupBy(CriteriaQuery<R> criteriaQuery, Root<T> root, QueryConfig config) {
List<Expression<?>> groups = new ArrayList<Expression<?>>();
for (ConditionalCriteria criteria : conditionalCriterias) {
if (Operator.GroupBy.equals(criteria.getOperator())) {
groups.add(getExpression(criteria, root));
}
}
if (!groups.isEmpty()) {
criteriaQuery.groupBy(groups);
}
}
/**
* Map conditional criteria to type safe predicates using unchecked casts.
*
* @param criteria
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate preparePredicate(ConditionalCriteria criteria) {
CriteriaBuilder builder = getCriteriaBuilder();
Root<T> root = getRoot();
Path<?> path = getPath(root, criteria.getPropertyFullName());
ConditionalCriteria.Operator operator = criteria.getOperator();
if (Operator.Equal.equals(operator)) {
return builder.equal(path, criteria.getFirstOperant());
} else if (Operator.IgnoreCaseEqual.equals(operator)) {
return builder.equal(builder.upper(path.as(String.class)), ((String) criteria.getFirstOperant()).toUpperCase());
} else if (Operator.LessThan.equals(operator)) {
return builder.lessThan((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant());
} else if (Operator.LessThanOrEqual.equals(operator)) {
return builder.lessThanOrEqualTo((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant());
} else if (Operator.GreatThan.equals(operator)) {
return builder.greaterThan((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant());
} else if (Operator.GreatThanOrEqual.equals(operator)) {
return builder.greaterThanOrEqualTo((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant());
} else if (Operator.Like.equals(operator)) {
return builder.like((Expression<String>) path, (String) criteria.getFirstOperant());
} else if (Operator.IgnoreCaseLike.equals(operator)) {
return builder.like(builder.upper(path.as(String.class)), ((String) criteria.getFirstOperant()).toUpperCase());
} else if (Operator.IsNull.equals(operator)) {
return builder.isNull(path);
} else if (Operator.IsNotNull.equals(operator)) {
return builder.isNotNull(path);
} else if (Operator.IsEmpty.equals(operator)) {
// TODO: support additional types like Map,...
if (getAttribute(root.getModel(), criteria.getPropertyFullName()).isCollection()) {
return builder.isEmpty((Expression<Collection>)path);
} else {
return null;
}
} else if (Operator.IsNotEmpty.equals(operator)) {
// TODO: support additional types like Map,...
if (getAttribute(root.getModel(), criteria.getPropertyFullName()).isCollection()) {
return builder.isNotEmpty((Expression<Collection>)path);
} else {
return null;
}
} else if (Operator.Between.equals(operator)) {
return builder.between((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant(), (Comparable) criteria.getSecondOperant());
} else if (Operator.Not.equals(operator)) {
return builder.not(preparePredicate((ConditionalCriteria) criteria.getFirstOperant()));
} else if (Operator.Or.equals(operator) && criteria.getFirstOperant() instanceof List<?>) {
Predicate disjunction = builder.disjunction();
List<ConditionalCriteria> list = (List<ConditionalCriteria>) criteria.getFirstOperant();
for (ConditionalCriteria condition : list) {
disjunction = builder.or(disjunction, preparePredicate(condition));
}
return disjunction;
} else if (Operator.Or.equals(operator)) {
return builder.or(
preparePredicate((ConditionalCriteria) criteria.getFirstOperant()),
preparePredicate((ConditionalCriteria) criteria.getSecondOperant()));
} else if (Operator.And.equals(operator) && criteria.getFirstOperant() instanceof List<?>) {
Predicate conjunction = builder.conjunction();
List<ConditionalCriteria> list = (List<ConditionalCriteria>) criteria.getFirstOperant();
for (ConditionalCriteria condition : list) {
conjunction = builder.and(conjunction, preparePredicate(condition));
}
return conjunction;
} else if (Operator.And.equals(operator)) {
return builder.and(
preparePredicate((ConditionalCriteria) criteria.getFirstOperant()),
preparePredicate((ConditionalCriteria) criteria.getSecondOperant()));
} else if (Operator.In.equals(operator)) {
if (criteria.getFirstOperant() instanceof Collection<?>) {
return path.in((Collection<?>) criteria.getFirstOperant());
} else {
return path.in((Object[])criteria.getFirstOperant());
}
} else if (Operator.EqualProperty.equals(operator)) {
return builder.equal(path, getPath(root, (String) criteria.getFirstOperant()));
} else if (Operator.LessThanProperty.equals(operator)) {
return builder.lessThan((Expression<Comparable>) path, (Expression<Comparable>) getPath(root, (String) criteria.getFirstOperant()));
} else if (Operator.LessThanOrEqualProperty.equals(operator)) {
return builder.lessThanOrEqualTo((Expression<Comparable>) path, (Expression<Comparable>) getPath(root, (String) criteria.getFirstOperant()));
} else if (Operator.GreatThanProperty.equals(operator)) {
return builder.greaterThan((Expression<Comparable>) path, (Expression<Comparable>) getPath(root, (String) criteria.getFirstOperant()));
} else if (Operator.GreatThanOrEqualProperty.equals(operator)) {
return builder.greaterThanOrEqualTo((Expression<Comparable>) path, (Expression<Comparable>) getPath(getRoot(), (String) criteria.getFirstOperant()));
} else if (Operator.ProjectionRoot.equals(operator)) {
// TODO: support projectionRoot, if possible
if (getConfig().throwExceptionOnConfigurationError()) {
throw new QueryConfigException("Operator 'ProjectionRoot' is not supported");
}
return null;
} else if (Operator.DistinctRoot.equals(operator)) {
getConfig().setDistinct(true);
return null;
} else {
return null;
}
}
public void executeCount() {
executeResultCount();
}
}
| sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/accessimpl/jpa/JpaFindByConditionAccessImplGeneric.java | /*
* Copyright 2009 The Fornax Project Team, including the original
* author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sculptor.framework.accessimpl.jpa;
import org.sculptor.framework.accessapi.ConditionalCriteria;
import org.sculptor.framework.accessapi.ConditionalCriteria.Operator;
import org.sculptor.framework.accessapi.FindByConditionAccess2;
import org.sculptor.framework.domain.LeafProperty;
import org.sculptor.framework.domain.Property;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.FetchParent;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Selection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* <p>
* Implementation of Access command FindByConditionAccess.
* </p>
* <p>
* Command design pattern.
* </p>
*/
public class JpaFindByConditionAccessImplGeneric<T,R>
extends JpaCriteriaQueryAccessBase<T,R> implements FindByConditionAccess2<R> {
private List<ConditionalCriteria> conditionalCriterias = new ArrayList<ConditionalCriteria>();
public JpaFindByConditionAccessImplGeneric() {
super();
}
public JpaFindByConditionAccessImplGeneric(Class<T> type) {
super(type);
}
public JpaFindByConditionAccessImplGeneric(Class<T> type, Class<R> resultType) {
super(type, resultType);
}
public void setCondition(List<ConditionalCriteria> criteria) {
conditionalCriterias=criteria;
}
public void addCondition(ConditionalCriteria criteria) {
conditionalCriterias.add(criteria);
}
public List<R> getResult() {
return getListResult();
}
@Override
protected List<Predicate> preparePredicates() {
List<Predicate> predicates = new ArrayList<Predicate>();
for (ConditionalCriteria criteria : conditionalCriterias) {
Predicate predicate = preparePredicate(criteria);
if (predicate != null) {
predicates.add(predicate);
}
}
return predicates;
}
@Override
protected void prepareConfig(QueryConfig config) {
config.setDistinct(false);
}
@SuppressWarnings("unchecked")
protected void prepareSelect(CriteriaQuery<R> criteriaQuery, Root<T> root, QueryConfig config) {
List<Selection<?>> selections = new ArrayList<Selection<?>>();
for (ConditionalCriteria criteria : conditionalCriterias) {
Selection<?> selection = null;
if (Operator.Select.equals(criteria.getOperator())) {
selection = getExpression(criteria, root);
} else if (Operator.Max.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().max(getExpression(criteria, root));
} else if (Operator.Min.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().min(getExpression(criteria, root));
} else if (Operator.Avg.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().avg(getExpression(criteria,root));
} else if (Operator.Sum.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().sum(getExpression(criteria, root));
} else if (Operator.SumAsLong.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().sumAsLong(getExpression(criteria, root).as(Integer.class));
} else if (Operator.SumAsDouble.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().sumAsDouble(getExpression(criteria, root).as(Float.class));
} else if (Operator.Count.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().count(getExpression(criteria, root)).as(Long.class);
} else if (Operator.CountDistinct.equals(criteria.getOperator())) {
selection = getCriteriaBuilder().countDistinct(getExpression(criteria, root)).as(Long.class);
}
if (selection != null) {
if (criteria.getPropertyAlias() != null) {
selection.alias(criteria.getPropertyAlias());
}
selections.add(selection);
}
}
if (!selections.isEmpty()) {
setFetchEager(null);
if (selections.size() == 1)
criteriaQuery.select((Selection<? extends R>) selections.get(0));
else
criteriaQuery.multiselect(selections);
}
}
private Expression<? extends Number> getExpression(ConditionalCriteria criteria, Root<T> root) {
CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
Expression<? extends Number> result = (Expression<? extends Number>) getPath(root, criteria.getPropertyFullName());
if (criteria.getFirstOperant() instanceof ConditionalCriteria.Function) {
ConditionalCriteria.Function function = (ConditionalCriteria.Function) criteria.getFirstOperant();
if (ConditionalCriteria.Function.hour.equals(function)) {
result = criteriaBuilder.function("hour", Integer.class, result);
} else if (ConditionalCriteria.Function.day.equals(function)) {
result = criteriaBuilder.function("day", Integer.class, result);
} else if (ConditionalCriteria.Function.month.equals(function)) {
result = criteriaBuilder.function("month", Integer.class, result);
} else if (ConditionalCriteria.Function.year.equals(function)) {
result = criteriaBuilder.function("year", Integer.class, result);
} else if (ConditionalCriteria.Function.week.equals(function)) {
result = criteriaBuilder.function("week", Integer.class, result);
} else if (ConditionalCriteria.Function.quarter.equals(function)) {
result = criteriaBuilder.function("quarter", Integer.class, result);
} else if (ConditionalCriteria.Function.dayOfWeek.equals(function)) {
result = criteriaBuilder.function("dow", Integer.class, result);
} else if (ConditionalCriteria.Function.dayOfYear.equals(function)) {
result = criteriaBuilder.function("doy", Integer.class, result);
}
}
return result;
}
@Override
protected void prepareFetch(Root<T> root, QueryConfig config) {
// Extract eager field names
List<String> eagerProperties = new ArrayList<>();
Property<?>[] fetchEager = getFetchEager();
if (fetchEager != null) {
for (Property p : getFetchEager()) {
String propFullName = p instanceof LeafProperty<?> ? ((LeafProperty<?>) p).getEmbeddedName() : p.getName();
eagerProperties.add(propFullName);
}
}
// Apply eager from criteria
for (ConditionalCriteria criteria : conditionalCriterias) {
if (Operator.FetchEager.equals(criteria.getOperator())) {
// TODO: this is not tested
String[] split = criteria.getPropertyFullName().split("\\.");
FetchParent parent = root;
for (String s : split) {
parent = parent.fetch(s, JoinType.LEFT);
}
// Remove fields which are overridden in criteria
eagerProperties.remove(criteria.getPropertyFullName());
} else if (Operator.FetchLazy.equals(criteria.getOperator())) {
// TODO: fetchLazy is not supported actually
}
}
// Apply eager unspecified in criteria
for (String eager : eagerProperties) {
String[] split = eager.split("\\.");
FetchParent parent = root;
for (String s : split) {
parent = parent.fetch(s, JoinType.LEFT);
}
}
}
@Override
protected void prepareOrderBy(CriteriaQuery<R> criteriaQuery, Root<T> root, QueryConfig config) {
List<Order> orderByList = new ArrayList<Order>();
for (ConditionalCriteria criteria : conditionalCriterias) {
if (Operator.OrderAsc.equals(criteria.getOperator())) {
if (config.isDistinct()) {
// for distinct select, sort column have to be in fetch columns - otherwise DB error
orderByList.add(getCriteriaBuilder().asc(getFetchPath(root, criteria)));
} else {
orderByList.add(getCriteriaBuilder().asc(getPath(root, criteria.getPropertyFullName())));
}
} else if (Operator.OrderDesc.equals(criteria.getOperator())) {
if (config.isDistinct()) {
// for distinct select, sort column have to be in fetch columns - otherwise DB error
orderByList.add(getCriteriaBuilder().desc(getFetchPath(root, criteria)));
} else {
orderByList.add(getCriteriaBuilder().desc(getPath(root, criteria.getPropertyFullName())));
}
}
}
if (!orderByList.isEmpty()) {
criteriaQuery.orderBy(orderByList);
}
}
private Path getFetchPath(Root<T> root, ConditionalCriteria criteria) {
FetchParent from = root;
for (int i = 0; i < criteria.getPropertyPath().length; i++) {
String stringPath = criteria.getPropertyPath()[i];
Set<Fetch<?, ?>> fetches = from.getFetches();
boolean found = false;
for (Fetch<?, ?> fetch : fetches) {
if (fetch.getAttribute().getName().equals(stringPath)) {
from = (FetchParent) fetch;
found = true;
break;
}
}
if (!found) {
from = from.fetch(stringPath, JoinType.LEFT);
}
}
return ((Path) from).get(criteria.getPropertyName());
}
@Override
protected void prepareGroupBy(CriteriaQuery<R> criteriaQuery, Root<T> root, QueryConfig config) {
List<Expression<?>> groups = new ArrayList<Expression<?>>();
for (ConditionalCriteria criteria : conditionalCriterias) {
if (Operator.GroupBy.equals(criteria.getOperator())) {
groups.add(getExpression(criteria, root));
}
}
if (!groups.isEmpty()) {
criteriaQuery.groupBy(groups);
}
}
/**
* Map conditional criteria to type safe predicates using unchecked casts.
*
* @param criteria
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Predicate preparePredicate(ConditionalCriteria criteria) {
CriteriaBuilder builder = getCriteriaBuilder();
Root<T> root = getRoot();
Path<?> path = getPath(root, criteria.getPropertyFullName());
ConditionalCriteria.Operator operator = criteria.getOperator();
if (Operator.Equal.equals(operator)) {
return builder.equal(path, criteria.getFirstOperant());
} else if (Operator.IgnoreCaseEqual.equals(operator)) {
return builder.equal(builder.upper(path.as(String.class)), ((String) criteria.getFirstOperant()).toUpperCase());
} else if (Operator.LessThan.equals(operator)) {
return builder.lessThan((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant());
} else if (Operator.LessThanOrEqual.equals(operator)) {
return builder.lessThanOrEqualTo((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant());
} else if (Operator.GreatThan.equals(operator)) {
return builder.greaterThan((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant());
} else if (Operator.GreatThanOrEqual.equals(operator)) {
return builder.greaterThanOrEqualTo((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant());
} else if (Operator.Like.equals(operator)) {
return builder.like((Expression<String>) path, (String) criteria.getFirstOperant());
} else if (Operator.IgnoreCaseLike.equals(operator)) {
return builder.like(builder.upper(path.as(String.class)), ((String) criteria.getFirstOperant()).toUpperCase());
} else if (Operator.IsNull.equals(operator)) {
return builder.isNull(path);
} else if (Operator.IsNotNull.equals(operator)) {
return builder.isNotNull(path);
} else if (Operator.IsEmpty.equals(operator)) {
// TODO: support additional types like Map,...
if (getAttribute(root.getModel(), criteria.getPropertyFullName()).isCollection()) {
return builder.isEmpty((Expression<Collection>)path);
} else {
return null;
}
} else if (Operator.IsNotEmpty.equals(operator)) {
// TODO: support additional types like Map,...
if (getAttribute(root.getModel(), criteria.getPropertyFullName()).isCollection()) {
return builder.isNotEmpty((Expression<Collection>)path);
} else {
return null;
}
} else if (Operator.Between.equals(operator)) {
return builder.between((Expression<Comparable>) path, (Comparable) criteria.getFirstOperant(), (Comparable) criteria.getSecondOperant());
} else if (Operator.Not.equals(operator)) {
return builder.not(preparePredicate((ConditionalCriteria) criteria.getFirstOperant()));
} else if (Operator.Or.equals(operator) && criteria.getFirstOperant() instanceof List<?>) {
Predicate disjunction = builder.disjunction();
List<ConditionalCriteria> list = (List<ConditionalCriteria>) criteria.getFirstOperant();
for (ConditionalCriteria condition : list) {
disjunction = builder.or(disjunction, preparePredicate(condition));
}
return disjunction;
} else if (Operator.Or.equals(operator)) {
return builder.or(
preparePredicate((ConditionalCriteria) criteria.getFirstOperant()),
preparePredicate((ConditionalCriteria) criteria.getSecondOperant()));
} else if (Operator.And.equals(operator) && criteria.getFirstOperant() instanceof List<?>) {
Predicate conjunction = builder.conjunction();
List<ConditionalCriteria> list = (List<ConditionalCriteria>) criteria.getFirstOperant();
for (ConditionalCriteria condition : list) {
conjunction = builder.and(conjunction, preparePredicate(condition));
}
return conjunction;
} else if (Operator.And.equals(operator)) {
return builder.and(
preparePredicate((ConditionalCriteria) criteria.getFirstOperant()),
preparePredicate((ConditionalCriteria) criteria.getSecondOperant()));
} else if (Operator.In.equals(operator)) {
if (criteria.getFirstOperant() instanceof Collection<?>) {
return path.in((Collection<?>) criteria.getFirstOperant());
} else {
return path.in((Object[])criteria.getFirstOperant());
}
} else if (Operator.EqualProperty.equals(operator)) {
return builder.equal(path, getPath(root, (String) criteria.getFirstOperant()));
} else if (Operator.LessThanProperty.equals(operator)) {
return builder.lessThan((Expression<Comparable>) path, (Expression<Comparable>) getPath(root, (String) criteria.getFirstOperant()));
} else if (Operator.LessThanOrEqualProperty.equals(operator)) {
return builder.lessThanOrEqualTo((Expression<Comparable>) path, (Expression<Comparable>) getPath(root, (String) criteria.getFirstOperant()));
} else if (Operator.GreatThanProperty.equals(operator)) {
return builder.greaterThan((Expression<Comparable>) path, (Expression<Comparable>) getPath(root, (String) criteria.getFirstOperant()));
} else if (Operator.GreatThanOrEqualProperty.equals(operator)) {
return builder.greaterThanOrEqualTo((Expression<Comparable>) path, (Expression<Comparable>) getPath(getRoot(), (String) criteria.getFirstOperant()));
} else if (Operator.ProjectionRoot.equals(operator)) {
// TODO: support projectionRoot, if possible
if (getConfig().throwExceptionOnConfigurationError()) {
throw new QueryConfigException("Operator 'ProjectionRoot' is not supported");
}
return null;
} else if (Operator.DistinctRoot.equals(operator)) {
getConfig().setDistinct(true);
return null;
} else {
return null;
}
}
public void executeCount() {
executeResultCount();
}
}
| Eliminate hibernate error AggregationFunction$COUNT cannot be cast to CompoundSelectionImpl
| sculptor-framework/sculptor-framework-main/src/main/java/org/sculptor/framework/accessimpl/jpa/JpaFindByConditionAccessImplGeneric.java | Eliminate hibernate error AggregationFunction$COUNT cannot be cast to CompoundSelectionImpl |
|
Java | apache-2.0 | cfc07847369970a5007d32623d9d699acd2acd1b | 0 | dreedyman/Rio,dreedyman/Rio,dreedyman/Rio | /*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rioproject.resources.util;
import com.sun.jini.constants.ThrowableConstants;
import org.rioproject.deploy.ServiceBeanInstantiationException;
/**
* Utility for getting things from a Throwable
*
* @author Dennis Reedy
*/
@SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
public class ThrowableUtil {
public static Throwable getRootCause(Throwable e) {
if(e instanceof ServiceBeanInstantiationException) {
if(((ServiceBeanInstantiationException)e).getCauseExceptionDescriptor()!=null) {
ServiceBeanInstantiationException.ExceptionDescriptor exDesc =
((ServiceBeanInstantiationException)e).getCauseExceptionDescriptor();
Throwable t = new Throwable(exDesc.getMessage());
t.setStackTrace(exDesc.getStacktrace());
return t;
}
}
Throwable cause = e;
Throwable t = cause;
while(t != null) {
t = cause.getCause();
if(t != null)
cause = t;
}
return (cause);
}
public static boolean isRetryable(Throwable t) {
boolean retryable = true;
final int category = ThrowableConstants.retryable(t);
Throwable cause = getRootCause(t);
if (category == ThrowableConstants.BAD_INVOCATION ||
category == ThrowableConstants.BAD_OBJECT ||
cause instanceof java.net.ConnectException) {
retryable = false;
}
return retryable;
}
}
| rio-lib/src/main/java/org/rioproject/resources/util/ThrowableUtil.java | /*
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rioproject.resources.util;
import com.sun.jini.constants.ThrowableConstants;
import org.rioproject.deploy.ServiceBeanInstantiationException;
/**
* Utility for getting things from a Throwable
*
* @author Dennis Reedy
*/
public class ThrowableUtil {
public static Throwable getRootCause(Throwable e) {
if(e instanceof ServiceBeanInstantiationException) {
if(((ServiceBeanInstantiationException)e).getCauseExceptionDescriptor()!=null) {
ServiceBeanInstantiationException.ExceptionDescriptor exDesc =
((ServiceBeanInstantiationException)e).getCauseExceptionDescriptor();
Throwable t = new Throwable(exDesc.getMessage());
t.setStackTrace(exDesc.getStacktrace());
return t;
}
}
Throwable cause = e;
Throwable t = cause;
while(t != null) {
t = cause.getCause();
if(t != null)
cause = t;
}
return (cause);
}
public static boolean isRetryable(Throwable t) {
boolean retryable = true;
final int category = ThrowableConstants.retryable(t);
Throwable cause = getRootCause(t);
if (category == ThrowableConstants.BAD_INVOCATION ||
category == ThrowableConstants.BAD_OBJECT ||
cause instanceof java.net.ConnectException) {
retryable = false;
}
return retryable;
}
}
| Have PMD ignore throwing raw exception types
| rio-lib/src/main/java/org/rioproject/resources/util/ThrowableUtil.java | Have PMD ignore throwing raw exception types |
|
Java | apache-2.0 | 2a0e364b0a7e4f06ce7a099b3785df1b7b75ca8d | 0 | diffplug/durian-rx,diffplug/durian-rx | /*
* Copyright 2015 DiffPlug
*
* 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.diffplug.common.rx;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collector;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.diffplug.common.base.Box;
/**
* Methods for manipulating Guava's immutable collections.
* <p>
* For each Guava {@code ImmutableCollection}, (where {@code Collection} is {@code List, Set, SortedSet, Map, SortedMap}) there are two methods:
* <ul>
* <li>{@code ImmutableCollection mutateCollection(ImmutableCollection source, Consumer<MutableCollection> mutator)}</li>
* <li>{@code <T> T mutateCollectionAndReturn(Box<ImmutableCollection>, Function<MutableCollection, T> mutator)}</li>
* </ul>
* Which work like this:
* <ul>
* <li>Copy the {@code ImmutableCollection} into a new {@code MutableCollection}.</li>
* <li>Pass this {@code MutableCollection} collection to the {@code mutator}.</li>
* <li>Copy the (now-mutated) {@code MutableCollection} into a new {@code ImmutableCollection}.</li>
* <li>The return value is:
* <ul>
* <li>{@code mutateCollection}: the mutated {@code ImmutableCollection} is returned.</li>
* <li>{@code mutateCollectionAndReturn}: the mutated {@code ImmutableCollection} is set into the supplied {@code box}, and the return value of the {@code mutator} is returned.</li>
* </ul>
* </ul>
* <p>
* There are also {@code Function<ImmutableCollection, ImmutableCollection> mutateCollection(Consumer<MutableCollection> mutator)}
* methods for each type, to easily create functions which operate on immutable collections.
* <p>
* This class also contains the simple {@link #optionalToSet} and {@link #optionalFrom(ImmutableSet)} methods.
*/
public class Immutables {
private Immutables() {}
////////////
// Mutate //
////////////
/** Returns a mutated version of the given list. */
public static <T> ImmutableList<T> mutateList(ImmutableList<T> source, Consumer<List<T>> mutator) {
List<T> mutable = new ArrayList<>(source);
mutator.accept(mutable);
return ImmutableList.copyOf(mutable);
}
/** Returns a mutated version of the given set. */
public static <T> ImmutableSet<T> mutateSet(ImmutableSet<T> source, Consumer<Set<T>> mutator) {
Set<T> mutable = new LinkedHashSet<>(source);
mutator.accept(mutable);
return ImmutableSet.copyOf(mutable);
}
/** Returns a mutated version of the given sorted set. */
public static <T> ImmutableSortedSet<T> mutateSortedSet(ImmutableSortedSet<T> source, Consumer<NavigableSet<T>> mutator) {
NavigableSet<T> mutable = new TreeSet<>(source);
mutator.accept(mutable);
return ImmutableSortedSet.copyOfSorted(mutable);
}
/** Returns a mutated version of the given map. */
public static <K, V> ImmutableMap<K, V> mutateMap(ImmutableMap<K, V> source, Consumer<Map<K, V>> mutator) {
Map<K, V> mutable = new LinkedHashMap<>(source);
mutator.accept(mutable);
return ImmutableMap.copyOf(mutable);
}
/** Returns a mutated version of the given sorted map. */
public static <K, V> ImmutableSortedMap<K, V> mutateSortedMap(ImmutableSortedMap<K, V> source, Consumer<NavigableMap<K, V>> mutator) {
NavigableMap<K, V> mutable = new TreeMap<>(source);
mutator.accept(mutable);
return ImmutableSortedMap.copyOfSorted(mutable);
}
/////////////
// Mutator //
/////////////
/** Returns a function which mutates a list using the given mutator. */
public static <T> UnaryOperator<ImmutableList<T>> mutatorList(Consumer<List<T>> mutator) {
return input -> mutateList(input, mutator);
}
/** Returns a function which mutates a set using the given mutator. */
public static <T> UnaryOperator<ImmutableSet<T>> mutatorSet(Consumer<Set<T>> mutator) {
return input -> mutateSet(input, mutator);
}
/** Returns a function which mutates a sorted set using the given mutator. */
public static <T> UnaryOperator<ImmutableSortedSet<T>> mutatorSortedSet(Consumer<NavigableSet<T>> mutator) {
return input -> mutateSortedSet(input, mutator);
}
/** Returns a function which mutates a map using the given mutator. */
public static <K, V> UnaryOperator<ImmutableMap<K, V>> mutatorMap(Consumer<Map<K, V>> mutator) {
return input -> mutateMap(input, mutator);
}
/** Returns a function which mutates a sorted map using the given mutator. */
public static <K, V> UnaryOperator<ImmutableSortedMap<K, V>> mutatorSortedMap(Consumer<NavigableMap<K, V>> mutator) {
return input -> mutateSortedMap(input, mutator);
}
///////////////////////
// Mutate and return //
///////////////////////
/** Mutates the given list and returns a value. */
public static <T, R> R mutateListAndReturn(Box<ImmutableList<T>> box, Function<List<T>, R> mutator) {
List<T> mutable = new ArrayList<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableList.copyOf(mutable));
return returnValue;
}
/** Mutates the given set and returns a value. */
public static <T, R> R mutateSetAndReturn(Box<ImmutableSet<T>> box, Function<Set<T>, R> mutator) {
Set<T> mutable = new LinkedHashSet<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableSet.copyOf(mutable));
return returnValue;
}
/** Mutates the given sorted set and returns a value. */
public static <T, R> R mutateSortedSetAndReturn(Box<ImmutableSortedSet<T>> box, Function<NavigableSet<T>, R> mutator) {
NavigableSet<T> mutable = new TreeSet<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableSortedSet.copyOfSorted(mutable));
return returnValue;
}
/** Mutates the given map and returns a value. */
public static <K, V, R> R mutateMapAndReturn(Box<ImmutableMap<K, V>> box, Function<Map<K, V>, R> mutator) {
Map<K, V> mutable = new LinkedHashMap<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableMap.copyOf(mutable));
return returnValue;
}
/** Mutates the given sorted map and returns a value. */
public static <K, V, R> R mutateSortedMapAndReturn(Box<ImmutableSortedMap<K, V>> box, Function<NavigableMap<K, V>, R> mutator) {
NavigableMap<K, V> mutable = new TreeMap<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableSortedMap.copyOfSorted(mutable));
return returnValue;
}
//////////////////////
// Optional <-> Stuff //
//////////////////////
/** Converts an {@link Optional} to an {@link ImmutableSet}. */
public static <T> ImmutableSet<T> optionalToSet(Optional<T> selection) {
if (selection.isPresent()) {
return ImmutableSet.of(selection.get());
} else {
return ImmutableSet.of();
}
}
/**
* Converts an {@link ImmutableCollection} to an {@link Optional}.
* @throws IllegalArgumentException if there are multiple elements.
*/
public static <T> Optional<T> optionalFrom(ImmutableCollection<T> collection) {
if (collection.size() == 0) {
return Optional.empty();
} else if (collection.size() == 1) {
return Optional.of(collection.iterator().next());
} else {
throw new IllegalArgumentException("Collection contains multiple elements.");
}
}
///////////////////////
// Java 8 Collectors //
///////////////////////
// Inspired by http://blog.comsysto.com/2014/11/12/java-8-collectors-for-guava-collections/
/** A Collector which returns an ImmutableList. */
public static <T> Collector<T, ?, ImmutableList<T>> toList() {
// called for each combiner element (once if single-threaded, multiple if parallel)
Supplier<ImmutableList.Builder<T>> supplier = ImmutableList::builder;
// called for every element in the stream
BiConsumer<ImmutableList.Builder<T>, T> accumulator = (b, v) -> b.add(v);
// combines multiple collectors for parallel streams
BinaryOperator<ImmutableList.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
// converts the builder into the list
Function<ImmutableList.Builder<T>, ImmutableList<T>> finisher = ImmutableList.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/** A Collector which returns an ImmutableSet. */
public static <T> Collector<T, ?, ImmutableSet<T>> toSet() {
Supplier<ImmutableSet.Builder<T>> supplier = ImmutableSet::builder;
BiConsumer<ImmutableSet.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableSet.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher = ImmutableSet.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/** A Collector of Comparables which returns an ImmutableSortedSet. */
public static <T extends Comparable<?>> Collector<T, ?, ImmutableSortedSet<T>> toSortedSet() {
return toSortedSetImp(ImmutableSortedSet::naturalOrder);
}
/** A Collector which returns an ImmutableSortedSet which is ordered by the given comparator. */
public static <T> Collector<T, ?, ImmutableSortedSet<T>> toSortedSet(Comparator<T> comparator) {
return toSortedSetImp(() -> ImmutableSortedSet.orderedBy(comparator));
}
private static <T> Collector<T, ?, ImmutableSortedSet<T>> toSortedSetImp(Supplier<ImmutableSortedSet.Builder<T>> supplier) {
BiConsumer<ImmutableSortedSet.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableSortedSet.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableSortedSet.Builder<T>, ImmutableSortedSet<T>> finisher = ImmutableSortedSet.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/** A Collector which returns an ImmutableMap using the given pair of key and value functions. */
public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableMap.Builder<K, V>> supplier = ImmutableMap::builder;
BiConsumer<ImmutableMap.Builder<K, V>, T> accumulator = (b, v) -> b.put(keyMapper.apply(v), valueMapper.apply(v));
BinaryOperator<ImmutableMap.Builder<K, V>> combiner = (l, r) -> l.putAll(r.build());
Function<ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> finisher = ImmutableMap.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/** A Collector which returns an ImmutableSortedMap which is populated by the given pair of key and value functions. */
public static <T, K extends Comparable<?>, V> Collector<T, ?, ImmutableSortedMap<K, V>> toSortedMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableSortedMap.Builder<K, V>> supplier = ImmutableSortedMap::naturalOrder;
return toSortedMap(supplier, keyMapper, valueMapper);
}
/** A Collector which returns an ImmutableSortedMap which is ordered by the given comparator, and populated by the given pair of key and value functions. */
public static <T, K extends Comparable<?>, V> Collector<T, ?, ImmutableSortedMap<K, V>> toSortedMap(Comparator<K> comparator, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableSortedMap.Builder<K, V>> supplier = () -> ImmutableSortedMap.orderedBy(comparator);
return toSortedMap(supplier, keyMapper, valueMapper);
}
private static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toSortedMap(Supplier<ImmutableSortedMap.Builder<K, V>> supplier, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
BiConsumer<ImmutableSortedMap.Builder<K, V>, T> accumulator = (b, v) -> b.put(keyMapper.apply(v), valueMapper.apply(v));
BinaryOperator<ImmutableSortedMap.Builder<K, V>> combiner = (l, r) -> l.putAll(r.build());
Function<ImmutableSortedMap.Builder<K, V>, ImmutableSortedMap<K, V>> finisher = ImmutableSortedMap.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
}
| src/com/diffplug/common/rx/Immutables.java | /*
* Copyright 2015 DiffPlug
*
* 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.diffplug.common.rx;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collector;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.diffplug.common.base.Box;
/**
* Methods for manipulating Guava's immutable collections.
* <p>
* For each Guava {@code ImmutableCollection}, (where {@code Collection} is {@code List, Set, SortedSet, Map, SortedMap}) there are two methods:
* <ul>
* <li>{@code ImmutableCollection mutateCollection(ImmutableCollection source, Consumer<MutableCollection> mutator)}</li>
* <li>{@code <T> T mutateCollectionAndReturn(Box<ImmutableCollection>, Function<MutableCollection, T> mutator)}</li>
* </ul>
* Which work like this:
* <ul>
* <li>Copy the {@code ImmutableCollection} into a new {@code MutableCollection}.</li>
* <li>Pass this {@code MutableCollection} collection to the {@code mutator}.</li>
* <li>Copy the (now-mutated) {@code MutableCollection} into a new {@code ImmutableCollection}.</li>
* <li>The return value is:
* <ul>
* <li>{@code mutateCollection}: the mutated {@code ImmutableCollection} is returned.</li>
* <li>{@code mutateCollectionAndReturn}: the mutated {@code ImmutableCollection} is set into the supplied {@code box}, and the return value of the {@code mutator} is returned.</li>
* </ul>
* </ul>
* <p>
* This class also contains the simple {@link #optionalToSet} and {@link #optionalFrom(ImmutableSet)} methods.
*/
public class Immutables {
private Immutables() {}
////////////
// Mutate //
////////////
/** Returns a mutated version of the given list. */
public static <T> ImmutableList<T> mutateList(ImmutableList<T> source, Consumer<List<T>> mutator) {
List<T> mutable = new ArrayList<>(source);
mutator.accept(mutable);
return ImmutableList.copyOf(mutable);
}
/** Returns a mutated version of the given set. */
public static <T> ImmutableSet<T> mutateSet(ImmutableSet<T> source, Consumer<Set<T>> mutator) {
Set<T> mutable = new LinkedHashSet<>(source);
mutator.accept(mutable);
return ImmutableSet.copyOf(mutable);
}
/** Returns a mutated version of the given sorted set. */
public static <T> ImmutableSortedSet<T> mutateSortedSet(ImmutableSortedSet<T> source, Consumer<NavigableSet<T>> mutator) {
NavigableSet<T> mutable = new TreeSet<>(source);
mutator.accept(mutable);
return ImmutableSortedSet.copyOfSorted(mutable);
}
/** Returns a mutated version of the given map. */
public static <K, V> ImmutableMap<K, V> mutateMap(ImmutableMap<K, V> source, Consumer<Map<K, V>> mutator) {
Map<K, V> mutable = new LinkedHashMap<>(source);
mutator.accept(mutable);
return ImmutableMap.copyOf(mutable);
}
/** Returns a mutated version of the given sorted map. */
public static <K, V> ImmutableSortedMap<K, V> mutateSortedMap(ImmutableSortedMap<K, V> source, Consumer<NavigableMap<K, V>> mutator) {
NavigableMap<K, V> mutable = new TreeMap<>(source);
mutator.accept(mutable);
return ImmutableSortedMap.copyOfSorted(mutable);
}
/////////////
// Mutator //
/////////////
/** Returns a function which mutates a list using the given mutator. */
public static <T> UnaryOperator<ImmutableList<T>> mutatorList(Consumer<List<T>> mutator) {
return input -> mutateList(input, mutator);
}
/** Returns a function which mutates a set using the given mutator. */
public static <T> UnaryOperator<ImmutableSet<T>> mutatorSet(Consumer<Set<T>> mutator) {
return input -> mutateSet(input, mutator);
}
/** Returns a function which mutates a sorted set using the given mutator. */
public static <T> UnaryOperator<ImmutableSortedSet<T>> mutatorSortedSet(Consumer<NavigableSet<T>> mutator) {
return input -> mutateSortedSet(input, mutator);
}
/** Returns a function which mutates a map using the given mutator. */
public static <K, V> UnaryOperator<ImmutableMap<K, V>> mutatorMap(Consumer<Map<K, V>> mutator) {
return input -> mutateMap(input, mutator);
}
/** Returns a function which mutates a sorted map using the given mutator. */
public static <K, V> UnaryOperator<ImmutableSortedMap<K, V>> mutatorSortedMap(Consumer<NavigableMap<K, V>> mutator) {
return input -> mutateSortedMap(input, mutator);
}
///////////////////////
// Mutate and return //
///////////////////////
/** Mutates the given list and returns a value. */
public static <T, R> R mutateListAndReturn(Box<ImmutableList<T>> box, Function<List<T>, R> mutator) {
List<T> mutable = new ArrayList<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableList.copyOf(mutable));
return returnValue;
}
/** Mutates the given set and returns a value. */
public static <T, R> R mutateSetAndReturn(Box<ImmutableSet<T>> box, Function<Set<T>, R> mutator) {
Set<T> mutable = new LinkedHashSet<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableSet.copyOf(mutable));
return returnValue;
}
/** Mutates the given sorted set and returns a value. */
public static <T, R> R mutateSortedSetAndReturn(Box<ImmutableSortedSet<T>> box, Function<NavigableSet<T>, R> mutator) {
NavigableSet<T> mutable = new TreeSet<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableSortedSet.copyOfSorted(mutable));
return returnValue;
}
/** Mutates the given map and returns a value. */
public static <K, V, R> R mutateMapAndReturn(Box<ImmutableMap<K, V>> box, Function<Map<K, V>, R> mutator) {
Map<K, V> mutable = new LinkedHashMap<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableMap.copyOf(mutable));
return returnValue;
}
/** Mutates the given sorted map and returns a value. */
public static <K, V, R> R mutateSortedMapAndReturn(Box<ImmutableSortedMap<K, V>> box, Function<NavigableMap<K, V>, R> mutator) {
NavigableMap<K, V> mutable = new TreeMap<>(box.get());
R returnValue = mutator.apply(mutable);
box.set(ImmutableSortedMap.copyOfSorted(mutable));
return returnValue;
}
//////////////////////
// Optional <-> Stuff //
//////////////////////
/** Converts an {@link Optional} to an {@link ImmutableSet}. */
public static <T> ImmutableSet<T> optionalToSet(Optional<T> selection) {
if (selection.isPresent()) {
return ImmutableSet.of(selection.get());
} else {
return ImmutableSet.of();
}
}
/**
* Converts an {@link ImmutableCollection} to an {@link Optional}.
* @throws IllegalArgumentException if there are multiple elements.
*/
public static <T> Optional<T> optionalFrom(ImmutableCollection<T> collection) {
if (collection.size() == 0) {
return Optional.empty();
} else if (collection.size() == 1) {
return Optional.of(collection.iterator().next());
} else {
throw new IllegalArgumentException("Collection contains multiple elements.");
}
}
///////////////////////
// Java 8 Collectors //
///////////////////////
// Inspired by http://blog.comsysto.com/2014/11/12/java-8-collectors-for-guava-collections/
/** A Collector which returns an ImmutableList. */
public static <T> Collector<T, ?, ImmutableList<T>> toList() {
// called for each combiner element (once if single-threaded, multiple if parallel)
Supplier<ImmutableList.Builder<T>> supplier = ImmutableList::builder;
// called for every element in the stream
BiConsumer<ImmutableList.Builder<T>, T> accumulator = (b, v) -> b.add(v);
// combines multiple collectors for parallel streams
BinaryOperator<ImmutableList.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
// converts the builder into the list
Function<ImmutableList.Builder<T>, ImmutableList<T>> finisher = ImmutableList.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/** A Collector which returns an ImmutableSet. */
public static <T> Collector<T, ?, ImmutableSet<T>> toSet() {
Supplier<ImmutableSet.Builder<T>> supplier = ImmutableSet::builder;
BiConsumer<ImmutableSet.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableSet.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher = ImmutableSet.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/** A Collector of Comparables which returns an ImmutableSortedSet. */
public static <T extends Comparable<?>> Collector<T, ?, ImmutableSortedSet<T>> toSortedSet() {
return toSortedSetImp(ImmutableSortedSet::naturalOrder);
}
/** A Collector which returns an ImmutableSortedSet which is ordered by the given comparator. */
public static <T> Collector<T, ?, ImmutableSortedSet<T>> toSortedSet(Comparator<T> comparator) {
return toSortedSetImp(() -> ImmutableSortedSet.orderedBy(comparator));
}
private static <T> Collector<T, ?, ImmutableSortedSet<T>> toSortedSetImp(Supplier<ImmutableSortedSet.Builder<T>> supplier) {
BiConsumer<ImmutableSortedSet.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableSortedSet.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableSortedSet.Builder<T>, ImmutableSortedSet<T>> finisher = ImmutableSortedSet.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/** A Collector which returns an ImmutableMap using the given pair of key and value functions. */
public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableMap.Builder<K, V>> supplier = ImmutableMap::builder;
BiConsumer<ImmutableMap.Builder<K, V>, T> accumulator = (b, v) -> b.put(keyMapper.apply(v), valueMapper.apply(v));
BinaryOperator<ImmutableMap.Builder<K, V>> combiner = (l, r) -> l.putAll(r.build());
Function<ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> finisher = ImmutableMap.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/** A Collector which returns an ImmutableSortedMap which is populated by the given pair of key and value functions. */
public static <T, K extends Comparable<?>, V> Collector<T, ?, ImmutableSortedMap<K, V>> toSortedMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableSortedMap.Builder<K, V>> supplier = ImmutableSortedMap::naturalOrder;
return toSortedMap(supplier, keyMapper, valueMapper);
}
/** A Collector which returns an ImmutableSortedMap which is ordered by the given comparator, and populated by the given pair of key and value functions. */
public static <T, K extends Comparable<?>, V> Collector<T, ?, ImmutableSortedMap<K, V>> toSortedMap(Comparator<K> comparator, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableSortedMap.Builder<K, V>> supplier = () -> ImmutableSortedMap.orderedBy(comparator);
return toSortedMap(supplier, keyMapper, valueMapper);
}
private static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toSortedMap(Supplier<ImmutableSortedMap.Builder<K, V>> supplier, Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
BiConsumer<ImmutableSortedMap.Builder<K, V>, T> accumulator = (b, v) -> b.put(keyMapper.apply(v), valueMapper.apply(v));
BinaryOperator<ImmutableSortedMap.Builder<K, V>> combiner = (l, r) -> l.putAll(r.build());
Function<ImmutableSortedMap.Builder<K, V>, ImmutableSortedMap<K, V>> finisher = ImmutableSortedMap.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
}
| Added javadoc for the new mutator methods. | src/com/diffplug/common/rx/Immutables.java | Added javadoc for the new mutator methods. |
|
Java | apache-2.0 | b34a4db35546d8fffa808f55fa525dae5f23fb18 | 0 | apache/jmeter,apache/jmeter,benbenw/jmeter,apache/jmeter,ham1/jmeter,benbenw/jmeter,etnetera/jmeter,etnetera/jmeter,ham1/jmeter,apache/jmeter,etnetera/jmeter,etnetera/jmeter,ham1/jmeter,apache/jmeter,benbenw/jmeter,ham1/jmeter,etnetera/jmeter,ham1/jmeter,benbenw/jmeter | /*
* Copyright 2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.jmeter.extractor;
import java.io.Serializable;
import org.apache.jmeter.processor.PostProcessor;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testbeans.TestBean;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.BeanShellInterpreter;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JMeterException;
import org.apache.log.Logger;
public class BeanShellPostProcessor extends AbstractTestElement implements PostProcessor, Serializable, TestBean {
private static final Logger log = LoggingManager.getLoggerForClass();
private static final long serialVersionUID = 2;
private String script;
transient private BeanShellInterpreter bshInterpreter = null;
// can be specified in jmeter.properties
private static final String INIT_FILE = "beanshell.postprocessor.init"; //$NON-NLS-1$
public BeanShellPostProcessor() {
super();
init();
}
private void init() {
try {
bshInterpreter = new BeanShellInterpreter(JMeterUtils.getProperty(INIT_FILE),log);
} catch (ClassNotFoundException e) {
log.error(e.getLocalizedMessage());
}
}
private Object readResolve() {
init();
return this;
}
public void process() {
JMeterContext jmctx = JMeterContextService.getContext();
SampleResult prev = jmctx.getPreviousResult();
if (prev == null || prev.getResponseData().length == 0) {
return;
}
JMeterVariables vars = jmctx.getVariables();
try {
// Add variables for access to context and variables
bshInterpreter.set("ctx", jmctx);//$NON-NLS-1$
bshInterpreter.set("vars", vars);//$NON-NLS-1$
bshInterpreter.set("prev", prev);//$NON-NLS-1$
bshInterpreter.set("data", prev.getResponseData());//$NON-NLS-1$
bshInterpreter.eval(script);
} catch (JMeterException e) {
log.warn("Problem in BeanShell script "+e);
}
}
public Object clone() {
BeanShellPostProcessor o = (BeanShellPostProcessor) super.clone();
o.script = script;
return o;
}
public String getScript(){
return script;
}
public void setScript(String s){
script=s;
}
}
| src/components/org/apache/jmeter/extractor/BeanShellPostProcessor.java | /*
* Copyright 2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.jmeter.extractor;
import java.io.Serializable;
import org.apache.jmeter.processor.PostProcessor;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testbeans.TestBean;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.BeanShellInterpreter;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JMeterException;
import org.apache.log.Logger;
public class BeanShellPostProcessor extends AbstractTestElement implements PostProcessor, Serializable, TestBean {
private static final Logger log = LoggingManager.getLoggerForClass();
private static final long serialVersionUID = 2;
private String script;
transient private BeanShellInterpreter bshInterpreter = null;
// can be specified in jmeter.properties
private static final String INIT_FILE = "beanshell.postprocessor.init"; //$NON-NLS-1$
public BeanShellPostProcessor() throws ClassNotFoundException {
super();
bshInterpreter = new BeanShellInterpreter(JMeterUtils.getProperty(INIT_FILE),log);
}
public void process() {
JMeterContext jmctx = JMeterContextService.getContext();
SampleResult prev = jmctx.getPreviousResult();
if (prev == null || prev.getResponseData().length == 0) {
return;
}
JMeterVariables vars = jmctx.getVariables();
try {
// Add variables for access to context and variables
bshInterpreter.set("ctx", jmctx);//$NON-NLS-1$
bshInterpreter.set("vars", vars);//$NON-NLS-1$
bshInterpreter.set("prev", prev);//$NON-NLS-1$
bshInterpreter.set("data", prev.getResponseData());//$NON-NLS-1$
bshInterpreter.eval(script);
} catch (JMeterException e) {
log.warn("Problem in BeanShell script "+e);
}
}
public Object clone() {
BeanShellPostProcessor o = (BeanShellPostProcessor) super.clone();
o.script = script;
return o;
}
public String getScript(){
return script;
}
public void setScript(String s){
script=s;
}
}
| Ensure the transient object is recreated by the server
git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/branches/rel-2-1@391725 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: 72efb762502e8ffbc7bff9035610a87560823935 | src/components/org/apache/jmeter/extractor/BeanShellPostProcessor.java | Ensure the transient object is recreated by the server |
|
Java | apache-2.0 | 6c6d9a841a44444577c166e5b8724aaf9152afc1 | 0 | BellaDati/belladati-sdk-java | package com.belladati.sdk.util.impl;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.http.client.utils.URIBuilder;
import com.belladati.sdk.exception.InternalConfigurationException;
import com.belladati.sdk.impl.BellaDatiServiceImpl;
import com.belladati.sdk.util.PaginatedList;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
public abstract class PaginatedListImpl<T> implements PaginatedList<T> {
protected final List<T> currentData = new ArrayList<T>();
private final BellaDatiServiceImpl service;
private final String relativeUrl;
private final String field;
/** The first page loaded during the most recent call to a load() method */
private int firstPage = -1;
/** The most recent page loaded */
private int page = -1;
/** The page size currently used by this instance */
private int size = -1;
public PaginatedListImpl(BellaDatiServiceImpl service, String relativeUrl, String field) {
this.service = service;
this.relativeUrl = relativeUrl;
this.field = field;
}
@Override
public Iterator<T> iterator() {
return currentData.iterator();
}
@Override
public PaginatedList<T> load() {
return loadFrom(relativeUrl);
}
@Override
public PaginatedList<T> load(int size) throws IllegalArgumentException {
return load(0, size);
}
@Override
public PaginatedList<T> load(int page, int size) throws IllegalArgumentException {
// argument checking
if (page < 0) {
throw new IllegalArgumentException("Page must be >= 0, was " + page);
}
if (size <= 0) {
throw new IllegalArgumentException("Size must be > 0, was " + size);
}
// query parameterized URL
return loadFrom(buildUri(page, size).toString());
}
private URI buildUri(int page, int size) {
try {
return new URIBuilder(relativeUrl).addParameter("offset", "" + page * size).addParameter("size", "" + size).build();
} catch (URISyntaxException e) {
throw new InternalConfigurationException("Invalid URI", e);
}
}
private PaginatedList<T> loadFrom(String parameterizedUri) {
currentData.clear();
addFrom(parameterizedUri);
firstPage = page;
return this;
}
private PaginatedList<T> addFrom(String parameterizedUri) {
JsonNode json = service.getAsJson(parameterizedUri);
size = json.get("size").asInt();
page = size == 0 ? 0 : json.get("offset").asInt() / size;
ArrayNode nodes = (ArrayNode) json.get(field);
for (JsonNode node : nodes) {
currentData.add(parse(service, node));
}
return this;
}
@Override
public PaginatedList<T> loadNext() {
if (!isLoaded()) {
// if we haven't loaded this list yet, load the first page
return load();
}
if (!hasNextPage()) {
// there are no more pages to load
return this;
}
return addFrom(buildUri(page + 1, size).toString());
}
@Override
public boolean isLoaded() {
return size > 0 && page >= 0;
}
@Override
public boolean hasNextPage() {
if (!isLoaded()) {
return true;
}
// if all pages until now were full, we have more items
return size * (page - firstPage + 1) == currentData.size();
}
@Override
public int getFirstLoadedPage() {
if (!isLoaded()) {
return -1;
}
return firstPage;
}
@Override
public int getLastLoadedPage() {
if (!isLoaded()) {
return -1;
}
return page;
}
@Override
public int getFirstLoadedIndex() {
if (!isLoaded() || currentData.isEmpty()) {
return -1;
}
return firstPage * size;
}
@Override
public int getLastLoadedIndex() {
if (!isLoaded() || currentData.isEmpty()) {
return -1;
}
return getFirstLoadedIndex() + currentData.size() - 1;
}
@Override
public int getPageSize() {
return size;
}
@Override
public boolean contains(T element) {
return currentData.contains(element);
}
@Override
public T get(int index) throws IndexOutOfBoundsException {
return currentData.get(index - getFirstLoadedIndex());
}
@Override
public int indexOf(T element) {
int dataIndex = currentData.indexOf(element);
if (dataIndex < 0) {
return -1;
}
return getFirstLoadedIndex() + dataIndex;
}
@Override
public boolean isEmpty() {
return currentData.isEmpty();
}
@Override
public int size() {
return currentData.size();
}
@Override
public List<T> toList() {
return Collections.unmodifiableList(currentData);
}
@Override
public String toString() {
return currentData.toString();
}
protected abstract T parse(BellaDatiServiceImpl service, JsonNode node);
}
| src/main/java/com/belladati/sdk/util/impl/PaginatedListImpl.java | package com.belladati.sdk.util.impl;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.http.client.utils.URIBuilder;
import com.belladati.sdk.exception.InternalConfigurationException;
import com.belladati.sdk.impl.BellaDatiServiceImpl;
import com.belladati.sdk.util.PaginatedList;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
public abstract class PaginatedListImpl<T> implements PaginatedList<T> {
protected final List<T> currentData = new ArrayList<T>();
private final BellaDatiServiceImpl service;
private final String relativeUrl;
private final String field;
/** The first page loaded during the most recent call to a load() method */
private int firstPage = -1;
/** The most recent page loaded */
private int page = -1;
/** The page size currently used by this instance */
private int size = -1;
public PaginatedListImpl(BellaDatiServiceImpl service, String relativeUrl, String field) {
this.service = service;
this.relativeUrl = relativeUrl;
this.field = field;
}
@Override
public Iterator<T> iterator() {
return currentData.iterator();
}
@Override
public PaginatedList<T> load() {
return loadFrom(relativeUrl);
}
@Override
public PaginatedList<T> load(int size) throws IllegalArgumentException {
return load(0, size);
}
@Override
public PaginatedList<T> load(int page, int size) throws IllegalArgumentException {
// argument checking
if (page < 0) {
throw new IllegalArgumentException("Page must be >= 0, was " + page);
}
if (size <= 0) {
throw new IllegalArgumentException("Size must be > 0, was " + size);
}
// query parameterized URL
return loadFrom(buildUri(page, size).toString());
}
private URI buildUri(int page, int size) {
try {
return new URIBuilder(relativeUrl).addParameter("offset", "" + page * size).addParameter("size", "" + size).build();
} catch (URISyntaxException e) {
throw new InternalConfigurationException("Invalid URI", e);
}
}
private PaginatedList<T> loadFrom(String parameterizedUri) {
currentData.clear();
addFrom(parameterizedUri);
firstPage = page;
return this;
}
private PaginatedList<T> addFrom(String parameterizedUri) {
JsonNode json = service.getAsJson(parameterizedUri);
size = json.get("size").asInt();
page = json.get("offset").asInt() / size;
ArrayNode nodes = (ArrayNode) json.get(field);
for (JsonNode node : nodes) {
currentData.add(parse(service, node));
}
return this;
}
@Override
public PaginatedList<T> loadNext() {
if (!isLoaded()) {
// if we haven't loaded this list yet, load the first page
return load();
}
if (!hasNextPage()) {
// there are no more pages to load
return this;
}
return addFrom(buildUri(page + 1, size).toString());
}
@Override
public boolean isLoaded() {
return size > 0 && page >= 0;
}
@Override
public boolean hasNextPage() {
if (!isLoaded()) {
return true;
}
// if all pages until now were full, we have more items
return size * (page - firstPage + 1) == currentData.size();
}
@Override
public int getFirstLoadedPage() {
if (!isLoaded()) {
return -1;
}
return firstPage;
}
@Override
public int getLastLoadedPage() {
if (!isLoaded()) {
return -1;
}
return page;
}
@Override
public int getFirstLoadedIndex() {
if (!isLoaded() || currentData.isEmpty()) {
return -1;
}
return firstPage * size;
}
@Override
public int getLastLoadedIndex() {
if (!isLoaded() || currentData.isEmpty()) {
return -1;
}
return getFirstLoadedIndex() + currentData.size() - 1;
}
@Override
public int getPageSize() {
return size;
}
@Override
public boolean contains(T element) {
return currentData.contains(element);
}
@Override
public T get(int index) throws IndexOutOfBoundsException {
return currentData.get(index - getFirstLoadedIndex());
}
@Override
public int indexOf(T element) {
int dataIndex = currentData.indexOf(element);
if (dataIndex < 0) {
return -1;
}
return getFirstLoadedIndex() + dataIndex;
}
@Override
public boolean isEmpty() {
return currentData.isEmpty();
}
@Override
public int size() {
return currentData.size();
}
@Override
public List<T> toList() {
return Collections.unmodifiableList(currentData);
}
@Override
public String toString() {
return currentData.toString();
}
protected abstract T parse(BellaDatiServiceImpl service, JsonNode node);
}
| NO_TICKET - Preventing division by 0
| src/main/java/com/belladati/sdk/util/impl/PaginatedListImpl.java | NO_TICKET - Preventing division by 0 |
|
Java | apache-2.0 | 21c608389c7a4b64458e7fdd0feefbec2d13c303 | 0 | likaiwalkman/spring-security,driftman/spring-security,jgrandja/spring-security,wkorando/spring-security,spring-projects/spring-security,djechelon/spring-security,xingguang2013/spring-security,zshift/spring-security,mrkingybc/spring-security,diegofernandes/spring-security,justinedelson/spring-security,rwinch/spring-security,follow99/spring-security,djechelon/spring-security,Xcorpio/spring-security,cyratech/spring-security,fhanik/spring-security,pwheel/spring-security,olezhuravlev/spring-security,liuguohua/spring-security,wilkinsona/spring-security,cyratech/spring-security,ajdinhedzic/spring-security,eddumelendez/spring-security,raindev/spring-security,thomasdarimont/spring-security,pkdevbox/spring-security,jmnarloch/spring-security,zshift/spring-security,likaiwalkman/spring-security,jgrandja/spring-security,olezhuravlev/spring-security,mparaz/spring-security,mdeinum/spring-security,djechelon/spring-security,jgrandja/spring-security,spring-projects/spring-security,pkdevbox/spring-security,chinazhaoht/spring-security,Xcorpio/spring-security,kazuki43zoo/spring-security,mparaz/spring-security,mdeinum/spring-security,adairtaosy/spring-security,Krasnyanskiy/spring-security,zgscwjm/spring-security,mparaz/spring-security,justinedelson/spring-security,follow99/spring-security,driftman/spring-security,diegofernandes/spring-security,kazuki43zoo/spring-security,wilkinsona/spring-security,dsyer/spring-security,forestqqqq/spring-security,mdeinum/spring-security,MatthiasWinzeler/spring-security,adairtaosy/spring-security,SanjayUser/SpringSecurityPro,eddumelendez/spring-security,SanjayUser/SpringSecurityPro,ractive/spring-security,liuguohua/spring-security,jgrandja/spring-security,raindev/spring-security,eddumelendez/spring-security,hippostar/spring-security,adairtaosy/spring-security,tekul/spring-security,vitorgv/spring-security,Xcorpio/spring-security,Xcorpio/spring-security,ractive/spring-security,fhanik/spring-security,thomasdarimont/spring-security,mounb/spring-security,tekul/spring-security,wkorando/spring-security,djechelon/spring-security,thomasdarimont/spring-security,rwinch/spring-security,thomasdarimont/spring-security,forestqqqq/spring-security,dsyer/spring-security,mrkingybc/spring-security,jmnarloch/spring-security,yinhe402/spring-security,panchenko/spring-security,caiwenshu/spring-security,forestqqqq/spring-security,wkorando/spring-security,likaiwalkman/spring-security,olezhuravlev/spring-security,izeye/spring-security,Peter32/spring-security,diegofernandes/spring-security,eddumelendez/spring-security,ajdinhedzic/spring-security,mparaz/spring-security,yinhe402/spring-security,liuguohua/spring-security,dsyer/spring-security,diegofernandes/spring-security,izeye/spring-security,fhanik/spring-security,driftman/spring-security,thomasdarimont/spring-security,zhaoqin102/spring-security,Krasnyanskiy/spring-security,panchenko/spring-security,xingguang2013/spring-security,spring-projects/spring-security,follow99/spring-security,ollie314/spring-security,caiwenshu/spring-security,xingguang2013/spring-security,fhanik/spring-security,tekul/spring-security,olezhuravlev/spring-security,vitorgv/spring-security,kazuki43zoo/spring-security,Peter32/spring-security,cyratech/spring-security,caiwenshu/spring-security,xingguang2013/spring-security,mounb/spring-security,jmnarloch/spring-security,olezhuravlev/spring-security,spring-projects/spring-security,spring-projects/spring-security,zhaoqin102/spring-security,mrkingybc/spring-security,hippostar/spring-security,mounb/spring-security,panchenko/spring-security,cyratech/spring-security,ollie314/spring-security,pwheel/spring-security,pwheel/spring-security,dsyer/spring-security,MatthiasWinzeler/spring-security,zgscwjm/spring-security,rwinch/spring-security,chinazhaoht/spring-security,kazuki43zoo/spring-security,mdeinum/spring-security,chinazhaoht/spring-security,yinhe402/spring-security,wilkinsona/spring-security,justinedelson/spring-security,rwinch/spring-security,spring-projects/spring-security,fhanik/spring-security,yinhe402/spring-security,jmnarloch/spring-security,Peter32/spring-security,MatthiasWinzeler/spring-security,driftman/spring-security,mrkingybc/spring-security,pkdevbox/spring-security,izeye/spring-security,follow99/spring-security,jgrandja/spring-security,ajdinhedzic/spring-security,jgrandja/spring-security,wilkinsona/spring-security,SanjayUser/SpringSecurityPro,rwinch/spring-security,hippostar/spring-security,zshift/spring-security,SanjayUser/SpringSecurityPro,raindev/spring-security,izeye/spring-security,rwinch/spring-security,fhanik/spring-security,zgscwjm/spring-security,dsyer/spring-security,ractive/spring-security,eddumelendez/spring-security,MatthiasWinzeler/spring-security,wkorando/spring-security,spring-projects/spring-security,raindev/spring-security,vitorgv/spring-security,liuguohua/spring-security,Krasnyanskiy/spring-security,caiwenshu/spring-security,Peter32/spring-security,zhaoqin102/spring-security,pkdevbox/spring-security,kazuki43zoo/spring-security,mounb/spring-security,ractive/spring-security,SanjayUser/SpringSecurityPro,ollie314/spring-security,pwheel/spring-security,hippostar/spring-security,chinazhaoht/spring-security,zshift/spring-security,vitorgv/spring-security,likaiwalkman/spring-security,justinedelson/spring-security,pwheel/spring-security,zhaoqin102/spring-security,ollie314/spring-security,zgscwjm/spring-security,tekul/spring-security,ajdinhedzic/spring-security,Krasnyanskiy/spring-security,adairtaosy/spring-security,forestqqqq/spring-security,djechelon/spring-security,panchenko/spring-security | /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.acls.objectidentity;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.springframework.security.acls.jdbc.LookupStrategy;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* Simple implementation of {@link ObjectIdentity}.
* <p>
* Uses <code>String</code>s to store the identity of the domain object instance. Also offers a constructor that uses
* reflection to build the identity information.
*
* @author Ben Alex
* @version $Id$
*/
public class ObjectIdentityImpl implements ObjectIdentity {
//~ Instance fields ================================================================================================
private Class<?> javaType;
private Serializable identifier;
//~ Constructors ===================================================================================================
public ObjectIdentityImpl(String javaType, Serializable identifier) {
Assert.hasText(javaType, "Java Type required");
Assert.notNull(identifier, "identifier required");
try {
this.javaType = ClassUtils.forName(javaType);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to load javaType: " + javaType, e);
}
this.identifier = identifier;
}
public ObjectIdentityImpl(Class<?> javaType, Serializable identifier) {
Assert.notNull(javaType, "Java Type required");
Assert.notNull(identifier, "identifier required");
this.javaType = javaType;
this.identifier = identifier;
}
/**
* Creates the <code>ObjectIdentityImpl</code> based on the passed
* object instance. The passed object must provide a <code>getId()</code>
* method, otherwise an exception will be thrown. The object passed will
* be considered the {@link #javaType}, so if more control is required,
* an alternate constructor should be used instead.
*
* @param object the domain object instance to create an identity for.
*
* @throws IdentityUnavailableException if identity could not be extracted
*/
public ObjectIdentityImpl(Object object) throws IdentityUnavailableException {
Assert.notNull(object, "object cannot be null");
this.javaType = ClassUtils.getUserClass(object.getClass());
Object result;
try {
Method method = this.javaType.getMethod("getId", new Class[] {});
result = method.invoke(object, new Object[] {});
} catch (Exception e) {
throw new IdentityUnavailableException("Could not extract identity from object " + object, e);
}
Assert.notNull(result, "getId() is required to return a non-null value");
Assert.isInstanceOf(Serializable.class, result, "Getter must provide a return value of type Serializable");
this.identifier = (Serializable) result;
}
//~ Methods ========================================================================================================
/**
* Important so caching operates properly.<P>Considers an object of the same class equal if it has the same
* <code>classname</code> and <code>id</code> properties.</p>
*
* <p>
* Note that this class uses string equality for the identifier field, which ensures it better supports
* differences between {@link LookupStrategy} requirements and the domain object represented by this
* <code>ObjectIdentityImpl</code>.
* </p>
*
* @param arg0 object to compare
*
* @return <code>true</code> if the presented object matches this object
*/
public boolean equals(Object arg0) {
if (arg0 == null) {
return false;
}
if (!(arg0 instanceof ObjectIdentityImpl)) {
return false;
}
ObjectIdentityImpl other = (ObjectIdentityImpl) arg0;
if (this.getIdentifier().toString().equals(other.getIdentifier().toString()) && this.getJavaType().equals(other.getJavaType())) {
return true;
}
return false;
}
public Serializable getIdentifier() {
return identifier;
}
public Class<?> getJavaType() {
return javaType;
}
/**
* Important so caching operates properly.
*
* @return the hash
*/
public int hashCode() {
int code = 31;
code ^= this.javaType.hashCode();
code ^= this.identifier.hashCode();
return code;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(this.getClass().getName()).append("[");
sb.append("Java Type: ").append(this.javaType.getName());
sb.append("; Identifier: ").append(this.identifier).append("]");
return sb.toString();
}
}
| acl/src/main/java/org/springframework/security/acls/objectidentity/ObjectIdentityImpl.java | /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.acls.objectidentity;
import org.springframework.security.acls.jdbc.LookupStrategy;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import java.io.Serializable;
import java.lang.reflect.Method;
/**
* Simple implementation of {@link ObjectIdentity}.
* <p>
* Uses <code>String</code>s to store the identity of the domain object instance. Also offers a constructor that uses
* reflection to build the identity information.
*
* @author Ben Alex
* @version $Id$
*/
public class ObjectIdentityImpl implements ObjectIdentity {
//~ Instance fields ================================================================================================
private Class<?> javaType;
private Serializable identifier;
//~ Constructors ===================================================================================================
public ObjectIdentityImpl(String javaType, Serializable identifier) {
Assert.hasText(javaType, "Java Type required");
Assert.notNull(identifier, "identifier required");
try {
this.javaType = Class.forName(javaType);
} catch (Exception ex) {
ReflectionUtils.handleReflectionException(ex);
}
this.identifier = identifier;
}
public ObjectIdentityImpl(Class<?> javaType, Serializable identifier) {
Assert.notNull(javaType, "Java Type required");
Assert.notNull(identifier, "identifier required");
this.javaType = javaType;
this.identifier = identifier;
}
/**
* Creates the <code>ObjectIdentityImpl</code> based on the passed
* object instance. The passed object must provide a <code>getId()</code>
* method, otherwise an exception will be thrown. The object passed will
* be considered the {@link #javaType}, so if more control is required,
* an alternate constructor should be used instead.
*
* @param object the domain object instance to create an identity for
*
* @throws IdentityUnavailableException if identity could not be extracted
*/
public ObjectIdentityImpl(Object object) throws IdentityUnavailableException {
Assert.notNull(object, "object cannot be null");
this.javaType = ClassUtils.getUserClass(object.getClass());
Object result;
try {
Method method = this.javaType.getMethod("getId", new Class[] {});
result = method.invoke(object, new Object[] {});
} catch (Exception e) {
throw new IdentityUnavailableException("Could not extract identity from object " + object, e);
}
Assert.notNull(result, "getId() is required to return a non-null value");
Assert.isInstanceOf(Serializable.class, result, "Getter must provide a return value of type Serializable");
this.identifier = (Serializable) result;
}
//~ Methods ========================================================================================================
/**
* Important so caching operates properly.<P>Considers an object of the same class equal if it has the same
* <code>classname</code> and <code>id</code> properties.</p>
*
* <p>
* Note that this class uses string equality for the identifier field, which ensures it better supports
* differences between {@link LookupStrategy} requirements and the domain object represented by this
* <code>ObjectIdentityImpl</code>.
* </p>
*
* @param arg0 object to compare
*
* @return <code>true</code> if the presented object matches this object
*/
public boolean equals(Object arg0) {
if (arg0 == null) {
return false;
}
if (!(arg0 instanceof ObjectIdentityImpl)) {
return false;
}
ObjectIdentityImpl other = (ObjectIdentityImpl) arg0;
if (this.getIdentifier().toString().equals(other.getIdentifier().toString()) && this.getJavaType().equals(other.getJavaType())) {
return true;
}
return false;
}
public Serializable getIdentifier() {
return identifier;
}
public Class<?> getJavaType() {
return javaType;
}
/**
* Important so caching operates properly.
*
* @return the hash
*/
public int hashCode() {
int code = 31;
code ^= this.javaType.hashCode();
code ^= this.identifier.hashCode();
return code;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(this.getClass().getName()).append("[");
sb.append("Java Type: ").append(this.javaType.getName());
sb.append("; Identifier: ").append(this.identifier).append("]");
return sb.toString();
}
}
| SEC-1128: Changed to use ClassUtils.forName to load "javaType" class.
| acl/src/main/java/org/springframework/security/acls/objectidentity/ObjectIdentityImpl.java | SEC-1128: Changed to use ClassUtils.forName to load "javaType" class. |
|
Java | apache-2.0 | 3347574170a13a324b467a8ca6169519f0766b1b | 0 | cunningt/camel,tdiesler/camel,gnodet/camel,davidkarlsen/camel,pmoerenhout/camel,pmoerenhout/camel,pmoerenhout/camel,christophd/camel,apache/camel,adessaigne/camel,tdiesler/camel,alvinkwekel/camel,gnodet/camel,pax95/camel,punkhorn/camel-upstream,christophd/camel,nicolaferraro/camel,Fabryprog/camel,ullgren/camel,objectiser/camel,tdiesler/camel,DariusX/camel,tadayosi/camel,apache/camel,DariusX/camel,alvinkwekel/camel,Fabryprog/camel,pmoerenhout/camel,apache/camel,tadayosi/camel,tdiesler/camel,punkhorn/camel-upstream,christophd/camel,nikhilvibhav/camel,pax95/camel,pmoerenhout/camel,apache/camel,objectiser/camel,alvinkwekel/camel,tadayosi/camel,adessaigne/camel,Fabryprog/camel,CodeSmell/camel,alvinkwekel/camel,tdiesler/camel,davidkarlsen/camel,cunningt/camel,ullgren/camel,davidkarlsen/camel,DariusX/camel,ullgren/camel,nicolaferraro/camel,cunningt/camel,zregvart/camel,objectiser/camel,zregvart/camel,apache/camel,cunningt/camel,pax95/camel,nicolaferraro/camel,adessaigne/camel,mcollovati/camel,objectiser/camel,adessaigne/camel,nicolaferraro/camel,tadayosi/camel,zregvart/camel,CodeSmell/camel,davidkarlsen/camel,pmoerenhout/camel,mcollovati/camel,Fabryprog/camel,pax95/camel,ullgren/camel,tadayosi/camel,CodeSmell/camel,punkhorn/camel-upstream,cunningt/camel,nikhilvibhav/camel,mcollovati/camel,tadayosi/camel,pax95/camel,mcollovati/camel,adessaigne/camel,gnodet/camel,apache/camel,nikhilvibhav/camel,cunningt/camel,christophd/camel,DariusX/camel,tdiesler/camel,pax95/camel,christophd/camel,zregvart/camel,punkhorn/camel-upstream,christophd/camel,gnodet/camel,gnodet/camel,CodeSmell/camel,adessaigne/camel,nikhilvibhav/camel | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.smpp;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.ExchangePattern;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.SimpleRegistry;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.Session;
import org.jsmpp.session.SessionStateListener;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* JUnit test class for <code>org.apache.camel.component.smpp.SmppComponent</code>
*/
public class SmppComponentTest {
private SmppComponent component;
private DefaultCamelContext context;
@Before
public void setUp() {
context = new DefaultCamelContext();
component = new SmppComponent(context);
}
@Test
public void constructorSmppConfigurationShouldSetTheConfiguration() {
SmppConfiguration configuration = new SmppConfiguration();
component = new SmppComponent(configuration);
assertSame(configuration, component.getConfiguration());
}
@Test
public void constructorCamelContextShouldSetTheContext() {
CamelContext context = new DefaultCamelContext();
component = new SmppComponent(context);
assertSame(context, component.getCamelContext());
}
@Test
public void createEndpointStringStringMapShouldReturnASmppEndpoint() throws Exception {
CamelContext context = new DefaultCamelContext();
component = new SmppComponent(context);
Map<String, String> parameters = new HashMap<>();
parameters.put("password", "secret");
Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?password=secret", parameters);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertNotNull(smppEndpoint.getConfiguration());
assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void createEndpointStringStringMapShouldReturnASmppsEndpoint() throws Exception {
CamelContext context = new DefaultCamelContext();
component = new SmppComponent(context);
Map<String, String> parameters = new HashMap<>();
parameters.put("password", "secret");
Endpoint endpoint = component.createEndpoint("smpps://smppclient@localhost:2775", "?password=secret", parameters);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertNotNull(smppEndpoint.getConfiguration());
assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void createEndpointStringStringMapWithoutACamelContextShouldReturnASmppEndpoint() throws Exception {
Map<String, String> parameters = new HashMap<>();
parameters.put("password", "secret");
Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?password=secret", parameters);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertNotNull(smppEndpoint.getConfiguration());
assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void allowEmptySystemTypeAndServiceTypeOption() throws Exception {
Map<String, String> parameters = new HashMap<>();
parameters.put("systemType", null);
parameters.put("serviceType", null);
Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?systemType=&serviceType=", parameters);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals(null, smppEndpoint.getConfiguration().getSystemType());
assertEquals(null, smppEndpoint.getConfiguration().getServiceType());
}
@Test
public void createEndpointSmppConfigurationShouldReturnASmppEndpoint() throws Exception {
SmppConfiguration configuration = new SmppConfiguration();
Endpoint endpoint = component.createEndpoint(configuration);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertSame(configuration, smppEndpoint.getConfiguration());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void createEndpointStringSmppConfigurationShouldReturnASmppEndpoint() throws Exception {
SmppConfiguration configuration = new SmppConfiguration();
Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775?password=password", configuration);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpp://smppclient@localhost:2775?password=password", smppEndpoint.getEndpointUri());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertSame(configuration, smppEndpoint.getConfiguration());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void getterShouldReturnTheSetValues() {
SmppConfiguration configuration = new SmppConfiguration();
component.setConfiguration(configuration);
assertSame(configuration, component.getConfiguration());
}
@Test
public void createEndpointWithSessionStateListener() throws Exception {
SimpleRegistry registry = new SimpleRegistry();
registry.bind("sessionStateListener", new SessionStateListener() {
@Override
public void onStateChange(SessionState arg0, SessionState arg1, Session arg2) {
}
});
context.setRegistry(registry);
component = new SmppComponent(context);
SmppEndpoint endpoint = (SmppEndpoint) component.createEndpoint("smpp://smppclient@localhost:2775?password=password&sessionStateListener=#sessionStateListener");
assertNotNull(endpoint.getConfiguration().getSessionStateListener());
}
}
| components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppComponentTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.smpp;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.ExchangePattern;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.SimpleRegistry;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.Session;
import org.jsmpp.session.SessionStateListener;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* JUnit test class for <code>org.apache.camel.component.smpp.SmppComponent</code>
*/
public class SmppComponentTest {
private SmppComponent component;
private DefaultCamelContext context;
@Before
public void setUp() {
context = new DefaultCamelContext();
component = new SmppComponent(context);
}
@Test
public void constructorSmppConfigurationShouldSetTheConfiguration() {
SmppConfiguration configuration = new SmppConfiguration();
component = new SmppComponent(configuration);
assertSame(configuration, component.getConfiguration());
}
@Test
public void constructorCamelContextShouldSetTheContext() {
CamelContext context = new DefaultCamelContext();
component = new SmppComponent(context);
assertSame(context, component.getCamelContext());
}
@Test
public void createEndpointStringStringMapShouldReturnASmppEndpoint() throws Exception {
CamelContext context = new DefaultCamelContext();
component = new SmppComponent(context);
Map<String, String> parameters = new HashMap<>();
parameters.put("password", "secret");
Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?password=secret", parameters);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertNotNull(smppEndpoint.getConfiguration());
assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void createEndpointStringStringMapShouldReturnASmppsEndpoint() throws Exception {
CamelContext context = new DefaultCamelContext();
component = new SmppComponent(context);
Map<String, String> parameters = new HashMap<>();
parameters.put("password", "secret");
Endpoint endpoint = component.createEndpoint("smpps://smppclient@localhost:2775", "?password=secret", parameters);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertNotNull(smppEndpoint.getConfiguration());
assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
assertEquals("smpps://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void createEndpointStringStringMapWithoutACamelContextShouldReturnASmppEndpoint() throws Exception {
Map<String, String> parameters = new HashMap<>();
parameters.put("password", "secret");
Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?password=secret", parameters);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertNotNull(smppEndpoint.getConfiguration());
assertEquals("secret", smppEndpoint.getConfiguration().getPassword());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void allowEmptySystemTypeAndServiceTypeOption() throws Exception {
Map<String, String> parameters = new HashMap<>();
parameters.put("systemType", null);
parameters.put("serviceType", null);
Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775", "?systemType=&serviceType=", parameters);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals(null, smppEndpoint.getConfiguration().getSystemType());
assertEquals(null, smppEndpoint.getConfiguration().getServiceType());
}
@Test
public void createEndpointSmppConfigurationShouldReturnASmppEndpoint() throws Exception {
SmppConfiguration configuration = new SmppConfiguration();
Endpoint endpoint = component.createEndpoint(configuration);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointUri());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertSame(configuration, smppEndpoint.getConfiguration());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void createEndpointStringSmppConfigurationShouldReturnASmppEndpoint() throws Exception {
SmppConfiguration configuration = new SmppConfiguration();
Endpoint endpoint = component.createEndpoint("smpp://smppclient@localhost:2775?password=password", configuration);
SmppEndpoint smppEndpoint = (SmppEndpoint) endpoint;
assertEquals("smpp://smppclient@localhost:2775?password=password", smppEndpoint.getEndpointUri());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getEndpointKey());
assertSame(component, smppEndpoint.getComponent());
assertSame(configuration, smppEndpoint.getConfiguration());
assertEquals("smpp://smppclient@localhost:2775", smppEndpoint.getConnectionString());
assertEquals(ExchangePattern.InOnly, smppEndpoint.getExchangePattern());
assertTrue(smppEndpoint.getBinding() instanceof SmppBinding);
assertNotNull(smppEndpoint.getCamelContext());
}
@Test
public void getterShouldReturnTheSetValues() {
SmppConfiguration configuration = new SmppConfiguration();
component.setConfiguration(configuration);
assertSame(configuration, component.getConfiguration());
}
@Test
public void createEndpointWithSessionStateListener() throws Exception {
SimpleRegistry registry = new SimpleRegistry();
registry.put("sessionStateListener", new SessionStateListener() {
@Override
public void onStateChange(SessionState arg0, SessionState arg1, Session arg2) {
}
});
context.setRegistry(registry);
component = new SmppComponent(context);
SmppEndpoint endpoint = (SmppEndpoint) component.createEndpoint("smpp://smppclient@localhost:2775?password=password&sessionStateListener=#sessionStateListener");
assertNotNull(endpoint.getConfiguration().getSessionStateListener());
}
}
| Camel-SMPP: Fixed build
| components/camel-smpp/src/test/java/org/apache/camel/component/smpp/SmppComponentTest.java | Camel-SMPP: Fixed build |
|
Java | apache-2.0 | aa125e8ea6c29e28d6b25dd88b1716937a34b551 | 0 | creswick/StreamingQR,creswick/StreamingQR | /**
* Copyright 2014 Galois, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.galois.qrstream.lib;
import android.app.Activity;
import android.app.Fragment;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageButton;
import com.galois.qrstream.qrpipe.IProgress;
import com.galois.qrstream.qrpipe.State;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
/**
* Created by donp on 2/11/14.
*/
public class ReceiveFragment extends Fragment implements SurfaceHolder.Callback {
private Camera camera;
private SurfaceView camera_window;
private ViewGroup.LayoutParams camera_window_params;
private RelativeLayout rootLayout;
private TorrentBar torrentBar;
private TextView progressText;
private View statusFooter;
private View statusHeader;
private DecodeThread decodeThread;
private Activity activity;
// Help QRlib manage the camera preview requests
private CameraManager cameraManager;
// Helps manage drawing qr finder points
private QRFoundPointsView cameraOverlay;
// Used to show cancellation message on UI thread
private Runnable runShowRxFailedDialog;
private static final class DrawFinderPointsRunnable implements Runnable {
private final float[] points;
private QRFoundPointsView cameraOverlay;
public DrawFinderPointsRunnable(QRFoundPointsView cameraOverlay) {
this.points = new float[0];
this.cameraOverlay = cameraOverlay;
}
public DrawFinderPointsRunnable(@NotNull float[] points, QRFoundPointsView cameraOverlay) {
if (points.length % 2 != 0) {
throw new IllegalArgumentException("Expected QR finder points to have even length");
}
this.points = points.clone();
this.cameraOverlay = cameraOverlay;
}
public void run() {
if (points.length > 0) {
cameraOverlay.setPoints(points);
cameraOverlay.setVisibility(View.VISIBLE);
}else{
cameraOverlay.setVisibility(View.INVISIBLE);
}
cameraOverlay.invalidate();
}
}
/**
* Handler to process progress updates from the IProgress implementation.
*
* This update handler is passed to the Progress object during the UI initialization.
*/
private final DisplayUpdateHandler displayUpdate = new DisplayUpdateHandler();
/**
* We're using a private static class here instead of an anonymous class because the anonymous
* handler could possibly hold on to encompassing resources in the ReceiveFragment instance.
*
* The instance we get by creating a new DisplayUpdateHandler object can only hold onto the
* torrentBar and progressText objects, which it requires.
*/
private static class DisplayUpdateHandler extends Handler {
private TorrentBar torrentBar;
private TextView progressText;
private View statusFooter;
private View statusHeader;
private QRFoundPointsView cameraOverlay;
private boolean isCameraOn = false;
private Runnable runShowRxFailedDialog;
public void setCameraOn(boolean isCameraOn) {
this.isCameraOn = isCameraOn;
}
public void setupUi(TorrentBar tb, TextView pt,
View statusHeader, View statusFooter,
QRFoundPointsView cameraOverlay, Runnable runShowRxFailedDialog) {
this.torrentBar = tb;
this.progressText = pt;
this.statusHeader = statusHeader;
this.statusFooter = statusFooter;
this.cameraOverlay = cameraOverlay;
this.runShowRxFailedDialog = runShowRxFailedDialog;
}
@Override
public void handleMessage(Message msg) {
final Bundle params = msg.getData();
if (msg.what == R.id.progress_update) {
State state = (State) params.getSerializable("state");
Log.d(Constants.APP_TAG, "DisplayUpdate.handleMessage " + state);
dispatchState(params, state);
} else if (msg.what == R.id.draw_qr_points) {
float[] points = params.getFloatArray("points");
Log.d(Constants.APP_TAG, "DisplayUpdate.handleMessage, draw_qr_points");
Log.d(Constants.APP_TAG, "draw_qr_points: pts length=" + points.length);
if (isCameraOn) {
this.post(new DrawFinderPointsRunnable(points, cameraOverlay));
}else{
this.post(new DrawFinderPointsRunnable(cameraOverlay));
}
} else {
Log.w(Constants.APP_TAG, "displayUpdate handler received unknown request");
}
}
private void dispatchState(final Bundle params, State state) {
switch (state) {
case Fail:
this.post(runShowRxFailedDialog);
torrentBar.reset();
break;
case Intermediate:
this.post(new Runnable() {
@Override
public void run() {
if (torrentBar != null && progressText != null) {
int progressStatus = params.getInt("percent_complete");
int count = params.getInt("chunk_count");
int total = params.getInt("chunk_total");
int cellId = params.getInt("chunk_id");
Log.d(Constants.APP_TAG, "DisplayUpdate.handleMessage cellReceived " + cellId);
if(!torrentBar.isConfigured()) {
// First progress message needs to setup the progress bar
torrentBar.setCellCount(total);
statusHeader.setVisibility(View.VISIBLE);
statusFooter.setVisibility(View.VISIBLE);
}
torrentBar.cellReceived(cellId);
progressText.setText("" + count + "/" + total + " " + progressStatus + "%");
}
}
});
break;
case Final:
this.post(new Runnable() {
@Override
public void run() {
if (torrentBar != null && progressText != null) {
torrentBar.setComplete();
progressText.setText("100%");
statusFooter.setVisibility(View.GONE);
}
}
});
break;
default:
break;
}
}
};
private final Progress progress = new Progress(displayUpdate);
public ReceiveFragment() {
}
/**
* Called when this fragment is associated with an Activity.
* Save the activity for use in the displayUpdate handler.
* @param activity
*/
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
}
View.OnClickListener cancelListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
cameraManager.stopRunning();
}
};
@Override
public @Nullable View onCreateView(@NotNull LayoutInflater inflater,
ViewGroup container,
@NotNull Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.receive_fragment, container, false);
rootLayout = (RelativeLayout)rootView.findViewById(R.id.receive_layout);
rootLayout.setKeepScreenOn(true);
rootView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
autoFocus();
return false;
}
});
/* remember the camera_window details for rebuilding later */
camera_window = (SurfaceView)rootLayout.findViewById(R.id.camera_window);
camera_window_params = camera_window.getLayoutParams();
setCameraWindowCallback();
cameraOverlay = (QRFoundPointsView) rootView.findViewById(R.id.camera_overlay);
torrentBar = (TorrentBar) rootView.findViewById(R.id.progressbar);
progressText = (TextView) rootView.findViewById(R.id.progresstext);
statusHeader = (ViewGroup)rootLayout.findViewById(R.id.status_overlay);
statusFooter = (ViewGroup)rootLayout.findViewById(R.id.status_overlay_footer);
Button cancelButton = (Button)rootLayout.findViewById(R.id.cancel_button);
cancelButton.setOnClickListener(cancelListener);
ImageButton progressCancelButton = (ImageButton) rootView.findViewById(R.id.progressbutton);
progressCancelButton.setOnClickListener(cancelListener);
runShowRxFailedDialog = new Runnable () {
@Override
public void run() {
Toast.makeText(getActivity(), R.string.receive_failedTxt, Toast.LENGTH_LONG).show();
resetUI();
startPipe(progress);
}
};
displayUpdate.setupUi(torrentBar, progressText, statusHeader, statusFooter, cameraOverlay, runShowRxFailedDialog);
resetUI();
return rootView;
}
@Override
public void onStart() {
// Execution order: onStart() then onResume(), onCreateView() may occur before onStart
Log.e(Constants.APP_TAG, "ReceiveFragment onStart");
resetUI();
super.onStart();
}
@Override
public void onStop() {
Log.e(Constants.APP_TAG, "ReceiveFragment onStop");
clearPendingUIMessages();
super.onStop();
}
@Override
public void onPause(){
Log.e(Constants.APP_TAG, "onPause with Thread #" + Thread.currentThread().getId());
// The camera preview cannot be shown until a fully initialized SurfaceHolder exists.
// We setup/release camera in the SurfaceHolder callbacks (surfaceDestroyed, surfaceCreated).
// It would be nice if those methods setup the camera fully, opening and releasing the
// resource.
// Most of the time, the app lifecycle will trigger the surfaceDestroyed callback.
// However, pushing the POWER button to exit when the app is running, does not trigger
// the callback. We could either,
// 1) remove SurfaceView ourselves to ensure the callbacks will be run, OR
// 2) manually track whether we have surface and check that if we have surface
// in onResume, that we open camera again.
// Remove the camera preview surface from display, so that
// the surface will get destroyed and camera will get released
if (cameraManager != null) {
// Expect cameraManager to be null only if camera failed to initialize
cameraManager.stopRunning();
}
camera_window.setVisibility(View.INVISIBLE);
cameraOverlay.setVisibility(View.INVISIBLE);
super.onPause();
}
@Override
public void onResume() {
// Setting the visibility here will cause the surfaceCreated callback
// to be invoked prompting the camera to be acquired and DecodeThread to start
camera_window.setVisibility(View.VISIBLE);
cameraOverlay.setVisibility(View.VISIBLE);
super.onResume();
}
/*
* (Re)build the camera window as the first element in rootLayout
*/
// TODO: Maybe delete this after checking that it is not needed in onResume()
private void replaceCameraWindow() {
SurfaceView previewSurface = (SurfaceView)rootLayout.findViewWithTag("camera_window");
if (previewSurface != null) {
camera_window = previewSurface;
camera_window_params = camera_window.getLayoutParams();
} else {
// Since we destroy the SurfaceView each time we pause the application
// we need to rebuild the layout.
if(camera_window == null) {
Log.e(Constants.APP_TAG,
"Unable to find camera_window view, and camera_window == null");
camera_window = new SurfaceView(rootLayout.getContext());
camera_window.setTag("camera_window");
// TODO discover if this case ever happens? Expect that it doesn't because onCreateView sets up camera_window
throw new RuntimeException("Unable to find camera_window view, and camera_window == null");
}
rootLayout.addView(camera_window, 0, camera_window_params);
}
setCameraWindowCallback();
}
private void setCameraWindowCallback() {
SurfaceHolder camWindowHolder = camera_window.getHolder();
camWindowHolder.addCallback(this);
}
/*
* Reset the UI elements to an initial state.
*/
private void resetUI() {
statusHeader.setVisibility(View.GONE);
statusFooter.setVisibility(View.GONE);
torrentBar.reset();
progressText.setText("");
}
private void clearPendingUIMessages() {
// Dispose of UI update messages that are no longer relevant.
// With 'null' as parameter, it removes all pending messages on UI thread.
// Ok because camera callbacks are not handled on UI thread anymore.
// We should be able to run this command to remove the alert messages
// displayUpdate.removeCallbacks(runShowRxFailedDialog);
// but there seems to be some kind of race condition that allows the runnable to continue
// running.
displayUpdate.removeCallbacksAndMessages(null);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e(Constants.APP_TAG, "surfaceDestroyed");
disposeCamera();
clearPendingUIMessages();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e(Constants.APP_TAG, "surfaceCreated");
if (holder == null) {
Log.e(Constants.APP_TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
} else {
initCamera(holder);
startPipe(progress);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.e(Constants.APP_TAG, "surfaceChanged");
}
/*
* Reserve the hardware camera and setup a callback for the preview frames
*/
private void initCamera (@NotNull SurfaceHolder surfaceHolder) {
if (camera != null) {
Log.d(Constants.APP_TAG, "initCamera() while camera already open.");
return;
}
// TODO How should application behave if we find only front facing camera
int cameraId = requestCameraId();
try {
Log.d(Constants.APP_TAG, "initCamera: Trying to open and initialize camera");
openCamera(cameraId);
int rotation = defaultCameraOrientation(cameraId);
camera.setDisplayOrientation(rotation);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
cameraOverlay.setCameraParameters(camera.getParameters().getPreviewSize(), rotation);
displayUpdate.setCameraOn(true);
autoFocus();
} catch (RuntimeException re) {
// TODO handle this more elegantly.
Toast.makeText(getActivity(), "Unable to open camera", Toast.LENGTH_LONG).show();
Log.e(Constants.APP_TAG, "Could not open camera. " + re);
re.printStackTrace();
displayUpdate.setCameraOn(false);
} catch (IOException e) {
e.printStackTrace();
displayUpdate.setCameraOn(false);
}
}
private CameraHandlerThread mThread = null;
private void openCamera(int cameraId) {
if (mThread == null) {
mThread = new CameraHandlerThread();
}
synchronized (mThread) {
mThread.openCamera(cameraId);
}
}
// CameraHandlerThread is not using the looper of the main UI thread.
// and so it does not need to be static handler.
private class CameraHandlerThread extends HandlerThread {
private final Handler mHandler;
CameraHandlerThread() {
super("CameraHandlerThread");
start();
mHandler = new Handler(getLooper());
Log.e(Constants.APP_TAG, "CameraHandlerThread Id# " + this.getId());
}
public void openCamera(final int cameraId) {
mHandler.post(new Runnable() {
@Override
public void run() {
camera = getCameraInstance(cameraId);
notifyCameraOpened();
}
});
try {
wait();
} catch (InterruptedException e) {
Log.w(Constants.APP_TAG, "wait was interrupted");
}
}
private synchronized void notifyCameraOpened() {
notify();
}
private Camera getCameraInstance(int cameraId) {
Camera c = null;
try {
c = Camera.open(cameraId);
}catch (RuntimeException e) {
// TODO handle this more elegantly.
Log.e(Constants.APP_TAG, "failed to open camera");
}
return c;
}
}
/*
* Returns the id of the first back facing camera if found.
* Otherwise, it returns the id of the first camera found.
*/
private int requestCameraId() {
int cameraId = 0;
int camerasOnPhone = Camera.getNumberOfCameras();
for (int i=0; i < camerasOnPhone; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
break;
}
}
return cameraId;
}
private void disposeCamera() {
if (null == camera) {
return;
}
// Alerts DrawFinderPointsRunnable that camera is not on and no points can be shown
displayUpdate.setCameraOn(false);
// Wait for camera to handle queue of PreviewCallback requests
// so that the camera can released safely
mThread.quit(); // should this be interrupted()? (Investigate if we see issues relating to camera shutdown / cleanup?)
mThread = null;
camera.stopPreview();
camera.release();
camera = null;
// Dispose of any UI update messages that are no longer relevant.
clearPendingUIMessages();
}
/**
* Calculate the default orientation for the requested camera.
* Front facing cameras will compensate for the mirror effect.
*
* @param cameraId The id of the camera to display.
* @return Rotation in degrees of the camera display.
*/
private int defaultCameraOrientation(int cameraId) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = getActivity().getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
return result;
}
public void autoFocus() {
camera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
// Do nothing. Let the user notice the image is in focus
}
});
}
/*
* Create a worker thread for decoding the preview frames
* using the qrlib receiver.
*/
public void startPipe(IProgress progress) {
Log.d(Constants.APP_TAG, "startPipe");
if(decodeThread != null) {
if(decodeThread.isAlive()) {
Log.e(Constants.APP_TAG, "startPipe Error: DecodeThread already running");
Log.e(Constants.APP_TAG, "startPipe Error: DecodeThread state= " + decodeThread.getState());
} else {
Log.d(Constants.APP_TAG, "startPipe dropping dead thread");
// drop dead thread
decodeThread = null;
}
}
if(decodeThread == null && camera != null) {
Log.d(Constants.APP_TAG, "startPipe building new decodeThread");
// If we get this far, the camera preview is available for
// decodeThread to begin requesting frames. Make sure that
// the decodeThread has a new instance of the cameraManager so that it starts in the
// running state.
if (cameraManager == null || !cameraManager.isRunning()) {
cameraManager = new CameraManager(camera);
}
decodeThread = new DecodeThread(getActivity(), progress, cameraManager);
decodeThread.start();
}
}
}
| development/android/qrstreamlib/src/main/java/com/galois/qrstream/lib/ReceiveFragment.java | /**
* Copyright 2014 Galois, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.galois.qrstream.lib;
import android.app.Activity;
import android.app.Fragment;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageButton;
import com.galois.qrstream.qrpipe.IProgress;
import com.galois.qrstream.qrpipe.State;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
/**
* Created by donp on 2/11/14.
*/
public class ReceiveFragment extends Fragment implements SurfaceHolder.Callback {
private Camera camera;
private SurfaceView camera_window;
private ViewGroup.LayoutParams camera_window_params;
private RelativeLayout rootLayout;
private TorrentBar torrentBar;
private TextView progressText;
private View statusFooter;
private View statusHeader;
private DecodeThread decodeThread;
private Activity activity;
// Help QRlib manage the camera preview requests
private CameraManager cameraManager;
// Helps manage drawing qr finder points
private QRFoundPointsView cameraOverlay;
// Used to show cancellation message on UI thread
private Runnable runShowRxFailedDialog;
private static final class DrawFinderPointsRunnable implements Runnable {
private final float[] points;
private QRFoundPointsView cameraOverlay;
public DrawFinderPointsRunnable(QRFoundPointsView cameraOverlay) {
this.points = new float[0];
this.cameraOverlay = cameraOverlay;
}
public DrawFinderPointsRunnable(@NotNull float[] points, QRFoundPointsView cameraOverlay) {
if (points.length % 2 != 0) {
throw new IllegalArgumentException("Expected QR finder points to have even length");
}
this.points = points.clone();
this.cameraOverlay = cameraOverlay;
}
public void run() {
if (points.length > 0) {
cameraOverlay.setPoints(points);
cameraOverlay.setVisibility(View.VISIBLE);
}else{
cameraOverlay.setVisibility(View.INVISIBLE);
}
cameraOverlay.invalidate();
}
}
/**
* Handler to process progress updates from the IProgress implementation.
*
* This update handler is passed to the Progress object during the UI initialization.
*/
private final DisplayUpdateHandler displayUpdate = new DisplayUpdateHandler();
/**
* We're using a private static class here instead of an anonymous class because the anonymous
* handler could possibly hold on to encompassing resources in the ReceiveFragment instance.
*
* The instance we get by creating a new DisplayUpdateHandler object can only hold onto the
* torrentBar and progressText objects, which it requires.
*/
private static class DisplayUpdateHandler extends Handler {
private TorrentBar torrentBar;
private TextView progressText;
private View statusFooter;
private View statusHeader;
private QRFoundPointsView cameraOverlay;
private boolean isCameraOn = false;
private Runnable runShowRxFailedDialog;
public void setCameraOn(boolean isCameraOn) {
this.isCameraOn = isCameraOn;
}
public void setupUi(TorrentBar tb, TextView pt,
View statusHeader, View statusFooter,
QRFoundPointsView cameraOverlay, Runnable runShowRxFailedDialog) {
this.torrentBar = tb;
this.progressText = pt;
this.statusHeader = statusHeader;
this.statusFooter = statusFooter;
this.cameraOverlay = cameraOverlay;
this.runShowRxFailedDialog = runShowRxFailedDialog;
}
@Override
public void handleMessage(Message msg) {
final Bundle params = msg.getData();
if (msg.what == R.id.progress_update) {
State state = (State) params.getSerializable("state");
Log.d(Constants.APP_TAG, "DisplayUpdate.handleMessage " + state);
dispatchState(params, state);
} else if (msg.what == R.id.draw_qr_points) {
float[] points = params.getFloatArray("points");
Log.d(Constants.APP_TAG, "DisplayUpdate.handleMessage, draw_qr_points");
Log.d(Constants.APP_TAG, "draw_qr_points: pts length=" + points.length);
if (isCameraOn) {
this.post(new DrawFinderPointsRunnable(points, cameraOverlay));
}else{
this.post(new DrawFinderPointsRunnable(cameraOverlay));
}
} else {
Log.w(Constants.APP_TAG, "displayUpdate handler received unknown request");
}
}
private void dispatchState(final Bundle params, State state) {
switch (state) {
case Fail:
this.post(runShowRxFailedDialog);
torrentBar.reset();
break;
case Intermediate:
this.post(new Runnable() {
@Override
public void run() {
if (torrentBar != null && progressText != null) {
int progressStatus = params.getInt("percent_complete");
int count = params.getInt("chunk_count");
int total = params.getInt("chunk_total");
int cellId = params.getInt("chunk_id");
Log.d(Constants.APP_TAG, "DisplayUpdate.handleMessage cellReceived " + cellId);
if(!torrentBar.isConfigured()) {
// First progress message needs to setup the progress bar
torrentBar.setCellCount(total);
statusHeader.setVisibility(View.VISIBLE);
statusFooter.setVisibility(View.VISIBLE);
}
torrentBar.cellReceived(cellId);
progressText.setText("" + count + "/" + total + " " + progressStatus + "%");
}
}
});
break;
case Final:
this.post(new Runnable() {
@Override
public void run() {
if (torrentBar != null && progressText != null) {
torrentBar.setComplete();
progressText.setText("100%");
statusFooter.setVisibility(View.GONE);
}
}
});
break;
default:
break;
}
}
};
private final Progress progress = new Progress(displayUpdate);
public ReceiveFragment() {
}
/**
* Called when this fragment is associated with an Activity.
* Save the activity for use in the displayUpdate handler.
* @param activity
*/
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
}
View.OnClickListener cancelListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
cameraManager.stopRunning();
}
};
@Override
public @Nullable View onCreateView(@NotNull LayoutInflater inflater,
ViewGroup container,
@NotNull Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.receive_fragment, container, false);
rootLayout = (RelativeLayout)rootView.findViewById(R.id.receive_layout);
rootLayout.setKeepScreenOn(true);
rootView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
autoFocus();
return false;
}
});
/* remember the camera_window details for rebuilding later */
camera_window = (SurfaceView)rootLayout.findViewById(R.id.camera_window);
camera_window_params = camera_window.getLayoutParams();
setCameraWindowCallback();
cameraOverlay = (QRFoundPointsView) rootView.findViewById(R.id.camera_overlay);
torrentBar = (TorrentBar) rootView.findViewById(R.id.progressbar);
progressText = (TextView) rootView.findViewById(R.id.progresstext);
statusHeader = (ViewGroup)rootLayout.findViewById(R.id.status_overlay);
statusFooter = (ViewGroup)rootLayout.findViewById(R.id.status_overlay_footer);
Button cancelButton = (Button)rootLayout.findViewById(R.id.cancel_button);
cancelButton.setOnClickListener(cancelListener);
ImageButton progressCancelButton = (ImageButton) rootView.findViewById(R.id.progressbutton);
progressCancelButton.setOnClickListener(cancelListener);
runShowRxFailedDialog = new Runnable () {
@Override
public void run() {
Toast.makeText(getActivity(), R.string.receive_failedTxt, Toast.LENGTH_LONG).show();
resetUI();
startPipe(progress);
}
};
displayUpdate.setupUi(torrentBar, progressText, statusHeader, statusFooter, cameraOverlay, runShowRxFailedDialog);
resetUI();
return rootView;
}
@Override
public void onStart() {
// Execution order: onStart() then onResume(), onCreateView() may occur before onStart
Log.e(Constants.APP_TAG, "ReceiveFragment onStart");
resetUI();
super.onStart();
}
@Override
public void onStop() {
Log.e(Constants.APP_TAG, "ReceiveFragment onStop");
clearPendingUIMessages();
super.onStop();
}
@Override
public void onPause(){
Log.e(Constants.APP_TAG, "onPause with Thread #" + Thread.currentThread().getId());
// The camera preview cannot be shown until a fully initialized SurfaceHolder exists.
// We setup/release camera in the SurfaceHolder callbacks (surfaceDestroyed, surfaceCreated).
// It would be nice if those methods setup the camera fully, opening and releasing the
// resource.
// Most of the time, the app lifecycle will trigger the surfaceDestroyed callback.
// However, pushing the POWER button to exit when the app is running, does not trigger
// the callback. We could either,
// 1) remove SurfaceView ourselves to ensure the callbacks will be run, OR
// 2) manually track whether we have surface and check that if we have surface
// in onResume, that we open camera again.
// Remove the camera preview surface from display, so that
// the surface will get destroyed and camera will get released
if (cameraManager != null) {
// Expect cameraManager to be null only if camera failed to initialize
cameraManager.stopRunning();
}
camera_window.setVisibility(View.INVISIBLE);
cameraOverlay.setVisibility(View.INVISIBLE);
super.onPause();
}
@Override
public void onResume() {
// Setting the visibility here will cause the surfaceCreated callback
// to be invoked prompting the camera to be acquired and DecodeThread to start
camera_window.setVisibility(View.VISIBLE);
cameraOverlay.setVisibility(View.VISIBLE);
super.onResume();
}
/*
* (Re)build the camera window as the first element in rootLayout
*/
// TODO: Maybe delete this after checking that it is not needed in onResume()
private void replaceCameraWindow() {
SurfaceView previewSurface = (SurfaceView)rootLayout.findViewWithTag("camera_window");
if (previewSurface != null) {
camera_window = previewSurface;
camera_window_params = camera_window.getLayoutParams();
} else {
// Since we destroy the SurfaceView each time we pause the application
// we need to rebuild the layout.
if(camera_window == null) {
Log.e(Constants.APP_TAG,
"Unable to find camera_window view, and camera_window == null");
camera_window = new SurfaceView(rootLayout.getContext());
camera_window.setTag("camera_window");
// TODO discover if this case ever happens? Expect that it doesn't because onCreateView sets up camera_window
throw new RuntimeException("Unable to find camera_window view, and camera_window == null");
}
rootLayout.addView(camera_window, 0, camera_window_params);
}
setCameraWindowCallback();
}
private void setCameraWindowCallback() {
SurfaceHolder camWindowHolder = camera_window.getHolder();
camWindowHolder.addCallback(this);
}
/*
* Reset the UI elements to an initial state.
*/
private void resetUI() {
statusHeader.setVisibility(View.GONE);
statusFooter.setVisibility(View.GONE);
torrentBar.reset();
progressText.setText("");
}
private void clearPendingUIMessages() {
// Dispose of UI update messages that are no longer relevant.
// With 'null' as parameter, it removes all pending messages on UI thread.
// Ok because camera callbacks are not handled on UI thread anymore.
// We should be able to run this command to remove the alert messages
// displayUpdate.removeCallbacks(runShowRxFailedDialog);
// but there seems to be some kind of race condition that allows the runnable to continue
// running.
displayUpdate.removeCallbacksAndMessages(null);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e(Constants.APP_TAG, "surfaceDestroyed");
disposeCamera();
clearPendingUIMessages();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e(Constants.APP_TAG, "surfaceCreated");
if (holder == null) {
Log.e(Constants.APP_TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
} else {
initCamera(holder);
startPipe(progress);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.e(Constants.APP_TAG, "surfaceChanged");
}
/*
* Reserve the hardware camera and setup a callback for the preview frames
*/
private void initCamera (@NotNull SurfaceHolder surfaceHolder) {
if (camera != null) {
Log.d(Constants.APP_TAG, "initCamera() while camera already open.");
return;
}
// TODO How should application behave if we find only front facing camera
int cameraId = requestCameraId();
try {
Log.d(Constants.APP_TAG, "initCamera: Trying to open and initialize camera");
openCamera(cameraId);
int rotation = defaultCameraOrientation(cameraId);
camera.setDisplayOrientation(rotation);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
cameraOverlay.setCameraParameters(camera.getParameters().getPreviewSize(), rotation);
displayUpdate.setCameraOn(true);
} catch (RuntimeException re) {
// TODO handle this more elegantly.
Toast.makeText(getActivity(), "Unable to open camera", Toast.LENGTH_LONG).show();
Log.e(Constants.APP_TAG, "Could not open camera. " + re);
re.printStackTrace();
displayUpdate.setCameraOn(false);
} catch (IOException e) {
e.printStackTrace();
displayUpdate.setCameraOn(false);
}
}
private CameraHandlerThread mThread = null;
private void openCamera(int cameraId) {
if (mThread == null) {
mThread = new CameraHandlerThread();
}
synchronized (mThread) {
mThread.openCamera(cameraId);
}
}
// CameraHandlerThread is not using the looper of the main UI thread.
// and so it does not need to be static handler.
private class CameraHandlerThread extends HandlerThread {
private final Handler mHandler;
CameraHandlerThread() {
super("CameraHandlerThread");
start();
mHandler = new Handler(getLooper());
Log.e(Constants.APP_TAG, "CameraHandlerThread Id# " + this.getId());
}
public void openCamera(final int cameraId) {
mHandler.post(new Runnable() {
@Override
public void run() {
camera = getCameraInstance(cameraId);
notifyCameraOpened();
}
});
try {
wait();
} catch (InterruptedException e) {
Log.w(Constants.APP_TAG, "wait was interrupted");
}
}
private synchronized void notifyCameraOpened() {
notify();
}
private Camera getCameraInstance(int cameraId) {
Camera c = null;
try {
c = Camera.open(cameraId);
}catch (RuntimeException e) {
// TODO handle this more elegantly.
Log.e(Constants.APP_TAG, "failed to open camera");
}
return c;
}
}
/*
* Returns the id of the first back facing camera if found.
* Otherwise, it returns the id of the first camera found.
*/
private int requestCameraId() {
int cameraId = 0;
int camerasOnPhone = Camera.getNumberOfCameras();
for (int i=0; i < camerasOnPhone; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
break;
}
}
return cameraId;
}
private void disposeCamera() {
if (null == camera) {
return;
}
// Alerts DrawFinderPointsRunnable that camera is not on and no points can be shown
displayUpdate.setCameraOn(false);
// Wait for camera to handle queue of PreviewCallback requests
// so that the camera can released safely
mThread.quit(); // should this be interrupted()? (Investigate if we see issues relating to camera shutdown / cleanup?)
mThread = null;
camera.stopPreview();
camera.release();
camera = null;
// Dispose of any UI update messages that are no longer relevant.
clearPendingUIMessages();
}
/**
* Calculate the default orientation for the requested camera.
* Front facing cameras will compensate for the mirror effect.
*
* @param cameraId The id of the camera to display.
* @return Rotation in degrees of the camera display.
*/
private int defaultCameraOrientation(int cameraId) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = getActivity().getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
return result;
}
public void autoFocus() {
camera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
// Do nothing. Let the user notice the image is in focus
}
});
}
/*
* Create a worker thread for decoding the preview frames
* using the qrlib receiver.
*/
public void startPipe(IProgress progress) {
Log.d(Constants.APP_TAG, "startPipe");
if(decodeThread != null) {
if(decodeThread.isAlive()) {
Log.e(Constants.APP_TAG, "startPipe Error: DecodeThread already running");
Log.e(Constants.APP_TAG, "startPipe Error: DecodeThread state= " + decodeThread.getState());
} else {
Log.d(Constants.APP_TAG, "startPipe dropping dead thread");
// drop dead thread
decodeThread = null;
}
}
if(decodeThread == null && camera != null) {
Log.d(Constants.APP_TAG, "startPipe building new decodeThread");
// If we get this far, the camera preview is available for
// decodeThread to begin requesting frames. Make sure that
// the decodeThread has a new instance of the cameraManager so that it starts in the
// running state.
if (cameraManager == null || !cameraManager.isRunning()) {
cameraManager = new CameraManager(camera);
}
decodeThread = new DecodeThread(getActivity(), progress, cameraManager);
decodeThread.start();
}
}
}
| Force camera to autofocus whenever it gets initialized.
| development/android/qrstreamlib/src/main/java/com/galois/qrstream/lib/ReceiveFragment.java | Force camera to autofocus whenever it gets initialized. |
|
Java | apache-2.0 | c4b12042f6a8dfb79b0abd5d5d58c5d6549139fd | 0 | orangelynx/TridentSDK,orangelynx/TridentSDK,nickrobson/TridentSDK,phase/TridentSDK,phase/TridentSDK,TridentSDK/TridentSDK,TridentSDK/TridentSDK,nickrobson/TridentSDK,TridentSDK/TridentSDK | /*
* Trident - A Multithreaded Server Alternative
* Copyright 2014 The TridentSDK Team
*
* 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.tridentsdk.plugin;
import net.tridentsdk.api.Trident;
import net.tridentsdk.api.docs.InternalUseOnly;
import net.tridentsdk.api.event.Listener;
import net.tridentsdk.api.factory.ExecutorFactory;
import net.tridentsdk.api.factory.Factories;
import net.tridentsdk.api.threads.TaskExecutor;
import net.tridentsdk.plugin.annotation.IgnoreRegistration;
import net.tridentsdk.plugin.annotation.PluginDescription;
import net.tridentsdk.plugin.cmd.Command;
import net.tridentsdk.plugin.cmd.CommandHandler;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class TridentPluginHandler {
private static final ExecutorFactory<TridentPlugin> PLUGIN_EXECUTOR_FACTORY = Factories.threads().executor(2);
private final List<TridentPlugin> plugins = new ArrayList<>();
@InternalUseOnly
public void load(final File pluginFile) {
final TaskExecutor executor = PLUGIN_EXECUTOR_FACTORY.scaledThread();
executor.addTask(new Runnable() {
@Override
public void run() {
JarFile jarFile = null;
try {
// load all classes
PluginClassLoader loader = new PluginClassLoader(pluginFile);
jarFile = new JarFile(pluginFile);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (!entry.getName().endsWith(".class")) continue;
loader.loadClass(entry.getName().replace('/', '.'));
}
// start initiating the plugin class and registering commands and listeners
Class<? extends TridentPlugin> pluginClass = loader.getPluginClass();
PluginDescription description = pluginClass.getAnnotation(PluginDescription.class);
if (description == null) {
throw new PluginLoadException("Description annotation does not exist!");
}
Constructor<? extends TridentPlugin> defaultConstructor =
pluginClass.getConstructor(File.class, PluginDescription.class);
final TridentPlugin plugin = defaultConstructor.newInstance(pluginFile, description);
plugins.add(plugin);
PLUGIN_EXECUTOR_FACTORY.set(executor, plugin);
plugin.onLoad();
for (Class<?> cls : plugin.classLoader.classes.values()) {
if (Listener.class.isAssignableFrom(cls) &&
!cls.isAnnotationPresent(IgnoreRegistration.class)) {
Trident.getServer().getEventManager().registerListener(executor,
(Listener) cls.newInstance());
}
if (Command.class.isAssignableFrom(cls)) {
CommandHandler.addCommand((Command) cls.newInstance());
}
}
plugin.onEnable();
plugin.startup(executor);
} catch (IOException | ClassNotFoundException | NoSuchMethodException
| IllegalAccessException | InvocationTargetException | InstantiationException ex) {
throw new PluginLoadException(ex);
} finally {
if (jarFile != null)
try {
jarFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
public void disable(TridentPlugin plugin) {
plugin.onDisable();
this.plugins.remove(plugin);
plugin.classLoader.unloadClasses();
}
public Iterable<TridentPlugin> getPlugins() {
return Collections.unmodifiableList(this.plugins);
}
public static ExecutorFactory<TridentPlugin> getPluginExecutorFactory() {
return PLUGIN_EXECUTOR_FACTORY;
}
}
| src/main/java/net/tridentsdk/plugin/TridentPluginHandler.java | /*
* Trident - A Multithreaded Server Alternative
* Copyright 2014 The TridentSDK Team
*
* 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.tridentsdk.plugin;
import net.tridentsdk.api.Trident;
import net.tridentsdk.api.docs.InternalUseOnly;
import net.tridentsdk.api.event.Listener;
import net.tridentsdk.api.factory.ExecutorFactory;
import net.tridentsdk.api.factory.Factories;
import net.tridentsdk.api.threads.TaskExecutor;
import net.tridentsdk.plugin.annotation.IgnoreRegistration;
import net.tridentsdk.plugin.annotation.PluginDescription;
import net.tridentsdk.plugin.cmd.Command;
import net.tridentsdk.plugin.cmd.CommandHandler;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class TridentPluginHandler {
private static final ExecutorFactory<TridentPlugin> PLUGIN_EXECUTOR_FACTORY = Factories.threads().executor(2);
private final List<TridentPlugin> plugins = new ArrayList<>();
@InternalUseOnly
public void load(final File pluginFile) {
final TaskExecutor executor = PLUGIN_EXECUTOR_FACTORY.scaledThread();
executor.addTask(new Runnable() {
@Override
public void run() {
JarFile jarFile = null;
try {
// load all classes
PluginClassLoader loader = new PluginClassLoader(pluginFile);
jarFile = new JarFile(pluginFile);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (!entry.getName().endsWith(".class")) continue;
loader.loadClass(entry.getName().replace('/', '.'));
}
// start initiating the plugin class and registering commands and listeners
Class<? extends TridentPlugin> pluginClass = loader.getPluginClass();
PluginDescription description = pluginClass.getAnnotation(PluginDescription.class);
if (description == null) {
throw new PluginLoadException("Description annotation does not exist!");
}
Constructor<? extends TridentPlugin> defaultConstructor =
pluginClass.getConstructor(File.class, PluginDescription.class);
final TridentPlugin plugin = defaultConstructor.newInstance(pluginFile, description);
plugins.add(plugin);
PLUGIN_EXECUTOR_FACTORY.set(executor, plugin);
plugin.onLoad();
for (Class<?> cls : plugin.classLoader.classes.values()) {
if (Listener.class.isAssignableFrom(cls) &&
!cls.isAnnotationPresent(IgnoreRegistration.class)) {
Trident.getServer().getEventManager().registerListener((Listener) cls.newInstance());
}
if (Command.class.isAssignableFrom(cls)) {
CommandHandler.addCommand((Command) cls.newInstance());
}
}
plugin.onEnable();
plugin.startup(executor);
} catch (IOException | ClassNotFoundException | NoSuchMethodException
| IllegalAccessException | InvocationTargetException | InstantiationException ex) {
throw new PluginLoadException(ex);
} finally {
if (jarFile != null)
try {
jarFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
public void disable(TridentPlugin plugin) {
plugin.onDisable();
this.plugins.remove(plugin);
plugin.classLoader.unloadClasses();
}
public Iterable<TridentPlugin> getPlugins() {
return Collections.unmodifiableList(this.plugins);
}
public static ExecutorFactory<TridentPlugin> getPluginExecutorFactory() {
return PLUGIN_EXECUTOR_FACTORY;
}
}
| Fix compilation error
| src/main/java/net/tridentsdk/plugin/TridentPluginHandler.java | Fix compilation error |
|
Java | apache-2.0 | 43433d400085cb152473be71c53783ab59d2cdfd | 0 | treason258/TreCore,treason258/TreCore | package com.mjiayou.trecorelib.util;
import android.app.Activity;
import android.util.Log;
import java.util.LinkedList;
import java.util.Stack;
/**
* Log输出封装
* <p>
* Created by treason on 16/5/14.
*/
public class LogUtil {
private static final String TAG = LogUtil.class.getSimpleName();
private static boolean mShow = true; // 配置是否显示LOG,默认显示
private static boolean mShowPath = false; // 配置是否显示路径,默认隐藏
private static int mPathLine = 3; // 配置显示路径的行数,默认3行
/**
* 配置是否显示LOG
*/
public static void setEnable(boolean show) {
mShow = show;
}
/**
* 配置是否显示路径
*/
public static void setShowPath(boolean show) {
mShowPath = show;
}
/**
* 配置显示路径的行数
*/
public static void setPathLine(int pathLine) {
mPathLine = pathLine;
}
/**
* Send a VERBOSE log message.
*/
public static void v(String tag, String msg) {
if (mShow) {
Log.v(TAG + "-" + tag, buildMessage(msg));
}
}
public static void v(String msg) {
if (mShow) {
Log.v(TAG, buildMessage(msg));
}
}
/**
* Send a DEBUG log message.
*/
public static void d(String tag, String msg) {
if (mShow) {
Log.d(TAG + "-" + tag, buildMessage(msg));
}
}
public static void d(String msg) {
if (mShow) {
Log.d(TAG, buildMessage(msg));
}
}
/**
* Send an INFO log message.
*/
public static void i(String tag, String msg) {
if (mShow) {
Log.i(TAG + "-" + tag, buildMessage(msg));
}
}
public static void i(String msg) {
if (mShow) {
Log.i(TAG, buildMessage(msg));
}
}
/**
* Send a WARN log message
*/
public static void w(String tag, String msg) {
if (mShow) {
Log.w(TAG + "-" + tag, buildMessage(msg));
}
}
public static void w(String msg) {
if (mShow) {
Log.w(TAG, buildMessage(msg));
}
}
/**
* Send an ERROR log message.
*/
public static void e(String tag, String msg, Throwable throwable) {
if (mShow) {
Log.e(TAG + "-" + tag, buildMessage(msg), throwable);
}
}
public static void e(String tag, String msg) {
if (mShow) {
Log.e(TAG + "-" + tag, buildMessage(msg));
}
}
public static void e(String msg) {
if (mShow) {
Log.e(TAG, buildMessage(msg));
}
}
public static void e(String msg, Throwable throwable) {
if (mShow) {
Log.e(TAG, buildMessage(msg), throwable);
}
}
/**
* TraceTime
*/
public static final String TAG_TRACE_TIME = "TraceTime";
private static Stack<Long> traceTimeStack = new Stack<>();
public static void traceStart(String tag) {
traceTimeStack.push(System.currentTimeMillis());
LogUtil.i(TAG_TRACE_TIME + "-" + tag, "startTime = " + System.currentTimeMillis());
}
public static void traceStop(String tag) {
if (traceTimeStack.isEmpty()) {
LogUtil.e("traceTimeStack.isEmpty()");
return;
}
long startTime = traceTimeStack.pop();
long durationTime = System.currentTimeMillis() - startTime;
LogUtil.i(TAG_TRACE_TIME + "-" + tag, "endTime = " + System.currentTimeMillis());
LogUtil.i(TAG_TRACE_TIME + "-" + tag, "durationTime = " + durationTime + "ms");
}
public static void traceReset() {
traceTimeStack.clear();
}
/**
* 打印初始化信息
*/
public static void printInit(String module) {
LogUtil.i(module, "初始化数据 -> " + module);
}
/**
* 打印异常信息
*/
public static void printStackTrace(Throwable throwable) {
LogUtil.e(buildMessage("printStackTrace"), throwable);
throwable.printStackTrace();
}
/**
* 打印 ActivityManager
*/
public static void printActivityList(LinkedList<Activity> activityList) {
StringBuilder builder = new StringBuilder();
builder.append("printActivityList | size -> ").append(activityList.size());
for (int i = 0; i < activityList.size(); i++) {
builder.append("\n").append(i).append(" -> ").append(activityList.get(i).getClass().getSimpleName());
}
LogUtil.i(builder.toString());
}
/**
* Building Message
*/
private static String buildMessage(String msg) {
StringBuilder builder = new StringBuilder();
builder.append(msg);
if (mShowPath) {
for (int i = 0; i < mPathLine; i++) {
if (i == 0 || i == 1) { // 因为封装过程中已经有两层为固定的
continue;
}
StackTraceElement caller = new Throwable().fillInStackTrace().getStackTrace()[i];
if (caller == null) {
continue;
}
builder.append("\n");
builder.append("at ");
builder.append(caller.getClassName());
builder.append(".");
builder.append(caller.getMethodName());
builder.append("(");
builder.append(caller.getFileName());
builder.append(":");
builder.append(caller.getLineNumber());
builder.append(")");
}
}
return builder.toString();
}
} | TreCoreLib/src/main/java/com/mjiayou/trecorelib/util/LogUtil.java | package com.mjiayou.trecorelib.util;
import android.app.Activity;
import android.util.Log;
import java.util.LinkedList;
import java.util.Stack;
/**
* Log输出封装
* <p>
* Created by treason on 16/5/14.
*/
public class LogUtil {
private static final String TAG = LogUtil.class.getSimpleName();
private static boolean mShow = true;
private static boolean mShowPath = false;
/**
* 配置是否显示LOG
*/
public static void setEnable(boolean show) {
mShow = show;
}
/**
* 配置是否显示路径
*/
public static void setShowPath(boolean show) {
mShowPath = show;
}
/**
* Send a VERBOSE log message.
*/
public static void v(String tag, String msg) {
if (mShow) {
Log.v(TAG + "-" + tag, buildMessage(msg));
}
}
public static void v(String msg) {
if (mShow) {
Log.v(TAG, buildMessage(msg));
}
}
/**
* Send a DEBUG log message.
*/
public static void d(String tag, String msg) {
if (mShow) {
Log.d(TAG + "-" + tag, buildMessage(msg));
}
}
public static void d(String msg) {
if (mShow) {
Log.d(TAG, buildMessage(msg));
}
}
/**
* Send an INFO log message.
*/
public static void i(String tag, String msg) {
if (mShow) {
Log.i(TAG + "-" + tag, buildMessage(msg));
}
}
public static void i(String msg) {
if (mShow) {
Log.i(TAG, buildMessage(msg));
}
}
/**
* Send a WARN log message
*/
public static void w(String tag, String msg) {
if (mShow) {
Log.w(TAG + "-" + tag, buildMessage(msg));
}
}
public static void w(String msg) {
if (mShow) {
Log.w(TAG, buildMessage(msg));
}
}
/**
* Send an ERROR log message.
*/
public static void e(String tag, String msg, Throwable throwable) {
if (mShow) {
Log.e(TAG + "-" + tag, buildMessage(msg), throwable);
}
}
public static void e(String tag, String msg) {
if (mShow) {
Log.e(TAG + "-" + tag, buildMessage(msg));
}
}
public static void e(String msg) {
if (mShow) {
Log.e(TAG, buildMessage(msg));
}
}
public static void e(String msg, Throwable throwable) {
if (mShow) {
Log.e(TAG, buildMessage(msg), throwable);
}
}
/**
* TraceTime
*/
public static final String TAG_TRACE_TIME = "TraceTime";
private static Stack<Long> traceTimeStack = new Stack<>();
public static void traceStart(String tag) {
traceTimeStack.push(System.currentTimeMillis());
LogUtil.i(TAG_TRACE_TIME + "-" + tag, "startTime = " + System.currentTimeMillis());
}
public static void traceStop(String tag) {
if (traceTimeStack.isEmpty()) {
LogUtil.e("traceTimeStack.isEmpty()");
return;
}
long startTime = traceTimeStack.pop();
long durationTime = System.currentTimeMillis() - startTime;
LogUtil.i(TAG_TRACE_TIME + "-" + tag, "endTime = " + System.currentTimeMillis());
LogUtil.i(TAG_TRACE_TIME + "-" + tag, "durationTime = " + durationTime + "ms");
}
public static void traceReset() {
traceTimeStack.clear();
}
/**
* 打印初始化信息
*/
public static void printInit(String module) {
LogUtil.i(module, "初始化数据 -> " + module);
}
/**
* 打印异常信息
*/
public static void printStackTrace(Throwable throwable) {
LogUtil.e(buildMessage("printStackTrace"), throwable);
throwable.printStackTrace();
}
/**
* 打印 ActivityManager
*/
public static void printActivityList(LinkedList<Activity> activityList) {
StringBuilder builder = new StringBuilder();
builder.append("printActivityList | size -> ").append(activityList.size());
for (int i = 0; i < activityList.size(); i++) {
builder.append("\n").append(i).append(" -> ").append(activityList.get(i).getClass().getSimpleName());
}
LogUtil.i(builder.toString());
}
/**
* Building Message
*/
private static String buildMessage(String msg) {
StringBuilder builder = new StringBuilder();
if (mShowPath) {
StackTraceElement caller = new Throwable().fillInStackTrace().getStackTrace()[2];
builder.append(caller.getClassName());
builder.append(".");
builder.append(caller.getMethodName());
builder.append("(): \n");
}
builder.append(msg);
return builder.toString();
}
} | 整理LogUtil
| TreCoreLib/src/main/java/com/mjiayou/trecorelib/util/LogUtil.java | 整理LogUtil |
|
Java | apache-2.0 | f2fb00dc9ea18c38228ca5b0dd4db15c1063a831 | 0 | jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2009-2013 Ausenco Engineering Canada Inc.
* Copyright (C) 2018-2021 JaamSim Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaamsim.Graphics;
import java.util.ArrayList;
import com.jaamsim.Commands.KeywordCommand;
import com.jaamsim.StringProviders.StringProvConstant;
import com.jaamsim.StringProviders.StringProvInput;
import com.jaamsim.basicsim.GUIListener;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.EntityInput;
import com.jaamsim.input.Input;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.KeywordIndex;
import com.jaamsim.input.StringInput;
import com.jaamsim.input.UnitTypeInput;
import com.jaamsim.math.Vec3d;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.DistanceUnit;
import com.jaamsim.units.Unit;
/**
* The "Text" object displays written text within the 3D model universe. Both fixed and variable text can be displayed.
* @author Harry King
*
*/
public class Text extends TextBasics {
@Keyword(description = "The fixed and variable text to be displayed, as specified by a Java "
+ "format string. "
+ "If variable text is to be displayed using the DataSource keyword, "
+ "include the appropriate Java format in the text. "
+ "For example, %s will display a text output and %.6f will display a "
+ "number with six decimal digits of accuracy. "
+ "A new line can be started by entering %n. "
+ "Note that a % character is generated by entering %%.",
exampleList = {"'Present speed = %.3f m/s'", "'Present State = %s'",
"'First line%nSecond line'"})
protected final StringInput formatText;
@Keyword(description = "The unit type for the numerical value to be displayed as variable "
+ "text. Set to DimensionlessUnit if the variable text is non-numeric "
+ "such as the state of a Server.",
exampleList = {"DistanceUnit", "DimensionlessUnit"})
protected final UnitTypeInput unitType;
@Keyword(description = "The unit in which to express an expression that returns a numerical "
+ "value. For example, if the UnitType input has been set to "
+ "DistanceUnit, then the output value could be displayed in kilometres, "
+ "instead of meters, by entering km to this keyword.",
exampleList = {"m/s"})
protected final EntityInput<Unit> unit;
@Keyword(description = "An expression that returns the variable text to be displayed. "
+ "The expression can return a number that will be formated as text, "
+ "or it can return text directly, such as the state of a Server.",
exampleList = {"[Queue1].AverageQueueTime", "[Server1].State",
"'[Queue1].QueueLength + [Queue2].QueueLength'",
"TimeSeries1"})
protected final StringProvInput dataSource;
@Keyword(description = "The text to display if there is any failure while formatting the "
+ "variable text or while evaluating the expression.",
exampleList = {"'Input Error'"})
private final StringInput failText;
@Keyword(description = "If TRUE, then the size of the background rectangle is adjusted "
+ "whenever the displayed text or its font is changed. "
+ "Resizing is performed only when the DataSource input has been left "
+ "blank.",
exampleList = { "TRUE" })
protected final BooleanInput autoSize;
protected String renderText = "";
{
formatText = new StringInput("Format", KEY_INPUTS, "%s");
this.addInput(formatText);
unitType = new UnitTypeInput("UnitType", KEY_INPUTS, DimensionlessUnit.class);
this.addInput(unitType);
unit = new EntityInput<>(Unit.class, "Unit", KEY_INPUTS, null);
unit.setSubClass(null);
this.addInput(unit);
dataSource = new StringProvInput("DataSource", KEY_INPUTS, new StringProvConstant(""));
dataSource.setUnitType(DimensionlessUnit.class);
this.addInput(dataSource);
this.addSynonym(dataSource, "OutputName");
failText = new StringInput("FailText", KEY_INPUTS, "Input Error");
this.addInput(failText);
autoSize = new BooleanInput("AutoSize", OPTIONS, true);
this.addInput(autoSize);
}
public Text() {}
@Override
public void updateForInput(Input<?> in) {
super.updateForInput(in);
if (in == formatText) {
setText(formatText.getValue());
return;
}
if (in == unitType) {
Class<? extends Unit> ut = unitType.getUnitType();
dataSource.setUnitType(ut);
unit.setSubClass(ut);
return;
}
}
@Override
public void setInputsForDragAndDrop() {
super.setInputsForDragAndDrop();
// Set the displayed text to the entity's name
InputAgent.applyArgs(this, "Format", this.getName());
// Set the size to match the text
resizeForText();
}
@Override
public void acceptEdits() {
super.acceptEdits();
ArrayList<KeywordIndex> kwList = new ArrayList<>(2);
kwList.add( InputAgent.formatArgs("Format", getText()) );
if (isAutoSize()) {
Vec3d size = getAutoSize(getText(), getStyle(), getTextHeight());
kwList.add( getJaamSimModel().formatVec3dInput("Size", size, DistanceUnit.class) );
}
KeywordIndex[] kws = new KeywordIndex[kwList.size()];
kwList.toArray(kws);
try {
InputAgent.storeAndExecute(new KeywordCommand(this, kws));
}
catch (Exception e) {
GUIListener gui = getJaamSimModel().getGUIListener();
if (gui != null)
gui.invokeErrorDialogBox("Input Error", e.getMessage());
}
}
public String getRenderText(double simTime) {
// If the object is selected, show the editable text
if (isEditMode())
return getText();
double siFactor = 1.0d;
if (unit.getValue() != null)
siFactor = unit.getValue().getConversionFactorToSI();
// Default Format
if (formatText.isDefault()) {
String ret = dataSource.getValue().getNextString(simTime, siFactor);
if (ret == null)
ret = "null";
return ret;
}
// Dynamic text is to be displayed
try {
String ret = dataSource.getValue().getNextString(simTime, formatText.getValue(), siFactor);
if (ret == null)
ret = "null";
return ret;
}
catch (Throwable e) {
return failText.getValue();
}
}
public boolean isAutoSize() {
return autoSize.getValue() && dataSource.isDefault();
}
@Override
public void updateGraphics(double simTime) {
super.updateGraphics(simTime);
// This text is cached because reflection is used to get it, so who knows how long it will take
String newRenderText = getRenderText(simTime);
if (newRenderText.equals(renderText)) {
// Nothing important has changed
return;
}
// The text has been updated
renderText = newRenderText;
}
@Override
public String getCachedText() {
return renderText;
}
}
| src/main/java/com/jaamsim/Graphics/Text.java | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2009-2013 Ausenco Engineering Canada Inc.
* Copyright (C) 2018-2021 JaamSim Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jaamsim.Graphics;
import com.jaamsim.Commands.KeywordCommand;
import com.jaamsim.StringProviders.StringProvConstant;
import com.jaamsim.StringProviders.StringProvInput;
import com.jaamsim.basicsim.GUIListener;
import com.jaamsim.input.BooleanInput;
import com.jaamsim.input.EntityInput;
import com.jaamsim.input.Input;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.Keyword;
import com.jaamsim.input.KeywordIndex;
import com.jaamsim.input.StringInput;
import com.jaamsim.input.UnitTypeInput;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.Unit;
/**
* The "Text" object displays written text within the 3D model universe. Both fixed and variable text can be displayed.
* @author Harry King
*
*/
public class Text extends TextBasics {
@Keyword(description = "The fixed and variable text to be displayed, as specified by a Java "
+ "format string. "
+ "If variable text is to be displayed using the DataSource keyword, "
+ "include the appropriate Java format in the text. "
+ "For example, %s will display a text output and %.6f will display a "
+ "number with six decimal digits of accuracy. "
+ "A new line can be started by entering %n. "
+ "Note that a % character is generated by entering %%.",
exampleList = {"'Present speed = %.3f m/s'", "'Present State = %s'",
"'First line%nSecond line'"})
protected final StringInput formatText;
@Keyword(description = "The unit type for the numerical value to be displayed as variable "
+ "text. Set to DimensionlessUnit if the variable text is non-numeric "
+ "such as the state of a Server.",
exampleList = {"DistanceUnit", "DimensionlessUnit"})
protected final UnitTypeInput unitType;
@Keyword(description = "The unit in which to express an expression that returns a numerical "
+ "value. For example, if the UnitType input has been set to "
+ "DistanceUnit, then the output value could be displayed in kilometres, "
+ "instead of meters, by entering km to this keyword.",
exampleList = {"m/s"})
protected final EntityInput<Unit> unit;
@Keyword(description = "An expression that returns the variable text to be displayed. "
+ "The expression can return a number that will be formated as text, "
+ "or it can return text directly, such as the state of a Server.",
exampleList = {"[Queue1].AverageQueueTime", "[Server1].State",
"'[Queue1].QueueLength + [Queue2].QueueLength'",
"TimeSeries1"})
protected final StringProvInput dataSource;
@Keyword(description = "The text to display if there is any failure while formatting the "
+ "variable text or while evaluating the expression.",
exampleList = {"'Input Error'"})
private final StringInput failText;
@Keyword(description = "If TRUE, then the size of the background rectangle is adjusted "
+ "whenever the displayed text or its font is changed. "
+ "Resizing is performed only when the DataSource input has been left "
+ "blank.",
exampleList = { "TRUE" })
protected final BooleanInput autoSize;
protected String renderText = "";
{
formatText = new StringInput("Format", KEY_INPUTS, "%s");
this.addInput(formatText);
unitType = new UnitTypeInput("UnitType", KEY_INPUTS, DimensionlessUnit.class);
this.addInput(unitType);
unit = new EntityInput<>(Unit.class, "Unit", KEY_INPUTS, null);
unit.setSubClass(null);
this.addInput(unit);
dataSource = new StringProvInput("DataSource", KEY_INPUTS, new StringProvConstant(""));
dataSource.setUnitType(DimensionlessUnit.class);
this.addInput(dataSource);
this.addSynonym(dataSource, "OutputName");
failText = new StringInput("FailText", KEY_INPUTS, "Input Error");
this.addInput(failText);
autoSize = new BooleanInput("AutoSize", OPTIONS, true);
this.addInput(autoSize);
}
public Text() {}
@Override
public void updateForInput(Input<?> in) {
super.updateForInput(in);
if (in == formatText) {
setText(formatText.getValue());
return;
}
if (in == unitType) {
Class<? extends Unit> ut = unitType.getUnitType();
dataSource.setUnitType(ut);
unit.setSubClass(ut);
return;
}
}
@Override
public void setInputsForDragAndDrop() {
super.setInputsForDragAndDrop();
// Set the displayed text to the entity's name
InputAgent.applyArgs(this, "Format", this.getName());
}
@Override
public void acceptEdits() {
super.acceptEdits();
KeywordIndex kw = InputAgent.formatArgs("Format", getText());
try {
InputAgent.storeAndExecute(new KeywordCommand(this, kw));
}
catch (Exception e) {
GUIListener gui = getJaamSimModel().getGUIListener();
if (gui != null)
gui.invokeErrorDialogBox("Input Error", e.getMessage());
}
}
public String getRenderText(double simTime) {
// If the object is selected, show the editable text
if (isEditMode())
return getText();
double siFactor = 1.0d;
if (unit.getValue() != null)
siFactor = unit.getValue().getConversionFactorToSI();
// Default Format
if (formatText.isDefault()) {
String ret = dataSource.getValue().getNextString(simTime, siFactor);
if (ret == null)
ret = "null";
return ret;
}
// Dynamic text is to be displayed
try {
String ret = dataSource.getValue().getNextString(simTime, formatText.getValue(), siFactor);
if (ret == null)
ret = "null";
return ret;
}
catch (Throwable e) {
return failText.getValue();
}
}
public boolean isAutoSize() {
return autoSize.getValue() && dataSource.isDefault();
}
@Override
public void updateGraphics(double simTime) {
super.updateGraphics(simTime);
// This text is cached because reflection is used to get it, so who knows how long it will take
String newRenderText = getRenderText(simTime);
if (newRenderText.equals(renderText)) {
// Nothing important has changed
return;
}
// The text has been updated
renderText = newRenderText;
}
@Override
public String getCachedText() {
return renderText;
}
}
| JS: autosize a Text object when it is first created or edited
Signed-off-by: Harry King <[email protected]>
| src/main/java/com/jaamsim/Graphics/Text.java | JS: autosize a Text object when it is first created or edited |
|
Java | apache-2.0 | 2ae5d50d6329a14c0bc909ea30e0624c0cc1576e | 0 | youseries/ureport,youseries/ureport,youseries/ureport | /*******************************************************************************
* Copyright 2017 Bstek
*
* 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.bstek.ureport.model;
import java.awt.Font;
import java.awt.FontMetrics;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JLabel;
import org.apache.commons.lang3.StringUtils;
import com.bstek.ureport.Range;
import com.bstek.ureport.Utils;
import com.bstek.ureport.build.BindData;
import com.bstek.ureport.build.Context;
import com.bstek.ureport.definition.Alignment;
import com.bstek.ureport.definition.BlankCellInfo;
import com.bstek.ureport.definition.Border;
import com.bstek.ureport.definition.CellStyle;
import com.bstek.ureport.definition.ConditionCellStyle;
import com.bstek.ureport.definition.ConditionPaging;
import com.bstek.ureport.definition.ConditionPropertyItem;
import com.bstek.ureport.definition.Expand;
import com.bstek.ureport.definition.LinkParameter;
import com.bstek.ureport.definition.PagingPosition;
import com.bstek.ureport.definition.Scope;
import com.bstek.ureport.definition.value.SimpleValue;
import com.bstek.ureport.definition.value.Value;
import com.bstek.ureport.exception.ReportComputeException;
import com.bstek.ureport.expression.model.Condition;
import com.bstek.ureport.expression.model.Expression;
import com.bstek.ureport.expression.model.data.BindDataListExpressionData;
import com.bstek.ureport.expression.model.data.ExpressionData;
import com.bstek.ureport.expression.model.data.ObjectExpressionData;
import com.bstek.ureport.expression.model.data.ObjectListExpressionData;
import com.bstek.ureport.utils.UnitUtils;
/**
* @author Jacky.gao
* @since 2016年11月1日
*/
public class Cell implements ReportCell {
private String name;
private int rowSpan;
private int colSpan;
/**
* 下面属性用于存放分页后的rowspan信息
* */
private int pageRowSpan=-1;
private String renderBean;
/**
* 当前单元格计算后的实际值
*/
private Object data;
/**
* 存储当前单元格对应值在进行格式化后的值
*/
private Object formatData;
private CellStyle cellStyle;
private CellStyle customCellStyle;
private Value value;
private Row row;
private Column column;
private Expand expand;
private boolean processed;
private boolean blankCell;
private boolean existPageFunction;
private List<Object> bindData;
private Range duplicateRange;
private boolean forPaging;
private String linkUrl;
private String linkTargetWindow;
private List<LinkParameter> linkParameters;
private Map<String,String> linkParameterMap;
private Expression linkUrlExpression;
private List<ConditionPropertyItem> conditionPropertyItems;
private boolean fillBlankRows;
/**
* 允许填充空白行时fillBlankRows=true,要求当前数据行数必须是multiple定义的行数的倍数,否则就补充空白行
*/
private int multiple;
/**
* 当前单元格左父格
*/
private Cell leftParentCell;
/**
* 当前单元格上父格
*/
private Cell topParentCell;
/**
* 当前单元格所在行所有子格
*/
private Map<String,List<Cell>> rowChildrenCellsMap=new HashMap<String,List<Cell>>();
/**
* 当前单元格所在列所有子格
*/
private Map<String,List<Cell>> columnChildrenCellsMap=new HashMap<String,List<Cell>>();
private List<String> increaseSpanCellNames;
private Map<String,BlankCellInfo> newBlankCellsMap;
private List<String> newCellNames;
public Cell newRowBlankCell(Context context,BlankCellInfo blankCellInfo,ReportCell mainCell){
Cell blankCell=newCell();
blankCell.setBlankCell(true);
blankCell.setValue(new SimpleValue(""));
blankCell.setExpand(Expand.None);
blankCell.setBindData(null);
if(blankCellInfo!=null){
int offset=blankCellInfo.getOffset();
int mainRowNumber=mainCell.getRow().getRowNumber();
if(offset==0){
blankCell.setRow(mainCell.getRow());
}else{
int rowNumber=mainRowNumber+offset;
Row row=context.getRow(rowNumber);
blankCell.setRow(row);
}
blankCell.setRowSpan(blankCellInfo.getSpan());
}
return blankCell;
}
public Cell newColumnBlankCell(Context context,BlankCellInfo blankCellInfo,ReportCell mainCell){
Cell blankCell=newCell();
blankCell.setBlankCell(true);
blankCell.setValue(new SimpleValue(""));
blankCell.setExpand(Expand.None);
blankCell.setBindData(null);
int offset=blankCellInfo.getOffset();
int mainColNumber=mainCell.getColumn().getColumnNumber();
if(offset==0){
blankCell.setColumn(mainCell.getColumn());
}else{
int colNumber=mainColNumber+offset;
Column col=context.getColumn(colNumber);
blankCell.setColumn(col);
}
blankCell.setColSpan(blankCellInfo.getSpan());
return blankCell;
}
public Cell newCell(){
Cell cell=new Cell();
cell.setColumn(column);
cell.setRow(row);
cell.setLeftParentCell(leftParentCell);
cell.setTopParentCell(topParentCell);
cell.setValue(value);
cell.setRowSpan(rowSpan);
cell.setColSpan(colSpan);
cell.setExpand(expand);
cell.setName(name);
cell.setCellStyle(cellStyle);
cell.setNewBlankCellsMap(newBlankCellsMap);
cell.setNewCellNames(newCellNames);
cell.setIncreaseSpanCellNames(increaseSpanCellNames);
cell.setDuplicateRange(duplicateRange);
cell.setLinkParameters(linkParameters);
cell.setLinkTargetWindow(linkTargetWindow);
cell.setLinkUrl(linkUrl);
cell.setPageRowSpan(pageRowSpan);
cell.setConditionPropertyItems(conditionPropertyItems);
cell.setFillBlankRows(fillBlankRows);
cell.setMultiple(multiple);
cell.setLinkUrlExpression(linkUrlExpression);
return cell;
}
public void addRowChild(Cell child){
String name=child.getName();
List<Cell> cells=rowChildrenCellsMap.get(name);
if(cells==null){
cells=new ArrayList<Cell>();
rowChildrenCellsMap.put(name, cells);
}
if(!cells.contains(child)){
cells.add(child);
}
if(leftParentCell!=null){
leftParentCell.addRowChild(child);
}
}
public void addColumnChild(Cell child){
String name=child.getName();
List<Cell> cells=columnChildrenCellsMap.get(name);
if(cells==null){
cells=new ArrayList<Cell>();
columnChildrenCellsMap.put(name, cells);
}
if(!cells.contains(child)){
cells.add(child);
}
if(topParentCell!=null){
topParentCell.addColumnChild(child);
}
}
@Override
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Object getFormatData() {
if(formatData==null){
return data;
}
return formatData;
}
public void setFormatData(Object formatData) {
this.formatData = formatData;
}
public void doCompute(Context context){
doComputeConditionProperty(context);
doFormat();
doDataWrapCompute(context);
}
public void doFormat(){
String format=cellStyle.getFormat();
String customFormat=null;
if(customCellStyle!=null){
customFormat=customCellStyle.getFormat();
}
if(StringUtils.isNotBlank(customFormat)){
format=customFormat;
}
if(StringUtils.isBlank(format) || data==null || StringUtils.isBlank(data.toString())){
return;
}
if(data instanceof Date){
Date d=(Date)data;
SimpleDateFormat sd=new SimpleDateFormat(format);
formatData=sd.format(d);
}else{
BigDecimal bd=null;
try{
bd=Utils.toBigDecimal(data);
}catch(Exception ex){
}
if(bd!=null){
DecimalFormat df=new DecimalFormat(format);
formatData=df.format(bd.doubleValue());
}
}
}
private void doComputeConditionProperty(Context context){
if(conditionPropertyItems==null || conditionPropertyItems.size()==0){
return;
}
for(ConditionPropertyItem item:conditionPropertyItems){
Condition condition=item.getCondition();
if(condition==null){
continue;
}
Object obj=null;
List<Object> bindDataList=this.bindData;
if(bindDataList!=null && bindDataList.size()>0){
obj=bindDataList.get(0);
}
if(!condition.filter(this, this, obj, context)){
continue;
}
ConditionPaging paging=item.getPaging();
if(paging!=null){
PagingPosition position=paging.getPosition();
if(position!=null){
if(position.equals(PagingPosition.after)){
int line=paging.getLine();
if(line==0){
row.setPageBreak(true);
}else{
int rowNumber=row.getRowNumber()+line;
Row targetRow=context.getRow(rowNumber);
targetRow.setPageBreak(true);
}
}else{
int rowNumber=row.getRowNumber()-1;
Row targetRow=context.getRow(rowNumber);
targetRow.setPageBreak(true);
}
}
}
int rowHeight=item.getRowHeight();
if(rowHeight>-1){
row.setRealHeight(rowHeight);
if(rowHeight==0 && !row.isHide()){
context.doHideProcessRow(row);
}
}
int colWidth=item.getColWidth();
if(colWidth>-1){
column.setWidth(colWidth);
if(colWidth==0 && !column.isHide()){
context.doHideProcessColumn(column);
}
}
if(StringUtils.isNotBlank(item.getNewValue())){
this.data=item.getNewValue();
this.formatData=item.getNewValue();
}
if(StringUtils.isNotBlank(item.getLinkUrl())){
linkUrl=item.getLinkUrl();
if(StringUtils.isNotBlank(item.getLinkTargetWindow())){
linkTargetWindow=item.getLinkTargetWindow();
}
if(item.getLinkParameters()!=null && item.getLinkParameters().size()>0){
linkParameters=item.getLinkParameters();
}
}
ConditionCellStyle style=item.getCellStyle();
if(style!=null){
Boolean bold=style.getBold();
if(bold!=null){
Scope scope=style.getBoldScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setBold(bold);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setBold(bold);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setBold(bold);
}
}
Boolean italic=style.getItalic();
if(italic!=null){
Scope scope=style.getItalicScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setItalic(italic);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setItalic(italic);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setItalic(italic);
}
}
Boolean underline=style.getUnderline();
if(underline!=null){
Scope scope=style.getUnderlineScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setUnderline(underline);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setUnderline(underline);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setUnderline(underline);
}
}
String forecolor=style.getForecolor();
if(StringUtils.isNotBlank(forecolor)){
Scope scope=style.getForecolorScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setForecolor(forecolor);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setForecolor(forecolor);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setForecolor(forecolor);
}
}
String bgcolor=style.getBgcolor();
if(StringUtils.isNotBlank(bgcolor)){
Scope scope=style.getBgcolorScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setBgcolor(bgcolor);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setBgcolor(bgcolor);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setBgcolor(bgcolor);
}
}
int fontSize=style.getFontSize();
if(fontSize>0){
Scope scope=style.getFontSizeScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setFontSize(fontSize);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setFontSize(fontSize);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setFontSize(fontSize);
}
}
String fontFamily=style.getFontFamily();
if(StringUtils.isNotBlank(fontFamily)){
Scope scope=style.getFontFamilyScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setFontFamily(fontFamily);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setFontFamily(fontFamily);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setFontFamily(fontFamily);
}
}
String format=style.getFormat();
if(StringUtils.isNotBlank(format)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setFormat(format);
}
Alignment align=style.getAlign();
if(align!=null){
Scope scope=style.getAlignScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setAlign(align);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setAlign(align);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setAlign(align);
}
}
Alignment valign=style.getValign();
if(valign!=null){
Scope scope=style.getValignScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setValign(valign);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setValign(valign);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setValign(valign);
}
}
Border leftBorder=style.getLeftBorder();
if(leftBorder!=null){
this.customCellStyle.setLeftBorder(leftBorder);
}
Border rightBorder=style.getRightBorder();
if(rightBorder!=null){
this.customCellStyle.setRightBorder(rightBorder);
}
Border topBorder=style.getTopBorder();
if(topBorder!=null){
this.customCellStyle.setTopBorder(topBorder);
}
Border bottomBorder=style.getBottomBorder();
if(bottomBorder!=null){
this.customCellStyle.setBottomBorder(bottomBorder);
}
}
}
}
public void doDataWrapCompute(Context context){
Boolean wrapCompute=cellStyle.getWrapCompute();
if(wrapCompute==null || !wrapCompute){
return;
}
Object targetData=getFormatData();
if(targetData==null || !(targetData instanceof String)){
return;
}
String dataText=targetData.toString();
if(StringUtils.isBlank(dataText) || dataText.length()<2){
return;
}
int totalColumnWidth=column.getWidth();
if(colSpan>0){
int colNumber=column.getColumnNumber();
for(int i=1;i<colSpan;i++){
Column col=context.getColumn(colNumber+i);
totalColumnWidth+=col.getWidth();
}
}
Font font=cellStyle.getFont();
JLabel jlabel=new JLabel();
FontMetrics fontMetrics=jlabel.getFontMetrics(font);
int textWidth=fontMetrics.stringWidth(dataText);
double fontSize=cellStyle.getFontSize();
float lineHeight=1.2f;
if(cellStyle.getLineHeight()>0){
lineHeight=cellStyle.getLineHeight();
}
fontSize=fontSize*lineHeight;
int singleLineHeight=UnitUtils.pointToPixel(fontSize);//fontMetrics.getHeight();
if(textWidth<=totalColumnWidth){
return;
}
int totalLineHeight=0;
StringBuilder multipleLine=new StringBuilder();
StringBuilder sb=new StringBuilder();
int length=dataText.length();
for(int i=0;i<length;i++){
char text=dataText.charAt(i);
if(text=='\r' || text=='\n'){
if(text=='\r'){
int nextIndex=i+1;
if(nextIndex<length){
char nextText=dataText.charAt(nextIndex);
if(nextText=='\n'){
i=nextIndex;
}
}
}
continue;
}
sb.append(text);
int width=fontMetrics.stringWidth(sb.toString())+4;
if(width>totalColumnWidth){
sb.deleteCharAt(sb.length()-1);
totalLineHeight+=singleLineHeight;
if(multipleLine.length()>0){
multipleLine.append('\n');
}
multipleLine.append(sb);
sb.delete(0, sb.length());
sb.append(text);
}
}
if(sb.length()>0){
totalLineHeight+=singleLineHeight;
if(multipleLine.length()>0){
multipleLine.append('\n');
}
multipleLine.append(sb);
}
this.formatData=multipleLine.toString();
int totalRowHeight=row.getHeight();
if(rowSpan>0){
int rowNumber=row.getRowNumber();
for(int i=1;i<rowSpan;i++){
Row targetRow=context.getRow(rowNumber+i);
totalRowHeight+=targetRow.getHeight();
}
}
int dif=totalLineHeight-totalRowHeight;
if(dif>0){
int rowHeight=row.getHeight();
int newRowHeight = rowHeight+dif;
if(row.getRealHeight()< newRowHeight){
row.setRealHeight(newRowHeight);
}
}
}
public static void main(String[] args) {
FontMetrics fontMetrics=new JLabel().getFontMetrics(new Font("宋体",Font.PLAIN,12));
String text="我是中国人,我来自China,好吧!top和bottom文档描述地很模糊,其实这里我们可以借鉴一下TextView对文本的绘制,"
+ "TextView在绘制文本的时候总会在文本的最外层留出一些内边距,为什么要这样做?因为TextView在绘制文本的时候考虑到了类似读音符号,"
+ "下图中的A上面的符号就是一个拉丁文的类似读音符号的东西";
int columnWidth=50;
long start=System.currentTimeMillis();
int totalLineHeight=0;
int singleLineHeight=fontMetrics.getHeight();
StringBuffer multipleLine=new StringBuffer();
StringBuffer sb=new StringBuffer();
for(int i=0;i<text.length();i++){
char str=text.charAt(i);
sb.append(str);
int width=fontMetrics.stringWidth(sb.toString());
if(width>columnWidth){
sb.deleteCharAt(sb.length()-1);
if(multipleLine.length()>0){
multipleLine.append("\r");
totalLineHeight+=singleLineHeight;
}
multipleLine.append(sb);
sb.delete(0, sb.length());
sb.append(str);
}
}
if(multipleLine.length()>0){
multipleLine.append("\r");
}
if(sb.length()>0){
multipleLine.append(sb);
}
long end=System.currentTimeMillis();
System.out.println(end-start);
System.out.println(multipleLine.toString());
System.out.println("totalLineHeight:"+totalLineHeight);
}
@Override
public CellStyle getCellStyle() {
return cellStyle;
}
public void setCellStyle(CellStyle cellStyle) {
this.cellStyle = cellStyle;
}
public CellStyle getCustomCellStyle() {
return customCellStyle;
}
public void setCustomCellStyle(CellStyle customCellStyle) {
this.customCellStyle = customCellStyle;
}
public boolean isBlankCell() {
return blankCell;
}
public void setBlankCell(boolean blankCell) {
this.blankCell = blankCell;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int getRowSpan() {
return rowSpan;
}
public void setRowSpan(int rowSpan) {
this.rowSpan = rowSpan;
}
@Override
public int getColSpan() {
return colSpan;
}
public void setColSpan(int colSpan) {
this.colSpan = colSpan;
}
public int getPageRowSpan() {
if(pageRowSpan==-1){
return rowSpan;
}
return pageRowSpan;
}
public void setPageRowSpan(int pageRowSpan) {
this.pageRowSpan = pageRowSpan;
}
@Override
public Row getRow() {
return row;
}
public void setRow(Row row) {
this.row = row;
}
@Override
public Column getColumn() {
return column;
}
public void setColumn(Column column) {
this.column = column;
}
@Override
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
public String getRenderBean() {
return renderBean;
}
public void setRenderBean(String renderBean) {
this.renderBean = renderBean;
}
public void setForPaging(boolean forPaging) {
this.forPaging = forPaging;
}
public boolean isForPaging() {
return forPaging;
}
public Range getDuplicateRange() {
return duplicateRange;
}
public void setDuplicateRange(Range duplicateRange) {
this.duplicateRange = duplicateRange;
}
public Map<String, List<Cell>> getRowChildrenCellsMap() {
return rowChildrenCellsMap;
}
public Map<String, List<Cell>> getColumnChildrenCellsMap() {
return columnChildrenCellsMap;
}
public List<ConditionPropertyItem> getConditionPropertyItems() {
return conditionPropertyItems;
}
public void setConditionPropertyItems(List<ConditionPropertyItem> conditionPropertyItems) {
this.conditionPropertyItems = conditionPropertyItems;
}
@Override
public Expand getExpand() {
return expand;
}
public void setExpand(Expand expand) {
this.expand = expand;
}
public Cell getLeftParentCell() {
return leftParentCell;
}
public void setLeftParentCell(Cell leftParentCell) {
this.leftParentCell = leftParentCell;
}
public Cell getTopParentCell() {
return topParentCell;
}
public void setTopParentCell(Cell topParentCell) {
this.topParentCell = topParentCell;
}
public boolean isProcessed() {
return processed;
}
public void setProcessed(boolean processed) {
this.processed = processed;
}
public boolean isExistPageFunction() {
return existPageFunction;
}
public void setExistPageFunction(boolean existPageFunction) {
this.existPageFunction = existPageFunction;
}
@Override
public List<Object> getBindData() {
return bindData;
}
public void setBindData(List<Object> bindData) {
this.bindData = bindData;
}
public List<String> getIncreaseSpanCellNames() {
return increaseSpanCellNames;
}
public void setIncreaseSpanCellNames(List<String> increaseSpanCellNames) {
this.increaseSpanCellNames = increaseSpanCellNames;
}
public Map<String, BlankCellInfo> getNewBlankCellsMap() {
return newBlankCellsMap;
}
public void setNewBlankCellsMap(Map<String, BlankCellInfo> newBlankCellsMap) {
this.newBlankCellsMap = newBlankCellsMap;
}
public List<String> getNewCellNames() {
return newCellNames;
}
public void setNewCellNames(List<String> newCellNames) {
this.newCellNames = newCellNames;
}
public String getLinkUrl() {
return linkUrl;
}
public void setLinkUrl(String linkUrl) {
this.linkUrl = linkUrl;
}
public String getLinkTargetWindow() {
return linkTargetWindow;
}
public void setLinkTargetWindow(String linkTargetWindow) {
this.linkTargetWindow = linkTargetWindow;
}
public List<LinkParameter> getLinkParameters() {
return linkParameters;
}
public void setLinkParameters(List<LinkParameter> linkParameters) {
this.linkParameters = linkParameters;
}
public String buildLinkParameters(Context context){
StringBuilder sb=new StringBuilder();
if(linkParameters!=null){
for(int i=0;i<linkParameters.size();i++){
LinkParameter param=linkParameters.get(i);
String name=param.getName();
if(linkParameterMap==null){
linkParameterMap=new HashMap<String,String>();
}
String value=linkParameterMap.get(name);
if(value==null){
Expression expr=param.getValueExpression();
value=buildExpression(context, name, expr);
}
try {
value=URLEncoder.encode(value, "utf-8");
value=URLEncoder.encode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new ReportComputeException(e);
}
if(i>0){
sb.append("&");
}
sb.append(name+"="+value);
}
}
return sb.toString();
}
public boolean isFillBlankRows() {
return fillBlankRows;
}
public void setFillBlankRows(boolean fillBlankRows) {
this.fillBlankRows = fillBlankRows;
}
public int getMultiple() {
return multiple;
}
public void setMultiple(int multiple) {
this.multiple = multiple;
}
public Expression getLinkUrlExpression() {
return linkUrlExpression;
}
public void setLinkUrlExpression(Expression linkUrlExpression) {
this.linkUrlExpression = linkUrlExpression;
}
private String buildExpression(Context context, String name, Expression expr) {
ExpressionData<?> exprData=expr.execute(this,this,context);
if(exprData instanceof ObjectListExpressionData){
ObjectListExpressionData listData=(ObjectListExpressionData)exprData;
List<?> list=listData.getData();
StringBuilder dataSB=new StringBuilder();
for(int i=0;i<list.size();i++){
Object obj=list.get(i);
if(obj==null){
obj="null";
}
if(i>0){
dataSB.append(",");
}
dataSB.append(obj);
}
linkParameterMap.put(name, dataSB.toString());
return dataSB.toString();
}else if(exprData instanceof ObjectExpressionData){
ObjectExpressionData data=(ObjectExpressionData)exprData;
Object obj=data.getData();
if(obj==null){
obj="null";
}else if(obj instanceof String){
obj=(String) obj;
}
linkParameterMap.put(name, obj.toString());
return obj.toString();
}else if(exprData instanceof BindDataListExpressionData){
BindDataListExpressionData bindDataListData=(BindDataListExpressionData)exprData;
List<BindData> list=bindDataListData.getData();
if(list.size()==1){
Object data = list.get(0).getValue();
if(data!=null){
return data.toString();
}else{
return "";
}
}else if(list.size()>1){
StringBuilder sb=new StringBuilder();
for(BindData bindData:list){
if(sb.length()>0){
sb.append(",");
}
Object data=bindData.getValue();
if(data!=null){
sb.append(data.toString());
}
}
return sb.toString();
}
}
return "";
}
}
| ureport2-core/src/main/java/com/bstek/ureport/model/Cell.java | /*******************************************************************************
* Copyright 2017 Bstek
*
* 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.bstek.ureport.model;
import java.awt.Font;
import java.awt.FontMetrics;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JLabel;
import org.apache.commons.lang3.StringUtils;
import com.bstek.ureport.Range;
import com.bstek.ureport.Utils;
import com.bstek.ureport.build.BindData;
import com.bstek.ureport.build.Context;
import com.bstek.ureport.definition.Alignment;
import com.bstek.ureport.definition.BlankCellInfo;
import com.bstek.ureport.definition.Border;
import com.bstek.ureport.definition.CellStyle;
import com.bstek.ureport.definition.ConditionCellStyle;
import com.bstek.ureport.definition.ConditionPaging;
import com.bstek.ureport.definition.ConditionPropertyItem;
import com.bstek.ureport.definition.Expand;
import com.bstek.ureport.definition.LinkParameter;
import com.bstek.ureport.definition.PagingPosition;
import com.bstek.ureport.definition.Scope;
import com.bstek.ureport.definition.value.SimpleValue;
import com.bstek.ureport.definition.value.Value;
import com.bstek.ureport.exception.ReportComputeException;
import com.bstek.ureport.expression.model.Condition;
import com.bstek.ureport.expression.model.Expression;
import com.bstek.ureport.expression.model.data.BindDataListExpressionData;
import com.bstek.ureport.expression.model.data.ExpressionData;
import com.bstek.ureport.expression.model.data.ObjectExpressionData;
import com.bstek.ureport.expression.model.data.ObjectListExpressionData;
import com.bstek.ureport.utils.UnitUtils;
/**
* @author Jacky.gao
* @since 2016年11月1日
*/
public class Cell implements ReportCell {
private String name;
private int rowSpan;
private int colSpan;
/**
* 下面属性用于存放分页后的rowspan信息
* */
private int pageRowSpan=-1;
private String renderBean;
/**
* 当前单元格计算后的实际值
*/
private Object data;
/**
* 存储当前单元格对应值在进行格式化后的值
*/
private Object formatData;
private CellStyle cellStyle;
private CellStyle customCellStyle;
private Value value;
private Row row;
private Column column;
private Expand expand;
private boolean processed;
private boolean blankCell;
private boolean existPageFunction;
private List<Object> bindData;
private Range duplicateRange;
private boolean forPaging;
private String linkUrl;
private String linkTargetWindow;
private List<LinkParameter> linkParameters;
private Map<String,String> linkParameterMap;
private Expression linkUrlExpression;
private List<ConditionPropertyItem> conditionPropertyItems;
private boolean fillBlankRows;
/**
* 允许填充空白行时fillBlankRows=true,要求当前数据行数必须是multiple定义的行数的倍数,否则就补充空白行
*/
private int multiple;
/**
* 当前单元格左父格
*/
private Cell leftParentCell;
/**
* 当前单元格上父格
*/
private Cell topParentCell;
/**
* 当前单元格所在行所有子格
*/
private Map<String,List<Cell>> rowChildrenCellsMap=new HashMap<String,List<Cell>>();
/**
* 当前单元格所在列所有子格
*/
private Map<String,List<Cell>> columnChildrenCellsMap=new HashMap<String,List<Cell>>();
private List<String> increaseSpanCellNames;
private Map<String,BlankCellInfo> newBlankCellsMap;
private List<String> newCellNames;
public Cell newRowBlankCell(Context context,BlankCellInfo blankCellInfo,ReportCell mainCell){
Cell blankCell=newCell();
blankCell.setBlankCell(true);
blankCell.setValue(new SimpleValue(""));
blankCell.setExpand(Expand.None);
blankCell.setBindData(null);
if(blankCellInfo!=null){
int offset=blankCellInfo.getOffset();
int mainRowNumber=mainCell.getRow().getRowNumber();
if(offset==0){
blankCell.setRow(mainCell.getRow());
}else{
int rowNumber=mainRowNumber+offset;
Row row=context.getRow(rowNumber);
blankCell.setRow(row);
}
blankCell.setRowSpan(blankCellInfo.getSpan());
}
return blankCell;
}
public Cell newColumnBlankCell(Context context,BlankCellInfo blankCellInfo,ReportCell mainCell){
Cell blankCell=newCell();
blankCell.setBlankCell(true);
blankCell.setValue(new SimpleValue(""));
blankCell.setExpand(Expand.None);
blankCell.setBindData(null);
int offset=blankCellInfo.getOffset();
int mainColNumber=mainCell.getColumn().getColumnNumber();
if(offset==0){
blankCell.setColumn(mainCell.getColumn());
}else{
int colNumber=mainColNumber+offset;
Column col=context.getColumn(colNumber);
blankCell.setColumn(col);
}
blankCell.setColSpan(blankCellInfo.getSpan());
return blankCell;
}
public Cell newCell(){
Cell cell=new Cell();
cell.setColumn(column);
cell.setRow(row);
cell.setLeftParentCell(leftParentCell);
cell.setTopParentCell(topParentCell);
cell.setValue(value);
cell.setRowSpan(rowSpan);
cell.setColSpan(colSpan);
cell.setExpand(expand);
cell.setName(name);
cell.setCellStyle(cellStyle);
cell.setNewBlankCellsMap(newBlankCellsMap);
cell.setNewCellNames(newCellNames);
cell.setIncreaseSpanCellNames(increaseSpanCellNames);
cell.setDuplicateRange(duplicateRange);
cell.setLinkParameters(linkParameters);
cell.setLinkTargetWindow(linkTargetWindow);
cell.setLinkUrl(linkUrl);
cell.setPageRowSpan(pageRowSpan);
cell.setConditionPropertyItems(conditionPropertyItems);
cell.setFillBlankRows(fillBlankRows);
cell.setMultiple(multiple);
cell.setLinkUrlExpression(linkUrlExpression);
return cell;
}
public void addRowChild(Cell child){
String name=child.getName();
List<Cell> cells=rowChildrenCellsMap.get(name);
if(cells==null){
cells=new ArrayList<Cell>();
rowChildrenCellsMap.put(name, cells);
}
if(!cells.contains(child)){
cells.add(child);
}
if(leftParentCell!=null){
leftParentCell.addRowChild(child);
}
}
public void addColumnChild(Cell child){
String name=child.getName();
List<Cell> cells=columnChildrenCellsMap.get(name);
if(cells==null){
cells=new ArrayList<Cell>();
columnChildrenCellsMap.put(name, cells);
}
if(!cells.contains(child)){
cells.add(child);
}
if(topParentCell!=null){
topParentCell.addColumnChild(child);
}
}
@Override
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Object getFormatData() {
if(formatData==null){
return data;
}
return formatData;
}
public void setFormatData(Object formatData) {
this.formatData = formatData;
}
public void doCompute(Context context){
doComputeConditionProperty(context);
doFormat();
doDataWrapCompute(context);
}
public void doFormat(){
String format=cellStyle.getFormat();
String customFormat=null;
if(customCellStyle!=null){
customFormat=customCellStyle.getFormat();
}
if(StringUtils.isNotBlank(customFormat)){
format=customFormat;
}
if(StringUtils.isBlank(format) || data==null || StringUtils.isBlank(data.toString())){
return;
}
if(data instanceof Date){
Date d=(Date)data;
SimpleDateFormat sd=new SimpleDateFormat(format);
formatData=sd.format(d);
}else{
BigDecimal bd=null;
try{
bd=Utils.toBigDecimal(data);
}catch(Exception ex){
}
if(bd!=null){
DecimalFormat df=new DecimalFormat(format);
formatData=df.format(bd.doubleValue());
}
}
}
private void doComputeConditionProperty(Context context){
if(conditionPropertyItems==null || conditionPropertyItems.size()==0){
return;
}
for(ConditionPropertyItem item:conditionPropertyItems){
Condition condition=item.getCondition();
if(condition==null){
continue;
}
Object obj=null;
List<Object> bindDataList=this.bindData;
if(bindDataList!=null && bindDataList.size()>0){
obj=bindDataList.get(0);
}
if(!condition.filter(this, this, obj, context)){
continue;
}
ConditionPaging paging=item.getPaging();
if(paging!=null){
PagingPosition position=paging.getPosition();
if(position!=null){
if(position.equals(PagingPosition.after)){
int line=paging.getLine();
if(line==0){
row.setPageBreak(true);
}else{
int rowNumber=row.getRowNumber()+line;
Row targetRow=context.getRow(rowNumber);
targetRow.setPageBreak(true);
}
}else{
int rowNumber=row.getRowNumber()-1;
Row targetRow=context.getRow(rowNumber);
targetRow.setPageBreak(true);
}
}
}
int rowHeight=item.getRowHeight();
if(rowHeight>-1){
row.setRealHeight(rowHeight);
if(rowHeight==0 && !row.isHide()){
context.doHideProcessRow(row);
}
}
int colWidth=item.getColWidth();
if(colWidth>-1){
column.setWidth(colWidth);
if(colWidth==0 && !column.isHide()){
context.doHideProcessColumn(column);
}
}
if(StringUtils.isNotBlank(item.getNewValue())){
this.data=item.getNewValue();
}
if(StringUtils.isNotBlank(item.getLinkUrl())){
linkUrl=item.getLinkUrl();
if(StringUtils.isNotBlank(item.getLinkTargetWindow())){
linkTargetWindow=item.getLinkTargetWindow();
}
if(item.getLinkParameters()!=null && item.getLinkParameters().size()>0){
linkParameters=item.getLinkParameters();
}
}
ConditionCellStyle style=item.getCellStyle();
if(style!=null){
Boolean bold=style.getBold();
if(bold!=null){
Scope scope=style.getBoldScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setBold(bold);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setBold(bold);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setBold(bold);
}
}
Boolean italic=style.getItalic();
if(italic!=null){
Scope scope=style.getItalicScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setItalic(italic);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setItalic(italic);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setItalic(italic);
}
}
Boolean underline=style.getUnderline();
if(underline!=null){
Scope scope=style.getUnderlineScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setUnderline(underline);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setUnderline(underline);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setUnderline(underline);
}
}
String forecolor=style.getForecolor();
if(StringUtils.isNotBlank(forecolor)){
Scope scope=style.getForecolorScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setForecolor(forecolor);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setForecolor(forecolor);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setForecolor(forecolor);
}
}
String bgcolor=style.getBgcolor();
if(StringUtils.isNotBlank(bgcolor)){
Scope scope=style.getBgcolorScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setBgcolor(bgcolor);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setBgcolor(bgcolor);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setBgcolor(bgcolor);
}
}
int fontSize=style.getFontSize();
if(fontSize>0){
Scope scope=style.getFontSizeScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setFontSize(fontSize);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setFontSize(fontSize);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setFontSize(fontSize);
}
}
String fontFamily=style.getFontFamily();
if(StringUtils.isNotBlank(fontFamily)){
Scope scope=style.getFontFamilyScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setFontFamily(fontFamily);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setFontFamily(fontFamily);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setFontFamily(fontFamily);
}
}
String format=style.getFormat();
if(StringUtils.isNotBlank(format)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setFormat(format);
}
Alignment align=style.getAlign();
if(align!=null){
Scope scope=style.getAlignScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setAlign(align);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setAlign(align);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setAlign(align);
}
}
Alignment valign=style.getValign();
if(valign!=null){
Scope scope=style.getValignScope();
if(scope.equals(Scope.cell)){
if(this.customCellStyle==null){
this.customCellStyle=new CellStyle();
}
this.customCellStyle.setValign(valign);
}else if(scope.equals(Scope.row)){
if(row.getCustomCellStyle()==null){
row.setCustomCellStyle(new CellStyle());
}
row.getCustomCellStyle().setValign(valign);
}else if(scope.equals(Scope.column)){
if(column.getCustomCellStyle()==null){
column.setCustomCellStyle(new CellStyle());
}
column.getCustomCellStyle().setValign(valign);
}
}
Border leftBorder=style.getLeftBorder();
if(leftBorder!=null){
this.customCellStyle.setLeftBorder(leftBorder);
}
Border rightBorder=style.getRightBorder();
if(rightBorder!=null){
this.customCellStyle.setRightBorder(rightBorder);
}
Border topBorder=style.getTopBorder();
if(topBorder!=null){
this.customCellStyle.setTopBorder(topBorder);
}
Border bottomBorder=style.getBottomBorder();
if(bottomBorder!=null){
this.customCellStyle.setBottomBorder(bottomBorder);
}
}
}
}
public void doDataWrapCompute(Context context){
Boolean wrapCompute=cellStyle.getWrapCompute();
if(wrapCompute==null || !wrapCompute){
return;
}
Object targetData=getFormatData();
if(targetData==null || !(targetData instanceof String)){
return;
}
String dataText=targetData.toString();
if(StringUtils.isBlank(dataText) || dataText.length()<2){
return;
}
int totalColumnWidth=column.getWidth();
if(colSpan>0){
int colNumber=column.getColumnNumber();
for(int i=1;i<colSpan;i++){
Column col=context.getColumn(colNumber+i);
totalColumnWidth+=col.getWidth();
}
}
Font font=cellStyle.getFont();
JLabel jlabel=new JLabel();
FontMetrics fontMetrics=jlabel.getFontMetrics(font);
int textWidth=fontMetrics.stringWidth(dataText);
double fontSize=cellStyle.getFontSize();
float lineHeight=1.2f;
if(cellStyle.getLineHeight()>0){
lineHeight=cellStyle.getLineHeight();
}
fontSize=fontSize*lineHeight;
int singleLineHeight=UnitUtils.pointToPixel(fontSize);//fontMetrics.getHeight();
if(textWidth<=totalColumnWidth){
return;
}
int totalLineHeight=0;
StringBuilder multipleLine=new StringBuilder();
StringBuilder sb=new StringBuilder();
int length=dataText.length();
for(int i=0;i<length;i++){
char text=dataText.charAt(i);
if(text=='\r' || text=='\n'){
if(text=='\r'){
int nextIndex=i+1;
if(nextIndex<length){
char nextText=dataText.charAt(nextIndex);
if(nextText=='\n'){
i=nextIndex;
}
}
}
continue;
}
sb.append(text);
int width=fontMetrics.stringWidth(sb.toString())+4;
if(width>totalColumnWidth){
sb.deleteCharAt(sb.length()-1);
totalLineHeight+=singleLineHeight;
if(multipleLine.length()>0){
multipleLine.append('\n');
}
multipleLine.append(sb);
sb.delete(0, sb.length());
sb.append(text);
}
}
if(sb.length()>0){
totalLineHeight+=singleLineHeight;
if(multipleLine.length()>0){
multipleLine.append('\n');
}
multipleLine.append(sb);
}
this.formatData=multipleLine.toString();
int totalRowHeight=row.getHeight();
if(rowSpan>0){
int rowNumber=row.getRowNumber();
for(int i=1;i<rowSpan;i++){
Row targetRow=context.getRow(rowNumber+i);
totalRowHeight+=targetRow.getHeight();
}
}
int dif=totalLineHeight-totalRowHeight;
if(dif>0){
int rowHeight=row.getHeight();
int newRowHeight = rowHeight+dif;
if(row.getRealHeight()< newRowHeight){
row.setRealHeight(newRowHeight);
}
}
}
public static void main(String[] args) {
FontMetrics fontMetrics=new JLabel().getFontMetrics(new Font("宋体",Font.PLAIN,12));
String text="我是中国人,我来自China,好吧!top和bottom文档描述地很模糊,其实这里我们可以借鉴一下TextView对文本的绘制,"
+ "TextView在绘制文本的时候总会在文本的最外层留出一些内边距,为什么要这样做?因为TextView在绘制文本的时候考虑到了类似读音符号,"
+ "下图中的A上面的符号就是一个拉丁文的类似读音符号的东西";
int columnWidth=50;
long start=System.currentTimeMillis();
int totalLineHeight=0;
int singleLineHeight=fontMetrics.getHeight();
StringBuffer multipleLine=new StringBuffer();
StringBuffer sb=new StringBuffer();
for(int i=0;i<text.length();i++){
char str=text.charAt(i);
sb.append(str);
int width=fontMetrics.stringWidth(sb.toString());
if(width>columnWidth){
sb.deleteCharAt(sb.length()-1);
if(multipleLine.length()>0){
multipleLine.append("\r");
totalLineHeight+=singleLineHeight;
}
multipleLine.append(sb);
sb.delete(0, sb.length());
sb.append(str);
}
}
if(multipleLine.length()>0){
multipleLine.append("\r");
}
if(sb.length()>0){
multipleLine.append(sb);
}
long end=System.currentTimeMillis();
System.out.println(end-start);
System.out.println(multipleLine.toString());
System.out.println("totalLineHeight:"+totalLineHeight);
}
@Override
public CellStyle getCellStyle() {
return cellStyle;
}
public void setCellStyle(CellStyle cellStyle) {
this.cellStyle = cellStyle;
}
public CellStyle getCustomCellStyle() {
return customCellStyle;
}
public void setCustomCellStyle(CellStyle customCellStyle) {
this.customCellStyle = customCellStyle;
}
public boolean isBlankCell() {
return blankCell;
}
public void setBlankCell(boolean blankCell) {
this.blankCell = blankCell;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int getRowSpan() {
return rowSpan;
}
public void setRowSpan(int rowSpan) {
this.rowSpan = rowSpan;
}
@Override
public int getColSpan() {
return colSpan;
}
public void setColSpan(int colSpan) {
this.colSpan = colSpan;
}
public int getPageRowSpan() {
if(pageRowSpan==-1){
return rowSpan;
}
return pageRowSpan;
}
public void setPageRowSpan(int pageRowSpan) {
this.pageRowSpan = pageRowSpan;
}
@Override
public Row getRow() {
return row;
}
public void setRow(Row row) {
this.row = row;
}
@Override
public Column getColumn() {
return column;
}
public void setColumn(Column column) {
this.column = column;
}
@Override
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
public String getRenderBean() {
return renderBean;
}
public void setRenderBean(String renderBean) {
this.renderBean = renderBean;
}
public void setForPaging(boolean forPaging) {
this.forPaging = forPaging;
}
public boolean isForPaging() {
return forPaging;
}
public Range getDuplicateRange() {
return duplicateRange;
}
public void setDuplicateRange(Range duplicateRange) {
this.duplicateRange = duplicateRange;
}
public Map<String, List<Cell>> getRowChildrenCellsMap() {
return rowChildrenCellsMap;
}
public Map<String, List<Cell>> getColumnChildrenCellsMap() {
return columnChildrenCellsMap;
}
public List<ConditionPropertyItem> getConditionPropertyItems() {
return conditionPropertyItems;
}
public void setConditionPropertyItems(List<ConditionPropertyItem> conditionPropertyItems) {
this.conditionPropertyItems = conditionPropertyItems;
}
@Override
public Expand getExpand() {
return expand;
}
public void setExpand(Expand expand) {
this.expand = expand;
}
public Cell getLeftParentCell() {
return leftParentCell;
}
public void setLeftParentCell(Cell leftParentCell) {
this.leftParentCell = leftParentCell;
}
public Cell getTopParentCell() {
return topParentCell;
}
public void setTopParentCell(Cell topParentCell) {
this.topParentCell = topParentCell;
}
public boolean isProcessed() {
return processed;
}
public void setProcessed(boolean processed) {
this.processed = processed;
}
public boolean isExistPageFunction() {
return existPageFunction;
}
public void setExistPageFunction(boolean existPageFunction) {
this.existPageFunction = existPageFunction;
}
@Override
public List<Object> getBindData() {
return bindData;
}
public void setBindData(List<Object> bindData) {
this.bindData = bindData;
}
public List<String> getIncreaseSpanCellNames() {
return increaseSpanCellNames;
}
public void setIncreaseSpanCellNames(List<String> increaseSpanCellNames) {
this.increaseSpanCellNames = increaseSpanCellNames;
}
public Map<String, BlankCellInfo> getNewBlankCellsMap() {
return newBlankCellsMap;
}
public void setNewBlankCellsMap(Map<String, BlankCellInfo> newBlankCellsMap) {
this.newBlankCellsMap = newBlankCellsMap;
}
public List<String> getNewCellNames() {
return newCellNames;
}
public void setNewCellNames(List<String> newCellNames) {
this.newCellNames = newCellNames;
}
public String getLinkUrl() {
return linkUrl;
}
public void setLinkUrl(String linkUrl) {
this.linkUrl = linkUrl;
}
public String getLinkTargetWindow() {
return linkTargetWindow;
}
public void setLinkTargetWindow(String linkTargetWindow) {
this.linkTargetWindow = linkTargetWindow;
}
public List<LinkParameter> getLinkParameters() {
return linkParameters;
}
public void setLinkParameters(List<LinkParameter> linkParameters) {
this.linkParameters = linkParameters;
}
public String buildLinkParameters(Context context){
StringBuilder sb=new StringBuilder();
if(linkParameters!=null){
for(int i=0;i<linkParameters.size();i++){
LinkParameter param=linkParameters.get(i);
String name=param.getName();
if(linkParameterMap==null){
linkParameterMap=new HashMap<String,String>();
}
String value=linkParameterMap.get(name);
if(value==null){
Expression expr=param.getValueExpression();
value=buildExpression(context, name, expr);
}
try {
value=URLEncoder.encode(value, "utf-8");
value=URLEncoder.encode(value, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new ReportComputeException(e);
}
if(i>0){
sb.append("&");
}
sb.append(name+"="+value);
}
}
return sb.toString();
}
public boolean isFillBlankRows() {
return fillBlankRows;
}
public void setFillBlankRows(boolean fillBlankRows) {
this.fillBlankRows = fillBlankRows;
}
public int getMultiple() {
return multiple;
}
public void setMultiple(int multiple) {
this.multiple = multiple;
}
public Expression getLinkUrlExpression() {
return linkUrlExpression;
}
public void setLinkUrlExpression(Expression linkUrlExpression) {
this.linkUrlExpression = linkUrlExpression;
}
private String buildExpression(Context context, String name, Expression expr) {
ExpressionData<?> exprData=expr.execute(this,this,context);
if(exprData instanceof ObjectListExpressionData){
ObjectListExpressionData listData=(ObjectListExpressionData)exprData;
List<?> list=listData.getData();
StringBuilder dataSB=new StringBuilder();
for(int i=0;i<list.size();i++){
Object obj=list.get(i);
if(obj==null){
obj="null";
}
if(i>0){
dataSB.append(",");
}
dataSB.append(obj);
}
linkParameterMap.put(name, dataSB.toString());
return dataSB.toString();
}else if(exprData instanceof ObjectExpressionData){
ObjectExpressionData data=(ObjectExpressionData)exprData;
Object obj=data.getData();
if(obj==null){
obj="null";
}else if(obj instanceof String){
obj=(String) obj;
}
linkParameterMap.put(name, obj.toString());
return obj.toString();
}else if(exprData instanceof BindDataListExpressionData){
BindDataListExpressionData bindDataListData=(BindDataListExpressionData)exprData;
List<BindData> list=bindDataListData.getData();
if(list.size()==1){
Object data = list.get(0).getValue();
if(data!=null){
return data.toString();
}else{
return "";
}
}else if(list.size()>1){
StringBuilder sb=new StringBuilder();
for(BindData bindData:list){
if(sb.length()>0){
sb.append(",");
}
Object data=bindData.getValue();
if(data!=null){
sb.append(data.toString());
}
}
return sb.toString();
}
}
return "";
}
}
| 修复条件属性中新值不起作用的BUG
| ureport2-core/src/main/java/com/bstek/ureport/model/Cell.java | 修复条件属性中新值不起作用的BUG |
|
Java | apache-2.0 | eda543b424b0ab71c5fd62c7ad718dfa4e1b7d20 | 0 | Kast0rTr0y/jackrabbit,sdmcraft/jackrabbit,Overseas-Student-Living/jackrabbit,kigsmtua/jackrabbit,SylvesterAbreu/jackrabbit,bartosz-grabski/jackrabbit,afilimonov/jackrabbit,bartosz-grabski/jackrabbit,bartosz-grabski/jackrabbit,Kast0rTr0y/jackrabbit,sdmcraft/jackrabbit,tripodsan/jackrabbit,Kast0rTr0y/jackrabbit,kigsmtua/jackrabbit,sdmcraft/jackrabbit,tripodsan/jackrabbit,kigsmtua/jackrabbit,Overseas-Student-Living/jackrabbit,tripodsan/jackrabbit,afilimonov/jackrabbit,SylvesterAbreu/jackrabbit,afilimonov/jackrabbit,Overseas-Student-Living/jackrabbit,SylvesterAbreu/jackrabbit | /*
* 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.jackrabbit.core.security.user;
import org.apache.jackrabbit.api.security.principal.ItemBasedPrincipal;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.AuthorizableExistsException;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Query;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.core.ItemImpl;
import org.apache.jackrabbit.core.NodeImpl;
import org.apache.jackrabbit.core.ProtectedItemModifier;
import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.SessionListener;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.security.SystemPrincipal;
import org.apache.jackrabbit.core.security.principal.PrincipalImpl;
import org.apache.jackrabbit.core.session.SessionOperation;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.Path;
import org.apache.jackrabbit.util.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.AccessDeniedException;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.version.VersionException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
/**
* Default implementation of the <code>UserManager</code> interface with the
* following characteristics:
*
* <ul>
* <li>Users and Groups are stored in the repository as JCR nodes.</li>
* <li>Users are created below {@link UserConstants#USERS_PATH},<br>Groups are
* created below {@link UserConstants#GROUPS_PATH} (unless otherwise configured).</li>
* <li>The Id of an authorizable is stored in the jcr:uuid property (md5 hash).</li>
* <li>In order to structure the users and groups tree and avoid creating a flat
* hierarchy, additional hierarchy nodes of type "rep:AuthorizableFolder" are
* introduced using
* <ul>
* <li>the specified intermediate path passed to the create methods</li>
* <li>or some built-in logic if the intermediate path is missing.</li>
* </ul>
* </li>
* </ul>
*
* The built-in logic applies the following rules:
* <ul>
* <li>The names of the hierarchy folders is determined from ID of the
* authorizable to be created, consisting of the leading N chars where N is
* the relative depth starting from the node at {@link #getUsersPath()}
* or {@link #getGroupsPath()}.</li>
* <li>By default 2 levels (depth == 2) are created.</li>
* <li>Parent nodes are expected to consist of folder structure only.</li>
* <li>If the ID contains invalid JCR chars that would prevent the creation of
* a Node with that name, the names of authorizable node and the intermediate
* hierarchy nodes are {@link Text#escapeIllegalJcrChars(String) escaped}.</li>
* </ul>
* Examples:
* Creating an non-existing user with ID 'aSmith' without specifying an
* intermediate path would result in the following structure:
*
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* + aSmith [rep:User]
* </pre>
*
* Creating a non-existing user with ID 'aSmith' specifying an intermediate
* path 'some/tree' would result in the following structure:
*
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + some [rep:AuthorizableFolder]
* + tree [rep:AuthorizableFolder]
* + aSmith [rep:User]
* </pre>
*
* This <code>UserManager</code> is able to handle the following configuration
* options:
*
* <ul>
* <li>{@link #PARAM_USERS_PATH}: Defines where user nodes are created.
* If missing set to {@link #USERS_PATH}.</li>
* <li>{@link #PARAM_GROUPS_PATH}. Defines where group nodes are created.
* If missing set to {@link #GROUPS_PATH}.</li>
* <li>{@link #PARAM_COMPATIBILE_JR16}: If the param is present and its
* value is <code>true</code> looking up authorizables by ID will use the
* <code>NodeResolver</code> if not found otherwise.<br>
* If the parameter is missing (or false) users and groups created
* with a Jackrabbit repository < v2.0 will not be found any more.<br>
* By default this option is disabled.</li>
* <li>{@link #PARAM_DEFAULT_DEPTH}: Parameter used to change the number of
* levels that are used by default to store authorizable nodes.<br>The value is
* expected to be a positive integer greater than zero. The default
* number of levels is 2.
* </li>
* <li>{@link #PARAM_AUTO_EXPAND_TREE}: If this parameter is present and its
* value is <code>true</code>, the trees containing user and group nodes will
* automatically created additional hierarchy levels if the number of nodes
* on a given level exceeds the maximal allowed {@link #PARAM_AUTO_EXPAND_SIZE size}.
* <br>By default this option is disabled.</li>
* <li>{@link #PARAM_AUTO_EXPAND_SIZE}: This parameter only takes effect
* if {@link #PARAM_AUTO_EXPAND_TREE} is enabled.<br>The value is expected to be
* a positive long greater than zero. The default value is 1000.</li>
* </ul>
*/
public class UserManagerImpl extends ProtectedItemModifier
implements UserManager, UserConstants, SessionListener {
/**
* Configuration option to change the
* {@link UserConstants#USERS_PATH default path} for creating users.
*/
public static final String PARAM_USERS_PATH = "usersPath";
/**
* Configuration option to change the
* {@link UserConstants#GROUPS_PATH default path} for creating groups.
*/
public static final String PARAM_GROUPS_PATH = "groupsPath";
/**
* Flag to enable a minimal backwards compatibility with Jackrabbit <
* v2.0<br>
* If the param is present and its value is <code>true</code> looking up
* authorizables by ID will use the <code>NodeResolver</code> if not found
* otherwise.<br>
* If the parameter is missing (or false) users and groups created
* with a Jackrabbit repository < v2.0 will not be found any more.<br>
* By default this option is disabled.
*/
public static final String PARAM_COMPATIBILE_JR16 = "compatibleJR16";
/**
* Parameter used to change the number of levels that are used by default
* store authorizable nodes.<br>The default number of levels is 2.
* <p/>
* <strong>NOTE:</strong> Changing the default depth once users and groups
* have been created in the repository will cause inconsistencies, due to
* the fact that the resolution of ID to an authorizable relies on the
* structure defined by the default depth.<br>
* It is recommended to remove all authorizable nodes that will not be
* reachable any more, before this config option is changed.
* <ul>
* <li>If default depth is increased:<br>
* All authorizables on levels < default depth are not reachable any more.</li>
* <li>If default depth is decreased:<br>
* All authorizables on levels > default depth aren't reachable any more
* unless the {@link #PARAM_AUTO_EXPAND_TREE} flag is set to <code>true</code>.</li>
* </ul>
*/
public static final String PARAM_DEFAULT_DEPTH = "defaultDepth";
/**
* If this parameter is present and its value is <code>true</code>, the trees
* containing user and group nodes will automatically created additional
* hierarchy levels if the number of nodes on a given level exceeds the
* maximal allowed {@link #PARAM_AUTO_EXPAND_SIZE size}.
* <br>By default this option is disabled.
*/
public static final String PARAM_AUTO_EXPAND_TREE = "autoExpandTree";
/**
* This parameter only takes effect if {@link #PARAM_AUTO_EXPAND_TREE} is
* enabled.<br>The default value is 1000.
*/
public static final String PARAM_AUTO_EXPAND_SIZE = "autoExpandSize";
/**
* If this parameter is present group memberships are collected in a node
* structure below {@link UserConstants#N_MEMBERS} instead of the default
* multi valued property {@link UserConstants#P_MEMBERS}. Its value determines
* the maximum number of member properties until additional intermediate nodes
* are inserted. Valid values are integers > 4.
*/
public static final String PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE = "groupMembershipSplitSize";
private static final Logger log = LoggerFactory.getLogger(UserManagerImpl.class);
private final SessionImpl session;
private final String adminId;
private final NodeResolver authResolver;
private final NodeCreator nodeCreator;
/**
* Configuration value defining the node where User nodes will be created.
* Default value is {@link UserConstants#USERS_PATH}.
*/
private final String usersPath;
/**
* Configuration value defining the node where Group nodes will be created.
* Default value is {@link UserConstants#GROUPS_PATH}.
*/
private final String groupsPath;
/**
* Flag indicating if {@link #getAuthorizable(String)} should be able to deal
* with users or groups created with Jackrabbit < 2.0.<br>
* As of 2.0 authorizables are created using a defined logic that allows
* to retrieve them without searching/traversing. If this flag is
* <code>true</code> this method will try to find authorizables using the
* <code>authResolver</code> if not found otherwise.
*/
private final boolean compatibleJR16;
/**
* boolean flag indicating whether the editing session is a system session.
*/
private final boolean isSystemUserManager;
/**
* Maximum number of properties on the group membership node structure under
* {@link UserConstants#N_MEMBERS} until additional intermediate nodes are inserted.
* If 0 (default), {@link UserConstants#P_MEMBERS} is used to record group
* memberships.
*/
private final int groupMembershipSplitSize;
private final MembershipCache membershipCache;
/**
* Create a new <code>UserManager</code> with the default configuration.
*
* @param session The editing/reading session.
* @param adminId The user ID of the administrator.
*/
public UserManagerImpl(SessionImpl session, String adminId) throws RepositoryException {
this(session, adminId, null, null);
}
/**
* Create a new <code>UserManager</code>
*
* @param session The editing/reading session.
* @param adminId The user ID of the administrator.
* @param config The configuration parameters.
*/
public UserManagerImpl(SessionImpl session, String adminId, Properties config) throws RepositoryException {
this(session, adminId, config, null);
}
/**
* Create a new <code>UserManager</code> for the given <code>session</code>.
* Currently the following configuration options are respected:
*
* <ul>
* <li>{@link #PARAM_USERS_PATH}. If missing set to {@link UserConstants#USERS_PATH}.</li>
* <li>{@link #PARAM_GROUPS_PATH}. If missing set to {@link UserConstants#GROUPS_PATH}.</li>
* <li>{@link #PARAM_DEFAULT_DEPTH}. The default number of levels is 2.</li>
* <li>{@link #PARAM_AUTO_EXPAND_TREE}. By default this option is disabled.</li>
* <li>{@link #PARAM_AUTO_EXPAND_SIZE}. The default value is 1000.</li>
* <li>{@link #PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE}. The default is 0 which means use
* {@link UserConstants#P_MEMBERS}.</li>
* </ul>
*
* See the overall {@link UserManagerImpl introduction} for details.
*
* @param session The editing/reading session.
* @param adminId The user ID of the administrator.
* @param config The configuration parameters.
* @param mCache Shared membership cache.
* @throws javax.jcr.RepositoryException
*/
public UserManagerImpl(SessionImpl session, String adminId, Properties config,
MembershipCache mCache) throws RepositoryException {
this.session = session;
this.adminId = adminId;
nodeCreator = new NodeCreator(config);
Object param = (config != null) ? config.get(PARAM_USERS_PATH) : null;
usersPath = (param != null) ? param.toString() : USERS_PATH;
param = (config != null) ? config.get(PARAM_GROUPS_PATH) : null;
groupsPath = (param != null) ? param.toString() : GROUPS_PATH;
param = (config != null) ? config.get(PARAM_COMPATIBILE_JR16) : null;
compatibleJR16 = (param != null) && Boolean.parseBoolean(param.toString());
param = (config != null) ? config.get(PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE) : null;
groupMembershipSplitSize = parseMembershipSplitSize(param);
if (mCache != null) {
membershipCache = mCache;
} else {
membershipCache = new MembershipCache(session, groupsPath, groupMembershipSplitSize > 0);
}
NodeResolver nr;
try {
nr = new IndexNodeResolver(session, session);
} catch (RepositoryException e) {
log.debug("UserManager: no QueryManager available for workspace '" + session.getWorkspace().getName() + "' -> Use traversing node resolver.");
nr = new TraversingNodeResolver(session, session);
}
authResolver = nr;
authResolver.setSearchRoots(usersPath, groupsPath);
/**
* evaluate if the editing session is a system session. since the
* SystemSession class is package protected the session object cannot
* be checked for the property instance.
*
* workaround: compare the class name and check if the subject contains
* the system principal.
*/
isSystemUserManager = "org.apache.jackrabbit.core.SystemSession".equals(session.getClass().getName()) &&
!session.getSubject().getPrincipals(SystemPrincipal.class).isEmpty();
}
/**
* Implementation specific methods releaving where users are created within
* the content.
*
* @return root path for user content.
* @see #PARAM_USERS_PATH For the corresponding configuration parameter.
*/
public String getUsersPath() {
return usersPath;
}
/**
* Implementation specific methods releaving where groups are created within
* the content.
*
* @return root path for group content.
* @see #PARAM_GROUPS_PATH For the corresponding configuration parameter.
*/
public String getGroupsPath() {
return groupsPath;
}
/**
* @return The membership cache present with this user manager instance.
*/
public MembershipCache getMembershipCache() {
return membershipCache;
}
/**
* Maximum number of properties on the group membership node structure under
* {@link UserConstants#N_MEMBERS} until additional intermediate nodes are inserted.
* If 0 (default), {@link UserConstants#P_MEMBERS} is used to record group
* memberships.
*
* @return
*/
public int getGroupMembershipSplitSize() {
return groupMembershipSplitSize;
}
//--------------------------------------------------------< UserManager >---
/**
* @see UserManager#getAuthorizable(String)
*/
public Authorizable getAuthorizable(String id) throws RepositoryException {
if (id == null || id.length() == 0) {
throw new IllegalArgumentException("Invalid authorizable name '" + id + "'");
}
Authorizable a = internalGetAuthorizable(id);
/**
* Extra check for the existence of the administrator user that must
* always exist.
* In case it got removed if must be recreated using a system session.
* Since a regular session may lack read permission on the admin-user's
* node an explicit test for the current editing session being
* a system session is performed.
*/
if (a == null && adminId.equals(id) && isSystemUserManager) {
log.info("Admin user does not exist.");
a = createAdmin();
}
return a;
}
/**
* @see UserManager#getAuthorizable(Principal)
*/
public Authorizable getAuthorizable(Principal principal) throws RepositoryException {
NodeImpl n = null;
// shortcuts that avoids executing a query.
if (principal instanceof AuthorizableImpl.NodeBasedPrincipal) {
NodeId nodeId = ((AuthorizableImpl.NodeBasedPrincipal) principal).getNodeId();
try {
n = session.getNodeById(nodeId);
} catch (ItemNotFoundException e) {
// no such authorizable -> null
}
} else if (principal instanceof ItemBasedPrincipal) {
String authPath = ((ItemBasedPrincipal) principal).getPath();
if (session.nodeExists(authPath)) {
n = (NodeImpl) session.getNode(authPath);
}
} else {
// another Principal implementation.
// a) try short-cut that works in case of ID.equals(principalName) only.
// b) execute query in case of pName mismatch or exception. however, query
// requires persisted user nodes (see known issue of UserImporter).
String name = principal.getName();
try {
Authorizable a = internalGetAuthorizable(name);
if (a != null && name.equals(a.getPrincipal().getName())) {
return a;
}
} catch (RepositoryException e) {
// ignore and execute the query.
}
// authorizable whose ID matched the principal name -> search.
n = (NodeImpl) authResolver.findNode(P_PRINCIPAL_NAME, name, NT_REP_AUTHORIZABLE);
}
// build the corresponding authorizable object
return getAuthorizable(n);
}
/**
* @see UserManager#findAuthorizables(String,String)
*/
public Iterator<Authorizable> findAuthorizables(String relPath, String value) throws RepositoryException {
return findAuthorizables(relPath, value, SEARCH_TYPE_AUTHORIZABLE);
}
/**
* @see UserManager#findAuthorizables(String,String, int)
*/
public Iterator<Authorizable> findAuthorizables(String relPath, String value, int searchType)
throws RepositoryException {
if (searchType < SEARCH_TYPE_USER || searchType > SEARCH_TYPE_AUTHORIZABLE) {
throw new IllegalArgumentException("Invalid search type " + searchType);
}
Path path = session.getQPath(relPath);
NodeIterator nodes;
if (relPath.indexOf('/') == -1) {
// search for properties somewhere below an authorizable node
nodes = authResolver.findNodes(path, value, searchType, true, Long.MAX_VALUE);
} else {
path = path.getNormalizedPath();
if (path.getLength() == 1) {
// only search below the authorizable node
Name ntName;
switch (searchType) {
case SEARCH_TYPE_GROUP:
ntName = NT_REP_GROUP;
break;
case SEARCH_TYPE_USER:
ntName = NT_REP_USER;
break;
default:
ntName = NT_REP_AUTHORIZABLE;
}
nodes = authResolver.findNodes(path.getName(), value, ntName, true);
} else {
// search below authorizable nodes but take some path constraints
// into account.
nodes = authResolver.findNodes(path, value, searchType, true, Long.MAX_VALUE);
}
}
return new AuthorizableIterator(nodes);
}
/**
* @see UserManager#findAuthorizables(Query)
*/
public Iterator<Authorizable> findAuthorizables(Query query) throws RepositoryException {
XPathQueryBuilder builder = new XPathQueryBuilder();
query.build(builder);
return new XPathQueryEvaluator(builder, this, session).eval();
}
/**
* @see UserManager#createUser(String,String)
*/
public User createUser(String userID, String password) throws RepositoryException {
return createUser(userID, password, new PrincipalImpl(userID), null);
}
/**
* @see UserManager#createUser(String, String, java.security.Principal, String)
*/
public User createUser(String userID, String password,
Principal principal, String intermediatePath)
throws AuthorizableExistsException, RepositoryException {
checkValidID(userID);
if (password == null) {
throw new IllegalArgumentException("Cannot create user: null password.");
}
// NOTE: principal validation during setPrincipal call.
try {
NodeImpl userNode = (NodeImpl) nodeCreator.createUserNode(userID, intermediatePath);
setPrincipal(userNode, principal);
setProperty(userNode, P_PASSWORD, getValue(UserImpl.buildPasswordValue(password)), true);
User user = createUser(userNode);
if (isAutoSave()) {
session.save();
}
log.debug("User created: " + userID + "; " + userNode.getPath());
return user;
} catch (RepositoryException e) {
// something went wrong -> revert changes and re-throw
session.refresh(false);
log.debug("Failed to create new User, reverting changes.");
throw e;
}
}
/**
* @see UserManager#createGroup(String)
*/
public Group createGroup(String groupID)
throws AuthorizableExistsException, RepositoryException {
return createGroup(groupID, new PrincipalImpl(groupID), null);
}
/**
* Same as {@link #createGroup(java.security.Principal, String)} where the
* intermediate path is <code>null</code>.
* @see UserManager#createGroup(Principal)
*/
public Group createGroup(Principal principal) throws RepositoryException {
return createGroup(principal, null);
}
/**
* Same as {@link #createGroup(String, Principal, String)} where a groupID
* is generated from the principal name. If the name conflicts with an
* existing authorizable ID (may happen in cases where
* principal name != ID) the principal name is expanded by a suffix;
* otherwise the resulting group ID equals the principal name.
*
* @param principal A principal that doesn't yet represent an existing user
* or group.
* @param intermediatePath Is always ignored.
* @return A new group.
* @throws AuthorizableExistsException
* @throws RepositoryException
* @see UserManager#createGroup(java.security.Principal, String)
*/
public Group createGroup(Principal principal, String intermediatePath) throws AuthorizableExistsException, RepositoryException {
checkValidPrincipal(principal);
String groupID = getGroupId(principal.getName());
return createGroup(groupID, principal, intermediatePath);
}
/**
* Create a new <code>Group</code> from the given <code>groupID</code> and
* <code>principal</code>. It will be created below the defined
* {@link #getGroupsPath() group path}.<br>
* Non-existent elements of the Path will be created as nodes
* of type {@link #NT_REP_AUTHORIZABLE_FOLDER rep:AuthorizableFolder}.
*
* @param groupID A groupID that hasn't been used before for another
* user or group.
* @param principal A principal that doesn't yet represent an existing user
* or group.
* @param intermediatePath Is always ignored.
* @return A new group.
* @throws AuthorizableExistsException
* @throws RepositoryException
* @see UserManager#createGroup(String, java.security.Principal, String)
*/
public Group createGroup(String groupID, Principal principal, String intermediatePath) throws AuthorizableExistsException, RepositoryException {
checkValidID(groupID);
// NOTE: principal validation during setPrincipal call.
try {
NodeImpl groupNode = (NodeImpl) nodeCreator.createGroupNode(groupID, intermediatePath);
if (principal != null) {
setPrincipal(groupNode, principal);
}
Group group = createGroup(groupNode);
if (isAutoSave()) {
session.save();
}
log.debug("Group created: " + groupID + "; " + groupNode.getPath());
return group;
} catch (RepositoryException e) {
session.refresh(false);
log.debug("newInstance new Group failed, revert changes on parent");
throw e;
}
}
/**
* Always returns <code>true</code> as by default the autoSave behavior
* cannot be altered (see also {@link #autoSave(boolean)}.
*
* @return Always <code>true</code>.
* @see org.apache.jackrabbit.api.security.user.UserManager#isAutoSave()
*/
public boolean isAutoSave() {
return true;
}
/**
* Always throws <code>unsupportedRepositoryOperationException</code> as
* modification of the autosave behavior is not supported.
*
* @see UserManager#autoSave(boolean)
*/
public void autoSave(boolean enable) throws UnsupportedRepositoryOperationException, RepositoryException {
throw new UnsupportedRepositoryOperationException("Cannot change autosave behavior.");
}
//--------------------------------------------------------------------------
/**
*
* @param node The new user/group node.
* @param principal A valid non-null principal.
* @throws AuthorizableExistsException If there is already another user/group
* with the same principal name.
* @throws RepositoryException If another error occurs.
*/
void setPrincipal(NodeImpl node, Principal principal) throws AuthorizableExistsException, RepositoryException {
checkValidPrincipal(principal);
/*
Check if there is *another* authorizable with the same principal.
The additional validation (nodes not be same) is required in order to
circumvent problems with re-importing existing authorizable in which
case the original user/group node is being recreated but the search
used to look for an colliding authorizable still finds the persisted
node.
*/
Authorizable existing = getAuthorizable(principal);
if (existing != null && !((AuthorizableImpl) existing).getNode().isSame(node)) {
throw new AuthorizableExistsException("Authorizable for '" + principal.getName() + "' already exists: ");
}
if (!node.isNew() || node.hasProperty(P_PRINCIPAL_NAME)) {
throw new RepositoryException("rep:principalName can only be set once on a new node.");
}
setProperty(node, P_PRINCIPAL_NAME, getValue(principal.getName()), true);
}
void setProtectedProperty(NodeImpl node, Name propName, Value value) throws RepositoryException, LockException, ConstraintViolationException, ItemExistsException, VersionException {
setProperty(node, propName, value);
if (isAutoSave()) {
node.save();
}
}
void setProtectedProperty(NodeImpl node, Name propName, Value[] values) throws RepositoryException, LockException, ConstraintViolationException, ItemExistsException, VersionException {
setProperty(node, propName, values);
if (isAutoSave()) {
node.save();
}
}
void setProtectedProperty(NodeImpl node, Name propName, Value[] values, int type) throws RepositoryException, LockException, ConstraintViolationException, ItemExistsException, VersionException {
setProperty(node, propName, values, type);
if (isAutoSave()) {
node.save();
}
}
void removeProtectedItem(ItemImpl item, Node parent) throws RepositoryException, AccessDeniedException, VersionException {
removeItem(item);
if (isAutoSave()) {
parent.save();
}
}
NodeImpl addProtectedNode(NodeImpl parent, Name name, Name ntName) throws RepositoryException {
NodeImpl n = addNode(parent, name, ntName);
if (isAutoSave()) {
parent.save();
}
return n;
}
<T> T performProtectedOperation(SessionImpl session, SessionOperation<T> operation) throws RepositoryException {
return performProtected(session, operation);
}
/**
* Implementation specific method used to retrieve a user/group by Node.
* <code>Null</code> is returned if
* <pre>
* - the passed node is <code>null</code>,
* - doesn't have the correct node type or
* - isn't placed underneath the configured user/group tree.
* </pre>
*
* @param n A user/group node.
* @return An authorizable or <code>null</code>.
* @throws RepositoryException If an error occurs.
*/
Authorizable getAuthorizable(NodeImpl n) throws RepositoryException {
Authorizable authorz = null;
if (n != null) {
String path = n.getPath();
if (n.isNodeType(NT_REP_USER) && Text.isDescendant(usersPath, path)) {
authorz = createUser(n);
} else if (n.isNodeType(NT_REP_GROUP) && Text.isDescendant(groupsPath, path)) {
authorz = createGroup(n);
} else {
/* else some other node type or outside of the valid user/group
hierarchy -> return null. */
log.debug("Unexpected user nodetype " + n.getPrimaryNodeType().getName());
}
} /* else no matching node -> return null */
return authorz;
}
/**
* Test if a user or group exists that has the given principals name as ID,
* which might happen if userID != principal-name.
* In this case: generate another ID for the group to be created.
*
* @param principalName to be used as hint for the group id.
* @return a group id.
* @throws RepositoryException If an error occurs.
*/
private String getGroupId(String principalName) throws RepositoryException {
String groupID = principalName;
int i = 0;
while (internalGetAuthorizable(groupID) != null) {
groupID = principalName + "_" + i;
i++;
}
return groupID;
}
/**
* @param id The user or group ID.
* @return The authorizable with the given <code>id</code> or <code>null</code>.
* @throws RepositoryException If an error occurs.
*/
private Authorizable internalGetAuthorizable(String id) throws RepositoryException {
NodeId nodeId = buildNodeId(id);
NodeImpl n = null;
try {
n = session.getNodeById(nodeId);
} catch (ItemNotFoundException e) {
if (compatibleJR16) {
// backwards-compatibility with JR < 2.0 user/group structure that doesn't
// allow to determine existence of an authorizable from the id directly.
// search for it the node belonging to that id
n = (NodeImpl) authResolver.findNode(P_USERID, id, NT_REP_USER);
if (n == null) {
// no user -> look for group.
// NOTE: JR < 2.0 always returned groupIDs that didn't contain any
// illegal JCR chars. Since Group.getID() 'unescapes' the node
// name additional escaping is required.
Name nodeName = session.getQName(Text.escapeIllegalJcrChars(id));
n = (NodeImpl) authResolver.findNode(nodeName, NT_REP_GROUP);
}
} // else: no matching node found -> ignore exception.
}
return getAuthorizable(n);
}
private Value getValue(String strValue) {
return session.getValueFactory().createValue(strValue);
}
/**
* @param userID A userID.
* @return true if the given userID belongs to the administrator user.
*/
boolean isAdminId(String userID) {
return (adminId != null) && adminId.equals(userID);
}
/**
* Build the User object from the given user node.
*
* @param userNode The new user node.
* @return An instance of <code>User</code>.
* @throws RepositoryException If the node isn't a child of the configured
* usersPath-node or if another error occurs.
*/
User createUser(NodeImpl userNode) throws RepositoryException {
if (userNode == null || !userNode.isNodeType(NT_REP_USER)) {
throw new IllegalArgumentException();
}
if (!Text.isDescendant(usersPath, userNode.getPath())) {
throw new RepositoryException("User has to be within the User Path");
}
return doCreateUser(userNode);
}
/**
* Build the user object from the given user node. May be overridden to
* return a custom implementation.
*
* @param node user node
* @return the user object
* @throws RepositoryException if an error occurs
*/
protected User doCreateUser(NodeImpl node) throws RepositoryException {
return new UserImpl(node, this);
}
/**
* Build the Group object from the given group node.
*
* @param groupNode The new group node.
* @return An instance of <code>Group</code>.
* @throws RepositoryException If the node isn't a child of the configured
* groupsPath-node or if another error occurs.
*/
Group createGroup(NodeImpl groupNode) throws RepositoryException {
if (groupNode == null || !groupNode.isNodeType(NT_REP_GROUP)) {
throw new IllegalArgumentException();
}
if (!Text.isDescendant(groupsPath, groupNode.getPath())) {
throw new RepositoryException("Group has to be within the Group Path");
}
return doCreateGroup(groupNode);
}
/**
* Build the group object from the given group node. May be overridden to
* return a custom implementation.
*
* @param node group node
* @return A group
* @throws RepositoryException if an error occurs
*/
protected Group doCreateGroup(NodeImpl node) throws RepositoryException {
return new GroupImpl(node, this);
}
/**
* Create the administrator user. If the node to be created collides
* with an existing node (ItemExistsException) the existing node gets removed
* and the admin user node is (re)created.
* <p/>
* Collision with an existing node may occur under the following circumstances:
*
* <ul>
* <li>The <code>usersPath</code> has been modified in the user manager
* configuration after a successful repository start that already created
* the administrator user.</li>
* <li>The NodeId created by {@link #buildNodeId(String)} by coincidence
* collides with another NodeId created during the regular node creation
* process.</li>
* </ul>
*
* @return The admin user.
* @throws RepositoryException If an error occurs.
*/
private User createAdmin() throws RepositoryException {
User admin;
try {
admin = createUser(adminId, adminId);
if (!isAutoSave()) {
session.save();
}
log.info("... created admin user with id \'" + adminId + "\' and default pw.");
} catch (ItemExistsException e) {
NodeImpl conflictingNode = session.getNodeById(buildNodeId(adminId));
String conflictPath = conflictingNode.getPath();
log.error("Detected conflicting node " + conflictPath + " of node type " + conflictingNode.getPrimaryNodeType().getName() + ".");
// TODO move conflicting node of type rep:User instead of removing and recreating.
conflictingNode.remove();
log.info("Removed conflicting node at " + conflictPath);
admin = createUser(adminId, adminId);
if (!isAutoSave()) {
session.save();
}
log.info("Resolved conflict and (re)created admin user with id \'" + adminId + "\' and default pw.");
}
return admin;
}
/**
* Creates a UUID from the given <code>id</code> String that is converted
* to lower case before.
*
* @param id The user/group id that needs to be converted to a valid NodeId.
* @return a new <code>NodeId</code>.
* @throws RepositoryException If an error occurs.
*/
private NodeId buildNodeId(String id) throws RepositoryException {
try {
UUID uuid = UUID.nameUUIDFromBytes(id.toLowerCase().getBytes("UTF-8"));
return new NodeId(uuid);
} catch (UnsupportedEncodingException e) {
throw new RepositoryException("Unexpected error while build ID hash", e);
}
}
/**
* Checks if the specified <code>id</code> is a non-empty string and not yet
* in use for another user or group.
*
* @param id The id of the user or group to be created.
* @throws IllegalArgumentException If the specified id is null or empty string.
* @throws AuthorizableExistsException If the id is already in use.
* @throws RepositoryException If another error occurs.
*/
private void checkValidID(String id) throws IllegalArgumentException, AuthorizableExistsException, RepositoryException {
if (id == null || id.length() == 0) {
throw new IllegalArgumentException("Cannot create authorizable: ID can neither be null nor empty String.");
}
if (internalGetAuthorizable(id) != null) {
throw new AuthorizableExistsException("User or Group for '" + id + "' already exists");
}
}
/**
* Throws <code>IllegalArgumentException</code> if the specified principal
* is <code>null</code> or if it's name is <code>null</code> or empty string.
* @param principal
*/
private static void checkValidPrincipal(Principal principal) {
if (principal == null || principal.getName() == null || "".equals(principal.getName())) {
throw new IllegalArgumentException("Principal may not be null and must have a valid name.");
}
}
private static int parseMembershipSplitSize(Object param) {
int n = 0;
if (param != null) {
try {
n = Integer.parseInt(param.toString());
if (n < 4) {
n = 0;
}
}
catch (NumberFormatException e) {
n = 0;
}
if (n == 0) {
log.warn("Invalid value {} for {}. Expected integer >= 4",
param.toString(), PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE);
}
}
return n;
}
//----------------------------------------------------< SessionListener >---
/**
* @see SessionListener#loggingOut(org.apache.jackrabbit.core.SessionImpl)
*/
public void loggingOut(SessionImpl session) {
// nothing to do.
}
/**
* @see SessionListener#loggedOut(org.apache.jackrabbit.core.SessionImpl)
*/
public void loggedOut(SessionImpl session) {
// and logout the session unless it is the logged-out session itself.
if (session != this.session) {
this.session.logout();
}
}
//------------------------------------------------------< inner classes >---
/**
* Inner class
*/
private final class AuthorizableIterator implements Iterator<Authorizable> {
private final Set<String> served = new HashSet<String>();
private Authorizable next;
private final NodeIterator authNodeIter;
private AuthorizableIterator(NodeIterator authNodeIter) {
this.authNodeIter = authNodeIter;
next = seekNext();
}
//-------------------------------------------------------< Iterator >---
/**
* @see Iterator#hasNext()
*/
public boolean hasNext() {
return next != null;
}
/**
* @see Iterator#next()
*/
public Authorizable next() {
Authorizable authr = next;
if (authr == null) {
throw new NoSuchElementException();
}
next = seekNext();
return authr;
}
/**
* @see Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
//----------------------------------------------------------------------
private Authorizable seekNext() {
while (authNodeIter.hasNext()) {
NodeImpl node = (NodeImpl) authNodeIter.nextNode();
try {
if (!served.contains(node.getUUID())) {
Authorizable authr = getAuthorizable(node);
served.add(node.getUUID());
if (authr != null) {
return authr;
}
}
} catch (RepositoryException e) {
log.debug(e.getMessage());
// continue seeking next authorizable
}
}
// no next authorizable -> iteration is completed.
return null;
}
}
//--------------------------------------------------------------------------
/**
* Inner class creating the JCR nodes corresponding the a given
* authorizable ID with the following behavior:
* <ul>
* <li>Users are created below /rep:security/rep:authorizables/rep:users or
* the corresponding path configured.</li>
* <li>Groups are created below /rep:security/rep:authorizables/rep:groups or
* the corresponding path configured.</li>
* <li>Below each category authorizables are created within a human readable
* structure based on the defined intermediate path or some internal logic
* with a depth defined by the <code>defaultDepth</code> config option.<br>
* E.g. creating a user node for an ID 'aSmith' would result in the following
* structure assuming defaultDepth == 2 is used:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* -> + aSmith [rep:User]
* </pre>
* </li>
* <li>In case of a user the node name is calculated from the specified UserID
* {@link Text#escapeIllegalJcrChars(String) escaping} any illegal JCR chars.
* In case of a Group the node name is calculated from the specified principal
* name circumventing any conflicts with existing ids and escaping illegal chars.</li>
* <li>If no intermediate path is passed the names of the intermediate
* folders are calculated from the leading chars of the escaped node name.</li>
* <li>If the escaped node name is shorter than the <code>defaultDepth</code>
* the last char is repeated.<br>
* E.g. creating a user node for an ID 'a' would result in the following
* structure assuming defaultDepth == 2 is used:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aa [rep:AuthorizableFolder]
* -> + a [rep:User]
* </pre>
* </li>
* <li>If the <code>autoExpandTree</code> option is <code>true</code> the
* user tree will be automatically expanded using additional levels if
* <code>autoExpandSize</code> is exceeded within a given level.</li>
* </ul>
*
* The auto-expansion of the authorizable tree is defined by the following
* steps and exceptional cases:
* <ul>
* <li>As long as <code>autoExpandSize</code> isn't reached authorizable
* nodes are created within the structure defined by the
* <code>defaultDepth</code>. (see above)</li>
* <li>If <code>autoExpandSize</code> is reached additional intermediate
* folders will be created.<br>
* E.g. creating a user node for an ID 'aSmith1001' would result in the
* following structure:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* + aSmith1 [rep:User]
* + aSmith2 [rep:User]
* [...]
* + aSmith1000 [rep:User]
* -> + aSm [rep:AuthorizableFolder]
* -> + aSmith1001 [rep:User]
* </pre>
* </li>
* <li>Conflicts: In order to prevent any conflicts that would arise from
* creating a authorizable node that upon later expansion could conflict
* with an authorizable folder, intermediate levels are always created if
* the node name equals any of the names reserved for the next level of
* folders.<br>
* In the example above any attempt to create a user with ID 'aSm' would
* result in an intermediate level irrespective if max-size has been
* reached or not:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* -> + aSm [rep:AuthorizableFolder]
* -> + aSm [rep:User]
* </pre>
* </li>
* <li>Special case: If the name of the authorizable node to be created is
* shorter or equal to the length of the folder at level N, the authorizable
* node is created even if max-size has been reached before.<br>
* An attempt to create the users 'aS' and 'aSm' in a structure containing
* tons of 'aSmith' users will therefore result in:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* + aSmith1 [rep:User]
* + aSmith2 [rep:User]
* [...]
* + aSmith1000 [rep:User]
* -> + aS [rep:User]
* + aSm [rep:AuthorizableFolder]
* + aSmith1001 [rep:User]
* -> + aSm [rep:User]
* </pre>
* </li>
* <li>Special case: If <code>autoExpandTree</code> is enabled later on
* AND any of the existing authorizable nodes collides with an intermediate
* folder to be created the auto-expansion is aborted and the new
* authorizable is inserted at the last valid level irrespective of
* max-size being reached.
* </li>
* </ul>
*
* The configuration options:
* <ul>
* <li><strong>defaultDepth</strong>:<br>
* A positive <code>integer</code> greater than zero defining the depth of
* the default structure that is always created.<br>
* Default value: 2</li>
* <li><strong>autoExpandTree</strong>:<br>
* <code>boolean</code> defining if the tree gets automatically expanded
* if within a level the maximum number of child nodes is reached.<br>
* Default value: <code>false</code></li>
* <li><strong>autoExpandSize</strong>:<br>
* A positive <code>long</code> greater than zero defining the maximum
* number of child nodes that are allowed at a given level.<br>
* Default value: 1000<br>
* NOTE: that total number of child nodes may still be greater that
* autoExpandSize.</li>
* </ul>
*/
private class NodeCreator {
private static final String DELIMITER = "/";
private static final int DEFAULT_DEPTH = 2;
private static final long DEFAULT_SIZE = 1000;
private final int defaultDepth;
private final boolean autoExpandTree;
// best effort max-size of authorizables per folder. there may be
// more nodes created if the editing session isn't allowed to see
// all child nodes.
private final long autoExpandSize;
private NodeCreator(Properties config) {
int d = DEFAULT_DEPTH;
boolean expand = false;
long size = DEFAULT_SIZE;
if (config != null) {
if (config.containsKey(PARAM_DEFAULT_DEPTH)) {
try {
d = Integer.parseInt(config.get(PARAM_DEFAULT_DEPTH).toString());
if (d <= 0) {
log.warn("Invalid defaultDepth '" + d + "' -> using default.");
d = DEFAULT_DEPTH;
}
} catch (NumberFormatException e) {
log.warn("Unable to parse defaultDepth config parameter -> using default.", e);
}
}
if (config.containsKey(PARAM_AUTO_EXPAND_TREE)) {
expand = Boolean.parseBoolean(config.get(PARAM_AUTO_EXPAND_TREE).toString());
}
if (config.containsKey(PARAM_AUTO_EXPAND_SIZE)) {
try {
size = Integer.parseInt(config.get(PARAM_AUTO_EXPAND_SIZE).toString());
if (expand && size <= 0) {
log.warn("Invalid autoExpandSize '" + size + "' -> using default.");
size = DEFAULT_SIZE;
}
} catch (NumberFormatException e) {
log.warn("Unable to parse autoExpandSize config parameter -> using default.", e);
}
}
}
defaultDepth = d;
autoExpandTree = expand;
autoExpandSize = size;
}
public Node createUserNode(String userID, String intermediatePath) throws RepositoryException {
return createAuthorizableNode(userID, false, intermediatePath);
}
public Node createGroupNode(String groupID, String intermediatePath) throws RepositoryException {
return createAuthorizableNode(groupID, true, intermediatePath);
}
private Node createAuthorizableNode(String id, boolean isGroup, String intermediatePath) throws RepositoryException {
String escapedId = Text.escapeIllegalJcrChars(id);
Node folder;
// first create the default folder nodes, that are always present.
folder = createDefaultFolderNodes(id, escapedId, isGroup, intermediatePath);
// eventually create additional intermediate folders.
if (intermediatePath == null) {
// internal logic only
folder = createIntermediateFolderNodes(id, escapedId, folder);
}
Name nodeName = session.getQName(escapedId);
Name ntName = (isGroup) ? NT_REP_GROUP : NT_REP_USER;
NodeId nid = buildNodeId(id);
// check if there exists an colliding folder child node.
while (((NodeImpl) folder).hasNode(nodeName)) {
NodeImpl colliding = ((NodeImpl) folder).getNode(nodeName);
if (colliding.isNodeType(NT_REP_AUTHORIZABLE_FOLDER)) {
log.warn("Existing folder node collides with user/group to be created. Expanding path: " + colliding.getPath());
folder = colliding;
} else {
// should never get here as folder creation above already
// asserts that only rep:authorizable folders exist.
// similarly collisions with existing authorizable have been
// checked.
String msg = "Failed to create authorizable with id '" + id + "' : Detected conflicting node of unexpected nodetype '" + colliding.getPrimaryNodeType().getName() + "'.";
log.error(msg);
throw new ConstraintViolationException(msg);
}
}
// check for collision with existing node outside of the user/group tree
if (session.getItemManager().itemExists(nid)) {
String msg = "Failed to create authorizable with id '" + id + "' : Detected conflict with existing node (NodeID: " + nid + ")";
log.error(msg);
throw new ItemExistsException(msg);
}
// finally create the authorizable node
return addNode((NodeImpl) folder, nodeName, ntName, nid);
}
private Node createDefaultFolderNodes(String id, String escapedId,
boolean isGroup, String intermediatePath) throws RepositoryException {
String defaultPath = getDefaultFolderPath(id, isGroup, intermediatePath);
// make sure users/groups are never nested and exclusively created
// under a tree of rep:AuthorizableFolder(s) starting at usersPath
// or groupsPath, respectively. ancestors of the usersPath/groupsPath
// may or may not be rep:AuthorizableFolder(s).
// therefore the shortcut Session.getNode(defaultPath) is omitted.
String[] segmts = defaultPath.split("/");
NodeImpl folder = (NodeImpl) session.getRootNode();
String authRoot = (isGroup) ? groupsPath : usersPath;
for (String segment : segmts) {
if (segment.length() < 1) {
continue;
}
if (folder.hasNode(segment)) {
folder = (NodeImpl) folder.getNode(segment);
if (Text.isDescendantOrEqual(authRoot, folder.getPath()) &&
!folder.isNodeType(NT_REP_AUTHORIZABLE_FOLDER)) {
throw new ConstraintViolationException("Invalid intermediate path. Must be of type rep:AuthorizableFolder.");
}
} else {
folder = addNode(folder, session.getQName(segment), NT_REP_AUTHORIZABLE_FOLDER);
}
}
// validation check if authorizable to be created doesn't conflict.
checkAuthorizableNodeExists(escapedId, folder);
return folder;
}
private String getDefaultFolderPath(String id, boolean isGroup, String intermediatePath) {
StringBuilder bld = new StringBuilder();
if (isGroup) {
bld.append(groupsPath);
} else {
bld.append(usersPath);
}
if (intermediatePath == null) {
// internal logic
StringBuilder lastSegment = new StringBuilder(defaultDepth);
int idLength = id.length();
for (int i = 0; i < defaultDepth; i++) {
if (idLength > i) {
lastSegment.append(id.charAt(i));
} else {
// escapedID is too short -> append the last char again
lastSegment.append(id.charAt(idLength-1));
}
bld.append(DELIMITER).append(Text.escapeIllegalJcrChars(lastSegment.toString()));
}
} else {
// structure defined by intermediate path
if (intermediatePath.startsWith(bld.toString())) {
intermediatePath = intermediatePath.substring(bld.toString().length());
}
if (intermediatePath.length() > 0 && !"/".equals(intermediatePath)) {
if (!intermediatePath.startsWith("/")) {
bld.append("/");
}
bld.append(intermediatePath);
}
}
return bld.toString();
}
private Node createIntermediateFolderNodes(String id, String escapedId, Node folder) throws RepositoryException {
if (!autoExpandTree) {
// additional folders are never created
return folder;
}
// additional folders needs be created if
// - the maximal size of child nodes is reached
// - if the authorizable node to be created potentially collides with
// any of the intermediate nodes.
int segmLength = defaultDepth +1;
while (intermediateFolderNeeded(escapedId, folder)) {
String folderName = Text.escapeIllegalJcrChars(id.substring(0, segmLength));
if (folder.hasNode(folderName)) {
NodeImpl n = (NodeImpl) folder.getNode(folderName);
// validation check: folder must be of type rep:AuthorizableFolder
// and not an authorizable node.
if (n.isNodeType(NT_REP_AUTHORIZABLE_FOLDER)) {
// expected nodetype -> no violation
folder = n;
} else if (n.isNodeType(NT_REP_AUTHORIZABLE)){
/*
an authorizable node has been created before with the
name of the intermediate folder to be created.
this may only occur if the 'autoExpandTree' option has
been enabled later on.
Resolution:
- abort auto-expanding and create the authorizable
at the current level, ignoring that max-size is reached.
- note, that this behavior has been preferred over tmp.
removing and recreating the colliding authorizable node.
*/
log.warn("Auto-expanding aborted. An existing authorizable node '" + n.getName() +"'conflicts with intermediate folder to be created.");
break;
} else {
// should never get here: some other, unexpected node type
String msg = "Failed to create authorizable node: Detected conflict with node of unexpected nodetype '" + n.getPrimaryNodeType().getName() + "'.";
log.error(msg);
throw new ConstraintViolationException(msg);
}
} else {
// folder doesn't exist nor does another colliding child node.
folder = addNode((NodeImpl) folder, session.getQName(folderName), NT_REP_AUTHORIZABLE_FOLDER);
}
segmLength++;
}
// final validation check if authorizable to be created doesn't conflict.
checkAuthorizableNodeExists(escapedId, folder);
return folder;
}
private void checkAuthorizableNodeExists(String nodeName, Node folder) throws AuthorizableExistsException, RepositoryException {
if (folder.hasNode(nodeName) &&
((NodeImpl) folder.getNode(nodeName)).isNodeType(NT_REP_AUTHORIZABLE)) {
throw new AuthorizableExistsException("Unable to create Group/User: Collision with existing authorizable.");
}
}
private boolean intermediateFolderNeeded(String nodeName, Node folder) throws RepositoryException {
// don't create additional intermediate folders for ids that are
// shorter or equally long as the folder name. In this case the
// MAX_SIZE flag is ignored.
if (nodeName.length() <= folder.getName().length()) {
return false;
}
// test for potential (or existing) collision in which case the
// intermediate node is created irrespective of the MAX_SIZE and the
// existing number of children.
if (nodeName.length() == folder.getName().length()+1) {
// max-size may not yet be reached yet on folder but the node to
// be created potentially collides with an intermediate folder.
// e.g.:
// existing folder structure: a/ab
// authID to be created : abt
// OR
// existing collision that would result from
// existing folder structure: a/ab/abt
// authID to be create : abt
return true;
}
// last possibility: max-size is reached.
if (folder.getNodes().getSize() >= autoExpandSize) {
return true;
}
// no collision and no need to create an additional intermediate
// folder due to max-size reached
return false;
}
}
}
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/security/user/UserManagerImpl.java | /*
* 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.jackrabbit.core.security.user;
import org.apache.jackrabbit.api.security.principal.ItemBasedPrincipal;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.AuthorizableExistsException;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.Query;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.core.ItemImpl;
import org.apache.jackrabbit.core.NodeImpl;
import org.apache.jackrabbit.core.ProtectedItemModifier;
import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.SessionListener;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.security.SystemPrincipal;
import org.apache.jackrabbit.core.security.principal.PrincipalImpl;
import org.apache.jackrabbit.core.session.SessionOperation;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.Path;
import org.apache.jackrabbit.util.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.AccessDeniedException;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.version.VersionException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
/**
* Default implementation of the <code>UserManager</code> interface with the
* following characteristics:
*
* <ul>
* <li>Users and Groups are stored in the repository as JCR nodes.</li>
* <li>Users are created below {@link UserConstants#USERS_PATH},<br>Groups are
* created below {@link UserConstants#GROUPS_PATH} (unless otherwise configured).</li>
* <li>The Id of an authorizable is stored in the jcr:uuid property (md5 hash).</li>
* <li>In order to structure the users and groups tree and avoid creating a flat
* hierarchy, additional hierarchy nodes of type "rep:AuthorizableFolder" are
* introduced using
* <ul>
* <li>the specified intermediate path passed to the create methods</li>
* <li>or some built-in logic if the intermediate path is missing.</li>
* </ul>
* </li>
* </ul>
*
* The built-in logic applies the following rules:
* <ul>
* <li>The names of the hierarchy folders is determined from ID of the
* authorizable to be created, consisting of the leading N chars where N is
* the relative depth starting from the node at {@link #getUsersPath()}
* or {@link #getGroupsPath()}.</li>
* <li>By default 2 levels (depth == 2) are created.</li>
* <li>Parent nodes are expected to consist of folder structure only.</li>
* <li>If the ID contains invalid JCR chars that would prevent the creation of
* a Node with that name, the names of authorizable node and the intermediate
* hierarchy nodes are {@link Text#escapeIllegalJcrChars(String) escaped}.</li>
* </ul>
* Examples:
* Creating an non-existing user with ID 'aSmith' without specifying an
* intermediate path would result in the following structure:
*
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* + aSmith [rep:User]
* </pre>
*
* Creating a non-existing user with ID 'aSmith' specifying an intermediate
* path 'some/tree' would result in the following structure:
*
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + some [rep:AuthorizableFolder]
* + tree [rep:AuthorizableFolder]
* + aSmith [rep:User]
* </pre>
*
* This <code>UserManager</code> is able to handle the following configuration
* options:
*
* <ul>
* <li>{@link #PARAM_USERS_PATH}: Defines where user nodes are created.
* If missing set to {@link #USERS_PATH}.</li>
* <li>{@link #PARAM_GROUPS_PATH}. Defines where group nodes are created.
* If missing set to {@link #GROUPS_PATH}.</li>
* <li>{@link #PARAM_COMPATIBILE_JR16}: If the param is present and its
* value is <code>true</code> looking up authorizables by ID will use the
* <code>NodeResolver</code> if not found otherwise.<br>
* If the parameter is missing (or false) users and groups created
* with a Jackrabbit repository < v2.0 will not be found any more.<br>
* By default this option is disabled.</li>
* <li>{@link #PARAM_DEFAULT_DEPTH}: Parameter used to change the number of
* levels that are used by default to store authorizable nodes.<br>The value is
* expected to be a positive integer greater than zero. The default
* number of levels is 2.
* </li>
* <li>{@link #PARAM_AUTO_EXPAND_TREE}: If this parameter is present and its
* value is <code>true</code>, the trees containing user and group nodes will
* automatically created additional hierarchy levels if the number of nodes
* on a given level exceeds the maximal allowed {@link #PARAM_AUTO_EXPAND_SIZE size}.
* <br>By default this option is disabled.</li>
* <li>{@link #PARAM_AUTO_EXPAND_SIZE}: This parameter only takes effect
* if {@link #PARAM_AUTO_EXPAND_TREE} is enabled.<br>The value is expected to be
* a positive long greater than zero. The default value is 1000.</li>
* </ul>
*/
public class UserManagerImpl extends ProtectedItemModifier
implements UserManager, UserConstants, SessionListener {
/**
* Configuration option to change the
* {@link UserConstants#USERS_PATH default path} for creating users.
*/
public static final String PARAM_USERS_PATH = "usersPath";
/**
* Configuration option to change the
* {@link UserConstants#GROUPS_PATH default path} for creating groups.
*/
public static final String PARAM_GROUPS_PATH = "groupsPath";
/**
* Flag to enable a minimal backwards compatibility with Jackrabbit <
* v2.0<br>
* If the param is present and its value is <code>true</code> looking up
* authorizables by ID will use the <code>NodeResolver</code> if not found
* otherwise.<br>
* If the parameter is missing (or false) users and groups created
* with a Jackrabbit repository < v2.0 will not be found any more.<br>
* By default this option is disabled.
*/
public static final String PARAM_COMPATIBILE_JR16 = "compatibleJR16";
/**
* Parameter used to change the number of levels that are used by default
* store authorizable nodes.<br>The default number of levels is 2.
* <p/>
* <strong>NOTE:</strong> Changing the default depth once users and groups
* have been created in the repository will cause inconsistencies, due to
* the fact that the resolution of ID to an authorizable relies on the
* structure defined by the default depth.<br>
* It is recommended to remove all authorizable nodes that will not be
* reachable any more, before this config option is changed.
* <ul>
* <li>If default depth is increased:<br>
* All authorizables on levels < default depth are not reachable any more.</li>
* <li>If default depth is decreased:<br>
* All authorizables on levels > default depth aren't reachable any more
* unless the {@link #PARAM_AUTO_EXPAND_TREE} flag is set to <code>true</code>.</li>
* </ul>
*/
public static final String PARAM_DEFAULT_DEPTH = "defaultDepth";
/**
* If this parameter is present and its value is <code>true</code>, the trees
* containing user and group nodes will automatically created additional
* hierarchy levels if the number of nodes on a given level exceeds the
* maximal allowed {@link #PARAM_AUTO_EXPAND_SIZE size}.
* <br>By default this option is disabled.
*/
public static final String PARAM_AUTO_EXPAND_TREE = "autoExpandTree";
/**
* This parameter only takes effect if {@link #PARAM_AUTO_EXPAND_TREE} is
* enabled.<br>The default value is 1000.
*/
public static final String PARAM_AUTO_EXPAND_SIZE = "autoExpandSize";
/**
* If this parameter is present group memberships are collected in a node
* structure below {@link UserConstants#N_MEMBERS} instead of the default
* multi valued property {@link UserConstants#P_MEMBERS}. Its value determines
* the maximum number of member properties until additional intermediate nodes
* are inserted. Valid values are integers > 4.
*/
public static final String PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE = "groupMembershipSplitSize";
private static final Logger log = LoggerFactory.getLogger(UserManagerImpl.class);
private final SessionImpl session;
private final String adminId;
private final NodeResolver authResolver;
private final NodeCreator nodeCreator;
/**
* Configuration value defining the node where User nodes will be created.
* Default value is {@link UserConstants#USERS_PATH}.
*/
private final String usersPath;
/**
* Configuration value defining the node where Group nodes will be created.
* Default value is {@link UserConstants#GROUPS_PATH}.
*/
private final String groupsPath;
/**
* Flag indicating if {@link #getAuthorizable(String)} should be able to deal
* with users or groups created with Jackrabbit < 2.0.<br>
* As of 2.0 authorizables are created using a defined logic that allows
* to retrieve them without searching/traversing. If this flag is
* <code>true</code> this method will try to find authorizables using the
* <code>authResolver</code> if not found otherwise.
*/
private final boolean compatibleJR16;
/**
* boolean flag indicating whether the editing session is a system session.
*/
private final boolean isSystemUserManager;
/**
* Maximum number of properties on the group membership node structure under
* {@link UserConstants#N_MEMBERS} until additional intermediate nodes are inserted.
* If 0 (default), {@link UserConstants#P_MEMBERS} is used to record group
* memberships.
*/
private final int groupMembershipSplitSize;
private final MembershipCache membershipCache;
/**
* Create a new <code>UserManager</code> with the default configuration.
*
* @param session The editing/reading session.
* @param adminId The user ID of the administrator.
*/
public UserManagerImpl(SessionImpl session, String adminId) throws RepositoryException {
this(session, adminId, null, null);
}
/**
* Create a new <code>UserManager</code>
*
* @param session The editing/reading session.
* @param adminId The user ID of the administrator.
* @param config The configuration parameters.
*/
public UserManagerImpl(SessionImpl session, String adminId, Properties config) throws RepositoryException {
this(session, adminId, config, null);
}
/**
* Create a new <code>UserManager</code> for the given <code>session</code>.
* Currently the following configuration options are respected:
*
* <ul>
* <li>{@link #PARAM_USERS_PATH}. If missing set to {@link UserConstants#USERS_PATH}.</li>
* <li>{@link #PARAM_GROUPS_PATH}. If missing set to {@link UserConstants#GROUPS_PATH}.</li>
* <li>{@link #PARAM_DEFAULT_DEPTH}. The default number of levels is 2.</li>
* <li>{@link #PARAM_AUTO_EXPAND_TREE}. By default this option is disabled.</li>
* <li>{@link #PARAM_AUTO_EXPAND_SIZE}. The default value is 1000.</li>
* <li>{@link #PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE}. The default is 0 which means use
* {@link UserConstants#P_MEMBERS}.</li>
* </ul>
*
* See the overall {@link UserManagerImpl introduction} for details.
*
* @param session The editing/reading session.
* @param adminId The user ID of the administrator.
* @param config The configuration parameters.
* @param mCache Shared membership cache.
* @throws javax.jcr.RepositoryException
*/
public UserManagerImpl(SessionImpl session, String adminId, Properties config,
MembershipCache mCache) throws RepositoryException {
this.session = session;
this.adminId = adminId;
nodeCreator = new NodeCreator(config);
Object param = (config != null) ? config.get(PARAM_USERS_PATH) : null;
usersPath = (param != null) ? param.toString() : USERS_PATH;
param = (config != null) ? config.get(PARAM_GROUPS_PATH) : null;
groupsPath = (param != null) ? param.toString() : GROUPS_PATH;
param = (config != null) ? config.get(PARAM_COMPATIBILE_JR16) : null;
compatibleJR16 = (param != null) && Boolean.parseBoolean(param.toString());
param = (config != null) ? config.get(PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE) : null;
groupMembershipSplitSize = parseMembershipSplitSize(param);
if (mCache != null) {
membershipCache = mCache;
} else {
membershipCache = new MembershipCache(session, groupsPath, groupMembershipSplitSize > 0);
}
NodeResolver nr;
try {
nr = new IndexNodeResolver(session, session);
} catch (RepositoryException e) {
log.debug("UserManager: no QueryManager available for workspace '" + session.getWorkspace().getName() + "' -> Use traversing node resolver.");
nr = new TraversingNodeResolver(session, session);
}
authResolver = nr;
authResolver.setSearchRoots(usersPath, groupsPath);
/**
* evaluate if the editing session is a system session. since the
* SystemSession class is package protected the session object cannot
* be checked for the property instance.
*
* workaround: compare the class name and check if the subject contains
* the system principal.
*/
isSystemUserManager = "org.apache.jackrabbit.core.SystemSession".equals(session.getClass().getName()) &&
!session.getSubject().getPrincipals(SystemPrincipal.class).isEmpty();
}
/**
* Implementation specific methods releaving where users are created within
* the content.
*
* @return root path for user content.
* @see #PARAM_USERS_PATH For the corresponding configuration parameter.
*/
public String getUsersPath() {
return usersPath;
}
/**
* Implementation specific methods releaving where groups are created within
* the content.
*
* @return root path for group content.
* @see #PARAM_GROUPS_PATH For the corresponding configuration parameter.
*/
public String getGroupsPath() {
return groupsPath;
}
/**
* @return The membership cache present with this user manager instance.
*/
public MembershipCache getMembershipCache() {
return membershipCache;
}
//--------------------------------------------------------< UserManager >---
/**
* @see UserManager#getAuthorizable(String)
*/
public Authorizable getAuthorizable(String id) throws RepositoryException {
if (id == null || id.length() == 0) {
throw new IllegalArgumentException("Invalid authorizable name '" + id + "'");
}
Authorizable a = internalGetAuthorizable(id);
/**
* Extra check for the existence of the administrator user that must
* always exist.
* In case it got removed if must be recreated using a system session.
* Since a regular session may lack read permission on the admin-user's
* node an explicit test for the current editing session being
* a system session is performed.
*/
if (a == null && adminId.equals(id) && isSystemUserManager) {
log.info("Admin user does not exist.");
a = createAdmin();
}
return a;
}
/**
* @see UserManager#getAuthorizable(Principal)
*/
public Authorizable getAuthorizable(Principal principal) throws RepositoryException {
NodeImpl n = null;
// shortcuts that avoids executing a query.
if (principal instanceof AuthorizableImpl.NodeBasedPrincipal) {
NodeId nodeId = ((AuthorizableImpl.NodeBasedPrincipal) principal).getNodeId();
try {
n = session.getNodeById(nodeId);
} catch (ItemNotFoundException e) {
// no such authorizable -> null
}
} else if (principal instanceof ItemBasedPrincipal) {
String authPath = ((ItemBasedPrincipal) principal).getPath();
if (session.nodeExists(authPath)) {
n = (NodeImpl) session.getNode(authPath);
}
} else {
// another Principal implementation.
// a) try short-cut that works in case of ID.equals(principalName) only.
// b) execute query in case of pName mismatch or exception. however, query
// requires persisted user nodes (see known issue of UserImporter).
String name = principal.getName();
try {
Authorizable a = internalGetAuthorizable(name);
if (a != null && name.equals(a.getPrincipal().getName())) {
return a;
}
} catch (RepositoryException e) {
// ignore and execute the query.
}
// authorizable whose ID matched the principal name -> search.
n = (NodeImpl) authResolver.findNode(P_PRINCIPAL_NAME, name, NT_REP_AUTHORIZABLE);
}
// build the corresponding authorizable object
return getAuthorizable(n);
}
/**
* @see UserManager#findAuthorizables(String,String)
*/
public Iterator<Authorizable> findAuthorizables(String relPath, String value) throws RepositoryException {
return findAuthorizables(relPath, value, SEARCH_TYPE_AUTHORIZABLE);
}
/**
* @see UserManager#findAuthorizables(String,String, int)
*/
public Iterator<Authorizable> findAuthorizables(String relPath, String value, int searchType)
throws RepositoryException {
if (searchType < SEARCH_TYPE_USER || searchType > SEARCH_TYPE_AUTHORIZABLE) {
throw new IllegalArgumentException("Invalid search type " + searchType);
}
Path path = session.getQPath(relPath);
NodeIterator nodes;
if (relPath.indexOf('/') == -1) {
// search for properties somewhere below an authorizable node
nodes = authResolver.findNodes(path, value, searchType, true, Long.MAX_VALUE);
} else {
path = path.getNormalizedPath();
if (path.getLength() == 1) {
// only search below the authorizable node
Name ntName;
switch (searchType) {
case SEARCH_TYPE_GROUP:
ntName = NT_REP_GROUP;
break;
case SEARCH_TYPE_USER:
ntName = NT_REP_USER;
break;
default:
ntName = NT_REP_AUTHORIZABLE;
}
nodes = authResolver.findNodes(path.getName(), value, ntName, true);
} else {
// search below authorizable nodes but take some path constraints
// into account.
nodes = authResolver.findNodes(path, value, searchType, true, Long.MAX_VALUE);
}
}
return new AuthorizableIterator(nodes);
}
public Iterator<Authorizable> findAuthorizables(Query query) throws RepositoryException {
XPathQueryBuilder builder = new XPathQueryBuilder();
query.build(builder);
return new XPathQueryEvaluator(builder, this, session).eval();
}
/**
* @see UserManager#createUser(String,String)
*/
public User createUser(String userID, String password) throws RepositoryException {
return createUser(userID, password, new PrincipalImpl(userID), null);
}
/**
* @see UserManager#createUser(String, String, java.security.Principal, String)
*/
public User createUser(String userID, String password,
Principal principal, String intermediatePath)
throws AuthorizableExistsException, RepositoryException {
checkValidID(userID);
if (password == null) {
throw new IllegalArgumentException("Cannot create user: null password.");
}
// NOTE: principal validation during setPrincipal call.
try {
NodeImpl userNode = (NodeImpl) nodeCreator.createUserNode(userID, intermediatePath);
setPrincipal(userNode, principal);
setProperty(userNode, P_PASSWORD, getValue(UserImpl.buildPasswordValue(password)), true);
User user = createUser(userNode);
if (isAutoSave()) {
session.save();
}
log.debug("User created: " + userID + "; " + userNode.getPath());
return user;
} catch (RepositoryException e) {
// something went wrong -> revert changes and re-throw
session.refresh(false);
log.debug("Failed to create new User, reverting changes.");
throw e;
}
}
/**
* @see UserManager#createGroup(String)
*/
public Group createGroup(String groupID)
throws AuthorizableExistsException, RepositoryException {
return createGroup(groupID, new PrincipalImpl(groupID), null);
}
/**
* Same as {@link #createGroup(java.security.Principal, String)} where the
* intermediate path is <code>null</code>.
* @see UserManager#createGroup(Principal)
*/
public Group createGroup(Principal principal) throws RepositoryException {
return createGroup(principal, null);
}
/**
* Same as {@link #createGroup(String, Principal, String)} where a groupID
* is generated from the principal name. If the name conflicts with an
* existing authorizable ID (may happen in cases where
* principal name != ID) the principal name is expanded by a suffix;
* otherwise the resulting group ID equals the principal name.
*
* @param principal A principal that doesn't yet represent an existing user
* or group.
* @param intermediatePath Is always ignored.
* @return A new group.
* @throws AuthorizableExistsException
* @throws RepositoryException
* @see UserManager#createGroup(java.security.Principal, String)
*/
public Group createGroup(Principal principal, String intermediatePath) throws AuthorizableExistsException, RepositoryException {
checkValidPrincipal(principal);
String groupID = getGroupId(principal.getName());
return createGroup(groupID, principal, intermediatePath);
}
/**
* Create a new <code>Group</code> from the given <code>groupID</code> and
* <code>principal</code>. It will be created below the defined
* {@link #getGroupsPath() group path}.<br>
* Non-existent elements of the Path will be created as nodes
* of type {@link #NT_REP_AUTHORIZABLE_FOLDER rep:AuthorizableFolder}.
*
* @param groupID A groupID that hasn't been used before for another
* user or group.
* @param principal A principal that doesn't yet represent an existing user
* or group.
* @param intermediatePath Is always ignored.
* @return A new group.
* @throws AuthorizableExistsException
* @throws RepositoryException
* @see UserManager#createGroup(String, java.security.Principal, String)
*/
public Group createGroup(String groupID, Principal principal, String intermediatePath) throws AuthorizableExistsException, RepositoryException {
checkValidID(groupID);
// NOTE: principal validation during setPrincipal call.
try {
NodeImpl groupNode = (NodeImpl) nodeCreator.createGroupNode(groupID, intermediatePath);
if (principal != null) {
setPrincipal(groupNode, principal);
}
Group group = createGroup(groupNode);
if (isAutoSave()) {
session.save();
}
log.debug("Group created: " + groupID + "; " + groupNode.getPath());
return group;
} catch (RepositoryException e) {
session.refresh(false);
log.debug("newInstance new Group failed, revert changes on parent");
throw e;
}
}
/**
* Always returns <code>true</code> as by default the autoSave behavior
* cannot be altered (see also {@link #autoSave(boolean)}.
*
* @return Always <code>true</code>.
* @see org.apache.jackrabbit.api.security.user.UserManager#isAutoSave()
*/
public boolean isAutoSave() {
return true;
}
/**
* Always throws <code>unsupportedRepositoryOperationException</code> as
* modification of the autosave behavior is not supported.
*
* @see UserManager#autoSave(boolean)
*/
public void autoSave(boolean enable) throws UnsupportedRepositoryOperationException, RepositoryException {
throw new UnsupportedRepositoryOperationException("Cannot change autosave behavior.");
}
/**
* Maximum number of properties on the group membership node structure under
* {@link UserConstants#N_MEMBERS} until additional intermediate nodes are inserted.
* If 0 (default), {@link UserConstants#P_MEMBERS} is used to record group
* memberships.
*
* @return
*/
public int getGroupMembershipSplitSize() {
return groupMembershipSplitSize;
}
//--------------------------------------------------------------------------
/**
*
* @param node The new user/group node.
* @param principal A valid non-null principal.
* @throws AuthorizableExistsException If there is already another user/group
* with the same principal name.
* @throws RepositoryException If another error occurs.
*/
void setPrincipal(NodeImpl node, Principal principal) throws AuthorizableExistsException, RepositoryException {
checkValidPrincipal(principal);
/*
Check if there is *another* authorizable with the same principal.
The additional validation (nodes not be same) is required in order to
circumvent problems with re-importing existing authorizable in which
case the original user/group node is being recreated but the search
used to look for an colliding authorizable still finds the persisted
node.
*/
Authorizable existing = getAuthorizable(principal);
if (existing != null && !((AuthorizableImpl) existing).getNode().isSame(node)) {
throw new AuthorizableExistsException("Authorizable for '" + principal.getName() + "' already exists: ");
}
if (!node.isNew() || node.hasProperty(P_PRINCIPAL_NAME)) {
throw new RepositoryException("rep:principalName can only be set once on a new node.");
}
setProperty(node, P_PRINCIPAL_NAME, getValue(principal.getName()), true);
}
void setProtectedProperty(NodeImpl node, Name propName, Value value) throws RepositoryException, LockException, ConstraintViolationException, ItemExistsException, VersionException {
setProperty(node, propName, value);
if (isAutoSave()) {
node.save();
}
}
void setProtectedProperty(NodeImpl node, Name propName, Value[] values) throws RepositoryException, LockException, ConstraintViolationException, ItemExistsException, VersionException {
setProperty(node, propName, values);
if (isAutoSave()) {
node.save();
}
}
void setProtectedProperty(NodeImpl node, Name propName, Value[] values, int type) throws RepositoryException, LockException, ConstraintViolationException, ItemExistsException, VersionException {
setProperty(node, propName, values, type);
if (isAutoSave()) {
node.save();
}
}
void removeProtectedItem(ItemImpl item, Node parent) throws RepositoryException, AccessDeniedException, VersionException {
removeItem(item);
if (isAutoSave()) {
parent.save();
}
}
NodeImpl addProtectedNode(NodeImpl parent, Name name, Name ntName) throws RepositoryException {
NodeImpl n = addNode(parent, name, ntName);
if (isAutoSave()) {
parent.save();
}
return n;
}
<T> T performProtectedOperation(SessionImpl session, SessionOperation<T> operation) throws RepositoryException {
return performProtected(session, operation);
}
/**
* Implementation specific method used to retrieve a user/group by Node.
* <code>Null</code> is returned if
* <pre>
* - the passed node is <code>null</code>,
* - doesn't have the correct node type or
* - isn't placed underneath the configured user/group tree.
* </pre>
*
* @param n A user/group node.
* @return An authorizable or <code>null</code>.
* @throws RepositoryException If an error occurs.
*/
Authorizable getAuthorizable(NodeImpl n) throws RepositoryException {
Authorizable authorz = null;
if (n != null) {
String path = n.getPath();
if (n.isNodeType(NT_REP_USER) && Text.isDescendant(usersPath, path)) {
authorz = createUser(n);
} else if (n.isNodeType(NT_REP_GROUP) && Text.isDescendant(groupsPath, path)) {
authorz = createGroup(n);
} else {
/* else some other node type or outside of the valid user/group
hierarchy -> return null. */
log.debug("Unexpected user nodetype " + n.getPrimaryNodeType().getName());
}
} /* else no matching node -> return null */
return authorz;
}
/**
* Test if a user or group exists that has the given principals name as ID,
* which might happen if userID != principal-name.
* In this case: generate another ID for the group to be created.
*
* @param principalName to be used as hint for the group id.
* @return a group id.
* @throws RepositoryException If an error occurs.
*/
private String getGroupId(String principalName) throws RepositoryException {
String groupID = principalName;
int i = 0;
while (internalGetAuthorizable(groupID) != null) {
groupID = principalName + "_" + i;
i++;
}
return groupID;
}
/**
* @param id The user or group ID.
* @return The authorizable with the given <code>id</code> or <code>null</code>.
* @throws RepositoryException If an error occurs.
*/
private Authorizable internalGetAuthorizable(String id) throws RepositoryException {
NodeId nodeId = buildNodeId(id);
NodeImpl n = null;
try {
n = session.getNodeById(nodeId);
} catch (ItemNotFoundException e) {
if (compatibleJR16) {
// backwards-compatibility with JR < 2.0 user/group structure that doesn't
// allow to determine existence of an authorizable from the id directly.
// search for it the node belonging to that id
n = (NodeImpl) authResolver.findNode(P_USERID, id, NT_REP_USER);
if (n == null) {
// no user -> look for group.
// NOTE: JR < 2.0 always returned groupIDs that didn't contain any
// illegal JCR chars. Since Group.getID() 'unescapes' the node
// name additional escaping is required.
Name nodeName = session.getQName(Text.escapeIllegalJcrChars(id));
n = (NodeImpl) authResolver.findNode(nodeName, NT_REP_GROUP);
}
} // else: no matching node found -> ignore exception.
}
return getAuthorizable(n);
}
private Value getValue(String strValue) {
return session.getValueFactory().createValue(strValue);
}
/**
* @param userID A userID.
* @return true if the given userID belongs to the administrator user.
*/
boolean isAdminId(String userID) {
return (adminId != null) && adminId.equals(userID);
}
/**
* Build the User object from the given user node.
*
* @param userNode The new user node.
* @return An instance of <code>User</code>.
* @throws RepositoryException If the node isn't a child of the configured
* usersPath-node or if another error occurs.
*/
User createUser(NodeImpl userNode) throws RepositoryException {
if (userNode == null || !userNode.isNodeType(NT_REP_USER)) {
throw new IllegalArgumentException();
}
if (!Text.isDescendant(usersPath, userNode.getPath())) {
throw new RepositoryException("User has to be within the User Path");
}
return doCreateUser(userNode);
}
/**
* Build the user object from the given user node. May be overridden to
* return a custom implementation.
*
* @param node user node
* @return the user object
* @throws RepositoryException if an error occurs
*/
protected User doCreateUser(NodeImpl node) throws RepositoryException {
return new UserImpl(node, this);
}
/**
* Build the Group object from the given group node.
*
* @param groupNode The new group node.
* @return An instance of <code>Group</code>.
* @throws RepositoryException If the node isn't a child of the configured
* groupsPath-node or if another error occurs.
*/
Group createGroup(NodeImpl groupNode) throws RepositoryException {
if (groupNode == null || !groupNode.isNodeType(NT_REP_GROUP)) {
throw new IllegalArgumentException();
}
if (!Text.isDescendant(groupsPath, groupNode.getPath())) {
throw new RepositoryException("Group has to be within the Group Path");
}
return doCreateGroup(groupNode);
}
/**
* Build the group object from the given group node. May be overridden to
* return a custom implementation.
*
* @param node group node
* @return A group
* @throws RepositoryException if an error occurs
*/
protected Group doCreateGroup(NodeImpl node) throws RepositoryException {
return new GroupImpl(node, this);
}
/**
* Create the administrator user. If the node to be created collides
* with an existing node (ItemExistsException) the existing node gets removed
* and the admin user node is (re)created.
* <p/>
* Collision with an existing node may occur under the following circumstances:
*
* <ul>
* <li>The <code>usersPath</code> has been modified in the user manager
* configuration after a successful repository start that already created
* the administrator user.</li>
* <li>The NodeId created by {@link #buildNodeId(String)} by coincidence
* collides with another NodeId created during the regular node creation
* process.</li>
* </ul>
*
* @return The admin user.
* @throws RepositoryException If an error occurs.
*/
private User createAdmin() throws RepositoryException {
User admin;
try {
admin = createUser(adminId, adminId);
if (!isAutoSave()) {
session.save();
}
log.info("... created admin user with id \'" + adminId + "\' and default pw.");
} catch (ItemExistsException e) {
NodeImpl conflictingNode = session.getNodeById(buildNodeId(adminId));
String conflictPath = conflictingNode.getPath();
log.error("Detected conflicting node " + conflictPath + " of node type " + conflictingNode.getPrimaryNodeType().getName() + ".");
// TODO move conflicting node of type rep:User instead of removing and recreating.
conflictingNode.remove();
log.info("Removed conflicting node at " + conflictPath);
admin = createUser(adminId, adminId);
if (!isAutoSave()) {
session.save();
}
log.info("Resolved conflict and (re)created admin user with id \'" + adminId + "\' and default pw.");
}
return admin;
}
/**
* Creates a UUID from the given <code>id</code> String that is converted
* to lower case before.
*
* @param id The user/group id that needs to be converted to a valid NodeId.
* @return a new <code>NodeId</code>.
* @throws RepositoryException If an error occurs.
*/
private NodeId buildNodeId(String id) throws RepositoryException {
try {
UUID uuid = UUID.nameUUIDFromBytes(id.toLowerCase().getBytes("UTF-8"));
return new NodeId(uuid);
} catch (UnsupportedEncodingException e) {
throw new RepositoryException("Unexpected error while build ID hash", e);
}
}
/**
* Checks if the specified <code>id</code> is a non-empty string and not yet
* in use for another user or group.
*
* @param id The id of the user or group to be created.
* @throws IllegalArgumentException If the specified id is null or empty string.
* @throws AuthorizableExistsException If the id is already in use.
* @throws RepositoryException If another error occurs.
*/
private void checkValidID(String id) throws IllegalArgumentException, AuthorizableExistsException, RepositoryException {
if (id == null || id.length() == 0) {
throw new IllegalArgumentException("Cannot create authorizable: ID can neither be null nor empty String.");
}
if (internalGetAuthorizable(id) != null) {
throw new AuthorizableExistsException("User or Group for '" + id + "' already exists");
}
}
/**
* Throws <code>IllegalArgumentException</code> if the specified principal
* is <code>null</code> or if it's name is <code>null</code> or empty string.
* @param principal
*/
private static void checkValidPrincipal(Principal principal) {
if (principal == null || principal.getName() == null || "".equals(principal.getName())) {
throw new IllegalArgumentException("Principal may not be null and must have a valid name.");
}
}
private static int parseMembershipSplitSize(Object param) {
int n = 0;
if (param != null) {
try {
n = Integer.parseInt(param.toString());
if (n < 4) {
n = 0;
}
}
catch (NumberFormatException e) {
n = 0;
}
if (n == 0) {
log.warn("Invalid value {} for {}. Expected integer >= 4",
param.toString(), PARAM_GROUP_MEMBERSHIP_SPLIT_SIZE);
}
}
return n;
}
//----------------------------------------------------< SessionListener >---
/**
* @see SessionListener#loggingOut(org.apache.jackrabbit.core.SessionImpl)
*/
public void loggingOut(SessionImpl session) {
// nothing to do.
}
/**
* @see SessionListener#loggedOut(org.apache.jackrabbit.core.SessionImpl)
*/
public void loggedOut(SessionImpl session) {
// and logout the session unless it is the logged-out session itself.
if (session != this.session) {
this.session.logout();
}
}
//------------------------------------------------------< inner classes >---
/**
* Inner class
*/
private final class AuthorizableIterator implements Iterator<Authorizable> {
private final Set<String> served = new HashSet<String>();
private Authorizable next;
private final NodeIterator authNodeIter;
private AuthorizableIterator(NodeIterator authNodeIter) {
this.authNodeIter = authNodeIter;
next = seekNext();
}
//-------------------------------------------------------< Iterator >---
/**
* @see Iterator#hasNext()
*/
public boolean hasNext() {
return next != null;
}
/**
* @see Iterator#next()
*/
public Authorizable next() {
Authorizable authr = next;
if (authr == null) {
throw new NoSuchElementException();
}
next = seekNext();
return authr;
}
/**
* @see Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
//----------------------------------------------------------------------
private Authorizable seekNext() {
while (authNodeIter.hasNext()) {
NodeImpl node = (NodeImpl) authNodeIter.nextNode();
try {
if (!served.contains(node.getUUID())) {
Authorizable authr = getAuthorizable(node);
served.add(node.getUUID());
if (authr != null) {
return authr;
}
}
} catch (RepositoryException e) {
log.debug(e.getMessage());
// continue seeking next authorizable
}
}
// no next authorizable -> iteration is completed.
return null;
}
}
//--------------------------------------------------------------------------
/**
* Inner class creating the JCR nodes corresponding the a given
* authorizable ID with the following behavior:
* <ul>
* <li>Users are created below /rep:security/rep:authorizables/rep:users or
* the corresponding path configured.</li>
* <li>Groups are created below /rep:security/rep:authorizables/rep:groups or
* the corresponding path configured.</li>
* <li>Below each category authorizables are created within a human readable
* structure based on the defined intermediate path or some internal logic
* with a depth defined by the <code>defaultDepth</code> config option.<br>
* E.g. creating a user node for an ID 'aSmith' would result in the following
* structure assuming defaultDepth == 2 is used:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* -> + aSmith [rep:User]
* </pre>
* </li>
* <li>In case of a user the node name is calculated from the specified UserID
* {@link Text#escapeIllegalJcrChars(String) escaping} any illegal JCR chars.
* In case of a Group the node name is calculated from the specified principal
* name circumventing any conflicts with existing ids and escaping illegal chars.</li>
* <li>If no intermediate path is passed the names of the intermediate
* folders are calculated from the leading chars of the escaped node name.</li>
* <li>If the escaped node name is shorter than the <code>defaultDepth</code>
* the last char is repeated.<br>
* E.g. creating a user node for an ID 'a' would result in the following
* structure assuming defaultDepth == 2 is used:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aa [rep:AuthorizableFolder]
* -> + a [rep:User]
* </pre>
* </li>
* <li>If the <code>autoExpandTree</code> option is <code>true</code> the
* user tree will be automatically expanded using additional levels if
* <code>autoExpandSize</code> is exceeded within a given level.</li>
* </ul>
*
* The auto-expansion of the authorizable tree is defined by the following
* steps and exceptional cases:
* <ul>
* <li>As long as <code>autoExpandSize</code> isn't reached authorizable
* nodes are created within the structure defined by the
* <code>defaultDepth</code>. (see above)</li>
* <li>If <code>autoExpandSize</code> is reached additional intermediate
* folders will be created.<br>
* E.g. creating a user node for an ID 'aSmith1001' would result in the
* following structure:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* + aSmith1 [rep:User]
* + aSmith2 [rep:User]
* [...]
* + aSmith1000 [rep:User]
* -> + aSm [rep:AuthorizableFolder]
* -> + aSmith1001 [rep:User]
* </pre>
* </li>
* <li>Conflicts: In order to prevent any conflicts that would arise from
* creating a authorizable node that upon later expansion could conflict
* with an authorizable folder, intermediate levels are always created if
* the node name equals any of the names reserved for the next level of
* folders.<br>
* In the example above any attempt to create a user with ID 'aSm' would
* result in an intermediate level irrespective if max-size has been
* reached or not:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* -> + aSm [rep:AuthorizableFolder]
* -> + aSm [rep:User]
* </pre>
* </li>
* <li>Special case: If the name of the authorizable node to be created is
* shorter or equal to the length of the folder at level N, the authorizable
* node is created even if max-size has been reached before.<br>
* An attempt to create the users 'aS' and 'aSm' in a structure containing
* tons of 'aSmith' users will therefore result in:
* <pre>
* + rep:security [nt:unstructured]
* + rep:authorizables [rep:AuthorizableFolder]
* + rep:users [rep:AuthorizableFolder]
* + a [rep:AuthorizableFolder]
* + aS [rep:AuthorizableFolder]
* + aSmith1 [rep:User]
* + aSmith2 [rep:User]
* [...]
* + aSmith1000 [rep:User]
* -> + aS [rep:User]
* + aSm [rep:AuthorizableFolder]
* + aSmith1001 [rep:User]
* -> + aSm [rep:User]
* </pre>
* </li>
* <li>Special case: If <code>autoExpandTree</code> is enabled later on
* AND any of the existing authorizable nodes collides with an intermediate
* folder to be created the auto-expansion is aborted and the new
* authorizable is inserted at the last valid level irrespective of
* max-size being reached.
* </li>
* </ul>
*
* The configuration options:
* <ul>
* <li><strong>defaultDepth</strong>:<br>
* A positive <code>integer</code> greater than zero defining the depth of
* the default structure that is always created.<br>
* Default value: 2</li>
* <li><strong>autoExpandTree</strong>:<br>
* <code>boolean</code> defining if the tree gets automatically expanded
* if within a level the maximum number of child nodes is reached.<br>
* Default value: <code>false</code></li>
* <li><strong>autoExpandSize</strong>:<br>
* A positive <code>long</code> greater than zero defining the maximum
* number of child nodes that are allowed at a given level.<br>
* Default value: 1000<br>
* NOTE: that total number of child nodes may still be greater that
* autoExpandSize.</li>
* </ul>
*/
private class NodeCreator {
private static final String DELIMITER = "/";
private static final int DEFAULT_DEPTH = 2;
private static final long DEFAULT_SIZE = 1000;
private final int defaultDepth;
private final boolean autoExpandTree;
// best effort max-size of authorizables per folder. there may be
// more nodes created if the editing session isn't allowed to see
// all child nodes.
private final long autoExpandSize;
private NodeCreator(Properties config) {
int d = DEFAULT_DEPTH;
boolean expand = false;
long size = DEFAULT_SIZE;
if (config != null) {
if (config.containsKey(PARAM_DEFAULT_DEPTH)) {
try {
d = Integer.parseInt(config.get(PARAM_DEFAULT_DEPTH).toString());
if (d <= 0) {
log.warn("Invalid defaultDepth '" + d + "' -> using default.");
d = DEFAULT_DEPTH;
}
} catch (NumberFormatException e) {
log.warn("Unable to parse defaultDepth config parameter -> using default.", e);
}
}
if (config.containsKey(PARAM_AUTO_EXPAND_TREE)) {
expand = Boolean.parseBoolean(config.get(PARAM_AUTO_EXPAND_TREE).toString());
}
if (config.containsKey(PARAM_AUTO_EXPAND_SIZE)) {
try {
size = Integer.parseInt(config.get(PARAM_AUTO_EXPAND_SIZE).toString());
if (expand && size <= 0) {
log.warn("Invalid autoExpandSize '" + size + "' -> using default.");
size = DEFAULT_SIZE;
}
} catch (NumberFormatException e) {
log.warn("Unable to parse autoExpandSize config parameter -> using default.", e);
}
}
}
defaultDepth = d;
autoExpandTree = expand;
autoExpandSize = size;
}
public Node createUserNode(String userID, String intermediatePath) throws RepositoryException {
return createAuthorizableNode(userID, false, intermediatePath);
}
public Node createGroupNode(String groupID, String intermediatePath) throws RepositoryException {
return createAuthorizableNode(groupID, true, intermediatePath);
}
private Node createAuthorizableNode(String id, boolean isGroup, String intermediatePath) throws RepositoryException {
String escapedId = Text.escapeIllegalJcrChars(id);
Node folder;
// first create the default folder nodes, that are always present.
folder = createDefaultFolderNodes(id, escapedId, isGroup, intermediatePath);
// eventually create additional intermediate folders.
if (intermediatePath == null) {
// internal logic only
folder = createIntermediateFolderNodes(id, escapedId, folder);
}
Name nodeName = session.getQName(escapedId);
Name ntName = (isGroup) ? NT_REP_GROUP : NT_REP_USER;
NodeId nid = buildNodeId(id);
// check if there exists an colliding folder child node.
while (((NodeImpl) folder).hasNode(nodeName)) {
NodeImpl colliding = ((NodeImpl) folder).getNode(nodeName);
if (colliding.isNodeType(NT_REP_AUTHORIZABLE_FOLDER)) {
log.warn("Existing folder node collides with user/group to be created. Expanding path: " + colliding.getPath());
folder = colliding;
} else {
// should never get here as folder creation above already
// asserts that only rep:authorizable folders exist.
// similarly collisions with existing authorizable have been
// checked.
String msg = "Failed to create authorizable with id '" + id + "' : Detected conflicting node of unexpected nodetype '" + colliding.getPrimaryNodeType().getName() + "'.";
log.error(msg);
throw new ConstraintViolationException(msg);
}
}
// check for collision with existing node outside of the user/group tree
if (session.getItemManager().itemExists(nid)) {
String msg = "Failed to create authorizable with id '" + id + "' : Detected conflict with existing node (NodeID: " + nid + ")";
log.error(msg);
throw new ItemExistsException(msg);
}
// finally create the authorizable node
return addNode((NodeImpl) folder, nodeName, ntName, nid);
}
private Node createDefaultFolderNodes(String id, String escapedId,
boolean isGroup, String intermediatePath) throws RepositoryException {
String defaultPath = getDefaultFolderPath(id, isGroup, intermediatePath);
// make sure users/groups are never nested and exclusively created
// under a tree of rep:AuthorizableFolder(s) starting at usersPath
// or groupsPath, respectively. ancestors of the usersPath/groupsPath
// may or may not be rep:AuthorizableFolder(s).
// therefore the shortcut Session.getNode(defaultPath) is omitted.
String[] segmts = defaultPath.split("/");
NodeImpl folder = (NodeImpl) session.getRootNode();
String authRoot = (isGroup) ? groupsPath : usersPath;
for (String segment : segmts) {
if (segment.length() < 1) {
continue;
}
if (folder.hasNode(segment)) {
folder = (NodeImpl) folder.getNode(segment);
if (Text.isDescendantOrEqual(authRoot, folder.getPath()) &&
!folder.isNodeType(NT_REP_AUTHORIZABLE_FOLDER)) {
throw new ConstraintViolationException("Invalid intermediate path. Must be of type rep:AuthorizableFolder.");
}
} else {
folder = addNode(folder, session.getQName(segment), NT_REP_AUTHORIZABLE_FOLDER);
}
}
// validation check if authorizable to be created doesn't conflict.
checkAuthorizableNodeExists(escapedId, folder);
return folder;
}
private String getDefaultFolderPath(String id, boolean isGroup, String intermediatePath) {
StringBuilder bld = new StringBuilder();
if (isGroup) {
bld.append(groupsPath);
} else {
bld.append(usersPath);
}
if (intermediatePath == null) {
// internal logic
StringBuilder lastSegment = new StringBuilder(defaultDepth);
int idLength = id.length();
for (int i = 0; i < defaultDepth; i++) {
if (idLength > i) {
lastSegment.append(id.charAt(i));
} else {
// escapedID is too short -> append the last char again
lastSegment.append(id.charAt(idLength-1));
}
bld.append(DELIMITER).append(Text.escapeIllegalJcrChars(lastSegment.toString()));
}
} else {
// structure defined by intermediate path
if (intermediatePath.startsWith(bld.toString())) {
intermediatePath = intermediatePath.substring(bld.toString().length());
}
if (intermediatePath.length() > 0 && !"/".equals(intermediatePath)) {
if (!intermediatePath.startsWith("/")) {
bld.append("/");
}
bld.append(intermediatePath);
}
}
return bld.toString();
}
private Node createIntermediateFolderNodes(String id, String escapedId, Node folder) throws RepositoryException {
if (!autoExpandTree) {
// additional folders are never created
return folder;
}
// additional folders needs be created if
// - the maximal size of child nodes is reached
// - if the authorizable node to be created potentially collides with
// any of the intermediate nodes.
int segmLength = defaultDepth +1;
while (intermediateFolderNeeded(escapedId, folder)) {
String folderName = Text.escapeIllegalJcrChars(id.substring(0, segmLength));
if (folder.hasNode(folderName)) {
NodeImpl n = (NodeImpl) folder.getNode(folderName);
// validation check: folder must be of type rep:AuthorizableFolder
// and not an authorizable node.
if (n.isNodeType(NT_REP_AUTHORIZABLE_FOLDER)) {
// expected nodetype -> no violation
folder = n;
} else if (n.isNodeType(NT_REP_AUTHORIZABLE)){
/*
an authorizable node has been created before with the
name of the intermediate folder to be created.
this may only occur if the 'autoExpandTree' option has
been enabled later on.
Resolution:
- abort auto-expanding and create the authorizable
at the current level, ignoring that max-size is reached.
- note, that this behavior has been preferred over tmp.
removing and recreating the colliding authorizable node.
*/
log.warn("Auto-expanding aborted. An existing authorizable node '" + n.getName() +"'conflicts with intermediate folder to be created.");
break;
} else {
// should never get here: some other, unexpected node type
String msg = "Failed to create authorizable node: Detected conflict with node of unexpected nodetype '" + n.getPrimaryNodeType().getName() + "'.";
log.error(msg);
throw new ConstraintViolationException(msg);
}
} else {
// folder doesn't exist nor does another colliding child node.
folder = addNode((NodeImpl) folder, session.getQName(folderName), NT_REP_AUTHORIZABLE_FOLDER);
}
segmLength++;
}
// final validation check if authorizable to be created doesn't conflict.
checkAuthorizableNodeExists(escapedId, folder);
return folder;
}
private void checkAuthorizableNodeExists(String nodeName, Node folder) throws AuthorizableExistsException, RepositoryException {
if (folder.hasNode(nodeName) &&
((NodeImpl) folder.getNode(nodeName)).isNodeType(NT_REP_AUTHORIZABLE)) {
throw new AuthorizableExistsException("Unable to create Group/User: Collision with existing authorizable.");
}
}
private boolean intermediateFolderNeeded(String nodeName, Node folder) throws RepositoryException {
// don't create additional intermediate folders for ids that are
// shorter or equally long as the folder name. In this case the
// MAX_SIZE flag is ignored.
if (nodeName.length() <= folder.getName().length()) {
return false;
}
// test for potential (or existing) collision in which case the
// intermediate node is created irrespective of the MAX_SIZE and the
// existing number of children.
if (nodeName.length() == folder.getName().length()+1) {
// max-size may not yet be reached yet on folder but the node to
// be created potentially collides with an intermediate folder.
// e.g.:
// existing folder structure: a/ab
// authID to be created : abt
// OR
// existing collision that would result from
// existing folder structure: a/ab/abt
// authID to be create : abt
return true;
}
// last possibility: max-size is reached.
if (folder.getNodes().getSize() >= autoExpandSize) {
return true;
}
// no collision and no need to create an additional intermediate
// folder due to max-size reached
return false;
}
}
}
| minor improvement (method order, javadoc)
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@1043086 13f79535-47bb-0310-9956-ffa450edef68
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/security/user/UserManagerImpl.java | minor improvement (method order, javadoc) |
|
Java | apache-2.0 | 8ab4dcfdfffd355da206636a208b9045635dd6fd | 0 | zilaiyedaren/zxing-iphone,joelind/zxing-iphone,zilaiyedaren/zxing-iphone,joelind/zxing-iphone,joelind/zxing-iphone,joelind/zxing-iphone,joelind/zxing-iphone,zilaiyedaren/zxing-iphone,zilaiyedaren/zxing-iphone,zilaiyedaren/zxing-iphone,joelind/zxing-iphone,zilaiyedaren/zxing-iphone,zilaiyedaren/zxing-iphone,zilaiyedaren/zxing-iphone,joelind/zxing-iphone,joelind/zxing-iphone | /*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android;
import com.google.zxing.ResultPoint;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.WindowManager;
import java.io.IOException;
import java.util.regex.Pattern;
/**
* This object wraps the Camera service object and expects to be the only one talking to it. The
* implementation encapsulates the steps needed to take preview-sized images, which are used for
* both preview and decoding.
*
* @author [email protected] (Daniel Switkin)
*/
final class CameraManager {
private static final String TAG = "CameraManager";
private static final int MIN_FRAME_WIDTH = 240;
private static final int MIN_FRAME_HEIGHT = 240;
private static final int MAX_FRAME_WIDTH = 480;
private static final int MAX_FRAME_HEIGHT = 360;
private static final int TEN_DESIRED_ZOOM = 27;
private static final int DESIRED_SHARPNESS = 30;
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
private static CameraManager cameraManager;
private Camera camera;
private final Context context;
private Point screenResolution;
private Point cameraResolution;
private Rect framingRect;
private Handler previewHandler;
private int previewMessage;
private Handler autoFocusHandler;
private int autoFocusMessage;
private boolean initialized;
private boolean previewing;
private int previewFormat;
private String previewFormatString;
private final boolean useOneShotPreviewCallback;
/**
* Preview frames are delivered here, which we pass on to the registered handler. Make sure to
* clear the handler so it will only receive one message.
*/
private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
if (previewHandler != null) {
Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x,
cameraResolution.y, data);
message.sendToTarget();
previewHandler = null;
}
}
};
/**
* Autofocus callbacks arrive here, and are dispatched to the Handler which requested them.
*/
private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
if (autoFocusHandler != null) {
Message message = autoFocusHandler.obtainMessage(autoFocusMessage, success);
// Simulate continuous autofocus by sending a focus request every 1.5 seconds.
autoFocusHandler.sendMessageDelayed(message, 1500L);
autoFocusHandler = null;
}
}
};
/**
* Initializes this static object with the Context of the calling Activity.
*
* @param context The Activity which wants to use the camera.
*/
public static void init(Context context) {
if (cameraManager == null) {
cameraManager = new CameraManager(context);
}
}
/**
* Gets the CameraManager singleton instance.
*
* @return A reference to the CameraManager singleton.
*/
public static CameraManager get() {
return cameraManager;
}
private CameraManager(Context context) {
this.context = context;
camera = null;
initialized = false;
previewing = false;
// Camera.setOneShotPreviewCallback() has a race condition in Cupcake, so we use the older
// Camera.setPreviewCallback() on 1.5 and earlier. For Donut and later, we need to use
// the more efficient one shot callback, as the older one can swamp the system and cause it
// to run out of memory. We can't use SDK_INT because it was introduced in the Donut SDK.
useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.CUPCAKE;
}
/**
* Opens the camera driver and initializes the hardware parameters.
*
* @param holder The surface object which the camera will draw preview frames into.
* @throws IOException Indicates the camera driver failed to open.
*/
public void openDriver(SurfaceHolder holder) throws IOException {
if (camera == null) {
camera = Camera.open();
if (camera == null) {
throw new IOException();
}
camera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
getScreenResolution();
}
setCameraParameters();
FlashlightManager.enableFlashlight();
}
}
/**
* Closes the camera driver if still in use.
*/
public void closeDriver() {
if (camera != null) {
FlashlightManager.disableFlashlight();
camera.release();
camera = null;
}
}
/**
* Asks the camera hardware to begin drawing preview frames to the screen.
*/
public void startPreview() {
if (camera != null && !previewing) {
camera.startPreview();
previewing = true;
}
}
/**
* Tells the camera to stop drawing preview frames.
*/
public void stopPreview() {
if (camera != null && previewing) {
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
camera.stopPreview();
previewHandler = null;
autoFocusHandler = null;
previewing = false;
}
}
/**
* A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
* in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
* respectively.
*
* @param handler The handler to send the message to.
* @param message The what field of the message to be sent.
*/
public void requestPreviewFrame(Handler handler, int message) {
if (camera != null && previewing) {
previewHandler = handler;
previewMessage = message;
if (useOneShotPreviewCallback) {
camera.setOneShotPreviewCallback(previewCallback);
} else {
camera.setPreviewCallback(previewCallback);
}
}
}
/**
* Asks the camera hardware to perform an autofocus.
*
* @param handler The Handler to notify when the autofocus completes.
* @param message The message to deliver.
*/
public void requestAutoFocus(Handler handler, int message) {
if (camera != null && previewing) {
autoFocusHandler = handler;
autoFocusMessage = message;
camera.autoFocus(autoFocusCallback);
}
}
/**
* Calculates the framing rect which the UI should draw to show the user where to place the
* barcode. This target helps with alignment as well as forces the user to hold the device
* far enough away to ensure the image will be in focus.
*
* @return The rectangle to draw on screen in window coordinates.
*/
public Rect getFramingRect() {
if (framingRect == null) {
if (camera == null) {
return null;
}
int width = cameraResolution.x * 3 / 4;
if (width < MIN_FRAME_WIDTH) {
width = MIN_FRAME_WIDTH;
} else if (width > MAX_FRAME_WIDTH) {
width = MAX_FRAME_WIDTH;
}
int height = cameraResolution.y * 3 / 4;
if (height < MIN_FRAME_HEIGHT) {
height = MIN_FRAME_HEIGHT;
} else if (height > MAX_FRAME_HEIGHT) {
height = MAX_FRAME_HEIGHT;
}
int leftOffset = (cameraResolution.x - width) / 2;
int topOffset = (cameraResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
Log.v(TAG, "Calculated framing rect: " + framingRect);
}
return framingRect;
}
/**
* Converts the result points from still resolution coordinates to screen coordinates.
*
* @param points The points returned by the Reader subclass through Result.getResultPoints().
* @return An array of Points scaled to the size of the framing rect and offset appropriately
* so they can be drawn in screen coordinates.
*/
public Point[] convertResultPoints(ResultPoint[] points) {
Rect frame = getFramingRect();
int count = points.length;
Point[] output = new Point[count];
for (int x = 0; x < count; x++) {
output[x] = new Point();
output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
}
return output;
}
/**
* A factory method to build the appropriate LuminanceSource object based on the format
* of the preview buffers, as described by Camera.Parameters.
*
* @param data A preview frame.
* @param width The width of the image.
* @param height The height of the image.
* @return A PlanarYUVLuminanceSource instance.
*/
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRect();
switch (previewFormat) {
// This is the standard Android format which all devices are REQUIRED to support.
// In theory, it's the only one we should ever care about.
case PixelFormat.YCbCr_420_SP:
// This format has never been seen in the wild, but is compatible as we only care
// about the Y channel, so allow it.
case PixelFormat.YCbCr_422_SP:
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
default:
// The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
// Fortunately, it too has all the Y data up front, so we can read it.
if ("yuv420p".equals(previewFormatString)) {
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
}
}
throw new IllegalArgumentException("Unsupported picture format: " +
previewFormat + '/' + previewFormatString);
}
/**
* Sets the camera up to take preview images which are used for both preview and decoding.
* We detect the preview format here so that buildLuminanceSource() can build an appropriate
* LuminanceSource subclass. In the future we may want to force YUV420SP as it's the smallest,
* and the planar Y can be used for barcode scanning without a copy in some cases.
*/
private void setCameraParameters() {
Camera.Parameters parameters = camera.getParameters();
previewFormat = parameters.getPreviewFormat();
previewFormatString = parameters.get("preview-format");
Log.v(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
cameraResolution = getCameraResolution(parameters);
Log.v(TAG, "Setting preview size: " + cameraResolution.x + ", " + cameraResolution.y);
parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
setFlash(parameters);
setZoom(parameters);
//setSharpness(parameters);
camera.setParameters(parameters);
}
private Point getScreenResolution() {
if (screenResolution == null) {
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
screenResolution = new Point(display.getWidth(), display.getHeight());
}
return screenResolution;
}
private Point getCameraResolution(Camera.Parameters parameters) {
String previewSizeValueString = parameters.get("preview-size-values");
// saw this on Xperia
if (previewSizeValueString == null) {
previewSizeValueString = parameters.get("preview-size-value");
}
Point cameraResolution = null;
if (previewSizeValueString != null) {
Log.v(TAG, "preview-size parameter: " + previewSizeValueString);
cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);
}
if (cameraResolution == null) {
// Ensure that the camera resolution is a multiple of 8, as the screen may not be.
cameraResolution = new Point(
(screenResolution.x >> 3) << 3,
(screenResolution.y >> 3) << 3);
}
return cameraResolution;
}
private static Point findBestPreviewSizeValue(String previewSizeValueString, Point screenResolution) {
int bestX = 0;
int bestY = 0;
int diff = Integer.MAX_VALUE;
for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
previewSize = previewSize.trim();
int dimPosition = previewSize.indexOf('x');
if (dimPosition < 0) {
Log.w(TAG, "Bad preview-size: " + previewSize);
continue;
}
int newX;
int newY;
try {
newX = Integer.parseInt(previewSize.substring(0, dimPosition));
newY = Integer.parseInt(previewSize.substring(dimPosition + 1));
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad preview-size: " + previewSize);
continue;
}
int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
if (newDiff == 0) {
bestX = newX;
bestY = newY;
break;
} else if (newDiff < diff) {
bestX = newX;
bestY = newY;
diff = newDiff;
}
}
if (bestX > 0 && bestY > 0) {
return new Point(bestX, bestY);
}
return null;
}
private void setFlash(Camera.Parameters parameters) {
// FIXME: This is a hack to turn the flash off on the Samsung Galaxy.
parameters.set("flash-value", 2);
// This is the standard setting to turn the flash off that all devices should honor.
parameters.set("flash-mode", "off");
}
private void setZoom(Camera.Parameters parameters) {
String zoomSupportedString = parameters.get("zoom-supported");
if (zoomSupportedString != null && !Boolean.parseBoolean(zoomSupportedString)) {
return;
}
int tenDesiredZoom = TEN_DESIRED_ZOOM;
String maxZoomString = parameters.get("max-zoom");
if (maxZoomString != null) {
try {
int tenMaxZoom = (int) (10.0 * Double.parseDouble(maxZoomString));
if (tenDesiredZoom > tenMaxZoom) {
tenDesiredZoom = tenMaxZoom;
}
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad max-zoom: " + maxZoomString);
}
}
String takingPictureZoomString = parameters.get("taking-picture-zoom-max");
if (takingPictureZoomString != null) {
try {
int tenMaxZoom = Integer.parseInt(takingPictureZoomString);
if (tenDesiredZoom > tenMaxZoom) {
tenDesiredZoom = tenMaxZoom;
}
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad taking-picture-zoom-max: " + takingPictureZoomString);
}
}
// Set zoom. This helps encourage the user to pull back.
// Some devices like the Behold have a zoom parameter
parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));
// Most devices, like the Hero, appear to expose this zoom parameter.
// It takes on values like "27" which appears to mean 2.7x zoom
parameters.set("taking-picture-zoom", tenDesiredZoom);
}
/*
private void setSharpness(Camera.Parameters parameters) {
int desiredSharpness = DESIRED_SHARPNESS;
String maxSharpnessString = parameters.get("sharpness-max");
if (maxSharpnessString != null) {
try {
int maxSharpness = Integer.parseInt(maxSharpnessString);
if (desiredSharpness > maxSharpness) {
desiredSharpness = maxSharpness;
}
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad sharpness-max: " + maxSharpnessString);
}
}
parameters.set("sharpness", desiredSharpness);
}
*/
}
| android/src/com/google/zxing/client/android/CameraManager.java | /*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android;
import com.google.zxing.ResultPoint;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.WindowManager;
import java.io.IOException;
import java.util.regex.Pattern;
/**
* This object wraps the Camera service object and expects to be the only one talking to it. The
* implementation encapsulates the steps needed to take preview-sized images, which are used for
* both preview and decoding.
*
* @author [email protected] (Daniel Switkin)
*/
final class CameraManager {
private static final String TAG = "CameraManager";
private static final int MIN_FRAME_WIDTH = 240;
private static final int MIN_FRAME_HEIGHT = 240;
private static final int MAX_FRAME_WIDTH = 480;
private static final int MAX_FRAME_HEIGHT = 360;
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
private static CameraManager cameraManager;
private Camera camera;
private final Context context;
private Point screenResolution;
private Point cameraResolution;
private Rect framingRect;
private Handler previewHandler;
private int previewMessage;
private Handler autoFocusHandler;
private int autoFocusMessage;
private boolean initialized;
private boolean previewing;
private int previewFormat;
private String previewFormatString;
private boolean useOneShotPreviewCallback;
/**
* Preview frames are delivered here, which we pass on to the registered handler. Make sure to
* clear the handler so it will only receive one message.
*/
private final Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
if (previewHandler != null) {
Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x,
cameraResolution.y, data);
message.sendToTarget();
previewHandler = null;
}
}
};
/**
* Autofocus callbacks arrive here, and are dispatched to the Handler which requested them.
*/
private final Camera.AutoFocusCallback autoFocusCallback = new Camera.AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
if (autoFocusHandler != null) {
Message message = autoFocusHandler.obtainMessage(autoFocusMessage, success);
// Simulate continuous autofocus by sending a focus request every 1.5 seconds.
autoFocusHandler.sendMessageDelayed(message, 1500L);
autoFocusHandler = null;
}
}
};
/**
* Initializes this static object with the Context of the calling Activity.
*
* @param context The Activity which wants to use the camera.
*/
public static void init(Context context) {
if (cameraManager == null) {
cameraManager = new CameraManager(context);
}
}
/**
* Gets the CameraManager singleton instance.
*
* @return A reference to the CameraManager singleton.
*/
public static CameraManager get() {
return cameraManager;
}
private CameraManager(Context context) {
this.context = context;
camera = null;
initialized = false;
previewing = false;
// Camera.setOneShotPreviewCallback() has a race condition in Cupcake, so we use the older
// Camera.setPreviewCallback() on 1.5 and earlier. For Donut and later, we need to use
// the more efficient one shot callback, as the older one can swamp the system and cause it
// to run out of memory. We can't use SDK_INT because it was introduced in the Donut SDK.
useOneShotPreviewCallback = Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.CUPCAKE;
}
/**
* Opens the camera driver and initializes the hardware parameters.
*
* @param holder The surface object which the camera will draw preview frames into.
* @throws IOException Indicates the camera driver failed to open.
*/
public void openDriver(SurfaceHolder holder) throws IOException {
if (camera == null) {
camera = Camera.open();
if (camera == null) {
throw new IOException();
}
camera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
getScreenResolution();
}
setCameraParameters();
FlashlightManager.enableFlashlight();
}
}
/**
* Closes the camera driver if still in use.
*/
public void closeDriver() {
if (camera != null) {
FlashlightManager.disableFlashlight();
camera.release();
camera = null;
}
}
/**
* Asks the camera hardware to begin drawing preview frames to the screen.
*/
public void startPreview() {
if (camera != null && !previewing) {
camera.startPreview();
previewing = true;
}
}
/**
* Tells the camera to stop drawing preview frames.
*/
public void stopPreview() {
if (camera != null && previewing) {
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
camera.stopPreview();
previewHandler = null;
autoFocusHandler = null;
previewing = false;
}
}
/**
* A single preview frame will be returned to the handler supplied. The data will arrive as byte[]
* in the message.obj field, with width and height encoded as message.arg1 and message.arg2,
* respectively.
*
* @param handler The handler to send the message to.
* @param message The what field of the message to be sent.
*/
public void requestPreviewFrame(Handler handler, int message) {
if (camera != null && previewing) {
previewHandler = handler;
previewMessage = message;
if (useOneShotPreviewCallback) {
camera.setOneShotPreviewCallback(previewCallback);
} else {
camera.setPreviewCallback(previewCallback);
}
}
}
/**
* Asks the camera hardware to perform an autofocus.
*
* @param handler The Handler to notify when the autofocus completes.
* @param message The message to deliver.
*/
public void requestAutoFocus(Handler handler, int message) {
if (camera != null && previewing) {
autoFocusHandler = handler;
autoFocusMessage = message;
camera.autoFocus(autoFocusCallback);
}
}
/**
* Calculates the framing rect which the UI should draw to show the user where to place the
* barcode. This target helps with alignment as well as forces the user to hold the device
* far enough away to ensure the image will be in focus.
*
* @return The rectangle to draw on screen in window coordinates.
*/
public Rect getFramingRect() {
if (framingRect == null) {
if (camera == null) {
return null;
}
int width = cameraResolution.x * 3 / 4;
if (width < MIN_FRAME_WIDTH) {
width = MIN_FRAME_WIDTH;
} else if (width > MAX_FRAME_WIDTH) {
width = MAX_FRAME_WIDTH;
}
int height = cameraResolution.y * 3 / 4;
if (height < MIN_FRAME_HEIGHT) {
height = MIN_FRAME_HEIGHT;
} else if (height > MAX_FRAME_HEIGHT) {
height = MAX_FRAME_HEIGHT;
}
int leftOffset = (cameraResolution.x - width) / 2;
int topOffset = (cameraResolution.y - height) / 2;
framingRect = new Rect(leftOffset, topOffset, leftOffset + width, topOffset + height);
Log.v(TAG, "Calculated framing rect: " + framingRect);
}
return framingRect;
}
/**
* Converts the result points from still resolution coordinates to screen coordinates.
*
* @param points The points returned by the Reader subclass through Result.getResultPoints().
* @return An array of Points scaled to the size of the framing rect and offset appropriately
* so they can be drawn in screen coordinates.
*/
public Point[] convertResultPoints(ResultPoint[] points) {
Rect frame = getFramingRect();
int count = points.length;
Point[] output = new Point[count];
for (int x = 0; x < count; x++) {
output[x] = new Point();
output[x].x = frame.left + (int) (points[x].getX() + 0.5f);
output[x].y = frame.top + (int) (points[x].getY() + 0.5f);
}
return output;
}
/**
* A factory method to build the appropriate LuminanceSource object based on the format
* of the preview buffers, as described by Camera.Parameters.
*
* @param data A preview frame.
* @param width The width of the image.
* @param height The height of the image.
* @return A PlanarYUVLuminanceSource instance.
*/
public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
Rect rect = getFramingRect();
switch (previewFormat) {
// This is the standard Android format which all devices are REQUIRED to support.
// In theory, it's the only one we should ever care about.
case PixelFormat.YCbCr_420_SP:
// This format has never been seen in the wild, but is compatible as we only care
// about the Y channel, so allow it.
case PixelFormat.YCbCr_422_SP:
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
default:
// The Samsung Moment incorrectly uses this variant instead of the 'sp' version.
// Fortunately, it too has all the Y data up front, so we can read it.
if ("yuv420p".equals(previewFormatString)) {
return new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
rect.width(), rect.height());
}
}
throw new IllegalArgumentException("Unsupported picture format: " +
previewFormat + '/' + previewFormatString);
}
/**
* Sets the camera up to take preview images which are used for both preview and decoding.
* We detect the preview format here so that buildLuminanceSource() can build an appropriate
* LuminanceSource subclass. In the future we may want to force YUV420SP as it's the smallest,
* and the planar Y can be used for barcode scanning without a copy in some cases.
*/
private void setCameraParameters() {
Camera.Parameters parameters = camera.getParameters();
previewFormat = parameters.getPreviewFormat();
previewFormatString = parameters.get("preview-format");
Log.v(TAG, "Default preview format: " + previewFormat + '/' + previewFormatString);
cameraResolution = getCameraResolution(parameters);
Log.v(TAG, "Setting preview size: " + cameraResolution.x + ", " + cameraResolution.y);
parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
// FIXME: This is a hack to turn the flash off on the Samsung Galaxy.
parameters.set("flash-value", 2);
// This is the standard setting to turn the flash off that all devices should honor.
parameters.set("flash-mode", "off");
// Set zoom to 2x if available. This helps encourage the user to pull back.
// Some devices like the Behold have a zoom parameter
parameters.set("zoom", "2.0");
// Most devices, like the Hero, appear to expose this zoom parameter.
// (I think) This means 2.0x
parameters.set("taking-picture-zoom", "20");
camera.setParameters(parameters);
}
private Point getScreenResolution() {
if (screenResolution == null) {
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
screenResolution = new Point(display.getWidth(), display.getHeight());
}
return screenResolution;
}
private Point getCameraResolution(Camera.Parameters parameters) {
String previewSizeValueString = parameters.get("preview-size-values");
// saw this on Xperia
if (previewSizeValueString == null) {
previewSizeValueString = parameters.get("preview-size-value");
}
Point cameraResolution = null;
if (previewSizeValueString != null) {
Log.v(TAG, "preview-size parameter: " + previewSizeValueString);
cameraResolution = findBestPreviewSizeValue(previewSizeValueString, screenResolution);
}
if (cameraResolution == null) {
// Ensure that the camera resolution is a multiple of 8, as the screen may not be.
cameraResolution = new Point(
(screenResolution.x >> 3) << 3,
(screenResolution.y >> 3) << 3);
}
return cameraResolution;
}
private static Point findBestPreviewSizeValue(String previewSizeValueString, Point screenResolution) {
int bestX = 0;
int bestY = 0;
int diff = Integer.MAX_VALUE;
for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
previewSize = previewSize.trim();
int dimPosition = previewSize.indexOf('x');
if (dimPosition < 0) {
Log.w(TAG, "Bad preview-size");
continue;
}
int newX;
int newY;
try {
newX = Integer.parseInt(previewSize.substring(0, dimPosition));
newY = Integer.parseInt(previewSize.substring(dimPosition + 1));
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad preview-size");
continue;
}
int newDiff = Math.abs(newX - screenResolution.x) + Math.abs(newY - screenResolution.y);
if (newDiff == 0) {
bestX = newX;
bestY = newY;
break;
} else if (newDiff < diff) {
bestX = newX;
bestY = newY;
diff = newDiff;
}
}
if (bestX > 0 && bestY > 0) {
return new Point(bestX, bestY);
}
return null;
}
}
| Set zoom a bit more reliably and aggressively
| android/src/com/google/zxing/client/android/CameraManager.java | Set zoom a bit more reliably and aggressively |
|
Java | apache-2.0 | be1a0fa594c1bebb0d542f709c8492663449ee74 | 0 | PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,PATRIC3/p3_solr,apache/manifoldcf-integration-solr-3.x,PATRIC3/p3_solr,apache/manifoldcf-integration-solr-4.x,PATRIC3/p3_solr | /**
* 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.solr.handler;
import org.apache.commons.io.IOUtils;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.solr.TestDistributedSearch;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.util.AbstractSolrTestCase;
import java.io.*;
import java.net.URL;
import junit.framework.TestCase;
/**
* Test for ReplicationHandler
*
* @version $Id$
* @since 1.4
*/
public class TestReplicationHandler extends TestCase {
private static final String CONF_DIR = "." + File.separator + "solr" + File.separator + "conf" + File.separator;
private static final String SLAVE_CONFIG = CONF_DIR + "solrconfig-slave.xml";
JettySolrRunner masterJetty, slaveJetty;
SolrServer masterClient, slaveClient;
SolrInstance master = null, slave = null;
String context = "/solr";
public void setUp() throws Exception {
super.setUp();
master = new SolrInstance("master", null);
master.setUp();
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
slave = new SolrInstance("slave", masterJetty.getLocalPort());
slave.setUp();
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
}
@Override
public void tearDown() throws Exception {
masterJetty.stop();
slaveJetty.stop();
master.tearDown();
slave.tearDown();
super.tearDown();
}
private JettySolrRunner createJetty(SolrInstance instance) throws Exception {
System.setProperty("solr.solr.home", instance.getHomeDir());
System.setProperty("solr.data.dir", instance.getDataDir());
JettySolrRunner jetty = new JettySolrRunner("/solr", 0);
jetty.start();
return jetty;
}
protected SolrServer createNewSolrServer(int port) {
try {
// setup the server...
String url = "http://localhost:" + port + context;
CommonsHttpSolrServer s = new CommonsHttpSolrServer(url);
s.setDefaultMaxConnectionsPerHost(100);
s.setMaxTotalConnections(100);
return s;
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
int index(SolrServer s, Object... fields) throws Exception {
SolrInputDocument doc = new SolrInputDocument();
for (int i = 0; i < fields.length; i += 2) {
doc.addField((String) (fields[i]), fields[i + 1]);
}
return s.add(doc).getStatus();
}
NamedList query(String query, SolrServer s) throws SolrServerException {
NamedList res = new SimpleOrderedMap();
ModifiableSolrParams params = new ModifiableSolrParams();
params.add("q", query);
QueryResponse qres = s.query(params);
res = qres.getResponse();
return res;
}
public void testIndexAndConfigReplication() throws Exception {
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
if (slaveQueryResult.getNumFound() == 0) {
//try sleeping again in case of slower comp
Thread.sleep(5000);
slaveQueryRsp = query("*:*", slaveClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
}
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
//start config files replication test
masterClient.deleteByQuery("*:*");
masterClient.commit();
//change the schema on master
copyFile(new File(CONF_DIR + "schema-replication2.xml"), new File(master.getConfDir(), "schema.xml"));
masterJetty.stop();
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
copyFile(new File(SLAVE_CONFIG), new File(slave.getConfDir(), "solrconfig.xml"), masterJetty.getLocalPort());
slaveJetty.stop();
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
//add a doc with new field and commit on master to trigger snappull from slave.
index(masterClient, "id", "2000", "name", "name = " + 2000, "newname", "newname = " + 2000);
masterClient.commit();
//sleep for 3s for replication to happen.
Thread.sleep(3000);
slaveQueryRsp = query("*:*", slaveClient);
SolrDocument d = ((SolrDocumentList) slaveQueryRsp.get("response")).get(0);
assertEquals("newname = 2000", (String) d.getFieldValue("newname"));
}
public void testIndexAndConfigAliasReplication() throws Exception {
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
if (slaveQueryResult.getNumFound() == 0) {
//try sleeping again in case of slower comp
Thread.sleep(5000);
slaveQueryRsp = query("*:*", slaveClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
}
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
//start config files replication test
//clear master index
masterClient.deleteByQuery("*:*");
masterClient.commit();
//change solrconfig on master
copyFile(new File(CONF_DIR + "solrconfig-master1.xml"), new File(master.getConfDir(), "solrconfig.xml"));
//change schema on master
copyFile(new File(CONF_DIR + "schema-replication2.xml"), new File(master.getConfDir(), "schema.xml"));
//keep a copy of the new schema
copyFile(new File(CONF_DIR + "schema-replication2.xml"), new File(master.getConfDir(), "schema-replication2.xml"));
masterJetty.stop();
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
copyFile(new File(SLAVE_CONFIG), new File(slave.getConfDir(), "solrconfig.xml"), masterJetty.getLocalPort());
slaveJetty.stop();
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
//add a doc with new field and commit on master to trigger snappull from slave.
index(masterClient, "id", "2000", "name", "name = " + 2000, "newname", "newname = " + 2000);
masterClient.commit();
//sleep for 3s for replication to happen.
Thread.sleep(3000);
index(slaveClient, "id", "2000", "name", "name = " + 2001, "newname", "newname = " + 2001);
slaveClient.commit();
slaveQueryRsp = query("*:*", slaveClient);
SolrDocument d = ((SolrDocumentList) slaveQueryRsp.get("response")).get(0);
assertEquals("newname = 2001", (String) d.getFieldValue("newname"));
}
public void testStopPoll() throws Exception {
// Test:
// setup master/slave.
// stop polling on slave, add a doc to master and verify slave hasn't picked it.
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
// start stop polling test
String masterUrl = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=disablepoll";
URL url = new URL(masterUrl);
InputStream stream = url.openStream();
try {
stream.close();
} catch (IOException e) {
//e.printStackTrace();
}
index(masterClient, "id", 501, "name", "name = " + 501);
masterClient.commit();
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
slaveQueryRsp = query("*:*", slaveClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(500, slaveQueryResult.getNumFound());
//get docs from slave and check if number is equal to master
slaveQueryRsp = query("*:*", masterClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(501, slaveQueryResult.getNumFound());
}
public void testSnapPullWithMasterUrl() throws Exception {
//change solrconfig on slave
//this has no entry for pollinginterval
copyFile(new File(CONF_DIR + "solrconfig-slave1.xml"), new File(slave.getConfDir(), "solrconfig.xml"));
slaveJetty.stop();
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
// snappull
String masterUrl = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=fetchindex&masterUrl=";
masterUrl += "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication";
URL url = new URL(masterUrl);
InputStream stream = url.openStream();
try {
stream.close();
} catch (IOException e) {
//e.printStackTrace();
}
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
}
public void testReplicateAfterStartup() throws Exception {
//stop slave
slaveJetty.stop();
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
//change solrconfig having 'replicateAfter startup' option on master
copyFile(new File(CONF_DIR + "solrconfig-master2.xml"),
new File(master.getConfDir(), "solrconfig.xml"));
masterJetty.stop();
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
copyFile(new File(SLAVE_CONFIG), new File(slave.getConfDir(), "solrconfig.xml"), masterJetty.getLocalPort());
//start slave
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
}
public void testReplicateAfterWrite2Slave() throws Exception {
//add 50 docs to master
int nDocs = 50;
for (int i = 0; i < nDocs; i++) {
index(masterClient, "id", i, "name", "name = " + i);
}
String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=disableReplication";
URL url = new URL(masterUrl);
InputStream stream = url.openStream();
try {
stream.close();
} catch (IOException e) {
//e.printStackTrace();
}
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(nDocs, masterQueryResult.getNumFound());
// Make sure that both the index version and index generation on the slave is
// higher than that of the master, just to make the test harder.
Thread.sleep(100);
index(slaveClient, "id", 551, "name", "name = " + 551);
slaveClient.commit(true, true);
index(slaveClient, "id", 552, "name", "name = " + 552);
slaveClient.commit(true, true);
index(slaveClient, "id", 553, "name", "name = " + 553);
slaveClient.commit(true, true);
index(slaveClient, "id", 554, "name", "name = " + 554);
slaveClient.commit(true, true);
index(slaveClient, "id", 555, "name", "name = " + 555);
slaveClient.commit(true, true);
//this doc is added to slave so it should show an item w/ that result
NamedList slaveQueryRsp = query("id:555", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(1, slaveQueryResult.getNumFound());
masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=enableReplication";
url = new URL(masterUrl);
stream = url.openStream();
try {
stream.close();
} catch (IOException e) {
//e.printStackTrace();
}
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//the slave should have done a full copy of the index so the doc with id:555 should not be there in the slave now
slaveQueryRsp = query("id:555", slaveClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(0, slaveQueryResult.getNumFound());
}
public void testBackup() throws Exception {
masterJetty.stop();
copyFile(new File(CONF_DIR + "solrconfig-master1.xml"), new File(master.getConfDir(), "solrconfig.xml"));
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
class BackupThread extends Thread {
volatile String fail = null;
public void run() {
String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP;
URL url;
InputStream stream = null;
try {
url = new URL(masterUrl);
stream = url.openStream();
stream.close();
} catch (Exception e) {
fail = e.getMessage();
} finally {
IOUtils.closeQuietly(stream);
}
};
};
BackupThread backupThread = new BackupThread();
backupThread.start();
File dataDir = new File(master.getDataDir());
class CheckStatus extends Thread {
volatile String fail = null;
volatile String response = null;
volatile boolean success = false;
public void run() {
String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_DETAILS;
URL url;
InputStream stream = null;
try {
url = new URL(masterUrl);
stream = url.openStream();
response = IOUtils.toString(stream);
if(response.contains("<str name=\"status\">success</str>")) {
success = true;
}
stream.close();
} catch (Exception e) {
fail = e.getMessage();
} finally {
IOUtils.closeQuietly(stream);
}
};
};
int waitCnt = 0;
CheckStatus checkStatus = new CheckStatus();
while(true) {
checkStatus.run();
if(checkStatus.fail != null) {
fail(checkStatus.fail);
}
if(checkStatus.success) {
break;
}
Thread.sleep(200);
if(waitCnt == 10) {
fail("Backup success not detected:" + checkStatus.response);
}
waitCnt++;
}
if(backupThread.fail != null) {
fail(backupThread.fail);
}
File[] files = dataDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
if(name.startsWith("snapshot")) {
return true;
}
return false;
}
});
assertEquals(1, files.length);
File snapDir = files[0];
IndexSearcher searcher = new IndexSearcher(new SimpleFSDirectory(snapDir.getAbsoluteFile(), null), true);
TopDocs hits = searcher.search(new MatchAllDocsQuery(), 1);
assertEquals(500, hits.totalHits);
}
/* character copy of file using UTF-8 */
void copyFile(File src, File dst) throws IOException {
copyFile(src, dst, null);
}
/**
* character copy of file using UTF-8. If port is non-null, will be substituted any time "TEST_PORT" is found.
*/
private void copyFile(File src, File dst, Integer port) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(src));
Writer out = new FileWriter(dst);
for (String line = in.readLine(); null != line; line = in.readLine()) {
if (null != port)
line = line.replace("TEST_PORT", port.toString());
out.write(line);
}
in.close();
out.close();
}
private class SolrInstance extends AbstractSolrTestCase {
String name;
Integer masterPort;
File homeDir;
File confDir;
/**
* if masterPort is null, this instance is a master -- otherwise this instance is a slave, and assumes the master is
* on localhost at the specified port.
*/
public SolrInstance(String name, Integer port) {
this.name = name;
this.masterPort = port;
}
public String getHomeDir() {
return homeDir.toString();
}
@Override
public String getSchemaFile() {
return CONF_DIR + "schema-replication1.xml";
}
public String getConfDir() {
return confDir.toString();
}
public String getDataDir() {
return dataDir.toString();
}
@Override
public String getSolrConfigFile() {
String fname = "";
if (null == masterPort)
fname = CONF_DIR + "solrconfig-master.xml";
else
fname = SLAVE_CONFIG;
return fname;
}
public void setUp() throws Exception {
System.setProperty("solr.test.sys.prop1", "propone");
System.setProperty("solr.test.sys.prop2", "proptwo");
String home = System.getProperty("java.io.tmpdir")
+ File.separator
+ getClass().getName() + "-" + System.currentTimeMillis();
if (null == masterPort) {
homeDir = new File(home + "master");
dataDir = new File(home + "master", "data");
confDir = new File(home + "master", "conf");
} else {
homeDir = new File(home + "slave");
dataDir = new File(home + "slave", "data");
confDir = new File(home + "slave", "conf");
}
homeDir.mkdirs();
dataDir.mkdirs();
confDir.mkdirs();
File f = new File(confDir, "solrconfig.xml");
copyFile(new File(getSolrConfigFile()), f, masterPort);
f = new File(confDir, "schema.xml");
copyFile(new File(getSchemaFile()), f);
}
public void tearDown() throws Exception {
super.tearDown();
AbstractSolrTestCase.recurseDelete(homeDir);
}
}
}
| solr/src/test/org/apache/solr/handler/TestReplicationHandler.java | /**
* 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.solr.handler;
import org.apache.commons.io.IOUtils;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.solr.TestDistributedSearch;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.util.AbstractSolrTestCase;
import java.io.*;
import java.net.URL;
/**
* Test for ReplicationHandler
*
* @version $Id$
* @since 1.4
*/
public class TestReplicationHandler extends AbstractSolrTestCase {
public String getSchemaFile() {
return null;
}
public String getSolrConfigFile() {
return null;
}
private static final String CONF_DIR = "." + File.separator + "solr" + File.separator + "conf" + File.separator;
private static final String SLAVE_CONFIG = CONF_DIR + "solrconfig-slave.xml";
JettySolrRunner masterJetty, slaveJetty;
SolrServer masterClient, slaveClient;
SolrInstance master = null, slave = null;
String context = "/solr";
public void setUp() throws Exception {
super.setUp();
master = new SolrInstance("master", null);
master.setUp();
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
slave = new SolrInstance("slave", masterJetty.getLocalPort());
slave.setUp();
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
}
@Override
public void tearDown() throws Exception {
super.preTearDown();
masterJetty.stop();
slaveJetty.stop();
master.tearDown();
slave.tearDown();
super.tearDown();
}
private JettySolrRunner createJetty(SolrInstance instance) throws Exception {
System.setProperty("solr.solr.home", instance.getHomeDir());
System.setProperty("solr.data.dir", instance.getDataDir());
JettySolrRunner jetty = new JettySolrRunner("/solr", 0);
jetty.start();
return jetty;
}
protected SolrServer createNewSolrServer(int port) {
try {
// setup the server...
String url = "http://localhost:" + port + context;
CommonsHttpSolrServer s = new CommonsHttpSolrServer(url);
s.setDefaultMaxConnectionsPerHost(100);
s.setMaxTotalConnections(100);
return s;
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
int index(SolrServer s, Object... fields) throws Exception {
SolrInputDocument doc = new SolrInputDocument();
for (int i = 0; i < fields.length; i += 2) {
doc.addField((String) (fields[i]), fields[i + 1]);
}
return s.add(doc).getStatus();
}
NamedList query(String query, SolrServer s) throws SolrServerException {
NamedList res = new SimpleOrderedMap();
ModifiableSolrParams params = new ModifiableSolrParams();
params.add("q", query);
QueryResponse qres = s.query(params);
res = qres.getResponse();
return res;
}
public void testIndexAndConfigReplication() throws Exception {
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
if (slaveQueryResult.getNumFound() == 0) {
//try sleeping again in case of slower comp
Thread.sleep(5000);
slaveQueryRsp = query("*:*", slaveClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
}
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
//start config files replication test
masterClient.deleteByQuery("*:*");
masterClient.commit();
//change the schema on master
copyFile(new File(CONF_DIR + "schema-replication2.xml"), new File(master.getConfDir(), "schema.xml"));
masterJetty.stop();
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
copyFile(new File(SLAVE_CONFIG), new File(slave.getConfDir(), "solrconfig.xml"), masterJetty.getLocalPort());
slaveJetty.stop();
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
//add a doc with new field and commit on master to trigger snappull from slave.
index(masterClient, "id", "2000", "name", "name = " + 2000, "newname", "newname = " + 2000);
masterClient.commit();
//sleep for 3s for replication to happen.
Thread.sleep(3000);
slaveQueryRsp = query("*:*", slaveClient);
SolrDocument d = ((SolrDocumentList) slaveQueryRsp.get("response")).get(0);
assertEquals("newname = 2000", (String) d.getFieldValue("newname"));
}
public void testIndexAndConfigAliasReplication() throws Exception {
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
if (slaveQueryResult.getNumFound() == 0) {
//try sleeping again in case of slower comp
Thread.sleep(5000);
slaveQueryRsp = query("*:*", slaveClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
}
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
//start config files replication test
//clear master index
masterClient.deleteByQuery("*:*");
masterClient.commit();
//change solrconfig on master
copyFile(new File(CONF_DIR + "solrconfig-master1.xml"), new File(master.getConfDir(), "solrconfig.xml"));
//change schema on master
copyFile(new File(CONF_DIR + "schema-replication2.xml"), new File(master.getConfDir(), "schema.xml"));
//keep a copy of the new schema
copyFile(new File(CONF_DIR + "schema-replication2.xml"), new File(master.getConfDir(), "schema-replication2.xml"));
masterJetty.stop();
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
copyFile(new File(SLAVE_CONFIG), new File(slave.getConfDir(), "solrconfig.xml"), masterJetty.getLocalPort());
slaveJetty.stop();
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
//add a doc with new field and commit on master to trigger snappull from slave.
index(masterClient, "id", "2000", "name", "name = " + 2000, "newname", "newname = " + 2000);
masterClient.commit();
//sleep for 3s for replication to happen.
Thread.sleep(3000);
index(slaveClient, "id", "2000", "name", "name = " + 2001, "newname", "newname = " + 2001);
slaveClient.commit();
slaveQueryRsp = query("*:*", slaveClient);
SolrDocument d = ((SolrDocumentList) slaveQueryRsp.get("response")).get(0);
assertEquals("newname = 2001", (String) d.getFieldValue("newname"));
}
public void testStopPoll() throws Exception {
// Test:
// setup master/slave.
// stop polling on slave, add a doc to master and verify slave hasn't picked it.
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
// start stop polling test
String masterUrl = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=disablepoll";
URL url = new URL(masterUrl);
InputStream stream = url.openStream();
try {
stream.close();
} catch (IOException e) {
//e.printStackTrace();
}
index(masterClient, "id", 501, "name", "name = " + 501);
masterClient.commit();
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
slaveQueryRsp = query("*:*", slaveClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(500, slaveQueryResult.getNumFound());
//get docs from slave and check if number is equal to master
slaveQueryRsp = query("*:*", masterClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(501, slaveQueryResult.getNumFound());
}
public void testSnapPullWithMasterUrl() throws Exception {
//change solrconfig on slave
//this has no entry for pollinginterval
copyFile(new File(CONF_DIR + "solrconfig-slave1.xml"), new File(slave.getConfDir(), "solrconfig.xml"));
slaveJetty.stop();
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
// snappull
String masterUrl = "http://localhost:" + slaveJetty.getLocalPort() + "/solr/replication?command=fetchindex&masterUrl=";
masterUrl += "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication";
URL url = new URL(masterUrl);
InputStream stream = url.openStream();
try {
stream.close();
} catch (IOException e) {
//e.printStackTrace();
}
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
}
public void testReplicateAfterStartup() throws Exception {
//stop slave
slaveJetty.stop();
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(500, masterQueryResult.getNumFound());
//change solrconfig having 'replicateAfter startup' option on master
copyFile(new File(CONF_DIR + "solrconfig-master2.xml"),
new File(master.getConfDir(), "solrconfig.xml"));
masterJetty.stop();
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
copyFile(new File(SLAVE_CONFIG), new File(slave.getConfDir(), "solrconfig.xml"), masterJetty.getLocalPort());
//start slave
slaveJetty = createJetty(slave);
slaveClient = createNewSolrServer(slaveJetty.getLocalPort());
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//get docs from slave and check if number is equal to master
NamedList slaveQueryRsp = query("*:*", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(500, slaveQueryResult.getNumFound());
//compare results
String cmp = TestDistributedSearch.compare(masterQueryResult, slaveQueryResult, 0, null);
assertEquals(null, cmp);
}
public void testReplicateAfterWrite2Slave() throws Exception {
//add 50 docs to master
int nDocs = 50;
for (int i = 0; i < nDocs; i++) {
index(masterClient, "id", i, "name", "name = " + i);
}
String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=disableReplication";
URL url = new URL(masterUrl);
InputStream stream = url.openStream();
try {
stream.close();
} catch (IOException e) {
//e.printStackTrace();
}
masterClient.commit();
NamedList masterQueryRsp = query("*:*", masterClient);
SolrDocumentList masterQueryResult = (SolrDocumentList) masterQueryRsp.get("response");
assertEquals(nDocs, masterQueryResult.getNumFound());
// Make sure that both the index version and index generation on the slave is
// higher than that of the master, just to make the test harder.
Thread.sleep(100);
index(slaveClient, "id", 551, "name", "name = " + 551);
slaveClient.commit(true, true);
index(slaveClient, "id", 552, "name", "name = " + 552);
slaveClient.commit(true, true);
index(slaveClient, "id", 553, "name", "name = " + 553);
slaveClient.commit(true, true);
index(slaveClient, "id", 554, "name", "name = " + 554);
slaveClient.commit(true, true);
index(slaveClient, "id", 555, "name", "name = " + 555);
slaveClient.commit(true, true);
//this doc is added to slave so it should show an item w/ that result
NamedList slaveQueryRsp = query("id:555", slaveClient);
SolrDocumentList slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(1, slaveQueryResult.getNumFound());
masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=enableReplication";
url = new URL(masterUrl);
stream = url.openStream();
try {
stream.close();
} catch (IOException e) {
//e.printStackTrace();
}
//sleep for pollinterval time 3s, to let slave pull data.
Thread.sleep(3000);
//the slave should have done a full copy of the index so the doc with id:555 should not be there in the slave now
slaveQueryRsp = query("id:555", slaveClient);
slaveQueryResult = (SolrDocumentList) slaveQueryRsp.get("response");
assertEquals(0, slaveQueryResult.getNumFound());
}
public void testBackup() throws Exception {
masterJetty.stop();
copyFile(new File(CONF_DIR + "solrconfig-master1.xml"), new File(master.getConfDir(), "solrconfig.xml"));
masterJetty = createJetty(master);
masterClient = createNewSolrServer(masterJetty.getLocalPort());
//add 500 docs to master
for (int i = 0; i < 500; i++)
index(masterClient, "id", i, "name", "name = " + i);
masterClient.commit();
class BackupThread extends Thread {
volatile String fail = null;
public void run() {
String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_BACKUP;
URL url;
InputStream stream = null;
try {
url = new URL(masterUrl);
stream = url.openStream();
stream.close();
} catch (Exception e) {
fail = e.getMessage();
} finally {
IOUtils.closeQuietly(stream);
}
};
};
BackupThread backupThread = new BackupThread();
backupThread.start();
File dataDir = new File(master.getDataDir());
class CheckStatus extends Thread {
volatile String fail = null;
volatile String response = null;
volatile boolean success = false;
public void run() {
String masterUrl = "http://localhost:" + masterJetty.getLocalPort() + "/solr/replication?command=" + ReplicationHandler.CMD_DETAILS;
URL url;
InputStream stream = null;
try {
url = new URL(masterUrl);
stream = url.openStream();
response = IOUtils.toString(stream);
if(response.contains("<str name=\"status\">success</str>")) {
success = true;
}
stream.close();
} catch (Exception e) {
fail = e.getMessage();
} finally {
IOUtils.closeQuietly(stream);
}
};
};
int waitCnt = 0;
CheckStatus checkStatus = new CheckStatus();
while(true) {
checkStatus.run();
if(checkStatus.fail != null) {
fail(checkStatus.fail);
}
if(checkStatus.success) {
break;
}
Thread.sleep(200);
if(waitCnt == 10) {
fail("Backup success not detected:" + checkStatus.response);
}
waitCnt++;
}
if(backupThread.fail != null) {
fail(backupThread.fail);
}
File[] files = dataDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
if(name.startsWith("snapshot")) {
return true;
}
return false;
}
});
assertEquals(1, files.length);
File snapDir = files[0];
IndexSearcher searcher = new IndexSearcher(new SimpleFSDirectory(snapDir.getAbsoluteFile(), null), true);
TopDocs hits = searcher.search(new MatchAllDocsQuery(), 1);
assertEquals(500, hits.totalHits);
}
/* character copy of file using UTF-8 */
void copyFile(File src, File dst) throws IOException {
copyFile(src, dst, null);
}
/**
* character copy of file using UTF-8. If port is non-null, will be substituted any time "TEST_PORT" is found.
*/
private void copyFile(File src, File dst, Integer port) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(src));
Writer out = new FileWriter(dst);
for (String line = in.readLine(); null != line; line = in.readLine()) {
if (null != port)
line = line.replace("TEST_PORT", port.toString());
out.write(line);
}
in.close();
out.close();
}
private class SolrInstance extends AbstractSolrTestCase {
String name;
Integer masterPort;
File homeDir;
File confDir;
/**
* if masterPort is null, this instance is a master -- otherwise this instance is a slave, and assumes the master is
* on localhost at the specified port.
*/
public SolrInstance(String name, Integer port) {
this.name = name;
this.masterPort = port;
}
public String getHomeDir() {
return homeDir.toString();
}
@Override
public String getSchemaFile() {
return CONF_DIR + "schema-replication1.xml";
}
public String getConfDir() {
return confDir.toString();
}
public String getDataDir() {
return dataDir.toString();
}
@Override
public String getSolrConfigFile() {
String fname = "";
if (null == masterPort)
fname = CONF_DIR + "solrconfig-master.xml";
else
fname = SLAVE_CONFIG;
return fname;
}
public void setUp() throws Exception {
System.setProperty("solr.test.sys.prop1", "propone");
System.setProperty("solr.test.sys.prop2", "proptwo");
String home = System.getProperty("java.io.tmpdir")
+ File.separator
+ getClass().getName() + "-" + System.currentTimeMillis();
if (null == masterPort) {
homeDir = new File(home + "master");
dataDir = new File(home + "master", "data");
confDir = new File(home + "master", "conf");
} else {
homeDir = new File(home + "slave");
dataDir = new File(home + "slave", "data");
confDir = new File(home + "slave", "conf");
}
homeDir.mkdirs();
dataDir.mkdirs();
confDir.mkdirs();
File f = new File(confDir, "solrconfig.xml");
copyFile(new File(getSolrConfigFile()), f, masterPort);
f = new File(confDir, "schema.xml");
copyFile(new File(getSchemaFile()), f);
}
public void tearDown() throws Exception {
super.tearDown();
AbstractSolrTestCase.recurseDelete(homeDir);
}
}
}
| make TestReplicationHandler just extend TestCase instead
git-svn-id: 6c059844b382e4b70377f6a3151bbb76419eaccf@925607 13f79535-47bb-0310-9956-ffa450edef68
| solr/src/test/org/apache/solr/handler/TestReplicationHandler.java | make TestReplicationHandler just extend TestCase instead |
|
Java | apache-2.0 | 98c9aa8d9eee39b465ce6c5eef4da97a2135ec23 | 0 | jimma/xerces,jimma/xerces,ronsigal/xerces,ronsigal/xerces,ronsigal/xerces,jimma/xerces | /*
* 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.xerces.impl.xs.traversers;
import java.util.Locale;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.impl.xs.SchemaGrammar;
import org.apache.xerces.impl.xs.SchemaSymbols;
import org.apache.xerces.impl.xs.XSAnnotationImpl;
import org.apache.xerces.impl.xs.XSComplexTypeDecl;
import org.apache.xerces.impl.xs.XSConstraints;
import org.apache.xerces.impl.xs.XSElementDecl;
import org.apache.xerces.impl.xs.XSParticleDecl;
import org.apache.xerces.impl.xs.util.XInt;
import org.apache.xerces.impl.xs.util.XSObjectListImpl;
import org.apache.xerces.util.DOMUtil;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xs.XSConstants;
import org.apache.xerces.xs.XSObject;
import org.apache.xerces.xs.XSObjectList;
import org.apache.xerces.xs.XSTypeDefinition;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
/**
* The element declaration schema component traverser.
* <element
* abstract = boolean : false
* block = (#all | List of (extension | restriction | substitution))
* default = string
* final = (#all | List of (extension | restriction))
* fixed = string
* form = (qualified | unqualified)
* id = ID
* maxOccurs = (nonNegativeInteger | unbounded) : 1
* minOccurs = nonNegativeInteger : 1
* name = NCName
* nillable = boolean : false
* ref = QName
* substitutionGroup = QName
* type = QName
* {any attributes with non-schema namespace . . .}>
* Content: (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))
* </element>
*
* @xerces.internal
*
* @author Sandy Gao, IBM
*
* @version $Id$
*/
class XSDElementTraverser extends XSDAbstractTraverser {
protected final XSElementDecl fTempElementDecl = new XSElementDecl();
// this controls what happens when a local element is encountered.
// We may not encounter all local elements when first parsing.
boolean fDeferTraversingLocalElements;
XSDElementTraverser (XSDHandler handler,
XSAttributeChecker gAttrCheck) {
super(handler, gAttrCheck);
}
/**
* Traverse a locally declared element (or an element reference).
*
* To handle the recursive cases efficiently, we delay the traversal
* and return an empty particle node. We'll fill in this particle node
* later after we've done with all the global declarations.
* This method causes a number of data structures in the schema handler to be filled in.
*
* @param elmDecl
* @param schemaDoc
* @param grammar
* @return the particle
*/
XSParticleDecl traverseLocal(Element elmDecl,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar,
int allContextFlags,
XSObject parent) {
XSParticleDecl particle = null;
if (fSchemaHandler.fDeclPool !=null) {
particle = fSchemaHandler.fDeclPool.getParticleDecl();
} else {
particle = new XSParticleDecl();
}
if (fDeferTraversingLocalElements) {
// The only thing we care about now is whether this element has
// minOccurs=0. This affects (if the element appears in a complex
// type) whether a type has emptiable content.
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
Attr attr = elmDecl.getAttributeNode(SchemaSymbols.ATT_MINOCCURS);
if (attr != null) {
String min = attr.getValue();
try {
int m = Integer.parseInt(XMLChar.trim(min));
if (m >= 0)
particle.fMinOccurs = m;
}
catch (NumberFormatException ex) {
}
}
fSchemaHandler.fillInLocalElemInfo(elmDecl, schemaDoc, allContextFlags, parent, particle);
} else {
traverseLocal(particle, elmDecl, schemaDoc, grammar, allContextFlags, parent, null);
// If it's an empty particle, return null.
if (particle.fType == XSParticleDecl.PARTICLE_EMPTY)
particle = null;
}
return particle;
}
/**
* Traverse a locally declared element (or an element reference).
*
* This is the real traversal method. It's called after we've done with
* all the global declarations.
*
* @param index
*/
protected void traverseLocal(XSParticleDecl particle,
Element elmDecl,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar,
int allContextFlags,
XSObject parent,
String[] localNSDecls) {
if (localNSDecls != null) {
schemaDoc.fNamespaceSupport.setEffectiveContext(localNSDecls);
}
// General Attribute Checking
Object[] attrValues = fAttrChecker.checkAttributes(elmDecl, false, schemaDoc);
QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF];
XInt minAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_MINOCCURS];
XInt maxAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_MAXOCCURS];
XSElementDecl element = null;
XSAnnotationImpl annotation = null;
if (elmDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) {
if (refAtt != null) {
element = (XSElementDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ELEMENT_TYPE, refAtt, elmDecl);
Element child = DOMUtil.getFirstChildElement(elmDecl);
if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) {
annotation = traverseAnnotationDecl(child, attrValues, false, schemaDoc);
child = DOMUtil.getNextSiblingElement(child);
}
else {
String text = DOMUtil.getSyntheticAnnotation(elmDecl);
if (text != null) {
annotation = traverseSyntheticAnnotation(elmDecl, text, attrValues, false, schemaDoc);
}
}
// Element Declaration Representation OK
// 2 If the item's parent is not <schema>, then all of the following must be true:
// 2.1 One of ref or name must be present, but not both.
// 2.2 If ref is present, then all of <complexType>, <simpleType>, <key>, <keyref>, <unique>, nillable, default, fixed, form, block and type must be absent, i.e. only minOccurs, maxOccurs, id are allowed in addition to ref, along with <annotation>.
if (child != null) {
reportSchemaError("src-element.2.2", new Object[]{refAtt.rawname, DOMUtil.getLocalName(child)}, child);
}
} else {
element = null;
}
} else {
element = traverseNamedElement(elmDecl, attrValues, schemaDoc, grammar, false, parent);
}
particle.fMinOccurs = minAtt.intValue();
particle.fMaxOccurs = maxAtt.intValue();
if (element != null) {
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = element;
}
else {
particle.fType = XSParticleDecl.PARTICLE_EMPTY;
}
if (refAtt != null) {
XSObjectList annotations;
if (annotation != null) {
annotations = new XSObjectListImpl();
((XSObjectListImpl) annotations).addXSObject(annotation);
} else {
annotations = XSObjectListImpl.EMPTY_LIST;
}
particle.fAnnotations = annotations;
} else {
particle.fAnnotations = ((element != null) ? element.fAnnotations
: XSObjectListImpl.EMPTY_LIST);
}
Long defaultVals = (Long)attrValues[XSAttributeChecker.ATTIDX_FROMDEFAULT];
checkOccurrences(particle, SchemaSymbols.ELT_ELEMENT,
(Element)elmDecl.getParentNode(), allContextFlags,
defaultVals.longValue());
fAttrChecker.returnAttrArray(attrValues, schemaDoc);
}
/**
* Traverse a globally declared element.
*
* @param elmDecl
* @param schemaDoc
* @param grammar
* @return the element declaration
*/
XSElementDecl traverseGlobal(Element elmDecl,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar) {
// General Attribute Checking'
Object[] attrValues = fAttrChecker.checkAttributes(elmDecl, true, schemaDoc);
XSElementDecl element = traverseNamedElement(elmDecl, attrValues, schemaDoc, grammar, true, null);
fAttrChecker.returnAttrArray(attrValues, schemaDoc);
return element;
}
/**
* Traverse a globally declared element.
*
* @param elmDecl
* @param attrValues
* @param schemaDoc
* @param grammar
* @param isGlobal
* @return the element declaration
*/
XSElementDecl traverseNamedElement(Element elmDecl,
Object[] attrValues,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar,
boolean isGlobal,
XSObject parent) {
Boolean abstractAtt = (Boolean) attrValues[XSAttributeChecker.ATTIDX_ABSTRACT];
XInt blockAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_BLOCK];
String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT];
XInt finalAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_FINAL];
String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED];
XInt formAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_FORM];
String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME];
Boolean nillableAtt = (Boolean) attrValues[XSAttributeChecker.ATTIDX_NILLABLE];
QName subGroupAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_SUBSGROUP];
QName typeAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_TYPE];
// Step 1: get declaration information
XSElementDecl element = null;
if (fSchemaHandler.fDeclPool !=null) {
element = fSchemaHandler.fDeclPool.getElementDecl();
} else {
element = new XSElementDecl();
}
// get 'name'
if (nameAtt != null)
element.fName = fSymbolTable.addSymbol(nameAtt);
// get 'target namespace'
if (isGlobal) {
element.fTargetNamespace = schemaDoc.fTargetNamespace;
element.setIsGlobal();
}
else {
if (parent instanceof XSComplexTypeDecl)
element.setIsLocal((XSComplexTypeDecl)parent);
if (formAtt != null) {
if (formAtt.intValue() == SchemaSymbols.FORM_QUALIFIED)
element.fTargetNamespace = schemaDoc.fTargetNamespace;
else
element.fTargetNamespace = null;
} else if (schemaDoc.fAreLocalElementsQualified) {
element.fTargetNamespace = schemaDoc.fTargetNamespace;
} else {
element.fTargetNamespace = null;
}
}
// get 'block', 'final', 'nillable', 'abstract'
element.fBlock = blockAtt == null ? schemaDoc.fBlockDefault : blockAtt.shortValue();
element.fFinal = finalAtt == null ? schemaDoc.fFinalDefault : finalAtt.shortValue();
// discard valid Block/Final 'Default' values that are invalid for Block/Final
element.fBlock &= (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
element.fFinal &= (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION);
if (nillableAtt.booleanValue())
element.setIsNillable();
if (abstractAtt != null && abstractAtt.booleanValue())
element.setIsAbstract();
// get 'value constraint'
if (fixedAtt != null) {
element.fDefault = new ValidatedInfo();
element.fDefault.normalizedValue = fixedAtt;
element.setConstraintType(XSConstants.VC_FIXED);
} else if (defaultAtt != null) {
element.fDefault = new ValidatedInfo();
element.fDefault.normalizedValue = defaultAtt;
element.setConstraintType(XSConstants.VC_DEFAULT);
} else {
element.setConstraintType(XSConstants.VC_NONE);
}
// get 'substitutionGroup affiliation'
if (subGroupAtt != null) {
element.fSubGroup = (XSElementDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ELEMENT_TYPE, subGroupAtt, elmDecl);
}
// get 'annotation'
Element child = DOMUtil.getFirstChildElement(elmDecl);
XSAnnotationImpl annotation = null;
if(child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) {
annotation = traverseAnnotationDecl(child, attrValues, false, schemaDoc);
child = DOMUtil.getNextSiblingElement(child);
}
else {
String text = DOMUtil.getSyntheticAnnotation(elmDecl);
if (text != null) {
annotation = traverseSyntheticAnnotation(elmDecl, text, attrValues, false, schemaDoc);
}
}
XSObjectList annotations;
if (annotation != null) {
annotations = new XSObjectListImpl();
((XSObjectListImpl)annotations).addXSObject (annotation);
} else {
annotations = XSObjectListImpl.EMPTY_LIST;
}
element.fAnnotations = annotations;
// get 'type definition'
XSTypeDefinition elementType = null;
boolean haveAnonType = false;
// Handle Anonymous type if there is one
if (child != null) {
String childName = DOMUtil.getLocalName(child);
if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
elementType = fSchemaHandler.fComplexTypeTraverser.traverseLocal(child, schemaDoc, grammar);
haveAnonType = true;
child = DOMUtil.getNextSiblingElement(child);
}
else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
elementType = fSchemaHandler.fSimpleTypeTraverser.traverseLocal(child, schemaDoc, grammar);
haveAnonType = true;
child = DOMUtil.getNextSiblingElement(child);
}
}
// Handler type attribute
if (elementType == null && typeAtt != null) {
elementType = (XSTypeDefinition)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.TYPEDECL_TYPE, typeAtt, elmDecl);
}
// Get it from the substitutionGroup declaration
if (elementType == null && element.fSubGroup != null) {
elementType = element.fSubGroup.fType;
}
if (elementType == null) {
elementType = SchemaGrammar.fAnyType;
}
element.fType = elementType;
// get 'identity constraint'
// see if there's something here; it had better be key, keyref or unique.
if (child != null) {
String childName = DOMUtil.getLocalName(child);
while (child != null &&
(childName.equals(SchemaSymbols.ELT_KEY) ||
childName.equals(SchemaSymbols.ELT_KEYREF) ||
childName.equals(SchemaSymbols.ELT_UNIQUE))) {
if (childName.equals(SchemaSymbols.ELT_KEY) ||
childName.equals(SchemaSymbols.ELT_UNIQUE)) {
// need to set <key>/<unique> to hidden before traversing it,
// because it has global scope
DOMUtil.setHidden(child, fSchemaHandler.fHiddenNodes);
fSchemaHandler.fUniqueOrKeyTraverser.traverse(child, element, schemaDoc, grammar);
if(DOMUtil.getAttrValue(child, SchemaSymbols.ATT_NAME).length() != 0 ) {
fSchemaHandler.checkForDuplicateNames(
(schemaDoc.fTargetNamespace == null) ? ","+DOMUtil.getAttrValue(child, SchemaSymbols.ATT_NAME)
: schemaDoc.fTargetNamespace+","+ DOMUtil.getAttrValue(child, SchemaSymbols.ATT_NAME),
fSchemaHandler.getIDRegistry(), fSchemaHandler.getIDRegistry_sub(),
child, schemaDoc);
}
} else if (childName.equals(SchemaSymbols.ELT_KEYREF)) {
fSchemaHandler.storeKeyRef(child, schemaDoc, element);
}
child = DOMUtil.getNextSiblingElement(child);
if (child != null) {
childName = DOMUtil.getLocalName(child);
}
}
}
// Step 3: check against schema for schemas
// required attributes
if (nameAtt == null) {
if (isGlobal)
reportSchemaError("s4s-att-must-appear", new Object[]{SchemaSymbols.ELT_ELEMENT, SchemaSymbols.ATT_NAME}, elmDecl);
else
reportSchemaError("src-element.2.1", null, elmDecl);
nameAtt = NO_NAME;
}
// element
if (child != null) {
reportSchemaError("s4s-elt-must-match.1", new Object[]{nameAtt, "(annotation?, (simpleType | complexType)?, (unique | key | keyref)*))", DOMUtil.getLocalName(child)}, child);
}
// Step 4: check 3.3.3 constraints
// src-element
// 1 default and fixed must not both be present.
if (defaultAtt != null && fixedAtt != null) {
reportSchemaError("src-element.1", new Object[]{nameAtt}, elmDecl);
}
// 2 If the item's parent is not <schema>, then all of the following must be true:
// 2.1 One of ref or name must be present, but not both.
// This is checked in XSAttributeChecker
// 2.2 If ref is present, then all of <complexType>, <simpleType>, <key>, <keyref>, <unique>, nillable, default, fixed, form, block and type must be absent, i.e. only minOccurs, maxOccurs, id are allowed in addition to ref, along with <annotation>.
// Attributes are checked in XSAttributeChecker, elements are checked in "traverse" method
// 3 type and either <simpleType> or <complexType> are mutually exclusive.
if (haveAnonType && (typeAtt != null)) {
reportSchemaError("src-element.3", new Object[]{nameAtt}, elmDecl);
}
// Step 5: check 3.3.6 constraints
// check for NOTATION type
checkNotationType(nameAtt, elementType, elmDecl);
// e-props-correct
// 2 If there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in Element Default Valid (Immediate) (3.3.6).
if (element.fDefault != null) {
fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport);
if (XSConstraints.ElementDefaultValidImmediate(element.fType, element.fDefault.normalizedValue, fValidationState, element.fDefault) == null) {
reportSchemaError ("e-props-correct.2", new Object[]{nameAtt, element.fDefault.normalizedValue}, elmDecl);
element.fDefault = null;
element.setConstraintType(XSConstants.VC_NONE);
}
}
// 4 If there is an {substitution group affiliation}, the {type definition} of the element declaration must be validly derived from the {type definition} of the {substitution group affiliation}, given the value of the {substitution group exclusions} of the {substitution group affiliation}, as defined in Type Derivation OK (Complex) (3.4.6) (if the {type definition} is complex) or as defined in Type Derivation OK (Simple) (3.14.6) (if the {type definition} is simple).
if (element.fSubGroup != null) {
if (!XSConstraints.checkTypeDerivationOk(element.fType, element.fSubGroup.fType, element.fSubGroup.fFinal)) {
reportSchemaError ("e-props-correct.4", new Object[]{nameAtt, subGroupAtt.prefix+":"+subGroupAtt.localpart}, elmDecl);
element.fSubGroup = null;
}
}
// 5 If the {type definition} or {type definition}'s {content type} is or is derived from ID then there must not be a {value constraint}.
if (element.fDefault != null) {
if ((elementType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE &&
((XSSimpleType)elementType).isIDType()) ||
(elementType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE &&
((XSComplexTypeDecl)elementType).containsTypeID())) {
reportSchemaError ("e-props-correct.5", new Object[]{element.fName}, elmDecl);
element.fDefault = null;
element.setConstraintType(XSConstants.VC_NONE);
}
}
// Element without a name. Return null.
if (element.fName == null)
return null;
// Step 5: register the element decl to the grammar
if (isGlobal) {
grammar.addGlobalElementDecl(element);
}
return element;
}
void reset(SymbolTable symbolTable, boolean validateAnnotations, Locale locale) {
super.reset(symbolTable, validateAnnotations, locale);
fDeferTraversingLocalElements = true;
} // reset()
}
| src/org/apache/xerces/impl/xs/traversers/XSDElementTraverser.java | /*
* 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.xerces.impl.xs.traversers;
import java.util.Locale;
import org.apache.xerces.impl.dv.ValidatedInfo;
import org.apache.xerces.impl.dv.XSSimpleType;
import org.apache.xerces.impl.xs.SchemaGrammar;
import org.apache.xerces.impl.xs.SchemaSymbols;
import org.apache.xerces.impl.xs.XSAnnotationImpl;
import org.apache.xerces.impl.xs.XSComplexTypeDecl;
import org.apache.xerces.impl.xs.XSConstraints;
import org.apache.xerces.impl.xs.XSElementDecl;
import org.apache.xerces.impl.xs.XSParticleDecl;
import org.apache.xerces.impl.xs.util.XInt;
import org.apache.xerces.impl.xs.util.XSObjectListImpl;
import org.apache.xerces.util.DOMUtil;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xs.XSConstants;
import org.apache.xerces.xs.XSObject;
import org.apache.xerces.xs.XSObjectList;
import org.apache.xerces.xs.XSTypeDefinition;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
/**
* The element declaration schema component traverser.
* <element
* abstract = boolean : false
* block = (#all | List of (extension | restriction | substitution))
* default = string
* final = (#all | List of (extension | restriction))
* fixed = string
* form = (qualified | unqualified)
* id = ID
* maxOccurs = (nonNegativeInteger | unbounded) : 1
* minOccurs = nonNegativeInteger : 1
* name = NCName
* nillable = boolean : false
* ref = QName
* substitutionGroup = QName
* type = QName
* {any attributes with non-schema namespace . . .}>
* Content: (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*))
* </element>
*
* @xerces.internal
*
* @author Sandy Gao, IBM
*
* @version $Id$
*/
class XSDElementTraverser extends XSDAbstractTraverser {
protected final XSElementDecl fTempElementDecl = new XSElementDecl();
// this controls what happens when a local element is encountered.
// We may not encounter all local elements when first parsing.
boolean fDeferTraversingLocalElements;
XSDElementTraverser (XSDHandler handler,
XSAttributeChecker gAttrCheck) {
super(handler, gAttrCheck);
}
/**
* Traverse a locally declared element (or an element reference).
*
* To handle the recursive cases efficiently, we delay the traversal
* and return an empty particle node. We'll fill in this particle node
* later after we've done with all the global declarations.
* This method causes a number of data structures in the schema handler to be filled in.
*
* @param elmDecl
* @param schemaDoc
* @param grammar
* @return the particle
*/
XSParticleDecl traverseLocal(Element elmDecl,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar,
int allContextFlags,
XSObject parent) {
XSParticleDecl particle = null;
if (fSchemaHandler.fDeclPool !=null) {
particle = fSchemaHandler.fDeclPool.getParticleDecl();
} else {
particle = new XSParticleDecl();
}
if (fDeferTraversingLocalElements) {
// The only thing we care about now is whether this element has
// minOccurs=0. This affects (if the element appears in a complex
// type) whether a type has emptiable content.
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
Attr attr = elmDecl.getAttributeNode(SchemaSymbols.ATT_MINOCCURS);
if (attr != null) {
String min = attr.getValue();
try {
int m = Integer.parseInt(XMLChar.trim(min));
if (m >= 0)
particle.fMinOccurs = m;
}
catch (NumberFormatException ex) {
}
}
fSchemaHandler.fillInLocalElemInfo(elmDecl, schemaDoc, allContextFlags, parent, particle);
} else {
traverseLocal(particle, elmDecl, schemaDoc, grammar, allContextFlags, parent, null);
// If it's an empty particle, return null.
if (particle.fType == XSParticleDecl.PARTICLE_EMPTY)
particle = null;
}
return particle;
}
/**
* Traverse a locally declared element (or an element reference).
*
* This is the real traversal method. It's called after we've done with
* all the global declarations.
*
* @param index
*/
protected void traverseLocal(XSParticleDecl particle,
Element elmDecl,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar,
int allContextFlags,
XSObject parent,
String[] localNSDecls) {
if (localNSDecls != null) {
schemaDoc.fNamespaceSupport.setEffectiveContext(localNSDecls);
}
// General Attribute Checking
Object[] attrValues = fAttrChecker.checkAttributes(elmDecl, false, schemaDoc);
QName refAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_REF];
XInt minAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_MINOCCURS];
XInt maxAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_MAXOCCURS];
XSElementDecl element = null;
XSAnnotationImpl annotation = null;
if (elmDecl.getAttributeNode(SchemaSymbols.ATT_REF) != null) {
if (refAtt != null) {
element = (XSElementDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ELEMENT_TYPE, refAtt, elmDecl);
Element child = DOMUtil.getFirstChildElement(elmDecl);
if (child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) {
annotation = traverseAnnotationDecl(child, attrValues, false, schemaDoc);
child = DOMUtil.getNextSiblingElement(child);
}
else {
String text = DOMUtil.getSyntheticAnnotation(elmDecl);
if (text != null) {
annotation = traverseSyntheticAnnotation(elmDecl, text, attrValues, false, schemaDoc);
}
}
// Element Declaration Representation OK
// 2 If the item's parent is not <schema>, then all of the following must be true:
// 2.1 One of ref or name must be present, but not both.
// 2.2 If ref is present, then all of <complexType>, <simpleType>, <key>, <keyref>, <unique>, nillable, default, fixed, form, block and type must be absent, i.e. only minOccurs, maxOccurs, id are allowed in addition to ref, along with <annotation>.
if (child != null) {
reportSchemaError("src-element.2.2", new Object[]{refAtt.rawname, DOMUtil.getLocalName(child)}, child);
}
} else {
element = null;
}
} else {
element = traverseNamedElement(elmDecl, attrValues, schemaDoc, grammar, false, parent);
}
particle.fMinOccurs = minAtt.intValue();
particle.fMaxOccurs = maxAtt.intValue();
if (element != null) {
particle.fType = XSParticleDecl.PARTICLE_ELEMENT;
particle.fValue = element;
}
else {
particle.fType = XSParticleDecl.PARTICLE_EMPTY;
}
if (refAtt != null) {
XSObjectList annotations;
if (annotation != null) {
annotations = new XSObjectListImpl();
((XSObjectListImpl) annotations).addXSObject(annotation);
} else {
annotations = XSObjectListImpl.EMPTY_LIST;
}
particle.fAnnotations = annotations;
} else {
particle.fAnnotations = ((element != null) ? element.fAnnotations
: XSObjectListImpl.EMPTY_LIST);
}
Long defaultVals = (Long)attrValues[XSAttributeChecker.ATTIDX_FROMDEFAULT];
checkOccurrences(particle, SchemaSymbols.ELT_ELEMENT,
(Element)elmDecl.getParentNode(), allContextFlags,
defaultVals.longValue());
fAttrChecker.returnAttrArray(attrValues, schemaDoc);
}
/**
* Traverse a globally declared element.
*
* @param elmDecl
* @param schemaDoc
* @param grammar
* @return the element declaration
*/
XSElementDecl traverseGlobal(Element elmDecl,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar) {
// General Attribute Checking'
Object[] attrValues = fAttrChecker.checkAttributes(elmDecl, true, schemaDoc);
XSElementDecl element = traverseNamedElement(elmDecl, attrValues, schemaDoc, grammar, true, null);
fAttrChecker.returnAttrArray(attrValues, schemaDoc);
return element;
}
/**
* Traverse a globally declared element.
*
* @param elmDecl
* @param attrValues
* @param schemaDoc
* @param grammar
* @param isGlobal
* @return the element declaration
*/
XSElementDecl traverseNamedElement(Element elmDecl,
Object[] attrValues,
XSDocumentInfo schemaDoc,
SchemaGrammar grammar,
boolean isGlobal,
XSObject parent) {
Boolean abstractAtt = (Boolean) attrValues[XSAttributeChecker.ATTIDX_ABSTRACT];
XInt blockAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_BLOCK];
String defaultAtt = (String) attrValues[XSAttributeChecker.ATTIDX_DEFAULT];
XInt finalAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_FINAL];
String fixedAtt = (String) attrValues[XSAttributeChecker.ATTIDX_FIXED];
XInt formAtt = (XInt) attrValues[XSAttributeChecker.ATTIDX_FORM];
String nameAtt = (String) attrValues[XSAttributeChecker.ATTIDX_NAME];
Boolean nillableAtt = (Boolean) attrValues[XSAttributeChecker.ATTIDX_NILLABLE];
QName subGroupAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_SUBSGROUP];
QName typeAtt = (QName) attrValues[XSAttributeChecker.ATTIDX_TYPE];
// Step 1: get declaration information
XSElementDecl element = null;
if (fSchemaHandler.fDeclPool !=null) {
element = fSchemaHandler.fDeclPool.getElementDecl();
} else {
element = new XSElementDecl();
}
// get 'name'
if (nameAtt != null)
element.fName = fSymbolTable.addSymbol(nameAtt);
// get 'target namespace'
if (isGlobal) {
element.fTargetNamespace = schemaDoc.fTargetNamespace;
element.setIsGlobal();
}
else {
if (parent instanceof XSComplexTypeDecl)
element.setIsLocal((XSComplexTypeDecl)parent);
if (formAtt != null) {
if (formAtt.intValue() == SchemaSymbols.FORM_QUALIFIED)
element.fTargetNamespace = schemaDoc.fTargetNamespace;
else
element.fTargetNamespace = null;
} else if (schemaDoc.fAreLocalElementsQualified) {
element.fTargetNamespace = schemaDoc.fTargetNamespace;
} else {
element.fTargetNamespace = null;
}
}
// get 'block', 'final', 'nillable', 'abstract'
element.fBlock = blockAtt == null ? schemaDoc.fBlockDefault : blockAtt.shortValue();
element.fFinal = finalAtt == null ? schemaDoc.fFinalDefault : finalAtt.shortValue();
// discard valid Block/Final 'Default' values that are invalid for Block/Final
element.fBlock &= (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION);
element.fFinal &= (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION);
if (nillableAtt.booleanValue())
element.setIsNillable();
if (abstractAtt != null && abstractAtt.booleanValue())
element.setIsAbstract();
// get 'value constraint'
if (fixedAtt != null) {
element.fDefault = new ValidatedInfo();
element.fDefault.normalizedValue = fixedAtt;
element.setConstraintType(XSConstants.VC_FIXED);
} else if (defaultAtt != null) {
element.fDefault = new ValidatedInfo();
element.fDefault.normalizedValue = defaultAtt;
element.setConstraintType(XSConstants.VC_DEFAULT);
} else {
element.setConstraintType(XSConstants.VC_NONE);
}
// get 'substitutionGroup affiliation'
if (subGroupAtt != null) {
element.fSubGroup = (XSElementDecl)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.ELEMENT_TYPE, subGroupAtt, elmDecl);
}
// get 'annotation'
Element child = DOMUtil.getFirstChildElement(elmDecl);
XSAnnotationImpl annotation = null;
if(child != null && DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION)) {
annotation = traverseAnnotationDecl(child, attrValues, false, schemaDoc);
child = DOMUtil.getNextSiblingElement(child);
}
else {
String text = DOMUtil.getSyntheticAnnotation(elmDecl);
if (text != null) {
annotation = traverseSyntheticAnnotation(elmDecl, text, attrValues, false, schemaDoc);
}
}
XSObjectList annotations;
if (annotation != null) {
annotations = new XSObjectListImpl();
((XSObjectListImpl)annotations).addXSObject (annotation);
} else {
annotations = XSObjectListImpl.EMPTY_LIST;
}
element.fAnnotations = annotations;
// get 'type definition'
XSTypeDefinition elementType = null;
boolean haveAnonType = false;
// Handle Anonymous type if there is one
if (child != null) {
String childName = DOMUtil.getLocalName(child);
if (childName.equals(SchemaSymbols.ELT_COMPLEXTYPE)) {
elementType = fSchemaHandler.fComplexTypeTraverser.traverseLocal(child, schemaDoc, grammar);
haveAnonType = true;
child = DOMUtil.getNextSiblingElement(child);
}
else if (childName.equals(SchemaSymbols.ELT_SIMPLETYPE)) {
elementType = fSchemaHandler.fSimpleTypeTraverser.traverseLocal(child, schemaDoc, grammar);
haveAnonType = true;
child = DOMUtil.getNextSiblingElement(child);
}
}
// Handler type attribute
if (elementType == null && typeAtt != null) {
elementType = (XSTypeDefinition)fSchemaHandler.getGlobalDecl(schemaDoc, XSDHandler.TYPEDECL_TYPE, typeAtt, elmDecl);
}
// Get it from the substitutionGroup declaration
if (elementType == null && element.fSubGroup != null) {
elementType = element.fSubGroup.fType;
}
if (elementType == null) {
elementType = SchemaGrammar.fAnyType;
}
element.fType = elementType;
// get 'identity constraint'
// see if there's something here; it had better be key, keyref or unique.
if (child != null) {
String childName = DOMUtil.getLocalName(child);
while (child != null &&
(childName.equals(SchemaSymbols.ELT_KEY) ||
childName.equals(SchemaSymbols.ELT_KEYREF) ||
childName.equals(SchemaSymbols.ELT_UNIQUE))) {
if (childName.equals(SchemaSymbols.ELT_KEY) ||
childName.equals(SchemaSymbols.ELT_UNIQUE)) {
// need to set <key>/<unique> to hidden before traversing it,
// because it has global scope
DOMUtil.setHidden(child, fSchemaHandler.fHiddenNodes);
fSchemaHandler.fUniqueOrKeyTraverser.traverse(child, element, schemaDoc, grammar);
if(DOMUtil.getAttrValue(child, SchemaSymbols.ATT_NAME).length() != 0 ) {
fSchemaHandler.checkForDuplicateNames(
(schemaDoc.fTargetNamespace == null) ? ","+DOMUtil.getAttrValue(child, SchemaSymbols.ATT_NAME)
: schemaDoc.fTargetNamespace+","+ DOMUtil.getAttrValue(child, SchemaSymbols.ATT_NAME),
fSchemaHandler.getIDRegistry(), fSchemaHandler.getIDRegistry_sub(),
child, schemaDoc);
}
} else if (childName.equals(SchemaSymbols.ELT_KEYREF)) {
fSchemaHandler.storeKeyRef(child, schemaDoc, element);
}
child = DOMUtil.getNextSiblingElement(child);
if (child != null) {
childName = DOMUtil.getLocalName(child);
}
}
}
// Step 2: register the element decl to the grammar
if (isGlobal && nameAtt != null)
grammar.addGlobalElementDecl(element);
// Step 3: check against schema for schemas
// required attributes
if (nameAtt == null) {
if (isGlobal)
reportSchemaError("s4s-att-must-appear", new Object[]{SchemaSymbols.ELT_ELEMENT, SchemaSymbols.ATT_NAME}, elmDecl);
else
reportSchemaError("src-element.2.1", null, elmDecl);
nameAtt = NO_NAME;
}
// element
if (child != null) {
reportSchemaError("s4s-elt-must-match.1", new Object[]{nameAtt, "(annotation?, (simpleType | complexType)?, (unique | key | keyref)*))", DOMUtil.getLocalName(child)}, child);
}
// Step 4: check 3.3.3 constraints
// src-element
// 1 default and fixed must not both be present.
if (defaultAtt != null && fixedAtt != null) {
reportSchemaError("src-element.1", new Object[]{nameAtt}, elmDecl);
}
// 2 If the item's parent is not <schema>, then all of the following must be true:
// 2.1 One of ref or name must be present, but not both.
// This is checked in XSAttributeChecker
// 2.2 If ref is present, then all of <complexType>, <simpleType>, <key>, <keyref>, <unique>, nillable, default, fixed, form, block and type must be absent, i.e. only minOccurs, maxOccurs, id are allowed in addition to ref, along with <annotation>.
// Attributes are checked in XSAttributeChecker, elements are checked in "traverse" method
// 3 type and either <simpleType> or <complexType> are mutually exclusive.
if (haveAnonType && (typeAtt != null)) {
reportSchemaError("src-element.3", new Object[]{nameAtt}, elmDecl);
}
// Step 5: check 3.3.6 constraints
// check for NOTATION type
checkNotationType(nameAtt, elementType, elmDecl);
// e-props-correct
// 2 If there is a {value constraint}, the canonical lexical representation of its value must be valid with respect to the {type definition} as defined in Element Default Valid (Immediate) (3.3.6).
if (element.fDefault != null) {
fValidationState.setNamespaceSupport(schemaDoc.fNamespaceSupport);
if (XSConstraints.ElementDefaultValidImmediate(element.fType, element.fDefault.normalizedValue, fValidationState, element.fDefault) == null) {
reportSchemaError ("e-props-correct.2", new Object[]{nameAtt, element.fDefault.normalizedValue}, elmDecl);
element.fDefault = null;
element.setConstraintType(XSConstants.VC_NONE);
}
}
// 4 If there is an {substitution group affiliation}, the {type definition} of the element declaration must be validly derived from the {type definition} of the {substitution group affiliation}, given the value of the {substitution group exclusions} of the {substitution group affiliation}, as defined in Type Derivation OK (Complex) (3.4.6) (if the {type definition} is complex) or as defined in Type Derivation OK (Simple) (3.14.6) (if the {type definition} is simple).
if (element.fSubGroup != null) {
if (!XSConstraints.checkTypeDerivationOk(element.fType, element.fSubGroup.fType, element.fSubGroup.fFinal)) {
reportSchemaError ("e-props-correct.4", new Object[]{nameAtt, subGroupAtt.prefix+":"+subGroupAtt.localpart}, elmDecl);
element.fSubGroup = null;
}
}
// 5 If the {type definition} or {type definition}'s {content type} is or is derived from ID then there must not be a {value constraint}.
if (element.fDefault != null) {
if ((elementType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE &&
((XSSimpleType)elementType).isIDType()) ||
(elementType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE &&
((XSComplexTypeDecl)elementType).containsTypeID())) {
reportSchemaError ("e-props-correct.5", new Object[]{element.fName}, elmDecl);
element.fDefault = null;
element.setConstraintType(XSConstants.VC_NONE);
}
}
// Element without a name. Return null.
if (element.fName == null)
return null;
return element;
}
void reset(SymbolTable symbolTable, boolean validateAnnotations, Locale locale) {
super.reset(symbolTable, validateAnnotations, locale);
fDeferTraversingLocalElements = true;
} // reset()
}
| Another change for https://issues.apache.org/jira/browse/XERCESJ-1372. Need to check substitution group (and possibly remove it) before adding the element declaration to the global element list.
git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@778430 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/xerces/impl/xs/traversers/XSDElementTraverser.java | Another change for https://issues.apache.org/jira/browse/XERCESJ-1372. Need to check substitution group (and possibly remove it) before adding the element declaration to the global element list. |
|
Java | bsd-2-clause | 863116e36f2e8cec3f68a618d72e50991023a159 | 0 | jenkinsci/p4-plugin,jenkinsci/p4-plugin,jenkinsci/p4-plugin | package org.jenkinsci.plugins.p4.client;
import com.perforce.p4java.PropertyDefs;
import com.perforce.p4java.impl.mapbased.rpc.RpcPropertyDefs;
import com.perforce.p4java.option.UsageOptions;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.ServerFactory;
import hudson.util.FormValidation;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Connection Factory
* <p>
* Provides concurrent connections to the Perforce Server
*
* @author pallen
*/
public class ConnectionFactory {
private static Logger logger = Logger.getLogger(ConnectionFactory.class
.getName());
private static IOptionsServer currentP4;
/**
* Returns existing connection
*
* @return Server connection object
*/
public static IOptionsServer getConnection() {
return currentP4;
}
/**
* Creates a server connection; provides a connection to the Perforce
* Server, initially client is undefined.
*
* @param config Connection configuration
* @return Server connection object
* @throws Exception push up stack
*/
public static IOptionsServer getConnection(ConnectionConfig config)
throws Exception {
IOptionsServer iserver = getRawConnection(config);
// Add trust for SSL connections
if (config.isSsl()) {
String serverTrust = iserver.getTrust();
if (!serverTrust.equalsIgnoreCase(config.getTrust())) {
logger.warning("Trust mismatch! Server fingerprint: "
+ serverTrust);
} else {
iserver.addTrust(config.getTrust());
}
}
// Connect and update current P4 connection
iserver.connect();
currentP4 = iserver;
return iserver;
}
public static FormValidation testConnection(ConnectionConfig config) {
// Test for SSL connections
try {
IOptionsServer iserver = getRawConnection(config);
if (config.isSsl()) {
String serverTrust = iserver.getTrust();
if (!serverTrust.equalsIgnoreCase(config.getTrust())) {
return FormValidation
.error("Trust mismatch! Server fingerprint: "
+ serverTrust);
} else {
iserver.addTrust(config.getTrust());
}
}
} catch (Exception e) {
StringBuffer sb = new StringBuffer();
sb.append("Unable to connect to: ");
sb.append(config.getServerUri());
sb.append("\n");
sb.append(e.getMessage());
return FormValidation.error(sb.toString());
}
return FormValidation.ok();
}
private static IOptionsServer getRawConnection(ConnectionConfig config)
throws Exception {
Properties props = System.getProperties();
// Identify ourselves in server log files.
Identifier id = new Identifier();
props.put(PropertyDefs.PROG_NAME_KEY, id.getProduct());
props.put(PropertyDefs.PROG_VERSION_KEY, id.getVersion());
// Allow p4 admin commands.
props.put(RpcPropertyDefs.RPC_RELAX_CMD_NAME_CHECKS_NICK, "true");
// disable timeout for slow servers / large db lock times
String timeout = String.valueOf(config.getTimeout());
props.put(RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK, timeout);
// enable graph depot and AndMaps
props.put(PropertyDefs.ENABLE_GRAPH_SHORT_FORM, "true");
props.put(PropertyDefs.ENABLE_ANDMAPS_SHORT_FORM, "true");
// disable BOM addition to UTF8 files
props.put(PropertyDefs.FILESYS_UTF8BOM_SHORT_FORM, "0");
// Set P4HOST if defined
UsageOptions opts = new UsageOptions(props);
String p4host = config.getP4Host();
if (p4host != null && !p4host.isEmpty()) {
opts.setHostName(p4host);
}
// Get a server connection
String serverUri = config.getServerUri();
IOptionsServer iserver;
iserver = ServerFactory.getOptionsServer(serverUri, props, opts);
return iserver;
}
}
| src/main/java/org/jenkinsci/plugins/p4/client/ConnectionFactory.java | package org.jenkinsci.plugins.p4.client;
import com.perforce.p4java.PropertyDefs;
import com.perforce.p4java.impl.mapbased.rpc.RpcPropertyDefs;
import com.perforce.p4java.option.UsageOptions;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.ServerFactory;
import hudson.util.FormValidation;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Connection Factory
* <p>
* Provides concurrent connections to the Perforce Server
*
* @author pallen
*/
public class ConnectionFactory {
private static Logger logger = Logger.getLogger(ConnectionFactory.class
.getName());
private static IOptionsServer currentP4;
/**
* Returns existing connection
*
* @return Server connection object
*/
public static IOptionsServer getConnection() {
return currentP4;
}
/**
* Creates a server connection; provides a connection to the Perforce
* Server, initially client is undefined.
*
* @param config Connection configuration
* @return Server connection object
* @throws Exception push up stack
*/
public static IOptionsServer getConnection(ConnectionConfig config)
throws Exception {
IOptionsServer iserver = getRawConnection(config);
// Add trust for SSL connections
if (config.isSsl()) {
String serverTrust = iserver.getTrust();
if (!serverTrust.equalsIgnoreCase(config.getTrust())) {
logger.warning("Trust mismatch! Server fingerprint: "
+ serverTrust);
} else {
iserver.addTrust(config.getTrust());
}
}
// Connect and update current P4 connection
iserver.connect();
currentP4 = iserver;
return iserver;
}
public static FormValidation testConnection(ConnectionConfig config) {
// Test for SSL connections
try {
IOptionsServer iserver = getRawConnection(config);
if (config.isSsl()) {
String serverTrust = iserver.getTrust();
if (!serverTrust.equalsIgnoreCase(config.getTrust())) {
return FormValidation
.error("Trust mismatch! Server fingerprint: "
+ serverTrust);
} else {
iserver.addTrust(config.getTrust());
}
}
} catch (Exception e) {
StringBuffer sb = new StringBuffer();
sb.append("Unable to connect to: ");
sb.append(config.getServerUri());
sb.append("\n");
sb.append(e.getMessage());
return FormValidation.error(sb.toString());
}
return FormValidation.ok();
}
private static IOptionsServer getRawConnection(ConnectionConfig config)
throws Exception {
Properties props = System.getProperties();
// Identify ourselves in server log files.
Identifier id = new Identifier();
props.put(PropertyDefs.PROG_NAME_KEY, id.getProduct());
props.put(PropertyDefs.PROG_VERSION_KEY, id.getVersion());
// Allow p4 admin commands.
props.put(RpcPropertyDefs.RPC_RELAX_CMD_NAME_CHECKS_NICK, "true");
// disable timeout for slow servers / large db lock times
String timeout = String.valueOf(config.getTimeout());
props.put(RpcPropertyDefs.RPC_SOCKET_SO_TIMEOUT_NICK, timeout);
// enable graph depot and AndMaps
props.put(PropertyDefs.ENABLE_GRAPH_SHORT_FORM, "true");
props.put(PropertyDefs.ENABLE_ANDMAPS_SHORT_FORM, "true");
// Set P4HOST if defined
UsageOptions opts = new UsageOptions(props);
String p4host = config.getP4Host();
if (p4host != null && !p4host.isEmpty()) {
opts.setHostName(p4host);
}
// Get a server connection
String serverUri = config.getServerUri();
IOptionsServer iserver;
iserver = ServerFactory.getOptionsServer(serverUri, props, opts);
return iserver;
}
}
| Disable BOM addition to UTF8 files.
https://github.com/p4paul/p4-jenkins/issues/32
| src/main/java/org/jenkinsci/plugins/p4/client/ConnectionFactory.java | Disable BOM addition to UTF8 files. |
|
Java | bsd-2-clause | 6de874233fb4d042cb8d95dc0f9da4bb55c8ee40 | 0 | RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools | /*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.util.cli;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import com.rtg.util.EnumHelper;
import com.rtg.util.PseudoEnum;
import com.rtg.util.TestUtils;
import junit.framework.TestCase;
/**
* Tests the CFlags class.
*
* @since 1.0
*/
public class CFlagsTest extends TestCase {
protected CFlags mFlags;
/** Used by JUnit (called after each test method) */
@Override
public void setUp() {
mFlags = new CFlags();
mFlags.setInvalidFlagHandler(null);
}
/** Used by JUnit (called before each test method) */
@Override
public void tearDown() {
mFlags = null;
}
public void testRemaining() {
mFlags.registerRequired("boolean", Boolean.class, "", "");
assertTrue(!mFlags.setFlags("s1", "--boolean", "true", "s2", "s3"));
}
public void testRequired() {
mFlags.registerRequired("boolean", Boolean.class, "a boolean value", "");
assertTrue(!mFlags.setFlags("s1", "s2", "s3"));
}
public void testRepeated() {
mFlags.registerRequired('b', "boolean", Boolean.class, "a boolean value", "");
try {
mFlags.registerRequired("boolean", Boolean.class, "a boolean value", "");
fail("Should not accept registering a flag with preexisting long name");
} catch (final IllegalArgumentException iae) {
// Expected
}
try {
mFlags.registerRequired('b', "foolean", Boolean.class, "a boolean value", "");
fail("Should not accept registering a flag with preexisting short name");
} catch (final IllegalArgumentException iae) {
// Expected
}
}
public void testTooMany() {
mFlags.registerOptional("boolean", "a boolean value");
assertTrue(mFlags.setFlags("--boolean"));
assertTrue(!mFlags.setFlags("--boolean", "--boolean"));
assertTrue(mFlags.setFlags("--boolean"));
mFlags.registerRequired("int", Integer.class, "number", "an integer value");
assertTrue(mFlags.setFlags("--int", "10"));
assertTrue(mFlags.setFlags("--int", "10"));
assertTrue(!mFlags.setFlags("--int", "10", "--boolean", "--int", "10"));
assertTrue(mFlags.setFlags("--int", "10", "--boolean"));
mFlags.registerOptional("stringy", String.class, "string", "some kind of string");
assertTrue(mFlags.setFlags("--int", "10", "--boolean", "--stringy", "a value"));
assertEquals("--int 10 --boolean --stringy \"a value\"", mFlags.getCommandLine());
}
public void testCli() {
mFlags.registerOptional("q", "Suppresses printing error messages and prompts.");
mFlags.registerOptional("log", "Same as q, but allow logging.");
mFlags.registerOptional("in", String.class, "<file>",
"Takes input from a file instead of the keyboard.");
mFlags.registerOptional("out", String.class, "<file>",
"Sends output to a file instead of the screen.", "default");
mFlags
.setDescription("For help on interactive use or script commands, type 'help' at program startup.");
if (!mFlags.setFlags("--q", "--in", "a")) {
fail("Shouldn't fail");
}
assertTrue(mFlags.isSet("q"));
assertTrue(mFlags.isSet("in"));
assertTrue(!mFlags.isSet("out"));
assertEquals("default", mFlags.getValue("out"));
assertEquals(Boolean.FALSE, mFlags.getValue("log"));
assertEquals(Boolean.TRUE, mFlags.getValue("q"));
if (mFlags.setFlags("--q", "--in")) {
fail("Should have failed.");
}
if (mFlags.setFlags("--in", "--help")) {
fail("Should have failed.");
}
}
public void testPrefixRetrieval() {
mFlags.registerRequired("boolean", Boolean.class, "", "");
assertNull(mFlags.getFlag("foo"));
assertNull(mFlags.getFlag("boo"));
assertNotNull(mFlags.getFlag("boolean"));
assertNull(mFlags.getFlagWithExpansion("foo"));
assertNotNull(mFlags.getFlagWithExpansion("boo"));
assertNotNull(mFlags.getFlagWithExpansion("boolean"));
assertTrue(mFlags.setFlags("--boo", "true"));
mFlags.registerRequired("boolean2", Boolean.class, "", "");
assertNull(mFlags.getFlag("boo"));
assertNotNull(mFlags.getFlag("boolean"));
assertNull(mFlags.getFlagWithExpansion("boo"));
assertNotNull(mFlags.getFlagWithExpansion("boolean"));
assertFalse(mFlags.setFlags("--boo", "true"));
}
public void testSetArgsWithStrings() {
mFlags.registerRequired("boolean", Boolean.class, "", "");
mFlags.registerRequired("byte", Byte.class, "", "");
mFlags.registerRequired("short", Short.class, "", "");
mFlags.registerRequired("char", Character.class, "", "");
mFlags.registerRequired("int", Integer.class, "", "");
mFlags.registerRequired("float", Float.class, "", "");
mFlags.registerOptional("long", Long.class, "", "");
mFlags.registerRequired("double", Double.class, "", "");
mFlags.registerOptional("file", File.class, "", "");
assertTrue(mFlags.setFlags("--boolean", "true", "--byte", "10", "--short", "127",
"--char", "c", "--int", "3", "--float", "4.6", "--long", "64234", "--file", "afilename",
"--double", "64324.234"));
assertTrue(mFlags.isSet("boolean"));
assertTrue(mFlags.getValue("boolean").equals(Boolean.TRUE));
assertTrue(mFlags.isSet("byte"));
assertTrue(mFlags.getValue("byte").equals(Byte.valueOf("10")));
assertTrue(mFlags.isSet("short"));
assertTrue(mFlags.getValue("short").equals(Short.valueOf("127")));
assertTrue(mFlags.isSet("char"));
assertTrue(mFlags.getValue("char").equals('c'));
assertTrue(mFlags.isSet("int"));
assertTrue(mFlags.getValue("int").equals(Integer.valueOf("3")));
assertTrue(mFlags.isSet("float"));
assertTrue(mFlags.getValue("float").equals(Float.valueOf("4.6")));
assertTrue(mFlags.isSet("long"));
assertTrue(mFlags.getValue("long").equals(Long.valueOf("64234")));
assertTrue(mFlags.isSet("double"));
assertTrue(mFlags.getValue("double").equals(Double.valueOf("64324.234")));
assertTrue(mFlags.isSet("file"));
assertTrue(mFlags.getValue("file").equals(new File("afilename")));
// getOptional and getRequired
final Collection<Flag> optional = mFlags.getOptional();
assertNotNull(optional);
assertTrue(4 == optional.size()); // always has help / XXhelp
assertFalse(optional.contains(mFlags.getFlag("boolean")));
assertTrue(optional.contains(mFlags.getFlag("help"))); // always has help
assertTrue(optional.contains(mFlags.getFlag("long")));
assertTrue(optional.contains(mFlags.getFlag("file")));
final Collection<Flag> required = mFlags.getRequired();
assertNotNull(required);
assertTrue(7 == required.size());
assertFalse(required.contains(mFlags.getFlag("long")));
assertTrue(required.contains(mFlags.getFlag("boolean")));
assertTrue(required.contains(mFlags.getFlag("byte")));
assertTrue(required.contains(mFlags.getFlag("short")));
assertTrue(required.contains(mFlags.getFlag("char")));
assertTrue(required.contains(mFlags.getFlag("int")));
assertTrue(required.contains(mFlags.getFlag("float")));
assertTrue(required.contains(mFlags.getFlag("double")));
// getType
assertEquals(Boolean.class, mFlags.getFlag("boolean").getParameterType());
assertEquals(Byte.class, mFlags.getFlag("byte").getParameterType());
assertEquals(Short.class, mFlags.getFlag("short").getParameterType());
assertEquals(Character.class, mFlags.getFlag("char").getParameterType());
assertEquals(Integer.class, mFlags.getFlag("int").getParameterType());
assertEquals(Long.class, mFlags.getFlag("long").getParameterType());
assertEquals(Float.class, mFlags.getFlag("float").getParameterType());
assertEquals(Double.class, mFlags.getFlag("double").getParameterType());
assertEquals(File.class, mFlags.getFlag("file").getParameterType());
}
//Hard to convert test. does not improve jumble score. Potentially does nothing
//public void testGetSet() {
// BeanPropertyTester bps = new BeanPropertyTester(mFlags);
// bps.testProperties();
//}
private static final String LS = System.lineSeparator();
public void testHelpFlag() {
final CFlags f = new CFlags();
final Flag x = f.getFlag("help");
assertNotNull(x);
assertEquals(Character.valueOf('h'), x.getChar());
assertEquals("print help on command-line flag usage", x.getDescription());
}
public void testVariousKinds() {
Flag f = mFlags.registerOptional("aa", "bb");
assertNotNull(f);
assertEquals("bb", f.getDescription());
f = mFlags.registerOptional('v', "cc", "dd");
assertNotNull(f);
assertEquals("dd", f.getDescription());
f = mFlags.registerRequired(File.class, "hi", "there");
assertNotNull(f);
f = mFlags.registerRequired("zz", File.class, "hix", "therex");
assertNotNull(f);
f = mFlags.registerRequired('j', "zzz", File.class, "hiz", "therez");
assertNotNull(f);
f = mFlags.registerOptional("zzr", File.class, "him", "therem");
assertNotNull(f);
// Nice long description that wraps around. However, when run on
// a regular user terminal, this may fail if the wrapping occurs
// at a different width.
f = mFlags.registerOptional('k', "zzx", File.class, "hih hih hih",
"thereh thereh thereh thereh thereh thereh thereh thereh thereh thereh thereh thereh");
assertNotNull(f);
f = mFlags.registerOptional('l', "zzy", File.class, "hio", "thereo", null);
assertNotNull(f);
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2"));
assertEquals("You must provide values for --zz HIX HI", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2", "-zz", "dog"));
assertEquals("Unknown flag -zz", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2", "--zz", "dog"));
assertEquals("You must provide a value for HI", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-l", "pox", "-j", "pox2", "--zz", "dog", "cat"));
assertEquals("", mFlags.getParseMessage());
TestUtils.containsAll(mFlags.getUsageString(), "Required flags: " + LS + " --zz=HIX therex" + LS
+ " -j, --zzz=HIZ therez" + LS + " HI there" + LS + LS
+ "Optional flags: " + LS + " --aa bb" + LS
+ " -v, --cc dd" + LS
+ " -h, --help print help on command-line flag usage" + LS
+ " --zzr=HIM therem",
" -k, --zzx=HIH HIH HIH thereh thereh thereh thereh thereh thereh",
" -l, --zzy=HIO thereo" + LS);
assertEquals("cat", mFlags.getAnonymousValue(0).toString());
try {
mFlags.getAnonymousValue(1);
} catch (final IndexOutOfBoundsException e) {
// ok
}
assertEquals(1, mFlags.getAnonymousValues(0).size());
assertTrue(mFlags.setFlags("-l", "pox", "-j", "pox2=r", "--zz", "dog", "cat"));
assertEquals("", mFlags.getParseMessage());
mFlags.setDescription("flunky test");
mFlags.setName("dogbreath");
mFlags.setRemainderHeader("%%");
TestUtils.containsAll(mFlags.getUsageString(), "Usage: dogbreath [OPTION]... --zz HIX -j HIZ HI %%" + LS + LS
+ "flunky test" + LS + LS
+ "Required flags: " + LS + " --zz=HIX therex" + LS
+ " -j, --zzz=HIZ therez" + LS + " HI there" + LS + LS
+ "Optional flags: " + LS + " --aa bb" + LS
+ " -v, --cc dd" + LS
+ " -h, --help print help on command-line flag usage" + LS
+ " --zzr=HIM therem" + LS
+ " -k, --zzx=HIH HIH HIH thereh thereh thereh thereh thereh thereh",
" -l, --zzy=HIO thereo" + LS);
assertEquals("[OPTION]... --zz HIX -j HIZ HI", mFlags.getCompactFlagUsage());
assertFalse(mFlags.setFlags("-l", "pox", "--help", "-j", "pox2=r", "--zz", "dog",
"cat"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("-l", "pox", "-h", "-j", "pox2=r", "--zz", "dog",
"cat"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2=r", "--zz", "dog", "cat",
"-h"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2=r", "--zz", "dog", "cat",
"--help"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
}
public void testInvalid() {
mFlags.setValidator(new Validator() {
@Override
public boolean isValid(final CFlags f) {
return false;
}
});
assertFalse(mFlags.setFlags());
mFlags.registerRequired("zz", Integer.class, "hix", "therex");
assertFalse(mFlags.setFlags());
}
public void testMultiValue() {
final Flag f = new Flag('x', "xx", "mv", 3, 4, Integer.class, "kk", 42, "try");
mFlags.register(f);
assertEquals("try", f.getCategory());
assertFalse(mFlags.isSet("xx"));
assertFalse(mFlags.setFlags("-x", "7"));
assertEquals("You must provide a value for -x KK (2 more times)", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--xx", "7"));
assertEquals("You must provide a value for -x KK (2 more times)", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-x", "7", "-x", "8"));
assertEquals("You must provide a value for -x KK (1 more time)", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "7", "-x", "8", "-x", "9"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "7", "-x", "8", "-x", "9", "-x", "10"));
assertEquals("", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-x", "7", "-x", "8", "-x", "9", "-x", "10", "-x",
"11"));
assertEquals("Attempt to set flag -x too many times.", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "7", "-x", "8", "--xx", "9", "-x", "10"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "7", "-x", "8", "--xx=9", "-x", "10"));
assertEquals("", mFlags.getParseMessage());
assertNotNull(mFlags.getValues("xx"));
assertNotNull(mFlags.getReceivedValues());
assertTrue(mFlags.isSet("xx"));
assertFalse(mFlags.isSet("yy"));
assertFalse(mFlags.setFlags("-x", "7", "-x", "8", "--xx", "9", "-x", "10", "-x",
"11"));
assertEquals("Attempt to set flag -x too many times.", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-x", "7", "-x", "8", "--xx", "9", "-x", "10", "-x",
"11", "-h", "--helx"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("-x", "7", "-x", "8", "--xx", "9", "-x", "10", "-x",
"11", "-o", "--help"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
}
public void testParseInt() {
final Flag f = new AnonymousFlag("mv", Integer.class, "kk");
mFlags.register(f);
assertTrue(mFlags.setFlags("09"));
assertEquals(9, mFlags.getAnonymousValue(0));
}
public void testMultiValueAnon() {
final Flag f = new AnonymousFlag("mv", Integer.class, "kk");
f.setMaxCount(4);
f.setMinCount(3);
mFlags.register(f);
assertFalse(mFlags.setFlags("7"));
assertEquals("You must provide a value for KK+ (2 more times)", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("7", "8"));
assertEquals("You must provide a value for KK+ (1 more time)", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("7", "8", "9"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("7", "8", "9", "10"));
assertEquals("", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("7", "8", "9", "10", "11"));
assertEquals("Unexpected argument \"11\"", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("7", "8", "9", "10", "-h"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("7", "8", "9", "10", "--help"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("7", "8", "9", "10", "11", "--help"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
mFlags.setInvalidFlagHandler(new InvalidFlagHandler() {
@Override
public void handleInvalidFlags(final CFlags ff) {
throw new ArithmeticException();
}
});
try {
mFlags.setFlags("7", "8", "9", "10", "11");
fail();
} catch (final ArithmeticException e) {
// ok
}
assertTrue(mFlags.setFlags("7", "8", "9", "10"));
assertNotNull(mFlags.getAnonymousFlags());
}
public void testRequired2() {
Flag f = mFlags.registerRequired("zz", File.class, "hix", "therex");
assertNotNull(f);
f = mFlags.registerRequired('j', "zzz", File.class, "hiz", "therez");
assertNotNull(f);
assertFalse(mFlags.setFlags());
assertEquals("You must provide values for --zz HIX -j HIZ", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--zz", "h"));
assertEquals("You must provide a value for -j HIZ", mFlags.getParseMessage());
// assertFalse(mFlags.setFlags("--zz", "h", "-j", "test\nthis"));
// assertEquals("Invalid value \"test\nthis\" for \"-j\". Value cannot contain new line characters.", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--zz", "h", "t"));
assertEquals("Unexpected argument \"t\"", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--zz", "h", "t", "k"));
assertEquals("Unexpected arguments \"t\" \"k\"", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--uu", "--zz", "h"));
assertEquals("Unknown flag --uu", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--zz", "h"));
assertEquals("You must provide a value for -j HIZ", mFlags.getParseMessage());
try {
mFlags.setFlags("--zz", null);
fail();
} catch (final NullPointerException e) {
// ok
}
}
public void testRange() {
final Flag f = new Flag('x', "xx", "mv", 1, 1, String.class, "kk", null, "");
final HashSet<String> m = new HashSet<>();
try {
f.setParameterRange(m);
fail();
} catch (final IllegalArgumentException e) {
// ok
}
m.add("value");
f.setParameterRange(m);
m.add("pox");
f.setParameterRange(m);
mFlags.register(f);
assertFalse(mFlags.setFlags("--xx", "v"));
assertEquals("Invalid value \"v\" for flag --xx. Value supplied is not in the set of allowed values.",
mFlags.getParseMessage());
assertTrue(mFlags.setFlags("--xx", "value"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "pox"));
assertEquals("", mFlags.getParseMessage());
}
public void testNumericRangeChecks() {
mFlags.registerOptional("a", Integer.class, "int", "therex");
mFlags.registerOptional("b", Double.class, "float", "therex");
mFlags.setFlags("--a", "2", "--b", "2");
assertTrue(mFlags.checkInRange("a", 2, true, 4, true));
assertFalse(mFlags.checkInRange("a", 2, false, 4, true));
assertTrue(mFlags.getParseMessage().contains("(2, 4]"));
assertFalse(mFlags.checkInRange("a", 3, true, 4, true));
assertTrue(mFlags.getParseMessage().contains("[3, 4]"));
assertTrue(mFlags.checkInRange("a", 0, true, 2, true));
assertFalse(mFlags.checkInRange("a", 0, true, 2, false));
assertTrue(mFlags.getParseMessage().contains("[0, 2)"));
assertFalse(mFlags.checkInRange("a", 0, true, 1, true));
assertTrue(mFlags.getParseMessage().contains("[0, 1]"));
assertFalse(mFlags.checkInRange("a", 3, true, Integer.MAX_VALUE, true));
assertTrue(mFlags.getParseMessage().contains("at least 3"));
assertFalse(mFlags.checkInRange("a", Integer.MIN_VALUE, true, 2, false));
assertTrue(mFlags.getParseMessage().contains("less than 2"));
assertTrue(mFlags.checkInRange("b", 2.0, true, 4.0, true));
assertFalse(mFlags.checkInRange("b", 2.0, false, 4.0, true));
assertTrue(mFlags.getParseMessage().contains("(2.0, 4.0]"));
assertFalse(mFlags.checkInRange("b", 3.0, true, 4.0, true));
assertTrue(mFlags.getParseMessage().contains("[3.0, 4.0]"));
assertTrue(mFlags.checkInRange("b", 0.0, true, 2.0, true));
assertFalse(mFlags.checkInRange("b", 0.0, true, 2.0, false));
assertTrue(mFlags.getParseMessage().contains("[0.0, 2.0)"));
assertFalse(mFlags.checkInRange("b", 0.0, true, 1.0, true));
assertTrue(mFlags.getParseMessage().contains("[0.0, 1.0]"));
assertFalse(mFlags.checkInRange("b", 3.0, true, Double.MAX_VALUE, true));
assertTrue(mFlags.getParseMessage().contains("at least 3.0"));
assertFalse(mFlags.checkInRange("b", -Double.MAX_VALUE, true, 2.0, false));
assertTrue(mFlags.getParseMessage().contains("less than 2.0"));
}
public void testCrossFlagChecks() {
mFlags.registerOptional("a", "therex");
mFlags.registerOptional("b", "therex");
mFlags.registerOptional("c", "therex");
mFlags.registerOptional("d", "therex");
mFlags.setFlags("--a", "--b");
assertTrue(mFlags.isSet("a"));
assertTrue(mFlags.isSet("b"));
// True if any one is set
assertTrue(mFlags.checkOr("a", "b"));
assertTrue(mFlags.checkOr("b", "c", "d"));
assertFalse(mFlags.checkOr("c", "d"));
// True if at most one is set
assertTrue(mFlags.checkNand("a", "d"));
assertTrue(mFlags.checkNand("c", "d"));
assertFalse(mFlags.checkNand("a", "b"));
assertTrue(mFlags.checkAtMostOne("a", "d"));
assertTrue(mFlags.checkAtMostOne("c", "d"));
assertFalse(mFlags.checkAtMostOne("a", "b"));
assertFalse(mFlags.checkAtMostOne("a", "b", "c", "d"));
// True if all are set
assertTrue(mFlags.checkRequired("a", "b"));
assertFalse(mFlags.checkRequired("a", "d"));
// True if exactly one is set
assertTrue(mFlags.checkXor("b", "c", "d"));
assertFalse(mFlags.checkXor("a", "b"));
assertFalse(mFlags.checkXor("c", "d"));
// True if neither or both are
assertTrue(mFlags.checkIff("a", "b"));
assertTrue(mFlags.checkIff("c", "d"));
assertFalse(mFlags.checkIff("a", "c"));
}
public void testSpecialAnonProps() {
final AnonymousFlag f1 = new AnonymousFlag("mv", Integer.class, "kk");
final AnonymousFlag f2 = new AnonymousFlag("mx", Integer.class, "zz");
assertEquals(1, f2.compareTo(f1));
assertEquals(-1, f1.compareTo(f2));
assertEquals(0, f1.compareTo(f1));
}
public void testFlagInnerClass() {
Flag f = new Flag('x', "xx", "mv", 0, 1, Integer.class, "kk", 42, "");
try {
f.setMaxCount(0);
fail();
} catch (final IllegalArgumentException e) {
// ok
}
f.setMaxCount(2);
f.setMinCount(2);
try {
f.setMaxCount(1);
fail();
} catch (final IllegalArgumentException e) {
// ok
}
Collection<Object> c = f.getValues();
assertTrue(c.contains(42));
f = new Flag('x', "xx", "mv", 3, 4, null, "kk", 42, "");
c = f.getValues();
assertTrue(c.contains(Boolean.FALSE));
final Flag f1 = new Flag('x', "xx", "mv", 3, 4, Integer.class, "kk", 42, "");
final Flag f2 = new Flag('y', "xy", "my", 3, 4, Integer.class, "ky", 42, "");
assertEquals(1, f2.compareTo(f1));
assertEquals(-1, f1.compareTo(f2));
assertEquals(0, f1.compareTo(f1));
f = new Flag('x', "xx", "mv", 0, Integer.MAX_VALUE, Integer.class, "kk", 42, "");
mFlags.register(f);
assertEquals(LS + "Optional flags: " + LS
+ " -h, --help print help on command-line flag usage" + LS
+ " -x, --xx=KK mv. May be specified 0 or more times (Default is 42)" + LS, mFlags
.getUsageString());
mFlags.setFlags("-x", "22");
final List<FlagValue> i = mFlags.getReceivedValues();
assertEquals(1, i.size());
final FlagValue fv = i.get(0);
assertNotNull(fv);
assertEquals(f, fv.getFlag());
assertEquals(22, fv.getValue());
assertEquals("xx=22", fv.toString());
}
static final class TestMyEnum implements PseudoEnum {
public static final TestMyEnum ONE = new TestMyEnum(0, "ONE");
public static final TestMyEnum TWO = new TestMyEnum(1, "TWO");
public static final TestMyEnum THREE = new TestMyEnum(2, "THREE");
private final int mOrdinal;
private final String mName;
private TestMyEnum(final int ordinal, final String name) {
mOrdinal = ordinal;
mName = name;
}
@Override
public String name() {
return mName;
}
@Override
public int ordinal() {
return mOrdinal;
}
@Override
public String toString() {
return mName;
}
private static final EnumHelper<TestMyEnum> ENUM_HELPER = new EnumHelper<>(TestMyEnum.class, new TestMyEnum[] {ONE, TWO, THREE});
public static TestMyEnum[] values() {
return ENUM_HELPER.values();
}
public static TestMyEnum valueOf(final String str) {
return ENUM_HELPER.valueOf(str);
}
}
public void testEnum() {
mFlags.registerRequired(TestMyEnum.class, "enum", "ENUM VALUE");
assertTrue(mFlags.setFlags("one"));
assertEquals(TestMyEnum.ONE, mFlags.getAnonymousValue(0));
}
public void testEnumDescription() {
mFlags.registerRequired(TestMyEnum.class, "enum", "ENUM VALUE");
final String str = mFlags.getUsageString();
assertTrue(str, str.toLowerCase(Locale.getDefault()).contains("allowed values are [one, two, three]"));
}
public void testEnum2() {
mFlags.registerRequired(TestMyEnum.class, "enum", "enum value");
assertFalse(mFlags.setFlags("nonvalue"));
}
public void testTypeChecking() {
mFlags.registerRequired(Integer.class, "int", "");
assertFalse(mFlags.setFlags("abc123"));
}
public void testInvalidFlagHandler() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final PrintStream out = new PrintStream(bos);
final ByteArrayOutputStream berr = new ByteArrayOutputStream();
final PrintStream err = new PrintStream(berr);
final CFlags f = new CFlags("", out, err);
f.setFlags("-h");
err.flush();
out.flush();
assertEquals("Usage: [OPTION]..." + LS + LS + "Optional flags: " + LS + " -h, --help print help on command-line flag usage" + LS + LS + "", bos.toString());
assertEquals("", berr.toString());
bos.reset();
f.setFlags("--no-such-flag");
err.flush();
assertEquals("Error: Unknown flag --no-such-flag" + LS + LS + "Usage: [OPTION]..." + LS + LS + "Try \'--help\' for more information" + LS, berr.toString());
assertEquals("", bos.toString());
}
public void testXHelp() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final PrintStream err = new PrintStream(bos);
final CFlags f = new CFlags("", err, null);
f.registerExtendedHelp();
f.registerOptional("Xoptional", "Test of --X options");
f.setFlags("-h");
err.flush();
assertEquals("Usage: [OPTION]..." + LS + LS + "Optional flags: " + LS
+ " -h, --help print help on command-line flag usage" + LS
+ LS + "", bos.toString());
bos.reset();
f.setFlags("--Xhelp");
err.flush();
TestUtils.containsAllUnwrapped(bos.toString(),
"Usage: [OPTION]...",
"Use them with caution",
"Optional flags: ",
" --Xhelp", "print help on extended command-line flag usage",
" --Xoptional Test of --X options");
}
public void testUnregister() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final PrintStream err = new PrintStream(bos);
final CFlags flags = new CFlags("", err, null);
flags.registerOptional('a', "A", "a");
Flag f = flags.unregister("A");
assertNotNull(f);
f = flags.unregister("B");
assertNull(f);
}
public void testXor() {
mFlags.registerRequired(TestMyEnum.class, "enum", "ENUM VALUE");
assertTrue(mFlags.setFlags("one"));
assertEquals(TestMyEnum.ONE, mFlags.getAnonymousValue(0));
}
}
| test/com/rtg/util/cli/CFlagsTest.java | /*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.util.cli;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import com.rtg.util.EnumHelper;
import com.rtg.util.PseudoEnum;
import com.rtg.util.TestUtils;
import junit.framework.TestCase;
/**
* Tests the CFlags class.
*
* @since 1.0
*/
public class CFlagsTest extends TestCase {
protected CFlags mFlags;
/** Used by JUnit (called after each test method) */
@Override
public void setUp() {
mFlags = new CFlags();
mFlags.setInvalidFlagHandler(null);
}
/** Used by JUnit (called before each test method) */
@Override
public void tearDown() {
mFlags = null;
}
public void testRemaining() {
mFlags.registerRequired("boolean", Boolean.class, "", "");
assertTrue(!mFlags.setFlags("s1", "--boolean", "true", "s2", "s3"));
}
public void testRequired() {
mFlags.registerRequired("boolean", Boolean.class, "a boolean value", "");
assertTrue(!mFlags.setFlags("s1", "s2", "s3"));
}
public void testRepeated() {
mFlags.registerRequired('b', "boolean", Boolean.class, "a boolean value", "");
try {
mFlags.registerRequired("boolean", Boolean.class, "a boolean value", "");
fail("Should not accept registering a flag with preexisting long name");
} catch (final IllegalArgumentException iae) {
// Expected
}
try {
mFlags.registerRequired('b', "foolean", Boolean.class, "a boolean value", "");
fail("Should not accept registering a flag with preexisting short name");
} catch (final IllegalArgumentException iae) {
// Expected
}
}
public void testTooMany() {
mFlags.registerOptional("boolean", "a boolean value");
assertTrue(mFlags.setFlags("--boolean"));
assertTrue(!mFlags.setFlags("--boolean", "--boolean"));
assertTrue(mFlags.setFlags("--boolean"));
mFlags.registerRequired("int", Integer.class, "number", "an integer value");
assertTrue(mFlags.setFlags("--int", "10"));
assertTrue(mFlags.setFlags("--int", "10"));
assertTrue(!mFlags.setFlags("--int", "10", "--boolean", "--int", "10"));
assertTrue(mFlags.setFlags("--int", "10", "--boolean"));
mFlags.registerOptional("stringy", String.class, "string", "some kind of string");
assertTrue(mFlags.setFlags("--int", "10", "--boolean", "--stringy", "a value"));
assertEquals("--int 10 --boolean --stringy \"a value\"", mFlags.getCommandLine());
}
public void testCli() {
mFlags.registerOptional("q", "Suppresses printing error messages and prompts.");
mFlags.registerOptional("log", "Same as q, but allow logging.");
mFlags.registerOptional("in", String.class, "<file>",
"Takes input from a file instead of the keyboard.");
mFlags.registerOptional("out", String.class, "<file>",
"Sends output to a file instead of the screen.", "default");
mFlags
.setDescription("For help on interactive use or script commands, type 'help' at program startup.");
if (!mFlags.setFlags("--q", "--in", "a")) {
fail("Shouldn't fail");
}
assertTrue(mFlags.isSet("q"));
assertTrue(mFlags.isSet("in"));
assertTrue(!mFlags.isSet("out"));
assertEquals("default", mFlags.getValue("out"));
assertEquals(Boolean.FALSE, mFlags.getValue("log"));
assertEquals(Boolean.TRUE, mFlags.getValue("q"));
if (mFlags.setFlags("--q", "--in")) {
fail("Should have failed.");
}
if (mFlags.setFlags("--in", "--help")) {
fail("Should have failed.");
}
}
public void testPrefixRetrieval() {
mFlags.registerRequired("boolean", Boolean.class, "", "");
assertNull(mFlags.getFlag("foo"));
assertNull(mFlags.getFlag("boo"));
assertNotNull(mFlags.getFlag("boolean"));
assertNull(mFlags.getFlagWithExpansion("foo"));
assertNotNull(mFlags.getFlagWithExpansion("boo"));
assertNotNull(mFlags.getFlagWithExpansion("boolean"));
assertTrue(mFlags.setFlags("--boo", "true"));
mFlags.registerRequired("boolean2", Boolean.class, "", "");
assertNull(mFlags.getFlag("boo"));
assertNotNull(mFlags.getFlag("boolean"));
assertNull(mFlags.getFlagWithExpansion("boo"));
assertNotNull(mFlags.getFlagWithExpansion("boolean"));
assertFalse(mFlags.setFlags("--boo", "true"));
}
public void testSetArgsWithStrings() {
mFlags.registerRequired("boolean", Boolean.class, "", "");
mFlags.registerRequired("byte", Byte.class, "", "");
mFlags.registerRequired("short", Short.class, "", "");
mFlags.registerRequired("char", Character.class, "", "");
mFlags.registerRequired("int", Integer.class, "", "");
mFlags.registerRequired("float", Float.class, "", "");
mFlags.registerOptional("long", Long.class, "", "");
mFlags.registerRequired("double", Double.class, "", "");
mFlags.registerOptional("file", File.class, "", "");
assertTrue(mFlags.setFlags("--boolean", "true", "--byte", "10", "--short", "127",
"--char", "c", "--int", "3", "--float", "4.6", "--long", "64234", "--file", "afilename",
"--double", "64324.234"));
assertTrue(mFlags.isSet("boolean"));
assertTrue(mFlags.getValue("boolean").equals(Boolean.TRUE));
assertTrue(mFlags.isSet("byte"));
assertTrue(mFlags.getValue("byte").equals(Byte.valueOf("10")));
assertTrue(mFlags.isSet("short"));
assertTrue(mFlags.getValue("short").equals(Short.valueOf("127")));
assertTrue(mFlags.isSet("char"));
assertTrue(mFlags.getValue("char").equals('c'));
assertTrue(mFlags.isSet("int"));
assertTrue(mFlags.getValue("int").equals(Integer.valueOf("3")));
assertTrue(mFlags.isSet("float"));
assertTrue(mFlags.getValue("float").equals(Float.valueOf("4.6")));
assertTrue(mFlags.isSet("long"));
assertTrue(mFlags.getValue("long").equals(Long.valueOf("64234")));
assertTrue(mFlags.isSet("double"));
assertTrue(mFlags.getValue("double").equals(Double.valueOf("64324.234")));
assertTrue(mFlags.isSet("file"));
assertTrue(mFlags.getValue("file").equals(new File("afilename")));
// getOptional and getRequired
final Collection<Flag> optional = mFlags.getOptional();
assertNotNull(optional);
assertTrue(4 == optional.size()); // always has help / XXhelp
assertFalse(optional.contains(mFlags.getFlag("boolean")));
assertTrue(optional.contains(mFlags.getFlag("help"))); // always has help
assertTrue(optional.contains(mFlags.getFlag("long")));
assertTrue(optional.contains(mFlags.getFlag("file")));
final Collection<Flag> required = mFlags.getRequired();
assertNotNull(required);
assertTrue(7 == required.size());
assertFalse(required.contains(mFlags.getFlag("long")));
assertTrue(required.contains(mFlags.getFlag("boolean")));
assertTrue(required.contains(mFlags.getFlag("byte")));
assertTrue(required.contains(mFlags.getFlag("short")));
assertTrue(required.contains(mFlags.getFlag("char")));
assertTrue(required.contains(mFlags.getFlag("int")));
assertTrue(required.contains(mFlags.getFlag("float")));
assertTrue(required.contains(mFlags.getFlag("double")));
// getType
assertEquals(Boolean.class, mFlags.getFlag("boolean").getParameterType());
assertEquals(Byte.class, mFlags.getFlag("byte").getParameterType());
assertEquals(Short.class, mFlags.getFlag("short").getParameterType());
assertEquals(Character.class, mFlags.getFlag("char").getParameterType());
assertEquals(Integer.class, mFlags.getFlag("int").getParameterType());
assertEquals(Long.class, mFlags.getFlag("long").getParameterType());
assertEquals(Float.class, mFlags.getFlag("float").getParameterType());
assertEquals(Double.class, mFlags.getFlag("double").getParameterType());
assertEquals(File.class, mFlags.getFlag("file").getParameterType());
}
//Hard to convert test. does not improve jumble score. Potentially does nothing
//public void testGetSet() {
// BeanPropertyTester bps = new BeanPropertyTester(mFlags);
// bps.testProperties();
//}
private static final String LS = System.lineSeparator();
public void testHelpFlag() {
final CFlags f = new CFlags();
final Flag x = f.getFlag("help");
assertNotNull(x);
assertEquals(Character.valueOf('h'), x.getChar());
assertEquals("print help on command-line flag usage", x.getDescription());
}
public void testVariousKinds() {
Flag f = mFlags.registerOptional("aa", "bb");
assertNotNull(f);
assertEquals("bb", f.getDescription());
f = mFlags.registerOptional('v', "cc", "dd");
assertNotNull(f);
assertEquals("dd", f.getDescription());
f = mFlags.registerRequired(File.class, "hi", "there");
assertNotNull(f);
f = mFlags.registerRequired("zz", File.class, "hix", "therex");
assertNotNull(f);
f = mFlags.registerRequired('j', "zzz", File.class, "hiz", "therez");
assertNotNull(f);
f = mFlags.registerOptional("zzr", File.class, "him", "therem");
assertNotNull(f);
// Nice long description that wraps around. However, when run on
// a regular user terminal, this may fail if the wrapping occurs
// at a different width.
f = mFlags.registerOptional('k', "zzx", File.class, "hih hih hih",
"thereh thereh thereh thereh thereh thereh thereh thereh thereh thereh thereh thereh");
assertNotNull(f);
f = mFlags.registerOptional('l', "zzy", File.class, "hio", "thereo", null);
assertNotNull(f);
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2"));
assertEquals("You must provide values for --zz HIX HI", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2", "-zz", "dog"));
assertEquals("Unknown flag -zz", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2", "--zz", "dog"));
assertEquals("You must provide a value for HI", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-l", "pox", "-j", "pox2", "--zz", "dog", "cat"));
assertEquals("", mFlags.getParseMessage());
TestUtils.containsAll(mFlags.getUsageString(), "Required flags: " + LS + " --zz=HIX therex" + LS
+ " -j, --zzz=HIZ therez" + LS + " HI there" + LS + LS
+ "Optional flags: " + LS + " --aa bb" + LS
+ " -v, --cc dd" + LS
+ " -h, --help print help on command-line flag usage" + LS
+ " --zzr=HIM therem",
" -k, --zzx=HIH HIH HIH thereh thereh thereh thereh thereh thereh",
" -l, --zzy=HIO thereo" + LS);
assertEquals("cat", mFlags.getAnonymousValue(0).toString());
try {
mFlags.getAnonymousValue(1);
} catch (final IndexOutOfBoundsException e) {
// ok
}
assertEquals(1, mFlags.getAnonymousValues(0).size());
assertTrue(mFlags.setFlags("-l", "pox", "-j", "pox2=r", "--zz", "dog", "cat"));
assertEquals("", mFlags.getParseMessage());
mFlags.setDescription("flunky test");
mFlags.setName("dogbreath");
mFlags.setRemainderHeader("%%");
TestUtils.containsAll(mFlags.getUsageString(), "Usage: dogbreath [OPTION]... --zz HIX -j HIZ HI %%" + LS + LS
+ "flunky test" + LS + LS
+ "Required flags: " + LS + " --zz=HIX therex" + LS
+ " -j, --zzz=HIZ therez" + LS + " HI there" + LS + LS
+ "Optional flags: " + LS + " --aa bb" + LS
+ " -v, --cc dd" + LS
+ " -h, --help print help on command-line flag usage" + LS
+ " --zzr=HIM therem" + LS
+ " -k, --zzx=HIH HIH HIH thereh thereh thereh thereh thereh thereh",
" -l, --zzy=HIO thereo" + LS);
assertEquals("[OPTION]... --zz HIX -j HIZ HI", mFlags.getCompactFlagUsage());
assertFalse(mFlags.setFlags("-l", "pox", "--help", "-j", "pox2=r", "--zz", "dog",
"cat"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("-l", "pox", "-h", "-j", "pox2=r", "--zz", "dog",
"cat"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2=r", "--zz", "dog", "cat",
"-h"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("-l", "pox", "-j", "pox2=r", "--zz", "dog", "cat",
"--help"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
}
public void testInvalid() {
mFlags.setValidator(new Validator() {
@Override
public boolean isValid(final CFlags f) {
return false;
}
});
assertFalse(mFlags.setFlags());
mFlags.registerRequired("zz", Integer.class, "hix", "therex");
assertFalse(mFlags.setFlags());
}
public void testMultiValue() {
final Flag f = new Flag('x', "xx", "mv", 3, 4, Integer.class, "kk", 42, "try");
mFlags.register(f);
assertEquals("try", f.getCategory());
assertFalse(mFlags.isSet("xx"));
assertFalse(mFlags.setFlags("-x", "7"));
assertEquals("You must provide a value for -x KK (2 more times)", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--xx", "7"));
assertEquals("You must provide a value for -x KK (2 more times)", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-x", "7", "-x", "8"));
assertEquals("You must provide a value for -x KK (1 more time)", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "7", "-x", "8", "-x", "9"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "7", "-x", "8", "-x", "9", "-x", "10"));
assertEquals("", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-x", "7", "-x", "8", "-x", "9", "-x", "10", "-x",
"11"));
assertEquals("Attempt to set flag -x too many times.", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "7", "-x", "8", "--xx", "9", "-x", "10"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "7", "-x", "8", "--xx=9", "-x", "10"));
assertEquals("", mFlags.getParseMessage());
assertNotNull(mFlags.getValues("xx"));
assertNotNull(mFlags.getReceivedValues());
assertTrue(mFlags.isSet("xx"));
assertFalse(mFlags.isSet("yy"));
assertFalse(mFlags.setFlags("-x", "7", "-x", "8", "--xx", "9", "-x", "10", "-x",
"11"));
assertEquals("Attempt to set flag -x too many times.", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("-x", "7", "-x", "8", "--xx", "9", "-x", "10", "-x",
"11", "-h", "--helx"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("-x", "7", "-x", "8", "--xx", "9", "-x", "10", "-x",
"11", "-o", "--help"));
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
}
public void testParseInt() {
final Flag f = new AnonymousFlag("mv", Integer.class, "kk");
mFlags.register(f);
assertTrue(mFlags.setFlags("09"));
assertEquals(9, mFlags.getAnonymousValue(0));
}
public void testMultiValueAnon() {
final Flag f = new AnonymousFlag("mv", Integer.class, "kk");
f.setMaxCount(4);
f.setMinCount(3);
mFlags.register(f);
assertFalse(mFlags.setFlags("7"));
assertEquals("You must provide a value for KK+ (2 more times)", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("7", "8"));
assertEquals("You must provide a value for KK+ (1 more time)", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("7", "8", "9"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("7", "8", "9", "10"));
assertEquals("", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("7", "8", "9", "10", "11"));
assertEquals("Unexpected argument \"11\"", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("7", "8", "9", "10", "-h"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("7", "8", "9", "10", "--help"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
assertFalse(mFlags.setFlags("7", "8", "9", "10", "11", "--help"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.isSet(CFlags.HELP_FLAG));
mFlags.setInvalidFlagHandler(new InvalidFlagHandler() {
@Override
public void handleInvalidFlags(final CFlags ff) {
throw new ArithmeticException();
}
});
try {
mFlags.setFlags("7", "8", "9", "10", "11");
fail();
} catch (final ArithmeticException e) {
// ok
}
assertTrue(mFlags.setFlags("7", "8", "9", "10"));
assertNotNull(mFlags.getAnonymousFlags());
}
public void testRequired2() {
Flag f = mFlags.registerRequired("zz", File.class, "hix", "therex");
assertNotNull(f);
f = mFlags.registerRequired('j', "zzz", File.class, "hiz", "therez");
assertNotNull(f);
assertFalse(mFlags.setFlags());
assertEquals("You must provide values for --zz HIX -j HIZ", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--zz", "h"));
assertEquals("You must provide a value for -j HIZ", mFlags.getParseMessage());
// assertFalse(mFlags.setFlags("--zz", "h", "-j", "test\nthis"));
// assertEquals("Invalid value \"test\nthis\" for \"-j\". Value cannot contain new line characters.", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--zz", "h", "t"));
assertEquals("Unexpected argument \"t\"", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--zz", "h", "t", "k"));
assertEquals("Unexpected arguments \"t\" \"k\"", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--uu", "--zz", "h"));
assertEquals("Unknown flag --uu", mFlags.getParseMessage());
assertFalse(mFlags.setFlags("--zz", "h"));
assertEquals("You must provide a value for -j HIZ", mFlags.getParseMessage());
try {
mFlags.setFlags("--zz", null);
fail();
} catch (final NullPointerException e) {
// ok
}
}
public void testRange() {
final Flag f = new Flag('x', "xx", "mv", 1, 1, String.class, "kk", null, "");
final HashSet<String> m = new HashSet<>();
try {
f.setParameterRange(m);
fail();
} catch (final IllegalArgumentException e) {
// ok
}
m.add("value");
f.setParameterRange(m);
m.add("pox");
f.setParameterRange(m);
mFlags.register(f);
assertFalse(mFlags.setFlags("--xx", "v"));
assertEquals("Invalid value \"v\" for flag --xx. Value supplied is not in the set of allowed values.",
mFlags.getParseMessage());
assertTrue(mFlags.setFlags("--xx", "value"));
assertEquals("", mFlags.getParseMessage());
assertTrue(mFlags.setFlags("-x", "pox"));
assertEquals("", mFlags.getParseMessage());
}
public void testNumericRangeChecks() {
mFlags.registerOptional("a", Integer.class, "int", "therex");
mFlags.registerOptional("b", Double.class, "float", "therex");
mFlags.setFlags("--a", "2", "--b", "2");
assertTrue(mFlags.checkInRange("a", 2, true, 4, true));
assertFalse(mFlags.checkInRange("a", 2, false, 4, true));
assertTrue(mFlags.getParseMessage().contains("(2, 4]"));
assertFalse(mFlags.checkInRange("a", 3, true, 4, true));
assertTrue(mFlags.getParseMessage().contains("[3, 4]"));
assertTrue(mFlags.checkInRange("a", 0, true, 2, true));
assertFalse(mFlags.checkInRange("a", 0, true, 2, false));
assertTrue(mFlags.getParseMessage().contains("[0, 2)"));
assertFalse(mFlags.checkInRange("a", 0, true, 1, true));
assertTrue(mFlags.getParseMessage().contains("[0, 1]"));
assertFalse(mFlags.checkInRange("a", 3, true, Integer.MAX_VALUE, true));
assertTrue(mFlags.getParseMessage().contains("at least 3"));
assertFalse(mFlags.checkInRange("a", Integer.MIN_VALUE, true, 2, false));
assertTrue(mFlags.getParseMessage().contains("less than 2"));
assertTrue(mFlags.checkInRange("b", 2.0, true, 4.0, true));
assertFalse(mFlags.checkInRange("b", 2.0, false, 4.0, true));
assertTrue(mFlags.getParseMessage().contains("(2.0, 4.0]"));
assertFalse(mFlags.checkInRange("b", 3.0, true, 4.0, true));
assertTrue(mFlags.getParseMessage().contains("[3.0, 4.0]"));
assertTrue(mFlags.checkInRange("b", 0.0, true, 2.0, true));
assertFalse(mFlags.checkInRange("b", 0.0, true, 2.0, false));
assertTrue(mFlags.getParseMessage().contains("[0.0, 2.0)"));
assertFalse(mFlags.checkInRange("b", 0.0, true, 1.0, true));
assertTrue(mFlags.getParseMessage().contains("[0.0, 1.0]"));
assertFalse(mFlags.checkInRange("b", 3.0, true, Double.MAX_VALUE, true));
assertTrue(mFlags.getParseMessage().contains("at least 3.0"));
assertFalse(mFlags.checkInRange("b", -Double.MAX_VALUE, true, 2.0, false));
assertTrue(mFlags.getParseMessage().contains("less than 2.0"));
}
public void testCrossFlagChecks() {
mFlags.registerOptional("a", "therex");
mFlags.registerOptional("b", "therex");
mFlags.registerOptional("c", "therex");
mFlags.registerOptional("d", "therex");
mFlags.setFlags("--a", "--b");
assertTrue(mFlags.isSet("a"));
assertTrue(mFlags.isSet("b"));
// True if any one is set
assertTrue(mFlags.checkOr("a", "b"));
assertTrue(mFlags.checkOr("b", "c", "d"));
assertFalse(mFlags.checkOr("c", "d"));
// True if at most one is set
assertTrue(mFlags.checkNand("a", "d"));
assertTrue(mFlags.checkNand("c", "d"));
assertFalse(mFlags.checkNand("a", "b"));
assertTrue(mFlags.checkAtMostOne("a", "d"));
assertTrue(mFlags.checkAtMostOne("c", "d"));
assertFalse(mFlags.checkAtMostOne("a", "b"));
assertFalse(mFlags.checkAtMostOne("a", "b", "c", "d"));
// True if all are set
assertTrue(mFlags.checkRequired("a", "b"));
assertFalse(mFlags.checkRequired("a", "d"));
// True if exactly one is set
assertTrue(mFlags.checkXor("b", "c", "d"));
assertFalse(mFlags.checkXor("a", "b"));
assertFalse(mFlags.checkXor("c", "d"));
// True if neither or both are
assertTrue(mFlags.checkIff("a", "b"));
assertTrue(mFlags.checkIff("c", "d"));
assertFalse(mFlags.checkIff("a", "c"));
}
public void testSpecialAnonProps() {
final AnonymousFlag f1 = new AnonymousFlag("mv", Integer.class, "kk");
final AnonymousFlag f2 = new AnonymousFlag("mx", Integer.class, "zz");
assertEquals(1, f2.compareTo(f1));
assertEquals(-1, f1.compareTo(f2));
assertEquals(0, f1.compareTo(f1));
}
public void testFlagInnerClass() {
Flag f = new Flag('x', "xx", "mv", 0, 1, Integer.class, "kk", 42, "");
try {
f.setMaxCount(0);
fail();
} catch (final IllegalArgumentException e) {
// ok
}
f.setMaxCount(2);
f.setMinCount(2);
try {
f.setMaxCount(1);
fail();
} catch (final IllegalArgumentException e) {
// ok
}
Collection<Object> c = f.getValues();
assertTrue(c.contains(42));
f = new Flag('x', "xx", "mv", 3, 4, null, "kk", 42, "");
c = f.getValues();
assertTrue(c.contains(Boolean.FALSE));
final Flag f1 = new Flag('x', "xx", "mv", 3, 4, Integer.class, "kk", 42, "");
final Flag f2 = new Flag('y', "xy", "my", 3, 4, Integer.class, "ky", 42, "");
assertEquals(1, f2.compareTo(f1));
assertEquals(-1, f1.compareTo(f2));
assertEquals(0, f1.compareTo(f1));
f = new Flag('x', "xx", "mv", 0, Integer.MAX_VALUE, Integer.class, "kk", 42, "");
mFlags.register(f);
assertEquals(LS + "Optional flags: " + LS
+ " -h, --help print help on command-line flag usage" + LS
+ " -x, --xx=KK mv. May be specified 0 or more times (Default is 42)" + LS, mFlags
.getUsageString());
mFlags.setFlags("-x", "22");
final List<FlagValue> i = mFlags.getReceivedValues();
assertEquals(1, i.size());
final FlagValue fv = i.get(0);
assertNotNull(fv);
assertEquals(f, fv.getFlag());
assertEquals(22, fv.getValue());
assertEquals("xx=22", fv.toString());
}
static final class TestMyEnum implements PseudoEnum {
public static final TestMyEnum ONE = new TestMyEnum(0, "ONE");
public static final TestMyEnum TWO = new TestMyEnum(1, "TWO");
public static final TestMyEnum THREE = new TestMyEnum(2, "THREE");
private final int mOrdinal;
private final String mName;
private TestMyEnum(final int ordinal, final String name) {
mOrdinal = ordinal;
mName = name;
}
@Override
public String name() {
return mName;
}
@Override
public int ordinal() {
return mOrdinal;
}
@Override
public String toString() {
return mName;
}
private static final EnumHelper<TestMyEnum> ENUM_HELPER = new EnumHelper<>(TestMyEnum.class, new TestMyEnum[] {ONE, TWO, THREE});
public static TestMyEnum[] values() {
return ENUM_HELPER.values();
}
public static TestMyEnum valueOf(final String str) {
return ENUM_HELPER.valueOf(str);
}
}
public void testEnum() {
mFlags.registerRequired(TestMyEnum.class, "enum", "ENUM VALUE");
assertTrue(mFlags.setFlags("one"));
assertEquals(TestMyEnum.ONE, mFlags.getAnonymousValue(0));
}
public void testEnumDescription() {
mFlags.registerRequired(TestMyEnum.class, "enum", "ENUM VALUE");
final String str = mFlags.getUsageString();
assertTrue(str, str.toLowerCase(Locale.getDefault()).contains("allowed values are [one, two, three]"));
}
public void testEnum2() {
mFlags.registerRequired(TestMyEnum.class, "enum", "enum value");
assertFalse(mFlags.setFlags("nonvalue"));
}
public void testTypeChecking() {
mFlags.registerRequired(Integer.class, "int", "");
assertFalse(mFlags.setFlags("abc123"));
}
public void testInvalidFlagHandler() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final PrintStream out = new PrintStream(bos);
final ByteArrayOutputStream berr = new ByteArrayOutputStream();
final PrintStream err = new PrintStream(berr);
final CFlags f = new CFlags("", out, err);
f.setFlags("-h");
err.flush();
out.flush();
assertEquals("Usage: [OPTION]..." + LS + LS + "Optional flags: " + LS + " -h, --help print help on command-line flag usage" + LS + LS + "", bos.toString());
assertEquals("", berr.toString());
bos.reset();
f.setFlags("--no-such-flag");
err.flush();
assertEquals("Error: Unknown flag --no-such-flag" + LS + LS + "Usage: [OPTION]..." + LS + LS + "Try \'--help\' for more information" + LS, berr.toString());
assertEquals("", bos.toString());
}
public void testXHelp() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final PrintStream err = new PrintStream(bos);
final CFlags f = new CFlags("", err, null);
f.registerExtendedHelp();
f.registerOptional("Xoptional", "Test of --X options");
f.setFlags("-h");
err.flush();
assertEquals("Usage: [OPTION]..." + LS + LS + "Optional flags: " + LS
+ " -h, --help print help on command-line flag usage" + LS
+ LS + "", bos.toString());
bos.reset();
f.setFlags("--Xhelp");
err.flush();
TestUtils.containsAllUnwrapped(bos.toString(),
"Usage: [OPTION]...",
"Use them with caution",
"Optional flags: ",
" --Xhelp print help on extended command-line flag usage",
" --Xoptional Test of --X options");
}
public void testUnregister() {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final PrintStream err = new PrintStream(bos);
final CFlags flags = new CFlags("", err, null);
flags.registerOptional('a', "A", "a");
Flag f = flags.unregister("A");
assertNotNull(f);
f = flags.unregister("B");
assertNull(f);
}
public void testXor() {
mFlags.registerRequired(TestMyEnum.class, "enum", "ENUM VALUE");
assertTrue(mFlags.setFlags("one"));
assertEquals(TestMyEnum.ONE, mFlags.getAnonymousValue(0));
}
}
| Fix missed test.
| test/com/rtg/util/cli/CFlagsTest.java | Fix missed test. |
|
Java | bsd-3-clause | 6c00bce368f983b13e243ac11323efcd739e1b41 | 0 | NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror,NUBIC/psc-mirror | package edu.northwestern.bioinformatics.studycalendar.dao.delta;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarMutableDomainObjectDao;
import edu.northwestern.bioinformatics.studycalendar.dao.DeletableDomainObjectDao;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Criterion;
import org.springframework.orm.hibernate3.HibernateCallback;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.ParseException;
/**
* @author Nataliya Shurupova
* @author Rhett Sutphin
*/
public class AmendmentDao extends StudyCalendarMutableDomainObjectDao<Amendment> implements DeletableDomainObjectDao<Amendment> {
@Override
public Class<Amendment> domainClass() {
return Amendment.class;
}
@SuppressWarnings({ "unchecked" })
public List<Amendment> getAll() {
return getHibernateTemplate().find("from Amendment");
}
@SuppressWarnings({ "unchecked" })
public Amendment getByNaturalKey(String key) {
final Amendment.Key keyParts = Amendment.decomposeNaturalKey(key);
List<Amendment> results = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
//need to have both "like" or "eq" criterias to work on Oracle and Postgres dbs.
Criteria crit = session.createCriteria(Amendment.class)
.add(Restrictions.disjunction()
.add(Restrictions.like("date", keyParts.getDate()))
.add(Restrictions.eq("date", keyParts.getDate()))
);
if (keyParts.getName() != null) crit.add( Restrictions.eq("name", keyParts.getName()) );
crit.addOrder(Order.asc("name"));
return crit.list();
}
});
if (results.size() == 0) {
return null;
} else if (results.size() > 1) {
// if there's one with this date and no name, it matches
for (Amendment result : results) if (result.getName() == null) return result;
List<String> resultKeys = new ArrayList<String>(results.size());
for (Amendment result : results) resultKeys.add(result.getNaturalKey());
throw new StudyCalendarValidationException(
"More than one amendment could match %s: %s. Please be more specific.",
key, StringUtils.join(resultKeys.iterator(), ", "));
} else {
return results.get(0);
}
}
public void delete(Amendment amendment) {
getHibernateTemplate().delete(amendment);
}
}
| src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/delta/AmendmentDao.java | package edu.northwestern.bioinformatics.studycalendar.dao.delta;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarMutableDomainObjectDao;
import edu.northwestern.bioinformatics.studycalendar.dao.DeletableDomainObjectDao;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Criterion;
import org.springframework.orm.hibernate3.HibernateCallback;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.ParseException;
/**
* @author Nataliya Shurupova
* @author Rhett Sutphin
*/
public class AmendmentDao extends StudyCalendarMutableDomainObjectDao<Amendment> implements DeletableDomainObjectDao<Amendment> {
@Override
public Class<Amendment> domainClass() {
return Amendment.class;
}
@SuppressWarnings({ "unchecked" })
public List<Amendment> getAll() {
return getHibernateTemplate().find("from Amendment");
}
@SuppressWarnings({ "unchecked" })
public Amendment getByNaturalKey(String key) {
final Amendment.Key keyParts = Amendment.decomposeNaturalKey(key);
List<Amendment> results = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria crit = session.createCriteria(Amendment.class)
.add(Restrictions.disjunction()
.add(Restrictions.like("date", keyParts.getDate()))
.add(Restrictions.eq("date", keyParts.getDate()))
);
if (keyParts.getName() != null) crit.add( Restrictions.eq("name", keyParts.getName()) );
crit.addOrder(Order.asc("name"));
return crit.list();
}
});
if (results.size() == 0) {
return null;
} else if (results.size() > 1) {
// if there's one with this date and no name, it matches
for (Amendment result : results) if (result.getName() == null) return result;
List<String> resultKeys = new ArrayList<String>(results.size());
for (Amendment result : results) resultKeys.add(result.getNaturalKey());
throw new StudyCalendarValidationException(
"More than one amendment could match %s: %s. Please be more specific.",
key, StringUtils.join(resultKeys.iterator(), ", "));
} else {
return results.get(0);
}
}
public void delete(Amendment amendment) {
getHibernateTemplate().delete(amendment);
}
}
| Fix for the bug #388 - Added a message to explain the search criterias for "like" or "eq"
git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@2566 0d517254-b314-0410-acde-c619094fa49f
| src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/delta/AmendmentDao.java | Fix for the bug #388 - Added a message to explain the search criterias for "like" or "eq" |
|
Java | mit | 8e6765cfcea83682ebe4b1b4aa57fdb2cdf63853 | 0 | TejasBhitle/Matrix2017 | /*
* *
* * This file is part of Matrix2017
* * Created for the annual technical festival of Sardar Patel Institute of Technology
* *
* * The original contributors of the software include:
* * - Adnan Ansari (psyclone20)
* * - Tejas Bhitle (TejasBhitle)
* * - Mithil Gotarne (mithilgotarne)
* * - Rohit Nahata (rohitnahata)
* * - Akshay Shah (akshah1997)
* *
* * Matrix2017 is free software: you can redistribute it and/or modify
* * it under the terms of the MIT License as published by the Massachusetts Institute of Technology
*/
package spit.matrix2017.Activities;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.design.internal.NavigationMenuView;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.squareup.picasso.Picasso;
import me.relex.circleindicator.CircleIndicator;
import spit.matrix2017.Fragments.AboutAppFragment;
import spit.matrix2017.Fragments.CommitteeFragment;
import spit.matrix2017.Fragments.ContactUsFragment;
import spit.matrix2017.Fragments.DevelopersFragment;
import spit.matrix2017.Fragments.FavoritesFragment;
import spit.matrix2017.Fragments.MainFragment;
import spit.matrix2017.Fragments.SponsorsFragment;
import spit.matrix2017.HelperClasses.CustomPagerAdapter;
import spit.matrix2017.HelperClasses.CustomViewPager;
import spit.matrix2017.R;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private AppBarLayout appBarLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
CollapsingToolbarLayout collapsingToolbarLayout;
FragmentManager fm;
String backStageName;
CustomPagerAdapter mCustomPagerAdapter;
CustomViewPager mViewPager;
private static final long DRAWER_DELAY = 250;
private static int NUM_PAGES = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT >= 21)
setContentView(R.layout.activity_main_v21);
else
setContentView(R.layout.activity_main);
int[] images = {
R.drawable.event_daniel_fernandes,
R.drawable.event_techshiksha,
R.drawable.event_ethical_hacking,
R.drawable.event_startup_showcase,
R.drawable.event_hackathon,
R.drawable.event_project_mania,
R.drawable.event_sky_observation,
R.drawable.event_vsm,
R.drawable.event_codatron,
R.drawable.event_laser_maze,
R.drawable.event_laser_tag,
R.drawable.event_tech_charades,
R.drawable.event_battle_frontier,
R.drawable.event_escape_plan,
R.drawable.event_tech_xplosion,
R.drawable.event_no_escape,
R.drawable.event_techeshis_castle,
R.drawable.event_tesseract,
R.drawable.event_human_foosball,
R.drawable.event_battle_of_brains,
R.drawable.event_lan_gaming,
R.drawable.event_pokemon_showdown,
R.drawable.event_lan_mafia,
R.drawable.event_mind_that_word,
};
for(int i: images)
Picasso.with(getApplicationContext()).load(i).resize(400, 400).centerCrop().fetch();
//ViewPager
mCustomPagerAdapter = new CustomPagerAdapter(this);
mViewPager = (CustomViewPager) findViewById(R.id.viewpager_main);
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
mViewPager.setAdapter(mCustomPagerAdapter);
indicator.setViewPager(mViewPager);
final Handler h = new Handler(Looper.getMainLooper());
final Runnable r = new Runnable() {
public void run() {
mViewPager.setCurrentItem((mViewPager.getCurrentItem()+1)%NUM_PAGES, true);
h.postDelayed(this, 5000);
}
};
h.postDelayed(r, 5000);
//instantiation
toolbar = (Toolbar)findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
navigationView =(NavigationView)findViewById(R.id.navigation_view);
drawerLayout =(DrawerLayout)findViewById(R.id.drawer_layout);
collapsingToolbarLayout= (CollapsingToolbarLayout)findViewById(R.id.collapsingToolbar_main);
collapsingToolbarLayout.setExpandedTitleColor(Color.WHITE);
appBarLayout = (AppBarLayout)findViewById(R.id.app_bar_layout);
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
AppBarLayout.Behavior appBarLayoutBehaviour = new AppBarLayout.Behavior();
appBarLayoutBehaviour.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
@Override
public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
return false;
}
});
layoutParams.setBehavior(appBarLayoutBehaviour);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
if(savedInstanceState == null){
fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
MainFragment mainFragment = MainFragment.newInstance();
transaction.replace(R.id.fragment_container,mainFragment).commit();
}
setupDrawerLayout();
NavigationMenuView navigationMenuView = (NavigationMenuView) navigationView.getChildAt(0);
if (navigationMenuView != null) {
navigationMenuView.setVerticalScrollBarEnabled(false);
}
navigationView.getMenu().getItem(0).setChecked(true);
}
public void setupDrawerLayout(){
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
if(!item.isChecked()) {
final FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
switch (item.getItemId()) {
case R.id.homepage_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
boolean isFragmentInStack = fm.popBackStackImmediate(backStageName, 0);
if (!isFragmentInStack) {
MainFragment fragment = MainFragment.newInstance();
fragmentTransaction.replace(R.id.fragment_container, fragment);
backStageName = fragment.getClass().getName();
fragmentTransaction.addToBackStack(backStageName).commit();
}
appBarLayout.setExpanded(true, true);
collapsingToolbarLayout.setTitle("Matrix 17");
}
}, DRAWER_DELAY);
break;
case R.id.favorites_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new FavoritesFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null).commit();
collapsingToolbarLayout.setTitle("Favorites");
}
}, DRAWER_DELAY);
break;
case R.id.sponsors_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new SponsorsFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle("Sponsors");
}
}, DRAWER_DELAY);
break;
case R.id.commitee_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new CommitteeFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle("Committee");
}
}, DRAWER_DELAY);
break;
case R.id.developers_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new DevelopersFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle("Developers");
}
}, DRAWER_DELAY);
break;
case R.id.contact_us_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new ContactUsFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle("Contact us");
}
}, DRAWER_DELAY);
break;
case R.id.share_app_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Check out the official app for Matrix 17!\n\n" + getResources().getString(R.string.playstore_link));
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, getResources().getString(R.string.share_message)));
}
}, DRAWER_DELAY);
return true;
case R.id.rate_app_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setData(Uri.parse(getResources().getString(R.string.playstore_link)));
startActivity(intent);
}
}, DRAWER_DELAY);
return true;
case R.id.about_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new AboutAppFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle(getResources().getString(R.string.aboutapp));
}
}, DRAWER_DELAY);
}
}
return true;
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Uri uri=null;
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.follow_us:
return true;
case R.id.menu_visit_website:
uri = Uri.parse(getResources().getString(R.string.matrix_website));
break;
case R.id.menu_follow_facebook:
uri = Uri.parse(getResources().getString(R.string.matrix_fb_link));
break;
case R.id.menu_follow_twitter:
uri = Uri.parse(getResources().getString(R.string.matrix_twit_link));
break;
case R.id.menu_follow_instagram:
uri = Uri.parse(getResources().getString(R.string.matrix_insta_link));
break;
case R.id.menu_follow_snapchat:
uri = Uri.parse(getResources().getString(R.string.matrix_snap_link));
break;
}
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed()
{
if(drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawers();
else {
navigationView.getMenu().getItem(0).setChecked(true);
collapsingToolbarLayout.setTitle("Matrix 17");
appBarLayout.setExpanded(true, true);
super.onBackPressed();
}
}
} | app/src/main/java/spit/matrix2017/Activities/MainActivity.java | /*
* *
* * This file is part of Matrix2017
* * Created for the annual technical festival of Sardar Patel Institute of Technology
* *
* * The original contributors of the software include:
* * - Adnan Ansari (psyclone20)
* * - Tejas Bhitle (TejasBhitle)
* * - Mithil Gotarne (mithilgotarne)
* * - Rohit Nahata (rohitnahata)
* * - Akshay Shah (akshah1997)
* *
* * Matrix2017 is free software: you can redistribute it and/or modify
* * it under the terms of the MIT License as published by the Massachusetts Institute of Technology
*/
package spit.matrix2017.Activities;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.design.internal.NavigationMenuView;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.squareup.picasso.Picasso;
import me.relex.circleindicator.CircleIndicator;
import spit.matrix2017.Fragments.AboutAppFragment;
import spit.matrix2017.Fragments.CommitteeFragment;
import spit.matrix2017.Fragments.ContactUsFragment;
import spit.matrix2017.Fragments.DevelopersFragment;
import spit.matrix2017.Fragments.FavoritesFragment;
import spit.matrix2017.Fragments.MainFragment;
import spit.matrix2017.Fragments.SponsorsFragment;
import spit.matrix2017.HelperClasses.CustomPagerAdapter;
import spit.matrix2017.HelperClasses.CustomViewPager;
import spit.matrix2017.R;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private AppBarLayout appBarLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
CollapsingToolbarLayout collapsingToolbarLayout;
FragmentManager fm;
String backStageName;
CustomPagerAdapter mCustomPagerAdapter;
CustomViewPager mViewPager;
private static final long DRAWER_DELAY = 250;
private static int NUM_PAGES = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT >= 21)
setContentView(R.layout.activity_main_v21);
else
setContentView(R.layout.activity_main);
int[] images = {
R.drawable.event_vsm,
R.drawable.event_codatron,
R.drawable.event_laser_maze,
R.drawable.event_laser_tag,
R.drawable.event_tech_charades,
R.drawable.event_battle_frontier,
R.drawable.event_escape_plan,
R.drawable.event_tech_xplosion,
R.drawable.event_no_escape,
R.drawable.event_techeshis_castle,
R.drawable.event_tesseract,
R.drawable.event_human_foosball,
R.drawable.event_battle_of_brains,
R.drawable.event_lan_gaming,
R.drawable.event_pokemon_showdown,
R.drawable.event_lan_mafia,
R.drawable.event_mind_that_word
};
for(int i: images)
Picasso.with(getApplicationContext()).load(i).resize(400, 400).centerCrop().fetch();
//ViewPager
mCustomPagerAdapter = new CustomPagerAdapter(this);
mViewPager = (CustomViewPager) findViewById(R.id.viewpager_main);
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
mViewPager.setAdapter(mCustomPagerAdapter);
indicator.setViewPager(mViewPager);
final Handler h = new Handler(Looper.getMainLooper());
final Runnable r = new Runnable() {
public void run() {
mViewPager.setCurrentItem((mViewPager.getCurrentItem()+1)%NUM_PAGES, true);
h.postDelayed(this, 5000);
}
};
h.postDelayed(r, 5000);
//instantiation
toolbar = (Toolbar)findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
navigationView =(NavigationView)findViewById(R.id.navigation_view);
drawerLayout =(DrawerLayout)findViewById(R.id.drawer_layout);
collapsingToolbarLayout= (CollapsingToolbarLayout)findViewById(R.id.collapsingToolbar_main);
collapsingToolbarLayout.setExpandedTitleColor(Color.WHITE);
appBarLayout = (AppBarLayout)findViewById(R.id.app_bar_layout);
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
AppBarLayout.Behavior appBarLayoutBehaviour = new AppBarLayout.Behavior();
appBarLayoutBehaviour.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
@Override
public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
return false;
}
});
layoutParams.setBehavior(appBarLayoutBehaviour);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
collapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE);
if(savedInstanceState == null){
fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
MainFragment mainFragment = MainFragment.newInstance();
transaction.replace(R.id.fragment_container,mainFragment).commit();
}
setupDrawerLayout();
NavigationMenuView navigationMenuView = (NavigationMenuView) navigationView.getChildAt(0);
if (navigationMenuView != null) {
navigationMenuView.setVerticalScrollBarEnabled(false);
}
navigationView.getMenu().getItem(0).setChecked(true);
}
public void setupDrawerLayout(){
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
if(!item.isChecked()) {
final FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
switch (item.getItemId()) {
case R.id.homepage_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
boolean isFragmentInStack = fm.popBackStackImmediate(backStageName, 0);
if (!isFragmentInStack) {
MainFragment fragment = MainFragment.newInstance();
fragmentTransaction.replace(R.id.fragment_container, fragment);
backStageName = fragment.getClass().getName();
fragmentTransaction.addToBackStack(backStageName).commit();
}
appBarLayout.setExpanded(true, true);
collapsingToolbarLayout.setTitle("Matrix 17");
}
}, DRAWER_DELAY);
break;
case R.id.favorites_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new FavoritesFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null).commit();
collapsingToolbarLayout.setTitle("Favorites");
}
}, DRAWER_DELAY);
break;
case R.id.sponsors_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new SponsorsFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle("Sponsors");
}
}, DRAWER_DELAY);
break;
case R.id.commitee_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new CommitteeFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle("Committee");
}
}, DRAWER_DELAY);
break;
case R.id.developers_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new DevelopersFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle("Developers");
}
}, DRAWER_DELAY);
break;
case R.id.contact_us_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new ContactUsFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle("Contact us");
}
}, DRAWER_DELAY);
break;
case R.id.share_app_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Check out the official app for Matrix 17!\n\n" + getResources().getString(R.string.playstore_link));
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, getResources().getString(R.string.share_message)));
}
}, DRAWER_DELAY);
return true;
case R.id.rate_app_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setData(Uri.parse(getResources().getString(R.string.playstore_link)));
startActivity(intent);
}
}, DRAWER_DELAY);
return true;
case R.id.about_menuItem:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStackImmediate();
fragmentTransaction.replace(R.id.fragment_container, new AboutAppFragment());
appBarLayout.setExpanded(false, true);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
collapsingToolbarLayout.setTitle(getResources().getString(R.string.aboutapp));
}
}, DRAWER_DELAY);
}
}
return true;
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Uri uri=null;
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.follow_us:
return true;
case R.id.menu_visit_website:
uri = Uri.parse(getResources().getString(R.string.matrix_website));
break;
case R.id.menu_follow_facebook:
uri = Uri.parse(getResources().getString(R.string.matrix_fb_link));
break;
case R.id.menu_follow_twitter:
uri = Uri.parse(getResources().getString(R.string.matrix_twit_link));
break;
case R.id.menu_follow_instagram:
uri = Uri.parse(getResources().getString(R.string.matrix_insta_link));
break;
case R.id.menu_follow_snapchat:
uri = Uri.parse(getResources().getString(R.string.matrix_snap_link));
break;
}
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed()
{
if(drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawers();
else {
navigationView.getMenu().getItem(0).setChecked(true);
collapsingToolbarLayout.setTitle("Matrix 17");
appBarLayout.setExpanded(true, true);
super.onBackPressed();
}
}
} | Added Images in main activity
| app/src/main/java/spit/matrix2017/Activities/MainActivity.java | Added Images in main activity |
|
Java | mit | 03b66f956dc2bd1156b169a22b53521a9a7874d0 | 0 | react-community/react-native-image-picker,rayshih/react-native-image-picker,rayshih/react-native-image-picker,marcshilling/react-native-image-picker,rayshih/react-native-image-picker,marcshilling/react-native-image-picker,marcshilling/react-native-image-picker,react-community/react-native-image-picker,react-community/react-native-image-picker,marcshilling/react-native-image-picker,rayshih/react-native-image-picker,react-community/react-native-image-picker | package com.imagepicker;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Base64;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.webkit.MimeTypeMap;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.WritableMap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
interface ActivityResultInterface {
void callback(int requestCode, int resultCode, Intent data);
}
public class ImagePickerModule extends ReactContextBaseJavaModule {
static final int REQUEST_LAUNCH_IMAGE_CAPTURE = 13001;
static final int REQUEST_LAUNCH_IMAGE_LIBRARY = 13002;
static final int REQUEST_LAUNCH_VIDEO_LIBRARY = 13003;
static final int REQUEST_LAUNCH_VIDEO_CAPTURE = 13004;
private final ReactApplicationContext mReactContext;
private ImagePickerActivityEventListener mActivityEventListener;
private Uri mCameraCaptureURI;
private Callback mCallback;
private Boolean noData = false;
private Boolean tmpImage;
private Boolean pickVideo = false;
private int maxWidth = 0;
private int maxHeight = 0;
private int quality = 100;
private int rotation = 0;
private int videoQuality = 1;
private int videoDurationLimit = 0;
WritableMap response;
public ImagePickerModule(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
mActivityEventListener = new ImagePickerActivityEventListener(reactContext, new ActivityResultInterface() {
@Override
public void callback(int requestCode, int resultCode, Intent data) {
onActivityResult(requestCode, resultCode, data);
}
});
}
@Override
public String getName() {
return "ImagePickerManager";
}
@ReactMethod
public void showImagePicker(final ReadableMap options, final Callback callback) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
response = Arguments.createMap();
response.putString("error", "can't find current Activity");
callback.invoke(response);
return;
}
final List<String> titles = new ArrayList<String>();
final List<String> actions = new ArrayList<String>();
if (options.hasKey("takePhotoButtonTitle")
&& options.getString("takePhotoButtonTitle") != null
&& !options.getString("takePhotoButtonTitle").isEmpty()
&& isCameraAvailable()) {
titles.add(options.getString("takePhotoButtonTitle"));
actions.add("photo");
}
if (options.hasKey("chooseFromLibraryButtonTitle")
&& options.getString("chooseFromLibraryButtonTitle") != null
&& !options.getString("chooseFromLibraryButtonTitle").isEmpty()) {
titles.add(options.getString("chooseFromLibraryButtonTitle"));
actions.add("library");
}
if (options.hasKey("customButtons")) {
ReadableArray customButtons = options.getArray("customButtons");
for (int i = 0; i < customButtons.size(); i++) {
ReadableMap button = customButtons.getMap(i);
int currentIndex = titles.size();
titles.add(currentIndex, button.getString("title"));
actions.add(currentIndex, button.getString("name"));
}
}
if (options.hasKey("cancelButtonTitle")
&& options.getString("cancelButtonTitle") != null
&& !options.getString("cancelButtonTitle").isEmpty()) {
titles.add(options.getString("cancelButtonTitle"));
actions.add("cancel");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(currentActivity, android.R.layout.select_dialog_item, titles);
AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity, android.R.style.Theme_Holo_Light_Dialog);
if (options.hasKey("title") && options.getString("title") != null && !options.getString("title").isEmpty()) {
builder.setTitle(options.getString("title"));
}
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int index) {
String action = actions.get(index);
response = Arguments.createMap();
switch (action) {
case "photo":
launchCamera(options, callback);
break;
case "library":
launchImageLibrary(options, callback);
break;
case "cancel":
response.putBoolean("didCancel", true);
callback.invoke(response);
break;
default: // custom button
response.putString("customButton", action);
callback.invoke(response);
}
}
});
final AlertDialog dialog = builder.create();
/**
* override onCancel method to callback cancel in case of a touch outside of
* the dialog or the BACK key pressed
*/
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
response = Arguments.createMap();
dialog.dismiss();
response.putBoolean("didCancel", true);
callback.invoke(response);
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
// NOTE: Currently not reentrant / doesn't support concurrent requests
@ReactMethod
public void launchCamera(final ReadableMap options, final Callback callback) {
response = Arguments.createMap();
if (!isCameraAvailable()) {
response.putString("error", "Camera not available");
callback.invoke(response);
return;
}
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
response.putString("error", "can't find current Activity");
callback.invoke(response);
return;
}
if (!permissionsCheck(currentActivity)) {
return;
}
parseOptions(options);
int requestCode;
Intent cameraIntent;
if (pickVideo) {
requestCode = REQUEST_LAUNCH_VIDEO_CAPTURE;
cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, videoQuality);
if (videoDurationLimit > 0) {
cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, videoDurationLimit);
}
} else {
requestCode = REQUEST_LAUNCH_IMAGE_CAPTURE;
cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// we create a tmp file to save the result
File imageFile = createNewFile();
mCameraCaptureURI = Uri.fromFile(imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraCaptureURI);
}
if (cameraIntent.resolveActivity(mReactContext.getPackageManager()) == null) {
response.putString("error", "Cannot launch camera");
callback.invoke(response);
return;
}
mCallback = callback;
try {
currentActivity.startActivityForResult(cameraIntent, requestCode);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
response = Arguments.createMap();
response.putString("error", "Cannot launch camera");
callback.invoke(response);
}
}
// NOTE: Currently not reentrant / doesn't support concurrent requests
@ReactMethod
public void launchImageLibrary(final ReadableMap options, final Callback callback) {
response = Arguments.createMap();
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
response.putString("error", "can't find current Activity");
callback.invoke(response);
return;
}
if (!permissionsCheck(currentActivity)) {
return;
}
parseOptions(options);
int requestCode;
Intent libraryIntent;
if (pickVideo) {
requestCode = REQUEST_LAUNCH_VIDEO_LIBRARY;
libraryIntent = new Intent(Intent.ACTION_PICK);
libraryIntent.setType("video/*");
} else {
requestCode = REQUEST_LAUNCH_IMAGE_LIBRARY;
libraryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
if (libraryIntent.resolveActivity(mReactContext.getPackageManager()) == null) {
response.putString("error", "Cannot launch photo library");
callback.invoke(response);
return;
}
mCallback = callback;
try {
currentActivity.startActivityForResult(libraryIntent, requestCode);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
response.putString("error", "Cannot launch photo library");
callback.invoke(response);
}
}
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
//robustness code
if (mCallback == null || (mCameraCaptureURI == null && requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE)
|| (requestCode != REQUEST_LAUNCH_IMAGE_CAPTURE && requestCode != REQUEST_LAUNCH_IMAGE_LIBRARY
&& requestCode != REQUEST_LAUNCH_VIDEO_LIBRARY && requestCode != REQUEST_LAUNCH_VIDEO_CAPTURE)) {
return;
}
response = Arguments.createMap();
// user cancel
if (resultCode != Activity.RESULT_OK) {
response.putBoolean("didCancel", true);
mCallback.invoke(response);
mCallback = null;
return;
}
Uri uri;
switch (requestCode) {
case REQUEST_LAUNCH_IMAGE_CAPTURE:
uri = mCameraCaptureURI;
this.fileScan(uri.getPath());
break;
case REQUEST_LAUNCH_IMAGE_LIBRARY:
uri = data.getData();
break;
case REQUEST_LAUNCH_VIDEO_LIBRARY:
response.putString("uri", data.getData().toString());
response.putString("path", getRealPathFromURI(data.getData()));
mCallback.invoke(response);
mCallback = null;
return;
case REQUEST_LAUNCH_VIDEO_CAPTURE:
response.putString("uri", data.getData().toString());
response.putString("path", getRealPathFromURI(data.getData()));
this.fileScan(response.getString("path"));
mCallback.invoke(response);
mCallback = null;
return;
default:
uri = null;
}
String realPath = getRealPathFromURI(uri);
boolean isUrl = false;
if (realPath != null) {
try {
URL url = new URL(realPath);
isUrl = true;
} catch (MalformedURLException e) {
// not a url
}
}
// image isn't in memory cache
if (realPath == null || isUrl) {
try {
File file = createFileFromURI(uri);
realPath = file.getAbsolutePath();
uri = Uri.fromFile(file);
} catch (Exception e) {
// image not in cache
response.putString("error", "Could not read photo");
response.putString("uri", uri.toString());
mCallback.invoke(response);
mCallback = null;
return;
}
}
int currentRotation = 0;
try {
ExifInterface exif = new ExifInterface(realPath);
// extract lat, long, and timestamp and add to the response
float[] latlng = new float[2];
exif.getLatLong(latlng);
float latitude = latlng[0];
float longitude = latlng[1];
if(latitude != 0f || longitude != 0f) {
response.putDouble("latitude", latitude);
response.putDouble("longitude", longitude);
}
String timestamp = exif.getAttribute(ExifInterface.TAG_DATETIME);
SimpleDateFormat exifDatetimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
String isoFormatString = isoFormat.format(exifDatetimeFormat.parse(timestamp)) + "Z";
response.putString("timestamp", isoFormatString);
} catch (Exception e) {}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
boolean isVertical = true;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
isVertical = false;
currentRotation = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
isVertical = false;
currentRotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
currentRotation = 180;
break;
}
response.putInt("originalRotation", currentRotation);
response.putBoolean("isVertical", isVertical);
} catch (IOException e) {
e.printStackTrace();
response.putString("error", e.getMessage());
mCallback.invoke(response);
mCallback = null;
return;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(realPath, options);
int initialWidth = options.outWidth;
int initialHeight = options.outHeight;
// don't create a new file if contraint are respected
if (((initialWidth < maxWidth && maxWidth > 0) || maxWidth == 0) && ((initialHeight < maxHeight && maxHeight > 0) || maxHeight == 0) && quality == 100 && (rotation == 0 || currentRotation == rotation)) {
response.putInt("width", initialWidth);
response.putInt("height", initialHeight);
} else {
File resized = getResizedImage(realPath, initialWidth, initialHeight);
if (resized == null) {
response.putString("error", "Can't resize the image");
} else {
realPath = resized.getAbsolutePath();
uri = Uri.fromFile(resized);
BitmapFactory.decodeFile(realPath, options);
response.putInt("width", options.outWidth);
response.putInt("height", options.outHeight);
}
}
response.putString("uri", uri.toString());
response.putString("path", realPath);
if (!noData) {
response.putString("data", getBase64StringFromFile(realPath));
}
putExtraFileInfo(realPath, response);
mCallback.invoke(response);
mCallback = null;
}
/**
* Returns number of milliseconds since Jan. 1, 1970, midnight local time.
* Returns -1 if the date time information if not available.
* copied from ExifInterface.java
* @hide
*/
private static long parseTimestamp(String dateTimeString, String subSecs) {
if (dateTimeString == null) return -1;
SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.getDefault());
sFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
ParsePosition pos = new ParsePosition(0);
try {
// The exif field is in local time. Parsing it as if it is UTC will yield time
// since 1/1/1970 local time
Date datetime = sFormatter.parse(dateTimeString, pos);
if (datetime == null) return -1;
long msecs = datetime.getTime();
if (subSecs != null) {
try {
long sub = Long.valueOf(subSecs);
while (sub > 1000) {
sub /= 10;
}
msecs += sub;
} catch (NumberFormatException e) {
//expected
}
}
return msecs;
} catch (IllegalArgumentException ex) {
return -1;
}
}
private boolean permissionsCheck(Activity activity) {
int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int cameraPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (writePermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
ActivityCompat.requestPermissions(activity, PERMISSIONS, 1);
return false;
}
return true;
}
private boolean isCameraAvailable() {
return mReactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)
|| mReactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
private String getRealPathFromURI(Uri uri) {
String result;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = mReactContext.getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = uri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
/**
* Create a file from uri to allow image picking of image in disk cache
* (Exemple: facebook image, google image etc..)
*
* @doc =>
* https://github.com/nostra13/Android-Universal-Image-Loader#load--display-task-flow
*
* @param uri
* @return File
* @throws Exception
*/
private File createFileFromURI(Uri uri) throws Exception {
File file = new File(mReactContext.getExternalCacheDir(), "photo-" + uri.getLastPathSegment());
InputStream input = mReactContext.getContentResolver().openInputStream(uri);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
input.close();
}
return file;
}
private String getBase64StringFromFile(String absoluteFilePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(absoluteFilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
/**
* Create a resized image to fulfill the maxWidth/maxHeight, quality and rotation values
*
* @param realPath
* @param initialWidth
* @param initialHeight
* @return resized file
*/
private File getResizedImage(final String realPath, final int initialWidth, final int initialHeight) {
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap photo = BitmapFactory.decodeFile(realPath, options);
if (photo == null) {
return null;
}
Bitmap scaledphoto = null;
if (maxWidth == 0 || maxWidth > initialWidth) {
maxWidth = initialWidth;
}
if (maxHeight == 0 || maxWidth > initialHeight) {
maxHeight = initialHeight;
}
double widthRatio = (double) maxWidth / initialWidth;
double heightRatio = (double) maxHeight / initialHeight;
double ratio = (widthRatio < heightRatio)
? widthRatio
: heightRatio;
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
matrix.postScale((float) ratio, (float) ratio);
ExifInterface exif;
try {
exif = new ExifInterface(realPath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
} catch (IOException e) {
e.printStackTrace();
}
scaledphoto = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
scaledphoto.compress(Bitmap.CompressFormat.JPEG, quality, bytes);
File f = createNewFile();
FileOutputStream fo;
try {
fo = new FileOutputStream(f);
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// recycle to avoid java.lang.OutOfMemoryError
if (photo != null) {
scaledphoto.recycle();
photo.recycle();
scaledphoto = null;
photo = null;
}
return f;
}
/**
* Create a new file
*
* @return an empty file
*/
private File createNewFile() {
String filename = "image-" + UUID.randomUUID().toString() + ".jpg";
File path;
if (tmpImage) {
path = mReactContext.getExternalCacheDir();
} else {
path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
}
File f = new File(path, filename);
try {
path.mkdirs();
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return f;
}
private void putExtraFileInfo(final String path, WritableMap response) {
// size && filename
try {
File f = new File(path);
response.putDouble("fileSize", f.length());
response.putString("fileName", f.getName());
} catch (Exception e) {
e.printStackTrace();
}
// type
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
if (extension != null) {
response.putString("type", MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
}
}
private void parseOptions(final ReadableMap options) {
noData = false;
if (options.hasKey("noData")) {
noData = options.getBoolean("noData");
}
maxWidth = 0;
if (options.hasKey("maxWidth")) {
maxWidth = options.getInt("maxWidth");
}
maxHeight = 0;
if (options.hasKey("maxHeight")) {
maxHeight = options.getInt("maxHeight");
}
quality = 100;
if (options.hasKey("quality")) {
quality = (int) (options.getDouble("quality") * 100);
}
tmpImage = true;
if (options.hasKey("storageOptions")) {
tmpImage = false;
}
rotation = 0;
if (options.hasKey("rotation")) {
rotation = options.getInt("rotation");
}
pickVideo = false;
if (options.hasKey("mediaType") && options.getString("mediaType").equals("video")) {
pickVideo = true;
}
videoQuality = 1;
if (options.hasKey("videoQuality") && options.getString("videoQuality").equals("low")) {
videoQuality = 0;
}
videoDurationLimit = 0;
if (options.hasKey("durationLimit")) {
videoDurationLimit = options.getInt("durationLimit");
}
}
public void fileScan(String path){
MediaScannerConnection.scanFile(mReactContext,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
// Required for RN 0.30+ modules than implement ActivityEventListener
public void onNewIntent(Intent intent) { }
}
| android/src/main/java/com/imagepicker/ImagePickerModule.java | package com.imagepicker;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Base64;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.webkit.MimeTypeMap;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.WritableMap;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
interface ActivityResultInterface {
void callback(int requestCode, int resultCode, Intent data);
}
public class ImagePickerModule extends ReactContextBaseJavaModule {
static final int REQUEST_LAUNCH_IMAGE_CAPTURE = 13001;
static final int REQUEST_LAUNCH_IMAGE_LIBRARY = 13002;
static final int REQUEST_LAUNCH_VIDEO_LIBRARY = 13003;
static final int REQUEST_LAUNCH_VIDEO_CAPTURE = 13004;
private final ReactApplicationContext mReactContext;
private ImagePickerActivityEventListener mActivityEventListener;
private Uri mCameraCaptureURI;
private Callback mCallback;
private Boolean noData = false;
private Boolean tmpImage;
private Boolean pickVideo = false;
private int maxWidth = 0;
private int maxHeight = 0;
private int quality = 100;
private int rotation = 0;
private int videoQuality = 1;
private int videoDurationLimit = 0;
WritableMap response;
public ImagePickerModule(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
mActivityEventListener = new ImagePickerActivityEventListener(reactContext, new ActivityResultInterface() {
@Override
public void callback(int requestCode, int resultCode, Intent data) {
onActivityResult(requestCode, resultCode, data);
}
});
}
@Override
public String getName() {
return "ImagePickerManager";
}
@ReactMethod
public void showImagePicker(final ReadableMap options, final Callback callback) {
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
response = Arguments.createMap();
response.putString("error", "can't find current Activity");
callback.invoke(response);
return;
}
final List<String> titles = new ArrayList<String>();
final List<String> actions = new ArrayList<String>();
if (options.hasKey("takePhotoButtonTitle")
&& options.getString("takePhotoButtonTitle") != null
&& !options.getString("takePhotoButtonTitle").isEmpty()
&& isCameraAvailable()) {
titles.add(options.getString("takePhotoButtonTitle"));
actions.add("photo");
}
if (options.hasKey("chooseFromLibraryButtonTitle")
&& options.getString("chooseFromLibraryButtonTitle") != null
&& !options.getString("chooseFromLibraryButtonTitle").isEmpty()) {
titles.add(options.getString("chooseFromLibraryButtonTitle"));
actions.add("library");
}
if (options.hasKey("customButtons")) {
ReadableArray customButtons = options.getArray("customButtons");
for (int i = 0; i < customButtons.size(); i++) {
ReadableMap button = customButtons.getMap(i);
int currentIndex = titles.size();
titles.add(currentIndex, button.getString("title"));
actions.add(currentIndex, button.getString("name"));
}
}
if (options.hasKey("cancelButtonTitle")
&& options.getString("cancelButtonTitle") != null
&& !options.getString("cancelButtonTitle").isEmpty()) {
titles.add(options.getString("cancelButtonTitle"));
actions.add("cancel");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(currentActivity,
android.R.layout.select_dialog_item, titles);
AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
if (options.hasKey("title") && options.getString("title") != null && !options.getString("title").isEmpty()) {
builder.setTitle(options.getString("title"));
}
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int index) {
String action = actions.get(index);
response = Arguments.createMap();
switch (action) {
case "photo":
launchCamera(options, callback);
break;
case "library":
launchImageLibrary(options, callback);
break;
case "cancel":
response.putBoolean("didCancel", true);
callback.invoke(response);
break;
default: // custom button
response.putString("customButton", action);
callback.invoke(response);
}
}
});
final AlertDialog dialog = builder.create();
/**
* override onCancel method to callback cancel in case of a touch outside of
* the dialog or the BACK key pressed
*/
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
response = Arguments.createMap();
dialog.dismiss();
response.putBoolean("didCancel", true);
callback.invoke(response);
}
});
dialog.show();
}
// NOTE: Currently not reentrant / doesn't support concurrent requests
@ReactMethod
public void launchCamera(final ReadableMap options, final Callback callback) {
int requestCode;
Intent cameraIntent;
response = Arguments.createMap();
if (!isCameraAvailable()) {
response.putString("error", "Camera not available");
callback.invoke(response);
return;
}
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
response.putString("error", "can't find current Activity");
callback.invoke(response);
return;
}
if (!permissionsCheck(currentActivity)) {
return;
}
parseOptions(options);
if (pickVideo) {
requestCode = REQUEST_LAUNCH_VIDEO_CAPTURE;
cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, videoQuality);
if (videoDurationLimit > 0) {
cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, videoDurationLimit);
}
} else {
requestCode = REQUEST_LAUNCH_IMAGE_CAPTURE;
cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// we create a tmp file to save the result
File imageFile = createNewFile();
mCameraCaptureURI = Uri.fromFile(imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraCaptureURI);
}
if (cameraIntent.resolveActivity(mReactContext.getPackageManager()) == null) {
response.putString("error", "Cannot launch camera");
callback.invoke(response);
return;
}
mCallback = callback;
try {
currentActivity.startActivityForResult(cameraIntent, requestCode);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
response = Arguments.createMap();
response.putString("error", "Cannot launch camera");
callback.invoke(response);
}
}
// NOTE: Currently not reentrant / doesn't support concurrent requests
@ReactMethod
public void launchImageLibrary(final ReadableMap options, final Callback callback) {
int requestCode;
Intent libraryIntent;
Activity currentActivity = getCurrentActivity();
if (currentActivity == null) {
response = Arguments.createMap();
response.putString("error", "can't find current Activity");
callback.invoke(response);
return;
}
if (!permissionsCheck(currentActivity)) {
return;
}
parseOptions(options);
if (pickVideo) {
requestCode = REQUEST_LAUNCH_VIDEO_LIBRARY;
libraryIntent = new Intent(Intent.ACTION_PICK);
libraryIntent.setType("video/*");
} else {
requestCode = REQUEST_LAUNCH_IMAGE_LIBRARY;
libraryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
if (libraryIntent.resolveActivity(mReactContext.getPackageManager()) == null) {
response = Arguments.createMap();
response.putString("error", "Cannot launch photo library");
callback.invoke(response);
return;
}
mCallback = callback;
try {
currentActivity.startActivityForResult(libraryIntent, requestCode);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
response = Arguments.createMap();
response.putString("error", "Cannot launch photo library");
callback.invoke(response);
}
}
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
//robustness code
if (mCallback == null || (mCameraCaptureURI == null && requestCode == REQUEST_LAUNCH_IMAGE_CAPTURE)
|| (requestCode != REQUEST_LAUNCH_IMAGE_CAPTURE && requestCode != REQUEST_LAUNCH_IMAGE_LIBRARY
&& requestCode != REQUEST_LAUNCH_VIDEO_LIBRARY && requestCode != REQUEST_LAUNCH_VIDEO_CAPTURE)) {
return;
}
response = Arguments.createMap();
// user cancel
if (resultCode != Activity.RESULT_OK) {
response.putBoolean("didCancel", true);
mCallback.invoke(response);
mCallback = null;
return;
}
Uri uri;
switch (requestCode) {
case REQUEST_LAUNCH_IMAGE_CAPTURE:
uri = mCameraCaptureURI;
this.fileScan(uri.getPath());
break;
case REQUEST_LAUNCH_IMAGE_LIBRARY:
uri = data.getData();
break;
case REQUEST_LAUNCH_VIDEO_LIBRARY:
response.putString("uri", data.getData().toString());
response.putString("path", getRealPathFromURI(data.getData()));
mCallback.invoke(response);
mCallback = null;
return;
case REQUEST_LAUNCH_VIDEO_CAPTURE:
response.putString("uri", data.getData().toString());
response.putString("path", getRealPathFromURI(data.getData()));
this.fileScan(response.getString("path"));
mCallback.invoke(response);
mCallback = null;
return;
default:
uri = null;
}
String realPath = getRealPathFromURI(uri);
boolean isUrl = false;
if (realPath != null) {
try {
URL url = new URL(realPath);
isUrl = true;
} catch (MalformedURLException e) {
// not a url
}
}
// image isn't in memory cache
if (realPath == null || isUrl) {
try {
File file = createFileFromURI(uri);
realPath = file.getAbsolutePath();
uri = Uri.fromFile(file);
} catch (Exception e) {
// image not in cache
response.putString("error", "Could not read photo");
response.putString("uri", uri.toString());
mCallback.invoke(response);
mCallback = null;
return;
}
}
int currentRotation = 0;
try {
ExifInterface exif = new ExifInterface(realPath);
// extract lat, long, and timestamp and add to the response
float[] latlng = new float[2];
exif.getLatLong(latlng);
float latitude = latlng[0];
float longitude = latlng[1];
if(latitude != 0f || longitude != 0f) {
response.putDouble("latitude", latitude);
response.putDouble("longitude", longitude);
}
String timestamp = exif.getAttribute(ExifInterface.TAG_DATETIME);
SimpleDateFormat exifDatetimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
String isoFormatString = isoFormat.format(exifDatetimeFormat.parse(timestamp)) + "Z";
response.putString("timestamp", isoFormatString);
} catch (Exception e) {}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
boolean isVertical = true;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
isVertical = false;
currentRotation = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
isVertical = false;
currentRotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
currentRotation = 180;
break;
}
response.putInt("originalRotation", currentRotation);
response.putBoolean("isVertical", isVertical);
} catch (IOException e) {
e.printStackTrace();
response.putString("error", e.getMessage());
mCallback.invoke(response);
mCallback = null;
return;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(realPath, options);
int initialWidth = options.outWidth;
int initialHeight = options.outHeight;
// don't create a new file if contraint are respected
if (((initialWidth < maxWidth && maxWidth > 0) || maxWidth == 0) && ((initialHeight < maxHeight && maxHeight > 0) || maxHeight == 0) && quality == 100 && (rotation == 0 || currentRotation == rotation)) {
response.putInt("width", initialWidth);
response.putInt("height", initialHeight);
} else {
File resized = getResizedImage(realPath, initialWidth, initialHeight);
if (resized == null) {
response.putString("error", "Can't resize the image");
} else {
realPath = resized.getAbsolutePath();
uri = Uri.fromFile(resized);
BitmapFactory.decodeFile(realPath, options);
response.putInt("width", options.outWidth);
response.putInt("height", options.outHeight);
}
}
response.putString("uri", uri.toString());
response.putString("path", realPath);
if (!noData) {
response.putString("data", getBase64StringFromFile(realPath));
}
putExtraFileInfo(realPath, response);
mCallback.invoke(response);
mCallback = null;
}
/**
* Returns number of milliseconds since Jan. 1, 1970, midnight local time.
* Returns -1 if the date time information if not available.
* copied from ExifInterface.java
* @hide
*/
private static long parseTimestamp(String dateTimeString, String subSecs) {
if (dateTimeString == null) return -1;
SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.getDefault());
sFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
ParsePosition pos = new ParsePosition(0);
try {
// The exif field is in local time. Parsing it as if it is UTC will yield time
// since 1/1/1970 local time
Date datetime = sFormatter.parse(dateTimeString, pos);
if (datetime == null) return -1;
long msecs = datetime.getTime();
if (subSecs != null) {
try {
long sub = Long.valueOf(subSecs);
while (sub > 1000) {
sub /= 10;
}
msecs += sub;
} catch (NumberFormatException e) {
//expected
}
}
return msecs;
} catch (IllegalArgumentException ex) {
return -1;
}
}
private boolean permissionsCheck(Activity activity) {
int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int cameraPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (writePermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
ActivityCompat.requestPermissions(activity, PERMISSIONS, 1);
return false;
}
return true;
}
private boolean isCameraAvailable() {
return mReactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)
|| mReactContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
private String getRealPathFromURI(Uri uri) {
String result;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = mReactContext.getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = uri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
/**
* Create a file from uri to allow image picking of image in disk cache
* (Exemple: facebook image, google image etc..)
*
* @doc =>
* https://github.com/nostra13/Android-Universal-Image-Loader#load--display-task-flow
*
* @param uri
* @return File
* @throws Exception
*/
private File createFileFromURI(Uri uri) throws Exception {
File file = new File(mReactContext.getExternalCacheDir(), "photo-" + uri.getLastPathSegment());
InputStream input = mReactContext.getContentResolver().openInputStream(uri);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
input.close();
}
return file;
}
private String getBase64StringFromFile(String absoluteFilePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(absoluteFilePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
/**
* Create a resized image to fulfill the maxWidth/maxHeight, quality and rotation values
*
* @param realPath
* @param initialWidth
* @param initialHeight
* @return resized file
*/
private File getResizedImage(final String realPath, final int initialWidth, final int initialHeight) {
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap photo = BitmapFactory.decodeFile(realPath, options);
if (photo == null) {
return null;
}
Bitmap scaledphoto = null;
if (maxWidth == 0 || maxWidth > initialWidth) {
maxWidth = initialWidth;
}
if (maxHeight == 0 || maxWidth > initialHeight) {
maxHeight = initialHeight;
}
double widthRatio = (double) maxWidth / initialWidth;
double heightRatio = (double) maxHeight / initialHeight;
double ratio = (widthRatio < heightRatio)
? widthRatio
: heightRatio;
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
matrix.postScale((float) ratio, (float) ratio);
ExifInterface exif;
try {
exif = new ExifInterface(realPath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
} catch (IOException e) {
e.printStackTrace();
}
scaledphoto = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
scaledphoto.compress(Bitmap.CompressFormat.JPEG, quality, bytes);
File f = createNewFile();
FileOutputStream fo;
try {
fo = new FileOutputStream(f);
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// recycle to avoid java.lang.OutOfMemoryError
if (photo != null) {
scaledphoto.recycle();
photo.recycle();
scaledphoto = null;
photo = null;
}
return f;
}
/**
* Create a new file
*
* @return an empty file
*/
private File createNewFile() {
String filename = "image-" + UUID.randomUUID().toString() + ".jpg";
File path;
if (tmpImage) {
path = mReactContext.getExternalCacheDir();
} else {
path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
}
File f = new File(path, filename);
try {
path.mkdirs();
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return f;
}
private void putExtraFileInfo(final String path, WritableMap response) {
// size && filename
try {
File f = new File(path);
response.putDouble("fileSize", f.length());
response.putString("fileName", f.getName());
} catch (Exception e) {
e.printStackTrace();
}
// type
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
if (extension != null) {
response.putString("type", MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
}
}
private void parseOptions(final ReadableMap options) {
noData = false;
if (options.hasKey("noData")) {
noData = options.getBoolean("noData");
}
maxWidth = 0;
if (options.hasKey("maxWidth")) {
maxWidth = options.getInt("maxWidth");
}
maxHeight = 0;
if (options.hasKey("maxHeight")) {
maxHeight = options.getInt("maxHeight");
}
quality = 100;
if (options.hasKey("quality")) {
quality = (int) (options.getDouble("quality") * 100);
}
tmpImage = true;
if (options.hasKey("storageOptions")) {
tmpImage = false;
}
rotation = 0;
if (options.hasKey("rotation")) {
rotation = options.getInt("rotation");
}
pickVideo = false;
if (options.hasKey("mediaType") && options.getString("mediaType").equals("video")) {
pickVideo = true;
}
videoQuality = 1;
if (options.hasKey("videoQuality") && options.getString("videoQuality").equals("low")) {
videoQuality = 0;
}
videoDurationLimit = 0;
if (options.hasKey("durationLimit")) {
videoDurationLimit = options.getInt("durationLimit");
}
}
public void fileScan(String path){
MediaScannerConnection.scanFile(mReactContext,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
// Required for RN 0.30+ modules than implement ActivityEventListener
public void onNewIntent(Intent intent) { }
}
| use holo light dialog theme
| android/src/main/java/com/imagepicker/ImagePickerModule.java | use holo light dialog theme |
|
Java | mit | fc429fc017dae20920fe523a4577546de4ba31b7 | 0 | Astarch/amos-ws18-proj3,Astarch/amos-ws18-proj3,Astarch/amos-ws18-proj3,Astarch/amos-ws18-proj3 | package de.pretrendr.awscli;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Test;
import org.springframework.context.annotation.Bean;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
public class AWSCLITest{
@Test
public void checkAWSCLIConnection() throws Exception{
//ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
assertTrue("Bad AWS CLI credentials",(new EnvironmentVariableCredentialsProvider().getCredentials() != null));
}
}
| backendRestDraft/src/test/java/de/pretrendr/awscli/AWSCLITest.java | package de.pretrendr.awscli;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Test;
import org.springframework.context.annotation.Bean;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
public class AWSCLITest{
@Test
public void checkAWSCLIConnection() throws Exception{
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
assertTrue("Bad AWS CLI credentials",(credentialsProvider.getCredentials() != null));
}
}
| test aws cli for circleci | backendRestDraft/src/test/java/de/pretrendr/awscli/AWSCLITest.java | test aws cli for circleci |
|
Java | mit | 88461efa59c85e8bce945f80ae5a7daaa9bb7cfb | 0 | jtechapps/FloppyThreeD,jtechapps/FloppyThreeD,jtechapps/FloppyThreeD | package com.jtechapps.FloppyThreeD.Screens;
import java.util.Iterator;
import java.util.Random;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.Bullet;
import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper;
import com.badlogic.gdx.physics.bullet.collision.btBoxShape;
import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm;
import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithmConstructionInfo;
import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.collision.btCollisionShape;
import com.badlogic.gdx.physics.bullet.collision.btCylinderShape;
import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo;
import com.badlogic.gdx.physics.bullet.collision.btManifoldResult;
import com.badlogic.gdx.physics.bullet.collision.btSphereBoxCollisionAlgorithm;
import com.badlogic.gdx.physics.bullet.collision.btSphereShape;
import com.badlogic.gdx.utils.Array;
import com.jtechapps.FloppyThreeD.NativeInterface;
public class ClassicGameScreen implements Screen, InputProcessor {
public PerspectiveCamera camera;
private float width;
private float height;
public ModelBatch modelBatch;
public Model model;//create 500*5*500 floor
public Array<ModelInstance> instances;
public Array<ModelInstance> pipeinstances;
public Array<ModelInstance> toppipeinstances;
public Environment environment;
public CameraInputController camController;
ModelInstance playerinstance;
private int blockscale = 5;//pipe height max 65 or 75
private float pipespeed = 0.5f;
private Texture groundTexture;
private float gravity = -65.0f;
private float playerforce = 0.0f;
boolean collision;
private boolean touched;
private boolean dead;
//physics
btCollisionShape groundShape;
btCollisionShape ballShape;
btCollisionShape pipeShape;
btCollisionObject groundObject;
btCollisionObject ballObject;
btCollisionConfiguration collisionConfig;
btDispatcher dispatcher;
private Array<btCollisionObject> pipecollisions;
private Array<btCollisionObject> toppipecollisions;
Game g;
private Sound dieSound;
private Sound flopSound;
private Sound scoreSound;
private int score = 0;
private NativeInterface nface;
public ClassicGameScreen(Game game, NativeInterface nativeInterface){
g = game;
nface = nativeInterface;
}
@Override
public void render(float delta) {
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(camera);
for (ModelInstance minstance : instances) {
modelBatch.render(minstance, environment);
}
for (int arrayint = 0; arrayint < pipeinstances.size; arrayint++){
if(touched && !dead){
pipeinstances.get(arrayint).transform.translate(pipespeed, 0, 0);
pipecollisions.get(arrayint).setWorldTransform(pipeinstances.get(arrayint).transform);
collision = checkCollision(pipecollisions.get(arrayint));
if(collision){
playerdie();
}
}
modelBatch.render(pipeinstances.get(arrayint), environment);
}
for (int arrayint = 0; arrayint < toppipeinstances.size; arrayint++) {
if(touched && !dead){
toppipeinstances.get(arrayint).transform.translate(pipespeed, 0, 0);
toppipecollisions.get(arrayint).setWorldTransform(toppipeinstances.get(arrayint).transform);
collision = checkCollision(toppipecollisions.get(arrayint));
if(collision){
playerdie();
}
}
modelBatch.render(toppipeinstances.get(arrayint), environment);
}
//check if pipes moved off screen.
Iterator<ModelInstance> iter = pipeinstances.iterator();
while(iter.hasNext()) {
ModelInstance pipe = iter.next();
Vector3 tmp = new Vector3();
pipe.transform.getTranslation(tmp);
float x = tmp.x;
Vector3 playertmp = new Vector3();
playerinstance.transform.getTranslation(playertmp);
float playerx = playertmp.x;
if(x == 50*blockscale){//middle
spawnpipes(pipeinstances, toppipeinstances);
}
if(x == playerx){//add score
if(!dead)
addscore();
}
if(x >= 60*blockscale){//left side
iter.remove();
}
}
Iterator<ModelInstance> iter2 = toppipeinstances.iterator();
while(iter2.hasNext()) {
ModelInstance pipe = iter2.next();
Vector3 tmp = new Vector3();
pipe.transform.getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter2.remove();
}
}
Iterator<btCollisionObject> iter3 = pipecollisions.iterator();//delete pipe collisions if they go off screen.
while(iter3.hasNext()) {
btCollisionObject pipe = iter3.next();
Vector3 tmp = new Vector3();
pipe.getWorldTransform().getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter3.remove();
}
}
Iterator<btCollisionObject> iter4 = toppipecollisions.iterator();//delete pipe collisions if they go off screen.
while(iter4.hasNext()) {
btCollisionObject pipe = iter4.next();
Vector3 tmp = new Vector3();
pipe.getWorldTransform().getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter4.remove();
}
}
//player physics
if(!collision && touched && !dead){
//gravity
playerinstance.transform.translate(0, gravity*delta, 0);
//jumps
float playerforcetoapply = playerforce*delta*2;
playerforce-=playerforcetoapply;
if(playerforce<=0){
playerforce = 0.0f;
}
playerinstance.transform.translate(0, playerforcetoapply/2, 0);
ballObject.setWorldTransform(playerinstance.transform);
collision = checkCollision();
if(collision){
playerdie();
}
Vector3 playertmppos = new Vector3();
playerinstance.transform.getTranslation(playertmppos);
if(playertmppos.y >= 90){
playerdie();
}
}
else if(touched && dead && collision){
playerinstance.transform.translate(0, gravity*delta, 0);
}
modelBatch.render(playerinstance, environment);
modelBatch.end();
}
private void addscore(){
score++;
scoreSound.play();
Gdx.app.log("score ", ""+score);
}
private void playerdie(){
//play sound and wait
dieSound.play();
dead = true;
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
Bullet.init();
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
camera = new PerspectiveCamera(67, 640*2, 480*2);
camera.position.set(50.0f*blockscale, 25.0f, 0.0f);
camera.lookAt(50.0f*blockscale, 25.0f, 50.0f*blockscale);
camera.near = 1f;
camera.far = 300f;
camera.update();
modelBatch = new ModelBatch();
instances = new Array<ModelInstance>();
pipeinstances = new Array<ModelInstance>();
toppipeinstances = new Array<ModelInstance>();
pipecollisions = new Array<btCollisionObject>();
toppipecollisions = new Array<btCollisionObject>();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f,
0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f,
-0.8f, -0.2f));
//environment.set(new ColorAttribute(ColorAttribute.Fog, 1f, 0.1f, 0.1f, 1.0f));
//physics
ballShape = new btSphereShape(4.0f);
pipeShape = new btCylinderShape(new Vector3(5.0f, 75.0f/2, 5.0f));
groundShape = new btBoxShape(new Vector3(50.0f*blockscale, 0.5f*blockscale, 50.0f*blockscale));
collisionConfig = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfig);
spawnfloor();
spawnpipes(pipeinstances, toppipeinstances);
spawnplayer();
groundObject = new btCollisionObject();
groundObject.setCollisionShape(groundShape);
groundObject.setWorldTransform(instances.peek().transform);
ballObject = new btCollisionObject();
ballObject.setCollisionShape(ballShape);
ballObject.setWorldTransform(playerinstance.transform);
//sounds
flopSound = Gdx.audio.newSound(Gdx.files.internal("sounds/switch.wav"));
dieSound = Gdx.audio.newSound(Gdx.files.internal("sounds/die.wav"));
scoreSound = Gdx.audio.newSound(Gdx.files.internal("sounds/point.wav"));
Gdx.input.setInputProcessor(this);
}
public void spawnfloor(){
groundTexture = new Texture("img/grass.png");
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
/*model = modelBuilder.createBox(blockscale*100, blockscale, blockscale*100, new Material(
TextureAttribute.createDiffuse(groundTexture)),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);*/
model = modelBuilder.createBox(blockscale*100, blockscale, blockscale*100, new Material(
ColorAttribute.createDiffuse(Color.CLEAR)),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);
ModelInstance instance = new ModelInstance(model);
instance.transform.translate(blockscale*50, -20.0f, blockscale*50);
instances.add(instance);
}
public void spawnCubeArray(Array<ModelInstance> cubeinstances){
for (int z = 0; z < 100; z++) {
for (int x = 0; x < 100; x++) {
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
if (x % 2 == 0) {
if(z % 2 == 0){
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
}
else {
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
}
} else {
if(z % 2 == 0){
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
}
else{
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
}
}
ModelInstance instance = new ModelInstance(model);
instance.transform.translate(x * blockscale, 0, z*blockscale);
cubeinstances.add(instance);
}
}
}
public void spawnplayer(){
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(8.0f, 8.0f, 8.0f, 100, 100, new Material(ColorAttribute.createDiffuse(Color.MAROON)), Usage.Position | Usage.Normal);
playerinstance = new ModelInstance(model);
playerinstance.transform.translate(53.0f*blockscale, 40.0f, 10.0f*blockscale);
}
public void spawnpipes(Array<ModelInstance> pinstances, Array<ModelInstance> tinstances){
Random rn = new Random();
int random = rn.nextInt(29) + 1;
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
model = modelBuilder.createCylinder(10.0f, 75.0f, 10.0f, 100, new Material(
ColorAttribute.createDiffuse(Color.MAGENTA)), Usage.Position | Usage.Normal);
ModelInstance bottompipeinstance = new ModelInstance(model);
ModelInstance toppipeinstance = new ModelInstance(model);
bottompipeinstance.transform.translate(40.0f*blockscale, -5.0f-random, 10.0f*blockscale);
toppipeinstance.transform.translate(40.0f*blockscale, 95.0f-random, 10.0f*blockscale);
pinstances.add(bottompipeinstance);
tinstances.add(toppipeinstance);
btCollisionObject bottompipeObject = new btCollisionObject();
bottompipeObject.setCollisionShape(pipeShape);
bottompipeObject.setWorldTransform(bottompipeinstance.transform);
btCollisionObject toppipeObject = new btCollisionObject();
toppipeObject.setCollisionShape(pipeShape);
toppipeObject.setWorldTransform(toppipeinstance.transform);
pipecollisions.add(bottompipeObject);
toppipecollisions.add(toppipeObject);
}
private void jump(){
if(!touched)
touched=true;
if(!dead){
playerforce+=100.0f;
flopSound.play();
}
else {
g.setScreen(new ClassicGameScreen(g, nface));
}
}
boolean checkCollision() {// thanks blogs.xoppa.com for bullet physics
CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject);
CollisionObjectWrapper co1 = new CollisionObjectWrapper(groundObject);
btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo();
ci.setDispatcher1(dispatcher);
btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false);
btDispatcherInfo info = new btDispatcherInfo();
btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper);
algorithm.processCollision(co0.wrapper, co1.wrapper, info, result);
boolean r = result.getPersistentManifold().getNumContacts() > 0;
result.dispose();
info.dispose();
algorithm.dispose();
ci.dispose();
co1.dispose();
co0.dispose();
return r;
}
boolean checkCollision(btCollisionObject colObject) {// thanks blogs.xoppa.com for bullet physics
CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject);
CollisionObjectWrapper co1 = new CollisionObjectWrapper(colObject);
btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo();
ci.setDispatcher1(dispatcher);
btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false);
btDispatcherInfo info = new btDispatcherInfo();
btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper);
algorithm.processCollision(co0.wrapper, co1.wrapper, info, result);
boolean r = result.getPersistentManifold().getNumContacts() > 0;
result.dispose();
info.dispose();
algorithm.dispose();
ci.dispose();
co1.dispose();
co0.dispose();
return r;
}
@Override
public void hide() {
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
model.dispose();
modelBatch.dispose();
groundTexture.dispose();
groundObject.dispose();
groundShape.dispose();
ballObject.dispose();
ballShape.dispose();
pipeShape.dispose();
dispatcher.dispose();
collisionConfig.dispose();
dieSound.dispose();
flopSound.dispose();
scoreSound.dispose();
nface.garbagecollect();
this.dispose();
}
@Override
public boolean keyDown(int keycode) {
if(keycode == Input.Keys.SPACE){
jump();
}
return false;
}
@Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean keyTyped(char character) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
jump();
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
}
| core/src/com/jtechapps/FloppyThreeD/Screens/ClassicGameScreen.java | package com.jtechapps.FloppyThreeD.Screens;
import java.util.Iterator;
import java.util.Random;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.Bullet;
import com.badlogic.gdx.physics.bullet.collision.CollisionObjectWrapper;
import com.badlogic.gdx.physics.bullet.collision.btBoxShape;
import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithm;
import com.badlogic.gdx.physics.bullet.collision.btCollisionAlgorithmConstructionInfo;
import com.badlogic.gdx.physics.bullet.collision.btCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btCollisionDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btCollisionObject;
import com.badlogic.gdx.physics.bullet.collision.btCollisionShape;
import com.badlogic.gdx.physics.bullet.collision.btCylinderShape;
import com.badlogic.gdx.physics.bullet.collision.btDefaultCollisionConfiguration;
import com.badlogic.gdx.physics.bullet.collision.btDispatcher;
import com.badlogic.gdx.physics.bullet.collision.btDispatcherInfo;
import com.badlogic.gdx.physics.bullet.collision.btManifoldResult;
import com.badlogic.gdx.physics.bullet.collision.btSphereBoxCollisionAlgorithm;
import com.badlogic.gdx.physics.bullet.collision.btSphereShape;
import com.badlogic.gdx.utils.Array;
import com.jtechapps.FloppyThreeD.NativeInterface;
public class ClassicGameScreen implements Screen, InputProcessor {
public PerspectiveCamera camera;
private float width;
private float height;
public ModelBatch modelBatch;
public Model model;//create 500*5*500 floor
public Array<ModelInstance> instances;
public Array<ModelInstance> pipeinstances;
public Array<ModelInstance> toppipeinstances;
public Environment environment;
public CameraInputController camController;
ModelInstance playerinstance;
private int blockscale = 5;//pipe height max 65 or 75
private float pipespeed = 0.5f;
private Texture groundTexture;
private float gravity = -65.0f;
private float playerforce = 0.0f;
boolean collision;
private boolean touched;
private boolean dead;
//physics
btCollisionShape groundShape;
btCollisionShape ballShape;
btCollisionShape pipeShape;
btCollisionObject groundObject;
btCollisionObject ballObject;
btCollisionConfiguration collisionConfig;
btDispatcher dispatcher;
private Array<btCollisionObject> pipecollisions;
private Array<btCollisionObject> toppipecollisions;
Game g;
private Sound dieSound;
private Sound flopSound;
private Sound scoreSound;
private int score = 0;
private NativeInterface nface;
public ClassicGameScreen(Game game, NativeInterface nativeInterface){
g = game;
nface = nativeInterface;
}
@Override
public void render(float delta) {
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(camera);
for (ModelInstance minstance : instances) {
modelBatch.render(minstance, environment);
}
for (int arrayint = 0; arrayint < pipeinstances.size; arrayint++){
if(touched && !dead){
pipeinstances.get(arrayint).transform.translate(pipespeed, 0, 0);
pipecollisions.get(arrayint).setWorldTransform(pipeinstances.get(arrayint).transform);
collision = checkCollision(pipecollisions.get(arrayint));
if(collision){
playerdie();
}
}
modelBatch.render(pipeinstances.get(arrayint), environment);
}
for (int arrayint = 0; arrayint < toppipeinstances.size; arrayint++) {
if(touched && !dead){
toppipeinstances.get(arrayint).transform.translate(pipespeed, 0, 0);
toppipecollisions.get(arrayint).setWorldTransform(toppipeinstances.get(arrayint).transform);
collision = checkCollision(toppipecollisions.get(arrayint));
if(collision){
playerdie();
}
}
modelBatch.render(toppipeinstances.get(arrayint), environment);
}
//check if pipes moved off screen.
Iterator<ModelInstance> iter = pipeinstances.iterator();
while(iter.hasNext()) {
ModelInstance pipe = iter.next();
Vector3 tmp = new Vector3();
pipe.transform.getTranslation(tmp);
float x = tmp.x;
Vector3 playertmp = new Vector3();
playerinstance.transform.getTranslation(playertmp);
float playerx = playertmp.x;
if(x == 50*blockscale){//middle
spawnpipes(pipeinstances, toppipeinstances);
}
if(x == playerx){//add score
addscore();
}
if(x >= 60*blockscale){//left side
iter.remove();
}
}
Iterator<ModelInstance> iter2 = toppipeinstances.iterator();
while(iter2.hasNext()) {
ModelInstance pipe = iter2.next();
Vector3 tmp = new Vector3();
pipe.transform.getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter2.remove();
}
}
Iterator<btCollisionObject> iter3 = pipecollisions.iterator();//delete pipe collisions if they go off screen.
while(iter3.hasNext()) {
btCollisionObject pipe = iter3.next();
Vector3 tmp = new Vector3();
pipe.getWorldTransform().getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter3.remove();
}
}
Iterator<btCollisionObject> iter4 = toppipecollisions.iterator();//delete pipe collisions if they go off screen.
while(iter4.hasNext()) {
btCollisionObject pipe = iter4.next();
Vector3 tmp = new Vector3();
pipe.getWorldTransform().getTranslation(tmp);
float x = tmp.x;
if(x >= 60*blockscale){//left side
iter4.remove();
}
}
//player physics
if(!collision && touched && !dead){
//gravity
playerinstance.transform.translate(0, gravity*delta, 0);
//jumps
float playerforcetoapply = playerforce*delta*2;
playerforce-=playerforcetoapply;
if(playerforce<=0){
playerforce = 0.0f;
}
playerinstance.transform.translate(0, playerforcetoapply/2, 0);
ballObject.setWorldTransform(playerinstance.transform);
collision = checkCollision();
if(collision){
playerdie();
}
Vector3 playertmppos = new Vector3();
playerinstance.transform.getTranslation(playertmppos);
if(playertmppos.y >= 90){
playerdie();
}
}
else if(touched && dead && collision){
playerinstance.transform.translate(0, gravity*delta, 0);
}
modelBatch.render(playerinstance, environment);
modelBatch.end();
}
private void addscore(){
score++;
scoreSound.play();
Gdx.app.log("score ", ""+score);
}
private void playerdie(){
//play sound and wait
dieSound.play();
dead = true;
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
Bullet.init();
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
camera = new PerspectiveCamera(67, 640*2, 480*2);
camera.position.set(50.0f*blockscale, 25.0f, 0.0f);
camera.lookAt(50.0f*blockscale, 25.0f, 50.0f*blockscale);
camera.near = 1f;
camera.far = 300f;
camera.update();
modelBatch = new ModelBatch();
instances = new Array<ModelInstance>();
pipeinstances = new Array<ModelInstance>();
toppipeinstances = new Array<ModelInstance>();
pipecollisions = new Array<btCollisionObject>();
toppipecollisions = new Array<btCollisionObject>();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f,
0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f,
-0.8f, -0.2f));
//environment.set(new ColorAttribute(ColorAttribute.Fog, 1f, 0.1f, 0.1f, 1.0f));
//physics
ballShape = new btSphereShape(4.0f);
pipeShape = new btCylinderShape(new Vector3(5.0f, 75.0f/2, 5.0f));
groundShape = new btBoxShape(new Vector3(50.0f*blockscale, 0.5f*blockscale, 50.0f*blockscale));
collisionConfig = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfig);
spawnfloor();
spawnpipes(pipeinstances, toppipeinstances);
spawnplayer();
groundObject = new btCollisionObject();
groundObject.setCollisionShape(groundShape);
groundObject.setWorldTransform(instances.peek().transform);
ballObject = new btCollisionObject();
ballObject.setCollisionShape(ballShape);
ballObject.setWorldTransform(playerinstance.transform);
//sounds
flopSound = Gdx.audio.newSound(Gdx.files.internal("sounds/switch.wav"));
dieSound = Gdx.audio.newSound(Gdx.files.internal("sounds/die.wav"));
scoreSound = Gdx.audio.newSound(Gdx.files.internal("sounds/point.wav"));
Gdx.input.setInputProcessor(this);
}
public void spawnfloor(){
groundTexture = new Texture("img/grass.png");
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
/*model = modelBuilder.createBox(blockscale*100, blockscale, blockscale*100, new Material(
TextureAttribute.createDiffuse(groundTexture)),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);*/
model = modelBuilder.createBox(blockscale*100, blockscale, blockscale*100, new Material(
ColorAttribute.createDiffuse(Color.CLEAR)),
Usage.Position | Usage.Normal | Usage.TextureCoordinates);
ModelInstance instance = new ModelInstance(model);
instance.transform.translate(blockscale*50, -20.0f, blockscale*50);
instances.add(instance);
}
public void spawnCubeArray(Array<ModelInstance> cubeinstances){
for (int z = 0; z < 100; z++) {
for (int x = 0; x < 100; x++) {
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
if (x % 2 == 0) {
if(z % 2 == 0){
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
}
else {
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
}
} else {
if(z % 2 == 0){
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.GREEN)),
Usage.Position | Usage.Normal);
}
else{
model = modelBuilder.createBox(blockscale, blockscale, blockscale, new Material(
ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
}
}
ModelInstance instance = new ModelInstance(model);
instance.transform.translate(x * blockscale, 0, z*blockscale);
cubeinstances.add(instance);
}
}
}
public void spawnplayer(){
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(8.0f, 8.0f, 8.0f, 100, 100, new Material(ColorAttribute.createDiffuse(Color.MAROON)), Usage.Position | Usage.Normal);
playerinstance = new ModelInstance(model);
playerinstance.transform.translate(53.0f*blockscale, 40.0f, 10.0f*blockscale);
}
public void spawnpipes(Array<ModelInstance> pinstances, Array<ModelInstance> tinstances){
Random rn = new Random();
int random = rn.nextInt(29) + 1;
ModelBuilder modelBuilder = new ModelBuilder();
Model model;
model = modelBuilder.createCylinder(10.0f, 75.0f, 10.0f, 100, new Material(
ColorAttribute.createDiffuse(Color.MAGENTA)), Usage.Position | Usage.Normal);
ModelInstance bottompipeinstance = new ModelInstance(model);
ModelInstance toppipeinstance = new ModelInstance(model);
bottompipeinstance.transform.translate(40.0f*blockscale, -5.0f-random, 10.0f*blockscale);
toppipeinstance.transform.translate(40.0f*blockscale, 95.0f-random, 10.0f*blockscale);
pinstances.add(bottompipeinstance);
tinstances.add(toppipeinstance);
btCollisionObject bottompipeObject = new btCollisionObject();
bottompipeObject.setCollisionShape(pipeShape);
bottompipeObject.setWorldTransform(bottompipeinstance.transform);
btCollisionObject toppipeObject = new btCollisionObject();
toppipeObject.setCollisionShape(pipeShape);
toppipeObject.setWorldTransform(toppipeinstance.transform);
pipecollisions.add(bottompipeObject);
toppipecollisions.add(toppipeObject);
}
private void jump(){
if(!touched)
touched=true;
if(!dead){
playerforce+=100.0f;
flopSound.play();
}
else {
g.setScreen(new ClassicGameScreen(g, nface));
}
}
boolean checkCollision() {// thanks blogs.xoppa.com for bullet physics
CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject);
CollisionObjectWrapper co1 = new CollisionObjectWrapper(groundObject);
btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo();
ci.setDispatcher1(dispatcher);
btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false);
btDispatcherInfo info = new btDispatcherInfo();
btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper);
algorithm.processCollision(co0.wrapper, co1.wrapper, info, result);
boolean r = result.getPersistentManifold().getNumContacts() > 0;
result.dispose();
info.dispose();
algorithm.dispose();
ci.dispose();
co1.dispose();
co0.dispose();
return r;
}
boolean checkCollision(btCollisionObject colObject) {// thanks blogs.xoppa.com for bullet physics
CollisionObjectWrapper co0 = new CollisionObjectWrapper(ballObject);
CollisionObjectWrapper co1 = new CollisionObjectWrapper(colObject);
btCollisionAlgorithmConstructionInfo ci = new btCollisionAlgorithmConstructionInfo();
ci.setDispatcher1(dispatcher);
btCollisionAlgorithm algorithm = new btSphereBoxCollisionAlgorithm(null, ci, co0.wrapper, co1.wrapper, false);
btDispatcherInfo info = new btDispatcherInfo();
btManifoldResult result = new btManifoldResult(co0.wrapper, co1.wrapper);
algorithm.processCollision(co0.wrapper, co1.wrapper, info, result);
boolean r = result.getPersistentManifold().getNumContacts() > 0;
result.dispose();
info.dispose();
algorithm.dispose();
ci.dispose();
co1.dispose();
co0.dispose();
return r;
}
@Override
public void hide() {
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
model.dispose();
modelBatch.dispose();
groundTexture.dispose();
groundObject.dispose();
groundShape.dispose();
ballObject.dispose();
ballShape.dispose();
pipeShape.dispose();
dispatcher.dispose();
collisionConfig.dispose();
dieSound.dispose();
flopSound.dispose();
scoreSound.dispose();
nface.garbagecollect();
this.dispose();
}
@Override
public boolean keyDown(int keycode) {
if(keycode == Input.Keys.SPACE){
jump();
}
return false;
}
@Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean keyTyped(char character) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
jump();
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
}
| Fixed glitch where if player died in the exact middle of the pipe the score would keep being added.
| core/src/com/jtechapps/FloppyThreeD/Screens/ClassicGameScreen.java | Fixed glitch where if player died in the exact middle of the pipe the score would keep being added. |
|
Java | mit | 4407f6141f34793bfab2c0a1a02a291d7924d041 | 0 | vimeo/vimeo-networking-java,vimeo/vimeo-networking-java,vimeo/vimeo-networking-java | /*
* Copyright (c) 2015 Vimeo (https://vimeo.com)
*
* 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.vimeo.networking;
/**
* The constants class for Vimeo API calls. This includes parameters, fields, and defaults
* <p>
* Created by kylevenn on 7/7/15.
*/
@SuppressWarnings("unused")
public final class Vimeo {
public static final String VIMEO_BASE_URL_STRING = "https://api.vimeo.com/";
public static final String API_VERSION = "3.4.2";
// Global Constants
public static final int NOT_FOUND = -1;
// Grant Types
public static final String CODE_GRANT_PATH = "/oauth/authorize";
public static final String CODE_GRANT_RESPONSE_TYPE = "code";
public static final String CODE_GRANT_STATE = "state";
public static final String CODE_GRANT_TYPE = "authorization_code";
public static final String DEVICE_GRANT_TYPE = "device_grant";
public static final String FACEBOOK_GRANT_TYPE = "facebook";
public static final String GOOGLE_GRANT_TYPE = "google";
public static final String PASSWORD_GRANT_TYPE = "password";
public static final String CLIENT_CREDENTIALS_GRANT_TYPE = "client_credentials";
public static final String OAUTH_ONE_GRANT_TYPE = "vimeo_oauth1";
// Endpoints
public static final String ENDPOINT_ME = "me";
public static final String ENDPOINT_RECOMMENDATIONS = "/recommendations";
public static final String ENDPOINT_TERMS_OF_SERVICE = "documents/termsofservice";
public static final String ENDPOINT_PRIVACY_POLICY = "documents/privacy";
public static final String ENDPOINT_PAYMENT_ADDENDUM = "documents/paymentaddendum";
// Parameters
public static final String PARAMETER_REDIRECT_URI = "redirect_uri";
public static final String PARAMETER_RESPONSE_TYPE = "response_type";
public static final String PARAMETER_STATE = "state";
public static final String PARAMETER_SCOPE = "scope";
public static final String PARAMETER_TOKEN = "token";
public static final String PARAMETER_ID_TOKEN = "id_token";
public static final String PARAMETER_CLIENT_ID = "client_id";
public static final String PARAMETER_USERS_NAME = "name";
public static final String PARAMETER_EMAIL = "email";
public static final String PARAMETER_PASSWORD = "password";
public static final String PARAMETER_USERS_LOCATION = "location";
public static final String PARAMETER_USERS_BIO = "bio";
public static final String PARAMETER_MARKETING_OPT_IN = "marketing_opt_in";
public static final String PARAMETER_VIDEO_VIEW = "view";
public static final String PARAMETER_VIDEO_COMMENTS = "comments";
public static final String PARAMETER_VIDEO_EMBED = "embed";
public static final String PARAMETER_VIDEO_DOWNLOAD = "download";
public static final String PARAMETER_VIDEO_ADD = "add";
public static final String PARAMETER_VIDEO_NAME = "name";
public static final String PARAMETER_VIDEO_DESCRIPTION = "description";
public static final String PARAMETER_VIDEO_PRIVACY = "privacy";
public static final String PARAMETER_VIDEO_PASSWORD = "password";
public static final String PARAMETER_ALBUM_NAME = "name";
public static final String PARAMETER_ALBUM_DESCRIPTION = "description";
public static final String PARAMETER_ALBUM_PRIVACY = "privacy";
public static final String PARAMETER_ALBUM_PASSWORD = "password";
public static final String PARAMETER_AUTH_CODE = "auth_code";
public static final String PARAMETER_APP_TYPE = "app_type";
public static final String PARAMETER_COMMENT_TEXT_BODY = "text";
public static final String PARAMETER_ACTIVE = "active";
// Header Parameters
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String HEADER_USER_AGENT = "User-Agent";
public static final String HEADER_ACCEPT = "Accept";
public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language";
// Header Values
public static final String HEADER_CACHE_PUBLIC = "public";
// Video Analytics Parameters
public static final String PARAMETER_SESSION_ID = "session_id";
public static final String PARAMETER_SESSION_TIME = "session_time";
public static final String PARAMETER_VUID = "vuid";
public static final String PARAMETER_LOCALE = "locale";
public static final String PARAMETER_EXIT_WATCHED_TIME = "exit_watched_time_code";
public static final String PARAMETER_FURTHEST_WATCHED_TIME = "furthest_watched_time_code";
public static final String PARAMETER_PROGRESS = "progress";
public static final String PARAMETER_EVENTS = "events";
public static final String PARAMETER_EVENT_TYPE = "type";
public static final String PARAMETER_EVENT_TYPE_WATER_LATER = "watchlater";
public static final String PARAMETER_EVENT_TYPE_LIKE = "like";
public static final String PARAMETER_EVENT_ACTION = "action";
public static final String PARAMETER_EVENT_ACTION_ADDED = "added";
public static final String PARAMETER_EVENT_ACTION_REMOVED = "removed";
// GET and Sorting Parameters
public static final String PARAMETER_GET_PAGE_SIZE = "per_page";
public static final String PARAMETER_GET_QUERY = "query";
public static final String PARAMETER_GET_SORT = "sort";
public static final String PARAMETER_GET_DIRECTION = "direction";
public static final String PARAMETER_GET_FIELD_FILTER = "fields";
public static final String PARAMETER_GET_CONTAINER_FIELD_FILTER = "container_fields";
public static final String PARAMETER_GET_LENGTH_MIN_DURATION = "min_duration";
public static final String PARAMETER_GET_LENGTH_MAX_DURATION = "max_duration";
public static final String PARAMETER_GET_FILTER = "filter";
public static final String PARAMETER_GET_UPLOAD_DATE_FILTER = "filter_upload_date";
public static final String PARAMETER_GET_NOTIFICATION_TYPES_FILTER = "filter_notification_types";
public static final String PARAMETER_PATCH_LATEST_NOTIFICATION_URI = "latest_notification_uri";
// Sorting (sort) Values
public static final String SORT_DEFAULT = "default";
public static final String SORT_RELEVANCE = "relevant";
public static final String SORT_POPULAR = "popularity";
public static final String SORT_DATE = "date";
public static final String SORT_PURCHASE_TIME = "purchase_time";
public static final String SORT_FOLLOWERS = "followers";
public static final String SORT_ALPHABETICAL = "alphabetical";
public static final String SORT_MANUAL = "manual";
public static final String SORT_DURATION = "duration";
public static final String SORT_LAST_USER_ACTION_EVENT_DATE = "last_user_action_event_date";
public static final String SORT_PLAYS = "plays";
public static final String SORT_LIKES = "likes";
public static final String SORT_MODIFIED_TIME = "modified_time";
public static final String SORT_COMMENTS = "comments";
// Notification values
public static final String NOTIFICATION_COMMENT = "comment";
public static final String NOTIFICATION_CREDIT = "credit";
public static final String NOTIFICATION_LIKE = "like";
public static final String NOTIFICATION_REPLY = "reply";
public static final String NOTIFICATION_FOLLOW = "follow";
public static final String NOTIFICATION_VIDEO_AVAILABLE = "video_available";
public static final String NOTIFICATION_SHARE = "share";
public static final String NOTIFICATION_MENTION = "mention";
public static final String NOTIFICATION_STORAGE_WARNING = "storage_warning";
public static final String NOTIFICATION_ACCOUNT_EXPIRATION_WARNING = "account_expiration_warning";
public static final String NOTIFICATION_TVOD_PURCHASE = "vod_purchase";
public static final String NOTIFICATION_TVOD_PREORDER_AVAILABLE = "vod_preorder_available";
public static final String NOTIFICATION_TVOD_RENTAL_EXPIRATION_WARNING = "vod_rental_expiration_warning";
public static final String NOTIFICATION_FOLLOWED_USER_VIDEO_AVAILABLE = "followed_user_video_available";
// Sort Direction Values
public static final String SORT_DIRECTION_ASCENDING = "asc";
public static final String SORT_DIRECTION_DESCENDING = "desc";
// Filter (filter) Values
public static final String FILTER_RELATED = "related";
public static final String FILTER_UPLOAD = "upload_date";
public static final String FILTER_VIEWABLE = "viewable";
public static final String FILTER_PLAYABLE = "playable";
public static final String FILTER_TRENDING = "trending";
public static final String FILTER_TVOD_RENTALS = "rented";
public static final String FILTER_TVOD_SUBSCRIPTIONS = "subscription";
public static final String FILTER_TVOD_PURCHASES = "purchased";
public static final String FILTER_NOTIFICATION_TYPES = "notification_types";
// Filter Upload Date Values
public static final String FILTER_UPLOAD_DATE_TODAY = "day";
public static final String FILTER_UPLOAD_DATE_WEEK = "week";
public static final String FILTER_UPLOAD_DATE_MONTH = "month";
public static final String FILTER_UPLOAD_DATE_YEAR = "year";
public static final String PAGE_SIZE_MAX = "100";
public static final String OPTIONS_POST = "POST";
// Fields (for invalid params)
public static final String FIELD_NAME = "name";
public static final String FIELD_EMAIL = "email";
public static final String FIELD_PASSWORD = "password";
public static final String FIELD_TOKEN = "token";
public static final String FIELD_USERNAME = "username";
public enum RefineLength {
ANY,
UNDER_FIVE_MINUTES,
OVER_FIVE_MINUTES
}
public enum RefineSort {
DEFAULT(SORT_DEFAULT),
RELEVANCE(SORT_RELEVANCE),
POPULARITY(SORT_POPULAR),
RECENT(SORT_DATE),
// Channels
FOLLOWERS(SORT_FOLLOWERS),
// Users
AZ(SORT_DIRECTION_ASCENDING),
ZA(SORT_DIRECTION_DESCENDING);
private String mText;
RefineSort(String text) {
this.mText = text;
}
public String getText() {
return this.mText;
}
public static RefineSort fromString(String text) {
if (text != null) {
for (RefineSort b : RefineSort.values()) {
if (text.equalsIgnoreCase(b.mText)) {
return b;
}
}
}
throw new IllegalArgumentException("No constant with mText " + text + " found");
}
}
public enum RefineUploadDate {
ANYTIME(""),
TODAY(FILTER_UPLOAD_DATE_TODAY),
THIS_WEEK(FILTER_UPLOAD_DATE_WEEK),
THIS_MONTH(FILTER_UPLOAD_DATE_MONTH),
THIS_YEAR(FILTER_UPLOAD_DATE_YEAR);
private String mText;
RefineUploadDate(String text) {
this.mText = text;
}
public String getText() {
return this.mText;
}
public static RefineUploadDate fromString(String text) {
if (text != null) {
for (RefineUploadDate b : RefineUploadDate.values()) {
if (text.equalsIgnoreCase(b.mText)) {
return b;
}
}
}
throw new IllegalArgumentException("No constant with mText " + text + " found");
}
}
public enum LogLevel {
// 0 1 2 3
VERBOSE, DEBUG, ERROR, NONE
}
private Vimeo() {
}
}
| vimeo-networking/src/main/java/com/vimeo/networking/Vimeo.java | /*
* Copyright (c) 2015 Vimeo (https://vimeo.com)
*
* 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.vimeo.networking;
/**
* The constants class for Vimeo API calls. This includes parameters, fields, and defaults
* <p>
* Created by kylevenn on 7/7/15.
*/
@SuppressWarnings("unused")
public final class Vimeo {
public static final String VIMEO_BASE_URL_STRING = "https://api.vimeo.com/";
public static final String API_VERSION = "3.4.2";
// Global Constants
public static final int NOT_FOUND = -1;
// Grant Types
public static final String CODE_GRANT_PATH = "/oauth/authorize";
public static final String CODE_GRANT_RESPONSE_TYPE = "code";
public static final String CODE_GRANT_STATE = "state";
public static final String CODE_GRANT_TYPE = "authorization_code";
public static final String DEVICE_GRANT_TYPE = "device_grant";
public static final String FACEBOOK_GRANT_TYPE = "facebook";
public static final String GOOGLE_GRANT_TYPE = "google";
public static final String PASSWORD_GRANT_TYPE = "password";
public static final String CLIENT_CREDENTIALS_GRANT_TYPE = "client_credentials";
public static final String OAUTH_ONE_GRANT_TYPE = "vimeo_oauth1";
// Endpoints
public static final String ENDPOINT_ME = "me";
public static final String ENDPOINT_RECOMMENDATIONS = "/recommendations";
public static final String ENDPOINT_TERMS_OF_SERVICE = "documents/termsofservice";
public static final String ENDPOINT_PRIVACY_POLICY = "documents/privacy";
public static final String ENDPOINT_PAYMENT_ADDENDUM = "documents/paymentaddendum";
// Parameters
public static final String PARAMETER_REDIRECT_URI = "redirect_uri";
public static final String PARAMETER_RESPONSE_TYPE = "response_type";
public static final String PARAMETER_STATE = "state";
public static final String PARAMETER_SCOPE = "scope";
public static final String PARAMETER_TOKEN = "token";
public static final String PARAMETER_ID_TOKEN = "id_token";
public static final String PARAMETER_CLIENT_ID = "client_id";
public static final String PARAMETER_USERS_NAME = "name";
public static final String PARAMETER_EMAIL = "email";
public static final String PARAMETER_PASSWORD = "password";
public static final String PARAMETER_USERS_LOCATION = "location";
public static final String PARAMETER_USERS_BIO = "bio";
public static final String PARAMETER_MARKETING_OPT_IN = "marketing_opt_in";
public static final String PARAMETER_VIDEO_VIEW = "view";
public static final String PARAMETER_VIDEO_COMMENTS = "comments";
public static final String PARAMETER_VIDEO_EMBED = "embed";
public static final String PARAMETER_VIDEO_DOWNLOAD = "download";
public static final String PARAMETER_VIDEO_ADD = "add";
public static final String PARAMETER_VIDEO_NAME = "name";
public static final String PARAMETER_VIDEO_DESCRIPTION = "description";
public static final String PARAMETER_VIDEO_PRIVACY = "privacy";
public static final String PARAMETER_VIDEO_PASSWORD = "password";
public static final String PARAMETER_ALBUM_NAME = "name";
public static final String PARAMETER_ALBUM_DESCRIPTION = "description";
public static final String PARAMETER_ALBUM_PRIVACY = "privacy";
public static final String PARAMETER_ALBUM_PASSWORD = "password";
public static final String PARAMETER_AUTH_CODE = "auth_code";
public static final String PARAMETER_APP_TYPE = "app_type";
public static final String PARAMETER_COMMENT_TEXT_BODY = "text";
public static final String PARAMETER_ACTIVE = "active";
// Header Parameters
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String HEADER_USER_AGENT = "User-Agent";
public static final String HEADER_ACCEPT = "Accept";
public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language";
// Header Values
public static final String HEADER_CACHE_PUBLIC = "public";
// Video Analytics Parameters
public static final String PARAMETER_SESSION_ID = "session_id";
public static final String PARAMETER_SESSION_TIME = "session_time";
public static final String PARAMETER_VUID = "vuid";
public static final String PARAMETER_LOCALE = "locale";
public static final String PARAMETER_EXIT_WATCHED_TIME = "exit_watched_time_code";
public static final String PARAMETER_FURTHEST_WATCHED_TIME = "furthest_watched_time_code";
public static final String PARAMETER_PROGRESS = "progress";
public static final String PARAMETER_EVENTS = "events";
public static final String PARAMETER_EVENT_TYPE = "type";
public static final String PARAMETER_EVENT_TYPE_WATER_LATER = "watchlater";
public static final String PARAMETER_EVENT_TYPE_LIKE = "like";
public static final String PARAMETER_EVENT_ACTION = "action";
public static final String PARAMETER_EVENT_ACTION_ADDED = "added";
public static final String PARAMETER_EVENT_ACTION_REMOVED = "removed";
// GET and Sorting Parameters
public static final String PARAMETER_GET_PAGE_SIZE = "per_page";
public static final String PARAMETER_GET_QUERY = "query";
public static final String PARAMETER_GET_SORT = "sort";
public static final String PARAMETER_GET_DIRECTION = "direction";
public static final String PARAMETER_GET_FIELD_FILTER = "fields";
public static final String PARAMETER_GET_CONTAINER_FIELD_FILTER = "container_fields";
public static final String PARAMETER_GET_LENGTH_MIN_DURATION = "min_duration";
public static final String PARAMETER_GET_LENGTH_MAX_DURATION = "max_duration";
public static final String PARAMETER_GET_FILTER = "filter";
public static final String PARAMETER_GET_UPLOAD_DATE_FILTER = "filter_upload_date";
public static final String PARAMETER_GET_NOTIFICATION_TYPES_FILTER = "filter_notification_types";
public static final String PARAMETER_PATCH_LATEST_NOTIFICATION_URI = "latest_notification_uri";
// Sorting (sort) Values
public static final String SORT_DEFAULT = "default";
public static final String SORT_RELEVANCE = "relevant";
public static final String SORT_POPULAR = "popularity";
public static final String SORT_DATE = "date";
public static final String SORT_PURCHASE_TIME = "purchase_time";
public static final String SORT_FOLLOWERS = "followers";
public static final String SORT_ALPHABETICAL = "alphabetical";
public static final String SORT_MANUAL = "manual";
public static final String SORT_DURATION = "duration";
public static final String SORT_LAST_USER_ACTION_EVENT_DATE = "last_user_action_event_date";
public static final String SORT_PLAYS = "plays";
public static final String SORT_LIKES = "likes";
public static final String SORT_MODIFIED_TIME = "modified_time";
public static final String SORT_COMMENTS = "comments";
// Sort Direction Values
public static final String SORT_DIRECTION_ASCENDING = "asc";
public static final String SORT_DIRECTION_DESCENDING = "desc";
// Filter (filter) Values
public static final String FILTER_RELATED = "related";
public static final String FILTER_UPLOAD = "upload_date";
public static final String FILTER_VIEWABLE = "viewable";
public static final String FILTER_PLAYABLE = "playable";
public static final String FILTER_TRENDING = "trending";
public static final String FILTER_TVOD_RENTALS = "rented";
public static final String FILTER_TVOD_SUBSCRIPTIONS = "subscription";
public static final String FILTER_TVOD_PURCHASES = "purchased";
public static final String FILTER_NOTIFICATION_TYPES = "notification_types";
// Filter Upload Date Values
public static final String FILTER_UPLOAD_DATE_TODAY = "day";
public static final String FILTER_UPLOAD_DATE_WEEK = "week";
public static final String FILTER_UPLOAD_DATE_MONTH = "month";
public static final String FILTER_UPLOAD_DATE_YEAR = "year";
public static final String PAGE_SIZE_MAX = "100";
public static final String OPTIONS_POST = "POST";
// Fields (for invalid params)
public static final String FIELD_NAME = "name";
public static final String FIELD_EMAIL = "email";
public static final String FIELD_PASSWORD = "password";
public static final String FIELD_TOKEN = "token";
public static final String FIELD_USERNAME = "username";
public enum RefineLength {
ANY,
UNDER_FIVE_MINUTES,
OVER_FIVE_MINUTES
}
public enum RefineSort {
DEFAULT(SORT_DEFAULT),
RELEVANCE(SORT_RELEVANCE),
POPULARITY(SORT_POPULAR),
RECENT(SORT_DATE),
// Channels
FOLLOWERS(SORT_FOLLOWERS),
// Users
AZ(SORT_DIRECTION_ASCENDING),
ZA(SORT_DIRECTION_DESCENDING);
private String mText;
RefineSort(String text) {
this.mText = text;
}
public String getText() {
return this.mText;
}
public static RefineSort fromString(String text) {
if (text != null) {
for (RefineSort b : RefineSort.values()) {
if (text.equalsIgnoreCase(b.mText)) {
return b;
}
}
}
throw new IllegalArgumentException("No constant with mText " + text + " found");
}
}
public enum RefineUploadDate {
ANYTIME(""),
TODAY(FILTER_UPLOAD_DATE_TODAY),
THIS_WEEK(FILTER_UPLOAD_DATE_WEEK),
THIS_MONTH(FILTER_UPLOAD_DATE_MONTH),
THIS_YEAR(FILTER_UPLOAD_DATE_YEAR);
private String mText;
RefineUploadDate(String text) {
this.mText = text;
}
public String getText() {
return this.mText;
}
public static RefineUploadDate fromString(String text) {
if (text != null) {
for (RefineUploadDate b : RefineUploadDate.values()) {
if (text.equalsIgnoreCase(b.mText)) {
return b;
}
}
}
throw new IllegalArgumentException("No constant with mText " + text + " found");
}
}
public enum LogLevel {
// 0 1 2 3
VERBOSE, DEBUG, ERROR, NONE
}
private Vimeo() {
}
}
| Moving notification constants to the Vimeo class where they are better situated
| vimeo-networking/src/main/java/com/vimeo/networking/Vimeo.java | Moving notification constants to the Vimeo class where they are better situated |
|
Java | mit | 570dab32920cf5d21bee822046fd802360271b17 | 0 | kmdouglass/Micro-Manager,kmdouglass/Micro-Manager | ///////////////////////////////////////////////////////////////////////////////
// AUTHOR: Henry Pinkard, [email protected]
//
// COPYRIGHT: University of California, San Francisco, 2015
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
package org.micromanager.plugins.magellan.bidc;
import org.micromanager.plugins.magellan.acq.AcquisitionEvent;
import org.micromanager.plugins.magellan.acq.MagellanEngine;
import org.micromanager.plugins.magellan.acq.MagellanTaggedImage;
import org.micromanager.plugins.magellan.demo.DemoModeImageData;
import ij.IJ;
import java.awt.geom.Point2D;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.micromanager.plugins.magellan.json.JSONException;
import org.micromanager.plugins.magellan.json.JSONObject;
import org.micromanager.plugins.magellan.main.Magellan;
import org.micromanager.plugins.magellan.misc.GlobalSettings;
import org.micromanager.plugins.magellan.misc.Log;
import org.micromanager.plugins.magellan.misc.MD;
import mmcorej.CMMCore;
import mmcorej.TaggedImage;
import org.micromanager.plugins.magellan.acq.Acquisition;
public class JavaLayerImageConstructor {
private static final int IMAGE_CONSTRUCTION_QUEUE_SIZE = 150;
private static final int IMAGE_CONSTRUCTION_THREADS = 5;
private static JavaLayerImageConstructor singleton_;
private static CMMCore core_ = Magellan.getCore();
private ExecutorService imageConstructionExecutor_;
private boolean javaLayerConstruction_ = false;
private volatile AtomicInteger numImagesConstructing_ = new AtomicInteger(0);
private LinkedBlockingQueue<ProtoTaggedImage> imagesToConstruct_ = new LinkedBlockingQueue<ProtoTaggedImage>(IMAGE_CONSTRUCTION_QUEUE_SIZE);
public JavaLayerImageConstructor() {
singleton_ = this;
//start up image construction thread
javaLayerConstruction_ = GlobalSettings.getInstance().isBIDCTwoPhoton();
if (javaLayerConstruction_) {
imageConstructionExecutor_ = Executors.newFixedThreadPool(5, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "Image construction thread");
}
});
}
}
public static JavaLayerImageConstructor getInstance() {
return singleton_;
}
public int getImageWidth() {
return (int) (javaLayerConstruction_ ? RawBufferWrapper.getWidth() : core_.getImageWidth());
}
public int getImageHeight() {
return (int) (javaLayerConstruction_ ? RawBufferWrapper.getHeight() : core_.getImageHeight());
}
public void snapImage() throws Exception {
if (javaLayerConstruction_) {
core_.initializeCircularBuffer();
//clear circular buffer because it is not actuall circular
core_.clearCircularBuffer();
}
core_.snapImage();
}
/**
* need to do this through core communicator so it occurs on the same thread
* as image construction
*/
public void addSignalMagellanTaggedImage(AcquisitionEvent evt, MagellanTaggedImage img) throws InterruptedException {
if (javaLayerConstruction_) {
while (numImagesConstructing_.get() != 0) {
Thread.sleep(5);
}
evt.acquisition_.addImage(img);
} else {
evt.acquisition_.addImage(img);
}
}
/**
* Intercept calls to get tagged image so image can be created in java layer
* Grab raw images from core and insert them into image construction executor
* for processing return immediately if theres space in processing queue so
* acq can continue, otherwise block until space opens up so acq doesnt try
* to go way faster than images can be constructed
*
*/
public void getMagellanTaggedImagesAndAddToAcq(AcquisitionEvent event, final long currentTime) throws Exception {
if (javaLayerConstruction_) {
//Images go into circular buffer one channel at a time followed by succsessive frames
//want to change the order to all frames of a channel at a time
int numFrames = 1;
try {
numFrames = (int) core_.getExposure();
} catch (Exception e) {
IJ.log("Couldnt get exposure form core");
}
final int numCamChannels = (int) core_.getNumberOfCameraChannels();
//get frames of all channels
final LinkedList<ImageAndInfo> imageList = new LinkedList<ImageAndInfo>();
for (int c = 0; c < core_.getNumberOfCameraChannels(); c++) {
for (int framesBack = numFrames - 1; framesBack >= 0; framesBack--) {
//channel 0 is farthest back
int backIndex = framesBack * numCamChannels + (numCamChannels - 1 - c);
MagellanTaggedImage img = convertTaggedImage(core_.getNBeforeLastTaggedImage(backIndex));
imageList.add(new ImageAndInfo(img, event, numCamChannels, c, currentTime, numFrames, numFrames - 1 - framesBack));
}
numImagesConstructing_.incrementAndGet();
imageConstructionExecutor_.submit(new Runnable() {
@Override
public void run() {
ImageAndInfo firstIAI = imageList.getFirst();
//Create appropriate image construction class
final FrameIntegrationMethod integrator;
if (firstIAI.event_.acquisition_.getFilterType() == FrameIntegrationMethod.FRAME_AVERAGE) {
integrator = new FrameAverageWrapper(GlobalSettings.getInstance().getChannelOffset(firstIAI.camChannelIndex_),
MD.getWidth(firstIAI.img_.tags), firstIAI.numFrames_);
} else if (firstIAI.event_.acquisition_.getFilterType() == FrameIntegrationMethod.RANK_FILTER) {
integrator = new RankFilterWrapper(GlobalSettings.getInstance().getChannelOffset(firstIAI.camChannelIndex_),
MD.getWidth(firstIAI.img_.tags), firstIAI.numFrames_, firstIAI.event_.acquisition_.getRank());
} else { //frame summation
integrator = new FrameSummationWrapper(GlobalSettings.getInstance().getChannelOffset(firstIAI.camChannelIndex_),
MD.getWidth(firstIAI.img_.tags), firstIAI.numFrames_);
}
//add frames to integrator
for (int i = 0; i < firstIAI.numFrames_; i++) {
integrator.addBuffer((byte[]) imageList.removeFirst().img_.pix);
}
//add metadata
MD.setWidth(firstIAI.img_.tags, integrator.getConstructedImageWidth());
MD.setHeight(firstIAI.img_.tags, integrator.getConstructedImageHeight());
if (integrator instanceof FrameSummationWrapper) {
MD.setPixelTypeFromByteDepth(firstIAI.img_.tags, 2);
}
MagellanEngine.addImageMetadata(firstIAI.img_.tags, firstIAI.event_, firstIAI.event_.timeIndex_,
firstIAI.camChannelIndex_, firstIAI.currentTime_ - firstIAI.event_.acquisition_.getStartTime_ms(),
firstIAI.numFrames_);
new ProtoTaggedImage(integrator, firstIAI.img_.tags, firstIAI.event_.acquisition_).integrateAndAddToAcq();
numImagesConstructing_.decrementAndGet();
}
});
}
} else if (GlobalSettings.getInstance().getDemoMode()) {
//add demo image
for (int c = 0; c < DemoModeImageData.getNumChannels(); c++) {
JSONObject tags = convertTaggedImage(core_.getTaggedImage()).tags;
MD.setChannelIndex(tags, c);
MagellanEngine.addImageMetadata(tags, event, event.timeIndex_, c, currentTime - event.acquisition_.getStartTime_ms(), 1);
event.acquisition_.addImage(makeDemoImage(c, event.xyPosition_.getCenter(), event.zPosition_, tags));
}
} else {
for (int c = 0; c < core_.getNumberOfCameraChannels(); c++) {
MagellanTaggedImage img = convertTaggedImage(core_.getTaggedImage(c));
MagellanEngine.addImageMetadata(img.tags, event, event.timeIndex_, c, currentTime - event.acquisition_.getStartTime_ms(), 1);
event.acquisition_.addImage(img);
}
}
}
private MagellanTaggedImage makeDemoImage(int camChannelIndex, Point2D.Double position, double zPos, JSONObject tags) {
Object demoPix;
try {
demoPix = DemoModeImageData.getBytePixelData(camChannelIndex, (int) position.x,
(int) position.y, (int) zPos, MD.getWidth(tags), MD.getHeight(tags));
return new MagellanTaggedImage(demoPix, tags);
} catch (Exception e) {
e.printStackTrace();
Log.log("Problem getting demo data");
throw new RuntimeException();
}
}
public static MagellanTaggedImage convertTaggedImage(TaggedImage img) {
try {
return new MagellanTaggedImage(img.pix, new JSONObject(img.tags.toString()));
} catch (JSONException ex) {
Log.log("Couldn't convert JSON metadata");
throw new RuntimeException();
}
}
class ProtoTaggedImage {
FrameIntegrationMethod integrator_;
JSONObject md_;
Acquisition acq_;
public ProtoTaggedImage(FrameIntegrationMethod integrator, JSONObject md, Acquisition acq) {
integrator_ = integrator;
md_ = md;
acq_ = acq;
}
void integrateAndAddToAcq() {
acq_.addImage(new MagellanTaggedImage(integrator_.constructImage(), md_));
}
}
class ImageAndInfo {
MagellanTaggedImage img_;
AcquisitionEvent event_;
int numCamChannels_;
int camChannelIndex_;
long currentTime_;
int numFrames_;
int frameNumber_;
public ImageAndInfo(MagellanTaggedImage img, AcquisitionEvent e, int numCamChannels, int cameraChannelIndex, long currentTime,
int numFrames, int frameNumber) {
img_ = img;
event_ = e;
numCamChannels_ = numCamChannels;
camChannelIndex_ = cameraChannelIndex;
currentTime_ = currentTime;
numFrames_ = numFrames;
frameNumber_ = frameNumber;
}
}
}
| plugins/Magellan/src/org/micromanager/plugins/magellan/bidc/JavaLayerImageConstructor.java | ///////////////////////////////////////////////////////////////////////////////
// AUTHOR: Henry Pinkard, [email protected]
//
// COPYRIGHT: University of California, San Francisco, 2015
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
package org.micromanager.plugins.magellan.bidc;
import org.micromanager.plugins.magellan.acq.AcquisitionEvent;
import org.micromanager.plugins.magellan.acq.MagellanEngine;
import org.micromanager.plugins.magellan.acq.MagellanTaggedImage;
import org.micromanager.plugins.magellan.demo.DemoModeImageData;
import ij.IJ;
import java.awt.geom.Point2D;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import org.micromanager.plugins.magellan.json.JSONException;
import org.micromanager.plugins.magellan.json.JSONObject;
import org.micromanager.plugins.magellan.main.Magellan;
import org.micromanager.plugins.magellan.misc.GlobalSettings;
import org.micromanager.plugins.magellan.misc.Log;
import org.micromanager.plugins.magellan.misc.MD;
import mmcorej.CMMCore;
import mmcorej.TaggedImage;
import org.micromanager.plugins.magellan.acq.Acquisition;
public class JavaLayerImageConstructor {
private static final int IMAGE_CONSTRUCTION_QUEUE_SIZE = 150;
private static final int IMAGE_CONSTRUCTION_THREADS = 5;
private static JavaLayerImageConstructor singleton_;
private static CMMCore core_ = Magellan.getCore();
private ExecutorService imageConstructionExecutor_;
private boolean javaLayerConstruction_ = false;
private volatile boolean imageConstructing_ = false;
private LinkedBlockingQueue<ProtoTaggedImage> imagesToConstruct_ = new LinkedBlockingQueue<ProtoTaggedImage>(IMAGE_CONSTRUCTION_QUEUE_SIZE);
public JavaLayerImageConstructor() {
singleton_ = this;
//start up image construction thread
javaLayerConstruction_ = GlobalSettings.getInstance().isBIDCTwoPhoton();
if (javaLayerConstruction_) {
imageConstructionExecutor_ = Executors.newFixedThreadPool(5, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "Image construction thread");
}
});
}
}
public static JavaLayerImageConstructor getInstance() {
return singleton_;
}
public int getImageWidth() {
return (int) (javaLayerConstruction_ ? RawBufferWrapper.getWidth() : core_.getImageWidth());
}
public int getImageHeight() {
return (int) (javaLayerConstruction_ ? RawBufferWrapper.getHeight() : core_.getImageHeight());
}
public void snapImage() throws Exception {
if (javaLayerConstruction_) {
core_.initializeCircularBuffer();
//clear circular buffer because it is not actuall circular
core_.clearCircularBuffer();
}
core_.snapImage();
}
/**
* need to do this through core communicator so it occurs on the same thread
* as image construction
*/
public void addSignalMagellanTaggedImage(AcquisitionEvent evt, MagellanTaggedImage img) throws InterruptedException {
if (javaLayerConstruction_) {
while (imageConstructing_) {
Thread.sleep(5);
}
evt.acquisition_.addImage(img);
} else {
evt.acquisition_.addImage(img);
}
}
/**
* Intercept calls to get tagged image so image can be created in java layer
* Grab raw images from core and insert them into image construction executor
* for processing return immediately if theres space in processing queue so
* acq can continue, otherwise block until space opens up so acq doesnt try
* to go way faster than images can be constructed
*
*/
public void getMagellanTaggedImagesAndAddToAcq(AcquisitionEvent event, final long currentTime) throws Exception {
if (javaLayerConstruction_) {
//Images go into circular buffer one channel at a time followed by succsessive frames
//want to change the order to all frames of a channel at a time
int numFrames = 1;
try {
numFrames = (int) core_.getExposure();
} catch (Exception e) {
IJ.log("Couldnt get exposure form core");
}
final int numCamChannels = (int) core_.getNumberOfCameraChannels();
//get frames of all channels
LinkedList<ImageAndInfo> imageList = new LinkedList<ImageAndInfo>();
for (int c = 0; c < core_.getNumberOfCameraChannels(); c++) {
for (int framesBack = numFrames - 1; framesBack >= 0; framesBack--) {
//channel 0 is farthest back
int backIndex = framesBack * numCamChannels + (numCamChannels - 1 - c);
MagellanTaggedImage img = convertTaggedImage(core_.getNBeforeLastTaggedImage(backIndex));
imageList.add(new ImageAndInfo(img, event, numCamChannels, c, currentTime, numFrames, numFrames - 1 - framesBack));
}
final ImageAndInfo firstIAI = imageList.getFirst();
//Create appropriate image construction class
final FrameIntegrationMethod integrator;
if (firstIAI.event_.acquisition_.getFilterType() == FrameIntegrationMethod.FRAME_AVERAGE) {
integrator = new FrameAverageWrapper(GlobalSettings.getInstance().getChannelOffset(firstIAI.camChannelIndex_),
MD.getWidth(firstIAI.img_.tags), firstIAI.numFrames_);
} else if (firstIAI.event_.acquisition_.getFilterType() == FrameIntegrationMethod.RANK_FILTER) {
integrator = new RankFilterWrapper(GlobalSettings.getInstance().getChannelOffset(firstIAI.camChannelIndex_),
MD.getWidth(firstIAI.img_.tags), firstIAI.numFrames_, firstIAI.event_.acquisition_.getRank());
} else { //frame summation
integrator = new FrameSummationWrapper(GlobalSettings.getInstance().getChannelOffset(firstIAI.camChannelIndex_),
MD.getWidth(firstIAI.img_.tags), firstIAI.numFrames_);
}
//add frames to integrator
for (int i = 0; i < firstIAI.numFrames_; i++) {
integrator.addBuffer((byte[]) imageList.removeFirst().img_.pix);
}
//add metadata
MD.setWidth(firstIAI.img_.tags, integrator.getConstructedImageWidth());
MD.setHeight(firstIAI.img_.tags, integrator.getConstructedImageHeight());
if (integrator instanceof FrameSummationWrapper) {
MD.setPixelTypeFromByteDepth(firstIAI.img_.tags, 2);
}
MagellanEngine.addImageMetadata(firstIAI.img_.tags, firstIAI.event_, firstIAI.event_.timeIndex_,
firstIAI.camChannelIndex_, firstIAI.currentTime_ - firstIAI.event_.acquisition_.getStartTime_ms(),
firstIAI.numFrames_);
imageConstructing_ = true;
imageConstructionExecutor_.submit(new Runnable() {
@Override
public void run() {
new ProtoTaggedImage(integrator, firstIAI.img_.tags,firstIAI.event_.acquisition_).integrateAndAddToAcq();
imageConstructing_ = false;
}
});
}
} else if (GlobalSettings.getInstance().getDemoMode()) {
//add demo image
for (int c = 0; c < DemoModeImageData.getNumChannels(); c++) {
JSONObject tags = convertTaggedImage(core_.getTaggedImage()).tags;
MD.setChannelIndex(tags, c);
MagellanEngine.addImageMetadata(tags, event, event.timeIndex_, c, currentTime - event.acquisition_.getStartTime_ms(), 1);
event.acquisition_.addImage(makeDemoImage(c, event.xyPosition_.getCenter(), event.zPosition_, tags));
}
} else {
for (int c = 0; c < core_.getNumberOfCameraChannels(); c++) {
MagellanTaggedImage img = convertTaggedImage(core_.getTaggedImage(c));
MagellanEngine.addImageMetadata(img.tags, event, event.timeIndex_, c, currentTime - event.acquisition_.getStartTime_ms(), 1);
event.acquisition_.addImage(img);
}
}
}
private MagellanTaggedImage makeDemoImage(int camChannelIndex, Point2D.Double position, double zPos, JSONObject tags) {
Object demoPix;
try {
demoPix = DemoModeImageData.getBytePixelData(camChannelIndex, (int) position.x,
(int) position.y, (int) zPos, MD.getWidth(tags), MD.getHeight(tags));
return new MagellanTaggedImage(demoPix, tags);
} catch (Exception e) {
e.printStackTrace();
Log.log("Problem getting demo data");
throw new RuntimeException();
}
}
public static MagellanTaggedImage convertTaggedImage(TaggedImage img) {
try {
return new MagellanTaggedImage(img.pix, new JSONObject(img.tags.toString()));
} catch (JSONException ex) {
Log.log("Couldn't convert JSON metadata");
throw new RuntimeException();
}
}
class ProtoTaggedImage {
FrameIntegrationMethod integrator_;
JSONObject md_;
Acquisition acq_;
public ProtoTaggedImage(FrameIntegrationMethod integrator, JSONObject md, Acquisition acq) {
integrator_ = integrator;
md_ = md;
acq_ = acq;
}
void integrateAndAddToAcq() {
acq_.addImage(new MagellanTaggedImage(integrator_.constructImage(), md_));
}
}
class ImageAndInfo {
MagellanTaggedImage img_;
AcquisitionEvent event_;
int numCamChannels_;
int camChannelIndex_;
long currentTime_;
int numFrames_;
int frameNumber_;
public ImageAndInfo(MagellanTaggedImage img, AcquisitionEvent e, int numCamChannels, int cameraChannelIndex, long currentTime,
int numFrames, int frameNumber) {
img_ = img;
event_ = e;
numCamChannels_ = numCamChannels;
camChannelIndex_ = cameraChannelIndex;
currentTime_ = currentTime;
numFrames_ = numFrames;
frameNumber_ = frameNumber;
}
}
}
| correct logic for monitoring when multithreaded image construction
git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@16324 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd
| plugins/Magellan/src/org/micromanager/plugins/magellan/bidc/JavaLayerImageConstructor.java | correct logic for monitoring when multithreaded image construction |
|
Java | mit | 619191948d6c5b3e5de98ae4e94cb6b8c5b0b093 | 0 | eraether/WatchWordBot | package com.raether.watchwordbot;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BuildableWatchWordGrid {
private List<String> words;
private List<Faction> owners;
private int width;
private int height;
public BuildableWatchWordGrid(List<String> words, int width, int height) {
setWords(words);
this.width = width;
this.height = height;
}
private BuildableWatchWordGrid setWords(List<String> words) {
this.words = words;
this.owners = new ArrayList<>();
for (int x = 0; x < words.size(); x++) {
this.owners.add(null);
}
return this;
}
public void randomlyAssign(Faction faction, int count,
Random rand) {
List<Integer> unassignedTileIndicies = getUnassignedTileIndices();
for (int i = 0; i < count; i++) {
int randomIndex = rand.nextInt(unassignedTileIndicies.size());
int index = unassignedTileIndicies.get(randomIndex);
unassignedTileIndicies.remove(randomIndex);
owners.set(index, faction);
}
}
private List<Integer> getUnassignedTileIndices() {
List<Integer> ints = new ArrayList<>();
for (int x = 0; x < owners.size(); x++) {
if (owners.get(x) == null) {
ints.add(x);
}
}
return ints;
}
public BuildableWatchWordGrid fillRemainder(Faction faction) {
for (Integer index : getUnassignedTileIndices()) {
owners.set(index, faction);
}
return this;
}
public WatchWordGrid build() {
List<WordTile> wordTiles = new ArrayList<>();
for (int x = 0; x < words.size(); x++) {
String word = words.get(x);
Faction faction = owners.get(x);
WordTile tile = new WordTile(word, faction, false);
wordTiles.add(tile);
}
return new WatchWordGrid(wordTiles, this.width, this.height);
}
} | src/main/java/com/raether/watchwordbot/BuildableWatchWordGrid.java | package com.raether.watchwordbot;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BuildableWatchWordGrid {
private List<String> words;
private List<Faction> owners;
private int width;
private int height;
public BuildableWatchWordGrid(List<String> words, int width, int height) {
setWords(words);
this.width = width;
this.height = height;
}
private BuildableWatchWordGrid setWords(List<String> words) {
this.words = words;
this.owners = new ArrayList<>();
for (int x = 0; x < words.size(); x++) {
this.owners.add(null);
}
return this;
}
public void randomlyAssign(Faction faction, int count,
Random rand) {
List<Integer> unassignedTileIndicies = getUnassignedTileIndices();
for (int i = 0; i < count; i++) {
int randomIndex = rand.nextInt(unassignedTileIndicies.size());
int index = unassignedTileIndicies.get(randomIndex);
unassignedTileIndicies.remove(randomIndex);
owners.set(index, faction);
}
}
private List<Integer> getUnassignedTileIndices() {
List<Integer> ints = new ArrayList<>();
for (int x = 0; x < owners.size(); x++) {
if (owners.get(x) == null) {
ints.add(x);
}
}
return ints;
}
public BuildableWatchWordGrid fillRemainder(Faction faction) {
for (Integer index : getUnassignedTileIndices()) {
owners.set(index, faction);
}
return this;
}
WatchWordGrid build() {
List<WordTile> wordTiles = new ArrayList<>();
for (int x = 0; x < words.size(); x++) {
String word = words.get(x);
Faction faction = owners.get(x);
WordTile tile = new WordTile(word, faction, false);
wordTiles.add(tile);
}
return new WatchWordGrid(wordTiles, this.width, this.height);
}
} | Add in public modifiers / fix typo
| src/main/java/com/raether/watchwordbot/BuildableWatchWordGrid.java | Add in public modifiers / fix typo |
|
Java | mit | 3093976821dd20d7862acd57b87ef4c982596110 | 0 | LeoIsasmendi/SuricatePodcast | /*
* The MIT License (MIT)
* Copyright (c) 2016. Sergio Leonardo Isasmendi
*
* 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 leoisasmendi.android.com.suricatepodcast;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.LauncherActivity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import java.util.Iterator;
import leoisasmendi.android.com.suricatepodcast.data.ItemLoader;
import leoisasmendi.android.com.suricatepodcast.data.ItemsContract;
import leoisasmendi.android.com.suricatepodcast.data.Playlist;
import leoisasmendi.android.com.suricatepodcast.data.PlaylistItem;
import leoisasmendi.android.com.suricatepodcast.data.PodcastsDataSource;
import leoisasmendi.android.com.suricatepodcast.data.SearchItem;
import leoisasmendi.android.com.suricatepodcast.data.SearchList;
import leoisasmendi.android.com.suricatepodcast.parcelable.EpisodeParcelable;
import leoisasmendi.android.com.suricatepodcast.provider.DataProvider;
import leoisasmendi.android.com.suricatepodcast.services.MediaPlayerService;
import leoisasmendi.android.com.suricatepodcast.ui.AboutFragment;
import leoisasmendi.android.com.suricatepodcast.ui.DetailFragment;
import leoisasmendi.android.com.suricatepodcast.ui.MainFragment;
import leoisasmendi.android.com.suricatepodcast.ui.SearchFragment;
import leoisasmendi.android.com.suricatepodcast.ui.ThemesFragment;
import leoisasmendi.android.com.suricatepodcast.utils.StorageUtil;
public class MainActivity extends AppCompatActivity implements MainFragment.OnMainListInteractionListener, SearchFragment.OnFragmentInteractionListener, LoaderManager.LoaderCallbacks<Cursor> {
final String TAG = getClass().getSimpleName();
private static final String TAG_MAIN = MainFragment.class.getSimpleName();
private static final String TAG_DETAIL = DetailFragment.class.getSimpleName();
private static final String TAG_SEARCH = SearchFragment.class.getSimpleName();
private static final String TAG_ABOUT = AboutFragment.class.getSimpleName();
private static final String TAG_THEMES = ThemesFragment.class.getSimpleName();
public static final String Broadcast_PLAY_NEW_AUDIO = "leoisasmendi.android.com.suricatepodcast.PlayNewAudio";
private FragmentManager fragmentManager;
private boolean mTwoPane;
//List of available Audio files
private Playlist playlist;
//List of selected items on SearchView
private SearchList selectedItems;
// MEDIA PLAYER
private MediaPlayerService player;
boolean serviceBound = false;
private ServiceConnection serviceConnection;
// ADS MOB
InterstitialAd mInterstitialAd;
public static final String ACTION_DATA_UPDATED = "leoisasmendi.android.com.suricatepodcast.app.ACTION_DATA_UPDATED";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
fragmentManager = getFragmentManager();
loadFragment(savedInstanceState);
//Binding this Client to the AudioPlayer Service
serviceConnection = getServiceConnection();
// Iniciar loader
getSupportLoaderManager().restartLoader(1, null, this);
}
private ServiceConnection getServiceConnection() {
return new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
Toast.makeText(MainActivity.this, "Service Bound", Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
}
private void loadAds() {
AdRequest adRequest = getAdRequestObject();
// Load ads into Interstitial Ads
mInterstitialAd.loadAd(adRequest);
}
private AdRequest getAdRequestObject() {
return new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// Check the LogCat to get your test device ID
.addTestDevice(getString(R.string.testDeviceAdsId))
.build();
}
private void showAds() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
loadAds();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuOp1:
showThemes();
return true;
case R.id.menuOp2:
showAbout();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void showThemes() {
showAds();
ThemesFragment themes = (ThemesFragment) fragmentManager.findFragmentByTag(TAG_THEMES);
if (themes == null) {
themes = new ThemesFragment();
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main, themes);
fragmentTransaction.addToBackStack(TAG_THEMES);
fragmentTransaction.commit();
}
private void showAbout() {
showAds();
AboutFragment about = (AboutFragment) fragmentManager.findFragmentByTag(TAG_ABOUT);
if (about == null) {
about = new AboutFragment();
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main, about);
fragmentTransaction.addToBackStack(TAG_ABOUT);
fragmentTransaction.commit();
}
@Override
protected void onResume() {
super.onResume();
}
private void loadFragment(Bundle savedInstanceState) {
if (findViewById(R.id.podcast_second_container) != null) {
// The detail container view will be present only in the large-screen layouts
// (res/layout-sw600dp). If this view is present, then the activity should be
// in two-pane mode.
mTwoPane = true;
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
if (savedInstanceState == null) {
fragmentManager.beginTransaction()
.replace(R.id.podcast_second_container, new DetailFragment(), TAG_DETAIL)
.commit();
}
} else {
mTwoPane = false;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MainFragment mainFragment = new MainFragment();
fragmentTransaction.replace(R.id.activity_main, mainFragment, TAG_MAIN);
fragmentTransaction.commit();
}
}
private void showSearchFragment() {
SearchFragment searchFragment = (SearchFragment) fragmentManager.findFragmentByTag(TAG_SEARCH);
if (searchFragment == null) {
searchFragment = new SearchFragment();
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (mTwoPane) {
fragmentTransaction.replace(R.id.podcast_second_container, searchFragment, TAG_SEARCH);
} else {
fragmentTransaction.replace(R.id.activity_main, searchFragment);
}
fragmentTransaction.addToBackStack(TAG_SEARCH);
fragmentTransaction.commit();
}
private void showDetailFragment(EpisodeParcelable parcelable) {
DetailFragment detailFragment = (DetailFragment) fragmentManager.findFragmentByTag(TAG_DETAIL);
if (detailFragment == null) {
detailFragment = new DetailFragment();
Bundle mBundle = new Bundle();
mBundle.putParcelable("EXTRA_EPISODE", parcelable);
detailFragment.setArguments(mBundle);
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main, detailFragment);
fragmentTransaction.addToBackStack(TAG_DETAIL);
fragmentTransaction.commit();
}
// SET ACTION BAR TITLE
public void setActionBarTitle(int resourceId) {
getSupportActionBar().setTitle(resourceId);
}
// SEARCH BUTTON
public void doSearch(View v) {
Log.d(TAG, "doSearch: ");
selectedItems = new SearchList();
showSearchFragment();
}
// SEARCH BUTTON
public void addSelectedItemsToPlaylist(View v) {
Log.d(TAG, "addSelectedItemsToPlaylist: ");
if (selectedItems.size() > 0) {
ContentValues aValue;
for (PlaylistItem item : selectedItems) {
Cursor c = getContentResolver().query(DataProvider.CONTENT_URI,
null,
ItemsContract.Items.ID_PODCAST + " = " + item.getId(),
null,
null);
if (c.getCount() == 0) {
// not found in database
aValue = new ContentValues();
aValue.put(ItemsContract.Items.ID_PODCAST, item.getId());
aValue.put(ItemsContract.Items.TITLE, item.getTitle());
aValue.put(ItemsContract.Items.DURATION, item.getDuration());
aValue.put(ItemsContract.Items.AUDIO, item.getAudio());
aValue.put(ItemsContract.Items.POSTER, item.getPoster());
getContentResolver().insert(DataProvider.CONTENT_URI, aValue);
}
}
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("ServiceState", serviceBound);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
serviceBound = savedInstanceState.getBoolean("ServiceState");
}
@Override
protected void onDestroy() {
super.onDestroy();
if (serviceBound) {
unbindService(serviceConnection);
//service is active
player.stopSelf();
}
}
private void playAudio(int audioIndex) {
//Check is service is active
if (!serviceBound) {
//Store Serializable audioList to SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeAudio(playlist);
storage.storeAudioIndex(audioIndex);
Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
//Store the new audioIndex to SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeAudioIndex(audioIndex);
//Service is active
//Send a broadcast to the service -> PLAY_NEW_AUDIO
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);
}
}
// INTERFACES
@Override
public void onLongClickFragmentInteraction(Cursor item) {
Log.i(TAG, "onLongClickFragmentInteraction: show detail fragment" + item.getString(ItemLoader.Query.TITLE));
EpisodeParcelable parcelable = new EpisodeParcelable();
parcelable.setId(item.getInt(ItemLoader.Query.ID_PODCAST));
parcelable.setTitle(item.getString(ItemLoader.Query.TITLE));
parcelable.setDuration(item.getString(ItemLoader.Query.DURATION));
parcelable.setPoster(item.getString(ItemLoader.Query.POSTER));
showDetailFragment(parcelable);
}
@Override
public void onClickFragmentInteraction(int position) {
Log.d(TAG, "onClickFragmentInteraction: playlist item pressed " + position);
this.playAudio(position);
}
@Override
public void updateSelectedList(SearchItem item) {
Log.d(TAG, "updateSelectedList: " + item.getTitle());
if (item.getSelected()) {
if (!selectedItems.contains(item)) {
Log.d(TAG, "updateSelectedList: ADDED");
selectedItems.add(item);
}
} else {
Log.d(TAG, "updateSelectedList: REMOVED");
selectedItems.remove(item);
}
Log.d(TAG, "updateSelectedList: LIST " + selectedItems.size());
}
// Cursor loader
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader: ");
return new CursorLoader(this, DataProvider.CONTENT_URI, null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//TODO: REACTOR THIS NONSENSE
if (playlist == null) {
playlist = new Playlist();
}
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
playlist.add(new PlaylistItem(data.getInt(ItemLoader.Query.ID_PODCAST),
data.getString(ItemLoader.Query.TITLE),
data.getString(ItemLoader.Query.DURATION),
data.getString(ItemLoader.Query.AUDIO),
data.getString(ItemLoader.Query.POSTER)));
}
MainFragment mainFragment = (MainFragment) fragmentManager.findFragmentByTag(TAG_MAIN);
data.moveToFirst();
mainFragment.updateAdaptor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
} | SuricatePodcast/app/src/main/java/leoisasmendi/android/com/suricatepodcast/MainActivity.java | /*
* The MIT License (MIT)
* Copyright (c) 2016. Sergio Leonardo Isasmendi
*
* 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 leoisasmendi.android.com.suricatepodcast;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import leoisasmendi.android.com.suricatepodcast.data.ItemLoader;
import leoisasmendi.android.com.suricatepodcast.data.ItemsContract;
import leoisasmendi.android.com.suricatepodcast.data.Playlist;
import leoisasmendi.android.com.suricatepodcast.data.PlaylistItem;
import leoisasmendi.android.com.suricatepodcast.data.SearchItem;
import leoisasmendi.android.com.suricatepodcast.data.SearchList;
import leoisasmendi.android.com.suricatepodcast.parcelable.EpisodeParcelable;
import leoisasmendi.android.com.suricatepodcast.provider.DataProvider;
import leoisasmendi.android.com.suricatepodcast.services.MediaPlayerService;
import leoisasmendi.android.com.suricatepodcast.ui.AboutFragment;
import leoisasmendi.android.com.suricatepodcast.ui.DetailFragment;
import leoisasmendi.android.com.suricatepodcast.ui.MainFragment;
import leoisasmendi.android.com.suricatepodcast.ui.SearchFragment;
import leoisasmendi.android.com.suricatepodcast.ui.ThemesFragment;
import leoisasmendi.android.com.suricatepodcast.utils.StorageUtil;
public class MainActivity extends AppCompatActivity implements MainFragment.OnMainListInteractionListener, SearchFragment.OnFragmentInteractionListener, LoaderManager.LoaderCallbacks<Cursor> {
final String TAG = getClass().getSimpleName();
private static final String TAG_MAIN = MainFragment.class.getSimpleName();
private static final String TAG_DETAIL = DetailFragment.class.getSimpleName();
private static final String TAG_SEARCH = SearchFragment.class.getSimpleName();
private static final String TAG_ABOUT = AboutFragment.class.getSimpleName();
private static final String TAG_THEMES = ThemesFragment.class.getSimpleName();
public static final String Broadcast_PLAY_NEW_AUDIO = "leoisasmendi.android.com.suricatepodcast.PlayNewAudio";
private FragmentManager fragmentManager;
private boolean mTwoPane;
//List of available Audio files
private Playlist playlist;
//List of selected items on SearchView
private SearchList selectedItems;
// MEDIA PLAYER
private MediaPlayerService player;
boolean serviceBound = false;
private ServiceConnection serviceConnection;
// ADS MOB
InterstitialAd mInterstitialAd;
public static final String ACTION_DATA_UPDATED = "leoisasmendi.android.com.suricatepodcast.app.ACTION_DATA_UPDATED";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
fragmentManager = getFragmentManager();
loadFragment(savedInstanceState);
//Binding this Client to the AudioPlayer Service
serviceConnection = getServiceConnection();
// Iniciar loader
getSupportLoaderManager().restartLoader(1, null, this);
}
private ServiceConnection getServiceConnection() {
return new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
Toast.makeText(MainActivity.this, "Service Bound", Toast.LENGTH_SHORT).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
}
private void loadAds() {
AdRequest adRequest = getAdRequestObject();
// Load ads into Interstitial Ads
mInterstitialAd.loadAd(adRequest);
}
private AdRequest getAdRequestObject() {
return new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// Check the LogCat to get your test device ID
.addTestDevice(getString(R.string.testDeviceAdsId))
.build();
}
private void showAds() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
loadAds();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuOp1:
showThemes();
return true;
case R.id.menuOp2:
showAbout();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void showThemes() {
showAds();
ThemesFragment themes = (ThemesFragment) fragmentManager.findFragmentByTag(TAG_THEMES);
if (themes == null) {
themes = new ThemesFragment();
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main, themes);
fragmentTransaction.addToBackStack(TAG_THEMES);
fragmentTransaction.commit();
}
private void showAbout() {
showAds();
AboutFragment about = (AboutFragment) fragmentManager.findFragmentByTag(TAG_ABOUT);
if (about == null) {
about = new AboutFragment();
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main, about);
fragmentTransaction.addToBackStack(TAG_ABOUT);
fragmentTransaction.commit();
}
@Override
protected void onResume() {
super.onResume();
}
private void loadFragment(Bundle savedInstanceState) {
if (findViewById(R.id.podcast_second_container) != null) {
// The detail container view will be present only in the large-screen layouts
// (res/layout-sw600dp). If this view is present, then the activity should be
// in two-pane mode.
mTwoPane = true;
// In two-pane mode, show the detail view in this activity by
// adding or replacing the detail fragment using a
// fragment transaction.
if (savedInstanceState == null) {
fragmentManager.beginTransaction()
.replace(R.id.podcast_second_container, new DetailFragment(), TAG_DETAIL)
.commit();
}
} else {
mTwoPane = false;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MainFragment mainFragment = new MainFragment();
fragmentTransaction.replace(R.id.activity_main, mainFragment, TAG_MAIN);
fragmentTransaction.commit();
}
}
private void showSearchFragment() {
SearchFragment searchFragment = (SearchFragment) fragmentManager.findFragmentByTag(TAG_SEARCH);
if (searchFragment == null) {
searchFragment = new SearchFragment();
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (mTwoPane) {
fragmentTransaction.replace(R.id.podcast_second_container, searchFragment, TAG_SEARCH);
} else {
fragmentTransaction.replace(R.id.activity_main, searchFragment);
}
fragmentTransaction.addToBackStack(TAG_SEARCH);
fragmentTransaction.commit();
}
private void showDetailFragment(EpisodeParcelable parcelable) {
DetailFragment detailFragment = (DetailFragment) fragmentManager.findFragmentByTag(TAG_DETAIL);
if (detailFragment == null) {
detailFragment = new DetailFragment();
Bundle mBundle = new Bundle();
mBundle.putParcelable("EXTRA_EPISODE", parcelable);
detailFragment.setArguments(mBundle);
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main, detailFragment);
fragmentTransaction.addToBackStack(TAG_DETAIL);
fragmentTransaction.commit();
}
// SET ACTION BAR TITLE
public void setActionBarTitle(int resourceId) {
getSupportActionBar().setTitle(resourceId);
}
// SEARCH BUTTON
public void doSearch(View v) {
Log.d(TAG, "doSearch: ");
selectedItems = new SearchList();
showSearchFragment();
}
// SEARCH BUTTON
public void addSelectedItemsToPlaylist(View v) {
Log.d(TAG, "addSelectedItemsToPlaylist: ");
// Uri uri = getContentResolver().insert(
// DataProvider.CONTENT_URI, aValue);
//
// Toast.makeText(getBaseContext(),
// uri.toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("ServiceState", serviceBound);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
serviceBound = savedInstanceState.getBoolean("ServiceState");
}
@Override
protected void onDestroy() {
super.onDestroy();
if (serviceBound) {
unbindService(serviceConnection);
//service is active
player.stopSelf();
}
}
private void playAudio(int audioIndex) {
//Check is service is active
if (!serviceBound) {
//Store Serializable audioList to SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeAudio(playlist);
storage.storeAudioIndex(audioIndex);
Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
//Store the new audioIndex to SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeAudioIndex(audioIndex);
//Service is active
//Send a broadcast to the service -> PLAY_NEW_AUDIO
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);
}
}
// INTERFACES
@Override
public void onLongClickFragmentInteraction(Cursor item) {
Log.i(TAG, "onLongClickFragmentInteraction: show detail fragment" + item.getString(ItemLoader.Query.TITLE));
EpisodeParcelable parcelable = new EpisodeParcelable();
parcelable.setId(item.getInt(ItemLoader.Query.ID_PODCAST));
parcelable.setTitle(item.getString(ItemLoader.Query.TITLE));
parcelable.setDuration(item.getString(ItemLoader.Query.DURATION));
parcelable.setPoster(item.getString(ItemLoader.Query.POSTER));
showDetailFragment(parcelable);
}
@Override
public void onClickFragmentInteraction(int position) {
Log.d(TAG, "onClickFragmentInteraction: playlist item pressed " + position);
this.playAudio(position);
}
@Override
public void updateSelectedList(SearchItem item) {
Log.d(TAG, "updateSelectedList: " + item.getTitle());
if (item.getSelected()) {
if (!selectedItems.contains(item)) {
Log.d(TAG, "updateSelectedList: ADDED");
selectedItems.add(item);
}
} else {
Log.d(TAG, "updateSelectedList: REMOVED");
selectedItems.remove(item);
}
Log.d(TAG, "updateSelectedList: LIST " + selectedItems.size());
}
// Cursor loader
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.d(TAG, "onCreateLoader: ");
return new CursorLoader(this, DataProvider.CONTENT_URI, null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//TODO: REACTOR THIS NONSENSE
if (playlist == null) {
playlist = new Playlist();
}
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
playlist.add(new PlaylistItem(data.getInt(ItemLoader.Query.ID_PODCAST),
data.getString(ItemLoader.Query.TITLE),
data.getString(ItemLoader.Query.DURATION),
data.getString(ItemLoader.Query.AUDIO),
data.getString(ItemLoader.Query.POSTER)));
}
MainFragment mainFragment = (MainFragment) fragmentManager.findFragmentByTag(TAG_MAIN);
data.moveToFirst();
mainFragment.updateAdaptor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
} | Fixed adding new element to ContentProvider
| SuricatePodcast/app/src/main/java/leoisasmendi/android/com/suricatepodcast/MainActivity.java | Fixed adding new element to ContentProvider |
|
Java | epl-1.0 | e31844f563e7712c27131e30f5fb31a82b8ccdcb | 0 | opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt,opendaylight/netvirt | /*
* Copyright (c) 2016 Red Hat, Inc. 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
*/
package org.opendaylight.netvirt.aclservice;
import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
import com.google.common.collect.Lists;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
import org.opendaylight.genius.mdsalutil.ActionInfo;
import org.opendaylight.genius.mdsalutil.FlowEntity;
import org.opendaylight.genius.mdsalutil.InstructionInfo;
import org.opendaylight.genius.mdsalutil.MDSALUtil;
import org.opendaylight.genius.mdsalutil.MatchInfoBase;
import org.opendaylight.genius.mdsalutil.NwConstants;
import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack;
import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack.NxCtAction;
import org.opendaylight.genius.mdsalutil.actions.ActionNxCtClear;
import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
import org.opendaylight.genius.mdsalutil.nxmatches.NxMatchCtState;
import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
import org.opendaylight.netvirt.aclservice.api.AclInterfaceCache;
import org.opendaylight.netvirt.aclservice.api.AclServiceListener;
import org.opendaylight.netvirt.aclservice.api.AclServiceManager.Action;
import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
import org.opendaylight.netvirt.aclservice.utils.AclConntrackClassifierType;
import org.opendaylight.netvirt.aclservice.utils.AclConstants;
import org.opendaylight.netvirt.aclservice.utils.AclDataUtil;
import org.opendaylight.netvirt.aclservice.utils.AclServiceOFFlowBuilder;
import org.opendaylight.netvirt.aclservice.utils.AclServiceUtils;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntries;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIp;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv4;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeEgress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionEgress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionIngress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.port.subnets.port.subnet.SubnetInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractAclServiceImpl implements AclServiceListener {
private static final Logger LOG = LoggerFactory.getLogger(AbstractAclServiceImpl.class);
protected final IMdsalApiManager mdsalManager;
protected final ManagedNewTransactionRunner txRunner;
protected final Class<? extends ServiceModeBase> serviceMode;
protected final AclDataUtil aclDataUtil;
protected final AclServiceUtils aclServiceUtils;
protected final JobCoordinator jobCoordinator;
protected final AclInterfaceCache aclInterfaceCache;
protected final Class<? extends DirectionBase> direction;
protected final String directionString;
/**
* Initialize the member variables.
*
* @param serviceMode the service mode
* @param dataBroker the data broker instance.
* @param mdsalManager the mdsal manager instance.
* @param aclDataUtil the acl data util.
* @param aclServiceUtils the acl service util.
* @param jobCoordinator the job coordinator
* @param aclInterfaceCache the acl interface cache
*/
public AbstractAclServiceImpl(Class<? extends ServiceModeBase> serviceMode, DataBroker dataBroker,
IMdsalApiManager mdsalManager, AclDataUtil aclDataUtil, AclServiceUtils aclServiceUtils,
JobCoordinator jobCoordinator, AclInterfaceCache aclInterfaceCache) {
this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
this.mdsalManager = mdsalManager;
this.serviceMode = serviceMode;
this.aclDataUtil = aclDataUtil;
this.aclServiceUtils = aclServiceUtils;
this.jobCoordinator = jobCoordinator;
this.aclInterfaceCache = aclInterfaceCache;
this.direction =
this.serviceMode.equals(ServiceModeEgress.class) ? DirectionIngress.class : DirectionEgress.class;
this.directionString = this.direction.equals(DirectionEgress.class) ? "Egress" : "Ingress";
}
@Override
public boolean applyAcl(AclInterface port) {
if (port == null) {
LOG.error("port cannot be null");
return false;
}
if (port.getSecurityGroups() == null) {
LOG.info("Port {} without SGs", port.getInterfaceId());
return false;
}
BigInteger dpId = port.getDpId();
if (dpId == null || port.getLPortTag() == null) {
LOG.error("Unable to find DpId from ACL interface with id {}", port.getInterfaceId());
return false;
}
LOG.debug("Applying ACL on port {} with DpId {}", port, dpId);
List<FlowEntity> flowEntries = new ArrayList<>();
programAcl(flowEntries, port, Action.ADD, NwConstants.ADD_FLOW);
updateRemoteAclFilterTable(flowEntries, port, NwConstants.ADD_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.ADD_FLOW);
return true;
}
@Override
public boolean bindAcl(AclInterface port) {
if (port == null || port.getSecurityGroups() == null) {
LOG.error("Port and port security groups cannot be null for binding ACL service, port={}", port);
return false;
}
bindService(port);
return true;
}
@Override
public boolean unbindAcl(AclInterface port) {
if (port == null) {
LOG.error("Port cannot be null for unbinding ACL service");
return false;
}
if (port.getDpId() != null) {
unbindService(port);
}
return true;
}
@Override
public boolean updateAcl(AclInterface portBefore, AclInterface portAfter) {
// this check is to avoid situations of port update coming before interface state is up
if (portAfter.getDpId() == null || portAfter.getLPortTag() == null) {
LOG.debug("Unable to find DpId from ACL interface with id {} and lport {}", portAfter.getInterfaceId(),
portAfter.getLPortTag());
return false;
}
boolean result = true;
boolean isPortSecurityEnable = portAfter.isPortSecurityEnabled();
boolean isPortSecurityEnableBefore = portBefore.isPortSecurityEnabled();
// if port security is changed, apply/remove Acls
if (isPortSecurityEnableBefore != isPortSecurityEnable) {
LOG.debug("On ACL update, Port security is {} for {}", isPortSecurityEnable ? "Enabled" :
"Disabled", portAfter.getInterfaceId());
if (isPortSecurityEnable) {
result = applyAcl(portAfter);
} else {
result = removeAcl(portBefore);
}
} else if (isPortSecurityEnable) {
// Acls has been updated, find added/removed Acls and act accordingly.
processInterfaceUpdate(portBefore, portAfter);
LOG.debug("On ACL update, ACL has been updated for {}", portAfter.getInterfaceId());
}
return result;
}
private void processInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
List<FlowEntity> addFlowEntries = new ArrayList<>();
List<FlowEntity> deleteFlowEntries = new ArrayList<>();
List<AllowedAddressPairs> addedAaps = AclServiceUtils
.getUpdatedAllowedAddressPairs(portAfter.getAllowedAddressPairs(), portBefore.getAllowedAddressPairs());
List<AllowedAddressPairs> deletedAaps = AclServiceUtils
.getUpdatedAllowedAddressPairs(portBefore.getAllowedAddressPairs(), portAfter.getAllowedAddressPairs());
if (deletedAaps != null && !deletedAaps.isEmpty()) {
programAclWithAllowedAddress(deleteFlowEntries, portBefore, deletedAaps, Action.UPDATE,
NwConstants.DEL_FLOW);
updateRemoteAclFilterTable(deleteFlowEntries, portBefore, portBefore.getSecurityGroups(), deletedAaps,
NwConstants.DEL_FLOW);
}
if (addedAaps != null && !addedAaps.isEmpty()) {
programAclWithAllowedAddress(addFlowEntries, portAfter, addedAaps, Action.UPDATE, NwConstants.ADD_FLOW);
updateRemoteAclFilterTable(addFlowEntries, portAfter, portAfter.getSecurityGroups(), addedAaps,
NwConstants.ADD_FLOW);
}
if (portAfter.getSubnetInfo() != null && portBefore.getSubnetInfo() == null) {
programBroadcastRules(addFlowEntries, portAfter, NwConstants.ADD_FLOW);
}
handleSubnetChange(portBefore, portAfter, addFlowEntries, deleteFlowEntries);
List<Uuid> addedAcls = AclServiceUtils.getUpdatedAclList(portAfter.getSecurityGroups(),
portBefore.getSecurityGroups());
List<Uuid> deletedAcls = AclServiceUtils.getUpdatedAclList(portBefore.getSecurityGroups(),
portAfter.getSecurityGroups());
if (!deletedAcls.isEmpty() || !addedAcls.isEmpty()) {
handleAclChange(deleteFlowEntries, portBefore, deletedAcls, NwConstants.DEL_FLOW);
handleAclChange(addFlowEntries, portAfter, addedAcls, NwConstants.ADD_FLOW);
}
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + portAfter.getInterfaceId(), deleteFlowEntries,
NwConstants.DEL_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + portAfter.getInterfaceId(), addFlowEntries,
NwConstants.ADD_FLOW);
}
private void handleSubnetChange(AclInterface portBefore, AclInterface portAfter,
List<FlowEntity> addFlowEntries, List<FlowEntity> deleteFlowEntries) {
List<SubnetInfo> deletedSubnets =
AclServiceUtils.getSubnetDiff(portBefore.getSubnetInfo(), portAfter.getSubnetInfo());
List<SubnetInfo> addedSubnets =
AclServiceUtils.getSubnetDiff(portAfter.getSubnetInfo(), portBefore.getSubnetInfo());
if (deletedSubnets != null && !deletedSubnets.isEmpty()) {
programIcmpv6RARule(deleteFlowEntries, portAfter, deletedSubnets, NwConstants.DEL_FLOW);
}
if (addedSubnets != null && !addedSubnets.isEmpty()) {
programIcmpv6RARule(addFlowEntries, portAfter, addedSubnets, NwConstants.ADD_FLOW);
}
}
private void handleAclChange(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclList,
int addOrRemove) {
int operationForAclRules = (addOrRemove == NwConstants.DEL_FLOW) ? NwConstants.MOD_FLOW : addOrRemove;
programAclRules(flowEntries, port, aclList, operationForAclRules);
updateRemoteAclFilterTable(flowEntries, port, aclList, port.getAllowedAddressPairs(), addOrRemove);
programAclDispatcherTable(flowEntries, port, addOrRemove);
}
protected SortedSet<Integer> getRemoteAclTags(AclInterface port) {
return this.direction == DirectionIngress.class ? port.getIngressRemoteAclTags()
: port.getEgressRemoteAclTags();
}
protected void programAclDispatcherTable(List<FlowEntity> flowEntries, AclInterface port, int addOrRemove) {
SortedSet<Integer> remoteAclTags = getRemoteAclTags(port);
if (remoteAclTags.isEmpty()) {
LOG.debug("No {} rules with remote group id for port={}", this.directionString, port.getInterfaceId());
return;
}
Integer firstRemoteAclTag = remoteAclTags.first();
Integer lastRemoteAclTag = remoteAclTags.last();
programFirstRemoteAclEntryInDispatcherTable(flowEntries, port, firstRemoteAclTag, addOrRemove);
programLastRemoteAclEntryInDispatcherTable(flowEntries, port, lastRemoteAclTag, addOrRemove);
Integer previousRemoteAclTag = firstRemoteAclTag;
for (Integer remoteAclTag : remoteAclTags) {
if (remoteAclTag.equals(firstRemoteAclTag)) {
continue;
}
List<MatchInfoBase> matches = new ArrayList<>();
matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(),
previousRemoteAclTag, serviceMode));
String flowId = this.directionString + "_ACL_Dispatcher_" + port.getDpId() + "_" + port.getLPortTag() + "_"
+ remoteAclTag;
List<InstructionInfo> instructions =
AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRuleBasedFilterTable());
instructions.add(AclServiceUtils.getWriteMetadataForRemoteAclTag(remoteAclTag));
addFlowEntryToList(flowEntries, port.getDpId(), getAclFilterCumDispatcherTable(), flowId,
AclConstants.ACE_GOTO_NEXT_REMOTE_ACL_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches,
instructions, addOrRemove);
previousRemoteAclTag = remoteAclTag;
}
}
protected void programFirstRemoteAclEntryInDispatcherTable(List<FlowEntity> flowEntries, AclInterface port,
Integer firstRemoteAclTag, int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode));
String flowId = this.directionString + "_ACL_Dispatcher_First_" + port.getDpId() + "_" + port.getLPortTag()
+ "_" + firstRemoteAclTag;
List<InstructionInfo> instructions =
AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRuleBasedFilterTable());
instructions.add(AclServiceUtils.getWriteMetadataForRemoteAclTag(firstRemoteAclTag));
addFlowEntryToList(flowEntries, port.getDpId(), getAclFilterCumDispatcherTable(), flowId,
AclConstants.ACE_FIRST_REMOTE_ACL_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions,
addOrRemove);
}
protected void programLastRemoteAclEntryInDispatcherTable(List<FlowEntity> flowEntries, AclInterface port,
Integer lastRemoteAclTag, int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(), lastRemoteAclTag,
serviceMode));
String flowId = this.directionString + "_ACL_Dispatcher_Last_" + port.getDpId() + "_" + port.getLPortTag() + "_"
+ lastRemoteAclTag;
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
addFlowEntryToList(flowEntries, port.getDpId(), getAclFilterCumDispatcherTable(), flowId,
AclConstants.ACE_LAST_REMOTE_ACL_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(port.getLPortTag()),
matches, instructions, addOrRemove);
}
private void programAcl(List<FlowEntity> flowEntries, AclInterface port, Action action, int addOrRemove) {
programAclWithAllowedAddress(flowEntries, port, port.getAllowedAddressPairs(), action, addOrRemove);
}
private void programAclWithAllowedAddress(List<FlowEntity> flowEntries, AclInterface port,
List<AllowedAddressPairs> allowedAddresses, Action action, int addOrRemove) {
BigInteger dpId = port.getDpId();
int lportTag = port.getLPortTag();
LOG.debug("Applying ACL Allowed Address on DpId {}, lportTag {}, Action {}", dpId, lportTag, action);
String portId = port.getInterfaceId();
programAntiSpoofingRules(flowEntries, port, allowedAddresses, action, addOrRemove);
programAclPortSpecificFixedRules(flowEntries, dpId, allowedAddresses, lportTag, portId, action, addOrRemove);
if (action == Action.ADD || action == Action.REMOVE) {
programAclRules(flowEntries, port, port.getSecurityGroups(), addOrRemove);
programAclDispatcherTable(flowEntries, port, addOrRemove);
}
}
/**
* Programs the acl custom rules.
*
* @param flowEntries the flow entries
* @param port acl interface
* @param aclUuidList the list of acl uuid to be applied
* @param addOrRemove whether to delete or add flow
* @return program succeeded
*/
protected boolean programAclRules(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclUuidList,
int addOrRemove) {
BigInteger dpId = port.getDpId();
LOG.debug("Applying custom rules on DpId {}, lportTag {}", dpId, port.getLPortTag());
if (aclUuidList == null || dpId == null) {
LOG.warn("{} ACL parameters can not be null. dpId={}, aclUuidList={}", this.directionString, dpId,
aclUuidList);
return false;
}
for (Uuid aclUuid : aclUuidList) {
Acl acl = this.aclDataUtil.getAcl(aclUuid.getValue());
if (null == acl) {
LOG.warn("The ACL {} not found in cache", aclUuid.getValue());
continue;
}
AccessListEntries accessListEntries = acl.getAccessListEntries();
if (accessListEntries != null && accessListEntries.getAce() != null) {
for (Ace ace: accessListEntries.getAce()) {
programAceRule(flowEntries, port, aclUuid.getValue(), ace, addOrRemove);
}
}
}
return true;
}
/**
* Programs the ace specific rule.
*
* @param flowEntries flow entries
* @param port acl interface
* @param aclName the acl name
* @param ace rule to be program
* @param addOrRemove whether to delete or add flow
*/
protected void programAceRule(List<FlowEntity> flowEntries, AclInterface port, String aclName, Ace ace,
int addOrRemove) {
SecurityRuleAttr aceAttr = AclServiceUtils.getAccessListAttributes(ace);
if (!isValidDirection(aceAttr.getDirection())) {
LOG.trace("Ignoring {} direction while processing for {} ACE Rule {}", aceAttr.getDirection(),
this.directionString, ace.getRuleName());
return;
}
LOG.debug("Program {} ACE rule for dpId={}, lportTag={}, addOrRemove={}, ace={}, portId={}",
this.directionString, port.getDpId(), port.getLPortTag(), addOrRemove, ace.getRuleName(),
port.getInterfaceId());
Matches matches = ace.getMatches();
if (matches != null && matches.getAceType() instanceof AceIp) {
Map<String, List<MatchInfoBase>> flowMap = AclServiceOFFlowBuilder.programIpFlow(matches);
if (!AclServiceUtils.doesAceHaveRemoteGroupId(aceAttr)) {
// programming for ACE which doesn't have any remote group Id
programForAceNotHavingRemoteAclId(flowEntries, port, aclName, ace, flowMap, addOrRemove);
} else {
Uuid remoteAclId = aceAttr.getRemoteGroupId();
// programming for ACE which have remote group Id
programAceSpecificFlows(flowEntries, port, aclName, ace, flowMap, remoteAclId, addOrRemove);
}
}
}
protected void programForAceNotHavingRemoteAclId(List<FlowEntity> flowEntries, AclInterface port, String aclName,
Ace ace, @Nullable Map<String, List<MatchInfoBase>> flowMap, int addOrRemove) {
if (null == flowMap) {
return;
}
MatchInfoBase lportTagMatch = AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode);
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclCommitterTable());
Integer flowPriority = this.aclServiceUtils.getAceFlowPriority(aclName);
for (Entry<String, List<MatchInfoBase>> entry : flowMap.entrySet()) {
String flowName = entry.getKey();
List<MatchInfoBase> matches = entry.getValue();
matches.add(lportTagMatch);
String flowId = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag() + "_"
+ ace.key().getRuleName();
int operation = addOrRemove == NwConstants.MOD_FLOW ? NwConstants.DEL_FLOW : addOrRemove;
addFlowEntryToList(flowEntries, port.getDpId(), getAclFilterCumDispatcherTable(), flowId, flowPriority,
0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, operation);
if (addOrRemove != NwConstants.DEL_FLOW) {
programAclForExistingTrafficTable(port, ace, addOrRemove, flowName, matches, flowPriority);
}
}
}
protected void programAceSpecificFlows(List<FlowEntity> flowEntries, AclInterface port, String aclName, Ace ace,
@Nullable Map<String, List<MatchInfoBase>> flowMap, Uuid remoteAclId, int addOrRemove) {
if (null == flowMap) {
return;
}
Integer remoteAclTag = this.aclServiceUtils.getAclTag(remoteAclId);
if (remoteAclTag == null || remoteAclTag == AclConstants.INVALID_ACL_TAG) {
LOG.error("remoteAclTag={} is null or invalid for remoteAclId={}", remoteAclTag, remoteAclId);
return;
}
List<MatchInfoBase> lportAndAclMatches =
AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(), remoteAclTag, serviceMode);
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRemoteAclTable());
Integer flowPriority = this.aclServiceUtils.getAceFlowPriority(aclName);
for (Entry<String, List<MatchInfoBase>> entry : flowMap.entrySet()) {
String flowName = entry.getKey();
List<MatchInfoBase> matches = entry.getValue();
matches.addAll(lportAndAclMatches);
String flowId = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag() + "_"
+ ace.key().getRuleName();
int operation = addOrRemove == NwConstants.MOD_FLOW ? NwConstants.DEL_FLOW : addOrRemove;
addFlowEntryToList(flowEntries, port.getDpId(), getAclRuleBasedFilterTable(), flowId, flowPriority, 0, 0,
AclConstants.COOKIE_ACL_BASE, matches, instructions, operation);
if (addOrRemove != NwConstants.DEL_FLOW) {
programAclForExistingTrafficTable(port, ace, addOrRemove, flowName, matches, flowPriority);
}
}
}
private void programAclForExistingTrafficTable(AclInterface port, Ace ace, int addOrRemove, String flowName,
List<MatchInfoBase> matches, Integer priority) {
AceIp acl = (AceIp) ace.getMatches().getAceType();
final String newFlowName = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag()
+ "_" + ((acl.getAceIpVersion() instanceof AceIpv4) ? "_IPv4" : "_IPv6") + "_FlowAfterRuleDeleted";
final List<MatchInfoBase> newMatches =
matches.stream().filter(obj -> !(obj instanceof NxMatchCtState || obj instanceof MatchMetadata))
.collect(Collectors.toList());
newMatches.add(AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode));
newMatches.add(new NxMatchCtState(AclConstants.TRACKED_RPL_CT_STATE, AclConstants.TRACKED_RPL_CT_STATE_MASK));
List<InstructionInfo> instructions =
AclServiceUtils.createCtMarkInstructionForNewState(getAclFilterCumDispatcherTable(), port.getElanId());
// Reversing the flow add/delete operation for this table.
List<FlowEntity> flowEntries = new ArrayList<>();
int operation = (addOrRemove == NwConstants.ADD_FLOW) ? NwConstants.DEL_FLOW : NwConstants.ADD_FLOW;
addFlowEntryToList(flowEntries, port.getDpId(), getAclForExistingTrafficTable(), newFlowName, priority, 0,
AclServiceUtils.getHardTimoutForApplyStatefulChangeOnExistingTraffic(ace, aclServiceUtils),
AclConstants.COOKIE_ACL_BASE, newMatches, instructions, operation);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, operation);
}
@Override
public boolean removeAcl(AclInterface port) {
if (port.getDpId() == null) {
LOG.warn("Unable to find DP Id from ACL interface with id {}", port.getInterfaceId());
return false;
}
List<FlowEntity> flowEntries = new ArrayList<>();
programAcl(flowEntries, port, Action.REMOVE, NwConstants.DEL_FLOW);
updateRemoteAclFilterTable(flowEntries, port, NwConstants.DEL_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.DEL_FLOW);
return true;
}
@Override
public boolean applyAce(AclInterface port, String aclName, Ace ace) {
if (!port.isPortSecurityEnabled() || port.getDpId() == null) {
return false;
}
List<FlowEntity> flowEntries = new ArrayList<>();
programAceRule(flowEntries, port, aclName, ace, NwConstants.ADD_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.ADD_FLOW);
return true;
}
@Override
public boolean removeAce(AclInterface port, String aclName, Ace ace) {
if (!port.isPortSecurityEnabled() || port.getDpId() == null) {
return false;
}
List<FlowEntity> flowEntries = new ArrayList<>();
programAceRule(flowEntries, port, aclName, ace, NwConstants.MOD_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.DEL_FLOW);
return true;
}
@Override
public void updateRemoteAcl(Acl aclBefore, Acl aclAfter, Collection<AclInterface> portsBefore) {
handleRemoteAclUpdate(aclBefore, aclAfter, portsBefore);
}
/**
* Bind service.
*
* @param aclInterface the acl interface
*/
public abstract void bindService(AclInterface aclInterface);
/**
* Unbind service.
*
* @param aclInterface the acl interface
*/
protected abstract void unbindService(AclInterface aclInterface);
/**
* Programs the anti-spoofing rules.
*
* @param flowEntries the flow entries
* @param port the acl interface
* @param allowedAddresses the allowed addresses
* @param action add/modify/remove action
* @param addOrRemove addorRemove
*/
protected abstract void programAntiSpoofingRules(List<FlowEntity> flowEntries, AclInterface port,
List<AllowedAddressPairs> allowedAddresses, Action action, int addOrRemove);
/**
* Programs broadcast rules.
*
* @param flowEntries the flow entries
* @param port the Acl Interface port
* @param addOrRemove whether to delete or add flow
*/
protected abstract void programBroadcastRules(List<FlowEntity> flowEntries, AclInterface port, int addOrRemove);
protected abstract void programIcmpv6RARule(List<FlowEntity> flowEntries, AclInterface port,
List<SubnetInfo> subnets, int addOrRemove);
/**
* Add Flow to list.
*
* @param dpId
* the dpId
* @param tableId
* the tableId
* @param flowId
* the flowId
* @param priority
* the priority
* @param idleTimeOut
* the idle timeout
* @param hardTimeOut
* the hard timeout
* @param cookie
* the cookie
* @param matches
* the list of matches to be writted
* @param instructions
* the list of instruction to be written.
* @param addOrRemove
* add or remove the entries.
*/
protected void addFlowEntryToList(List<FlowEntity> flowEntries, BigInteger dpId, short tableId, String flowId,
int priority, int idleTimeOut, int hardTimeOut, BigInteger cookie, List<? extends MatchInfoBase> matches,
List<InstructionInfo> instructions, int addOrRemove) {
List<InstructionInfo> instructionInfos = null;
if (addOrRemove == NwConstants.ADD_FLOW) {
instructionInfos = instructions;
}
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, tableId, flowId, priority,
flowId, idleTimeOut, hardTimeOut, cookie, matches, instructionInfos);
LOG.trace("Adding flow to list: DpnId {}, flowId {}", dpId, flowId);
flowEntries.add(flowEntity);
}
protected void programFlows(String jobName, List<FlowEntity> flowEntries, int addOrRemove) {
List<List<FlowEntity>> flowEntityParts = Lists.partition(flowEntries, AclConstants.FLOWS_PER_TRANSACTION);
for (List<FlowEntity> part : flowEntityParts) {
jobCoordinator.enqueueJob(jobName,
() -> Collections.singletonList(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
tx -> {
if (addOrRemove == NwConstants.ADD_FLOW) {
for (FlowEntity flowEntity: part) {
mdsalManager.addFlow(tx, flowEntity);
}
} else {
for (FlowEntity flowEntity: part) {
mdsalManager.removeFlow(tx, flowEntity);
}
}
})), AclConstants.JOB_MAX_RETRIES);
}
}
protected List<InstructionInfo> getDispatcherTableResubmitInstructions() {
return getDispatcherTableResubmitInstructions(new ArrayList<>());
}
/**
* Gets the dispatcher table resubmit instructions based on ingress/egress service mode w.r.t switch.
*
* @param actionsInfos
* the actions infos
* @return the instructions for dispatcher table resubmit
*/
protected List<InstructionInfo> getDispatcherTableResubmitInstructions(List<ActionInfo> actionsInfos) {
short dispatcherTableId = NwConstants.LPORT_DISPATCHER_TABLE;
if (ServiceModeEgress.class.equals(this.serviceMode)) {
dispatcherTableId = NwConstants.EGRESS_LPORT_DISPATCHER_TABLE;
}
List<InstructionInfo> instructions = new ArrayList<>();
actionsInfos.add(new ActionNxResubmit(dispatcherTableId));
instructions.add(new InstructionApplyActions(actionsInfos));
return instructions;
}
protected void handleRemoteAclUpdate(Acl aclBefore, Acl aclAfter, Collection<AclInterface> portsBefore) {
String aclName = aclAfter.getAclName();
Collection<AclInterface> interfaceList = aclDataUtil.getInterfaceList(new Uuid(aclName));
if (interfaceList.isEmpty()) {
LOG.trace("handleRemoteAclUpdate: No interfaces found with ACL={}", aclName);
return;
}
Set<Uuid> remoteAclsBefore = AclServiceUtils.getRemoteAclIdsByDirection(aclBefore, this.direction);
Set<Uuid> remoteAclsAfter = AclServiceUtils.getRemoteAclIdsByDirection(aclAfter, this.direction);
Set<Uuid> remoteAclsAdded = new HashSet<>(remoteAclsAfter);
remoteAclsAdded.removeAll(remoteAclsBefore);
Set<Uuid> remoteAclsDeleted = new HashSet<>(remoteAclsBefore);
remoteAclsDeleted.removeAll(remoteAclsAfter);
List<FlowEntity> addFlowEntries = new ArrayList<>();
List<FlowEntity> deleteFlowEntries = new ArrayList<>();
if (!remoteAclsAdded.isEmpty() || !remoteAclsDeleted.isEmpty()) {
// delete and add flows in ACL dispatcher table for all applicable
// ports
for (AclInterface portBefore : portsBefore) {
programAclDispatcherTable(deleteFlowEntries, portBefore, NwConstants.DEL_FLOW);
}
for (AclInterface port : interfaceList) {
programAclDispatcherTable(addFlowEntries, port, NwConstants.ADD_FLOW);
}
}
Set<BigInteger> dpns = interfaceList.stream().map(AclInterface::getDpId).collect(Collectors.toSet());
programRemoteAclTable(deleteFlowEntries, aclName, remoteAclsDeleted, dpns, NwConstants.DEL_FLOW);
programRemoteAclTable(addFlowEntries, aclName, remoteAclsAdded, dpns, NwConstants.ADD_FLOW);
programFlows(aclName, deleteFlowEntries, NwConstants.DEL_FLOW);
programFlows(aclName, addFlowEntries, NwConstants.ADD_FLOW);
}
private void programRemoteAclTable(List<FlowEntity> flowEntries, String aclName, Set<Uuid> remoteAclIds,
Set<BigInteger> dpns, int addOrRemove) {
for (Uuid remoteAclId : remoteAclIds) {
Collection<AclInterface> remoteAclInterfaces = aclDataUtil.getInterfaceList(remoteAclId);
if (remoteAclInterfaces.isEmpty()) {
continue;
}
Set<AllowedAddressPairs> aaps =
remoteAclInterfaces.stream().map(AclInterface::getAllowedAddressPairs).flatMap(List::stream)
.filter(AclServiceUtils::isNotIpAllNetwork).collect(Collectors.toSet());
Integer aclTag = aclServiceUtils.getAclTag(remoteAclId);
if (addOrRemove == NwConstants.ADD_FLOW) {
for (BigInteger dpn : dpns) {
for (AllowedAddressPairs aap : aaps) {
programRemoteAclTableFlow(flowEntries, dpn, aclTag, aap, addOrRemove);
}
}
} else if (addOrRemove == NwConstants.DEL_FLOW) {
Set<BigInteger> remoteAclDpns = new HashSet<>();
Map<String, Set<AclInterface>> mapAclWithPortSet =
aclDataUtil.getRemoteAclInterfaces(remoteAclId, this.direction);
if (mapAclWithPortSet != null) {
Map<String, Set<AclInterface>> copyOfMapAclWithPortSet = new HashMap<>(mapAclWithPortSet);
copyOfMapAclWithPortSet.remove(aclName);
remoteAclDpns = collectDpns(copyOfMapAclWithPortSet);
}
Set<BigInteger> dpnsToOperate = new HashSet<>(dpns);
dpnsToOperate.removeAll(remoteAclDpns);
LOG.debug(
"Deleting flows in Remote ACL table for remoteAclId={}, direction={}, dpnsToOperate={}, "
+ "remoteAclDpns={}, dpns={}",
remoteAclId.getValue(), directionString, dpnsToOperate, remoteAclDpns, dpns);
for (BigInteger dpn : dpnsToOperate) {
for (AllowedAddressPairs aap : aaps) {
programRemoteAclTableFlow(flowEntries, dpn, aclTag, aap, addOrRemove);
}
}
}
}
}
private void updateRemoteAclFilterTable(List<FlowEntity> flowEntries, AclInterface port, int addOrRemove) {
updateRemoteAclFilterTable(flowEntries, port, port.getSecurityGroups(), port.getAllowedAddressPairs(),
addOrRemove);
}
private void updateRemoteAclFilterTable(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclList,
List<AllowedAddressPairs> aaps, int addOrRemove) {
if (aclList == null) {
LOG.debug("Port {} without SGs", port.getInterfaceId());
return;
}
String portId = port.getInterfaceId();
LOG.trace("updateRemoteAclFilterTable for portId={}, aclList={}, aaps={}, addOrRemove={}", portId, aclList,
aaps, addOrRemove);
for (Uuid aclId : aclList) {
if (aclDataUtil.getRemoteAcl(aclId, this.direction) != null) {
Integer aclTag = aclServiceUtils.getAclTag(aclId);
if (addOrRemove == NwConstants.ADD_FLOW) {
syncRemoteAclTable(flowEntries, portId, aclId, aclTag, aaps, addOrRemove);
}
else if (addOrRemove == NwConstants.DEL_FLOW) {
jobCoordinator.enqueueJob(aclId.getValue().intern(), () -> {
List<FlowEntity> remoteTableFlowEntries = new ArrayList<>();
syncRemoteAclTable(remoteTableFlowEntries, portId, aclId, aclTag, aaps, addOrRemove);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + aclId.getValue(),
remoteTableFlowEntries, NwConstants.DEL_FLOW);
return Collections.emptyList();
});
}
}
}
Set<Uuid> remoteAclIds = aclServiceUtils.getRemoteAclIdsByDirection(aclList, direction);
for (Uuid remoteAclId : remoteAclIds) {
syncRemoteAclTableFromOtherDpns(flowEntries, port, remoteAclId, addOrRemove);
}
}
private void syncRemoteAclTable(List<FlowEntity> flowEntries, String portId, Uuid acl, Integer aclTag,
List<AllowedAddressPairs> aaps, int addOrRemove) {
Map<String, Set<AclInterface>> mapAclWithPortSet = aclDataUtil.getRemoteAclInterfaces(acl, this.direction);
Set<BigInteger> dpns = collectDpns(mapAclWithPortSet);
for (AllowedAddressPairs aap : aaps) {
if (!AclServiceUtils.isNotIpAllNetwork(aap)) {
continue;
}
if (aclServiceUtils.skipDeleteInCaseOfOverlappingIP(portId, acl, aap.getIpAddress(),
addOrRemove)) {
LOG.debug("Skipping delete of IP={} in remote ACL table for remoteAclId={}, portId={}",
aap.getIpAddress(), portId, acl.getValue());
continue;
}
for (BigInteger dpId : dpns) {
programRemoteAclTableFlow(flowEntries, dpId, aclTag, aap, addOrRemove);
}
}
}
private void syncRemoteAclTableFromOtherDpns(List<FlowEntity> flowEntries, AclInterface port, Uuid remoteAclId,
int addOrRemove) {
Collection<AclInterface> aclInterfaces = aclDataUtil.getInterfaceList(remoteAclId);
if (!aclInterfaces.isEmpty() && isFirstPortInDpnWithRemoteAclId(port, remoteAclId)) {
Integer aclTag = aclServiceUtils.getAclTag(remoteAclId);
for (AclInterface aclInterface : aclInterfaces) {
if (port.getInterfaceId().equals(aclInterface.getInterfaceId())) {
continue;
}
for (AllowedAddressPairs aap : aclInterface.getAllowedAddressPairs()) {
if (AclServiceUtils.isNotIpAllNetwork(aap)) {
programRemoteAclTableFlow(flowEntries, port.getDpId(), aclTag, aap, addOrRemove);
}
}
}
}
}
private boolean isFirstPortInDpnWithRemoteAclId(AclInterface port, Uuid remoteAclId) {
String portId = port.getInterfaceId();
BigInteger dpId = port.getDpId();
Map<String, Set<AclInterface>> remoteAclInterfacesMap =
aclDataUtil.getRemoteAclInterfaces(remoteAclId, direction);
if (remoteAclInterfacesMap != null) {
for (Set<AclInterface> interfaceSet : remoteAclInterfacesMap.values()) {
for (AclInterface aclInterface : interfaceSet) {
if (portId.equals(aclInterface.getInterfaceId())) {
continue;
}
if (dpId.equals(aclInterface.getDpId())) {
return false;
}
}
}
}
return true;
}
protected abstract void programRemoteAclTableFlow(List<FlowEntity> flowEntries, BigInteger dpId, Integer aclTag,
AllowedAddressPairs aap, int addOrRemove);
protected Set<BigInteger> collectDpns(@Nullable Map<String, Set<AclInterface>> mapAclWithPortSet) {
Set<BigInteger> dpns = new HashSet<>();
if (mapAclWithPortSet == null) {
return dpns;
}
for (Set<AclInterface> innerSet : mapAclWithPortSet.values()) {
if (innerSet == null) {
continue;
}
for (AclInterface inter : innerSet) {
dpns.add(inter.getDpId());
}
}
return dpns;
}
/**
* Programs the port specific fixed rules.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param allowedAddresses the allowed addresses
* @param lportTag the lport tag
* @param portId the portId
* @param action the action
* @param write whether to add or remove the flow.
*/
protected void programAclPortSpecificFixedRules(List<FlowEntity> flowEntries, BigInteger dpId,
List<AllowedAddressPairs> allowedAddresses, int lportTag, String portId, Action action, int write) {
programGotoClassifierTableRules(flowEntries, dpId, allowedAddresses, lportTag, write);
if (action == Action.ADD || action == Action.REMOVE) {
programConntrackRecircRules(flowEntries, dpId, allowedAddresses, lportTag, portId, write);
programPortSpecificDropRules(flowEntries, dpId, lportTag, write);
programAclCommitRules(flowEntries, dpId, lportTag, portId, write);
}
LOG.info("programAclPortSpecificFixedRules: flows for dpId={}, lportId={}, action={}, write={}", dpId, lportTag,
action, write);
}
protected abstract void programGotoClassifierTableRules(List<FlowEntity> flowEntries, BigInteger dpId,
List<AllowedAddressPairs> aaps, int lportTag, int addOrRemove);
/**
* Adds the rule to send the packet to the netfilter to check whether it is a known packet.
*
* @param flowEntries the flow entries
* @param dpId the dpId
* @param aaps the allowed address pairs
* @param lportTag the lport tag
* @param portId the portId
* @param addOrRemove whether to add or remove the flow
*/
protected void programConntrackRecircRules(List<FlowEntity> flowEntries, BigInteger dpId,
List<AllowedAddressPairs> aaps, int lportTag, String portId, int addOrRemove) {
if (AclServiceUtils.doesIpv4AddressExists(aaps)) {
programConntrackRecircRule(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV4, addOrRemove);
}
if (AclServiceUtils.doesIpv6AddressExists(aaps)) {
programConntrackRecircRule(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV6, addOrRemove);
}
}
protected void programConntrackRecircRule(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
String portId, MatchEthernetType matchEtherType, int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(matchEtherType);
matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
List<InstructionInfo> instructions = new ArrayList<>();
if (addOrRemove == NwConstants.ADD_FLOW) {
Long elanTag = getElanIdFromAclInterface(portId);
if (elanTag == null) {
LOG.error("ElanId not found for portId={}; Context: dpId={}, lportTag={}, addOrRemove={},", portId,
dpId, lportTag, addOrRemove);
return;
}
List<ActionInfo> actionsInfos = new ArrayList<>();
actionsInfos.add(new ActionNxConntrack(2, 0, 0, elanTag.intValue(), getAclForExistingTrafficTable()));
instructions.add(new InstructionApplyActions(actionsInfos));
}
String flowName =
this.directionString + "_Fixed_Conntrk_" + dpId + "_" + lportTag + "_" + matchEtherType + "_Recirc";
addFlowEntryToList(flowEntries, dpId, getAclConntrackSenderTable(), flowName,
AclConstants.ACL_DEFAULT_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions,
addOrRemove);
}
/**
* Adds the rules to drop the unknown/invalid packets .
*
* @param flowEntries the flow entries
* @param dpId the dpId
* @param lportTag the lport tag
* @param addOrRemove whether to add or remove the flow
*/
protected void programPortSpecificDropRules(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
int addOrRemove) {
LOG.debug("Programming Drop Rules: DpId={}, lportTag={}, addOrRemove={}", dpId, lportTag, addOrRemove);
programConntrackInvalidDropRule(flowEntries, dpId, lportTag, addOrRemove);
programAclRuleMissDropRule(flowEntries, dpId, lportTag, addOrRemove);
}
/**
* Adds the rule to drop the conntrack invalid packets .
*
* @param flowEntries the flow entries
* @param dpId the dpId
* @param lportTag the lport tag
* @param addOrRemove whether to add or remove the flow
*/
protected void programConntrackInvalidDropRule(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
int addOrRemove) {
List<MatchInfoBase> matches = AclServiceOFFlowBuilder.addLPortTagMatches(lportTag,
AclConstants.TRACKED_INV_CT_STATE, AclConstants.TRACKED_INV_CT_STATE_MASK, serviceMode);
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
String flowId = this.directionString + "_Fixed_Conntrk_Drop" + dpId + "_" + lportTag + "_Tracked_Invalid";
addFlowEntryToList(flowEntries, dpId, getAclFilterCumDispatcherTable(), flowId,
AclConstants.CT_STATE_TRACKED_INVALID_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(lportTag),
matches, instructions, addOrRemove);
}
/**
* Program ACL rule miss drop rule for a port.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param lportTag the lport tag
* @param addOrRemove the add or remove
*/
protected void programAclRuleMissDropRule(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
String flowId = this.directionString + "_Fixed_Acl_Rule_Miss_Drop_" + dpId + "_" + lportTag;
addFlowEntryToList(flowEntries, dpId, getAclFilterCumDispatcherTable(), flowId,
AclConstants.ACL_PORT_SPECIFIC_DROP_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(lportTag),
matches, instructions, addOrRemove);
}
/**
* Program acl commit rules.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param lportTag the lport tag
* @param portId the port id
* @param addOrRemove the add or remove
*/
protected void programAclCommitRules(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag, String portId,
int addOrRemove) {
programAclCommitRuleForConntrack(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV4, addOrRemove);
programAclCommitRuleForConntrack(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV6, addOrRemove);
programAclCommitRuleForNonConntrack(flowEntries, dpId, lportTag, addOrRemove);
}
/**
* Program acl commit rule for conntrack.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param lportTag the lport tag
* @param portId the port id
* @param matchEtherType the match ether type
* @param addOrRemove the add or remove
*/
protected void programAclCommitRuleForConntrack(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
String portId, MatchEthernetType matchEtherType, int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(matchEtherType);
matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndConntrackClassifierType(lportTag,
AclConntrackClassifierType.CONNTRACK_SUPPORTED, serviceMode));
List<ActionInfo> actionsInfos = new ArrayList<>();
if (addOrRemove == NwConstants.ADD_FLOW) {
Long elanId = getElanIdFromAclInterface(portId);
if (elanId == null) {
LOG.error("ElanId not found for portId={}; Context: dpId={}, lportTag={}, addOrRemove={}", portId, dpId,
lportTag, addOrRemove);
return;
}
List<NxCtAction> ctActionsList =
Lists.newArrayList(new ActionNxConntrack.NxCtMark(AclConstants.CT_MARK_EST_STATE));
actionsInfos.add(new ActionNxConntrack(2, 1, 0, elanId.intValue(), (short) 255, ctActionsList));
actionsInfos.add(new ActionNxCtClear());
}
List<InstructionInfo> instructions = getDispatcherTableResubmitInstructions(actionsInfos);
String flowName = directionString + "_Acl_Commit_Conntrack_" + dpId + "_" + lportTag + "_" + matchEtherType;
// Flow for conntrack traffic to commit and resubmit to dispatcher
addFlowEntryToList(flowEntries, dpId, getAclCommitterTable(), flowName, AclConstants.ACL_DEFAULT_PRIORITY,
0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, addOrRemove);
}
/**
* Program acl commit rule for non conntrack.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param lportTag the lport tag
* @param addOrRemove the add or remove
*/
protected void programAclCommitRuleForNonConntrack(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndConntrackClassifierType(lportTag,
AclConntrackClassifierType.NON_CONNTRACK_SUPPORTED, serviceMode));
List<InstructionInfo> instructions = getDispatcherTableResubmitInstructions();
String flowName = this.directionString + "_Acl_Commit_Non_Conntrack_" + dpId + "_" + lportTag;
// Flow for non-conntrack traffic to resubmit to dispatcher
addFlowEntryToList(flowEntries, dpId, getAclCommitterTable(), flowName, AclConstants.ACL_DEFAULT_PRIORITY,
0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, addOrRemove);
}
@Nullable
protected Long getElanIdFromAclInterface(String elanInterfaceName) {
AclInterface aclInterface = aclInterfaceCache.get(elanInterfaceName);
if (null != aclInterface) {
return aclInterface.getElanId();
}
return null;
}
protected abstract boolean isValidDirection(Class<? extends DirectionBase> direction);
protected abstract short getAclConntrackSenderTable();
protected abstract short getAclForExistingTrafficTable();
protected abstract short getAclFilterCumDispatcherTable();
protected abstract short getAclRuleBasedFilterTable();
protected abstract short getAclRemoteAclTable();
protected abstract short getAclCommitterTable();
}
| aclservice/impl/src/main/java/org/opendaylight/netvirt/aclservice/AbstractAclServiceImpl.java | /*
* Copyright (c) 2016 Red Hat, Inc. 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
*/
package org.opendaylight.netvirt.aclservice;
import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
import com.google.common.collect.Lists;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
import org.opendaylight.genius.mdsalutil.ActionInfo;
import org.opendaylight.genius.mdsalutil.FlowEntity;
import org.opendaylight.genius.mdsalutil.InstructionInfo;
import org.opendaylight.genius.mdsalutil.MDSALUtil;
import org.opendaylight.genius.mdsalutil.MatchInfoBase;
import org.opendaylight.genius.mdsalutil.NwConstants;
import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack;
import org.opendaylight.genius.mdsalutil.actions.ActionNxConntrack.NxCtAction;
import org.opendaylight.genius.mdsalutil.actions.ActionNxCtClear;
import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
import org.opendaylight.genius.mdsalutil.nxmatches.NxMatchCtState;
import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
import org.opendaylight.netvirt.aclservice.api.AclInterfaceCache;
import org.opendaylight.netvirt.aclservice.api.AclServiceListener;
import org.opendaylight.netvirt.aclservice.api.AclServiceManager.Action;
import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
import org.opendaylight.netvirt.aclservice.utils.AclConntrackClassifierType;
import org.opendaylight.netvirt.aclservice.utils.AclConstants;
import org.opendaylight.netvirt.aclservice.utils.AclDataUtil;
import org.opendaylight.netvirt.aclservice.utils.AclServiceOFFlowBuilder;
import org.opendaylight.netvirt.aclservice.utils.AclServiceUtils;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.AccessListEntries;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.Matches;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.AceIp;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.ace.matches.ace.type.ace.ip.ace.ip.version.AceIpv4;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.servicebinding.rev160406.ServiceModeEgress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionEgress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionIngress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.port.subnets.port.subnet.SubnetInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractAclServiceImpl implements AclServiceListener {
private static final Logger LOG = LoggerFactory.getLogger(AbstractAclServiceImpl.class);
protected final IMdsalApiManager mdsalManager;
protected final ManagedNewTransactionRunner txRunner;
protected final Class<? extends ServiceModeBase> serviceMode;
protected final AclDataUtil aclDataUtil;
protected final AclServiceUtils aclServiceUtils;
protected final JobCoordinator jobCoordinator;
protected final AclInterfaceCache aclInterfaceCache;
protected final Class<? extends DirectionBase> direction;
protected final String directionString;
/**
* Initialize the member variables.
*
* @param serviceMode the service mode
* @param dataBroker the data broker instance.
* @param mdsalManager the mdsal manager instance.
* @param aclDataUtil the acl data util.
* @param aclServiceUtils the acl service util.
* @param jobCoordinator the job coordinator
* @param aclInterfaceCache the acl interface cache
*/
public AbstractAclServiceImpl(Class<? extends ServiceModeBase> serviceMode, DataBroker dataBroker,
IMdsalApiManager mdsalManager, AclDataUtil aclDataUtil, AclServiceUtils aclServiceUtils,
JobCoordinator jobCoordinator, AclInterfaceCache aclInterfaceCache) {
this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
this.mdsalManager = mdsalManager;
this.serviceMode = serviceMode;
this.aclDataUtil = aclDataUtil;
this.aclServiceUtils = aclServiceUtils;
this.jobCoordinator = jobCoordinator;
this.aclInterfaceCache = aclInterfaceCache;
this.direction =
this.serviceMode.equals(ServiceModeEgress.class) ? DirectionIngress.class : DirectionEgress.class;
this.directionString = this.direction.equals(DirectionEgress.class) ? "Egress" : "Ingress";
}
@Override
public boolean applyAcl(AclInterface port) {
if (port == null) {
LOG.error("port cannot be null");
return false;
}
if (port.getSecurityGroups() == null) {
LOG.info("Port {} without SGs", port.getInterfaceId());
return false;
}
BigInteger dpId = port.getDpId();
if (dpId == null || port.getLPortTag() == null) {
LOG.error("Unable to find DpId from ACL interface with id {}", port.getInterfaceId());
return false;
}
LOG.debug("Applying ACL on port {} with DpId {}", port, dpId);
List<FlowEntity> flowEntries = new ArrayList<>();
programAcl(flowEntries, port, Action.ADD, NwConstants.ADD_FLOW);
updateRemoteAclFilterTable(flowEntries, port, NwConstants.ADD_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.ADD_FLOW);
return true;
}
@Override
public boolean bindAcl(AclInterface port) {
if (port == null || port.getSecurityGroups() == null) {
LOG.error("Port and port security groups cannot be null for binding ACL service, port={}", port);
return false;
}
bindService(port);
return true;
}
@Override
public boolean unbindAcl(AclInterface port) {
if (port == null) {
LOG.error("Port cannot be null for unbinding ACL service");
return false;
}
if (port.getDpId() != null) {
unbindService(port);
}
return true;
}
@Override
public boolean updateAcl(AclInterface portBefore, AclInterface portAfter) {
// this check is to avoid situations of port update coming before interface state is up
if (portAfter.getDpId() == null || portAfter.getLPortTag() == null) {
LOG.debug("Unable to find DpId from ACL interface with id {} and lport {}", portAfter.getInterfaceId(),
portAfter.getLPortTag());
return false;
}
boolean result = true;
boolean isPortSecurityEnable = portAfter.isPortSecurityEnabled();
boolean isPortSecurityEnableBefore = portBefore.isPortSecurityEnabled();
// if port security is changed, apply/remove Acls
if (isPortSecurityEnableBefore != isPortSecurityEnable) {
LOG.debug("On ACL update, Port security is {} for {}", isPortSecurityEnable ? "Enabled" :
"Disabled", portAfter.getInterfaceId());
if (isPortSecurityEnable) {
result = applyAcl(portAfter);
} else {
result = removeAcl(portBefore);
}
} else if (isPortSecurityEnable) {
// Acls has been updated, find added/removed Acls and act accordingly.
processInterfaceUpdate(portBefore, portAfter);
LOG.debug("On ACL update, ACL has been updated for {}", portAfter.getInterfaceId());
}
return result;
}
private void processInterfaceUpdate(AclInterface portBefore, AclInterface portAfter) {
List<FlowEntity> addFlowEntries = new ArrayList<>();
List<FlowEntity> deleteFlowEntries = new ArrayList<>();
List<AllowedAddressPairs> addedAaps = AclServiceUtils
.getUpdatedAllowedAddressPairs(portAfter.getAllowedAddressPairs(), portBefore.getAllowedAddressPairs());
List<AllowedAddressPairs> deletedAaps = AclServiceUtils
.getUpdatedAllowedAddressPairs(portBefore.getAllowedAddressPairs(), portAfter.getAllowedAddressPairs());
if (deletedAaps != null && !deletedAaps.isEmpty()) {
programAclWithAllowedAddress(deleteFlowEntries, portBefore, deletedAaps, Action.UPDATE,
NwConstants.DEL_FLOW);
updateRemoteAclFilterTable(deleteFlowEntries, portBefore, portBefore.getSecurityGroups(), deletedAaps,
NwConstants.DEL_FLOW);
}
if (addedAaps != null && !addedAaps.isEmpty()) {
programAclWithAllowedAddress(addFlowEntries, portAfter, addedAaps, Action.UPDATE, NwConstants.ADD_FLOW);
updateRemoteAclFilterTable(addFlowEntries, portAfter, portAfter.getSecurityGroups(), addedAaps,
NwConstants.ADD_FLOW);
}
if (portAfter.getSubnetInfo() != null && portBefore.getSubnetInfo() == null) {
programBroadcastRules(addFlowEntries, portAfter, NwConstants.ADD_FLOW);
}
handleSubnetChange(portBefore, portAfter, addFlowEntries, deleteFlowEntries);
List<Uuid> addedAcls = AclServiceUtils.getUpdatedAclList(portAfter.getSecurityGroups(),
portBefore.getSecurityGroups());
List<Uuid> deletedAcls = AclServiceUtils.getUpdatedAclList(portBefore.getSecurityGroups(),
portAfter.getSecurityGroups());
if (deletedAcls.isEmpty() && addedAcls.isEmpty()) {
LOG.trace("No change w.r.t ACL list for port={}", portAfter.getInterfaceId());
return;
}
handleAclChange(deleteFlowEntries, portBefore, deletedAcls, NwConstants.DEL_FLOW);
handleAclChange(addFlowEntries, portAfter, addedAcls, NwConstants.ADD_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + portAfter.getInterfaceId(), deleteFlowEntries,
NwConstants.DEL_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + portAfter.getInterfaceId(), addFlowEntries,
NwConstants.ADD_FLOW);
}
private void handleSubnetChange(AclInterface portBefore, AclInterface portAfter,
List<FlowEntity> addFlowEntries, List<FlowEntity> deleteFlowEntries) {
List<SubnetInfo> deletedSubnets =
AclServiceUtils.getSubnetDiff(portBefore.getSubnetInfo(), portAfter.getSubnetInfo());
List<SubnetInfo> addedSubnets =
AclServiceUtils.getSubnetDiff(portAfter.getSubnetInfo(), portBefore.getSubnetInfo());
if (deletedSubnets != null && !deletedSubnets.isEmpty()) {
programIcmpv6RARule(deleteFlowEntries, portAfter, deletedSubnets, NwConstants.DEL_FLOW);
}
if (addedSubnets != null && !addedSubnets.isEmpty()) {
programIcmpv6RARule(addFlowEntries, portAfter, addedSubnets, NwConstants.ADD_FLOW);
}
}
private void handleAclChange(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclList,
int addOrRemove) {
int operationForAclRules = (addOrRemove == NwConstants.DEL_FLOW) ? NwConstants.MOD_FLOW : addOrRemove;
programAclRules(flowEntries, port, aclList, operationForAclRules);
updateRemoteAclFilterTable(flowEntries, port, aclList, port.getAllowedAddressPairs(), addOrRemove);
programAclDispatcherTable(flowEntries, port, addOrRemove);
}
protected SortedSet<Integer> getRemoteAclTags(AclInterface port) {
return this.direction == DirectionIngress.class ? port.getIngressRemoteAclTags()
: port.getEgressRemoteAclTags();
}
protected void programAclDispatcherTable(List<FlowEntity> flowEntries, AclInterface port, int addOrRemove) {
SortedSet<Integer> remoteAclTags = getRemoteAclTags(port);
if (remoteAclTags.isEmpty()) {
LOG.debug("No {} rules with remote group id for port={}", this.directionString, port.getInterfaceId());
return;
}
Integer firstRemoteAclTag = remoteAclTags.first();
Integer lastRemoteAclTag = remoteAclTags.last();
programFirstRemoteAclEntryInDispatcherTable(flowEntries, port, firstRemoteAclTag, addOrRemove);
programLastRemoteAclEntryInDispatcherTable(flowEntries, port, lastRemoteAclTag, addOrRemove);
Integer previousRemoteAclTag = firstRemoteAclTag;
for (Integer remoteAclTag : remoteAclTags) {
if (remoteAclTag.equals(firstRemoteAclTag)) {
continue;
}
List<MatchInfoBase> matches = new ArrayList<>();
matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(),
previousRemoteAclTag, serviceMode));
String flowId = this.directionString + "_ACL_Dispatcher_" + port.getDpId() + "_" + port.getLPortTag() + "_"
+ remoteAclTag;
List<InstructionInfo> instructions =
AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRuleBasedFilterTable());
instructions.add(AclServiceUtils.getWriteMetadataForRemoteAclTag(remoteAclTag));
addFlowEntryToList(flowEntries, port.getDpId(), getAclFilterCumDispatcherTable(), flowId,
AclConstants.ACE_GOTO_NEXT_REMOTE_ACL_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches,
instructions, addOrRemove);
previousRemoteAclTag = remoteAclTag;
}
}
protected void programFirstRemoteAclEntryInDispatcherTable(List<FlowEntity> flowEntries, AclInterface port,
Integer firstRemoteAclTag, int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode));
String flowId = this.directionString + "_ACL_Dispatcher_First_" + port.getDpId() + "_" + port.getLPortTag()
+ "_" + firstRemoteAclTag;
List<InstructionInfo> instructions =
AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRuleBasedFilterTable());
instructions.add(AclServiceUtils.getWriteMetadataForRemoteAclTag(firstRemoteAclTag));
addFlowEntryToList(flowEntries, port.getDpId(), getAclFilterCumDispatcherTable(), flowId,
AclConstants.ACE_FIRST_REMOTE_ACL_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions,
addOrRemove);
}
protected void programLastRemoteAclEntryInDispatcherTable(List<FlowEntity> flowEntries, AclInterface port,
Integer lastRemoteAclTag, int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(), lastRemoteAclTag,
serviceMode));
String flowId = this.directionString + "_ACL_Dispatcher_Last_" + port.getDpId() + "_" + port.getLPortTag() + "_"
+ lastRemoteAclTag;
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
addFlowEntryToList(flowEntries, port.getDpId(), getAclFilterCumDispatcherTable(), flowId,
AclConstants.ACE_LAST_REMOTE_ACL_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(port.getLPortTag()),
matches, instructions, addOrRemove);
}
private void programAcl(List<FlowEntity> flowEntries, AclInterface port, Action action, int addOrRemove) {
programAclWithAllowedAddress(flowEntries, port, port.getAllowedAddressPairs(), action, addOrRemove);
}
private void programAclWithAllowedAddress(List<FlowEntity> flowEntries, AclInterface port,
List<AllowedAddressPairs> allowedAddresses, Action action, int addOrRemove) {
BigInteger dpId = port.getDpId();
int lportTag = port.getLPortTag();
LOG.debug("Applying ACL Allowed Address on DpId {}, lportTag {}, Action {}", dpId, lportTag, action);
String portId = port.getInterfaceId();
programAntiSpoofingRules(flowEntries, port, allowedAddresses, action, addOrRemove);
programAclPortSpecificFixedRules(flowEntries, dpId, allowedAddresses, lportTag, portId, action, addOrRemove);
if (action == Action.ADD || action == Action.REMOVE) {
programAclRules(flowEntries, port, port.getSecurityGroups(), addOrRemove);
programAclDispatcherTable(flowEntries, port, addOrRemove);
}
}
/**
* Programs the acl custom rules.
*
* @param flowEntries the flow entries
* @param port acl interface
* @param aclUuidList the list of acl uuid to be applied
* @param addOrRemove whether to delete or add flow
* @return program succeeded
*/
protected boolean programAclRules(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclUuidList,
int addOrRemove) {
BigInteger dpId = port.getDpId();
LOG.debug("Applying custom rules on DpId {}, lportTag {}", dpId, port.getLPortTag());
if (aclUuidList == null || dpId == null) {
LOG.warn("{} ACL parameters can not be null. dpId={}, aclUuidList={}", this.directionString, dpId,
aclUuidList);
return false;
}
for (Uuid aclUuid : aclUuidList) {
Acl acl = this.aclDataUtil.getAcl(aclUuid.getValue());
if (null == acl) {
LOG.warn("The ACL {} not found in cache", aclUuid.getValue());
continue;
}
AccessListEntries accessListEntries = acl.getAccessListEntries();
if (accessListEntries != null && accessListEntries.getAce() != null) {
for (Ace ace: accessListEntries.getAce()) {
programAceRule(flowEntries, port, aclUuid.getValue(), ace, addOrRemove);
}
}
}
return true;
}
/**
* Programs the ace specific rule.
*
* @param flowEntries flow entries
* @param port acl interface
* @param aclName the acl name
* @param ace rule to be program
* @param addOrRemove whether to delete or add flow
*/
protected void programAceRule(List<FlowEntity> flowEntries, AclInterface port, String aclName, Ace ace,
int addOrRemove) {
SecurityRuleAttr aceAttr = AclServiceUtils.getAccessListAttributes(ace);
if (!isValidDirection(aceAttr.getDirection())) {
LOG.trace("Ignoring {} direction while processing for {} ACE Rule {}", aceAttr.getDirection(),
this.directionString, ace.getRuleName());
return;
}
LOG.debug("Program {} ACE rule for dpId={}, lportTag={}, addOrRemove={}, ace={}, portId={}",
this.directionString, port.getDpId(), port.getLPortTag(), addOrRemove, ace.getRuleName(),
port.getInterfaceId());
Matches matches = ace.getMatches();
if (matches != null && matches.getAceType() instanceof AceIp) {
Map<String, List<MatchInfoBase>> flowMap = AclServiceOFFlowBuilder.programIpFlow(matches);
if (!AclServiceUtils.doesAceHaveRemoteGroupId(aceAttr)) {
// programming for ACE which doesn't have any remote group Id
programForAceNotHavingRemoteAclId(flowEntries, port, aclName, ace, flowMap, addOrRemove);
} else {
Uuid remoteAclId = aceAttr.getRemoteGroupId();
// programming for ACE which have remote group Id
programAceSpecificFlows(flowEntries, port, aclName, ace, flowMap, remoteAclId, addOrRemove);
}
}
}
protected void programForAceNotHavingRemoteAclId(List<FlowEntity> flowEntries, AclInterface port, String aclName,
Ace ace, @Nullable Map<String, List<MatchInfoBase>> flowMap, int addOrRemove) {
if (null == flowMap) {
return;
}
MatchInfoBase lportTagMatch = AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode);
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclCommitterTable());
Integer flowPriority = this.aclServiceUtils.getAceFlowPriority(aclName);
for (Entry<String, List<MatchInfoBase>> entry : flowMap.entrySet()) {
String flowName = entry.getKey();
List<MatchInfoBase> matches = entry.getValue();
matches.add(lportTagMatch);
String flowId = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag() + "_"
+ ace.key().getRuleName();
int operation = addOrRemove == NwConstants.MOD_FLOW ? NwConstants.DEL_FLOW : addOrRemove;
addFlowEntryToList(flowEntries, port.getDpId(), getAclFilterCumDispatcherTable(), flowId, flowPriority,
0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, operation);
if (addOrRemove != NwConstants.DEL_FLOW) {
programAclForExistingTrafficTable(port, ace, addOrRemove, flowName, matches, flowPriority);
}
}
}
protected void programAceSpecificFlows(List<FlowEntity> flowEntries, AclInterface port, String aclName, Ace ace,
@Nullable Map<String, List<MatchInfoBase>> flowMap, Uuid remoteAclId, int addOrRemove) {
if (null == flowMap) {
return;
}
Integer remoteAclTag = this.aclServiceUtils.getAclTag(remoteAclId);
if (remoteAclTag == null || remoteAclTag == AclConstants.INVALID_ACL_TAG) {
LOG.error("remoteAclTag={} is null or invalid for remoteAclId={}", remoteAclTag, remoteAclId);
return;
}
List<MatchInfoBase> lportAndAclMatches =
AclServiceUtils.buildMatchesForLPortTagAndRemoteAclTag(port.getLPortTag(), remoteAclTag, serviceMode);
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getGotoInstructionInfo(getAclRemoteAclTable());
Integer flowPriority = this.aclServiceUtils.getAceFlowPriority(aclName);
for (Entry<String, List<MatchInfoBase>> entry : flowMap.entrySet()) {
String flowName = entry.getKey();
List<MatchInfoBase> matches = entry.getValue();
matches.addAll(lportAndAclMatches);
String flowId = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag() + "_"
+ ace.key().getRuleName();
int operation = addOrRemove == NwConstants.MOD_FLOW ? NwConstants.DEL_FLOW : addOrRemove;
addFlowEntryToList(flowEntries, port.getDpId(), getAclRuleBasedFilterTable(), flowId, flowPriority, 0, 0,
AclConstants.COOKIE_ACL_BASE, matches, instructions, operation);
if (addOrRemove != NwConstants.DEL_FLOW) {
programAclForExistingTrafficTable(port, ace, addOrRemove, flowName, matches, flowPriority);
}
}
}
private void programAclForExistingTrafficTable(AclInterface port, Ace ace, int addOrRemove, String flowName,
List<MatchInfoBase> matches, Integer priority) {
AceIp acl = (AceIp) ace.getMatches().getAceType();
final String newFlowName = flowName + this.directionString + "_" + port.getDpId() + "_" + port.getLPortTag()
+ "_" + ((acl.getAceIpVersion() instanceof AceIpv4) ? "_IPv4" : "_IPv6") + "_FlowAfterRuleDeleted";
final List<MatchInfoBase> newMatches =
matches.stream().filter(obj -> !(obj instanceof NxMatchCtState || obj instanceof MatchMetadata))
.collect(Collectors.toList());
newMatches.add(AclServiceUtils.buildLPortTagMatch(port.getLPortTag(), serviceMode));
newMatches.add(new NxMatchCtState(AclConstants.TRACKED_RPL_CT_STATE, AclConstants.TRACKED_RPL_CT_STATE_MASK));
List<InstructionInfo> instructions =
AclServiceUtils.createCtMarkInstructionForNewState(getAclFilterCumDispatcherTable(), port.getElanId());
// Reversing the flow add/delete operation for this table.
List<FlowEntity> flowEntries = new ArrayList<>();
int operation = (addOrRemove == NwConstants.ADD_FLOW) ? NwConstants.DEL_FLOW : NwConstants.ADD_FLOW;
addFlowEntryToList(flowEntries, port.getDpId(), getAclForExistingTrafficTable(), newFlowName, priority, 0,
AclServiceUtils.getHardTimoutForApplyStatefulChangeOnExistingTraffic(ace, aclServiceUtils),
AclConstants.COOKIE_ACL_BASE, newMatches, instructions, operation);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, operation);
}
@Override
public boolean removeAcl(AclInterface port) {
if (port.getDpId() == null) {
LOG.warn("Unable to find DP Id from ACL interface with id {}", port.getInterfaceId());
return false;
}
List<FlowEntity> flowEntries = new ArrayList<>();
programAcl(flowEntries, port, Action.REMOVE, NwConstants.DEL_FLOW);
updateRemoteAclFilterTable(flowEntries, port, NwConstants.DEL_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.DEL_FLOW);
return true;
}
@Override
public boolean applyAce(AclInterface port, String aclName, Ace ace) {
if (!port.isPortSecurityEnabled() || port.getDpId() == null) {
return false;
}
List<FlowEntity> flowEntries = new ArrayList<>();
programAceRule(flowEntries, port, aclName, ace, NwConstants.ADD_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.ADD_FLOW);
return true;
}
@Override
public boolean removeAce(AclInterface port, String aclName, Ace ace) {
if (!port.isPortSecurityEnabled() || port.getDpId() == null) {
return false;
}
List<FlowEntity> flowEntries = new ArrayList<>();
programAceRule(flowEntries, port, aclName, ace, NwConstants.MOD_FLOW);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + port.getInterfaceId(), flowEntries, NwConstants.DEL_FLOW);
return true;
}
@Override
public void updateRemoteAcl(Acl aclBefore, Acl aclAfter, Collection<AclInterface> portsBefore) {
handleRemoteAclUpdate(aclBefore, aclAfter, portsBefore);
}
/**
* Bind service.
*
* @param aclInterface the acl interface
*/
public abstract void bindService(AclInterface aclInterface);
/**
* Unbind service.
*
* @param aclInterface the acl interface
*/
protected abstract void unbindService(AclInterface aclInterface);
/**
* Programs the anti-spoofing rules.
*
* @param flowEntries the flow entries
* @param port the acl interface
* @param allowedAddresses the allowed addresses
* @param action add/modify/remove action
* @param addOrRemove addorRemove
*/
protected abstract void programAntiSpoofingRules(List<FlowEntity> flowEntries, AclInterface port,
List<AllowedAddressPairs> allowedAddresses, Action action, int addOrRemove);
/**
* Programs broadcast rules.
*
* @param flowEntries the flow entries
* @param port the Acl Interface port
* @param addOrRemove whether to delete or add flow
*/
protected abstract void programBroadcastRules(List<FlowEntity> flowEntries, AclInterface port, int addOrRemove);
protected abstract void programIcmpv6RARule(List<FlowEntity> flowEntries, AclInterface port,
List<SubnetInfo> subnets, int addOrRemove);
/**
* Add Flow to list.
*
* @param dpId
* the dpId
* @param tableId
* the tableId
* @param flowId
* the flowId
* @param priority
* the priority
* @param idleTimeOut
* the idle timeout
* @param hardTimeOut
* the hard timeout
* @param cookie
* the cookie
* @param matches
* the list of matches to be writted
* @param instructions
* the list of instruction to be written.
* @param addOrRemove
* add or remove the entries.
*/
protected void addFlowEntryToList(List<FlowEntity> flowEntries, BigInteger dpId, short tableId, String flowId,
int priority, int idleTimeOut, int hardTimeOut, BigInteger cookie, List<? extends MatchInfoBase> matches,
List<InstructionInfo> instructions, int addOrRemove) {
List<InstructionInfo> instructionInfos = null;
if (addOrRemove == NwConstants.ADD_FLOW) {
instructionInfos = instructions;
}
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, tableId, flowId, priority,
flowId, idleTimeOut, hardTimeOut, cookie, matches, instructionInfos);
LOG.trace("Adding flow to list: DpnId {}, flowId {}", dpId, flowId);
flowEntries.add(flowEntity);
}
protected void programFlows(String jobName, List<FlowEntity> flowEntries, int addOrRemove) {
List<List<FlowEntity>> flowEntityParts = Lists.partition(flowEntries, AclConstants.FLOWS_PER_TRANSACTION);
for (List<FlowEntity> part : flowEntityParts) {
jobCoordinator.enqueueJob(jobName,
() -> Collections.singletonList(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
tx -> {
if (addOrRemove == NwConstants.ADD_FLOW) {
for (FlowEntity flowEntity: part) {
mdsalManager.addFlow(tx, flowEntity);
}
} else {
for (FlowEntity flowEntity: part) {
mdsalManager.removeFlow(tx, flowEntity);
}
}
})), AclConstants.JOB_MAX_RETRIES);
}
}
protected List<InstructionInfo> getDispatcherTableResubmitInstructions() {
return getDispatcherTableResubmitInstructions(new ArrayList<>());
}
/**
* Gets the dispatcher table resubmit instructions based on ingress/egress service mode w.r.t switch.
*
* @param actionsInfos
* the actions infos
* @return the instructions for dispatcher table resubmit
*/
protected List<InstructionInfo> getDispatcherTableResubmitInstructions(List<ActionInfo> actionsInfos) {
short dispatcherTableId = NwConstants.LPORT_DISPATCHER_TABLE;
if (ServiceModeEgress.class.equals(this.serviceMode)) {
dispatcherTableId = NwConstants.EGRESS_LPORT_DISPATCHER_TABLE;
}
List<InstructionInfo> instructions = new ArrayList<>();
actionsInfos.add(new ActionNxResubmit(dispatcherTableId));
instructions.add(new InstructionApplyActions(actionsInfos));
return instructions;
}
protected void handleRemoteAclUpdate(Acl aclBefore, Acl aclAfter, Collection<AclInterface> portsBefore) {
String aclName = aclAfter.getAclName();
Collection<AclInterface> interfaceList = aclDataUtil.getInterfaceList(new Uuid(aclName));
if (interfaceList.isEmpty()) {
LOG.trace("handleRemoteAclUpdate: No interfaces found with ACL={}", aclName);
return;
}
Set<Uuid> remoteAclsBefore = AclServiceUtils.getRemoteAclIdsByDirection(aclBefore, this.direction);
Set<Uuid> remoteAclsAfter = AclServiceUtils.getRemoteAclIdsByDirection(aclAfter, this.direction);
Set<Uuid> remoteAclsAdded = new HashSet<>(remoteAclsAfter);
remoteAclsAdded.removeAll(remoteAclsBefore);
Set<Uuid> remoteAclsDeleted = new HashSet<>(remoteAclsBefore);
remoteAclsDeleted.removeAll(remoteAclsAfter);
List<FlowEntity> addFlowEntries = new ArrayList<>();
List<FlowEntity> deleteFlowEntries = new ArrayList<>();
if (!remoteAclsAdded.isEmpty() || !remoteAclsDeleted.isEmpty()) {
// delete and add flows in ACL dispatcher table for all applicable
// ports
for (AclInterface portBefore : portsBefore) {
programAclDispatcherTable(deleteFlowEntries, portBefore, NwConstants.DEL_FLOW);
}
for (AclInterface port : interfaceList) {
programAclDispatcherTable(addFlowEntries, port, NwConstants.ADD_FLOW);
}
}
Set<BigInteger> dpns = interfaceList.stream().map(AclInterface::getDpId).collect(Collectors.toSet());
programRemoteAclTable(deleteFlowEntries, aclName, remoteAclsDeleted, dpns, NwConstants.DEL_FLOW);
programRemoteAclTable(addFlowEntries, aclName, remoteAclsAdded, dpns, NwConstants.ADD_FLOW);
programFlows(aclName, deleteFlowEntries, NwConstants.DEL_FLOW);
programFlows(aclName, addFlowEntries, NwConstants.ADD_FLOW);
}
private void programRemoteAclTable(List<FlowEntity> flowEntries, String aclName, Set<Uuid> remoteAclIds,
Set<BigInteger> dpns, int addOrRemove) {
for (Uuid remoteAclId : remoteAclIds) {
Collection<AclInterface> remoteAclInterfaces = aclDataUtil.getInterfaceList(remoteAclId);
if (remoteAclInterfaces.isEmpty()) {
continue;
}
Set<AllowedAddressPairs> aaps =
remoteAclInterfaces.stream().map(AclInterface::getAllowedAddressPairs).flatMap(List::stream)
.filter(AclServiceUtils::isNotIpAllNetwork).collect(Collectors.toSet());
Integer aclTag = aclServiceUtils.getAclTag(remoteAclId);
if (addOrRemove == NwConstants.ADD_FLOW) {
for (BigInteger dpn : dpns) {
for (AllowedAddressPairs aap : aaps) {
programRemoteAclTableFlow(flowEntries, dpn, aclTag, aap, addOrRemove);
}
}
} else if (addOrRemove == NwConstants.DEL_FLOW) {
Set<BigInteger> remoteAclDpns = new HashSet<>();
Map<String, Set<AclInterface>> mapAclWithPortSet =
aclDataUtil.getRemoteAclInterfaces(remoteAclId, this.direction);
if (mapAclWithPortSet != null) {
Map<String, Set<AclInterface>> copyOfMapAclWithPortSet = new HashMap<>(mapAclWithPortSet);
copyOfMapAclWithPortSet.remove(aclName);
remoteAclDpns = collectDpns(copyOfMapAclWithPortSet);
}
Set<BigInteger> dpnsToOperate = new HashSet<>(dpns);
dpnsToOperate.removeAll(remoteAclDpns);
LOG.debug(
"Deleting flows in Remote ACL table for remoteAclId={}, direction={}, dpnsToOperate={}, "
+ "remoteAclDpns={}, dpns={}",
remoteAclId.getValue(), directionString, dpnsToOperate, remoteAclDpns, dpns);
for (BigInteger dpn : dpnsToOperate) {
for (AllowedAddressPairs aap : aaps) {
programRemoteAclTableFlow(flowEntries, dpn, aclTag, aap, addOrRemove);
}
}
}
}
}
private void updateRemoteAclFilterTable(List<FlowEntity> flowEntries, AclInterface port, int addOrRemove) {
updateRemoteAclFilterTable(flowEntries, port, port.getSecurityGroups(), port.getAllowedAddressPairs(),
addOrRemove);
}
private void updateRemoteAclFilterTable(List<FlowEntity> flowEntries, AclInterface port, List<Uuid> aclList,
List<AllowedAddressPairs> aaps, int addOrRemove) {
if (aclList == null) {
LOG.debug("Port {} without SGs", port.getInterfaceId());
return;
}
String portId = port.getInterfaceId();
LOG.trace("updateRemoteAclFilterTable for portId={}, aclList={}, aaps={}, addOrRemove={}", portId, aclList,
aaps, addOrRemove);
for (Uuid aclId : aclList) {
if (aclDataUtil.getRemoteAcl(aclId, this.direction) != null) {
Integer aclTag = aclServiceUtils.getAclTag(aclId);
if (addOrRemove == NwConstants.ADD_FLOW) {
syncRemoteAclTable(flowEntries, portId, aclId, aclTag, aaps, addOrRemove);
}
else if (addOrRemove == NwConstants.DEL_FLOW) {
jobCoordinator.enqueueJob(aclId.getValue().intern(), () -> {
List<FlowEntity> remoteTableFlowEntries = new ArrayList<>();
syncRemoteAclTable(remoteTableFlowEntries, portId, aclId, aclTag, aaps, addOrRemove);
programFlows(AclConstants.ACL_JOB_KEY_PREFIX + aclId.getValue(),
remoteTableFlowEntries, NwConstants.DEL_FLOW);
return Collections.emptyList();
});
}
}
}
Set<Uuid> remoteAclIds = aclServiceUtils.getRemoteAclIdsByDirection(aclList, direction);
for (Uuid remoteAclId : remoteAclIds) {
syncRemoteAclTableFromOtherDpns(flowEntries, port, remoteAclId, addOrRemove);
}
}
private void syncRemoteAclTable(List<FlowEntity> flowEntries, String portId, Uuid acl, Integer aclTag,
List<AllowedAddressPairs> aaps, int addOrRemove) {
Map<String, Set<AclInterface>> mapAclWithPortSet = aclDataUtil.getRemoteAclInterfaces(acl, this.direction);
Set<BigInteger> dpns = collectDpns(mapAclWithPortSet);
for (AllowedAddressPairs aap : aaps) {
if (!AclServiceUtils.isNotIpAllNetwork(aap)) {
continue;
}
if (aclServiceUtils.skipDeleteInCaseOfOverlappingIP(portId, acl, aap.getIpAddress(),
addOrRemove)) {
LOG.debug("Skipping delete of IP={} in remote ACL table for remoteAclId={}, portId={}",
aap.getIpAddress(), portId, acl.getValue());
continue;
}
for (BigInteger dpId : dpns) {
programRemoteAclTableFlow(flowEntries, dpId, aclTag, aap, addOrRemove);
}
}
}
private void syncRemoteAclTableFromOtherDpns(List<FlowEntity> flowEntries, AclInterface port, Uuid remoteAclId,
int addOrRemove) {
Collection<AclInterface> aclInterfaces = aclDataUtil.getInterfaceList(remoteAclId);
if (!aclInterfaces.isEmpty() && isFirstPortInDpnWithRemoteAclId(port, remoteAclId)) {
Integer aclTag = aclServiceUtils.getAclTag(remoteAclId);
for (AclInterface aclInterface : aclInterfaces) {
if (port.getInterfaceId().equals(aclInterface.getInterfaceId())) {
continue;
}
for (AllowedAddressPairs aap : aclInterface.getAllowedAddressPairs()) {
if (AclServiceUtils.isNotIpAllNetwork(aap)) {
programRemoteAclTableFlow(flowEntries, port.getDpId(), aclTag, aap, addOrRemove);
}
}
}
}
}
private boolean isFirstPortInDpnWithRemoteAclId(AclInterface port, Uuid remoteAclId) {
String portId = port.getInterfaceId();
BigInteger dpId = port.getDpId();
Map<String, Set<AclInterface>> remoteAclInterfacesMap =
aclDataUtil.getRemoteAclInterfaces(remoteAclId, direction);
if (remoteAclInterfacesMap != null) {
for (Set<AclInterface> interfaceSet : remoteAclInterfacesMap.values()) {
for (AclInterface aclInterface : interfaceSet) {
if (portId.equals(aclInterface.getInterfaceId())) {
continue;
}
if (dpId.equals(aclInterface.getDpId())) {
return false;
}
}
}
}
return true;
}
protected abstract void programRemoteAclTableFlow(List<FlowEntity> flowEntries, BigInteger dpId, Integer aclTag,
AllowedAddressPairs aap, int addOrRemove);
protected Set<BigInteger> collectDpns(@Nullable Map<String, Set<AclInterface>> mapAclWithPortSet) {
Set<BigInteger> dpns = new HashSet<>();
if (mapAclWithPortSet == null) {
return dpns;
}
for (Set<AclInterface> innerSet : mapAclWithPortSet.values()) {
if (innerSet == null) {
continue;
}
for (AclInterface inter : innerSet) {
dpns.add(inter.getDpId());
}
}
return dpns;
}
/**
* Programs the port specific fixed rules.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param allowedAddresses the allowed addresses
* @param lportTag the lport tag
* @param portId the portId
* @param action the action
* @param write whether to add or remove the flow.
*/
protected void programAclPortSpecificFixedRules(List<FlowEntity> flowEntries, BigInteger dpId,
List<AllowedAddressPairs> allowedAddresses, int lportTag, String portId, Action action, int write) {
programGotoClassifierTableRules(flowEntries, dpId, allowedAddresses, lportTag, write);
if (action == Action.ADD || action == Action.REMOVE) {
programConntrackRecircRules(flowEntries, dpId, allowedAddresses, lportTag, portId, write);
programPortSpecificDropRules(flowEntries, dpId, lportTag, write);
programAclCommitRules(flowEntries, dpId, lportTag, portId, write);
}
LOG.info("programAclPortSpecificFixedRules: flows for dpId={}, lportId={}, action={}, write={}", dpId, lportTag,
action, write);
}
protected abstract void programGotoClassifierTableRules(List<FlowEntity> flowEntries, BigInteger dpId,
List<AllowedAddressPairs> aaps, int lportTag, int addOrRemove);
/**
* Adds the rule to send the packet to the netfilter to check whether it is a known packet.
*
* @param flowEntries the flow entries
* @param dpId the dpId
* @param aaps the allowed address pairs
* @param lportTag the lport tag
* @param portId the portId
* @param addOrRemove whether to add or remove the flow
*/
protected void programConntrackRecircRules(List<FlowEntity> flowEntries, BigInteger dpId,
List<AllowedAddressPairs> aaps, int lportTag, String portId, int addOrRemove) {
if (AclServiceUtils.doesIpv4AddressExists(aaps)) {
programConntrackRecircRule(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV4, addOrRemove);
}
if (AclServiceUtils.doesIpv6AddressExists(aaps)) {
programConntrackRecircRule(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV6, addOrRemove);
}
}
protected void programConntrackRecircRule(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
String portId, MatchEthernetType matchEtherType, int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(matchEtherType);
matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
List<InstructionInfo> instructions = new ArrayList<>();
if (addOrRemove == NwConstants.ADD_FLOW) {
Long elanTag = getElanIdFromAclInterface(portId);
if (elanTag == null) {
LOG.error("ElanId not found for portId={}; Context: dpId={}, lportTag={}, addOrRemove={},", portId,
dpId, lportTag, addOrRemove);
return;
}
List<ActionInfo> actionsInfos = new ArrayList<>();
actionsInfos.add(new ActionNxConntrack(2, 0, 0, elanTag.intValue(), getAclForExistingTrafficTable()));
instructions.add(new InstructionApplyActions(actionsInfos));
}
String flowName =
this.directionString + "_Fixed_Conntrk_" + dpId + "_" + lportTag + "_" + matchEtherType + "_Recirc";
addFlowEntryToList(flowEntries, dpId, getAclConntrackSenderTable(), flowName,
AclConstants.ACL_DEFAULT_PRIORITY, 0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions,
addOrRemove);
}
/**
* Adds the rules to drop the unknown/invalid packets .
*
* @param flowEntries the flow entries
* @param dpId the dpId
* @param lportTag the lport tag
* @param addOrRemove whether to add or remove the flow
*/
protected void programPortSpecificDropRules(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
int addOrRemove) {
LOG.debug("Programming Drop Rules: DpId={}, lportTag={}, addOrRemove={}", dpId, lportTag, addOrRemove);
programConntrackInvalidDropRule(flowEntries, dpId, lportTag, addOrRemove);
programAclRuleMissDropRule(flowEntries, dpId, lportTag, addOrRemove);
}
/**
* Adds the rule to drop the conntrack invalid packets .
*
* @param flowEntries the flow entries
* @param dpId the dpId
* @param lportTag the lport tag
* @param addOrRemove whether to add or remove the flow
*/
protected void programConntrackInvalidDropRule(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
int addOrRemove) {
List<MatchInfoBase> matches = AclServiceOFFlowBuilder.addLPortTagMatches(lportTag,
AclConstants.TRACKED_INV_CT_STATE, AclConstants.TRACKED_INV_CT_STATE_MASK, serviceMode);
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
String flowId = this.directionString + "_Fixed_Conntrk_Drop" + dpId + "_" + lportTag + "_Tracked_Invalid";
addFlowEntryToList(flowEntries, dpId, getAclFilterCumDispatcherTable(), flowId,
AclConstants.CT_STATE_TRACKED_INVALID_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(lportTag),
matches, instructions, addOrRemove);
}
/**
* Program ACL rule miss drop rule for a port.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param lportTag the lport tag
* @param addOrRemove the add or remove
*/
protected void programAclRuleMissDropRule(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(AclServiceUtils.buildLPortTagMatch(lportTag, serviceMode));
List<InstructionInfo> instructions = AclServiceOFFlowBuilder.getDropInstructionInfo();
String flowId = this.directionString + "_Fixed_Acl_Rule_Miss_Drop_" + dpId + "_" + lportTag;
addFlowEntryToList(flowEntries, dpId, getAclFilterCumDispatcherTable(), flowId,
AclConstants.ACL_PORT_SPECIFIC_DROP_PRIORITY, 0, 0, AclServiceUtils.getDropFlowCookie(lportTag),
matches, instructions, addOrRemove);
}
/**
* Program acl commit rules.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param lportTag the lport tag
* @param portId the port id
* @param addOrRemove the add or remove
*/
protected void programAclCommitRules(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag, String portId,
int addOrRemove) {
programAclCommitRuleForConntrack(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV4, addOrRemove);
programAclCommitRuleForConntrack(flowEntries, dpId, lportTag, portId, MatchEthernetType.IPV6, addOrRemove);
programAclCommitRuleForNonConntrack(flowEntries, dpId, lportTag, addOrRemove);
}
/**
* Program acl commit rule for conntrack.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param lportTag the lport tag
* @param portId the port id
* @param matchEtherType the match ether type
* @param addOrRemove the add or remove
*/
protected void programAclCommitRuleForConntrack(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
String portId, MatchEthernetType matchEtherType, int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.add(matchEtherType);
matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndConntrackClassifierType(lportTag,
AclConntrackClassifierType.CONNTRACK_SUPPORTED, serviceMode));
List<ActionInfo> actionsInfos = new ArrayList<>();
if (addOrRemove == NwConstants.ADD_FLOW) {
Long elanId = getElanIdFromAclInterface(portId);
if (elanId == null) {
LOG.error("ElanId not found for portId={}; Context: dpId={}, lportTag={}, addOrRemove={}", portId, dpId,
lportTag, addOrRemove);
return;
}
List<NxCtAction> ctActionsList =
Lists.newArrayList(new ActionNxConntrack.NxCtMark(AclConstants.CT_MARK_EST_STATE));
actionsInfos.add(new ActionNxConntrack(2, 1, 0, elanId.intValue(), (short) 255, ctActionsList));
actionsInfos.add(new ActionNxCtClear());
}
List<InstructionInfo> instructions = getDispatcherTableResubmitInstructions(actionsInfos);
String flowName = directionString + "_Acl_Commit_Conntrack_" + dpId + "_" + lportTag + "_" + matchEtherType;
// Flow for conntrack traffic to commit and resubmit to dispatcher
addFlowEntryToList(flowEntries, dpId, getAclCommitterTable(), flowName, AclConstants.ACL_DEFAULT_PRIORITY,
0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, addOrRemove);
}
/**
* Program acl commit rule for non conntrack.
*
* @param flowEntries the flow entries
* @param dpId the dp id
* @param lportTag the lport tag
* @param addOrRemove the add or remove
*/
protected void programAclCommitRuleForNonConntrack(List<FlowEntity> flowEntries, BigInteger dpId, int lportTag,
int addOrRemove) {
List<MatchInfoBase> matches = new ArrayList<>();
matches.addAll(AclServiceUtils.buildMatchesForLPortTagAndConntrackClassifierType(lportTag,
AclConntrackClassifierType.NON_CONNTRACK_SUPPORTED, serviceMode));
List<InstructionInfo> instructions = getDispatcherTableResubmitInstructions();
String flowName = this.directionString + "_Acl_Commit_Non_Conntrack_" + dpId + "_" + lportTag;
// Flow for non-conntrack traffic to resubmit to dispatcher
addFlowEntryToList(flowEntries, dpId, getAclCommitterTable(), flowName, AclConstants.ACL_DEFAULT_PRIORITY,
0, 0, AclConstants.COOKIE_ACL_BASE, matches, instructions, addOrRemove);
}
@Nullable
protected Long getElanIdFromAclInterface(String elanInterfaceName) {
AclInterface aclInterface = aclInterfaceCache.get(elanInterfaceName);
if (null != aclInterface) {
return aclInterface.getElanId();
}
return null;
}
protected abstract boolean isValidDirection(Class<? extends DirectionBase> direction);
protected abstract short getAclConntrackSenderTable();
protected abstract short getAclForExistingTrafficTable();
protected abstract short getAclFilterCumDispatcherTable();
protected abstract short getAclRuleBasedFilterTable();
protected abstract short getAclRemoteAclTable();
protected abstract short getAclCommitterTable();
}
| NETVIRT-1522: Allowed address pair not updated
Port with SG enabled, when updated with Allowed address pair, newly
added address is not being added into Acl Tables.
Fixed the issue by changing the checks which was causing aap's to be
skipped during port update.
Change-Id: I14e12302483783f113d2244a6267f037d0282cf9
Signed-off-by: kiranvasudeva <[email protected]>
| aclservice/impl/src/main/java/org/opendaylight/netvirt/aclservice/AbstractAclServiceImpl.java | NETVIRT-1522: Allowed address pair not updated |
|
Java | agpl-3.0 | 4b842fc9c9f893d22a1dd62c85b4b4b2d22db2f3 | 0 | bhutchinson/kfs,smith750/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,smith750/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,kuali/kfs,kuali/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,kkronenb/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,ua-eas/kfs,ua-eas/kfs,kuali/kfs,quikkian-ua-devops/will-financials,kuali/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,ua-eas/kfs,kkronenb/kfs,kkronenb/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,kuali/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs | /*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.module.vendor.service.impl;
import org.kuali.core.bo.Parameter;
import org.kuali.core.service.KualiConfigurationService;
import org.kuali.core.util.ObjectUtils;
import org.kuali.core.web.format.FormatException;
import org.kuali.kfs.KFSConstants;
import org.kuali.kfs.KFSKeyConstants;
import org.kuali.module.vendor.VendorConstants;
import org.kuali.module.vendor.VendorParameterConstants;
import org.kuali.module.vendor.VendorRuleConstants;
import org.kuali.module.vendor.service.TaxNumberService;
public class TaxNumberServiceImpl implements TaxNumberService {
public KualiConfigurationService kualiConfigurationService;
/**
* Sets the kualiConfigurationService attribute value.
* @param kualiConfigurationService The kualiConfigurationService to set.
*/
public void setKualiConfigurationService(KualiConfigurationService kualiConfigurationService) {
this.kualiConfigurationService = kualiConfigurationService;
}
public static Parameter taxNumberFormats;
public static Parameter feinNumberFormats;
public static Parameter notAllowedTaxNumbers;
public String formatToDefaultFormat(String taxNbr) throws FormatException {
String digits = taxNbr.replaceAll("\\D", "");
Integer defaultTaxNumberDigits =
new Integer (kualiConfigurationService.getParameterValue(KFSConstants.VENDOR_NAMESPACE,VendorParameterConstants.Components.VENDOR,"DEFAULT_TAX_NUMBER_DIGITS"));
if (digits.length() < defaultTaxNumberDigits) {
throw new FormatException("Tax number has fewer than " + defaultTaxNumberDigits + " digits.", KFSKeyConstants.ERROR_CUSTOM, taxNbr);
}
else if (digits.length() > defaultTaxNumberDigits) {
throw new FormatException("Tax number has more than " + defaultTaxNumberDigits + " digits.", KFSKeyConstants.ERROR_CUSTOM, taxNbr);
}
else {
return digits;
}
}
/**
* A predicate to determine if a String field is all numbers
*
* @param field A String tax number
* @return True if String is numeric
*/
public boolean isStringAllNumbers(String field) {
if (!isStringEmpty(field)) {
field = field.trim();
for (int x = 0; x < field.length(); x++) {
char c = field.charAt(x);
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
return false;
}
/**
* A predicate to determine if a String field is null or empty
*
* @param field A String tax number
* @return True if String is null or empty
*/
public boolean isStringEmpty(String field) {
if (field == null || field.equals("")) {
return true;
}
else {
return false;
}
}
/**
* A predicate to determine the validity of tax numbers
* We're using regular expressions stored in the business rules table
* to validate whether the tax number is in the correct format.
* The regular expressions are : (please update this javadoc comment
* when the regular expressions change)
* 1. For SSN : (?!000)(?!666)(\d{3})([ \-]?)(?!00)(\d{2})([\-]?)(?!0000)(\d{4})
* 2. For FEIN : (?!00)(\d{3})([ \-]?)(\d{2})([\-]?)(?!0000)(\d{4})
*
* @param taxNbr A tax number String (SSN or FEIN)
* @param taxType determines SSN or FEIN tax number type
* @return True if the tax number is known to be in a valid format
*/
public boolean isValidTaxNumber( String taxNbr, String taxType ) {
String[] ssnFormats = parseSSNFormats();
String[] feinFormats = parseFEINFormats();
Integer defaultTaxNumberDigits =
new Integer (kualiConfigurationService.getParameterValue(KFSConstants.VENDOR_NAMESPACE,VendorParameterConstants.Components.VENDOR,"DEFAULT_TAX_NUMBER_DIGITS"));
if (taxNbr.length() != defaultTaxNumberDigits ||
!isStringAllNumbers(taxNbr)) {
return false;
}
if (taxType.equals(VendorConstants.TAX_TYPE_SSN)) {
for( int i = 0; i < ssnFormats.length; i++ ) {
if( taxNbr.matches( ssnFormats[i] ) ){
return true;
}
}
return false;
}
else if (taxType.equals(VendorConstants.TAX_TYPE_FEIN)) {
for( int i = 0; i < feinFormats.length; i++ ) {
if( taxNbr.matches( feinFormats[i] ) ){
return true;
}
}
return false;
}
return true;
}
/**
* Someday we'll have to use the rules table instead of
* using constants.
* This method will return true if the tax number is an allowed tax number
* and return false if it's not allowed.
*
* @param taxNbr The tax number to be processed.
* @return boolean true if the tax number is allowed and false otherwise.
*/
public boolean isAllowedTaxNumber(String taxNbr) {
String[] notAllowedTaxNumbers = parseNotAllowedTaxNumbers();
for (int i=0; i<notAllowedTaxNumbers.length; i++) {
if (taxNbr.matches(notAllowedTaxNumbers[i])) {
return false;
}
}
return true;
}
/**
* Splits the set of tax number formats which are returned from the rule service as a
* semicolon-delimeted String into a String array.
*
* @return A String array of the tax number format regular expressions.
*/
public String[] parseSSNFormats() {
if( ObjectUtils.isNull( taxNumberFormats ) ) {
taxNumberFormats = kualiConfigurationService.getParameter(
KFSConstants.VENDOR_NAMESPACE, VendorParameterConstants.Components.VENDOR, "TAX_SSN_NUMBER_FORMATS");
}
return kualiConfigurationService.getParameterValues( taxNumberFormats );
}
/**
* Splits the set of tax fein number formats which are returned from the rule service as a
* semicolon-delimeted String into a String array.
*
* @return A String array of the tax fein number format regular expressions.
*/
public String[] parseFEINFormats() {
if( ObjectUtils.isNull( feinNumberFormats ) ) {
feinNumberFormats = kualiConfigurationService.getParameter(
KFSConstants.VENDOR_NAMESPACE,VendorParameterConstants.Components.VENDOR,"TAX_FEIN_NUMBER_FORMATS");
}
return kualiConfigurationService.getParameterValues( feinNumberFormats );
}
/**
* Splits the set of not allowed tax number formats which are returned from the rule service as a
* semicolon-delimeted String into a String array.
*
* @return A String array of the not allowed tax number format regular expressions.
*/
public String[] parseNotAllowedTaxNumbers() {
if( ObjectUtils.isNull( notAllowedTaxNumbers ) ) {
notAllowedTaxNumbers = kualiConfigurationService.getParameter(
KFSConstants.VENDOR_NAMESPACE, VendorParameterConstants.Components.VENDOR, VendorRuleConstants.PURAP_NOT_ALLOWED_TAX_NUMBERS);
}
return kualiConfigurationService.getParameterValues( notAllowedTaxNumbers );
}
}
| work/src/org/kuali/kfs/vnd/service/impl/TaxNumberServiceImpl.java | /*
* Copyright 2007 The Kuali Foundation.
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.module.vendor.service.impl;
import org.kuali.core.bo.Parameter;
import org.kuali.core.service.KualiConfigurationService;
import org.kuali.core.util.ObjectUtils;
import org.kuali.core.web.format.FormatException;
import org.kuali.kfs.KFSConstants;
import org.kuali.kfs.KFSKeyConstants;
import org.kuali.module.vendor.VendorConstants;
import org.kuali.module.vendor.VendorParameterConstants;
import org.kuali.module.vendor.VendorRuleConstants;
import org.kuali.module.vendor.service.TaxNumberService;
public class TaxNumberServiceImpl implements TaxNumberService {
public KualiConfigurationService kualiConfigurationService;
/**
* Sets the kualiConfigurationService attribute value.
* @param kualiConfigurationService The kualiConfigurationService to set.
*/
public void setKualiConfigurationService(KualiConfigurationService kualiConfigurationService) {
this.kualiConfigurationService = kualiConfigurationService;
}
public static Parameter taxNumberFormats;
public static Parameter feinNumberFormats;
public static Parameter notAllowedTaxNumbers;
public String formatToDefaultFormat(String taxNbr) throws FormatException {
String digits = taxNbr.replaceAll("\\D", "");
Integer defaultTaxNumberDigits =
new Integer (kualiConfigurationService.getParameterValue(KFSConstants.VENDOR_NAMESPACE,VendorParameterConstants.Components.VENDOR,"DEFAULT_TAX_NUMBER_DIGITS"));
if (digits.length() < defaultTaxNumberDigits) {
throw new FormatException("Tax number has fewer than " + defaultTaxNumberDigits + " digits.", KFSKeyConstants.ERROR_CUSTOM, taxNbr);
}
else if (digits.length() > defaultTaxNumberDigits) {
throw new FormatException("Tax number has more than " + defaultTaxNumberDigits + " digits.", KFSKeyConstants.ERROR_CUSTOM, taxNbr);
}
else {
return digits;
}
}
/**
* A predicate to determine if a String field is all numbers
*
* @param field A String tax number
* @return True if String is numeric
*/
public boolean isStringAllNumbers(String field) {
if (!isStringEmpty(field)) {
field = field.trim();
for (int x = 0; x < field.length(); x++) {
char c = field.charAt(x);
if (!Character.isDigit(c)) {
return false;
}
}
return true;
}
return false;
}
/**
* A predicate to determine if a String field is null or empty
*
* @param field A String tax number
* @return True if String is null or empty
*/
public boolean isStringEmpty(String field) {
if (field == null || field.equals("")) {
return true;
}
else {
return false;
}
}
/**
* A predicate to determine the validity of tax numbers
* We're using regular expressions stored in the business rules table
* to validate whether the tax number is in the correct format.
* The regular expressions are : (please update this javadoc comment
* when the regular expressions change)
* 1. For SSN : (?!000)(?!666)(\d{3})([ \-]?)(?!00)(\d{2})([\-]?)(?!0000)(\d{4})
* 2. For FEIN : (?!00)(\d{3})([ \-]?)(\d{2})([\-]?)(?!0000)(\d{4})
*
* @param taxNbr A tax number String (SSN or FEIN)
* @param taxType determines SSN or FEIN tax number type
* @return True if the tax number is known to be in a valid format
*/
public boolean isValidTaxNumber( String taxNbr, String taxType ) {
String[] ssnFormats = parseSSNFormats();
String[] feinFormats = parseFEINFormats();
Integer defaultTaxNumberDigits =
new Integer (kualiConfigurationService.getParameterValue(KFSConstants.VENDOR_NAMESPACE,VendorParameterConstants.Components.VENDOR,"DEFAULT_TAX_NUMBER_DIGITS"));
if (taxNbr.length() != defaultTaxNumberDigits ||
!isStringAllNumbers(taxNbr)) {
return false;
}
if (taxType.equals(VendorConstants.TAX_TYPE_SSN)) {
for( int i = 0; i < ssnFormats.length; i++ ) {
if( taxNbr.matches( ssnFormats[i] ) ){
return true;
}
}
return false;
}
else if (taxType.equals(VendorConstants.TAX_TYPE_FEIN)) {
for( int i = 0; i < feinFormats.length; i++ ) {
if( taxNbr.matches( feinFormats[i] ) ){
return true;
}
}
return false;
}
return true;
}
/**
* Someday we'll have to use the rules table instead of
* using constants.
* This method will return true if the tax number is an allowed tax number
* and return false if it's not allowed.
*
* @param taxNbr The tax number to be processed.
* @return boolean true if the tax number is allowed and false otherwise.
*/
public boolean isAllowedTaxNumber(String taxNbr) {
String[] notAllowedTaxNumbers = parseNotAllowedTaxNumbers();
for (int i=0; i<notAllowedTaxNumbers.length; i++) {
if (taxNbr.matches(notAllowedTaxNumbers[i])) {
return false;
}
}
return true;
}
/**
* Splits the set of tax number formats which are returned from the rule service as a
* semicolon-delimeted String into a String array.
*
* @return A String array of the tax number format regular expressions.
*/
public String[] parseSSNFormats() {
if( ObjectUtils.isNull( taxNumberFormats ) ) {
taxNumberFormats = kualiConfigurationService.getParameter(
KFSConstants.VENDOR_NAMESPACE, VendorParameterConstants.Components.VENDOR, "TAX_SSN_NUMBER_FORMATS");
}
return kualiConfigurationService.getParameterValues( taxNumberFormats );
}
/**
* Splits the set of tax fein number formats which are returned from the rule service as a
* semicolon-delimeted String into a String array.
*
* @return A String array of the tax fein number format regular expressions.
*/
public String[] parseFEINFormats() {
if( ObjectUtils.isNull( feinNumberFormats ) ) {
feinNumberFormats = kualiConfigurationService.getParameter(
KFSConstants.VENDOR_NAMESPACE,VendorParameterConstants.Components.VENDOR,"TAX_FEIN_NUMBER_FORMATS");
}
return kualiConfigurationService.getParameterValues( feinNumberFormats );
}
/**
* Splits the set of not allowed tax number formats which are returned from the rule service as a
* semicolon-delimeted String into a String array.
*
* @return A String array of the not allowed tax number format regular expressions.
*/
public String[] parseNotAllowedTaxNumbers() {
if( ObjectUtils.isNull( notAllowedTaxNumbers ) ) {
notAllowedTaxNumbers = kualiConfigurationService.getParameter(
KFSConstants.PURAP_NAMESPACE, VendorParameterConstants.Components.VENDOR, VendorRuleConstants.PURAP_NOT_ALLOWED_TAX_NUMBERS);
}
return kualiConfigurationService.getParameterValues( notAllowedTaxNumbers );
}
}
| KULRNE-5800
| work/src/org/kuali/kfs/vnd/service/impl/TaxNumberServiceImpl.java | KULRNE-5800 |
|
Java | agpl-3.0 | 551c920402e925b1a03b5fcf5f336d031391af7a | 0 | qiuyesuifeng/sql-layer,jaytaylor/sql-layer,wfxiang08/sql-layer-1,ngaut/sql-layer,shunwang/sql-layer-1,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,ngaut/sql-layer,shunwang/sql-layer-1,ngaut/sql-layer,relateiq/sql-layer,relateiq/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,relateiq/sql-layer,wfxiang08/sql-layer-1 | /**
* Copyright (C) 2009-2013 Akiban Technologies, 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/>.
*/
package com.akiban.sql.pg;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import com.akiban.sql.optimizer.plan.CostEstimate;
import com.akiban.sql.parser.ParameterNode;
import com.akiban.sql.parser.StatementNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.akiban.server.error.AkibanInternalException;
import com.akiban.server.error.ConnectionTerminatedException;
import com.akiban.server.error.InvalidOperationException;
import com.akiban.server.error.SecurityException;
import com.akiban.server.error.UnsupportedConfigurationException;
import com.akiban.sql.parser.AlterServerNode;
public class PostgresServerStatement implements PostgresStatement {
private static final Logger LOG = LoggerFactory.getLogger(PostgresServerStatement.class);
private final AlterServerNode statement;
private long aisGeneration;
protected PostgresServerStatement (AlterServerNode stmt) {
this.statement = stmt;
}
@Override
public TransactionMode getTransactionMode() {
return TransactionMode.ALLOWED;
}
@Override
public TransactionAbortedMode getTransactionAbortedMode() {
return TransactionAbortedMode.ALLOWED;
}
@Override
public AISGenerationMode getAISGenerationMode() {
return AISGenerationMode.ALLOWED;
}
@Override
public PostgresType[] getParameterTypes() {
return null;
}
@Override
public void sendDescription(PostgresQueryContext context,
boolean always, boolean params)
throws IOException {
if (always) {
PostgresServerSession server = context.getServer();
PostgresMessenger messenger = server.getMessenger();
if (params) {
messenger.beginMessage(PostgresMessages.PARAMETER_DESCRIPTION_TYPE.code());
messenger.writeShort(0);
messenger.sendMessage();
}
messenger.beginMessage(PostgresMessages.NO_DATA_TYPE.code());
messenger.sendMessage();
}
}
@Override
public int execute(PostgresQueryContext context, int maxrows) throws IOException {
context.checkQueryCancelation();
PostgresServerSession server = context.getServer();
try {
doOperation(server);
} catch (Exception e) {
if (!(e instanceof ConnectionTerminatedException))
LOG.error("Execute command failed: " + e.getMessage());
if (e instanceof IOException)
throw (IOException)e;
else if (e instanceof InvalidOperationException) {
throw (InvalidOperationException)e;
}
throw new AkibanInternalException ("PostgrsServerStatement execute failed.", e);
}
return 0;
}
@Override
public boolean hasAISGeneration() {
return aisGeneration != 0;
}
@Override
public void setAISGeneration(long aisGeneration) {
this.aisGeneration = aisGeneration;
}
@Override
public long getAISGeneration() {
return aisGeneration;
}
@Override
public PostgresStatement finishGenerating(PostgresServerSession server,
String sql, StatementNode stmt,
List<ParameterNode> params, int[] paramTypes) {
return this;
}
@Override
public boolean putInCache() {
return false;
}
@Override
public CostEstimate getCostEstimate() {
return null;
}
protected void doOperation (PostgresServerSession session) throws Exception {
if (!session.getSecurityService().hasRestrictedAccess(session.getSession()))
throw new SecurityException("Operation not allowed");
PostgresServerConnection current = (PostgresServerConnection)session;
PostgresServer server = current.getServer();
Integer sessionId = statement.getSessionID();
String byUser = session.getProperty("user");
String completeCurrent = null;
/*
* Note: Caution when adding new types and check execution under ROLLBACK, see getTransactionAbortedMode()
*/
switch (statement.getAlterSessionType()) {
case SET_SERVER_VARIABLE:
setVariable (session, statement.getVariable(), statement.getValue());
sendComplete (session.getMessenger());
break;
case INTERRUPT_SESSION:
if (sessionId == null) {
for (PostgresServerConnection conn : server.getConnections()) {
if (conn != current)
conn.cancelQuery(null, byUser);
}
}
else {
PostgresServerConnection conn = server.getConnection(sessionId);
if ((conn != null) && (conn != current))
conn.cancelQuery(null, byUser);
}
sendComplete (session.getMessenger());
break;
case DISCONNECT_SESSION:
case KILL_SESSION:
{
String msg = "your session being disconnected";
if (sessionId == null) {
Collection<PostgresServerConnection> conns = server.getConnections();
for (PostgresServerConnection conn : conns) {
if (conn == current)
completeCurrent = msg;
else
conn.cancelQuery(msg, byUser);
}
for (PostgresServerConnection conn : conns) {
if (conn != current)
conn.waitAndStop();
}
}
else {
PostgresServerConnection conn = server.getConnection(sessionId);
if (conn == current)
completeCurrent = msg;
else if (conn != null) {
conn.cancelQuery(msg, byUser);
conn.waitAndStop();
}
// TODO: Else no such session error?
}
}
if (completeCurrent == null)
sendComplete(session.getMessenger());
break;
case SHUTDOWN:
{
String msg = "Akiban server being shutdown";
Collection<PostgresServerConnection> conns = server.getConnections();
for (PostgresServerConnection conn : conns) {
if (conn == current)
completeCurrent = msg;
else if (!statement.isShutdownImmediate())
conn.cancelQuery(msg, byUser);
}
if (!statement.isShutdownImmediate()) {
for (PostgresServerConnection conn : conns) {
if (conn != current)
conn.waitAndStop();
}
}
shutdown();
}
// Note: no command completion, since always terminating.
break;
}
// Now finally do what was indicated for the current connection.
if (completeCurrent != null)
throw new ConnectionTerminatedException(completeCurrent);
}
protected void setVariable(PostgresServerSession server, String variable, String value) {
if (!Arrays.asList(PostgresSessionStatement.ALLOWED_CONFIGURATION).contains(variable))
throw new UnsupportedConfigurationException (variable);
server.setProperty(variable, value);
}
protected void sendComplete (PostgresMessenger messenger) throws IOException {
messenger.beginMessage(PostgresMessages.COMMAND_COMPLETE_TYPE.code());
messenger.writeString(statement.statementToString());
messenger.sendMessage();
}
protected void shutdown () throws Exception {
new Thread() {
@Override
public void run() {
try {
MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
jmxServer.invoke(new ObjectName ("com.akiban:type=SHUTDOWN"), "shutdown", new Object[0], new String[0]);
}
catch (Exception ex) {
LOG.error("Shutdown failed", ex);
}
}
}.start();
}
}
| src/main/java/com/akiban/sql/pg/PostgresServerStatement.java | /**
* Copyright (C) 2009-2013 Akiban Technologies, 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/>.
*/
package com.akiban.sql.pg;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import com.akiban.sql.optimizer.plan.CostEstimate;
import com.akiban.sql.parser.ParameterNode;
import com.akiban.sql.parser.StatementNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.akiban.server.error.AkibanInternalException;
import com.akiban.server.error.ConnectionTerminatedException;
import com.akiban.server.error.InvalidOperationException;
import com.akiban.server.error.UnsupportedConfigurationException;
import com.akiban.sql.parser.AlterServerNode;
public class PostgresServerStatement implements PostgresStatement {
private static final Logger LOG = LoggerFactory.getLogger(PostgresServerStatement.class);
private final AlterServerNode statement;
private long aisGeneration;
protected PostgresServerStatement (AlterServerNode stmt) {
this.statement = stmt;
}
@Override
public TransactionMode getTransactionMode() {
return TransactionMode.ALLOWED;
}
@Override
public TransactionAbortedMode getTransactionAbortedMode() {
return TransactionAbortedMode.ALLOWED;
}
@Override
public AISGenerationMode getAISGenerationMode() {
return AISGenerationMode.ALLOWED;
}
@Override
public PostgresType[] getParameterTypes() {
return null;
}
@Override
public void sendDescription(PostgresQueryContext context,
boolean always, boolean params)
throws IOException {
if (always) {
PostgresServerSession server = context.getServer();
PostgresMessenger messenger = server.getMessenger();
if (params) {
messenger.beginMessage(PostgresMessages.PARAMETER_DESCRIPTION_TYPE.code());
messenger.writeShort(0);
messenger.sendMessage();
}
messenger.beginMessage(PostgresMessages.NO_DATA_TYPE.code());
messenger.sendMessage();
}
}
@Override
public int execute(PostgresQueryContext context, int maxrows) throws IOException {
context.checkQueryCancelation();
PostgresServerSession server = context.getServer();
try {
doOperation(server);
} catch (Exception e) {
if (!(e instanceof ConnectionTerminatedException))
LOG.error("Execute command failed: " + e.getMessage());
if (e instanceof IOException)
throw (IOException)e;
else if (e instanceof InvalidOperationException) {
throw (InvalidOperationException)e;
}
throw new AkibanInternalException ("PostgrsServerStatement execute failed.", e);
}
return 0;
}
@Override
public boolean hasAISGeneration() {
return aisGeneration != 0;
}
@Override
public void setAISGeneration(long aisGeneration) {
this.aisGeneration = aisGeneration;
}
@Override
public long getAISGeneration() {
return aisGeneration;
}
@Override
public PostgresStatement finishGenerating(PostgresServerSession server,
String sql, StatementNode stmt,
List<ParameterNode> params, int[] paramTypes) {
return this;
}
@Override
public boolean putInCache() {
return false;
}
@Override
public CostEstimate getCostEstimate() {
return null;
}
protected void doOperation (PostgresServerSession session) throws Exception {
PostgresServerConnection current = (PostgresServerConnection)session;
PostgresServer server = current.getServer();
Integer sessionId = statement.getSessionID();
String byUser = session.getProperty("user");
String completeCurrent = null;
/*
* Note: Caution when adding new types and check execution under ROLLBACK, see getTransactionAbortedMode()
*/
switch (statement.getAlterSessionType()) {
case SET_SERVER_VARIABLE:
setVariable (session, statement.getVariable(), statement.getValue());
sendComplete (session.getMessenger());
break;
case INTERRUPT_SESSION:
if (sessionId == null) {
for (PostgresServerConnection conn : server.getConnections()) {
if (conn != current)
conn.cancelQuery(null, byUser);
}
}
else {
PostgresServerConnection conn = server.getConnection(sessionId);
if ((conn != null) && (conn != current))
conn.cancelQuery(null, byUser);
}
sendComplete (session.getMessenger());
break;
case DISCONNECT_SESSION:
case KILL_SESSION:
{
String msg = "your session being disconnected";
if (sessionId == null) {
Collection<PostgresServerConnection> conns = server.getConnections();
for (PostgresServerConnection conn : conns) {
if (conn == current)
completeCurrent = msg;
else
conn.cancelQuery(msg, byUser);
}
for (PostgresServerConnection conn : conns) {
if (conn != current)
conn.waitAndStop();
}
}
else {
PostgresServerConnection conn = server.getConnection(sessionId);
if (conn == current)
completeCurrent = msg;
else if (conn != null) {
conn.cancelQuery(msg, byUser);
conn.waitAndStop();
}
// TODO: Else no such session error?
}
}
if (completeCurrent == null)
sendComplete(session.getMessenger());
break;
case SHUTDOWN:
{
String msg = "Akiban server being shutdown";
Collection<PostgresServerConnection> conns = server.getConnections();
for (PostgresServerConnection conn : conns) {
if (conn == current)
completeCurrent = msg;
else if (!statement.isShutdownImmediate())
conn.cancelQuery(msg, byUser);
}
if (!statement.isShutdownImmediate()) {
for (PostgresServerConnection conn : conns) {
if (conn != current)
conn.waitAndStop();
}
}
shutdown();
}
// Note: no command completion, since always terminating.
break;
}
// Now finally do what was indicated for the current connection.
if (completeCurrent != null)
throw new ConnectionTerminatedException(completeCurrent);
}
protected void setVariable(PostgresServerSession server, String variable, String value) {
if (!Arrays.asList(PostgresSessionStatement.ALLOWED_CONFIGURATION).contains(variable))
throw new UnsupportedConfigurationException (variable);
server.setProperty(variable, value);
}
protected void sendComplete (PostgresMessenger messenger) throws IOException {
messenger.beginMessage(PostgresMessages.COMMAND_COMPLETE_TYPE.code());
messenger.writeString(statement.statementToString());
messenger.sendMessage();
}
protected void shutdown () throws Exception {
new Thread() {
@Override
public void run() {
try {
MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
jmxServer.invoke(new ObjectName ("com.akiban:type=SHUTDOWN"), "shutdown", new Object[0], new String[0]);
}
catch (Exception ex) {
LOG.error("Shutdown failed", ex);
}
}
}.start();
}
}
| Use the same new check for ALTER SERVER.
| src/main/java/com/akiban/sql/pg/PostgresServerStatement.java | Use the same new check for ALTER SERVER. |
|
Java | agpl-3.0 | c2836d7aade35173c92e8113b5bdfd50380e55ee | 0 | quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,bhutchinson/kfs,kuali/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,kkronenb/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,smith750/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,kuali/kfs,kuali/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,smith750/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,bhutchinson/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kuali/kfs | /*
* Kuali License Info
*/
/*
* Copyright (c) 2004, 2005 The National Association of College and University Business Officers,
* Cornell University, Trustees of Indiana University, Michigan State University Board of Trustees,
* Trustees of San Joaquin Delta College, University of Hawai'i, The Arizona Board of Regents on
* behalf of the University of Arizona, and the r*smart group.
*
* Licensed under the Educational Community License Version 1.0 (the "License"); By obtaining,
* using and/or copying this Original Work, you agree that you have read, understand, and will
* comply with the terms and conditions of the Educational Community License.
*
* You may obtain a copy of the License at:
*
* http://kualiproject.org/license.html
*
* 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 org.kuali.module.financial.service.impl;
import static org.kuali.Constants.GL_CREDIT_CODE;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.AUTO_APPROVE_DOCUMENTS_IND;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.AUTO_APPROVE_NUMBER_OF_DAYS;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.DEFAULT_TRANS_ACCOUNT_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.DEFAULT_TRANS_CHART_CODE_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.DEFAULT_TRANS_OBJECT_CODE_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.ERROR_TRANS_ACCOUNT_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.ERROR_TRANS_CHART_CODE_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.PCARD_DOCUMENT_PARAMETERS_SEC_GROUP;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.SINGLE_TRANSACTION_IND_PARM_NM;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.kuali.Constants;
import org.kuali.PropertyConstants;
import org.kuali.core.bo.AttributeReferenceDummy;
import org.kuali.core.rule.event.SaveOnlyDocumentEvent;
import org.kuali.core.service.BusinessObjectService;
import org.kuali.core.service.DataDictionaryService;
import org.kuali.core.service.DateTimeService;
import org.kuali.core.service.DocumentService;
import org.kuali.core.service.KualiConfigurationService;
import org.kuali.core.util.DateUtils;
import org.kuali.core.util.ErrorMap;
import org.kuali.core.util.GlobalVariables;
import org.kuali.core.util.KualiDecimal;
import org.kuali.core.web.format.TimestampFormatter;
import org.kuali.core.workflow.service.WorkflowDocumentService;
import org.kuali.module.financial.bo.ProcurementCardHolder;
import org.kuali.module.financial.bo.ProcurementCardSourceAccountingLine;
import org.kuali.module.financial.bo.ProcurementCardTargetAccountingLine;
import org.kuali.module.financial.bo.ProcurementCardTransaction;
import org.kuali.module.financial.bo.ProcurementCardTransactionDetail;
import org.kuali.module.financial.bo.ProcurementCardVendor;
import org.kuali.module.financial.document.ProcurementCardDocument;
import org.kuali.module.financial.rules.AccountingLineRuleUtil;
import org.kuali.module.financial.service.ProcurementCardCreateDocumentService;
import edu.iu.uis.eden.exception.WorkflowException;
/**
* Implementation of ProcurementCardCreateDocumentService
*
* @see org.kuali.module.financial.service.ProcurementCardCreateDocumentService
* @author Kuali Financial Transactions Team ([email protected])
*/
public class ProcurementCardCreateDocumentServiceImpl implements ProcurementCardCreateDocumentService {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ProcurementCardCreateDocumentServiceImpl.class);
private KualiConfigurationService kualiConfigurationService;
private BusinessObjectService businessObjectService;
private DocumentService documentService;
private DataDictionaryService dataDictionaryService;
private DateTimeService dateTimeService;
private WorkflowDocumentService workflowDocumentService;
/**
* @see org.kuali.module.financial.service.ProcurementCardCreateDocumentService#createProcurementCardDocuments()
*/
public boolean createProcurementCardDocuments() {
List documents = new ArrayList();
List cardTransactions = retrieveTransactions();
// iterate through card transaction list and create documents
for (Iterator iter = cardTransactions.iterator(); iter.hasNext();) {
documents.add(createProcurementCardDocument((List) iter.next()));
}
// now store all the documents
for (Iterator iter = documents.iterator(); iter.hasNext();) {
ProcurementCardDocument pcardDocument = (ProcurementCardDocument) iter.next();
try {
documentService.validateAndPersistDocument(pcardDocument, new SaveOnlyDocumentEvent(pcardDocument));
}
catch (Exception e) {
LOG.error("Error persisting document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + " " + e.getMessage());
throw new RuntimeException("Error persisting document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + " " + e.getMessage());
}
}
return true;
}
/**
* Routes all pcard documents in 'I' status.
*
* @see org.kuali.module.financial.service.ProcurementCardCreateDocumentService#routeProcurementCardDocuments(java.util.List)
*/
public boolean routeProcurementCardDocuments() {
List documentList = new ArrayList();
try {
documentList = (List) documentService.findByDocumentHeaderStatusCode(ProcurementCardDocument.class, Constants.DocumentStatusCodes.INITIATED);
}
catch (WorkflowException e1) {
LOG.error("Error retrieving pcdo documents for routing: " + e1.getMessage());
throw new RuntimeException(e1.getMessage());
}
for (Iterator iter = documentList.iterator(); iter.hasNext();) {
ProcurementCardDocument pcardDocument = (ProcurementCardDocument) iter.next();
try {
LOG.info("Routing PCDO document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + ".");
documentService.prepareWorkflowDocument(pcardDocument);
// calling workflow service to bypass business rule checks
workflowDocumentService.route(pcardDocument.getDocumentHeader().getWorkflowDocument(), "", null);
}
catch (WorkflowException e) {
LOG.error("Error routing document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + " " + e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
return true;
}
/**
* @see org.kuali.module.financial.service.ProcurementCardCreateDocumentService#autoApproveProcurementCardDocuments()
*/
public boolean autoApproveProcurementCardDocuments() {
// check if auto approve is turned on
boolean autoApproveOn = kualiConfigurationService.getApplicationParameterIndicator(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, AUTO_APPROVE_DOCUMENTS_IND);
if (!autoApproveOn) {
return true;
}
List documentList = new ArrayList();
try {
documentList = (List) documentService.findByDocumentHeaderStatusCode(ProcurementCardDocument.class, Constants.DocumentStatusCodes.ENROUTE);
}
catch (WorkflowException e1) {
throw new RuntimeException(e1.getMessage());
}
// get number of days and type for autoapprove
int autoApproveNumberDays = Integer.parseInt(kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, AUTO_APPROVE_NUMBER_OF_DAYS));
Timestamp currentDate = dateTimeService.getCurrentTimestamp();
for (Iterator iter = documentList.iterator(); iter.hasNext();) {
ProcurementCardDocument pcardDocument = (ProcurementCardDocument) iter.next();
Timestamp docCreateDate = pcardDocument.getDocumentHeader().getWorkflowDocument().getCreateDate();
// if number of days in route is passed the allowed number, call doc service for super user approve
if (DateUtils.getDifferenceInDays(docCreateDate, currentDate) > autoApproveNumberDays) {
// update document description to reflect the auto approval
pcardDocument.getDocumentHeader().setFinancialDocumentDescription("Auto Approved On " + (new TimestampFormatter()).format(currentDate) + ".");
try {
LOG.info("Auto approving document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber());
documentService.superUserApproveDocument(pcardDocument, "");
}
catch (WorkflowException e) {
LOG.error("Error auto approving document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + " " + e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
}
return true;
}
/**
* retrieves list of transactions from temporary table, and groups them into document lists, based on single transaction
* indicator or grouping of card
*
* @return List of List containing transactions for document
*/
private List retrieveTransactions() {
List groupedTransactions = new ArrayList();
// retrieve records from transaction table order by card number
List transactions = (List) businessObjectService.findMatchingOrderBy(ProcurementCardTransaction.class, new HashMap(), PropertyConstants.TRANSACTION_CREDIT_CARD_NUMBER, true);
// check apc for single transaction documents or multple by card
boolean singleTransaction = kualiConfigurationService.getApplicationParameterIndicator(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, SINGLE_TRANSACTION_IND_PARM_NM);
List documentTransactions = new ArrayList();
if (singleTransaction) {
for (Iterator iter = transactions.iterator(); iter.hasNext();) {
documentTransactions.add(iter.next());
groupedTransactions.add(documentTransactions);
documentTransactions = new ArrayList();
}
}
else {
Map cardTransactionsMap = new HashMap();
for (Iterator iter = transactions.iterator(); iter.hasNext();) {
ProcurementCardTransaction transaction = (ProcurementCardTransaction) iter.next();
if (!cardTransactionsMap.containsKey(transaction.getTransactionCreditCardNumber())) {
cardTransactionsMap.put(transaction.getTransactionCreditCardNumber(), new ArrayList());
}
((List) cardTransactionsMap.get(transaction.getTransactionCreditCardNumber())).add(transaction);
}
for (Iterator iter = cardTransactionsMap.values().iterator(); iter.hasNext();) {
groupedTransactions.add(iter.next());
}
}
return groupedTransactions;
}
/**
* Creates a ProcurementCardDocument from the List of transactions
*
* @param transactions - List of ProcurementCardTransaction objects
* @return ProcurementCardDocument
*/
private ProcurementCardDocument createProcurementCardDocument(List transactions) {
ProcurementCardDocument pcardDocument = null;
try {
// get new document from doc service
pcardDocument = (ProcurementCardDocument) documentService.getNewDocument(ProcurementCardDocument.class);
// set the card holder record on the document from the first transaction
createCardHolderRecord(pcardDocument, (ProcurementCardTransaction) transactions.get(0));
// for each transaction, create transaction detail object and then acct lines for the detail
int transactionLineNumber = 1;
KualiDecimal documentTotalAmount = new KualiDecimal(0);
String errorText = "";
for (Iterator iter = transactions.iterator(); iter.hasNext();) {
ProcurementCardTransaction transaction = (ProcurementCardTransaction) iter.next();
// create transaction detail record with accounting lines
errorText += createTransactionDetailRecord(pcardDocument, transaction, transactionLineNumber);
// update document total
documentTotalAmount = documentTotalAmount.add(transaction.getFinancialDocumentTotalAmount());
transactionLineNumber++;
}
pcardDocument.getDocumentHeader().setFinancialDocumentTotalAmount(documentTotalAmount);
pcardDocument.getDocumentHeader().setFinancialDocumentDescription("SYSTEM Generated");
// Remove duplicate messages from errorText
String messages[] = StringUtils.split(errorText, ".");
for (int i = 0; i < messages.length; i++) {
int countMatches = StringUtils.countMatches(errorText, messages[i]) - 1;
errorText = StringUtils.replace(errorText, messages[i] + ".", "", countMatches);
}
// In case errorText is still too long, truncate it and indicate so.
int documentExplanationMaxLength = dataDictionaryService.getAttributeMaxLength(AttributeReferenceDummy.class.getName(), PropertyConstants.DOCUMENT_EXPLANATION);
if (errorText.length() <= documentExplanationMaxLength) {
pcardDocument.setExplanation(errorText);
} else {
String tuncatedMessage = " ... TRUNCATED.";
errorText = errorText.substring(0, documentExplanationMaxLength - tuncatedMessage.length()) + tuncatedMessage;
}
}
catch (WorkflowException e) {
LOG.error("Error creating pcdo documents: " + e.getMessage());
throw new RuntimeException("Error creating pcdo documents: " + e.getMessage());
}
return pcardDocument;
}
/**
* Creates card holder record and sets in document.
*
* @param pcardDocument - document to place record in
* @param transaction - transaction to set fields from
*/
private void createCardHolderRecord(ProcurementCardDocument pcardDocument, ProcurementCardTransaction transaction) {
ProcurementCardHolder cardHolder = new ProcurementCardHolder();
cardHolder.setFinancialDocumentNumber(pcardDocument.getFinancialDocumentNumber());
cardHolder.setAccountNumber(transaction.getAccountNumber());
cardHolder.setCardCycleAmountLimit(transaction.getCardCycleAmountLimit());
cardHolder.setCardCycleVolumeLimit(transaction.getCardCycleVolumeLimit());
cardHolder.setCardHolderAlternateName(transaction.getCardHolderAlternateName());
cardHolder.setCardHolderCityName(transaction.getCardHolderCityName());
cardHolder.setCardHolderLine1Address(transaction.getCardHolderLine1Address());
cardHolder.setCardHolderLine2Address(transaction.getCardHolderLine2Address());
cardHolder.setCardHolderName(transaction.getCardHolderName());
cardHolder.setCardHolderStateCode(transaction.getCardHolderStateCode());
cardHolder.setCardHolderWorkPhoneNumber(transaction.getCardHolderWorkPhoneNumber());
cardHolder.setCardHolderZipCode(transaction.getCardHolderZipCode());
cardHolder.setCardLimit(transaction.getCardLimit());
cardHolder.setCardNoteText(transaction.getCardNoteText());
cardHolder.setCardStatusCode(transaction.getCardStatusCode());
cardHolder.setChartOfAccountsCode(transaction.getChartOfAccountsCode());
cardHolder.setSubAccountNumber(transaction.getSubAccountNumber());
cardHolder.setTransactionCreditCardNumber(transaction.getTransactionCreditCardNumber());
pcardDocument.setProcurementCardHolder(cardHolder);
}
/**
* Creates transaction detail record and adds to document.
*
* @param pcardDocument - document to place record in
* @param transaction - transaction to set fields from
*/
private String createTransactionDetailRecord(ProcurementCardDocument pcardDocument, ProcurementCardTransaction transaction, Integer transactionLineNumber) {
ProcurementCardTransactionDetail transactionDetail = new ProcurementCardTransactionDetail();
// set the document transaction detail fields from the loaded transaction record
transactionDetail.setFinancialDocumentNumber(pcardDocument.getFinancialDocumentNumber());
transactionDetail.setFinancialDocumentTransactionLineNumber(transactionLineNumber);
transactionDetail.setTransactionDate(transaction.getTransactionDate());
transactionDetail.setTransactionReferenceNumber(transaction.getTransactionReferenceNumber());
transactionDetail.setTransactionBillingCurrencyCode(transaction.getTransactionBillingCurrencyCode());
transactionDetail.setTransactionCurrencyExchangeRate(transaction.getTransactionCurrencyExchangeRate());
transactionDetail.setTransactionDate(transaction.getTransactionDate());
transactionDetail.setTransactionOriginalCurrencyAmount(transaction.getTransactionOriginalCurrencyAmount());
transactionDetail.setTransactionOriginalCurrencyCode(transaction.getTransactionOriginalCurrencyCode());
transactionDetail.setTransactionPointOfSaleCode(transaction.getTransactionPointOfSaleCode());
transactionDetail.setTransactionPostingDate(transaction.getTransactionPostingDate());
transactionDetail.setTransactionPurchaseIdentifierDescription(transaction.getTransactionPurchaseIdentifierDescription());
transactionDetail.setTransactionPurchaseIdentifierIndicator(transaction.getTransactionPurchaseIdentifierIndicator());
transactionDetail.setTransactionSalesTaxAmount(transaction.getTransactionSalesTaxAmount());
transactionDetail.setTransactionSettlementAmount(transaction.getTransactionSettlementAmount());
transactionDetail.setTransactionTaxExemptIndicator(transaction.getTransactionTaxExemptIndicator());
transactionDetail.setTransactionTravelAuthorizationCode(transaction.getTransactionTravelAuthorizationCode());
transactionDetail.setTransactionUnitContactName(transaction.getTransactionUnitContactName());
transactionDetail.setTransactionTotalAmount(transaction.getFinancialDocumentTotalAmount());
// create transaction vendor record
createTransactionVendorRecord(pcardDocument, transaction, transactionDetail);
// add transaction detail to document
pcardDocument.getTransactionEntries().add(transactionDetail);
// now create the initial source and target lines for this transaction
return createAndValidateAccountingLines(pcardDocument, transaction, transactionDetail);
}
/**
* Creates transaction vendor detail record and adds to transaction detail.
*
* @param pcardDocument - document to set fields in
* @param transaction - transaction to set fields from
*/
private void createTransactionVendorRecord(ProcurementCardDocument pcardDocument, ProcurementCardTransaction transaction, ProcurementCardTransactionDetail transactionDetail) {
ProcurementCardVendor transactionVendor = new ProcurementCardVendor();
transactionVendor.setFinancialDocumentNumber(pcardDocument.getFinancialDocumentNumber());
transactionVendor.setFinancialDocumentTransactionLineNumber(transactionDetail.getFinancialDocumentTransactionLineNumber());
transactionVendor.setTransactionMerchantCategoryCode(transaction.getTransactionMerchantCategoryCode());
transactionVendor.setVendorCityName(transaction.getVendorCityName());
transactionVendor.setVendorLine1Address(transaction.getVendorLine1Address());
transactionVendor.setVendorLine2Address(transaction.getVendorLine2Address());
transactionVendor.setVendorName(transaction.getVendorName());
transactionVendor.setVendorOrderNumber(transaction.getVendorOrderNumber());
transactionVendor.setVendorStateCode(transaction.getVendorStateCode());
transactionVendor.setVendorZipCode(transaction.getVendorZipCode());
transactionVendor.setVisaVendorIdentifier(transaction.getVisaVendorIdentifier());
transactionDetail.setProcurementCardVendor(transactionVendor);
}
/**
* From the transaction accounting attributes, creates source and target accounting lines. Attributes are validated first, and
* replaced with default and error values if needed. There will be 1 source and 1 target line generated
*
* @param transaction - transaction to process
* @param docTransactionDetail - Object to put accounting lines into
* @return String containing any error messages
*/
private String createAndValidateAccountingLines(ProcurementCardDocument pcardDocument, ProcurementCardTransaction transaction, ProcurementCardTransactionDetail docTransactionDetail) {
// build source lines
ProcurementCardSourceAccountingLine sourceLine = createSourceAccountingLine(transaction, docTransactionDetail);
// add line to transaction through document since document contains the next sequence number fields
pcardDocument.addSourceAccountingLine(sourceLine);
// build target lines
ProcurementCardTargetAccountingLine targetLine = createTargetAccountingLine(transaction, docTransactionDetail);
// add line to transaction through document since document contains the next sequence number fields
pcardDocument.addTargetAccountingLine(targetLine);
return validateTargetAccountingLine(targetLine);
}
/**
* Creates the to record for the transaction. The COA attributes from the transaction are used to create the accounting line.
*
* @param transaction
* @param docTransactionDetail
* @return ProcurementCardSourceAccountingLine
*/
private ProcurementCardTargetAccountingLine createTargetAccountingLine(ProcurementCardTransaction transaction, ProcurementCardTransactionDetail docTransactionDetail) {
ProcurementCardTargetAccountingLine targetLine = new ProcurementCardTargetAccountingLine();
targetLine.setFinancialDocumentNumber(docTransactionDetail.getFinancialDocumentNumber());
targetLine.setFinancialDocumentTransactionLineNumber(docTransactionDetail.getFinancialDocumentTransactionLineNumber());
targetLine.setChartOfAccountsCode(transaction.getChartOfAccountsCode());
targetLine.setAccountNumber(transaction.getAccountNumber());
targetLine.setFinancialObjectCode(transaction.getFinancialObjectCode());
targetLine.setSubAccountNumber(transaction.getSubAccountNumber());
targetLine.setFinancialSubObjectCode(transaction.getFinancialSubObjectCode());
targetLine.setProjectCode(transaction.getProjectCode());
if (GL_CREDIT_CODE.equals(transaction.getTransactionDebitCreditCode())) {
targetLine.setAmount(transaction.getFinancialDocumentTotalAmount().negated());
}
else {
targetLine.setAmount(transaction.getFinancialDocumentTotalAmount());
}
return targetLine;
}
/**
* Creates the from record for the transaction. The clearing chart, account, and object code is used for creating the line.
*
* @param transaction
* @param docTransactionDetail
* @return ProcurementCardSourceAccountingLine
*/
private ProcurementCardSourceAccountingLine createSourceAccountingLine(ProcurementCardTransaction transaction, ProcurementCardTransactionDetail docTransactionDetail) {
ProcurementCardSourceAccountingLine sourceLine = new ProcurementCardSourceAccountingLine();
sourceLine.setFinancialDocumentNumber(docTransactionDetail.getFinancialDocumentNumber());
sourceLine.setFinancialDocumentTransactionLineNumber(docTransactionDetail.getFinancialDocumentTransactionLineNumber());
sourceLine.setChartOfAccountsCode(getDefaultChartCode());
sourceLine.setAccountNumber(getDefaultAccountNumber());
sourceLine.setFinancialObjectCode(getDefaultObjectCode());
sourceLine.setSubAccountNumber("");
sourceLine.setFinancialSubObjectCode("");
sourceLine.setProjectCode("");
if (GL_CREDIT_CODE.equals(transaction.getTransactionDebitCreditCode())) {
sourceLine.setAmount(transaction.getFinancialDocumentTotalAmount().negated());
}
else {
sourceLine.setAmount(transaction.getFinancialDocumentTotalAmount());
}
return sourceLine;
}
/**
* Validates the COA attributes for existence and active indicator. Will substitute for defined default parameters or set fields
* to empty that have errors.
*
* @param sourceLine
* @return String with error messages
*/
private String validateTargetAccountingLine(ProcurementCardTargetAccountingLine targetLine) {
String errorText = "";
targetLine.refresh();
if (!AccountingLineRuleUtil.isValidObjectCode(targetLine.getObjectCode(), dataDictionaryService.getDataDictionary())) {
LOG.info("Object Code " + targetLine.getFinancialObjectCode() + " is invalid; using default Object Code.");
errorText += (" Object Code " + targetLine.getFinancialObjectCode() + " is invalid; using default Object Code.");
targetLine.setFinancialObjectCode(getDefaultObjectCode());
}
if (StringUtils.isNotBlank(targetLine.getSubAccountNumber()) && !AccountingLineRuleUtil.isValidSubAccount(targetLine.getSubAccount(), dataDictionaryService.getDataDictionary())) {
LOG.info("Sub Account " + targetLine.getSubAccountNumber() + " is invalid; Setting to blank.");
errorText += " Sub Account " + targetLine.getSubAccountNumber() + " is invalid; Setting to blank.";
targetLine.setSubAccountNumber("");
}
// refresh again since further checks depend on the above attributes (which could have changed)
targetLine.refresh();
if (StringUtils.isNotBlank(targetLine.getFinancialSubObjectCode()) && !AccountingLineRuleUtil.isValidSubObjectCode(targetLine.getSubObjectCode(), dataDictionaryService.getDataDictionary())) {
LOG.info("Sub Object Code " + targetLine.getFinancialSubObjectCode() + " is invalid; setting to blank.");
errorText += " Sub Object Code " + targetLine.getFinancialSubObjectCode() + " is invalid; setting to blank.";
targetLine.setFinancialSubObjectCode("");
}
if (StringUtils.isNotBlank(targetLine.getProjectCode()) && !AccountingLineRuleUtil.isValidProjectCode(targetLine.getProject(), dataDictionaryService.getDataDictionary())) {
LOG.info("Project Code " + targetLine.getProjectCode() + " is invalid; setting to blank.");
errorText += " Project Code " + targetLine.getProjectCode() + " is invalid; setting to blank.";
targetLine.setProjectCode("");
}
if (!AccountingLineRuleUtil.isValidAccount(targetLine.getAccount(), dataDictionaryService.getDataDictionary()) || targetLine.getAccount().isExpired()) {
LOG.info("Account " + targetLine.getAccountNumber() + " is invalid; using error account.");
errorText += " Account " + targetLine.getAccountNumber() + " is invalid; using error Chart & Account.";
targetLine.setChartOfAccountsCode(getErrorChartCode());
targetLine.setAccountNumber(getErrorAccountNumber());
}
targetLine.refresh();
// clear out GlobalVariable error map, since we have taken care of the errors
GlobalVariables.setErrorMap(new ErrorMap());
return errorText;
}
/**
* @return error chart code defined in the apc
*/
private String getErrorChartCode() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, ERROR_TRANS_CHART_CODE_PARM_NM);
}
/**
* @return error account number defined in the apc
*/
private String getErrorAccountNumber() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, ERROR_TRANS_ACCOUNT_PARM_NM);
}
/**
* @return default chart code defined in the apc
*/
private String getDefaultChartCode() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, DEFAULT_TRANS_CHART_CODE_PARM_NM);
}
/**
* @return default account number defined in the apc
*/
private String getDefaultAccountNumber() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, DEFAULT_TRANS_ACCOUNT_PARM_NM);
}
/**
* @return default object code defined in the apc
*/
private String getDefaultObjectCode() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, DEFAULT_TRANS_OBJECT_CODE_PARM_NM);
}
/**
* Calls businessObjectService to remove all the rows from the transaction load table.
*/
private void cleanTransactionsTable() {
businessObjectService.deleteMatching(ProcurementCardTransaction.class, new HashMap());
}
/**
* Loads all the parsed xml transactions into the temp transaction table.
*
* @param transactions - List of ProcurementCardTransaction to load.
*/
private void loadTransactions(List transactions) {
businessObjectService.save(transactions);
}
/**
* @return Returns the kualiConfigurationService.
*/
public KualiConfigurationService getKualiConfigurationService() {
return kualiConfigurationService;
}
/**
* @param kualiConfigurationService The kualiConfigurationService to set.
*/
public void setKualiConfigurationService(KualiConfigurationService kualiConfigurationService) {
this.kualiConfigurationService = kualiConfigurationService;
}
/**
* @return Returns the businessObjectService.
*/
public BusinessObjectService getBusinessObjectService() {
return businessObjectService;
}
/**
* @param businessObjectService The businessObjectService to set.
*/
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
/**
* @return Returns the documentService.
*/
public DocumentService getDocumentService() {
return documentService;
}
/**
* @param documentService The documentService to set.
*/
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
/**
* @return Returns the dataDictionaryService.
*/
public DataDictionaryService getDataDictionaryService() {
return dataDictionaryService;
}
/**
* @param dataDictionaryService dataDictionaryService to set.
*/
public void setDataDictionaryService(DataDictionaryService dataDictionaryService) {
this.dataDictionaryService = dataDictionaryService;
}
/**
* @return Returns the dateTimeService.
*/
public DateTimeService getDateTimeService() {
return dateTimeService;
}
/**
* @param dateTimeService The dateTimeService to set.
*/
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
/**
* Gets the workflowDocumentService attribute.
* @return Returns the workflowDocumentService.
*/
public WorkflowDocumentService getWorkflowDocumentService() {
return workflowDocumentService;
}
/**
* Sets the workflowDocumentService attribute value.
* @param workflowDocumentService The workflowDocumentService to set.
*/
public void setWorkflowDocumentService(WorkflowDocumentService workflowDocumentService) {
this.workflowDocumentService = workflowDocumentService;
}
} | work/src/org/kuali/kfs/fp/batch/service/impl/ProcurementCardCreateDocumentServiceImpl.java | /*
* Kuali License Info
*/
/*
* Copyright (c) 2004, 2005 The National Association of College and University Business Officers,
* Cornell University, Trustees of Indiana University, Michigan State University Board of Trustees,
* Trustees of San Joaquin Delta College, University of Hawai'i, The Arizona Board of Regents on
* behalf of the University of Arizona, and the r*smart group.
*
* Licensed under the Educational Community License Version 1.0 (the "License"); By obtaining,
* using and/or copying this Original Work, you agree that you have read, understand, and will
* comply with the terms and conditions of the Educational Community License.
*
* You may obtain a copy of the License at:
*
* http://kualiproject.org/license.html
*
* 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 org.kuali.module.financial.service.impl;
import static org.kuali.Constants.GL_CREDIT_CODE;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.kuali.Constants;
import org.kuali.PropertyConstants;
import org.kuali.core.rule.event.SaveOnlyDocumentEvent;
import org.kuali.core.service.BusinessObjectService;
import org.kuali.core.service.DataDictionaryService;
import org.kuali.core.service.DateTimeService;
import org.kuali.core.service.DocumentService;
import org.kuali.core.service.KualiConfigurationService;
import org.kuali.core.util.DateUtils;
import org.kuali.core.util.ErrorMap;
import org.kuali.core.util.GlobalVariables;
import org.kuali.core.util.KualiDecimal;
import org.kuali.core.web.format.TimestampFormatter;
import org.kuali.core.workflow.service.WorkflowDocumentService;
import org.kuali.module.financial.bo.ProcurementCardHolder;
import org.kuali.module.financial.bo.ProcurementCardSourceAccountingLine;
import org.kuali.module.financial.bo.ProcurementCardTargetAccountingLine;
import org.kuali.module.financial.bo.ProcurementCardTransaction;
import org.kuali.module.financial.bo.ProcurementCardTransactionDetail;
import org.kuali.module.financial.bo.ProcurementCardVendor;
import org.kuali.module.financial.document.ProcurementCardDocument;
import org.kuali.module.financial.rules.AccountingLineRuleUtil;
import org.kuali.module.financial.rules.TransactionalDocumentRuleBaseConstants;
import org.kuali.module.financial.service.ProcurementCardCreateDocumentService;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.PCARD_DOCUMENT_PARAMETERS_SEC_GROUP;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.AUTO_APPROVE_DOCUMENTS_IND;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.AUTO_APPROVE_NUMBER_OF_DAYS;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.SINGLE_TRANSACTION_IND_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.ERROR_TRANS_ACCOUNT_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.ERROR_TRANS_CHART_CODE_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.DEFAULT_TRANS_ACCOUNT_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.DEFAULT_TRANS_CHART_CODE_PARM_NM;
import static org.kuali.module.financial.rules.ProcurementCardDocumentRuleConstants.DEFAULT_TRANS_OBJECT_CODE_PARM_NM;
import edu.iu.uis.eden.exception.WorkflowException;
/**
* Implementation of ProcurementCardCreateDocumentService
*
* @see org.kuali.module.financial.service.ProcurementCardCreateDocumentService
* @author Kuali Financial Transactions Team ([email protected])
*/
public class ProcurementCardCreateDocumentServiceImpl implements ProcurementCardCreateDocumentService {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ProcurementCardCreateDocumentServiceImpl.class);
private KualiConfigurationService kualiConfigurationService;
private BusinessObjectService businessObjectService;
private DocumentService documentService;
private DataDictionaryService dataDictionaryService;
private DateTimeService dateTimeService;
private WorkflowDocumentService workflowDocumentService;
/**
* @see org.kuali.module.financial.service.ProcurementCardCreateDocumentService#createProcurementCardDocuments()
*/
public boolean createProcurementCardDocuments() {
List documents = new ArrayList();
List cardTransactions = retrieveTransactions();
// iterate through card transaction list and create documents
for (Iterator iter = cardTransactions.iterator(); iter.hasNext();) {
documents.add(createProcurementCardDocument((List) iter.next()));
}
// now store all the documents
for (Iterator iter = documents.iterator(); iter.hasNext();) {
ProcurementCardDocument pcardDocument = (ProcurementCardDocument) iter.next();
try {
documentService.validateAndPersistDocument(pcardDocument, new SaveOnlyDocumentEvent(pcardDocument));
}
catch (Exception e) {
LOG.error("Error persisting document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + " " + e.getMessage());
throw new RuntimeException("Error persisting document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + " " + e.getMessage());
}
}
return true;
}
/**
* Routes all pcard documents in 'I' status.
*
* @see org.kuali.module.financial.service.ProcurementCardCreateDocumentService#routeProcurementCardDocuments(java.util.List)
*/
public boolean routeProcurementCardDocuments() {
List documentList = new ArrayList();
try {
documentList = (List) documentService.findByDocumentHeaderStatusCode(ProcurementCardDocument.class, Constants.DocumentStatusCodes.INITIATED);
}
catch (WorkflowException e1) {
LOG.error("Error retrieving pcdo documents for routing: " + e1.getMessage());
throw new RuntimeException(e1.getMessage());
}
for (Iterator iter = documentList.iterator(); iter.hasNext();) {
ProcurementCardDocument pcardDocument = (ProcurementCardDocument) iter.next();
try {
LOG.info("Routing PCDO document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + ".");
documentService.prepareWorkflowDocument(pcardDocument);
// calling workflow service to bypass business rule checks
workflowDocumentService.route(pcardDocument.getDocumentHeader().getWorkflowDocument(), "", null);
}
catch (WorkflowException e) {
LOG.error("Error routing document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + " " + e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
return true;
}
/**
* @see org.kuali.module.financial.service.ProcurementCardCreateDocumentService#autoApproveProcurementCardDocuments()
*/
public boolean autoApproveProcurementCardDocuments() {
// check if auto approve is turned on
boolean autoApproveOn = kualiConfigurationService.getApplicationParameterIndicator(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, AUTO_APPROVE_DOCUMENTS_IND);
if (!autoApproveOn) {
return true;
}
List documentList = new ArrayList();
try {
documentList = (List) documentService.findByDocumentHeaderStatusCode(ProcurementCardDocument.class, Constants.DocumentStatusCodes.ENROUTE);
}
catch (WorkflowException e1) {
throw new RuntimeException(e1.getMessage());
}
// get number of days and type for autoapprove
int autoApproveNumberDays = Integer.parseInt(kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, AUTO_APPROVE_NUMBER_OF_DAYS));
Timestamp currentDate = dateTimeService.getCurrentTimestamp();
for (Iterator iter = documentList.iterator(); iter.hasNext();) {
ProcurementCardDocument pcardDocument = (ProcurementCardDocument) iter.next();
Timestamp docCreateDate = pcardDocument.getDocumentHeader().getWorkflowDocument().getCreateDate();
// if number of days in route is passed the allowed number, call doc service for super user approve
if (DateUtils.getDifferenceInDays(docCreateDate, currentDate) > autoApproveNumberDays) {
// update document description to reflect the auto approval
pcardDocument.getDocumentHeader().setFinancialDocumentDescription("Auto Approved On " + (new TimestampFormatter()).format(currentDate) + ".");
try {
LOG.info("Auto approving document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber());
documentService.superUserApproveDocument(pcardDocument, "");
}
catch (WorkflowException e) {
LOG.error("Error auto approving document # " + pcardDocument.getDocumentHeader().getFinancialDocumentNumber() + " " + e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
}
return true;
}
/**
* retrieves list of transactions from temporary table, and groups them into document lists, based on single transaction
* indicator or grouping of card
*
* @return List of List containing transactions for document
*/
private List retrieveTransactions() {
List groupedTransactions = new ArrayList();
// retrieve records from transaction table order by card number
List transactions = (List) businessObjectService.findMatchingOrderBy(ProcurementCardTransaction.class, new HashMap(), PropertyConstants.TRANSACTION_CREDIT_CARD_NUMBER, true);
// check apc for single transaction documents or multple by card
boolean singleTransaction = kualiConfigurationService.getApplicationParameterIndicator(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, SINGLE_TRANSACTION_IND_PARM_NM);
List documentTransactions = new ArrayList();
if (singleTransaction) {
for (Iterator iter = transactions.iterator(); iter.hasNext();) {
documentTransactions.add(iter.next());
groupedTransactions.add(documentTransactions);
documentTransactions = new ArrayList();
}
}
else {
Map cardTransactionsMap = new HashMap();
for (Iterator iter = transactions.iterator(); iter.hasNext();) {
ProcurementCardTransaction transaction = (ProcurementCardTransaction) iter.next();
if (!cardTransactionsMap.containsKey(transaction.getTransactionCreditCardNumber())) {
cardTransactionsMap.put(transaction.getTransactionCreditCardNumber(), new ArrayList());
}
((List) cardTransactionsMap.get(transaction.getTransactionCreditCardNumber())).add(transaction);
}
for (Iterator iter = cardTransactionsMap.values().iterator(); iter.hasNext();) {
groupedTransactions.add(iter.next());
}
}
return groupedTransactions;
}
/**
* Creates a ProcurementCardDocument from the List of transactions
*
* @param transactions - List of ProcurementCardTransaction objects
* @return ProcurementCardDocument
*/
private ProcurementCardDocument createProcurementCardDocument(List transactions) {
ProcurementCardDocument pcardDocument = null;
try {
// get new document from doc service
pcardDocument = (ProcurementCardDocument) documentService.getNewDocument(ProcurementCardDocument.class);
// set the card holder record on the document from the first transaction
createCardHolderRecord(pcardDocument, (ProcurementCardTransaction) transactions.get(0));
// for each transaction, create transaction detail object and then acct lines for the detail
int transactionLineNumber = 1;
KualiDecimal documentTotalAmount = new KualiDecimal(0);
String errorText = "";
for (Iterator iter = transactions.iterator(); iter.hasNext();) {
ProcurementCardTransaction transaction = (ProcurementCardTransaction) iter.next();
// create transaction detail record with accounting lines
errorText += createTransactionDetailRecord(pcardDocument, transaction, transactionLineNumber);
// update document total
documentTotalAmount = documentTotalAmount.add(transaction.getFinancialDocumentTotalAmount());
transactionLineNumber++;
}
pcardDocument.getDocumentHeader().setFinancialDocumentTotalAmount(documentTotalAmount);
pcardDocument.getDocumentHeader().setFinancialDocumentDescription("SYSTEM Generated");
// TODO: Fix for length problem of explanation, possibly make into note?
// pcardDocument.setExplanation(errorText);
}
catch (WorkflowException e) {
LOG.error("Error creating pcdo documents: " + e.getMessage());
throw new RuntimeException("Error creating pcdo documents: " + e.getMessage());
}
return pcardDocument;
}
/**
* Creates card holder record and sets in document.
*
* @param pcardDocument - document to place record in
* @param transaction - transaction to set fields from
*/
private void createCardHolderRecord(ProcurementCardDocument pcardDocument, ProcurementCardTransaction transaction) {
ProcurementCardHolder cardHolder = new ProcurementCardHolder();
cardHolder.setFinancialDocumentNumber(pcardDocument.getFinancialDocumentNumber());
cardHolder.setAccountNumber(transaction.getAccountNumber());
cardHolder.setCardCycleAmountLimit(transaction.getCardCycleAmountLimit());
cardHolder.setCardCycleVolumeLimit(transaction.getCardCycleVolumeLimit());
cardHolder.setCardHolderAlternateName(transaction.getCardHolderAlternateName());
cardHolder.setCardHolderCityName(transaction.getCardHolderCityName());
cardHolder.setCardHolderLine1Address(transaction.getCardHolderLine1Address());
cardHolder.setCardHolderLine2Address(transaction.getCardHolderLine2Address());
cardHolder.setCardHolderName(transaction.getCardHolderName());
cardHolder.setCardHolderStateCode(transaction.getCardHolderStateCode());
cardHolder.setCardHolderWorkPhoneNumber(transaction.getCardHolderWorkPhoneNumber());
cardHolder.setCardHolderZipCode(transaction.getCardHolderZipCode());
cardHolder.setCardLimit(transaction.getCardLimit());
cardHolder.setCardNoteText(transaction.getCardNoteText());
cardHolder.setCardStatusCode(transaction.getCardStatusCode());
cardHolder.setChartOfAccountsCode(transaction.getChartOfAccountsCode());
cardHolder.setSubAccountNumber(transaction.getSubAccountNumber());
cardHolder.setTransactionCreditCardNumber(transaction.getTransactionCreditCardNumber());
pcardDocument.setProcurementCardHolder(cardHolder);
}
/**
* Creates transaction detail record and adds to document.
*
* @param pcardDocument - document to place record in
* @param transaction - transaction to set fields from
*/
private String createTransactionDetailRecord(ProcurementCardDocument pcardDocument, ProcurementCardTransaction transaction, Integer transactionLineNumber) {
ProcurementCardTransactionDetail transactionDetail = new ProcurementCardTransactionDetail();
// set the document transaction detail fields from the loaded transaction record
transactionDetail.setFinancialDocumentNumber(pcardDocument.getFinancialDocumentNumber());
transactionDetail.setFinancialDocumentTransactionLineNumber(transactionLineNumber);
transactionDetail.setTransactionDate(transaction.getTransactionDate());
transactionDetail.setTransactionReferenceNumber(transaction.getTransactionReferenceNumber());
transactionDetail.setTransactionBillingCurrencyCode(transaction.getTransactionBillingCurrencyCode());
transactionDetail.setTransactionCurrencyExchangeRate(transaction.getTransactionCurrencyExchangeRate());
transactionDetail.setTransactionDate(transaction.getTransactionDate());
transactionDetail.setTransactionOriginalCurrencyAmount(transaction.getTransactionOriginalCurrencyAmount());
transactionDetail.setTransactionOriginalCurrencyCode(transaction.getTransactionOriginalCurrencyCode());
transactionDetail.setTransactionPointOfSaleCode(transaction.getTransactionPointOfSaleCode());
transactionDetail.setTransactionPostingDate(transaction.getTransactionPostingDate());
transactionDetail.setTransactionPurchaseIdentifierDescription(transaction.getTransactionPurchaseIdentifierDescription());
transactionDetail.setTransactionPurchaseIdentifierIndicator(transaction.getTransactionPurchaseIdentifierIndicator());
transactionDetail.setTransactionSalesTaxAmount(transaction.getTransactionSalesTaxAmount());
transactionDetail.setTransactionSettlementAmount(transaction.getTransactionSettlementAmount());
transactionDetail.setTransactionTaxExemptIndicator(transaction.getTransactionTaxExemptIndicator());
transactionDetail.setTransactionTravelAuthorizationCode(transaction.getTransactionTravelAuthorizationCode());
transactionDetail.setTransactionUnitContactName(transaction.getTransactionUnitContactName());
transactionDetail.setTransactionTotalAmount(transaction.getFinancialDocumentTotalAmount());
// create transaction vendor record
createTransactionVendorRecord(pcardDocument, transaction, transactionDetail);
// add transaction detail to document
pcardDocument.getTransactionEntries().add(transactionDetail);
// now create the initial source and target lines for this transaction
return createAndValidateAccountingLines(pcardDocument, transaction, transactionDetail);
}
/**
* Creates transaction vendor detail record and adds to transaction detail.
*
* @param pcardDocument - document to set fields in
* @param transaction - transaction to set fields from
*/
private void createTransactionVendorRecord(ProcurementCardDocument pcardDocument, ProcurementCardTransaction transaction, ProcurementCardTransactionDetail transactionDetail) {
ProcurementCardVendor transactionVendor = new ProcurementCardVendor();
transactionVendor.setFinancialDocumentNumber(pcardDocument.getFinancialDocumentNumber());
transactionVendor.setFinancialDocumentTransactionLineNumber(transactionDetail.getFinancialDocumentTransactionLineNumber());
transactionVendor.setTransactionMerchantCategoryCode(transaction.getTransactionMerchantCategoryCode());
transactionVendor.setVendorCityName(transaction.getVendorCityName());
transactionVendor.setVendorLine1Address(transaction.getVendorLine1Address());
transactionVendor.setVendorLine2Address(transaction.getVendorLine2Address());
transactionVendor.setVendorName(transaction.getVendorName());
transactionVendor.setVendorOrderNumber(transaction.getVendorOrderNumber());
transactionVendor.setVendorStateCode(transaction.getVendorStateCode());
transactionVendor.setVendorZipCode(transaction.getVendorZipCode());
transactionVendor.setVisaVendorIdentifier(transaction.getVisaVendorIdentifier());
transactionDetail.setProcurementCardVendor(transactionVendor);
}
/**
* From the transaction accounting attributes, creates source and target accounting lines. Attributes are validated first, and
* replaced with default and error values if needed. There will be 1 source and 1 target line generated
*
* @param transaction - transaction to process
* @param docTransactionDetail - Object to put accounting lines into
* @return String containing any error messages
*/
private String createAndValidateAccountingLines(ProcurementCardDocument pcardDocument, ProcurementCardTransaction transaction, ProcurementCardTransactionDetail docTransactionDetail) {
// build source lines
ProcurementCardSourceAccountingLine sourceLine = createSourceAccountingLine(transaction, docTransactionDetail);
// add line to transaction through document since document contains the next sequence number fields
pcardDocument.addSourceAccountingLine(sourceLine);
// build target lines
ProcurementCardTargetAccountingLine targetLine = createTargetAccountingLine(transaction, docTransactionDetail);
// add line to transaction through document since document contains the next sequence number fields
pcardDocument.addTargetAccountingLine(targetLine);
return validateTargetAccountingLine(targetLine);
}
/**
* Creates the to record for the transaction. The COA attributes from the transaction are used to create the accounting line.
*
* @param transaction
* @param docTransactionDetail
* @return ProcurementCardSourceAccountingLine
*/
private ProcurementCardTargetAccountingLine createTargetAccountingLine(ProcurementCardTransaction transaction, ProcurementCardTransactionDetail docTransactionDetail) {
ProcurementCardTargetAccountingLine targetLine = new ProcurementCardTargetAccountingLine();
targetLine.setFinancialDocumentNumber(docTransactionDetail.getFinancialDocumentNumber());
targetLine.setFinancialDocumentTransactionLineNumber(docTransactionDetail.getFinancialDocumentTransactionLineNumber());
targetLine.setChartOfAccountsCode(transaction.getChartOfAccountsCode());
targetLine.setAccountNumber(transaction.getAccountNumber());
targetLine.setFinancialObjectCode(transaction.getFinancialObjectCode());
targetLine.setSubAccountNumber(transaction.getSubAccountNumber());
targetLine.setFinancialSubObjectCode(transaction.getFinancialSubObjectCode());
targetLine.setProjectCode(transaction.getProjectCode());
if (GL_CREDIT_CODE.equals(transaction.getTransactionDebitCreditCode())) {
targetLine.setAmount(transaction.getFinancialDocumentTotalAmount().negated());
}
else {
targetLine.setAmount(transaction.getFinancialDocumentTotalAmount());
}
return targetLine;
}
/**
* Creates the from record for the transaction. The clearing chart, account, and object code is used for creating the line.
*
* @param transaction
* @param docTransactionDetail
* @return ProcurementCardSourceAccountingLine
*/
private ProcurementCardSourceAccountingLine createSourceAccountingLine(ProcurementCardTransaction transaction, ProcurementCardTransactionDetail docTransactionDetail) {
ProcurementCardSourceAccountingLine sourceLine = new ProcurementCardSourceAccountingLine();
sourceLine.setFinancialDocumentNumber(docTransactionDetail.getFinancialDocumentNumber());
sourceLine.setFinancialDocumentTransactionLineNumber(docTransactionDetail.getFinancialDocumentTransactionLineNumber());
sourceLine.setChartOfAccountsCode(getDefaultChartCode());
sourceLine.setAccountNumber(getDefaultAccountNumber());
sourceLine.setFinancialObjectCode(getDefaultObjectCode());
sourceLine.setSubAccountNumber("");
sourceLine.setFinancialSubObjectCode("");
sourceLine.setProjectCode("");
if (GL_CREDIT_CODE.equals(transaction.getTransactionDebitCreditCode())) {
sourceLine.setAmount(transaction.getFinancialDocumentTotalAmount().negated());
}
else {
sourceLine.setAmount(transaction.getFinancialDocumentTotalAmount());
}
return sourceLine;
}
/**
* Validates the COA attributes for existence and active indicator. Will substitute for defined default parameters or set fields
* to empty that have errors.
*
* @param sourceLine
* @return String with error messages
*/
private String validateTargetAccountingLine(ProcurementCardTargetAccountingLine targetLine) {
String errorText = "";
targetLine.refresh();
if (!AccountingLineRuleUtil.isValidObjectCode(targetLine.getObjectCode(), dataDictionaryService.getDataDictionary())) {
LOG.info("Object Code " + targetLine.getFinancialObjectCode() + " is invalid. Using default Object Code.");
errorText += (" Object Code " + targetLine.getFinancialObjectCode() + " is invalid. Using default Object Code.");
targetLine.setFinancialObjectCode(getDefaultObjectCode());
}
if (StringUtils.isNotBlank(targetLine.getSubAccountNumber()) && !AccountingLineRuleUtil.isValidSubAccount(targetLine.getSubAccount(), dataDictionaryService.getDataDictionary())) {
LOG.info("Sub Account " + targetLine.getSubAccountNumber() + " is invalid. Setting to blank");
errorText += " Sub Account " + targetLine.getSubAccountNumber() + " is invalid. Setting to blank";
targetLine.setSubAccountNumber("");
}
// refresh again since further checks depend on the above attributes (which could have changed)
targetLine.refresh();
if (StringUtils.isNotBlank(targetLine.getFinancialSubObjectCode()) && !AccountingLineRuleUtil.isValidSubObjectCode(targetLine.getSubObjectCode(), dataDictionaryService.getDataDictionary())) {
LOG.info("Sub Object Code " + targetLine.getFinancialSubObjectCode() + " is invalid. Setting to blank");
errorText += " Sub Object Code " + targetLine.getFinancialSubObjectCode() + " is invalid. Setting to blank";
targetLine.setFinancialSubObjectCode("");
}
if (StringUtils.isNotBlank(targetLine.getProjectCode()) && !AccountingLineRuleUtil.isValidProjectCode(targetLine.getProject(), dataDictionaryService.getDataDictionary())) {
LOG.info("Project Code " + targetLine.getProjectCode() + " is invalid. Setting to blank");
errorText += " Project Code " + targetLine.getProjectCode() + " is invalid. Setting to blank";
targetLine.setProjectCode("");
}
if (!AccountingLineRuleUtil.isValidAccount(targetLine.getAccount(), dataDictionaryService.getDataDictionary()) || targetLine.getAccount().isExpired()) {
LOG.info("Account " + targetLine.getAccountNumber() + " is invalid. Using error account.");
errorText += " Account " + targetLine.getAccountNumber() + " is invalid. Using error Chart & Account.";
targetLine.setChartOfAccountsCode(getErrorChartCode());
targetLine.setAccountNumber(getErrorAccountNumber());
}
targetLine.refresh();
// clear out GlobalVariable error map, since we have taken care of the errors
GlobalVariables.setErrorMap(new ErrorMap());
return errorText;
}
/**
* @return error chart code defined in the apc
*/
private String getErrorChartCode() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, ERROR_TRANS_CHART_CODE_PARM_NM);
}
/**
* @return error account number defined in the apc
*/
private String getErrorAccountNumber() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, ERROR_TRANS_ACCOUNT_PARM_NM);
}
/**
* @return default chart code defined in the apc
*/
private String getDefaultChartCode() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, DEFAULT_TRANS_CHART_CODE_PARM_NM);
}
/**
* @return default account number defined in the apc
*/
private String getDefaultAccountNumber() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, DEFAULT_TRANS_ACCOUNT_PARM_NM);
}
/**
* @return default object code defined in the apc
*/
private String getDefaultObjectCode() {
return kualiConfigurationService.getApplicationParameterValue(PCARD_DOCUMENT_PARAMETERS_SEC_GROUP, DEFAULT_TRANS_OBJECT_CODE_PARM_NM);
}
/**
* Calls businessObjectService to remove all the rows from the transaction load table.
*/
private void cleanTransactionsTable() {
businessObjectService.deleteMatching(ProcurementCardTransaction.class, new HashMap());
}
/**
* Loads all the parsed xml transactions into the temp transaction table.
*
* @param transactions - List of ProcurementCardTransaction to load.
*/
private void loadTransactions(List transactions) {
businessObjectService.save(transactions);
}
/**
* @return Returns the kualiConfigurationService.
*/
public KualiConfigurationService getKualiConfigurationService() {
return kualiConfigurationService;
}
/**
* @param kualiConfigurationService The kualiConfigurationService to set.
*/
public void setKualiConfigurationService(KualiConfigurationService kualiConfigurationService) {
this.kualiConfigurationService = kualiConfigurationService;
}
/**
* @return Returns the businessObjectService.
*/
public BusinessObjectService getBusinessObjectService() {
return businessObjectService;
}
/**
* @param businessObjectService The businessObjectService to set.
*/
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
/**
* @return Returns the documentService.
*/
public DocumentService getDocumentService() {
return documentService;
}
/**
* @param documentService The documentService to set.
*/
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
/**
* @return Returns the dataDictionaryService.
*/
public DataDictionaryService getDataDictionaryService() {
return dataDictionaryService;
}
/**
* @param dataDictionaryService dataDictionaryService to set.
*/
public void setDataDictionaryService(DataDictionaryService dataDictionaryService) {
this.dataDictionaryService = dataDictionaryService;
}
/**
* @return Returns the dateTimeService.
*/
public DateTimeService getDateTimeService() {
return dateTimeService;
}
/**
* @param dateTimeService The dateTimeService to set.
*/
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
/**
* Gets the workflowDocumentService attribute.
* @return Returns the workflowDocumentService.
*/
public WorkflowDocumentService getWorkflowDocumentService() {
return workflowDocumentService;
}
/**
* Sets the workflowDocumentService attribute value.
* @param workflowDocumentService The workflowDocumentService to set.
*/
public void setWorkflowDocumentService(WorkflowDocumentService workflowDocumentService) {
this.workflowDocumentService = workflowDocumentService;
}
} | KULEDOCS-1547: PCDO batch maxlength error exception fixed.
| work/src/org/kuali/kfs/fp/batch/service/impl/ProcurementCardCreateDocumentServiceImpl.java | KULEDOCS-1547: PCDO batch maxlength error exception fixed. |
|
Java | agpl-3.0 | 4bae9bfe72c34cc905fbafc7a1d9e98053f19680 | 0 | Bram28/LEGUP,Bram28/LEGUP,Bram28/LEGUP | package edu.rpi.phil.legup.puzzles.nurikabe;
import javax.swing.ImageIcon;
import edu.rpi.phil.legup.BoardState;
import edu.rpi.phil.legup.PuzzleRule;
import java.awt.Point;
import java.util.Set;
import java.util.LinkedHashSet;
public class RuleCornerBlack extends PuzzleRule
{
private static final long serialVersionUID = 889434116L;
RuleCornerBlack()
{
setName("Corner Black");
description = "If there is only one white square connected to unkowns and one more white is needed then the angles of that white square are black";
image = new ImageIcon("images/nurikabe/rules/CornerBlack.png");
}
public String getImageName()
{
return "images/nurikabe/rules/CornerBlack.png";
}
protected String checkRuleRaw(BoardState destBoardState)
{
String error = null;
BoardState origBoardState = destBoardState.getSingleParentState();
// Check for only one branch
if (destBoardState.getParents().size() != 1)
{
return "This rule only involves having a single branch!";
}
int width = destBoardState.getWidth();
int height = destBoardState.getHeight();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (destBoardState.getCellContents(x, y) != origBoardState.getCellContents(x, y))
{
if (destBoardState.getCellContents(x, y) != Nurikabe.CELL_BLACK)
{
return "Only black cells are allowed for this rule!";
}
Set<Point> whiteDiagonals = whiteCellDiagonalLocation(destBoardState, new Point(x, y), width, height);
if (whiteDiagonals.size() == 0)
return "The black must be kitty-corner to a white cell!";
int correctTwos = 0;
for (Point p : whiteDiagonals)
{
Set<Point> openAdjs = openAdjacents(destBoardState, p, width, height);
if (openAdjs == null)
return "The region is already completed!";
if (openAdjs.size() != 2)
continue;
int correctAdjs = 0;
for (Point o : openAdjs)
{
if (o.distance(x, y) == 1)
correctAdjs++;
}
if (correctAdjs == 2)
correctTwos++;
}
if (correctTwos == 0)
return "There must be two unknown cells adjacent to the white cell!";
}
}
}
return null;
}
/**
Finds the location of the adjacent diagonal white cell on the blacks corner
Returns a point with values (-1,-1) if no such cell exists
*/
private Set<Point> whiteCellDiagonalLocation(BoardState board, Point black, int width, int height)
{
Set<Point> targets = new LinkedHashSet<Point>();
if (black.x-1 >= 0 && black.y-1 >= 0)
{
if (board.getCellContents(black.x-1, black.y-1) > 10
|| board.getCellContents(black.x-1, black.y-1) == Nurikabe.CELL_WHITE)
targets.add(new Point(black.x-1, black.y-1));
}
if (black.x+1 < width && black.y-1 >= 0)
{
if (board.getCellContents(black.x+1, black.y-1) > 10
|| board.getCellContents(black.x+1, black.y-1) == Nurikabe.CELL_WHITE)
targets.add(new Point(black.x+1, black.y-1));
}
if (black.x-1 >= 0 && black.y+1 < height)
{
if (board.getCellContents(black.x-1, black.y+1) > 10
|| board.getCellContents(black.x-1, black.y+1) == Nurikabe.CELL_WHITE)
targets.add(new Point(black.x-1, black.y+1));
}
if (black.x+1 < width && black.y+1 < height)
{
if (board.getCellContents(black.x+1, black.y+1) > 10
|| board.getCellContents(black.x+1, black.y+1) == Nurikabe.CELL_WHITE)
targets.add(new Point(black.x+1, black.y+1));
}
return targets;
}
/**
returns the locations of the unknown cells which are adjacent to the white two
*/
private Set<Point> openAdjacents(BoardState board, Point white, int width, int height)
{
Set<Point> targets = new LinkedHashSet<Point>();
if (white.x-1 >= 0)
{
if (board.getCellContents(white.x-1, white.y) == Nurikabe.CELL_UNKNOWN)
targets.add(new Point(white.x-1, white.y));
if (board.getCellContents(white.x-1, white.y) == Nurikabe.CELL_WHITE)
return null;
}
if (white.x+1 < width)
{
if (board.getCellContents(white.x+1, white.y) == Nurikabe.CELL_UNKNOWN)
targets.add(new Point(white.x+1, white.y));
if (board.getCellContents(white.x+1, white.y) == Nurikabe.CELL_WHITE)
return null;
}
if (white.y+1 < height)
{
if (board.getCellContents(white.x, white.y+1) == Nurikabe.CELL_UNKNOWN)
targets.add(new Point(white.x, white.y+1));
if (board.getCellContents(white.x, white.y+1) == Nurikabe.CELL_WHITE)
return null;
}
if (white.y-1 >= 0)
{
if (board.getCellContents(white.x, white.y-1) == Nurikabe.CELL_UNKNOWN)
targets.add(new Point(white.x, white.y-1));
if (board.getCellContents(white.x, white.y+1) == Nurikabe.CELL_WHITE)
return null;
}
return targets;
}
}
| code/edu/rpi/phil/legup/puzzles/nurikabe/RuleCornerBlack.java | package edu.rpi.phil.legup.puzzles.nurikabe;
import javax.swing.ImageIcon;
import edu.rpi.phil.legup.BoardState;
import edu.rpi.phil.legup.PuzzleRule;
import java.awt.Point;
import java.util.Set;
import java.util.LinkedHashSet;
public class RuleCornerBlack extends PuzzleRule
{
private static final long serialVersionUID = 889434116L;
RuleCornerBlack()
{
setName("Corner Black");
description = "If there is only one white square connected to unkowns and one more white is needed then the angles of that white square are black";
image = new ImageIcon("images/nurikabe/rules/CornerBlack.png");
}
public String getImageName()
{
return "images/nurikabe/rules/CornerBlack.png";
}
protected String checkRuleRaw(BoardState destBoardState)
{
String error = null;
BoardState origBoardState = destBoardState.getSingleParentState();
// Check for only one branch
if (destBoardState.getParents().size() != 1)
{
return "This rule only involves having a single branch!";
}
int width = destBoardState.getWidth();
int height = destBoardState.getHeight();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (destBoardState.getCellContents(x, y) != origBoardState.getCellContents(x, y))
{
if (destBoardState.getCellContents(x, y) != Nurikabe.CELL_BLACK)
{
return "Only black cells are allowed for this rule!";
}
Set<Point> whiteTwos = whiteTwoLocation(destBoardState, new Point(x, y), width, height);
if (whiteTwos.size() == 0)
return "The black must be kitty-corner to a white 2 cell!";
int correctTwos = 0;
for (Point p : whiteTwos)
{
Set<Point> openAdjs = openAdjacents(destBoardState, p, width, height);
if (openAdjs == null)
return "The region is already completed!";
if (openAdjs.size() != 2)
continue;
int correctAdjs = 0;
for (Point o : openAdjs)
{
if (o.distance(x, y) == 1)
correctAdjs++;
}
if (correctAdjs == 2)
correctTwos++;
}
if (correctTwos == 0)
return "There must be two unknown cells adjacent to the white 2!";
}
}
}
return null;
}
/**
Finds the location of the #2 white cell on the blacks corner
Returns a point with values (-1,-1) if no such cell exists
*/
private Set<Point> whiteTwoLocation(BoardState board, Point black, int width, int height)
{
Set<Point> targets = new LinkedHashSet<Point>();
if (black.x-1 >= 0 && black.y-1 >= 0)
{
if (board.getCellContents(black.x-1, black.y-1) == 12)
targets.add(new Point(black.x-1, black.y-1));
}
if (black.x+1 < width && black.y-1 >= 0)
{
if (board.getCellContents(black.x+1, black.y-1) == 12)
targets.add(new Point(black.x+1, black.y-1));
}
if (black.x-1 >= 0 && black.y+1 < height)
{
if (board.getCellContents(black.x-1, black.y+1) == 12)
targets.add(new Point(black.x-1, black.y+1));
}
if (black.x+1 < width && black.y+1 < height)
{
if (board.getCellContents(black.x+1, black.y+1) == 12)
targets.add(new Point(black.x+1, black.y+1));
}
return targets;
}
/**
returns the locations of the unknown cells which are adjacent to the white two
*/
private Set<Point> openAdjacents(BoardState board, Point white, int width, int height)
{
Set<Point> targets = new LinkedHashSet<Point>();
if (white.x-1 >= 0)
{
if (board.getCellContents(white.x-1, white.y) == Nurikabe.CELL_UNKNOWN)
targets.add(new Point(white.x-1, white.y));
if (board.getCellContents(white.x-1, white.y) == Nurikabe.CELL_WHITE)
return null;
}
if (white.x+1 < width)
{
if (board.getCellContents(white.x+1, white.y) == Nurikabe.CELL_UNKNOWN)
targets.add(new Point(white.x+1, white.y));
if (board.getCellContents(white.x+1, white.y) == Nurikabe.CELL_WHITE)
return null;
}
if (white.y+1 < height)
{
if (board.getCellContents(white.x, white.y+1) == Nurikabe.CELL_UNKNOWN)
targets.add(new Point(white.x, white.y+1));
if (board.getCellContents(white.x, white.y+1) == Nurikabe.CELL_WHITE)
return null;
}
if (white.y-1 >= 0)
{
if (board.getCellContents(white.x, white.y-1) == Nurikabe.CELL_UNKNOWN)
targets.add(new Point(white.x, white.y-1));
if (board.getCellContents(white.x, white.y+1) == Nurikabe.CELL_WHITE)
return null;
}
return targets;
}
}
| Updated Corner Black to work on more cases
Corner Black wouldn't work if the chain of white blocks was greater than
2
| code/edu/rpi/phil/legup/puzzles/nurikabe/RuleCornerBlack.java | Updated Corner Black to work on more cases |
|
Java | lgpl-2.1 | e33e463a1f831a76b06882a796af2a42a4cceb3a | 0 | aloubyansky/wildfly-core,aloubyansky/wildfly-core,soul2zimate/wildfly-core,ivassile/wildfly-core,jfdenise/wildfly-core,jamezp/wildfly-core,bstansberry/wildfly-core,luck3y/wildfly-core,jfdenise/wildfly-core,JiriOndrusek/wildfly-core,JiriOndrusek/wildfly-core,bstansberry/wildfly-core,aloubyansky/wildfly-core,ivassile/wildfly-core,yersan/wildfly-core,darranl/wildfly-core,soul2zimate/wildfly-core,darranl/wildfly-core,JiriOndrusek/wildfly-core,jamezp/wildfly-core,yersan/wildfly-core,luck3y/wildfly-core,soul2zimate/wildfly-core,jfdenise/wildfly-core,darranl/wildfly-core,bstansberry/wildfly-core,jamezp/wildfly-core,yersan/wildfly-core,ivassile/wildfly-core,luck3y/wildfly-core | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., 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.as.server.deployment;
/**
* An enumeration of the phases of a deployment unit's processing cycle.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public enum Phase {
/* == TEMPLATE ==
* Upon entry, this phase performs the following actions:
* <ul>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
/**
* This phase creates the initial root structure. Depending on the service for this phase will ensure that the
* deployment unit's initial root structure is available and accessible.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li>
* <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments:
* <ul>
* <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* </ul>
* <p>
*/
STRUCTURE(null),
/**
* This phase assembles information from the root structure to prepare for adding and processing additional external
* structure, such as from class path entries and other similar mechanisms.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li>
* <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li>
* <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li>
* </ul>
* <p>
*/
PARSE(null),
/**
* In this phase parsing of deployment metadata is complete and the component may be registered with the subsystem.
* This is prior to working out the components dependency and equivalent to the OSGi INSTALL life cycle.
*/
REGISTER(null),
/**
* In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>Any additional external structure is mounted during {@link #XXX}</li>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
DEPENDENCIES(null),
CONFIGURE_MODULE(null),
POST_MODULE(null),
INSTALL(null),
CLEANUP(null),
;
/**
* This is the key for the attachment to use as the phase's "value". The attachment is taken from
* the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified.
*/
private final AttachmentKey<?> phaseKey;
private Phase(final AttachmentKey<?> key) {
phaseKey = key;
}
/**
* Get the next phase, or {@code null} if none.
*
* @return the next phase, or {@code null} if there is none
*/
public Phase next() {
final int ord = ordinal() + 1;
final Phase[] phases = Phase.values();
return ord == phases.length ? null : phases[ord];
}
/**
* Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value
* of this phase.
*
* @return the key
*/
public AttachmentKey<?> getPhaseKey() {
return phaseKey;
}
// STRUCTURE
public static final int STRUCTURE_EXPLODED_MOUNT = 0x0100;
public static final int STRUCTURE_MOUNT = 0x0200;
public static final int STRUCTURE_MANIFEST = 0x0300;
public static final int STRUCTURE_OSGI_MANIFEST = 0x0400;
public static final int STRUCTURE_EE_SPEC_DESC_PROPERTY_REPLACEMENT = 0x0500;
public static final int STRUCTURE_EE_JBOSS_DESC_PROPERTY_REPLACEMENT= 0x0550;
public static final int STRUCTURE_JDBC_DRIVER = 0x0600;
public static final int STRUCTURE_RAR = 0x0700;
public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0800;
public static final int STRUCTURE_WAR = 0x0900;
public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0A00;
public static final int STRUCTURE_REGISTER_JBOSS_ALL_XML_PARSER = 0x0A10;
public static final int STRUCTURE_PARSE_JBOSS_ALL_XML = 0x0A20;
public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0B00;
public static final int STRUCTURE_JBOSS_EJB_CLIENT_XML_PARSE = 0x0C00;
public static final int STRUCTURE_EJB_EAR_APPLICATION_NAME = 0x0D00;
public static final int STRUCTURE_EAR = 0x0E00;
public static final int STRUCTURE_APP_CLIENT = 0x0F00;
public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x1000;
public static final int STRUCTURE_ANNOTATION_INDEX = 0x1100;
public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x1200;
public static final int STRUCTURE_APPLICATION_CLIENT_IN_EAR = 0x1300;
public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x1400;
public static final int STRUCTURE_BUNDLE_SUB_DEPLOYMENT = 0x1450;
public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x1500;
public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x1600;
public static final int STRUCTURE_SUB_DEPLOYMENT = 0x1700;
public static final int STRUCTURE_JBOSS_DEPLOYMENT_STRUCTURE = 0x1800;
public static final int STRUCTURE_CLASS_PATH = 0x1900;
public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1A00;
public static final int STRUCTURE_EE_MODULE_INIT = 0x1B00;
public static final int STRUCTURE_EE_RESOURCE_INJECTION_REGISTRY = 0x1C00;
// PARSE
public static final int PARSE_EE_DEPLOYMENT_PROPERTIES = 0x0001;
public static final int PARSE_EE_DEPLOYMENT_PROPERTY_RESOLVER = 0x0002;
public static final int PARSE_EE_VAULT_PROPERTY_RESOLVER = 0x0003;
public static final int PARSE_EE_SYSTEM_PROPERTY_RESOLVER = 0x0004;
public static final int PARSE_EE_PROPERTY_RESOLVER = 0x0005;
public static final int PARSE_EE_MODULE_NAME = 0x0100;
public static final int PARSE_EJB_DEFAULT_DISTINCT_NAME = 0x0110;
public static final int PARSE_EAR_SUBDEPLOYMENTS_ISOLATION_DEFAULT = 0x0200;
public static final int PARSE_DEPENDENCIES_MANIFEST = 0x0300;
public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0301;
public static final int PARSE_EXTENSION_LIST = 0x0700;
public static final int PARSE_EXTENSION_NAME = 0x0800;
public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900;
public static final int PARSE_OSGI_PROPERTIES = 0x0A00;
public static final int PARSE_WEB_DEPLOYMENT = 0x0B00;
public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00;
public static final int PARSE_JSF_VERSION = 0x0C50;
public static final int PARSE_JSF_SHARED_TLDS = 0x0C51;
public static final int PARSE_ANNOTATION_WAR = 0x0D00;
public static final int PARSE_ANNOTATION_EJB = 0x0D10;
public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00;
public static final int PARSE_TLD_DEPLOYMENT = 0x0F00;
public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000;
// create and attach EJB metadata for EJB deployments
public static final int PARSE_EJB_DEPLOYMENT = 0x1100;
public static final int PARSE_APP_CLIENT_XML = 0x1101;
public static final int PARSE_CREATE_COMPONENT_DESCRIPTIONS = 0x1150;
// described EJBs must be created after annotated EJBs
public static final int PARSE_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1152;
public static final int PARSE_CMP_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1153;
public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200;
// create and attach the component description out of EJB annotations
public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901;
public static final int PARSE_WEB_COMPONENTS = 0x1F00;
public static final int PARSE_WEB_MERGE_METADATA = 0x2000;
public static final int PARSE_WEBSERVICES_CONTEXT_INJECTION = 0x2040;
public static final int PARSE_WEBSERVICES_XML = 0x2050;
public static final int PARSE_JBOSS_WEBSERVICES_XML = 0x2051;
public static final int PARSE_JAXWS_EJB_INTEGRATION = 0x2052;
public static final int PARSE_JAXRPC_POJO_INTEGRATION = 0x2053;
public static final int PARSE_JAXRPC_EJB_INTEGRATION = 0x2054;
public static final int PARSE_JAXWS_HANDLER_CHAIN_ANNOTATION = 0x2055;
public static final int PARSE_WS_JMS_INTEGRATION = 0x2056;
public static final int PARSE_JAXWS_ENDPOINT_CREATE_COMPONENT_DESCRIPTIONS = 0x2057;
public static final int PARSE_JAXWS_HANDLER_CREATE_COMPONENT_DESCRIPTIONS = 0x2058;
public static final int PARSE_RA_DEPLOYMENT = 0x2100;
public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200;
public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300;
public static final int PARSE_POJO_DEPLOYMENT = 0x2400;
public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500;
public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900;
public static final int PARSE_EE_ANNOTATIONS = 0x2901;
public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00;
public static final int PARSE_CDI_ANNOTATIONS = 0x2A10;
public static final int PARSE_WELD_DEPLOYMENT = 0x2B00;
public static final int PARSE_WELD_WEB_INTEGRATION = 0x2B10;
public static final int PARSE_DATA_SOURCE_DEFINITION_ANNOTATION = 0x2D00;
public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00;
public static final int PARSE_EJB_TIMERSERVICE_BINDING = 0x2E01;
public static final int PARSE_PERSISTENCE_UNIT = 0x2F00;
public static final int PARSE_LIFECYCLE_ANNOTATION = 0x3200;
public static final int PARSE_PASSIVATION_ANNOTATION = 0x3250;
public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300;
public static final int PARSE_AROUNDTIMEOUT_ANNOTATION = 0x3400;
public static final int PARSE_TIMEOUT_ANNOTATION = 0x3401;
public static final int PARSE_EJB_DD_INTERCEPTORS = 0x3500;
public static final int PARSE_EJB_SECURITY_ROLE_REF_DD = 0x3501;
public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x3600;
public static final int PARSE_DISTINCT_NAME = 0x3601;
public static final int PARSE_OSGI_DEPLOYMENT = 0x3700;
public static final int PARSE_OSGI_SUBSYSTEM_ACTIVATOR = 0x3800;
// should be after all components are known
public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x4000;
public static final int PARSE_JACORB = 0x4100;
public static final int PARSE_TRANSACTION_ROLLBACK_ACTION = 0x4200;
public static final int PARSE_WEB_INITIALIZE_IN_ORDER = 0x4300;
public static final int PARSE_EAR_MESSAGE_DESTINATIONS = 0x4400;
public static final int PARSE_DSXML_DEPLOYMENT = 0x4500;
public static final int PARSE_MESSAGING_XML_RESOURCES = 0x4600;
// REGISTER
public static final int REGISTER_BUNDLE_INSTALL = 0x0100;
// DEPENDENCIES
public static final int DEPENDENCIES_EJB = 0x0200;
public static final int DEPENDENCIES_MODULE = 0x0300;
public static final int DEPENDENCIES_RAR_CONFIG = 0x0400;
public static final int DEPENDENCIES_MANAGED_BEAN = 0x0500;
public static final int DEPENDENCIES_SAR_MODULE = 0x0600;
public static final int DEPENDENCIES_WAR_MODULE = 0x0700;
public static final int DEPENDENCIES_CLASS_PATH = 0x0800;
public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900;
public static final int DEPENDENCIES_WELD = 0x0A00;
public static final int DEPENDENCIES_SEAM = 0x0A01;
public static final int DEPENDENCIES_WS = 0x0C00;
public static final int DEPENDENCIES_SECURITY = 0x0C50;
public static final int DEPENDENCIES_JAXRS = 0x0D00;
public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00;
public static final int DEPENDENCIES_PERSISTENCE_ANNOTATION = 0x0F00;
public static final int DEPENDENCIES_JPA = 0x1000;
public static final int DEPENDENCIES_GLOBAL_MODULES = 0x1100;
public static final int DEPENDENCIES_JDK = 0x1200;
public static final int DEPENDENCIES_JACORB = 0x1300;
public static final int DEPENDENCIES_CMP = 0x1500;
public static final int DEPENDENCIES_JAXR = 0x1600;
public static final int DEPENDENCIES_DRIVERS = 0x1700;
public static final int DEPENDENCIES_JSF = 0x1800;
//these must be last, and in this specific order
public static final int DEPENDENCIES_APPLICATION_CLIENT = 0x2000;
public static final int DEPENDENCIES_VISIBLE_MODULES = 0x2100;
public static final int DEPENDENCIES_EE_CLASS_DESCRIPTIONS = 0x2200;
// CONFIGURE_MODULE
public static final int CONFIGURE_RESOLVE_BUNDLE = 0x0100;
public static final int CONFIGURE_MODULE_SPEC = 0x0200;
public static final int CONFIGURE_RESOLVE_SUB_BUNDLE = 0x0300;
// POST_MODULE
public static final int POST_MODULE_INJECTION_ANNOTATION = 0x0100;
public static final int POST_MODULE_REFLECTION_INDEX = 0x0200;
public static final int POST_MODULE_TRANSFORMER = 0x0201;
public static final int POST_MODULE_JSF_MANAGED_BEANS = 0x0300;
public static final int POST_MODULE_INTERCEPTOR_ANNOTATIONS = 0x0301;
public static final int POST_MODULE_EJB_BUSINESS_VIEW_ANNOTATION = 0x0400;
public static final int POST_MODULE_EJB_HOME_MERGE = 0x0401;
public static final int POST_MODULE_EJB_DD_METHOD_RESOLUTION = 0x0402;
public static final int POST_MODULE_EJB_TIMER_METADATA_MERGE = 0x0506;
public static final int POST_MODULE_EJB_SLSB_POOL_NAME_MERGE = 0x0507;
public static final int POST_MODULE_EJB_MDB_POOL_NAME_MERGE = 0x0508;
public static final int POST_MODULE_EJB_ENTITY_POOL_NAME_MERGE = 0x0509;
public static final int POST_MODULE_EJB_DD_INTERCEPTORS = 0x0600;
public static final int POST_MODULE_EJB_TIMER_SERVICE = 0x0601;
public static final int POST_MODULE_EJB_TRANSACTION_MANAGEMENT = 0x0602;
public static final int POST_MODULE_EJB_TX_ATTR_MERGE = 0x0603;
public static final int POST_MODULE_EJB_CONCURRENCY_MANAGEMENT_MERGE= 0x0604;
public static final int POST_MODULE_EJB_CONCURRENCY_MERGE = 0x0605;
public static final int POST_MODULE_EJB_RUN_AS_MERGE = 0x0606;
public static final int POST_MODULE_EJB_RESOURCE_ADAPTER_MERGE = 0x0607;
public static final int POST_MODULE_EJB_REMOVE_METHOD = 0x0608;
public static final int POST_MODULE_EJB_STARTUP_MERGE = 0x0609;
public static final int POST_MODULE_EJB_SECURITY_DOMAIN = 0x060A;
public static final int POST_MODULE_EJB_ROLES = 0x060B;
public static final int POST_MODULE_METHOD_PERMISSIONS = 0x060C;
public static final int POST_MODULE_EJB_STATEFUL_TIMEOUT = 0x060D;
public static final int POST_MODULE_EJB_ASYNCHRONOUS_MERGE = 0x060E;
public static final int POST_MODULE_EJB_SESSION_SYNCHRONIZATION = 0x060F;
public static final int POST_MODULE_EJB_INIT_METHOD = 0x0610;
public static final int POST_MODULE_EJB_SESSION_BEAN = 0x0611;
public static final int POST_MODULE_EJB_SECURITY_PRINCIPAL_ROLE_MAPPING_MERGE = 0x0612;
public static final int POST_MODULE_EJB_CACHE = 0x0614;
public static final int POST_MODULE_EJB_CLUSTERED = 0x0615;
public static final int POST_MODULE_WELD_COMPONENT_INTEGRATION = 0x0800;
public static final int POST_MODULE_INSTALL_EXTENSION = 0x0A00;
public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0B00;
public static final int POST_MODULE_EAR_DEPENDENCY = 0x0C00;
public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0D00;
public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0E00;
// should come before ejb jndi bindings processor
public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x1000;
public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x1100;
public static final int POST_MODULE_EJB_CLIENT_METADATA = 0x1102;
public static final int POST_MODULE_EJB_APPLICATION_EXCEPTIONS = 0x1200;
public static final int POST_INITIALIZE_IN_ORDER = 0x1300;
public static final int POST_MODULE_ENV_ENTRY = 0x1400;
public static final int POST_MODULE_EJB_REF = 0x1500;
public static final int POST_MODULE_PERSISTENCE_REF = 0x1600;
public static final int POST_MODULE_PERSISTENCE_CLASS_FILE_TRANSFORMER = 0x1620;
public static final int POST_MODULE_DATASOURCE_REF = 0x1700;
public static final int POST_MODULE_WS_REF_DESCRIPTOR = 0x1800;
public static final int POST_MODULE_WS_REF_ANNOTATION = 0x1801;
public static final int POST_MODULE_JAXRS_SCANNING = 0x1A00;
public static final int POST_MODULE_JAXRS_COMPONENT = 0x1B00;
public static final int POST_MODULE_JAXRS_CDI_INTEGRATION = 0x1C00;
public static final int POST_MODULE_LOCAL_HOME = 0x1E00;
public static final int POST_MODULE_APPLICATION_CLIENT_MANIFEST = 0x1F00;
public static final int POST_MODULE_APPLICATION_CLIENT_ACTIVE = 0x2000;
public static final int POST_MODULE_APP_CLIENT_METHOD_RESOLUTION = 0x2020;
public static final int POST_MODULE_EJB_ORB_BIND = 0x2100;
public static final int POST_MODULE_CMP_PARSE = 0x2300;
public static final int POST_MODULE_CMP_ENTITY_METADATA = 0x2400;
public static final int POST_MODULE_CMP_STORE_MANAGER = 0x2500;
public static final int POST_MODULE_EJB_IIOP = 0x2600;
public static final int POST_MODULE_POJO = 0x2700;
public static final int POST_MODULE_NAMING_CONTEXT = 0x2800;
public static final int POST_MODULE_APP_NAMING_CONTEXT = 0x2900;
public static final int POST_MODULE_CACHED_CONNECTION_MANAGER = 0x2A00;
public static final int POST_MODULE_LOGGING_CONFIG = 0x2B00;
// INSTALL
public static final int INSTALL_JNDI_DEPENDENCY_SETUP = 0x0100;
public static final int INSTALL_JPA_INTERCEPTORS = 0x0200;
public static final int INSTALL_JACC_POLICY = 0x0350;
public static final int INSTALL_COMPONENT_AGGREGATION = 0x0400;
public static final int INSTALL_RESOLVE_MESSAGE_DESTINATIONS = 0x0403;
public static final int INSTALL_EJB_CLIENT_CONTEXT = 0x0404;
public static final int INSTALL_EJB_JACC_PROCESSING = 0x0405;
public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500;
public static final int INSTALL_RESOLVER_MODULE = 0x0600;
public static final int INSTALL_RA_NATIVE = 0x0800;
public static final int INSTALL_RA_DEPLOYMENT = 0x0801;
public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900;
public static final int INSTALL_POJO_DEPLOYMENT = 0x0A00;
public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00;
public static final int INSTALL_EE_MODULE_CONFIG = 0x1101;
public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200;
public static final int INSTALL_DEPENDS_ON_ANNOTATION = 0x1210;
public static final int INSTALL_PERSISTENCE_PROVIDER = 0x1215; // before INSTALL_PERSISTENTUNIT
public static final int INSTALL_PERSISTENTUNIT = 0x1220;
public static final int INSTALL_EE_COMPONENT = 0x1230;
public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300;
public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500;
public static final int INSTALL_JSF_ANNOTATIONS = 0x1600;
public static final int INSTALL_JDBC_DRIVER = 0x1800;
public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900;
public static final int INSTALL_BUNDLE_CONTEXT_BINDING = 0x1A00;
public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00;
public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00;
public static final int INSTALL_JNDI_DEPENDENCIES = 0x1C01;
public static final int INSTALL_WS_UNIVERSAL_META_DATA_MODEL = 0x1C10;
public static final int INSTALL_WS_DEPLOYMENT_ASPECTS = 0x1C11;
// IMPORTANT: WS integration installs deployment aspects dynamically
// so consider INSTALL 0x1C10 - 0x1CFF reserved for WS subsystem!
public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00;
public static final int INSTALL_WAB_DEPLOYMENT = 0x1E00;
public static final int INSTALL_DEPLOYMENT_REPOSITORY = 0x1F00;
public static final int INSTALL_EJB_MANAGEMENT_RESOURCES = 0x2000;
public static final int INSTALL_APPLICATION_CLIENT = 0x2010;
public static final int INSTALL_DSXML_DEPLOYMENT = 0x2020;
public static final int INSTALL_MESSAGING_XML_RESOURCES = 0x2030;
public static final int INSTALL_BUNDLE_ACTIVATE = 0x2040;
// CLEANUP
public static final int CLEANUP_REFLECTION_INDEX = 0x0100;
public static final int CLEANUP_EE = 0x0200;
public static final int CLEANUP_EJB = 0x0300;
public static final int CLEANUP_ANNOTATION_INDEX = 0x0400;
}
| server/src/main/java/org/jboss/as/server/deployment/Phase.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., 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.as.server.deployment;
/**
* An enumeration of the phases of a deployment unit's processing cycle.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public enum Phase {
/* == TEMPLATE ==
* Upon entry, this phase performs the following actions:
* <ul>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
/**
* This phase creates the initial root structure. Depending on the service for this phase will ensure that the
* deployment unit's initial root structure is available and accessible.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li>
* <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments:
* <ul>
* <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* </ul>
* <p>
*/
STRUCTURE(null),
/**
* This phase assembles information from the root structure to prepare for adding and processing additional external
* structure, such as from class path entries and other similar mechanisms.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li>
* <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li>
* <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li>
* </ul>
* <p>
*/
PARSE(null),
/**
* In this phase parsing of deployment metadata is complete and the component may be registered with the subsystem.
* This is prior to working out the components dependency and equivalent to the OSGi INSTALL life cycle.
*/
REGISTER(null),
/**
* In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>Any additional external structure is mounted during {@link #XXX}</li>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
DEPENDENCIES(null),
CONFIGURE_MODULE(null),
POST_MODULE(null),
INSTALL(null),
CLEANUP(null),
;
/**
* This is the key for the attachment to use as the phase's "value". The attachment is taken from
* the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified.
*/
private final AttachmentKey<?> phaseKey;
private Phase(final AttachmentKey<?> key) {
phaseKey = key;
}
/**
* Get the next phase, or {@code null} if none.
*
* @return the next phase, or {@code null} if there is none
*/
public Phase next() {
final int ord = ordinal() + 1;
final Phase[] phases = Phase.values();
return ord == phases.length ? null : phases[ord];
}
/**
* Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value
* of this phase.
*
* @return the key
*/
public AttachmentKey<?> getPhaseKey() {
return phaseKey;
}
// STRUCTURE
public static final int STRUCTURE_EXPLODED_MOUNT = 0x0100;
public static final int STRUCTURE_MOUNT = 0x0200;
public static final int STRUCTURE_MANIFEST = 0x0300;
public static final int STRUCTURE_OSGI_MANIFEST = 0x0400;
public static final int STRUCTURE_EE_SPEC_DESC_PROPERTY_REPLACEMENT = 0x0500;
public static final int STRUCTURE_EE_JBOSS_DESC_PROPERTY_REPLACEMENT= 0x0550;
public static final int STRUCTURE_JDBC_DRIVER = 0x0600;
public static final int STRUCTURE_RAR = 0x0700;
public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0800;
public static final int STRUCTURE_WAR = 0x0900;
public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0A00;
public static final int STRUCTURE_REGISTER_JBOSS_ALL_XML_PARSER = 0x0A10;
public static final int STRUCTURE_PARSE_JBOSS_ALL_XML = 0x0A20;
public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0B00;
public static final int STRUCTURE_JBOSS_EJB_CLIENT_XML_PARSE = 0x0C00;
public static final int STRUCTURE_EJB_EAR_APPLICATION_NAME = 0x0D00;
public static final int STRUCTURE_EAR = 0x0E00;
public static final int STRUCTURE_APP_CLIENT = 0x0F00;
public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x1000;
public static final int STRUCTURE_ANNOTATION_INDEX = 0x1100;
public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x1200;
public static final int STRUCTURE_APPLICATION_CLIENT_IN_EAR = 0x1300;
public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x1400;
public static final int STRUCTURE_BUNDLE_JAR_IN_EAR = 0x1450;
public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x1500;
public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x1600;
public static final int STRUCTURE_SUB_DEPLOYMENT = 0x1700;
public static final int STRUCTURE_JBOSS_DEPLOYMENT_STRUCTURE = 0x1800;
public static final int STRUCTURE_CLASS_PATH = 0x1900;
public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1A00;
public static final int STRUCTURE_EE_MODULE_INIT = 0x1B00;
public static final int STRUCTURE_EE_RESOURCE_INJECTION_REGISTRY = 0x1C00;
// PARSE
public static final int PARSE_EE_DEPLOYMENT_PROPERTIES = 0x0001;
public static final int PARSE_EE_DEPLOYMENT_PROPERTY_RESOLVER = 0x0002;
public static final int PARSE_EE_VAULT_PROPERTY_RESOLVER = 0x0003;
public static final int PARSE_EE_SYSTEM_PROPERTY_RESOLVER = 0x0004;
public static final int PARSE_EE_PROPERTY_RESOLVER = 0x0005;
public static final int PARSE_EE_MODULE_NAME = 0x0100;
public static final int PARSE_EJB_DEFAULT_DISTINCT_NAME = 0x0110;
public static final int PARSE_EAR_SUBDEPLOYMENTS_ISOLATION_DEFAULT = 0x0200;
public static final int PARSE_DEPENDENCIES_MANIFEST = 0x0300;
public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0301;
public static final int PARSE_EXTENSION_LIST = 0x0700;
public static final int PARSE_EXTENSION_NAME = 0x0800;
public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900;
public static final int PARSE_OSGI_PROPERTIES = 0x0A00;
public static final int PARSE_WEB_DEPLOYMENT = 0x0B00;
public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00;
public static final int PARSE_JSF_VERSION = 0x0C50;
public static final int PARSE_JSF_SHARED_TLDS = 0x0C51;
public static final int PARSE_ANNOTATION_WAR = 0x0D00;
public static final int PARSE_ANNOTATION_EJB = 0x0D10;
public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00;
public static final int PARSE_TLD_DEPLOYMENT = 0x0F00;
public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000;
// create and attach EJB metadata for EJB deployments
public static final int PARSE_EJB_DEPLOYMENT = 0x1100;
public static final int PARSE_APP_CLIENT_XML = 0x1101;
public static final int PARSE_CREATE_COMPONENT_DESCRIPTIONS = 0x1150;
// described EJBs must be created after annotated EJBs
public static final int PARSE_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1152;
public static final int PARSE_CMP_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1153;
public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200;
// create and attach the component description out of EJB annotations
public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901;
public static final int PARSE_WEB_COMPONENTS = 0x1F00;
public static final int PARSE_WEB_MERGE_METADATA = 0x2000;
public static final int PARSE_WEBSERVICES_CONTEXT_INJECTION = 0x2040;
public static final int PARSE_WEBSERVICES_XML = 0x2050;
public static final int PARSE_JBOSS_WEBSERVICES_XML = 0x2051;
public static final int PARSE_JAXWS_EJB_INTEGRATION = 0x2052;
public static final int PARSE_JAXRPC_POJO_INTEGRATION = 0x2053;
public static final int PARSE_JAXRPC_EJB_INTEGRATION = 0x2054;
public static final int PARSE_JAXWS_HANDLER_CHAIN_ANNOTATION = 0x2055;
public static final int PARSE_WS_JMS_INTEGRATION = 0x2056;
public static final int PARSE_JAXWS_ENDPOINT_CREATE_COMPONENT_DESCRIPTIONS = 0x2057;
public static final int PARSE_JAXWS_HANDLER_CREATE_COMPONENT_DESCRIPTIONS = 0x2058;
public static final int PARSE_RA_DEPLOYMENT = 0x2100;
public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200;
public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300;
public static final int PARSE_POJO_DEPLOYMENT = 0x2400;
public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500;
public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900;
public static final int PARSE_EE_ANNOTATIONS = 0x2901;
public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00;
public static final int PARSE_CDI_ANNOTATIONS = 0x2A10;
public static final int PARSE_WELD_DEPLOYMENT = 0x2B00;
public static final int PARSE_WELD_WEB_INTEGRATION = 0x2B10;
public static final int PARSE_DATA_SOURCE_DEFINITION_ANNOTATION = 0x2D00;
public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00;
public static final int PARSE_EJB_TIMERSERVICE_BINDING = 0x2E01;
public static final int PARSE_PERSISTENCE_UNIT = 0x2F00;
public static final int PARSE_LIFECYCLE_ANNOTATION = 0x3200;
public static final int PARSE_PASSIVATION_ANNOTATION = 0x3250;
public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300;
public static final int PARSE_AROUNDTIMEOUT_ANNOTATION = 0x3400;
public static final int PARSE_TIMEOUT_ANNOTATION = 0x3401;
public static final int PARSE_EJB_DD_INTERCEPTORS = 0x3500;
public static final int PARSE_EJB_SECURITY_ROLE_REF_DD = 0x3501;
public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x3600;
public static final int PARSE_DISTINCT_NAME = 0x3601;
public static final int PARSE_OSGI_DEPLOYMENT = 0x3700;
public static final int PARSE_OSGI_SUBSYSTEM_ACTIVATOR = 0x3800;
// should be after all components are known
public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x4000;
public static final int PARSE_JACORB = 0x4100;
public static final int PARSE_TRANSACTION_ROLLBACK_ACTION = 0x4200;
public static final int PARSE_WEB_INITIALIZE_IN_ORDER = 0x4300;
public static final int PARSE_EAR_MESSAGE_DESTINATIONS = 0x4400;
public static final int PARSE_DSXML_DEPLOYMENT = 0x4500;
public static final int PARSE_MESSAGING_XML_RESOURCES = 0x4600;
// REGISTER
public static final int REGISTER_BUNDLE_INSTALL = 0x0100;
// DEPENDENCIES
public static final int DEPENDENCIES_EJB = 0x0200;
public static final int DEPENDENCIES_MODULE = 0x0300;
public static final int DEPENDENCIES_RAR_CONFIG = 0x0400;
public static final int DEPENDENCIES_MANAGED_BEAN = 0x0500;
public static final int DEPENDENCIES_SAR_MODULE = 0x0600;
public static final int DEPENDENCIES_WAR_MODULE = 0x0700;
public static final int DEPENDENCIES_CLASS_PATH = 0x0800;
public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900;
public static final int DEPENDENCIES_WELD = 0x0A00;
public static final int DEPENDENCIES_SEAM = 0x0A01;
public static final int DEPENDENCIES_WS = 0x0C00;
public static final int DEPENDENCIES_SECURITY = 0x0C50;
public static final int DEPENDENCIES_JAXRS = 0x0D00;
public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00;
public static final int DEPENDENCIES_PERSISTENCE_ANNOTATION = 0x0F00;
public static final int DEPENDENCIES_JPA = 0x1000;
public static final int DEPENDENCIES_GLOBAL_MODULES = 0x1100;
public static final int DEPENDENCIES_JDK = 0x1200;
public static final int DEPENDENCIES_JACORB = 0x1300;
public static final int DEPENDENCIES_CMP = 0x1500;
public static final int DEPENDENCIES_JAXR = 0x1600;
public static final int DEPENDENCIES_DRIVERS = 0x1700;
public static final int DEPENDENCIES_JSF = 0x1800;
//these must be last, and in this specific order
public static final int DEPENDENCIES_APPLICATION_CLIENT = 0x2000;
public static final int DEPENDENCIES_VISIBLE_MODULES = 0x2100;
public static final int DEPENDENCIES_EE_CLASS_DESCRIPTIONS = 0x2200;
// CONFIGURE_MODULE
public static final int CONFIGURE_RESOLVE_BUNDLE = 0x0100;
public static final int CONFIGURE_MODULE_SPEC = 0x0200;
public static final int CONFIGURE_RESOLVE_SUB_BUNDLE = 0x0300;
// POST_MODULE
public static final int POST_MODULE_INJECTION_ANNOTATION = 0x0100;
public static final int POST_MODULE_REFLECTION_INDEX = 0x0200;
public static final int POST_MODULE_TRANSFORMER = 0x0201;
public static final int POST_MODULE_JSF_MANAGED_BEANS = 0x0300;
public static final int POST_MODULE_INTERCEPTOR_ANNOTATIONS = 0x0301;
public static final int POST_MODULE_EJB_BUSINESS_VIEW_ANNOTATION = 0x0400;
public static final int POST_MODULE_EJB_HOME_MERGE = 0x0401;
public static final int POST_MODULE_EJB_DD_METHOD_RESOLUTION = 0x0402;
public static final int POST_MODULE_EJB_TIMER_METADATA_MERGE = 0x0506;
public static final int POST_MODULE_EJB_SLSB_POOL_NAME_MERGE = 0x0507;
public static final int POST_MODULE_EJB_MDB_POOL_NAME_MERGE = 0x0508;
public static final int POST_MODULE_EJB_ENTITY_POOL_NAME_MERGE = 0x0509;
public static final int POST_MODULE_EJB_DD_INTERCEPTORS = 0x0600;
public static final int POST_MODULE_EJB_TIMER_SERVICE = 0x0601;
public static final int POST_MODULE_EJB_TRANSACTION_MANAGEMENT = 0x0602;
public static final int POST_MODULE_EJB_TX_ATTR_MERGE = 0x0603;
public static final int POST_MODULE_EJB_CONCURRENCY_MANAGEMENT_MERGE= 0x0604;
public static final int POST_MODULE_EJB_CONCURRENCY_MERGE = 0x0605;
public static final int POST_MODULE_EJB_RUN_AS_MERGE = 0x0606;
public static final int POST_MODULE_EJB_RESOURCE_ADAPTER_MERGE = 0x0607;
public static final int POST_MODULE_EJB_REMOVE_METHOD = 0x0608;
public static final int POST_MODULE_EJB_STARTUP_MERGE = 0x0609;
public static final int POST_MODULE_EJB_SECURITY_DOMAIN = 0x060A;
public static final int POST_MODULE_EJB_ROLES = 0x060B;
public static final int POST_MODULE_METHOD_PERMISSIONS = 0x060C;
public static final int POST_MODULE_EJB_STATEFUL_TIMEOUT = 0x060D;
public static final int POST_MODULE_EJB_ASYNCHRONOUS_MERGE = 0x060E;
public static final int POST_MODULE_EJB_SESSION_SYNCHRONIZATION = 0x060F;
public static final int POST_MODULE_EJB_INIT_METHOD = 0x0610;
public static final int POST_MODULE_EJB_SESSION_BEAN = 0x0611;
public static final int POST_MODULE_EJB_SECURITY_PRINCIPAL_ROLE_MAPPING_MERGE = 0x0612;
public static final int POST_MODULE_EJB_CACHE = 0x0614;
public static final int POST_MODULE_EJB_CLUSTERED = 0x0615;
public static final int POST_MODULE_WELD_COMPONENT_INTEGRATION = 0x0800;
public static final int POST_MODULE_INSTALL_EXTENSION = 0x0A00;
public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0B00;
public static final int POST_MODULE_EAR_DEPENDENCY = 0x0C00;
public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0D00;
public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0E00;
// should come before ejb jndi bindings processor
public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x1000;
public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x1100;
public static final int POST_MODULE_EJB_CLIENT_METADATA = 0x1102;
public static final int POST_MODULE_EJB_APPLICATION_EXCEPTIONS = 0x1200;
public static final int POST_INITIALIZE_IN_ORDER = 0x1300;
public static final int POST_MODULE_ENV_ENTRY = 0x1400;
public static final int POST_MODULE_EJB_REF = 0x1500;
public static final int POST_MODULE_PERSISTENCE_REF = 0x1600;
public static final int POST_MODULE_PERSISTENCE_CLASS_FILE_TRANSFORMER = 0x1620;
public static final int POST_MODULE_DATASOURCE_REF = 0x1700;
public static final int POST_MODULE_WS_REF_DESCRIPTOR = 0x1800;
public static final int POST_MODULE_WS_REF_ANNOTATION = 0x1801;
public static final int POST_MODULE_JAXRS_SCANNING = 0x1A00;
public static final int POST_MODULE_JAXRS_COMPONENT = 0x1B00;
public static final int POST_MODULE_JAXRS_CDI_INTEGRATION = 0x1C00;
public static final int POST_MODULE_LOCAL_HOME = 0x1E00;
public static final int POST_MODULE_APPLICATION_CLIENT_MANIFEST = 0x1F00;
public static final int POST_MODULE_APPLICATION_CLIENT_ACTIVE = 0x2000;
public static final int POST_MODULE_APP_CLIENT_METHOD_RESOLUTION = 0x2020;
public static final int POST_MODULE_EJB_ORB_BIND = 0x2100;
public static final int POST_MODULE_CMP_PARSE = 0x2300;
public static final int POST_MODULE_CMP_ENTITY_METADATA = 0x2400;
public static final int POST_MODULE_CMP_STORE_MANAGER = 0x2500;
public static final int POST_MODULE_EJB_IIOP = 0x2600;
public static final int POST_MODULE_POJO = 0x2700;
public static final int POST_MODULE_NAMING_CONTEXT = 0x2800;
public static final int POST_MODULE_APP_NAMING_CONTEXT = 0x2900;
public static final int POST_MODULE_CACHED_CONNECTION_MANAGER = 0x2A00;
public static final int POST_MODULE_LOGGING_CONFIG = 0x2B00;
// INSTALL
public static final int INSTALL_JNDI_DEPENDENCY_SETUP = 0x0100;
public static final int INSTALL_JPA_INTERCEPTORS = 0x0200;
public static final int INSTALL_JACC_POLICY = 0x0350;
public static final int INSTALL_COMPONENT_AGGREGATION = 0x0400;
public static final int INSTALL_RESOLVE_MESSAGE_DESTINATIONS = 0x0403;
public static final int INSTALL_EJB_CLIENT_CONTEXT = 0x0404;
public static final int INSTALL_EJB_JACC_PROCESSING = 0x0405;
public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500;
public static final int INSTALL_RESOLVER_MODULE = 0x0600;
public static final int INSTALL_RA_NATIVE = 0x0800;
public static final int INSTALL_RA_DEPLOYMENT = 0x0801;
public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900;
public static final int INSTALL_POJO_DEPLOYMENT = 0x0A00;
public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00;
public static final int INSTALL_EE_MODULE_CONFIG = 0x1101;
public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200;
public static final int INSTALL_DEPENDS_ON_ANNOTATION = 0x1210;
public static final int INSTALL_PERSISTENCE_PROVIDER = 0x1215; // before INSTALL_PERSISTENTUNIT
public static final int INSTALL_PERSISTENTUNIT = 0x1220;
public static final int INSTALL_EE_COMPONENT = 0x1230;
public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300;
public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500;
public static final int INSTALL_JSF_ANNOTATIONS = 0x1600;
public static final int INSTALL_JDBC_DRIVER = 0x1800;
public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900;
public static final int INSTALL_BUNDLE_CONTEXT_BINDING = 0x1A00;
public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00;
public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00;
public static final int INSTALL_JNDI_DEPENDENCIES = 0x1C01;
public static final int INSTALL_WS_UNIVERSAL_META_DATA_MODEL = 0x1C10;
public static final int INSTALL_WS_DEPLOYMENT_ASPECTS = 0x1C11;
// IMPORTANT: WS integration installs deployment aspects dynamically
// so consider INSTALL 0x1C10 - 0x1CFF reserved for WS subsystem!
public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00;
public static final int INSTALL_WAB_DEPLOYMENT = 0x1E00;
public static final int INSTALL_DEPLOYMENT_REPOSITORY = 0x1F00;
public static final int INSTALL_EJB_MANAGEMENT_RESOURCES = 0x2000;
public static final int INSTALL_APPLICATION_CLIENT = 0x2010;
public static final int INSTALL_DSXML_DEPLOYMENT = 0x2020;
public static final int INSTALL_MESSAGING_XML_RESOURCES = 0x2030;
public static final int INSTALL_BUNDLE_ACTIVATE = 0x2040;
// CLEANUP
public static final int CLEANUP_REFLECTION_INDEX = 0x0100;
public static final int CLEANUP_EE = 0x0200;
public static final int CLEANUP_EJB = 0x0300;
public static final int CLEANUP_ANNOTATION_INDEX = 0x0400;
}
| [AS7-5054] Allow CDI deployments as OSGi bundles
was: 391b9bc945939ec4d84d43491e0deb246ea100f8
| server/src/main/java/org/jboss/as/server/deployment/Phase.java | [AS7-5054] Allow CDI deployments as OSGi bundles |
|
Java | unlicense | d213f09d2c918a7c923aca0ba2db6d9663127476 | 0 | TeamMeanMachine/meanlib,TeamMeanMachine/meanlib | package org.team2471.frc.lib.motion_profiling;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import org.team2471.frc.lib.vector.Vector2;
public class Path2D {
private Path2DCurve m_xyCurve; // positive y is forward in robot space, and positive x is to the robot's right
private MotionCurve m_easeCurve; // the ease curve is the percentage along the path the robot as a function of time
private double m_robotWidth = 36.5 / 12.0; // average FRC robots are 28 inches wide, converted to feet. // seems like this belongs in the Command
private Vector2 m_prevCenterPositionForLeft;
private Vector2 m_prevCenterPositionForRight;
private Vector2 m_prevLeftPosition;
private Vector2 m_prevRightPosition;
private double travelDirection;
private boolean m_mirrored;
private String name;
public Path2D() {
m_xyCurve = new Path2DCurve();
m_easeCurve = new MotionCurve();
travelDirection = 1.0;
}
public Path2D(String name) {
this.name = name;
m_xyCurve = new Path2DCurve();
m_easeCurve = new MotionCurve();
travelDirection = 1.0;
}
public void reset() {
m_prevCenterPositionForLeft = null;
m_prevCenterPositionForRight = null;
m_prevLeftPosition = null;
m_prevRightPosition = null;
}
public void addVector2(Vector2 point) {
addPoint(point.x, point.y);
}
public void addPoint(double x, double y) {
m_xyCurve.addPointToEnd(x, y);
}
public void addPointAndTangent(double x, double y, double xTangent, double yTangent) {
m_xyCurve.addPointToEnd(x, y, xTangent, yTangent);
}
public void addPointAngleAndMagnitude(double x, double y, double angle, double magnitude) {
m_xyCurve.addPointAngleAndMagnitudeToEnd(x, y, angle, magnitude);
}
public void addEasePoint(double time, double value) {
m_easeCurve.storeValue(time, value);
}
public void addEasePointSlopeAndMagnitude(double time, double value, double slope, double magnitude) {
m_easeCurve.storeValueSlopeAndMagnitude(time, value, slope, magnitude);
}
public Vector2 getPosition(double time) {
return getPositionAtEase(m_easeCurve.getValue(time));
}
public Vector2 getTangent(double time) {
return getTangentAtEase(m_easeCurve.getValue(time));
}
public Vector2 getPositionAtEase(double ease) {
double totalDistance = m_xyCurve.getLength();
return m_xyCurve.getPositionAtDistance(ease * totalDistance);
}
public Vector2 getTangentAtEase(double ease) {
double totalDistance = m_xyCurve.getLength();
return m_xyCurve.getTangentAtDistance(ease * totalDistance);
}
public Vector2 getSidePosition(double time, double xOffset) { // offset can be positive or negative (half the width of the robot)
Vector2 centerPosition = getPosition(time); // this could compute the position for a specific offset vector on the robot
Vector2 tangent = getTangent(time);
tangent = Vector2.normalize(tangent);
tangent = Vector2.perpendicular(tangent);
tangent = Vector2.multiply(tangent, xOffset);
Vector2 sidePosition = Vector2.add(centerPosition, tangent);
return sidePosition;
}
public Vector2 getLeftPosition(double time) {
return getSidePosition(time, -m_robotWidth / 2.0);
}
public Vector2 getRightPosition(double time) {
return getSidePosition(time, m_robotWidth / 2.0);
}
private double privateGetLeftPositionDelta(double time) {
if (m_prevLeftPosition == null) {
m_prevCenterPositionForLeft = getPosition(time);
m_prevLeftPosition = getLeftPosition(time);
return 0.0;
}
Vector2 centerPosition = getPosition(time);
Vector2 leftPosition = getLeftPosition(time);
Vector2 deltaCenter = Vector2.subtract(centerPosition, m_prevCenterPositionForLeft);
Vector2 deltaLeft = Vector2.subtract(leftPosition, m_prevLeftPosition);
m_prevCenterPositionForLeft = centerPosition;
m_prevLeftPosition = leftPosition;
if (Vector2.dot(deltaCenter, deltaLeft) > 0) {
return Vector2.length(deltaLeft);
} else {
return -Vector2.length(deltaLeft);
}
}
private double privateGetRightPositionDelta(double time) {
if (m_prevRightPosition == null) {
m_prevCenterPositionForRight = getPosition(time);
m_prevRightPosition = getRightPosition(time);
return 0.0;
}
Vector2 centerPosition = getPosition(time);
Vector2 rightPosition = getRightPosition(time);
Vector2 deltaCenter = Vector2.subtract(centerPosition, m_prevCenterPositionForRight);
Vector2 deltaRight = Vector2.subtract(rightPosition, m_prevRightPosition);
m_prevCenterPositionForRight = centerPosition;
m_prevRightPosition = rightPosition;
if (Vector2.dot(deltaCenter, deltaRight) > 0) {
return Vector2.length(deltaRight);
} else {
return -Vector2.length(deltaRight);
}
}
public double getLeftPositionDelta(double time) {
if (travelDirection>0)
return privateGetLeftPositionDelta(time);
else
return -privateGetRightPositionDelta(time);
}
public double getRightPositionDelta(double time) {
if (travelDirection>0)
return privateGetRightPositionDelta(time);
else
return -privateGetLeftPositionDelta(time);
}
public double getRobotWidth() {
return m_robotWidth;
}
public void setRobotWidth(double robotWidth) {
m_robotWidth = robotWidth;
}
public double getPathLength() {
return m_xyCurve.getLength();
}
public double getDuration() {
return m_easeCurve.getLength();
}
public MotionCurve getEaseCurve() {
return m_easeCurve;
}
public double getTravelDirection() {
return travelDirection;
}
public void setTravelDirection(double travelDirection) {
this.travelDirection = travelDirection;
}
public boolean isMirrored() {
return m_mirrored;
}
public void setMirrored(boolean mirrored) {
this.m_mirrored = mirrored;
}
public void writeToNetworkTable() {
NetworkTable table = NetworkTable.getTable("PathVisualizer");
table.putString( name, toString() );
}
public void readFromNetworkTable() {
NetworkTable table = NetworkTable.getTable("PathVisualizer");
String pathString = table.getString( name, "" );
}
public String toString() {
String rValue = "";
for (Path2DPoint point = m_xyCurve.getHeadPoint(); point != null; point = point.getNextPoint()) {
rValue += point.toString();
}
return rValue;
}
public Path2DCurve getXYCurve() {
return m_xyCurve;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| src/main/java/org/team2471/frc/lib/motion_profiling/Path2D.java | package org.team2471.frc.lib.motion_profiling;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import org.team2471.frc.lib.vector.Vector2;
public class Path2D {
private Path2DCurve m_xyCurve; // positive y is forward in robot space, and positive x is to the robot's right
private MotionCurve m_easeCurve; // the ease curve is the percentage along the path the robot as a function of time
private double m_robotWidth = 36.5 / 12.0; // average FRC robots are 28 inches wide, converted to feet. // seems like this belongs in the Command
private Vector2 m_prevCenterPositionForLeft;
private Vector2 m_prevCenterPositionForRight;
private Vector2 m_prevLeftPosition;
private Vector2 m_prevRightPosition;
private double travelDirection;
private boolean m_mirrored;
private String name;
public Path2D() {
m_xyCurve = new Path2DCurve();
m_easeCurve = new MotionCurve();
travelDirection = 1.0;
}
public void reset() {
m_prevCenterPositionForLeft = null;
m_prevCenterPositionForRight = null;
m_prevLeftPosition = null;
m_prevRightPosition = null;
}
public void addVector2(Vector2 point) {
addPoint(point.x, point.y);
}
public void addPoint(double x, double y) {
m_xyCurve.addPointToEnd(x, y);
}
public void addPointAndTangent(double x, double y, double xTangent, double yTangent) {
m_xyCurve.addPointToEnd(x, y, xTangent, yTangent);
}
public void addPointAngleAndMagnitude(double x, double y, double angle, double magnitude) {
m_xyCurve.addPointAngleAndMagnitudeToEnd(x, y, angle, magnitude);
}
public void addEasePoint(double time, double value) {
m_easeCurve.storeValue(time, value);
}
public void addEasePointSlopeAndMagnitude(double time, double value, double slope, double magnitude) {
m_easeCurve.storeValueSlopeAndMagnitude(time, value, slope, magnitude);
}
public Vector2 getPosition(double time) {
return getPositionAtEase(m_easeCurve.getValue(time));
}
public Vector2 getTangent(double time) {
return getTangentAtEase(m_easeCurve.getValue(time));
}
public Vector2 getPositionAtEase(double ease) {
double totalDistance = m_xyCurve.getLength();
return m_xyCurve.getPositionAtDistance(ease * totalDistance);
}
public Vector2 getTangentAtEase(double ease) {
double totalDistance = m_xyCurve.getLength();
return m_xyCurve.getTangentAtDistance(ease * totalDistance);
}
public Vector2 getSidePosition(double time, double xOffset) { // offset can be positive or negative (half the width of the robot)
Vector2 centerPosition = getPosition(time); // this could compute the position for a specific offset vector on the robot
Vector2 tangent = getTangent(time);
tangent = Vector2.normalize(tangent);
tangent = Vector2.perpendicular(tangent);
tangent = Vector2.multiply(tangent, xOffset);
Vector2 sidePosition = Vector2.add(centerPosition, tangent);
return sidePosition;
}
public Vector2 getLeftPosition(double time) {
return getSidePosition(time, -m_robotWidth / 2.0);
}
public Vector2 getRightPosition(double time) {
return getSidePosition(time, m_robotWidth / 2.0);
}
private double privateGetLeftPositionDelta(double time) {
if (m_prevLeftPosition == null) {
m_prevCenterPositionForLeft = getPosition(time);
m_prevLeftPosition = getLeftPosition(time);
return 0.0;
}
Vector2 centerPosition = getPosition(time);
Vector2 leftPosition = getLeftPosition(time);
Vector2 deltaCenter = Vector2.subtract(centerPosition, m_prevCenterPositionForLeft);
Vector2 deltaLeft = Vector2.subtract(leftPosition, m_prevLeftPosition);
m_prevCenterPositionForLeft = centerPosition;
m_prevLeftPosition = leftPosition;
if (Vector2.dot(deltaCenter, deltaLeft) > 0) {
return Vector2.length(deltaLeft);
} else {
return -Vector2.length(deltaLeft);
}
}
private double privateGetRightPositionDelta(double time) {
if (m_prevRightPosition == null) {
m_prevCenterPositionForRight = getPosition(time);
m_prevRightPosition = getRightPosition(time);
return 0.0;
}
Vector2 centerPosition = getPosition(time);
Vector2 rightPosition = getRightPosition(time);
Vector2 deltaCenter = Vector2.subtract(centerPosition, m_prevCenterPositionForRight);
Vector2 deltaRight = Vector2.subtract(rightPosition, m_prevRightPosition);
m_prevCenterPositionForRight = centerPosition;
m_prevRightPosition = rightPosition;
if (Vector2.dot(deltaCenter, deltaRight) > 0) {
return Vector2.length(deltaRight);
} else {
return -Vector2.length(deltaRight);
}
}
public double getLeftPositionDelta(double time) {
if (travelDirection>0)
return privateGetLeftPositionDelta(time);
else
return -privateGetRightPositionDelta(time);
}
public double getRightPositionDelta(double time) {
if (travelDirection>0)
return privateGetRightPositionDelta(time);
else
return -privateGetLeftPositionDelta(time);
}
public double getRobotWidth() {
return m_robotWidth;
}
public void setRobotWidth(double robotWidth) {
m_robotWidth = robotWidth;
}
public double getPathLength() {
return m_xyCurve.getLength();
}
public double getDuration() {
return m_easeCurve.getLength();
}
public MotionCurve getEaseCurve() {
return m_easeCurve;
}
public double getTravelDirection() {
return travelDirection;
}
public void setTravelDirection(double travelDirection) {
this.travelDirection = travelDirection;
}
public boolean isMirrored() {
return m_mirrored;
}
public void setMirrored(boolean mirrored) {
this.m_mirrored = mirrored;
}
public void writeToNetworkTable() {
NetworkTable table = NetworkTable.getTable("PathVisualizer");
table.putString( name, toString() );
}
public void readFromNetworkTable() {
NetworkTable table = NetworkTable.getTable("PathVisualizer");
String pathString = table.getString( name, "" );
}
public String toString() {
String rValue = "";
for (Path2DPoint point = m_xyCurve.getHeadPoint(); point != null; point = point.getNextPoint()) {
rValue += point.toString();
}
return rValue;
}
public Path2DCurve getXYCurve() {
return m_xyCurve;
}
}
| Accessors for Path2D.
| src/main/java/org/team2471/frc/lib/motion_profiling/Path2D.java | Accessors for Path2D. |
|
Java | apache-2.0 | aa14498acf017333bedb760fa51c04809cc595b2 | 0 | FuadEfendi/ElasticsearchVaadinDemo,FuadEfendi/ElasticsearchVaadinDemo | /*
* Copyright 2016 Fuad Efendi <[email protected]>
*
* 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 ca.fe.examples.charts;
import com.vaadin.addon.charts.Chart;
import com.vaadin.addon.charts.model.AxisTitle;
import com.vaadin.addon.charts.model.ChartType;
import com.vaadin.addon.charts.model.Configuration;
import com.vaadin.addon.charts.model.DataSeries;
import com.vaadin.addon.charts.model.DataSeriesItem3d;
import com.vaadin.addon.charts.model.Labels;
import com.vaadin.addon.charts.model.Marker;
import com.vaadin.addon.charts.model.PlotOptionsBubble;
import com.vaadin.addon.charts.model.TickPosition;
import com.vaadin.addon.charts.model.XAxis;
import com.vaadin.addon.charts.model.YAxis;
import com.vaadin.addon.charts.model.style.GradientColor;
import com.vaadin.addon.charts.model.style.SolidColor;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.VerticalLayout;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by fefendi on 2016-08-11.
*/
public class BubbleChartExample extends AbstractChartExample {
private static final long serialVersionUID = 1L;
private static final transient Logger logger = LogManager.getLogger(BubbleChartExample.class);
String context;
public void init(String context) {
this.context = context;
setCompositionRoot(new com.vaadin.ui.Label("Uninitialized"));
}
@Override
public void attach() {
VerticalLayout layout = new VerticalLayout();
if ("bubble".equals(context))
bubblechart(layout);
else
setCompositionRoot(new com.vaadin.ui.Label("Invalid Context"));
setCompositionRoot(layout);
}
// BEGIN-EXAMPLE: charts.charttype.bubble
void bubblechart(VerticalLayout layout) {
// Create a bubble chart
Chart chart = new Chart(ChartType.BUBBLE);
chart.setWidth("640px");
chart.setHeight("350px");
Configuration conf = chart.getConfiguration();
conf.setTitle("Distribution of Users by Country");
conf.getLegend().setEnabled(false);
conf.getTooltip().setFormatter("this.point.name + ': ' + Math.round(this.point.z * this.point.z) + ' profiles'");
// World map as background
String url =
VaadinServlet.getCurrent().getServletContext().getContextPath() +
"/VAADIN/themes/elasticsearch-vaadin-demo/img/neocreo_Blue_World_Map_640x.png";
conf.getChart().setPlotBackgroundImage(url);
// Show more bubbly bubbles with spherical color gradient
PlotOptionsBubble plotOptions = new PlotOptionsBubble();
Marker marker = new Marker();
GradientColor color = GradientColor.createRadial(0.4, 0.3, 0.7);
color.addColorStop(0.0, new SolidColor(255, 255, 255, 0.5));
color.addColorStop(1.0, new SolidColor(170, 70, 67, 0.5));
marker.setFillColor(color);
plotOptions.setMarker(marker);
conf.setPlotOptions(plotOptions);
DataSeries series = new DataSeries("Countries");
List<Bucket> buckets = searchCountries();
for (Bucket bucket : buckets) {
String country = bucket.getKeyAsString();
long count = bucket.getDocCount();
Coordinate pos = getCountryCoordinates(country);
if (pos == null) {
logger.warn("country coordinates not found: {}", country);
continue;
}
DataSeriesItem3d item = new DataSeriesItem3d();
item.setX(pos.longitude * Math.cos(pos.latitude / 2.0 * (Math.PI / 160)));
item.setY(pos.latitude * 1.2);
item.setZ(Math.sqrt(count));
item.setName(country);
series.add(item);
}
conf.addSeries(series);
// Set the category labels on the axis correspondingly
XAxis xaxis = new XAxis();
xaxis.setTitle(new AxisTitle(null));
xaxis.setExtremes(-180, 180);
xaxis.setLabels(new Labels(false));
xaxis.setLineWidth(0);
xaxis.setLineColor(new SolidColor(0, 0, 0, 0.0)); // Invisible
conf.addxAxis(xaxis);
// Set the Y axis title
YAxis yaxis = new YAxis();
yaxis.setTitle("");
yaxis.setExtremes(-90, 90);
yaxis.setTickPosition(TickPosition.OUTSIDE);
yaxis.setTickLength(1);
yaxis.setTickInterval(100);
yaxis.setTickColor(new SolidColor(0, 0, 0, 0.5)); // Invisible
yaxis.setTickWidth(0);
yaxis.setLabels(new Labels(false));
yaxis.setLineWidth(0);
yaxis.setLineColor(new SolidColor(0, 0, 0, 0.0)); // Invisible
conf.addyAxis(yaxis);
layout.addComponent(chart);
}
private List<Bucket> searchCountries() {
AbstractAggregationBuilder aggregation = AggregationBuilders
.terms("countries")
.field("locations.country")
.minDocCount(1)
.size(0);
SearchResponse response = client
.prepareSearch()
.setIndices("avid3")
.setTypes("profile")
.setSize(0)
.addAggregation(aggregation)
.execute()
.actionGet();
Aggregations aggregations = response.getAggregations();
Terms terms = aggregations.get("countries");
return terms.getBuckets();
}
// END-EXAMPLE: charts.charttype.bubble
class Coordinate implements Serializable {
private static final long serialVersionUID = 1L;
public double longitude;
public double latitude;
public Coordinate(double lat, double lng) {
this.longitude = -lng;
this.latitude = lat;
}
}
static Map<String, Coordinate> countryCoordinates;
Coordinate getCountryCoordinates(String name) {
if (countryCoordinates == null)
countryCoordinates = createCountryCoordinates();
return countryCoordinates.get(name);
}
public Map<String, Coordinate> createCountryCoordinates() {
HashMap<String, Coordinate> coords = new HashMap<String, Coordinate>();
coords.put("Afghanistan", new Coordinate(33.00, -65.00));
coords.put("Akrotiri", new Coordinate(34.62, -32.97));
coords.put("Albania", new Coordinate(41.00, -20.00));
coords.put("Algeria", new Coordinate(28.00, -3.00));
coords.put("American Samoa", new Coordinate(-14.33, 170.00));
coords.put("Andorra", new Coordinate(42.50, -1.50));
coords.put("Angola", new Coordinate(-12.50, -18.50));
coords.put("Anguilla", new Coordinate(18.25, 63.17));
coords.put("Antarctica", new Coordinate(-90.00, -0.00));
coords.put("Antigua and Barbuda", new Coordinate(17.05, 61.80));
coords.put("Arctic Ocean", new Coordinate(90.00, -0.00));
coords.put("Argentina", new Coordinate(-34.00, 64.00));
coords.put("Armenia", new Coordinate(40.00, -45.00));
coords.put("Aruba", new Coordinate(12.50, 69.97));
coords.put("Ashmore and Cartier Islands", new Coordinate(-12.23, -123.08));
coords.put("Atlantic Ocean", new Coordinate(0.00, 25.00));
coords.put("Australia", new Coordinate(-27.00, -133.00));
coords.put("Austria", new Coordinate(47.33, -13.33));
coords.put("Österreich", new Coordinate(47.33, -13.33));
coords.put("Azerbaijan", new Coordinate(40.50, -47.50));
coords.put("Bahamas, The", new Coordinate(24.25, 76.00));
coords.put("Bahrain", new Coordinate(26.00, -50.55));
coords.put("Baker Island", new Coordinate(0.22, 176.47));
coords.put("Bangladesh", new Coordinate(24.00, -90.00));
coords.put("Barbados", new Coordinate(13.17, 59.53));
coords.put("Bassas da India", new Coordinate(-21.50, -39.83));
coords.put("Belarus", new Coordinate(53.00, -28.00));
coords.put("Беларусь", new Coordinate(53.00, -28.00));
coords.put("Belgium", new Coordinate(50.83, -4.00));
coords.put("Belgique", new Coordinate(50.83, -4.00));
coords.put("Belize", new Coordinate(17.25, 88.75));
coords.put("Benin", new Coordinate(9.50, -2.25));
coords.put("Bermuda", new Coordinate(32.33, 64.75));
coords.put("Bhutan", new Coordinate(27.50, -90.50));
coords.put("Bolivia", new Coordinate(-17.00, 65.00));
coords.put("Bosnia and Herzegovina", new Coordinate(44.00, -18.00));
coords.put("Botswana", new Coordinate(-22.00, -24.00));
coords.put("Bouvet Island", new Coordinate(-54.43, -3.40));
coords.put("Brazil", new Coordinate(-10.00, 55.00));
coords.put("Brasil", new Coordinate(-10.00, 55.00));
coords.put("British Virgin Islands", new Coordinate(18.50, 64.50));
coords.put("Brunei", new Coordinate(4.50, -114.67));
coords.put("Bulgaria", new Coordinate(43.00, -25.00));
coords.put("Burkina Faso", new Coordinate(13.00, 2.00));
coords.put("Burma", new Coordinate(22.00, -98.00));
coords.put("Burundi", new Coordinate(-3.50, -30.00));
coords.put("Cambodia", new Coordinate(13.00, -105.00));
coords.put("Cameroon", new Coordinate(6.00, -12.00));
coords.put("Canada", new Coordinate(60.00, 95.00));
coords.put("Cape Verde", new Coordinate(16.00, 24.00));
coords.put("Cayman Islands", new Coordinate(19.50, 80.50));
coords.put("Central African Republic", new Coordinate(7.00, -21.00));
coords.put("Chad", new Coordinate(15.00, -19.00));
coords.put("Chile", new Coordinate(-30.00, 71.00));
coords.put("China", new Coordinate(35.00, -105.00));
coords.put("中国", new Coordinate(35.00, -105.00));
coords.put("Christmas Island", new Coordinate(-10.50, -105.67));
coords.put("Clipperton Island", new Coordinate(10.28, 109.22));
coords.put("Cocos (Keeling) Islands", new Coordinate(-12.50, -96.83));
coords.put("Colombia", new Coordinate(4.00, 72.00));
coords.put("Comoros", new Coordinate(-12.17, -44.25));
coords.put("Congo, Democratic Republic of the", new Coordinate(0.00, -25.00));
coords.put("Congo, Republic of the", new Coordinate(-1.00, -15.00));
coords.put("Cook Islands", new Coordinate(-21.23, 159.77));
coords.put("Coral Sea Islands", new Coordinate(-18.00, -152.00));
coords.put("Costa Rica", new Coordinate(10.00, 84.00));
coords.put("Crimea", new Coordinate(49.00, -33.00)); //zzz
coords.put("Croatia", new Coordinate(45.17, -15.50));
coords.put("Cuba", new Coordinate(21.50, 80.00));
coords.put("Cyprus", new Coordinate(35.00, -33.00));
coords.put("Czech Republic", new Coordinate(49.75, -15.50));
coords.put("Česká republika", new Coordinate(49.75, -15.50));
coords.put("Côte d'Ivoire", new Coordinate(8.00, 5.00));
coords.put("Denmark", new Coordinate(56.00, -10.00));
coords.put("Danmark", new Coordinate(56.00, -10.00));
coords.put("Dhekelia", new Coordinate(34.98, -33.75));
coords.put("Djibouti", new Coordinate(11.50, -43.00));
coords.put("Dominica", new Coordinate(15.42, 61.33));
coords.put("Dominican Republic", new Coordinate(19.00, 70.67));
coords.put("East Timor", new Coordinate(-8.83, -125.92));
coords.put("Ecuador", new Coordinate(-2.00, 77.50));
coords.put("Egypt", new Coordinate(27.00, -30.00));
coords.put("El Salvador", new Coordinate(13.83, 88.92));
coords.put("Equatorial Guinea", new Coordinate(2.00, -10.00));
coords.put("Eritrea", new Coordinate(15.00, -39.00));
coords.put("Estonia", new Coordinate(59.00, -26.00));
coords.put("Ethiopia", new Coordinate(8.00, -38.00));
coords.put("Europa Island", new Coordinate(-22.33, -40.37));
coords.put("Falkland Islands (Islas Malvinas)", new Coordinate(-51.75, 59.00));
coords.put("Faroe Islands", new Coordinate(62.00, 7.00));
coords.put("Fiji", new Coordinate(-18.00, -175.00));
coords.put("Finland", new Coordinate(64.00, -26.00));
coords.put("Suomi", new Coordinate(64.00, -26.00));
coords.put("France", new Coordinate(46.00, -2.00));
coords.put("French Guiana", new Coordinate(4.00, 53.00));
coords.put("French Polynesia", new Coordinate(-15.00, 140.00));
coords.put("Gabon", new Coordinate(-1.00, -11.75));
coords.put("Gambia, The", new Coordinate(13.47, 16.57));
coords.put("Gaza Strip", new Coordinate(31.42, -34.33));
coords.put("Georgia", new Coordinate(42.00, -43.50));
coords.put("Germany", new Coordinate(51.00, -9.00));
coords.put("Deutschland", new Coordinate(51.00, -9.00));
coords.put("Ghana", new Coordinate(8.00, 2.00));
coords.put("Gibraltar", new Coordinate(36.13, 5.35));
coords.put("Glorioso Islands", new Coordinate(-11.50, -47.33));
coords.put("Greece", new Coordinate(39.00, -22.00));
coords.put("Ελλάδα", new Coordinate(39.00, -22.00));
coords.put("Greenland", new Coordinate(72.00, 40.00));
coords.put("Grenada", new Coordinate(12.12, 61.67));
coords.put("Guadeloupe", new Coordinate(16.25, 61.58));
coords.put("Guam", new Coordinate(13.47, -144.78));
coords.put("Guatemala", new Coordinate(15.50, 90.25));
coords.put("Guernsey", new Coordinate(49.47, 2.58));
coords.put("Guinea", new Coordinate(11.00, 10.00));
coords.put("Guinea-Bissau", new Coordinate(12.00, 15.00));
coords.put("Guyana", new Coordinate(5.00, 59.00));
coords.put("Haiti", new Coordinate(19.00, 72.42));
coords.put("Heard Island and McDonald Islands", new Coordinate(-53.10, -72.52));
coords.put("Holy See (Vatican City)", new Coordinate(41.90, -12.45));
coords.put("Honduras", new Coordinate(15.00, 86.50));
coords.put("Hong Kong", new Coordinate(22.25, -114.17));
coords.put("香港", new Coordinate(22.25, -114.17));
coords.put("Howland Island", new Coordinate(0.80, 176.63));
coords.put("Hungary", new Coordinate(47.00, -20.00));
coords.put("Magyarország", new Coordinate(47.00, -20.00));
coords.put("Iceland", new Coordinate(65.00, 18.00));
coords.put("India", new Coordinate(20.00, -77.00));
coords.put("Indian Ocean", new Coordinate(-20.00, -80.00));
coords.put("Indonesia", new Coordinate(-5.00, -120.00));
coords.put("Iran", new Coordinate(32.00, -53.00));
coords.put("Iraq", new Coordinate(33.00, -44.00));
coords.put("Ireland", new Coordinate(53.00, 8.00));
coords.put("Israel", new Coordinate(31.50, -34.75));
coords.put("ישראל", new Coordinate(31.50, -34.75));
coords.put("Italy", new Coordinate(42.83, -12.83));
coords.put("Italia", new Coordinate(42.83, -12.83));
coords.put("Jamaica", new Coordinate(18.25, 77.50));
coords.put("Jan Mayen", new Coordinate(71.00, 8.00));
coords.put("Japan", new Coordinate(36.00, -138.00));
coords.put("日本国", new Coordinate(36.00, -138.00));
coords.put("日本", new Coordinate(36.00, -138.00));
coords.put("Jarvis Island", new Coordinate(-0.38, 160.02));
coords.put("Jersey", new Coordinate(49.25, 2.17));
coords.put("Johnston Atoll", new Coordinate(16.75, 169.52));
coords.put("Jordan", new Coordinate(31.00, -36.00));
coords.put("Juan de Nova Island", new Coordinate(-17.05, -42.75));
coords.put("Kazakhstan", new Coordinate(48.00, -68.00));
coords.put("Казахстан", new Coordinate(48.00, -68.00));
coords.put("Kenya", new Coordinate(1.00, -38.00));
coords.put("Kingman Reef", new Coordinate(6.38, 162.42));
coords.put("Kiribati", new Coordinate(1.42, -173.00));
coords.put("Korea, North", new Coordinate(40.00, -127.00));
coords.put("Korea, South", new Coordinate(37.00, -127.50));
coords.put("한국", new Coordinate(37.00, -127.50));
coords.put("Kuwait", new Coordinate(29.50, -45.75));
coords.put("Kyrgyzstan", new Coordinate(41.00, -75.00));
coords.put("Laos", new Coordinate(18.00, -105.00));
coords.put("Latvia", new Coordinate(57.00, -25.00));
coords.put("Lebanon", new Coordinate(33.83, -35.83));
coords.put("Lesotho", new Coordinate(-29.50, -28.50));
coords.put("Liberia", new Coordinate(6.50, 9.50));
coords.put("Libya", new Coordinate(25.00, -17.00));
coords.put("Liechtenstein", new Coordinate(47.27, -9.53));
coords.put("Lithuania", new Coordinate(56.00, -24.00));
coords.put("Luxembourg", new Coordinate(49.75, -6.17));
coords.put("Macau", new Coordinate(22.17, -113.55));
coords.put("澳門", new Coordinate(22.17, -113.55));
coords.put("Macedonia, Republic of", new Coordinate(41.83, -22.00));
coords.put("Madagascar", new Coordinate(-20.00, -47.00));
coords.put("Malawi", new Coordinate(-13.50, -34.00));
coords.put("Malaysia", new Coordinate(2.50, -112.50));
coords.put("Maldives", new Coordinate(3.25, -73.00));
coords.put("Mali", new Coordinate(17.00, 4.00));
coords.put("Malta", new Coordinate(35.83, -14.58));
coords.put("Man, Isle of", new Coordinate(54.25, 4.50));
coords.put("Marshall Islands", new Coordinate(9.00, -168.00));
coords.put("Martinique", new Coordinate(14.67, 61.00));
coords.put("Mauritania", new Coordinate(20.00, 12.00));
coords.put("Mauritius", new Coordinate(-20.28, -57.55));
coords.put("Mayotte", new Coordinate(-12.83, -45.17));
coords.put("Mexico", new Coordinate(23.00, 102.00));
coords.put("México", new Coordinate(23.00, 102.00));
coords.put("Micronesia, Federated States of", new Coordinate(6.92, -158.25));
coords.put("Midway Islands", new Coordinate(28.20, 177.37));
coords.put("Moldova", new Coordinate(47.00, -29.00));
coords.put("Monaco", new Coordinate(43.73, -7.40));
coords.put("Mongolia", new Coordinate(46.00, -105.00));
coords.put("Montenegro", new Coordinate(42.50, -19.30));
coords.put("Montserrat", new Coordinate(16.75, 62.20));
coords.put("Morocco", new Coordinate(32.00, 5.00));
coords.put("Mozambique", new Coordinate(-18.25, -35.00));
coords.put("Namibia", new Coordinate(-22.00, -17.00));
coords.put("Nauru", new Coordinate(-0.53, -166.92));
coords.put("Navassa Island", new Coordinate(18.42, 75.03));
coords.put("Nepal", new Coordinate(28.00, -84.00));
coords.put("Netherlands", new Coordinate(52.50, -5.75));
coords.put("Nederland", new Coordinate(52.50, -5.75));
coords.put("Niederlande", new Coordinate(52.50, -5.85));
coords.put("Netherlands Antilles", new Coordinate(12.25, 68.75));
coords.put("New Caledonia", new Coordinate(-21.50, -165.50));
coords.put("New Zealand", new Coordinate(-41.00, -174.00));
coords.put("Nicaragua", new Coordinate(13.00, 85.00));
coords.put("Niger", new Coordinate(16.00, -8.00));
coords.put("Nigeria", new Coordinate(10.00, -8.00));
coords.put("Niue", new Coordinate(-19.03, 169.87));
coords.put("Norfolk Island", new Coordinate(-29.03, -167.95));
coords.put("Northern Mariana Islands", new Coordinate(15.20, -145.75));
coords.put("Norway", new Coordinate(62.00, -10.00));
coords.put("Norge", new Coordinate(62.00, -10.00));
coords.put("Oman", new Coordinate(21.00, -57.00));
coords.put("Pacific Ocean", new Coordinate(0.00, 160.00));
coords.put("Pakistan", new Coordinate(30.00, -70.00));
coords.put("Palau", new Coordinate(7.50, -134.50));
coords.put("Palmyra Atoll", new Coordinate(5.88, 162.08));
coords.put("Panama", new Coordinate(9.00, 80.00));
coords.put("Papua New Guinea", new Coordinate(-6.00, -147.00));
coords.put("Paracel Islands", new Coordinate(16.50, -112.00));
coords.put("Paraguay", new Coordinate(-23.00, 58.00));
coords.put("Peru", new Coordinate(-10.00, 76.00));
coords.put("Perú", new Coordinate(-10.00, 76.00));
coords.put("Philippines", new Coordinate(13.00, -122.00));
coords.put("Pilipinas", new Coordinate(13.00, -122.00));
coords.put("Pitcairn Islands", new Coordinate(-25.07, 130.10));
coords.put("Polska", new Coordinate(52.00, -20.00));
coords.put("Portugal", new Coordinate(39.50, 8.00));
coords.put("Puerto Rico", new Coordinate(18.25, 66.50));
coords.put("Qatar", new Coordinate(25.50, -51.25));
coords.put("Romania", new Coordinate(46.00, -25.00));
coords.put("Россия", new Coordinate(60.00, -100.00));
coords.put("Rwanda", new Coordinate(-2.00, -30.00));
coords.put("Réunion", new Coordinate(-21.10, -55.60));
coords.put("Saint Barthelemy", new Coordinate(18.50, 63.42));
coords.put("Saint Helena", new Coordinate(-15.93, 5.70));
coords.put("Saint Kitts and Nevis", new Coordinate(17.33, 62.75));
coords.put("Saint Lucia", new Coordinate(13.88, 60.97));
coords.put("Saint Martin", new Coordinate(18.08, 63.95));
coords.put("Saint Pierre and Miquelon", new Coordinate(46.83, 56.33));
coords.put("Saint Vincent and the Grenadines", new Coordinate(13.25, 61.20));
coords.put("Samoa", new Coordinate(-13.58, 172.33));
coords.put("San Marino", new Coordinate(43.77, -12.42));
coords.put("Saudi Arabia", new Coordinate(25.00, -45.00));
coords.put("Senegal", new Coordinate(14.00, 14.00));
coords.put("Serbia and Montenegro", new Coordinate(44.00, -21.00));
coords.put("Seychelles", new Coordinate(-4.58, -55.67));
coords.put("Sierra Leone", new Coordinate(8.50, 11.50));
coords.put("Singapore", new Coordinate(1.37, -103.80));
coords.put("新加坡", new Coordinate(1.37, -103.80));
coords.put("Slovakia", new Coordinate(48.67, -19.50));
coords.put("Slovenia", new Coordinate(46.12, -14.82));
coords.put("Solomon Islands", new Coordinate(-8.00, -159.00));
coords.put("Somalia", new Coordinate(10.00, -49.00));
coords.put("South Africa", new Coordinate(-29.00, -24.00));
coords.put("South Georgia and the South Sandwich Islands", new Coordinate(-54.50, 37.00));
coords.put("Spain", new Coordinate(40.00, 4.00));
coords.put("España", new Coordinate(40.00, 4.00));
coords.put("Spratly Islands", new Coordinate(8.63, -111.92));
coords.put("Sri Lanka", new Coordinate(7.00, -81.00));
coords.put("Sudan", new Coordinate(15.00, -30.00));
coords.put("Suriname", new Coordinate(4.00, 56.00));
coords.put("Svalbard", new Coordinate(78.00, -20.00));
coords.put("Swaziland", new Coordinate(-26.50, -31.50));
coords.put("Sweden", new Coordinate(62.00, -15.00));
coords.put("Sverige", new Coordinate(62.00, -15.00));
coords.put("Switzerland", new Coordinate(47.00, -8.00));
coords.put("Schweiz", new Coordinate(47.00, -8.00));
coords.put("Syria", new Coordinate(35.00, -38.00));
coords.put("São Tomé and Príncipe", new Coordinate(1.00, -7.00));
coords.put("Taiwan", new Coordinate(23.50, -121.00));
coords.put("台灣", new Coordinate(23.50, -121.00));
coords.put("Tajikistan", new Coordinate(39.00, -71.00));
coords.put("Tanzania", new Coordinate(-6.00, -35.00));
coords.put("Thailand", new Coordinate(15.00, -100.00));
coords.put("ประเทศไทย", new Coordinate(15.00, -100.00));
coords.put("Togo", new Coordinate(8.00, -1.17));
coords.put("Tokelau", new Coordinate(-9.00, 172.00));
coords.put("Tonga", new Coordinate(-20.00, 175.00));
coords.put("Trinidad and Tobago", new Coordinate(11.00, 61.00));
coords.put("Tromelin Island", new Coordinate(-15.87, -54.42));
coords.put("Tunisia", new Coordinate(34.00, -9.00));
coords.put("Turkey", new Coordinate(39.00, -35.00));
coords.put("Türkiye", new Coordinate(39.00, -35.00));
coords.put("Turkmenistan", new Coordinate(40.00, -60.00));
coords.put("Turks and Caicos Islands", new Coordinate(21.75, 71.58));
coords.put("Tuvalu", new Coordinate(-8.00, -178.00));
coords.put("Uganda", new Coordinate(1.00, -32.00));
coords.put("Ukraine", new Coordinate(49.00, -32.00));
coords.put("Україна", new Coordinate(49.00, -32.00));
coords.put("United Arab Emirates", new Coordinate(24.00, -54.00));
coords.put("United Kingdom", new Coordinate(54.00, 2.00));
coords.put("United States", new Coordinate(38.00, 97.00));
coords.put("Uruguay", new Coordinate(-33.00, 56.00));
coords.put("Uzbekistan", new Coordinate(41.00, -64.00));
coords.put("Vanuatu", new Coordinate(-16.00, -167.00));
coords.put("Venezuela", new Coordinate(8.00, 66.00));
coords.put("Vietnam", new Coordinate(16.00, -106.00));
coords.put("Virgin Islands", new Coordinate(18.33, 64.83));
coords.put("Wake Island", new Coordinate(19.28, -166.65));
coords.put("Wallis and Futuna", new Coordinate(-13.30, 176.20));
coords.put("West Bank", new Coordinate(32.00, -35.25));
coords.put("Western Sahara", new Coordinate(24.50, 13.00));
coords.put("Yemen", new Coordinate(15.00, -48.00));
coords.put("Zambia", new Coordinate(-15.00, -30.00));
coords.put("Zimbabwe", new Coordinate(-20.00, -30.00));
coords.put("", new Coordinate(-75.00, -50.00));
coords.put("CA", new Coordinate(-75.00, -60.00));
return coords;
}
}
| src/main/java/ca/fe/examples/charts/BubbleChartExample.java | /*
* Copyright 2016 Fuad Efendi <[email protected]>
*
* 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 ca.fe.examples.charts;
import com.vaadin.addon.charts.Chart;
import com.vaadin.addon.charts.model.AxisTitle;
import com.vaadin.addon.charts.model.ChartType;
import com.vaadin.addon.charts.model.Configuration;
import com.vaadin.addon.charts.model.DataSeries;
import com.vaadin.addon.charts.model.DataSeriesItem3d;
import com.vaadin.addon.charts.model.Labels;
import com.vaadin.addon.charts.model.Marker;
import com.vaadin.addon.charts.model.PlotOptionsBubble;
import com.vaadin.addon.charts.model.TickPosition;
import com.vaadin.addon.charts.model.XAxis;
import com.vaadin.addon.charts.model.YAxis;
import com.vaadin.addon.charts.model.style.GradientColor;
import com.vaadin.addon.charts.model.style.SolidColor;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.VerticalLayout;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by fefendi on 2016-08-11.
*/
public class BubbleChartExample extends AbstractChartExample {
private static final long serialVersionUID = 1L;
private static final transient Logger logger = LogManager.getLogger(BubbleChartExample.class);
String context;
public void init(String context) {
this.context = context;
setCompositionRoot(new com.vaadin.ui.Label("Uninitialized"));
}
@Override
public void attach() {
VerticalLayout layout = new VerticalLayout();
if ("bubble".equals(context))
bubblechart(layout);
else
setCompositionRoot(new com.vaadin.ui.Label("Invalid Context"));
setCompositionRoot(layout);
}
// BEGIN-EXAMPLE: charts.charttype.bubble
void bubblechart(VerticalLayout layout) {
// Create a bubble chart
Chart chart = new Chart(ChartType.BUBBLE);
chart.setWidth("640px");
chart.setHeight("350px");
Configuration conf = chart.getConfiguration();
conf.setTitle("Distribution of Users by Country");
conf.getLegend().setEnabled(false); // Disable legend
conf.getTooltip().setFormatter("this.point.name + ': ' + " +
"Math.round(this.point.z * 100000) + " +
"' profiles'");
// World map as background
String url =
VaadinServlet.getCurrent().getServletContext().getContextPath() +
"/VAADIN/themes/elasticsearch-vaadin-demo/img/neocreo_Blue_World_Map_640x.png";
conf.getChart().setPlotBackgroundImage(url);
// Show more bubbly bubbles with spherical color gradient
PlotOptionsBubble plotOptions = new PlotOptionsBubble();
Marker marker = new Marker();
GradientColor color = GradientColor.createRadial(0.4, 0.3, 0.7);
color.addColorStop(0.0, new SolidColor(255, 255, 255, 0.5));
color.addColorStop(1.0, new SolidColor(170, 70, 67, 0.5));
marker.setFillColor(color);
plotOptions.setMarker(marker);
conf.setPlotOptions(plotOptions);
DataSeries series = new DataSeries("Countries");
List<Bucket> buckets = searchCountries();
List<Object[]> dataset = new ArrayList<>();
for (Bucket bucket : buckets) {
String country = bucket.getKeyAsString();
long count = bucket.getDocCount();
Coordinate pos = getCountryCoordinates(country);
if (pos == null) logger.warn("country coordinates not found: {}", country);
else dataset.add(new Object[]{country, count});
}
for (Object[] country : dataset) {
String name = (String) country[0];
long amount = (long) country[1];
Coordinate pos = getCountryCoordinates(name);
DataSeriesItem3d item = new DataSeriesItem3d();
item.setX(pos.longitude * Math.cos(pos.latitude / 2.0 * (Math.PI / 160)));
item.setY(pos.latitude * 1.2);
item.setZ(((double) amount) / 100000);
item.setName(name);
series.add(item);
}
conf.addSeries(series);
// Set the category labels on the axis correspondingly
XAxis xaxis = new XAxis();
xaxis.setTitle(new AxisTitle(null));
xaxis.setExtremes(-180, 180);
xaxis.setLabels(new Labels(false));
xaxis.setLineWidth(0);
xaxis.setLineColor(new SolidColor(0, 0, 0, 0.0)); // Invisible
conf.addxAxis(xaxis);
// Set the Y axis title
YAxis yaxis = new YAxis();
yaxis.setTitle("");
yaxis.setExtremes(-90, 90);
yaxis.setTickPosition(TickPosition.OUTSIDE);
yaxis.setTickLength(1);
yaxis.setTickInterval(100);
yaxis.setTickColor(new SolidColor(0, 0, 0, 0.5)); // Invisible
yaxis.setTickWidth(0);
yaxis.setLabels(new Labels(false));
yaxis.setLineWidth(0);
yaxis.setLineColor(new SolidColor(0, 0, 0, 0.0)); // Invisible
conf.addyAxis(yaxis);
layout.addComponent(chart);
}
private List<Bucket> searchCountries() {
AbstractAggregationBuilder aggregation = AggregationBuilders
.terms("countries")
.field("locations.country")
.minDocCount(1)
.size(0);
SearchResponse response = client
.prepareSearch()
.setIndices("avid3")
.setTypes("profile")
.setSize(0)
.addAggregation(aggregation)
.execute()
.actionGet();
Aggregations aggregations = response.getAggregations();
Terms terms = aggregations.get("countries");
return terms.getBuckets();
}
// END-EXAMPLE: charts.charttype.bubble
class Coordinate implements Serializable {
private static final long serialVersionUID = 1L;
public double longitude;
public double latitude;
public Coordinate(double lat, double lng) {
this.longitude = -lng;
this.latitude = lat;
}
}
static Map<String, Coordinate> countryCoordinates;
Coordinate getCountryCoordinates(String name) {
if (countryCoordinates == null)
countryCoordinates = createCountryCoordinates();
return countryCoordinates.get(name);
}
public Map<String, Coordinate> createCountryCoordinates() {
HashMap<String, Coordinate> coords = new HashMap<String, Coordinate>();
coords.put("Afghanistan", new Coordinate(33.00, -65.00));
coords.put("Akrotiri", new Coordinate(34.62, -32.97));
coords.put("Albania", new Coordinate(41.00, -20.00));
coords.put("Algeria", new Coordinate(28.00, -3.00));
coords.put("American Samoa", new Coordinate(-14.33, 170.00));
coords.put("Andorra", new Coordinate(42.50, -1.50));
coords.put("Angola", new Coordinate(-12.50, -18.50));
coords.put("Anguilla", new Coordinate(18.25, 63.17));
coords.put("Antarctica", new Coordinate(-90.00, -0.00));
coords.put("Antigua and Barbuda", new Coordinate(17.05, 61.80));
coords.put("Arctic Ocean", new Coordinate(90.00, -0.00));
coords.put("Argentina", new Coordinate(-34.00, 64.00));
coords.put("Armenia", new Coordinate(40.00, -45.00));
coords.put("Aruba", new Coordinate(12.50, 69.97));
coords.put("Ashmore and Cartier Islands", new Coordinate(-12.23, -123.08));
coords.put("Atlantic Ocean", new Coordinate(0.00, 25.00));
coords.put("Australia", new Coordinate(-27.00, -133.00));
coords.put("Austria", new Coordinate(47.33, -13.33));
coords.put("Österreich", new Coordinate(47.33, -13.33));
coords.put("Azerbaijan", new Coordinate(40.50, -47.50));
coords.put("Bahamas, The", new Coordinate(24.25, 76.00));
coords.put("Bahrain", new Coordinate(26.00, -50.55));
coords.put("Baker Island", new Coordinate(0.22, 176.47));
coords.put("Bangladesh", new Coordinate(24.00, -90.00));
coords.put("Barbados", new Coordinate(13.17, 59.53));
coords.put("Bassas da India", new Coordinate(-21.50, -39.83));
coords.put("Belarus", new Coordinate(53.00, -28.00));
coords.put("Беларусь", new Coordinate(53.00, -28.00));
coords.put("Belgium", new Coordinate(50.83, -4.00));
coords.put("Belgique", new Coordinate(50.83, -4.00));
coords.put("Belize", new Coordinate(17.25, 88.75));
coords.put("Benin", new Coordinate(9.50, -2.25));
coords.put("Bermuda", new Coordinate(32.33, 64.75));
coords.put("Bhutan", new Coordinate(27.50, -90.50));
coords.put("Bolivia", new Coordinate(-17.00, 65.00));
coords.put("Bosnia and Herzegovina", new Coordinate(44.00, -18.00));
coords.put("Botswana", new Coordinate(-22.00, -24.00));
coords.put("Bouvet Island", new Coordinate(-54.43, -3.40));
coords.put("Brazil", new Coordinate(-10.00, 55.00));
coords.put("Brasil", new Coordinate(-10.00, 55.00));
coords.put("British Virgin Islands", new Coordinate(18.50, 64.50));
coords.put("Brunei", new Coordinate(4.50, -114.67));
coords.put("Bulgaria", new Coordinate(43.00, -25.00));
coords.put("Burkina Faso", new Coordinate(13.00, 2.00));
coords.put("Burma", new Coordinate(22.00, -98.00));
coords.put("Burundi", new Coordinate(-3.50, -30.00));
coords.put("Cambodia", new Coordinate(13.00, -105.00));
coords.put("Cameroon", new Coordinate(6.00, -12.00));
coords.put("Canada", new Coordinate(60.00, 95.00));
coords.put("Cape Verde", new Coordinate(16.00, 24.00));
coords.put("Cayman Islands", new Coordinate(19.50, 80.50));
coords.put("Central African Republic", new Coordinate(7.00, -21.00));
coords.put("Chad", new Coordinate(15.00, -19.00));
coords.put("Chile", new Coordinate(-30.00, 71.00));
coords.put("China", new Coordinate(35.00, -105.00));
coords.put("中国", new Coordinate(35.00, -105.00));
coords.put("Christmas Island", new Coordinate(-10.50, -105.67));
coords.put("Clipperton Island", new Coordinate(10.28, 109.22));
coords.put("Cocos (Keeling) Islands", new Coordinate(-12.50, -96.83));
coords.put("Colombia", new Coordinate(4.00, 72.00));
coords.put("Comoros", new Coordinate(-12.17, -44.25));
coords.put("Congo, Democratic Republic of the", new Coordinate(0.00, -25.00));
coords.put("Congo, Republic of the", new Coordinate(-1.00, -15.00));
coords.put("Cook Islands", new Coordinate(-21.23, 159.77));
coords.put("Coral Sea Islands", new Coordinate(-18.00, -152.00));
coords.put("Costa Rica", new Coordinate(10.00, 84.00));
coords.put("Crimea", new Coordinate(49.00, -33.00)); //zzz
coords.put("Croatia", new Coordinate(45.17, -15.50));
coords.put("Cuba", new Coordinate(21.50, 80.00));
coords.put("Cyprus", new Coordinate(35.00, -33.00));
coords.put("Czech Republic", new Coordinate(49.75, -15.50));
coords.put("Česká republika", new Coordinate(49.75, -15.50));
coords.put("Côte d'Ivoire", new Coordinate(8.00, 5.00));
coords.put("Denmark", new Coordinate(56.00, -10.00));
coords.put("Danmark", new Coordinate(56.00, -10.00));
coords.put("Dhekelia", new Coordinate(34.98, -33.75));
coords.put("Djibouti", new Coordinate(11.50, -43.00));
coords.put("Dominica", new Coordinate(15.42, 61.33));
coords.put("Dominican Republic", new Coordinate(19.00, 70.67));
coords.put("East Timor", new Coordinate(-8.83, -125.92));
coords.put("Ecuador", new Coordinate(-2.00, 77.50));
coords.put("Egypt", new Coordinate(27.00, -30.00));
coords.put("El Salvador", new Coordinate(13.83, 88.92));
coords.put("Equatorial Guinea", new Coordinate(2.00, -10.00));
coords.put("Eritrea", new Coordinate(15.00, -39.00));
coords.put("Estonia", new Coordinate(59.00, -26.00));
coords.put("Ethiopia", new Coordinate(8.00, -38.00));
coords.put("Europa Island", new Coordinate(-22.33, -40.37));
coords.put("Falkland Islands (Islas Malvinas)", new Coordinate(-51.75, 59.00));
coords.put("Faroe Islands", new Coordinate(62.00, 7.00));
coords.put("Fiji", new Coordinate(-18.00, -175.00));
coords.put("Finland", new Coordinate(64.00, -26.00));
coords.put("Suomi", new Coordinate(64.00, -26.00));
coords.put("France", new Coordinate(46.00, -2.00));
coords.put("French Guiana", new Coordinate(4.00, 53.00));
coords.put("French Polynesia", new Coordinate(-15.00, 140.00));
coords.put("Gabon", new Coordinate(-1.00, -11.75));
coords.put("Gambia, The", new Coordinate(13.47, 16.57));
coords.put("Gaza Strip", new Coordinate(31.42, -34.33));
coords.put("Georgia", new Coordinate(42.00, -43.50));
coords.put("Germany", new Coordinate(51.00, -9.00));
coords.put("Deutschland", new Coordinate(51.00, -9.00));
coords.put("Ghana", new Coordinate(8.00, 2.00));
coords.put("Gibraltar", new Coordinate(36.13, 5.35));
coords.put("Glorioso Islands", new Coordinate(-11.50, -47.33));
coords.put("Greece", new Coordinate(39.00, -22.00));
coords.put("Ελλάδα", new Coordinate(39.00, -22.00));
coords.put("Greenland", new Coordinate(72.00, 40.00));
coords.put("Grenada", new Coordinate(12.12, 61.67));
coords.put("Guadeloupe", new Coordinate(16.25, 61.58));
coords.put("Guam", new Coordinate(13.47, -144.78));
coords.put("Guatemala", new Coordinate(15.50, 90.25));
coords.put("Guernsey", new Coordinate(49.47, 2.58));
coords.put("Guinea", new Coordinate(11.00, 10.00));
coords.put("Guinea-Bissau", new Coordinate(12.00, 15.00));
coords.put("Guyana", new Coordinate(5.00, 59.00));
coords.put("Haiti", new Coordinate(19.00, 72.42));
coords.put("Heard Island and McDonald Islands", new Coordinate(-53.10, -72.52));
coords.put("Holy See (Vatican City)", new Coordinate(41.90, -12.45));
coords.put("Honduras", new Coordinate(15.00, 86.50));
coords.put("Hong Kong", new Coordinate(22.25, -114.17));
coords.put("香港", new Coordinate(22.25, -114.17));
coords.put("Howland Island", new Coordinate(0.80, 176.63));
coords.put("Hungary", new Coordinate(47.00, -20.00));
coords.put("Magyarország", new Coordinate(47.00, -20.00));
coords.put("Iceland", new Coordinate(65.00, 18.00));
coords.put("India", new Coordinate(20.00, -77.00));
coords.put("Indian Ocean", new Coordinate(-20.00, -80.00));
coords.put("Indonesia", new Coordinate(-5.00, -120.00));
coords.put("Iran", new Coordinate(32.00, -53.00));
coords.put("Iraq", new Coordinate(33.00, -44.00));
coords.put("Ireland", new Coordinate(53.00, 8.00));
coords.put("Israel", new Coordinate(31.50, -34.75));
coords.put("ישראל", new Coordinate(31.50, -34.75));
coords.put("Italy", new Coordinate(42.83, -12.83));
coords.put("Italia", new Coordinate(42.83, -12.83));
coords.put("Jamaica", new Coordinate(18.25, 77.50));
coords.put("Jan Mayen", new Coordinate(71.00, 8.00));
coords.put("Japan", new Coordinate(36.00, -138.00));
coords.put("日本国", new Coordinate(36.00, -138.00));
coords.put("日本", new Coordinate(36.00, -138.00));
coords.put("Jarvis Island", new Coordinate(-0.38, 160.02));
coords.put("Jersey", new Coordinate(49.25, 2.17));
coords.put("Johnston Atoll", new Coordinate(16.75, 169.52));
coords.put("Jordan", new Coordinate(31.00, -36.00));
coords.put("Juan de Nova Island", new Coordinate(-17.05, -42.75));
coords.put("Kazakhstan", new Coordinate(48.00, -68.00));
coords.put("Казахстан", new Coordinate(48.00, -68.00));
coords.put("Kenya", new Coordinate(1.00, -38.00));
coords.put("Kingman Reef", new Coordinate(6.38, 162.42));
coords.put("Kiribati", new Coordinate(1.42, -173.00));
coords.put("Korea, North", new Coordinate(40.00, -127.00));
coords.put("Korea, South", new Coordinate(37.00, -127.50));
coords.put("한국", new Coordinate(37.00, -127.50));
coords.put("Kuwait", new Coordinate(29.50, -45.75));
coords.put("Kyrgyzstan", new Coordinate(41.00, -75.00));
coords.put("Laos", new Coordinate(18.00, -105.00));
coords.put("Latvia", new Coordinate(57.00, -25.00));
coords.put("Lebanon", new Coordinate(33.83, -35.83));
coords.put("Lesotho", new Coordinate(-29.50, -28.50));
coords.put("Liberia", new Coordinate(6.50, 9.50));
coords.put("Libya", new Coordinate(25.00, -17.00));
coords.put("Liechtenstein", new Coordinate(47.27, -9.53));
coords.put("Lithuania", new Coordinate(56.00, -24.00));
coords.put("Luxembourg", new Coordinate(49.75, -6.17));
coords.put("Macau", new Coordinate(22.17, -113.55));
coords.put("澳門", new Coordinate(22.17, -113.55));
coords.put("Macedonia, Republic of", new Coordinate(41.83, -22.00));
coords.put("Madagascar", new Coordinate(-20.00, -47.00));
coords.put("Malawi", new Coordinate(-13.50, -34.00));
coords.put("Malaysia", new Coordinate(2.50, -112.50));
coords.put("Maldives", new Coordinate(3.25, -73.00));
coords.put("Mali", new Coordinate(17.00, 4.00));
coords.put("Malta", new Coordinate(35.83, -14.58));
coords.put("Man, Isle of", new Coordinate(54.25, 4.50));
coords.put("Marshall Islands", new Coordinate(9.00, -168.00));
coords.put("Martinique", new Coordinate(14.67, 61.00));
coords.put("Mauritania", new Coordinate(20.00, 12.00));
coords.put("Mauritius", new Coordinate(-20.28, -57.55));
coords.put("Mayotte", new Coordinate(-12.83, -45.17));
coords.put("Mexico", new Coordinate(23.00, 102.00));
coords.put("México", new Coordinate(23.00, 102.00));
coords.put("Micronesia, Federated States of", new Coordinate(6.92, -158.25));
coords.put("Midway Islands", new Coordinate(28.20, 177.37));
coords.put("Moldova", new Coordinate(47.00, -29.00));
coords.put("Monaco", new Coordinate(43.73, -7.40));
coords.put("Mongolia", new Coordinate(46.00, -105.00));
coords.put("Montenegro", new Coordinate(42.50, -19.30));
coords.put("Montserrat", new Coordinate(16.75, 62.20));
coords.put("Morocco", new Coordinate(32.00, 5.00));
coords.put("Mozambique", new Coordinate(-18.25, -35.00));
coords.put("Namibia", new Coordinate(-22.00, -17.00));
coords.put("Nauru", new Coordinate(-0.53, -166.92));
coords.put("Navassa Island", new Coordinate(18.42, 75.03));
coords.put("Nepal", new Coordinate(28.00, -84.00));
coords.put("Netherlands", new Coordinate(52.50, -5.75));
coords.put("Nederland", new Coordinate(52.50, -5.75));
coords.put("Niederlande", new Coordinate(52.50, -5.85));
coords.put("Netherlands Antilles", new Coordinate(12.25, 68.75));
coords.put("New Caledonia", new Coordinate(-21.50, -165.50));
coords.put("New Zealand", new Coordinate(-41.00, -174.00));
coords.put("Nicaragua", new Coordinate(13.00, 85.00));
coords.put("Niger", new Coordinate(16.00, -8.00));
coords.put("Nigeria", new Coordinate(10.00, -8.00));
coords.put("Niue", new Coordinate(-19.03, 169.87));
coords.put("Norfolk Island", new Coordinate(-29.03, -167.95));
coords.put("Northern Mariana Islands", new Coordinate(15.20, -145.75));
coords.put("Norway", new Coordinate(62.00, -10.00));
coords.put("Norge", new Coordinate(62.00, -10.00));
coords.put("Oman", new Coordinate(21.00, -57.00));
coords.put("Pacific Ocean", new Coordinate(0.00, 160.00));
coords.put("Pakistan", new Coordinate(30.00, -70.00));
coords.put("Palau", new Coordinate(7.50, -134.50));
coords.put("Palmyra Atoll", new Coordinate(5.88, 162.08));
coords.put("Panama", new Coordinate(9.00, 80.00));
coords.put("Papua New Guinea", new Coordinate(-6.00, -147.00));
coords.put("Paracel Islands", new Coordinate(16.50, -112.00));
coords.put("Paraguay", new Coordinate(-23.00, 58.00));
coords.put("Peru", new Coordinate(-10.00, 76.00));
coords.put("Perú", new Coordinate(-10.00, 76.00));
coords.put("Philippines", new Coordinate(13.00, -122.00));
coords.put("Pilipinas", new Coordinate(13.00, -122.00));
coords.put("Pitcairn Islands", new Coordinate(-25.07, 130.10));
coords.put("Polska", new Coordinate(52.00, -20.00));
coords.put("Portugal", new Coordinate(39.50, 8.00));
coords.put("Puerto Rico", new Coordinate(18.25, 66.50));
coords.put("Qatar", new Coordinate(25.50, -51.25));
coords.put("Romania", new Coordinate(46.00, -25.00));
coords.put("Россия", new Coordinate(60.00, -100.00));
coords.put("Rwanda", new Coordinate(-2.00, -30.00));
coords.put("Réunion", new Coordinate(-21.10, -55.60));
coords.put("Saint Barthelemy", new Coordinate(18.50, 63.42));
coords.put("Saint Helena", new Coordinate(-15.93, 5.70));
coords.put("Saint Kitts and Nevis", new Coordinate(17.33, 62.75));
coords.put("Saint Lucia", new Coordinate(13.88, 60.97));
coords.put("Saint Martin", new Coordinate(18.08, 63.95));
coords.put("Saint Pierre and Miquelon", new Coordinate(46.83, 56.33));
coords.put("Saint Vincent and the Grenadines", new Coordinate(13.25, 61.20));
coords.put("Samoa", new Coordinate(-13.58, 172.33));
coords.put("San Marino", new Coordinate(43.77, -12.42));
coords.put("Saudi Arabia", new Coordinate(25.00, -45.00));
coords.put("Senegal", new Coordinate(14.00, 14.00));
coords.put("Serbia and Montenegro", new Coordinate(44.00, -21.00));
coords.put("Seychelles", new Coordinate(-4.58, -55.67));
coords.put("Sierra Leone", new Coordinate(8.50, 11.50));
coords.put("Singapore", new Coordinate(1.37, -103.80));
coords.put("新加坡", new Coordinate(1.37, -103.80));
coords.put("Slovakia", new Coordinate(48.67, -19.50));
coords.put("Slovenia", new Coordinate(46.12, -14.82));
coords.put("Solomon Islands", new Coordinate(-8.00, -159.00));
coords.put("Somalia", new Coordinate(10.00, -49.00));
coords.put("South Africa", new Coordinate(-29.00, -24.00));
coords.put("South Georgia and the South Sandwich Islands", new Coordinate(-54.50, 37.00));
coords.put("Spain", new Coordinate(40.00, 4.00));
coords.put("España", new Coordinate(40.00, 4.00));
coords.put("Spratly Islands", new Coordinate(8.63, -111.92));
coords.put("Sri Lanka", new Coordinate(7.00, -81.00));
coords.put("Sudan", new Coordinate(15.00, -30.00));
coords.put("Suriname", new Coordinate(4.00, 56.00));
coords.put("Svalbard", new Coordinate(78.00, -20.00));
coords.put("Swaziland", new Coordinate(-26.50, -31.50));
coords.put("Sweden", new Coordinate(62.00, -15.00));
coords.put("Sverige", new Coordinate(62.00, -15.00));
coords.put("Switzerland", new Coordinate(47.00, -8.00));
coords.put("Schweiz", new Coordinate(47.00, -8.00));
coords.put("Syria", new Coordinate(35.00, -38.00));
coords.put("São Tomé and Príncipe", new Coordinate(1.00, -7.00));
coords.put("Taiwan", new Coordinate(23.50, -121.00));
coords.put("台灣", new Coordinate(23.50, -121.00));
coords.put("Tajikistan", new Coordinate(39.00, -71.00));
coords.put("Tanzania", new Coordinate(-6.00, -35.00));
coords.put("Thailand", new Coordinate(15.00, -100.00));
coords.put("ประเทศไทย", new Coordinate(15.00, -100.00));
coords.put("Togo", new Coordinate(8.00, -1.17));
coords.put("Tokelau", new Coordinate(-9.00, 172.00));
coords.put("Tonga", new Coordinate(-20.00, 175.00));
coords.put("Trinidad and Tobago", new Coordinate(11.00, 61.00));
coords.put("Tromelin Island", new Coordinate(-15.87, -54.42));
coords.put("Tunisia", new Coordinate(34.00, -9.00));
coords.put("Turkey", new Coordinate(39.00, -35.00));
coords.put("Türkiye", new Coordinate(39.00, -35.00));
coords.put("Turkmenistan", new Coordinate(40.00, -60.00));
coords.put("Turks and Caicos Islands", new Coordinate(21.75, 71.58));
coords.put("Tuvalu", new Coordinate(-8.00, -178.00));
coords.put("Uganda", new Coordinate(1.00, -32.00));
coords.put("Ukraine", new Coordinate(49.00, -32.00));
coords.put("Україна", new Coordinate(49.00, -32.00));
coords.put("United Arab Emirates", new Coordinate(24.00, -54.00));
coords.put("United Kingdom", new Coordinate(54.00, 2.00));
coords.put("United States", new Coordinate(38.00, 97.00));
coords.put("Uruguay", new Coordinate(-33.00, 56.00));
coords.put("Uzbekistan", new Coordinate(41.00, -64.00));
coords.put("Vanuatu", new Coordinate(-16.00, -167.00));
coords.put("Venezuela", new Coordinate(8.00, 66.00));
coords.put("Vietnam", new Coordinate(16.00, -106.00));
coords.put("Virgin Islands", new Coordinate(18.33, 64.83));
coords.put("Wake Island", new Coordinate(19.28, -166.65));
coords.put("Wallis and Futuna", new Coordinate(-13.30, 176.20));
coords.put("West Bank", new Coordinate(32.00, -35.25));
coords.put("Western Sahara", new Coordinate(24.50, 13.00));
coords.put("Yemen", new Coordinate(15.00, -48.00));
coords.put("Zambia", new Coordinate(-15.00, -30.00));
coords.put("Zimbabwe", new Coordinate(-20.00, -30.00));
coords.put("", new Coordinate(-75.00, -50.00));
coords.put("CA", new Coordinate(-75.00, -60.00));
return coords;
}
}
| trivial improvement
| src/main/java/ca/fe/examples/charts/BubbleChartExample.java | trivial improvement |
|
Java | apache-2.0 | 94aab22e98ba2fb9e9dd8fe0fb9111a444ba2496 | 0 | archiecobbs/jsimpledb,tempbottle/jsimpledb,permazen/permazen,permazen/permazen,archiecobbs/jsimpledb,permazen/permazen,archiecobbs/jsimpledb,tempbottle/jsimpledb,tempbottle/jsimpledb |
/*
* Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.schema;
import java.util.List;
/**
* Spring-enabled {@link SchemaUpdate} supporting updates via SQL statements.
*
* <p>
* Instances can be created succintly using the <code><dellroad-stuff:sql-update></code> custom XML element, which works
* just like <code><dellroad-stuff:sql></code> except that it wraps the resulting {@link SQLDatabaseAction}
* as a delegate inside an instance of this class.
*
* <p>
* For example:
* <blockquote><pre>
* <beans xmlns="http://www.springframework.org/schema/beans"
* <b>xmlns:dellroad-stuff="http://dellroad-stuff.googlecode.com/schema/dellroad-stuff"</b>
* xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
* xsi:schemaLocation="
* http://www.springframework.org/schema/beans
* http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
* <b>http://dellroad-stuff.googlecode.com/schema/dellroad-stuff
* http://dellroad-stuff.googlecode.com/svn/wiki/schemas/dellroad-stuff-1.0.xsd</b>">
*
* <!-- Schema update to add the 'phone' column to the 'User' table -->
* <b><dellroad-stuff:sql-update id="addPhone">ALTER TABLE User ADD phone VARCHAR(64)</dellroad-stuff:sql-update></b>
*
* <!-- Schema update to run some complicated external SQL script -->
* <b><dellroad-stuff:sql-update id="majorChanges" depends-on="addPhone" resource="classpath:majorChanges.sql"/></b>
*
* <!-- more beans... -->
*
* </beans>
* </pre></blockquote>
* </p>
*
* <p>
* A multi-statement SQL script is normally treated as a set of individual updates. For example:
* <blockquote><pre>
* <b><dellroad-stuff:sql-update id="renameColumn">
* ALTER TABLE User ADD newName VARCHAR(64);
* ALTER TABLE User SET newName = oldName;
* ALTER TABLE User DROP oldName;
* </dellroad-stuff:sql-update></b>
* </pre></blockquote>
* This will create three separate update beans named <code>renameColumn-00001</code>, <code>renameColumn-00002</code>, and
* <code>renameColumn-00003</code>. You can disable this behavior by adding the attribute <code>single-action="true"</code>,
* in which case all three of the statements will be executed together in the same transaction and recorded under the name
* <code>renameColumn</code>; this means that they must all complete successfully or you could end up with a partially
* completed update.
* </p>
*
* <p>
* Note that if the nested SQL script only contains one SQL statement, any <code>single-action</code> attribute is
* ignored and the bean's given name (e.g., <code>renameColumn</code>) is always used as the name of the single update.
* </p>
*/
public class SpringSQLSchemaUpdate extends AbstractSpringSchemaUpdate {
private SQLDatabaseAction action;
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
if (this.action == null)
throw new Exception("no DatabaseAction configured");
}
/**
* Configure the {@link SQLDatabaseAction}. This is a required property.
*
* @see DatabaseAction
*/
public void setSQLDatabaseAction(SQLDatabaseAction action) {
this.action = action;
}
@Override
public List<DatabaseAction> getDatabaseActions() {
return this.action.split();
}
}
| src/java/org/dellroad/stuff/schema/SpringSQLSchemaUpdate.java |
/*
* Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
*
* $Id$
*/
package org.dellroad.stuff.schema;
import java.util.List;
/**
* Spring-enabled {@link SchemaUpdate} supporting updates via SQL statements.
*
* <p>
* Instances can be created succintly using the <code><dellroad-stuff:sql-update></code> custom XML element, which works
* just like <code><dellroad-stuff:sql></code> except that it wraps the resulting {@link SQLDatabaseAction}
* as a delegate inside an instance of this class.
*
* <p>
* For example:
* <blockquote><pre>
* <beans xmlns="http://www.springframework.org/schema/beans"
* <b>xmlns:dellroad-stuff="http://dellroad-stuff.googlecode.com/schema/dellroad-stuff"</b>
* xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
* xsi:schemaLocation="
* http://www.springframework.org/schema/beans
* http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
* <b>http://dellroad-stuff.googlecode.com/schema/dellroad-stuff
* http://dellroad-stuff.googlecode.com/svn/wiki/schemas/dellroad-stuff-1.0.xsd</b>">
*
* <!-- Schema update to add the 'phone' column to the 'User' table -->
* <b><dellroad-stuff:sql-update id="addPhone">ALTER TABLE User ADD phone VARCHAR(64)</dellroad-stuff:sql-update></b>
*
* <!-- Schema update to run some complicated external SQL script -->
* <b><dellroad-stuff:sql-update id="majorChanges" depends-on="addPhone" resource="classpath:majorChanges.sql"/></b>
*
* <!-- more beans... -->
*
* </beans>
* </pre></blockquote>
* </p>
*
* <p>
* A multi-statement SQL script is normally treated as a set of individual updates. For example:
* <blockquote><pre>
* <b><dellroad-stuff:sql-update id="renameColumn">
* ALTER TABLE User ADD newName VARCHAR(64);
* ALTER TABLE User SET newName = oldName;
* ALTER TABLE User DROP oldName;
* </dellroad-stuff:sql-update></b>
* </pre></blockquote>
* This will create three separate update beans named <code>renameColumn-1</code>, <code>renameColumn-2</code>, and
* <code>renameColumn-3</code>. You can disable this behavior by adding the attribute <code>single-action="true"</code>,
* in which case all three of the statements will be executed together in the same transaction and recorded under the name
* <code>renameColumn</code>; this means that they must all complete successfully or you could end up with a partially
* completed update.
* </p>
*
* <p>
* Note that if the nested SQL script only contains one SQL statement, any <code>single-action</code> attribute is
* ignored and the bean's given name (e.g., <code>renameColumn</code>) is always used as the name of the single update.
* </p>
*/
public class SpringSQLSchemaUpdate extends AbstractSpringSchemaUpdate {
private SQLDatabaseAction action;
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
if (this.action == null)
throw new Exception("no DatabaseAction configured");
}
/**
* Configure the {@link SQLDatabaseAction}. This is a required property.
*
* @see DatabaseAction
*/
public void setSQLDatabaseAction(SQLDatabaseAction action) {
this.action = action;
}
@Override
public List<DatabaseAction> getDatabaseActions() {
return this.action.split();
}
}
| Fix Javadoc description of multi-action update naming scheme.
| src/java/org/dellroad/stuff/schema/SpringSQLSchemaUpdate.java | Fix Javadoc description of multi-action update naming scheme. |
|
Java | apache-2.0 | a6dc71070d1a0017a6ede4a1fd38eb28b9b70857 | 0 | project-ncl/pnc,pkocandr/pnc,matejonnet/pnc,thescouser89/pnc,rnc/pnc | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.restclient.websocket;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.WebSocket;
import org.jboss.pnc.common.json.JsonOutputConverterMapper;
import org.jboss.pnc.dto.notification.BuildChangedNotification;
import org.jboss.pnc.dto.notification.BuildConfigurationCreation;
import org.jboss.pnc.dto.notification.BuildPushResultNotification;
import org.jboss.pnc.dto.notification.GroupBuildChangedNotification;
import org.jboss.pnc.dto.notification.Notification;
import org.jboss.pnc.dto.notification.ProductMilestoneCloseResultNotification;
import org.jboss.pnc.dto.notification.RepositoryCreationFailure;
import org.jboss.pnc.dto.notification.SCMRepositoryCreationSuccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* @author <a href="mailto:[email protected]">Jan Michalov</a>
*/
public class VertxWebSocketClient implements WebSocketClient, AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(VertxWebSocketClient.class);
private static final ObjectMapper objectMapper = JsonOutputConverterMapper.getMapper();
private Vertx vertx;
private HttpClient httpClient;
private WebSocket webSocketConnection;
// use concurrent version since we may modify that list concurrently
private Set<Dispatcher> dispatchers = ConcurrentHashMap.newKeySet();
private Set<CompletableFuture<Notification>> singleNotificationFutures = ConcurrentHashMap.newKeySet();
/**
* maximum amount of time in milliseconds taken between retries
* <p>
* default: 10 min
*/
private int upperLimitForRetry = 600000;
private int numberOfRetries = 0;
/**
* a multiplier that increases delay between reconnect attempts
*/
private float delayMultiplier = 1.5F;
/**
* amount of milliseconds client waits before attempting to reconnect
*/
private int initialDelay = 250;
private int reconnectDelay;
public VertxWebSocketClient() {
reconnectDelay = initialDelay;
}
public VertxWebSocketClient(int upperLimitForRetry, int initialDelay, int delayMultiplier) {
this.delayMultiplier = delayMultiplier;
this.upperLimitForRetry = upperLimitForRetry;
this.initialDelay = initialDelay;
reconnectDelay = initialDelay;
}
@Override
public CompletableFuture<Void> connect(String webSocketServerUrl) {
if (webSocketServerUrl == null) {
throw new IllegalArgumentException("WebSocketServerUrl is null");
}
final URI serverURI;
try {
serverURI = new URI(webSocketServerUrl);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("WebSocketServerUrl is not valid URI", e);
}
if (this.vertx == null) {
this.vertx = Vertx.vertx();
this.httpClient = vertx.createHttpClient();
}
if (webSocketConnection != null && !webSocketConnection.isClosed()) {
log.trace("Already connected.");
return CompletableFuture.completedFuture(null);
}
CompletableFuture<Void> future = new CompletableFuture<>();
// in case no port was given, default to http port 80
int port = serverURI.getPort() == -1 ? 80 : serverURI.getPort();
httpClient.webSocket(port, serverURI.getHost(), serverURI.getPath(), result -> {
if (result.succeeded()) {
log.debug("Connection to WebSocket server: " + webSocketServerUrl + " successful.");
resetDefaults();
webSocketConnection = result.result();
webSocketConnection.textMessageHandler(this::dispatch);
webSocketConnection.closeHandler((ignore) -> connectionClosed(webSocketServerUrl));
// Async operation complete
future.complete(null);
} else {
log.error("Connection to WebSocket server: " + webSocketServerUrl + " unsuccessful.", result.cause());
// if there was a request to reconnect through retries, try to reconnect for possible network issues
if (numberOfRetries > 0) {
connectionLost(webSocketServerUrl);
}
future.completeExceptionally(result.cause());
}
});
return future;
}
private void dispatch(String message) {
dispatchers.forEach((dispatcher) -> dispatcher.accept(message));
}
private void connectionClosed(String webSocketServerUrl) {
log.warn("WebSocket connection was remotely closed, will retry in: " + reconnectDelay + " milliseconds.");
retryConnection(webSocketServerUrl);
}
private void connectionLost(String webSocketServerUrl) {
log.warn(
"WebSocket connection lost. Possible VPN/Network issues, will retry in: " + reconnectDelay
+ " milliseconds.");
retryConnection(webSocketServerUrl);
}
private void retryConnection(String webSocketServerUrl) {
numberOfRetries++;
vertx.setTimer(reconnectDelay, (timerId) -> connectAndReset(webSocketServerUrl));
// don't exceed upper limit for retry
if (reconnectDelay * delayMultiplier > upperLimitForRetry)
reconnectDelay = upperLimitForRetry;
else
reconnectDelay *= delayMultiplier;
}
private CompletableFuture<Void> connectAndReset(String webSocketServerUrl) {
log.warn("Trying to reconnect. Number of retries: " + numberOfRetries);
return connect(webSocketServerUrl).thenRun(this::resetDefaults);
}
private void resetDefaults() {
reconnectDelay = initialDelay;
numberOfRetries = 0;
}
@Override
public CompletableFuture<Void> disconnect() {
if (webSocketConnection == null || webSocketConnection.isClosed()) {
// already disconnected
return CompletableFuture.completedFuture(null);
}
CompletableFuture<Void> future = new CompletableFuture<>();
webSocketConnection.closeHandler(null);
webSocketConnection.close((result) -> {
if (result.succeeded()) {
log.debug("Connection to WebSocket server successfully closed.");
future.complete(null);
} else {
log.error("Connection to WebSocket server unsuccessfully closed.", result.cause());
future.completeExceptionally(result.cause());
}
});
return future.whenComplete((x, y) -> vertx.close());
}
@Override
public <T extends Notification> ListenerUnsubscriber onMessage(
Class<T> notificationClass,
Consumer<T> listener,
Predicate<T>... filters) throws ConnectionClosedException {
if (webSocketConnection == null || webSocketConnection.isClosed()) {
throw new ConnectionClosedException("Connection to WebSocket is closed.");
}
// add JSON message mapping before executing the listener
Dispatcher dispatcher = (stringMessage) -> {
T notification;
try {
notification = objectMapper.readValue(stringMessage, notificationClass);
for (Predicate<T> filter : filters) {
if (filter != null && !filter.test(notification)) {
// does not satisfy a predicate
return;
}
}
} catch (JsonProcessingException e) {
// could not parse to particular class of notification, unknown or different type of notification
// ignoring the message
return;
}
listener.accept(notification);
};
dispatchers.add(dispatcher);
return () -> dispatchers.remove(dispatcher);
}
@Override
public <T extends Notification> CompletableFuture<T> catchSingleNotification(
Class<T> notificationClass,
Predicate<T>... filters) {
CompletableFuture<T> future = new CompletableFuture<>();
ListenerUnsubscriber unsubscriber = null;
singleNotificationFutures.add((CompletableFuture<Notification>) future);
try {
unsubscriber = onMessage(notificationClass, future::complete, filters);
} catch (ConnectionClosedException e) {
future.completeExceptionally(e);
// in this case we have to set unsubscriber manually to avoid NPE
unsubscriber = () -> {};
}
final ListenerUnsubscriber finalUnsubscriber = unsubscriber;
return future.whenComplete((notification, throwable) -> finalUnsubscriber.run());
}
@Override
public ListenerUnsubscriber onBuildChangedNotification(
Consumer<BuildChangedNotification> onNotification,
Predicate<BuildChangedNotification>... filters) throws ConnectionClosedException {
return onMessage(BuildChangedNotification.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onBuildConfigurationCreation(
Consumer<BuildConfigurationCreation> onNotification,
Predicate<BuildConfigurationCreation>... filters) throws ConnectionClosedException {
return onMessage(BuildConfigurationCreation.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onBuildPushResult(
Consumer<BuildPushResultNotification> onNotification,
Predicate<BuildPushResultNotification>... filters) throws ConnectionClosedException {
return onMessage(BuildPushResultNotification.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onGroupBuildChangedNotification(
Consumer<GroupBuildChangedNotification> onNotification,
Predicate<GroupBuildChangedNotification>... filters) throws ConnectionClosedException {
return onMessage(GroupBuildChangedNotification.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onRepositoryCreationFailure(
Consumer<RepositoryCreationFailure> onNotification,
Predicate<RepositoryCreationFailure>... filters) throws ConnectionClosedException {
return onMessage(RepositoryCreationFailure.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onSCMRepositoryCreationSuccess(
Consumer<SCMRepositoryCreationSuccess> onNotification,
Predicate<SCMRepositoryCreationSuccess>... filters) throws ConnectionClosedException {
return onMessage(SCMRepositoryCreationSuccess.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onProductMilestoneCloseResult(
Consumer<ProductMilestoneCloseResultNotification> onNotification,
Predicate<ProductMilestoneCloseResultNotification>... filters) throws ConnectionClosedException {
return onMessage(ProductMilestoneCloseResultNotification.class, onNotification, filters);
}
@Override
public CompletableFuture<BuildChangedNotification> catchBuildChangedNotification(
Predicate<BuildChangedNotification>... filters) {
return catchSingleNotification(BuildChangedNotification.class, filters);
}
@Override
public CompletableFuture<BuildConfigurationCreation> catchBuildConfigurationCreation(
Predicate<BuildConfigurationCreation>... filters) {
return catchSingleNotification(BuildConfigurationCreation.class, filters);
}
@Override
public CompletableFuture<BuildPushResultNotification> catchBuildPushResult(
Predicate<BuildPushResultNotification>... filters) {
return catchSingleNotification(BuildPushResultNotification.class, filters);
}
@Override
public CompletableFuture<GroupBuildChangedNotification> catchGroupBuildChangedNotification(
Predicate<GroupBuildChangedNotification>... filters) {
return catchSingleNotification(GroupBuildChangedNotification.class, filters);
}
@Override
public CompletableFuture<RepositoryCreationFailure> catchRepositoryCreationFailure(
Predicate<RepositoryCreationFailure>... filters) {
return catchSingleNotification(RepositoryCreationFailure.class, filters);
}
@Override
public CompletableFuture<SCMRepositoryCreationSuccess> catchSCMRepositoryCreationSuccess(
Predicate<SCMRepositoryCreationSuccess>... filters) {
return catchSingleNotification(SCMRepositoryCreationSuccess.class, filters);
}
@Override
public CompletableFuture<ProductMilestoneCloseResultNotification> catchProductMilestoneCloseResult(
Predicate<ProductMilestoneCloseResultNotification>... filters) {
return catchSingleNotification(ProductMilestoneCloseResultNotification.class, filters);
}
@Override
public void close() throws Exception {
disconnect().join();
if (vertx != null)
vertx.close();
}
/**
* TODO: Use Java 11 Cleaner class instead after Orchestrator migration to Java 11
*
* @throws Throwable throwable
* @see <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/ref/Cleaner.html">Java 11
* Cleaner</a>
*/
@Override
@Deprecated
protected void finalize() throws Throwable {
try {
try {
// attempt to properly disconnect
disconnect().get();
} finally {
// always close vertx
vertx.close();
}
} finally {
// always finalize
super.finalize();
}
}
}
| rest-client/src/main/java/org/jboss/pnc/restclient/websocket/VertxWebSocketClient.java | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.pnc.restclient.websocket;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.WebSocket;
import org.jboss.pnc.common.json.JsonOutputConverterMapper;
import org.jboss.pnc.dto.notification.BuildChangedNotification;
import org.jboss.pnc.dto.notification.BuildConfigurationCreation;
import org.jboss.pnc.dto.notification.BuildPushResultNotification;
import org.jboss.pnc.dto.notification.GroupBuildChangedNotification;
import org.jboss.pnc.dto.notification.Notification;
import org.jboss.pnc.dto.notification.ProductMilestoneCloseResultNotification;
import org.jboss.pnc.dto.notification.RepositoryCreationFailure;
import org.jboss.pnc.dto.notification.SCMRepositoryCreationSuccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* @author <a href="mailto:[email protected]">Jan Michalov</a>
*/
public class VertxWebSocketClient implements WebSocketClient, AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(VertxWebSocketClient.class);
private static final ObjectMapper objectMapper = JsonOutputConverterMapper.getMapper();
private Vertx vertx;
private HttpClient httpClient;
private WebSocket webSocketConnection;
// use concurrent version since we may modify that list concurrently
private Set<Dispatcher> dispatchers = ConcurrentHashMap.newKeySet();
private Set<CompletableFuture<Notification>> singleNotificationFutures = ConcurrentHashMap.newKeySet();
/**
* maximum amount of time in milliseconds taken between retries
*
* default: 10 min
*/
private int upperLimitForRetry = 600000;
private int numberOfRetries = 0;
/**
* a multiplier that increases delay between reconnect attempts
*/
private float delayMultiplier = 1.5F;
/**
* amount of milliseconds client waits before attempting to reconnect
*/
private int initialDelay = 250;
private int reconnectDelay;
public VertxWebSocketClient() {
reconnectDelay = initialDelay;
}
public VertxWebSocketClient(int upperLimitForRetry, int initialDelay, int delayMultiplier) {
this.delayMultiplier = delayMultiplier;
this.upperLimitForRetry = upperLimitForRetry;
this.initialDelay = initialDelay;
reconnectDelay = initialDelay;
}
@Override
public CompletableFuture<Void> connect(String webSocketServerUrl) {
if (webSocketServerUrl == null) {
throw new IllegalArgumentException("WebSocketServerUrl is null");
}
final URI serverURI;
try {
serverURI = new URI(webSocketServerUrl);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("WebSocketServerUrl is not valid URI", e);
}
if (this.vertx == null) {
this.vertx = Vertx.vertx();
this.httpClient = vertx.createHttpClient();
}
if (webSocketConnection != null && !webSocketConnection.isClosed()) {
log.trace("Already connected.");
return CompletableFuture.completedFuture(null);
}
CompletableFuture<Void> future = new CompletableFuture<>();
// in case no port was given, default to http port 80
int port = serverURI.getPort() == -1 ? 80 : serverURI.getPort();
httpClient.webSocket(port, serverURI.getHost(), serverURI.getPath(), result -> {
if (result.succeeded()) {
log.debug("Connection to WebSocket server: " + webSocketServerUrl + " successful.");
resetDefaults();
webSocketConnection = result.result();
webSocketConnection.textMessageHandler(this::dispatch);
webSocketConnection.closeHandler((ignore) -> connectionClosed(webSocketServerUrl));
// Async operation complete
future.complete(null);
} else {
log.error("Connection to WebSocket server: " + webSocketServerUrl + " unsuccessful.", result.cause());
// if there was a request to reconnect through retries, try to reconnect for possible network issues
if (numberOfRetries > 0) {
connectionLost(webSocketServerUrl);
}
future.completeExceptionally(result.cause());
}
});
return future;
}
private void dispatch(String message) {
dispatchers.forEach((dispatcher) -> dispatcher.accept(message));
}
private void connectionClosed(String webSocketServerUrl) {
log.warn("WebSocket connection was remotely closed, will retry in: " + reconnectDelay + " milliseconds.");
retryConnection(webSocketServerUrl);
}
private void connectionLost(String webSocketServerUrl) {
log.warn(
"WebSocket connection lost. Possible VPN/Network issues, will retry in: " + reconnectDelay
+ " milliseconds.");
retryConnection(webSocketServerUrl);
}
private void retryConnection(String webSocketServerUrl) {
numberOfRetries++;
vertx.setTimer(reconnectDelay, (timerId) -> connectAndReset(webSocketServerUrl));
// don't exceed upper limit for retry
if (reconnectDelay * delayMultiplier > upperLimitForRetry)
reconnectDelay = upperLimitForRetry;
else
reconnectDelay *= delayMultiplier;
}
private CompletableFuture<Void> connectAndReset(String webSocketServerUrl) {
log.warn("Trying to reconnect. Number of retries: " + numberOfRetries);
return connect(webSocketServerUrl).thenRun(this::resetDefaults);
}
private void resetDefaults() {
reconnectDelay = initialDelay;
numberOfRetries = 0;
}
@Override
public CompletableFuture<Void> disconnect() {
if (webSocketConnection == null || webSocketConnection.isClosed()) {
// already disconnected
return CompletableFuture.completedFuture(null);
}
CompletableFuture<Void> future = new CompletableFuture<>();
webSocketConnection.closeHandler(null);
webSocketConnection.close((result) -> {
if (result.succeeded()) {
log.debug("Connection to WebSocket server successfully closed.");
future.complete(null);
} else {
log.error("Connection to WebSocket server unsuccessfully closed.", result.cause());
future.completeExceptionally(result.cause());
}
});
return future.whenComplete((x, y) -> vertx.close());
}
@Override
public <T extends Notification> ListenerUnsubscriber onMessage(
Class<T> notificationClass,
Consumer<T> listener,
Predicate<T>... filters) throws ConnectionClosedException {
if (webSocketConnection == null || webSocketConnection.isClosed()) {
throw new ConnectionClosedException("Connection to WebSocket is closed.");
}
// add JSON message mapping before executing the listener
Dispatcher dispatcher = (stringMessage) -> {
T notification;
try {
notification = objectMapper.readValue(stringMessage, notificationClass);
for (Predicate<T> filter : filters) {
if (filter != null && !filter.test(notification)) {
// does not satisfy a predicate
return;
}
}
} catch (JsonProcessingException e) {
// could not parse to particular class of notification, unknown or different type of notification
// ignoring the message
return;
}
listener.accept(notification);
};
dispatchers.add(dispatcher);
return () -> dispatchers.remove(dispatcher);
}
@Override
public <T extends Notification> CompletableFuture<T> catchSingleNotification(
Class<T> notificationClass,
Predicate<T>... filters) {
CompletableFuture<T> future = new CompletableFuture<>();
ListenerUnsubscriber unsubscriber = null;
singleNotificationFutures.add((CompletableFuture<Notification>) future);
try {
unsubscriber = onMessage(notificationClass, future::complete, filters);
} catch (ConnectionClosedException e) {
future.completeExceptionally(e);
// in this case we have to set unsubscriber manually to avoid NPE
unsubscriber = () -> {};
}
final ListenerUnsubscriber finalUnsubscriber = unsubscriber;
return future.whenComplete((notification, throwable) -> finalUnsubscriber.run());
}
@Override
public ListenerUnsubscriber onBuildChangedNotification(
Consumer<BuildChangedNotification> onNotification,
Predicate<BuildChangedNotification>... filters) throws ConnectionClosedException {
return onMessage(BuildChangedNotification.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onBuildConfigurationCreation(
Consumer<BuildConfigurationCreation> onNotification,
Predicate<BuildConfigurationCreation>... filters) throws ConnectionClosedException {
return onMessage(BuildConfigurationCreation.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onBuildPushResult(
Consumer<BuildPushResultNotification> onNotification,
Predicate<BuildPushResultNotification>... filters) throws ConnectionClosedException {
return onMessage(BuildPushResultNotification.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onGroupBuildChangedNotification(
Consumer<GroupBuildChangedNotification> onNotification,
Predicate<GroupBuildChangedNotification>... filters) throws ConnectionClosedException {
return onMessage(GroupBuildChangedNotification.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onRepositoryCreationFailure(
Consumer<RepositoryCreationFailure> onNotification,
Predicate<RepositoryCreationFailure>... filters) throws ConnectionClosedException {
return onMessage(RepositoryCreationFailure.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onSCMRepositoryCreationSuccess(
Consumer<SCMRepositoryCreationSuccess> onNotification,
Predicate<SCMRepositoryCreationSuccess>... filters) throws ConnectionClosedException {
return onMessage(SCMRepositoryCreationSuccess.class, onNotification, filters);
}
@Override
public ListenerUnsubscriber onProductMilestoneCloseResult(
Consumer<ProductMilestoneCloseResultNotification> onNotification,
Predicate<ProductMilestoneCloseResultNotification>... filters) throws ConnectionClosedException {
return onMessage(ProductMilestoneCloseResultNotification.class, onNotification, filters);
}
@Override
public CompletableFuture<BuildChangedNotification> catchBuildChangedNotification(
Predicate<BuildChangedNotification>... filters) {
return catchSingleNotification(BuildChangedNotification.class, filters);
}
@Override
public CompletableFuture<BuildConfigurationCreation> catchBuildConfigurationCreation(
Predicate<BuildConfigurationCreation>... filters) {
return catchSingleNotification(BuildConfigurationCreation.class, filters);
}
@Override
public CompletableFuture<BuildPushResultNotification> catchBuildPushResult(
Predicate<BuildPushResultNotification>... filters) {
return catchSingleNotification(BuildPushResultNotification.class, filters);
}
@Override
public CompletableFuture<GroupBuildChangedNotification> catchGroupBuildChangedNotification(
Predicate<GroupBuildChangedNotification>... filters) {
return catchSingleNotification(GroupBuildChangedNotification.class, filters);
}
@Override
public CompletableFuture<RepositoryCreationFailure> catchRepositoryCreationFailure(
Predicate<RepositoryCreationFailure>... filters) {
return catchSingleNotification(RepositoryCreationFailure.class, filters);
}
@Override
public CompletableFuture<SCMRepositoryCreationSuccess> catchSCMRepositoryCreationSuccess(
Predicate<SCMRepositoryCreationSuccess>... filters) {
return catchSingleNotification(SCMRepositoryCreationSuccess.class, filters);
}
@Override
public CompletableFuture<ProductMilestoneCloseResultNotification> catchProductMilestoneCloseResult(
Predicate<ProductMilestoneCloseResultNotification>... filters) {
return catchSingleNotification(ProductMilestoneCloseResultNotification.class, filters);
}
@Override
public void close() throws Exception {
disconnect().join();
if (vertx != null)
vertx.close();
}
}
| [NCL-5662] make Vertx close on WS client getting garbage collected
| rest-client/src/main/java/org/jboss/pnc/restclient/websocket/VertxWebSocketClient.java | [NCL-5662] make Vertx close on WS client getting garbage collected |
|
Java | apache-2.0 | fcc80e27177304d136c657c7b86d14e8025ee5d8 | 0 | nus-ncl/service-web,nus-ncl/service-web,nus-ncl/service-web,nus-ncl/service-web | package sg.ncl.testbed_interface;
import lombok.Getter;
import lombok.Setter;
/**
* Created by dcszwang on 11/7/2016.
*/
@Getter
@Setter
public class PasswordResetForm {
private String password1;
private String password2;
public String errMsg;
}
| src/main/java/sg/ncl/testbed_interface/PasswordResetForm.java | package sg.ncl.testbed_interface;
import lombok.Getter;
import lombok.Setter;
/**
* Created by dcszwang on 11/7/2016.
*/
@Getter
@Setter
public class PasswordResetForm {
private String id;
private String password1;
private String password2;
public String errMsg;
}
| DEV-782 Removed unused field 'id' in PasswordResetForm class
| src/main/java/sg/ncl/testbed_interface/PasswordResetForm.java | DEV-782 Removed unused field 'id' in PasswordResetForm class |
|
Java | apache-2.0 | 1598b81ae6f12ca99927531b09ccb5dd873070f4 | 0 | Autoscaler/autoscaler,Autoscaler/autoscaler,Autoscaler/autoscaler | package com.hpe.caf.autoscale.source.marathon;
import com.hpe.caf.api.ConfigurationException;
import com.hpe.caf.api.ConfigurationSource;
import com.hpe.caf.api.ServicePath;
import com.hpe.caf.api.autoscale.ScalerException;
import com.hpe.caf.api.autoscale.ServiceSource;
import com.hpe.caf.api.autoscale.ServiceSourceProvider;
import com.hpe.caf.autoscale.MarathonAutoscaleConfiguration;
import feign.Feign;
import feign.Request;
import mesosphere.marathon.client.Marathon;
import mesosphere.marathon.client.MarathonClient;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
public class MarathonServiceSourceProvider implements ServiceSourceProvider
{
private static final int MARATHON_TIMEOUT = 10_000;
@Override
public ServiceSource getServiceSource(final ConfigurationSource configurationSource, final ServicePath servicePath)
throws ScalerException
{
try {
Iterator<String> groupIterator = servicePath.groupIterator();
StringBuilder groupPath = new StringBuilder();
while (groupIterator.hasNext()) {
groupPath.append(groupIterator.next()).append('/');
}
MarathonAutoscaleConfiguration config = configurationSource.getConfiguration(MarathonAutoscaleConfiguration.class);
Feign.Builder builder = Feign.builder().options(new Request.Options(MARATHON_TIMEOUT, MARATHON_TIMEOUT));
Marathon marathon = MarathonClient.getInstance(builder, config.getEndpoint());
return new MarathonServiceSource(marathon, groupPath.toString(), new URL(config.getEndpoint()));
} catch (ConfigurationException | MalformedURLException e) {
throw new ScalerException("Failed to create service source", e);
}
}
}
| src/main/java/com/hpe/caf/autoscale/source/marathon/MarathonServiceSourceProvider.java | package com.hpe.caf.autoscale.source.marathon;
import com.hpe.caf.api.ConfigurationException;
import com.hpe.caf.api.ConfigurationSource;
import com.hpe.caf.api.ServicePath;
import com.hpe.caf.api.autoscale.ScalerException;
import com.hpe.caf.api.autoscale.ServiceSource;
import com.hpe.caf.api.autoscale.ServiceSourceProvider;
import com.hpe.caf.autoscale.MarathonAutoscaleConfiguration;
import mesosphere.marathon.client.Marathon;
import mesosphere.marathon.client.MarathonClient;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
public class MarathonServiceSourceProvider implements ServiceSourceProvider
{
@Override
public ServiceSource getServiceSource(final ConfigurationSource configurationSource, final ServicePath servicePath)
throws ScalerException
{
try {
Iterator<String> groupIterator = servicePath.groupIterator();
StringBuilder groupPath = new StringBuilder();
while (groupIterator.hasNext()) {
groupPath.append(groupIterator.next()).append('/');
}
MarathonAutoscaleConfiguration config = configurationSource.getConfiguration(MarathonAutoscaleConfiguration.class);
Marathon marathon = MarathonClient.getInstance(config.getEndpoint());
return new MarathonServiceSource(marathon, groupPath.toString(), new URL(config.getEndpoint()));
} catch (ConfigurationException | MalformedURLException e) {
throw new ScalerException("Failed to create service source", e);
}
}
}
| Set HTTP timeout to 10 seconds
| src/main/java/com/hpe/caf/autoscale/source/marathon/MarathonServiceSourceProvider.java | Set HTTP timeout to 10 seconds |
|
Java | apache-2.0 | f3a7afa323c62861b4f28c1de8cc4c6eba330f7e | 0 | OpenConext/OpenConext-teams,OpenConext/OpenConext-teams,OpenConext/OpenConext-teams | package nl.surfnet.coin.teams.control;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.junit.Before;
import org.junit.Test;
import org.opensocial.models.Person;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.view.RedirectView;
import nl.surfnet.coin.teams.domain.Invitation;
import nl.surfnet.coin.teams.domain.Team;
import nl.surfnet.coin.teams.interceptor.LoginInterceptor;
import nl.surfnet.coin.teams.service.TeamInviteService;
import nl.surfnet.coin.teams.service.TeamService;
/**
* Test for {@link InvitationController}
*/
public class InvitationControllerTest extends AbstractControllerTest {
InvitationController controller = new InvitationController();
private static final String INVITATION_HASH = "0b733d119c3705ae4fc284203f1ee8ec";
private HttpServletRequest mockRequest;
private Invitation invitation;
@Test
public void testAccept() throws Exception {
String page = controller.accept(getModelMap(), mockRequest);
assertEquals("acceptinvitation", page);
}
@Test
public void testDecline() throws Exception {
RedirectView view = controller.decline(mockRequest);
assertTrue("Declined invitation", invitation.isDeclined());
assertEquals("home.shtml?teams=my&view=app", view.getUrl());
}
@Test
public void testDoAccept() throws Exception {
RedirectView view = controller.doAccept(mockRequest);
String redirectUrl = "detailteam.shtml?team=team-1&view=app";
assertEquals(redirectUrl, view.getUrl());
}
@Test
public void testDelete() throws Exception {
RedirectView view = controller.deleteInvitation(new ModelMap(), mockRequest);
String redirectUrl = "detailteam.shtml?team=team-1&view=app";
assertEquals(redirectUrl, view.getUrl());
}
@Before
public void setup() throws Exception {
super.setup();
Person mockPerson = mock(Person.class);
when(mockPerson.getId()).thenReturn("person-1");
HttpSession mockSession = mock(HttpSession.class);
when(mockSession.getAttribute(LoginInterceptor.PERSON_SESSION_KEY)).
thenReturn(mockPerson);
mockRequest = mock(HttpServletRequest.class);
when(mockRequest.getSession()).thenReturn(mockSession);
when(mockRequest.getParameter("id")).thenReturn(INVITATION_HASH);
Team mockTeam = mock(Team.class);
when(mockTeam.getId()).thenReturn("team-1");
invitation = new Invitation("test-email",
"team-1", "test-inviter");
TeamInviteService teamInviteService = mock(TeamInviteService.class);
when(teamInviteService.findInvitationByInviteId(INVITATION_HASH)).thenReturn(invitation);
autoWireMock(controller, teamInviteService, TeamInviteService.class);
TeamService teamService = mock(TeamService.class);
when(teamService.findTeamById("team-1")).thenReturn(mockTeam);
autoWireMock(controller, teamService, TeamService.class);
}
}
| coin-teams-war/src/test/java/nl/surfnet/coin/teams/control/InvitationControllerTest.java | package nl.surfnet.coin.teams.control;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.junit.Before;
import org.junit.Test;
import org.opensocial.models.Person;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.view.RedirectView;
import nl.surfnet.coin.teams.domain.Invitation;
import nl.surfnet.coin.teams.domain.Team;
import nl.surfnet.coin.teams.interceptor.LoginInterceptor;
import nl.surfnet.coin.teams.service.TeamInviteService;
import nl.surfnet.coin.teams.service.TeamService;
/**
* Test for {@link InvitationController}
*/
public class InvitationControllerTest extends AbstractControllerTest {
InvitationController controller = new InvitationController();
private static final String INVITATION_HASH = "0b733d119c3705ae4fc284203f1ee8ec";
private HttpServletRequest mockRequest;
private Team mockTeam;
@Test
public void testAccept() throws Exception {
Invitation invitation = new Invitation("test-email",
"team-1", "test-inviter");
TeamInviteService teamInviteService = mock(TeamInviteService.class);
when(teamInviteService.findInvitationByInviteId(INVITATION_HASH)).thenReturn(invitation);
TeamService teamService = mock(TeamService.class);
when(teamService.findTeamById("team-1")).thenReturn(mockTeam);
autoWireMock(controller, teamInviteService, TeamInviteService.class);
autoWireMock(controller, teamService, TeamService.class);
String page = controller.accept(getModelMap(), mockRequest);
assertEquals("acceptinvitation", page);
}
@Test
public void testDecline() throws Exception {
Invitation invitation = new Invitation("test-email",
"test-teamId", "test-inviter");
TeamInviteService teamInviteService = mock(TeamInviteService.class);
when(teamInviteService.findInvitationByInviteId(INVITATION_HASH)).thenReturn(invitation);
autoWireMock(controller, teamInviteService, TeamInviteService.class);
RedirectView view = controller.decline(mockRequest);
assertTrue("Declined invitation", invitation.isDeclined());
assertEquals("home.shtml?teams=my&view=app", view.getUrl());
}
@Test
public void testDoAccept() throws Exception {
Invitation invitation = new Invitation("test-email",
"team-1", "test-inviter");
TeamInviteService teamInviteService = mock(TeamInviteService.class);
when(teamInviteService.findInvitationByInviteId(INVITATION_HASH)).thenReturn(invitation);
TeamService teamService = mock(TeamService.class);
when(teamService.findTeamById("team-1")).thenReturn(mockTeam);
autoWireMock(controller, teamInviteService, TeamInviteService.class);
autoWireMock(controller, teamService, TeamService.class);
RedirectView view = controller.doAccept(mockRequest);
String redirectUrl = "detailteam.shtml?team=team-1&view=app";
assertEquals(redirectUrl, view.getUrl());
}
@Test
public void testDelete() throws Exception {
Invitation invitation = new Invitation("test-email",
"team-1", "test-inviter");
TeamInviteService teamInviteService = mock(TeamInviteService.class);
when(teamInviteService.findInvitationByInviteId(INVITATION_HASH)).thenReturn(invitation);
TeamService teamService = mock(TeamService.class);
when(teamService.findTeamById("team-1")).thenReturn(mockTeam);
autoWireMock(controller, teamInviteService, TeamInviteService.class);
autoWireMock(controller, teamService, TeamService.class);
RedirectView view = controller.deleteInvitation(new ModelMap(), mockRequest);
String redirectUrl = "detailteam.shtml?team=team-1&view=app";
assertEquals(redirectUrl, view.getUrl());
}
@Before
public void setup() throws Exception {
super.setup();
Person mockPerson = mock(Person.class);
when(mockPerson.getId()).thenReturn("person-1");
HttpSession mockSession = mock(HttpSession.class);
when(mockSession.getAttribute(LoginInterceptor.PERSON_SESSION_KEY)).
thenReturn(mockPerson);
mockRequest = mock(HttpServletRequest.class);
when(mockRequest.getSession()).thenReturn(mockSession);
when(mockRequest.getParameter("id")).thenReturn(INVITATION_HASH);
mockTeam = mock(Team.class);
when(mockTeam.getId()).thenReturn("team-1");
}
}
| even less code duplication
git-svn-id: 7f9817d80667deac6042fd45474745cdc98fb3cd@1155 3364c4cd-9065-40b6-aee7-261f90ce6533
| coin-teams-war/src/test/java/nl/surfnet/coin/teams/control/InvitationControllerTest.java | even less code duplication |
|
Java | apache-2.0 | fed9d5b25c70c76107d995cd9536023f4387e86c | 0 | jameswei/google-http-java-client,skinzer/google-http-java-client,googleapis/google-http-java-client,b-cuts/google-http-java-client,t9nf/google-http-java-client,wgpshashank/google-http-java-client,t9nf/google-http-java-client,bright60/google-http-java-client,SunghanKim/google-http-java-client,ejona86/google-http-java-client,wgpshashank/google-http-java-client,ejona86/google-http-java-client,googleapis/google-http-java-client,fengshao0907/google-http-java-client,t9nf/google-http-java-client,spotify/google-http-java-client,skinzer/google-http-java-client,t9nf/google-http-java-client,nonexpectation/google-http-java-client,ejona86/google-http-java-client,b-cuts/google-http-java-client,veraicon/google-http-java-client,nonexpectation/google-http-java-client,bright60/google-http-java-client,SunghanKim/google-http-java-client,jameswei/google-http-java-client,nonexpectation/google-http-java-client,veraicon/google-http-java-client,googleapis/google-http-java-client,googleapis/google-http-java-client,jameswei/google-http-java-client,b-cuts/google-http-java-client,veraicon/google-http-java-client,spotify/google-http-java-client,suclike/google-http-java-client,nonexpectation/google-http-java-client,jameswei/google-http-java-client,spotify/google-http-java-client,fengshao0907/google-http-java-client,bright60/google-http-java-client,SunghanKim/google-http-java-client,suclike/google-http-java-client,skinzer/google-http-java-client,fengshao0907/google-http-java-client,wgpshashank/google-http-java-client,wgpshashank/google-http-java-client,bright60/google-http-java-client,b-cuts/google-http-java-client,SunghanKim/google-http-java-client,suclike/google-http-java-client,veraicon/google-http-java-client | /*
* Copyright (c) 2010 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 com.google.api.client.json;
import com.google.api.client.util.ArrayMap;
import com.google.api.client.util.Data;
import com.google.api.client.util.Key;
import com.google.api.client.util.NullValue;
import com.google.api.client.util.StringUtils;
import com.google.api.client.util.Value;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import com.google.gson.reflect.TypeToken;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Abstract test case for testing a {@link JsonFactory}.
*
* @author Yaniv Inbar
*/
public abstract class AbstractJsonFactoryTest extends TestCase {
public AbstractJsonFactoryTest(String name) {
super(name);
}
protected abstract JsonFactory newFactory();
private static final String EMPTY = "";
public void testParse_empty() throws IOException {
JsonParser parser = newFactory().createJsonParser(EMPTY);
parser.nextToken();
try {
parser.parseAndClose(HashMap.class, null);
fail("expected " + IllegalArgumentException.class);
} catch (IllegalArgumentException e) {
// expected
}
}
private static final String EMPTY_OBJECT = "{}";
public void testParse_emptyMap() throws IOException {
JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT);
parser.nextToken();
@SuppressWarnings("unchecked")
HashMap<String, Object> map = parser.parseAndClose(HashMap.class, null);
assertTrue(map.isEmpty());
}
public void testParse_emptyGenericJson() throws IOException {
JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT);
parser.nextToken();
GenericJson json = parser.parseAndClose(GenericJson.class, null);
assertTrue(json.isEmpty());
}
public void testParser_partialEmpty() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(EMPTY_OBJECT);
parser.nextToken();
parser.nextToken();
// current token is now end_object
@SuppressWarnings("unchecked")
HashMap<String, Object> result = parser.parseAndClose(HashMap.class, null);
assertEquals(EMPTY_OBJECT, factory.toString(result));
// check types and values
assertTrue(result.isEmpty());
}
private static final String JSON_ENTRY = "{\"title\":\"foo\"}";
private static final String JSON_FEED =
"{\"entries\":[" + "{\"title\":\"foo\"}," + "{\"title\":\"bar\"}]}";
public void testParseEntry() throws Exception {
Entry entry = newFactory().createJsonParser(JSON_ENTRY).parseAndClose(Entry.class, null);
assertEquals("foo", entry.title);
}
public void testParser_partialEntry() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.nextToken();
// current token is now field_name
Entry result = parser.parseAndClose(Entry.class, null);
assertEquals(JSON_ENTRY, factory.toString(result));
// check types and values
assertEquals("foo", result.title);
}
public void testParseFeed() throws Exception {
JsonParser parser = newFactory().createJsonParser(JSON_FEED);
parser.nextToken();
Feed feed = parser.parseAndClose(Feed.class, null);
Iterator<Entry> iterator = feed.entries.iterator();
assertEquals("foo", iterator.next().title);
assertEquals("bar", iterator.next().title);
assertFalse(iterator.hasNext());
}
@SuppressWarnings("unchecked")
public void testParseEntryAsMap() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
HashMap<String, Object> map = parser.parseAndClose(HashMap.class, null);
assertEquals("foo", map.remove("title"));
assertTrue(map.isEmpty());
}
public void testSkipToKey_missingEmpty() throws IOException {
JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT);
parser.nextToken();
parser.skipToKey("missing");
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
}
public void testSkipToKey_missing() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.skipToKey("missing");
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
}
public void testSkipToKey_found() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.skipToKey("title");
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
assertEquals("foo", parser.getText());
}
public void testSkipToKey_startWithFieldName() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.nextToken();
parser.skipToKey("title");
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
assertEquals("foo", parser.getText());
}
public void testSkipChildren_string() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.skipToKey("title");
parser.skipChildren();
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
assertEquals("foo", parser.getText());
}
public void testSkipChildren_object() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.skipChildren();
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
}
public void testSkipChildren_array() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_FEED);
parser.nextToken();
parser.skipToKey("entries");
parser.skipChildren();
assertEquals(JsonToken.END_ARRAY, parser.getCurrentToken());
}
public void testNextToken() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_FEED);
assertEquals(JsonToken.START_OBJECT, parser.nextToken());
assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
assertEquals(JsonToken.START_ARRAY, parser.nextToken());
assertEquals(JsonToken.START_OBJECT, parser.nextToken());
assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
assertEquals(JsonToken.END_OBJECT, parser.nextToken());
assertEquals(JsonToken.START_OBJECT, parser.nextToken());
assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
assertEquals(JsonToken.END_OBJECT, parser.nextToken());
assertEquals(JsonToken.END_ARRAY, parser.nextToken());
assertEquals(JsonToken.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken());
}
public void testCurrentToken() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_FEED);
assertNull(parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.START_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.FIELD_NAME, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.START_ARRAY, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.START_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.FIELD_NAME, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.START_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.FIELD_NAME, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.END_ARRAY, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertNull(parser.getCurrentToken());
}
public static class Entry {
@Key
public String title;
}
public static class Feed {
@Key
public Collection<Entry> entries;
}
public static class A {
@Key
public Map<String, String> map;
}
static final String CONTAINED_MAP = "{\"map\":{\"title\":\"foo\"}}";
public void testParse() throws IOException {
JsonParser parser = newFactory().createJsonParser(CONTAINED_MAP);
parser.nextToken();
A a = parser.parse(A.class, null);
assertEquals(ImmutableMap.of("title", "foo"), a.map);
}
public static class NumberTypes {
@Key
byte byteValue;
@Key
Byte byteObjValue;
@Key
short shortValue;
@Key
Short shortObjValue;
@Key
int intValue;
@Key
Integer intObjValue;
@Key
float floatValue;
@Key
Float floatObjValue;
@Key
long longValue;
@Key
Long longObjValue;
@Key
double doubleValue;
@Key
Double doubleObjValue;
@Key
BigInteger bigIntegerValue;
@Key
UnsignedInteger unsignedIntegerValue;
@Key
UnsignedLong unsignedLongValue;
@Key
BigDecimal bigDecimalValue;
@Key("yetAnotherBigDecimalValue")
BigDecimal anotherBigDecimalValue;
}
public static class NumberTypesAsString {
@Key
@JsonString
byte byteValue;
@Key
@JsonString
Byte byteObjValue;
@Key
@JsonString
short shortValue;
@Key
@JsonString
Short shortObjValue;
@Key
@JsonString
int intValue;
@Key
@JsonString
Integer intObjValue;
@Key
@JsonString
float floatValue;
@Key
@JsonString
Float floatObjValue;
@Key
@JsonString
long longValue;
@Key
@JsonString
Long longObjValue;
@Key
@JsonString
double doubleValue;
@Key
@JsonString
Double doubleObjValue;
@Key
@JsonString
BigInteger bigIntegerValue;
@Key
@JsonString
UnsignedInteger unsignedIntegerValue;
@Key
@JsonString
UnsignedLong unsignedLongValue;
@Key
@JsonString
BigDecimal bigDecimalValue;
@Key("yetAnotherBigDecimalValue")
@JsonString
BigDecimal anotherBigDecimalValue;
}
static final String NUMBER_TYPES =
"{\"bigDecimalValue\":1.0,\"bigIntegerValue\":1,\"byteObjValue\":1,\"byteValue\":1,"
+ "\"doubleObjValue\":1.0,\"doubleValue\":1.0,\"floatObjValue\":1.0,\"floatValue\":1.0,"
+ "\"intObjValue\":1,\"intValue\":1,\"longObjValue\":1,\"longValue\":1,"
+ "\"shortObjValue\":1,\"shortValue\":1,\"unsignedIntegerValue\":1,\"unsignedLongValue\":1,"
+ "\"yetAnotherBigDecimalValue\":1}";
static final String NUMBER_TYPES_AS_STRING =
"{\"bigDecimalValue\":\"1.0\",\"bigIntegerValue\":\"1\",\"byteObjValue\":\"1\","
+ "\"byteValue\":\"1\",\"doubleObjValue\":\"1.0\",\"doubleValue\":\"1.0\","
+ "\"floatObjValue\":\"1.0\",\"floatValue\":\"1.0\",\"intObjValue\":\"1\","
+ "\"intValue\":\"1\",\"longObjValue\":\"1\",\"longValue\":\"1\",\"shortObjValue\":\"1\","
+ "\"shortValue\":\"1\",\"unsignedIntegerValue\":\"1\",\"unsignedLongValue\":\"1\","
+ "\"yetAnotherBigDecimalValue\":\"1\"}";
public void testParser_numberTypes() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
// number types
parser = factory.createJsonParser(NUMBER_TYPES);
parser.nextToken();
NumberTypes result = parser.parse(NumberTypes.class, null);
assertEquals(NUMBER_TYPES, factory.toString(result));
// number types as string
parser = factory.createJsonParser(NUMBER_TYPES_AS_STRING);
parser.nextToken();
NumberTypesAsString resultAsString = parser.parse(NumberTypesAsString.class, null);
assertEquals(NUMBER_TYPES_AS_STRING, factory.toString(resultAsString));
// number types with @JsonString
try {
parser = factory.createJsonParser(NUMBER_TYPES_AS_STRING);
parser.nextToken();
parser.parse(NumberTypes.class, null);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
// number types as string without @JsonString
try {
parser = factory.createJsonParser(NUMBER_TYPES);
parser.nextToken();
parser.parse(NumberTypesAsString.class, null);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
public void testToFromString() throws IOException {
JsonFactory factory = newFactory();
NumberTypes result = factory.fromString(NUMBER_TYPES, NumberTypes.class);
assertEquals(NUMBER_TYPES, factory.toString(result));
}
private static final String UTF8_VALUE = "123\u05D9\u05e0\u05D9\u05D1";
private static final String UTF8_JSON = "{\"value\":\"" + UTF8_VALUE + "\"}";
public void testToFromString_UTF8() throws IOException {
JsonFactory factory = newFactory();
GenericJson result = factory.fromString(UTF8_JSON, GenericJson.class);
assertEquals(UTF8_VALUE, result.get("value"));
assertEquals(UTF8_JSON, factory.toString(result));
}
public static class AnyType {
@Key
public Object arr;
@Key
public Object bool;
@Key
public Object num;
@Key
public Object obj;
@Key
public Object str;
@Key
public Object nul;
}
static final String ANY_TYPE = "{\"arr\":[1],\"bool\":true,\"nul\":null,\"num\":5,"
+ "\"obj\":{\"key\":\"value\"},\"str\":\"value\"}";
public void testParser_anyType() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(ANY_TYPE);
parser.nextToken();
AnyType result = parser.parse(AnyType.class, null);
assertEquals(ANY_TYPE, factory.toString(result));
}
public static class ArrayType {
@Key
int[] arr;
@Key
int[][] arr2;
@Key
public Integer[] integerArr;
}
static final String ARRAY_TYPE = "{\"arr\":[4,5],\"arr2\":[[1,2],[3]],\"integerArr\":[6,7]}";
public void testParser_arrayType() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(ARRAY_TYPE);
parser.nextToken();
ArrayType result = parser.parse(ArrayType.class, null);
assertEquals(ARRAY_TYPE, factory.toString(result));
// check types and values
int[] arr = result.arr;
assertTrue(Arrays.equals(new int[] {4, 5}, arr));
int[][] arr2 = result.arr2;
assertEquals(2, arr2.length);
int[] arr20 = arr2[0];
assertEquals(2, arr20.length);
int arr200 = arr20[0];
assertEquals(1, arr200);
assertEquals(2, arr20[1]);
int[] arr21 = arr2[1];
assertEquals(1, arr21.length);
assertEquals(3, arr21[0]);
Integer[] integerArr = result.integerArr;
assertEquals(2, integerArr.length);
assertEquals(6, integerArr[0].intValue());
}
public static class CollectionOfCollectionType {
@Key
public LinkedList<LinkedList<String>> arr;
}
static final String COLLECTION_TYPE = "{\"arr\":[[\"a\",\"b\"],[\"c\"]]}";
public void testParser_collectionType() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(COLLECTION_TYPE);
parser.nextToken();
CollectionOfCollectionType result = parser.parse(CollectionOfCollectionType.class, null);
assertEquals(COLLECTION_TYPE, factory.toString(result));
// check that it is actually a linked list
LinkedList<LinkedList<String>> arr = result.arr;
LinkedList<String> linkedlist = arr.get(0);
assertEquals("a", linkedlist.get(0));
}
public static class MapOfMapType {
@Key
public Map<String, Map<String, Integer>>[] value;
}
static final String MAP_TYPE =
"{\"value\":[{\"map1\":{\"k1\":1,\"k2\":2},\"map2\":{\"kk1\":3,\"kk2\":4}}]}";
public void testParser_mapType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(MAP_TYPE);
parser.nextToken();
MapOfMapType result = parser.parse(MapOfMapType.class, null);
// serialize
assertEquals(MAP_TYPE, factory.toString(result));
// check parsed result
Map<String, Map<String, Integer>>[] value = result.value;
Map<String, Map<String, Integer>> firstMap = value[0];
Map<String, Integer> map1 = firstMap.get("map1");
Integer integer = map1.get("k1");
assertEquals(1, integer.intValue());
Map<String, Integer> map2 = firstMap.get("map2");
assertEquals(3, map2.get("kk1").intValue());
assertEquals(4, map2.get("kk2").intValue());
}
public void testParser_hashmapForMapType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(MAP_TYPE);
parser.nextToken();
@SuppressWarnings("unchecked")
HashMap<String, ArrayList<ArrayMap<String, ArrayMap<String, BigDecimal>>>> result =
parser.parse(HashMap.class, null);
// serialize
assertEquals(MAP_TYPE, factory.toString(result));
// check parsed result
ArrayList<ArrayMap<String, ArrayMap<String, BigDecimal>>> value = result.get("value");
ArrayMap<String, ArrayMap<String, BigDecimal>> firstMap = value.get(0);
ArrayMap<String, BigDecimal> map1 = firstMap.get("map1");
BigDecimal integer = map1.get("k1");
assertEquals(1, integer.intValue());
}
public static class WildCardTypes {
@Key
public Collection<? super Integer>[] lower;
@Key
public Map<String, ?> map;
@Key
public Collection<? super TreeMap<String, ? extends Integer>> mapInWild;
@Key
public Map<String, ? extends Integer> mapUpper;
@Key
public Collection<?>[] simple;
@Key
public Collection<? extends Integer>[] upper;
}
static final String WILDCARD_TYPE =
"{\"lower\":[[1,2,3]],\"map\":{\"v\":1},\"mapInWild\":[{\"v\":1}],"
+ "\"mapUpper\":{\"v\":1},\"simple\":[[1,2,3]],\"upper\":[[1,2,3]]}";
@SuppressWarnings("unchecked")
public void testParser_wildCardType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(WILDCARD_TYPE);
parser.nextToken();
WildCardTypes result = parser.parse(WildCardTypes.class, null);
// serialize
assertEquals(WILDCARD_TYPE, factory.toString(result));
// check parsed result
Collection<BigDecimal>[] simple = (Collection<BigDecimal>[]) result.simple;
ArrayList<BigDecimal> wildcard = (ArrayList<BigDecimal>) simple[0];
BigDecimal wildcardFirstValue = wildcard.get(0);
assertEquals(1, wildcardFirstValue.intValue());
Collection<Integer>[] upper = (Collection<Integer>[]) result.upper;
ArrayList<Integer> wildcardUpper = (ArrayList<Integer>) upper[0];
Integer wildcardFirstValueUpper = wildcardUpper.get(0);
assertEquals(1, wildcardFirstValueUpper.intValue());
Collection<Integer>[] lower = (Collection<Integer>[]) result.lower;
ArrayList<Integer> wildcardLower = (ArrayList<Integer>) lower[0];
Integer wildcardFirstValueLower = wildcardLower.get(0);
assertEquals(1, wildcardFirstValueLower.intValue());
Map<String, BigDecimal> map = (Map<String, BigDecimal>) result.map;
BigDecimal mapValue = map.get("v");
assertEquals(1, mapValue.intValue());
Map<String, Integer> mapUpper = (Map<String, Integer>) result.mapUpper;
Integer mapUpperValue = mapUpper.get("v");
assertEquals(1, mapUpperValue.intValue());
ArrayList<TreeMap<String, ? extends Integer>> mapInWild =
(ArrayList<TreeMap<String, ? extends Integer>>) result.mapInWild;
TreeMap<String, Integer> mapInWildFirst = (TreeMap<String, Integer>) mapInWild.get(0);
Integer mapInWildFirstValue = mapInWildFirst.get("v");
assertEquals(1, mapInWildFirstValue.intValue());
}
public static class TypeVariableType<T> {
@Key
public T[][] arr;
@Key
public LinkedList<LinkedList<T>> list;
@Key
public T nullValue;
@Key
public T value;
}
public static class IntegerTypeVariableType extends TypeVariableType<Integer> {
}
public static class IntArrayTypeVariableType extends TypeVariableType<int[]> {
}
public static class DoubleListTypeVariableType extends TypeVariableType<List<Double>> {
}
public static class FloatMapTypeVariableType extends TypeVariableType<Map<String, Float>> {
}
static final String INTEGER_TYPE_VARIABLE_TYPE =
"{\"arr\":[null,[null,1]],\"list\":[null,[null,1]],\"nullValue\":null,\"value\":1}";
static final String INT_ARRAY_TYPE_VARIABLE_TYPE =
"{\"arr\":[null,[null,[1]]],\"list\":[null,[null,[1]]],\"nullValue\":null,\"value\":[1]}";
static final String DOUBLE_LIST_TYPE_VARIABLE_TYPE =
"{\"arr\":[null,[null,[1.0]]],\"list\":[null,[null,[1.0]]],"
+ "\"nullValue\":null,\"value\":[1.0]}";
static final String FLOAT_MAP_TYPE_VARIABLE_TYPE =
"{\"arr\":[null,[null,{\"a\":1.0}]],\"list\":[null,[null,{\"a\":1.0}]],"
+ "\"nullValue\":null,\"value\":{\"a\":1.0}}";
public void testParser_integerTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(INTEGER_TYPE_VARIABLE_TYPE);
parser.nextToken();
IntegerTypeVariableType result = parser.parse(IntegerTypeVariableType.class, null);
// serialize
assertEquals(INTEGER_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
Integer[][] arr = result.arr;
assertEquals(2, arr.length);
assertEquals(Data.nullOf(Integer[].class), arr[0]);
Integer[] subArr = arr[1];
assertEquals(2, subArr.length);
assertEquals(Data.NULL_INTEGER, subArr[0]);
Integer arrValue = subArr[1];
assertEquals(1, arrValue.intValue());
// collection
LinkedList<LinkedList<Integer>> list = result.list;
assertEquals(2, list.size());
assertEquals(Data.nullOf(LinkedList.class), list.get(0));
LinkedList<Integer> subList = list.get(1);
assertEquals(2, subList.size());
assertEquals(Data.NULL_INTEGER, subList.get(0));
arrValue = subList.get(1);
assertEquals(1, arrValue.intValue());
// null value
Integer nullValue = result.nullValue;
assertEquals(Data.NULL_INTEGER, nullValue);
// value
Integer value = result.value;
assertEquals(1, value.intValue());
}
public void testParser_intArrayTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(INT_ARRAY_TYPE_VARIABLE_TYPE);
parser.nextToken();
IntArrayTypeVariableType result = parser.parse(IntArrayTypeVariableType.class, null);
// serialize
assertEquals(INT_ARRAY_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
int[][][] arr = result.arr;
assertEquals(2, arr.length);
assertEquals(Data.nullOf(int[][].class), arr[0]);
int[][] subArr = arr[1];
assertEquals(2, subArr.length);
assertEquals(Data.nullOf(int[].class), subArr[0]);
int[] arrValue = subArr[1];
assertTrue(Arrays.equals(new int[] {1}, arrValue));
// collection
LinkedList<LinkedList<int[]>> list = result.list;
assertEquals(2, list.size());
assertEquals(Data.nullOf(LinkedList.class), list.get(0));
LinkedList<int[]> subList = list.get(1);
assertEquals(2, subList.size());
assertEquals(Data.nullOf(int[].class), subList.get(0));
arrValue = subList.get(1);
assertTrue(Arrays.equals(new int[] {1}, arrValue));
// null value
int[] nullValue = result.nullValue;
assertEquals(Data.nullOf(int[].class), nullValue);
// value
int[] value = result.value;
assertTrue(Arrays.equals(new int[] {1}, value));
}
public void testParser_doubleListTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(DOUBLE_LIST_TYPE_VARIABLE_TYPE);
parser.nextToken();
DoubleListTypeVariableType result = parser.parse(DoubleListTypeVariableType.class, null);
// serialize
assertEquals(DOUBLE_LIST_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
List<Double>[][] arr = result.arr;
assertEquals(2, arr.length);
assertEquals(Data.nullOf(List[].class), arr[0]);
List<Double>[] subArr = arr[1];
assertEquals(2, subArr.length);
assertEquals(Data.nullOf(ArrayList.class), subArr[0]);
List<Double> arrValue = subArr[1];
assertEquals(1, arrValue.size());
Double dValue = arrValue.get(0);
assertEquals(1.0, dValue.doubleValue());
// collection
LinkedList<LinkedList<List<Double>>> list = result.list;
assertEquals(2, list.size());
assertEquals(Data.nullOf(LinkedList.class), list.get(0));
LinkedList<List<Double>> subList = list.get(1);
assertEquals(2, subList.size());
assertEquals(Data.nullOf(ArrayList.class), subList.get(0));
arrValue = subList.get(1);
assertEquals(ImmutableList.of(new Double(1)), arrValue);
// null value
List<Double> nullValue = result.nullValue;
assertEquals(Data.nullOf(ArrayList.class), nullValue);
// value
List<Double> value = result.value;
assertEquals(ImmutableList.of(new Double(1)), value);
}
public void testParser_floatMapTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(FLOAT_MAP_TYPE_VARIABLE_TYPE);
parser.nextToken();
FloatMapTypeVariableType result = parser.parse(FloatMapTypeVariableType.class, null);
// serialize
assertEquals(FLOAT_MAP_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
Map<String, Float>[][] arr = result.arr;
assertEquals(2, arr.length);
assertEquals(Data.nullOf(Map[].class), arr[0]);
Map<String, Float>[] subArr = arr[1];
assertEquals(2, subArr.length);
assertEquals(Data.nullOf(HashMap.class), subArr[0]);
Map<String, Float> arrValue = subArr[1];
assertEquals(1, arrValue.size());
Float fValue = arrValue.get("a");
assertEquals(1.0f, fValue.floatValue());
// collection
LinkedList<LinkedList<Map<String, Float>>> list = result.list;
assertEquals(2, list.size());
assertEquals(Data.nullOf(LinkedList.class), list.get(0));
LinkedList<Map<String, Float>> subList = list.get(1);
assertEquals(2, subList.size());
assertEquals(Data.nullOf(HashMap.class), subList.get(0));
arrValue = subList.get(1);
assertEquals(1, arrValue.size());
fValue = arrValue.get("a");
assertEquals(1.0f, fValue.floatValue());
// null value
Map<String, Float> nullValue = result.nullValue;
assertEquals(Data.nullOf(HashMap.class), nullValue);
// value
Map<String, Float> value = result.value;
assertEquals(1, value.size());
fValue = value.get("a");
assertEquals(1.0f, fValue.floatValue());
}
@SuppressWarnings("unchecked")
public void testParser_treemapForTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(INTEGER_TYPE_VARIABLE_TYPE);
parser.nextToken();
TreeMap<String, Object> result = parser.parse(TreeMap.class, null);
// serialize
assertEquals(INTEGER_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
ArrayList<Object> arr = (ArrayList<Object>) result.get("arr");
assertEquals(2, arr.size());
assertEquals(Data.nullOf(Object.class), arr.get(0));
ArrayList<BigDecimal> subArr = (ArrayList<BigDecimal>) arr.get(1);
assertEquals(2, subArr.size());
assertEquals(Data.nullOf(Object.class), subArr.get(0));
BigDecimal arrValue = subArr.get(1);
assertEquals(1, arrValue.intValue());
// null value
Object nullValue = result.get("nullValue");
assertEquals(Data.nullOf(Object.class), nullValue);
// value
BigDecimal value = (BigDecimal) result.get("value");
assertEquals(1, value.intValue());
}
public static class StringNullValue {
@Key
public String[][] arr2;
@Key
public String[] arr;
@Key
public String value;
}
static final String NULL_VALUE = "{\"arr\":[null],\"arr2\":[null,[null]],\"value\":null}";
public void testParser_nullValue() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(NULL_VALUE);
parser.nextToken();
StringNullValue result = parser.parse(StringNullValue.class, null);
// serialize
assertEquals(NULL_VALUE, factory.toString(result));
// check parsed result
assertEquals(Data.NULL_STRING, result.value);
String[] arr = result.arr;
assertEquals(1, arr.length);
assertEquals(Data.nullOf(String.class), arr[0]);
String[][] arr2 = result.arr2;
assertEquals(2, arr2.length);
assertEquals(Data.nullOf(String[].class), arr2[0]);
String[] subArr2 = arr2[1];
assertEquals(1, subArr2.length);
assertEquals(Data.NULL_STRING, subArr2[0]);
}
public enum E {
@Value
VALUE,
@Value("other")
OTHER_VALUE,
@NullValue
NULL, IGNORED_VALUE
}
public static class EnumValue {
@Key
public E value;
@Key
public E otherValue;
@Key
public E nullValue;
}
static final String ENUM_VALUE =
"{\"nullValue\":null,\"otherValue\":\"other\",\"value\":\"VALUE\"}";
public void testParser_enumValue() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(ENUM_VALUE);
parser.nextToken();
EnumValue result = parser.parse(EnumValue.class, null);
// serialize
assertEquals(ENUM_VALUE, factory.toString(result));
// check parsed result
assertEquals(E.VALUE, result.value);
assertEquals(E.OTHER_VALUE, result.otherValue);
assertEquals(E.NULL, result.nullValue);
}
public static class X<XT> {
@Key
Y<XT> y;
}
public static class Y<YT> {
@Key
Z<YT> z;
}
public static class Z<ZT> {
@Key
ZT f;
}
public static class TypeVariablesPassedAround extends X<LinkedList<String>> {
}
static final String TYPE_VARS = "{\"y\":{\"z\":{\"f\":[\"abc\"]}}}";
public void testParser_typeVariablesPassAround() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(TYPE_VARS);
parser.nextToken();
TypeVariablesPassedAround result = parser.parse(TypeVariablesPassedAround.class, null);
// serialize
assertEquals(TYPE_VARS, factory.toString(result));
// check parsed result
LinkedList<String> f = result.y.z.f;
assertEquals("abc", f.get(0));
}
static final String STRING_ARRAY = "[\"a\",\"b\",\"c\"]";
public void testParser_stringArray() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(STRING_ARRAY);
parser.nextToken();
String[] result = parser.parse(String[].class, null);
assertEquals(STRING_ARRAY, factory.toString(result));
// check types and values
assertTrue(Arrays.equals(new String[] {"a", "b", "c"}, result));
}
static final String INT_ARRAY = "[1,2,3]";
public void testParser_intArray() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(INT_ARRAY);
parser.nextToken();
int[] result = parser.parse(int[].class, null);
assertEquals(INT_ARRAY, factory.toString(result));
// check types and values
assertTrue(Arrays.equals(new int[] {1, 2, 3}, result));
}
private static final String EMPTY_ARRAY = "[]";
public void testParser_emptyArray() throws IOException {
JsonFactory factory = newFactory();
String[] result = factory.createJsonParser(EMPTY_ARRAY).parse(String[].class, null);
assertEquals(EMPTY_ARRAY, factory.toString(result));
// check types and values
assertEquals(0, result.length);
}
public void testParser_partialEmptyArray() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(EMPTY_ARRAY);
parser.nextToken();
parser.nextToken();
// token is now end_array
String[] result = parser.parse(String[].class, null);
assertEquals(EMPTY_ARRAY, factory.toString(result));
// check types and values
assertEquals(0, result.length);
}
private static final String NUMBER_TOP_VALUE = "1";
public void testParser_num() throws IOException {
JsonFactory factory = newFactory();
int result = factory.createJsonParser(NUMBER_TOP_VALUE).parse(int.class, null);
assertEquals(NUMBER_TOP_VALUE, factory.toString(result));
// check types and values
assertEquals(1, result);
}
private static final String STRING_TOP_VALUE = "\"a\"";
public void testParser_string() throws IOException {
JsonFactory factory = newFactory();
String result = factory.createJsonParser(STRING_TOP_VALUE).parse(String.class, null);
assertEquals(STRING_TOP_VALUE, factory.toString(result));
// check types and values
assertEquals("a", result);
}
private static final String NULL_TOP_VALUE = "null";
public void testParser_null() throws IOException {
JsonFactory factory = newFactory();
String result = factory.createJsonParser(NULL_TOP_VALUE).parse(String.class, null);
assertEquals(NULL_TOP_VALUE, factory.toString(result));
// check types and values
assertTrue(Data.isNull(result));
}
private static final String BOOL_TOP_VALUE = "true";
public void testParser_bool() throws IOException {
JsonFactory factory = newFactory();
boolean result = factory.createJsonParser(BOOL_TOP_VALUE).parse(boolean.class, null);
assertEquals(BOOL_TOP_VALUE, factory.toString(result));
// check types and values
assertTrue(result);
}
public final void testGenerateEntry() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonGenerator generator = newFactory().createJsonGenerator(out, Charsets.UTF_8);
Entry entry = new Entry();
entry.title = "foo";
generator.serialize(entry);
generator.flush();
assertEquals(JSON_ENTRY, new String(out.toByteArray()));
}
public final void testGenerateFeed() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonGenerator generator = newFactory().createJsonGenerator(out, Charsets.UTF_8);
Feed feed = new Feed();
Entry entryFoo = new Entry();
entryFoo.title = "foo";
Entry entryBar = new Entry();
entryBar.title = "bar";
feed.entries = new ArrayList<Entry>();
feed.entries.add(entryFoo);
feed.entries.add(entryBar);
generator.serialize(feed);
generator.flush();
assertEquals(JSON_FEED, new String(out.toByteArray()));
}
public final void testToString_entry() throws Exception {
Entry entry = new Entry();
entry.title = "foo";
assertEquals(JSON_ENTRY, newFactory().toString(entry));
}
public final void testToString_Feed() throws Exception {
Feed feed = new Feed();
Entry entryFoo = new Entry();
entryFoo.title = "foo";
Entry entryBar = new Entry();
entryBar.title = "bar";
feed.entries = new ArrayList<Entry>();
feed.entries.add(entryFoo);
feed.entries.add(entryBar);
assertEquals(JSON_FEED, newFactory().toString(feed));
}
public final void testToByteArray_entry() throws Exception {
Entry entry = new Entry();
entry.title = "foo";
assertTrue(
Arrays.equals(StringUtils.getBytesUtf8(JSON_ENTRY), newFactory().toByteArray(entry)));
}
public final void testToPrettyString_entryApproximate() throws Exception {
Entry entry = new Entry();
entry.title = "foo";
JsonFactory factory = newFactory();
String prettyString = factory.toPrettyString(entry);
assertEquals(JSON_ENTRY, factory.toString(factory.fromString(prettyString, Entry.class)));
}
public final void testToPrettyString_FeedApproximate() throws Exception {
Feed feed = new Feed();
Entry entryFoo = new Entry();
entryFoo.title = "foo";
Entry entryBar = new Entry();
entryBar.title = "bar";
feed.entries = new ArrayList<Entry>();
feed.entries.add(entryFoo);
feed.entries.add(entryBar);
JsonFactory factory = newFactory();
String prettyString = factory.toPrettyString(feed);
assertEquals(JSON_FEED, factory.toString(factory.fromString(prettyString, Feed.class)));
}
public void testParser_nullInputStream() throws IOException {
try {
newFactory().createJsonParser((InputStream) null, Charsets.UTF_8);
fail("expected " + NullPointerException.class);
} catch (NullPointerException e) {
// expected
}
}
public void testParser_nullString() throws IOException {
try {
newFactory().createJsonParser((String) null);
fail("expected " + NullPointerException.class);
} catch (NullPointerException e) {
// expected
}
}
public void testParser_nullReader() throws IOException {
try {
newFactory().createJsonParser((Reader) null);
fail("expected " + NullPointerException.class);
} catch (NullPointerException e) {
// expected
}
}
public void testObjectParserParse_entry() throws Exception {
Entry entry = (Entry) newFactory().createJsonObjectParser()
.parseAndClose(new StringReader(JSON_ENTRY), new TypeToken<Entry>() {}.getType());
assertEquals("foo", entry.title);
}
public void testObjectParserParse_stringList() throws IOException {
JsonFactory factory = newFactory();
@SuppressWarnings("unchecked")
List<String> result = (List<String>) factory.createJsonObjectParser()
.parseAndClose(new StringReader(STRING_ARRAY), new TypeToken<List<String>>() {}.getType());
@SuppressWarnings("unused")
String string = result.get(0);
assertEquals(STRING_ARRAY, factory.toString(result));
// check types and values
assertTrue(ImmutableList.of("a", "b", "c").equals(result));
}
}
| google-http-client/src/test/java/com/google/api/client/json/AbstractJsonFactoryTest.java | /*
* Copyright (c) 2010 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 com.google.api.client.json;
import com.google.api.client.util.ArrayMap;
import com.google.api.client.util.Data;
import com.google.api.client.util.Key;
import com.google.api.client.util.NullValue;
import com.google.api.client.util.StringUtils;
import com.google.api.client.util.Value;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.UnsignedInteger;
import com.google.common.primitives.UnsignedLong;
import junit.framework.TestCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Abstract test case for testing a {@link JsonFactory}.
*
* @author Yaniv Inbar
*/
public abstract class AbstractJsonFactoryTest extends TestCase {
public AbstractJsonFactoryTest(String name) {
super(name);
}
protected abstract JsonFactory newFactory();
private static final String EMPTY = "";
public void testParse_empty() throws IOException {
JsonParser parser = newFactory().createJsonParser(EMPTY);
parser.nextToken();
try {
parser.parseAndClose(HashMap.class, null);
fail("expected " + IllegalArgumentException.class);
} catch (IllegalArgumentException e) {
// expected
}
}
private static final String EMPTY_OBJECT = "{}";
public void testParse_emptyMap() throws IOException {
JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT);
parser.nextToken();
@SuppressWarnings("unchecked")
HashMap<String, Object> map = parser.parseAndClose(HashMap.class, null);
assertTrue(map.isEmpty());
}
public void testParse_emptyGenericJson() throws IOException {
JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT);
parser.nextToken();
GenericJson json = parser.parseAndClose(GenericJson.class, null);
assertTrue(json.isEmpty());
}
public void testParser_partialEmpty() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(EMPTY_OBJECT);
parser.nextToken();
parser.nextToken();
// current token is now end_object
@SuppressWarnings("unchecked")
HashMap<String, Object> result = parser.parseAndClose(HashMap.class, null);
assertEquals(EMPTY_OBJECT, factory.toString(result));
// check types and values
assertTrue(result.isEmpty());
}
private static final String JSON_ENTRY = "{\"title\":\"foo\"}";
private static final String JSON_FEED =
"{\"entries\":[" + "{\"title\":\"foo\"}," + "{\"title\":\"bar\"}]}";
public void testParseEntry() throws Exception {
Entry entry = newFactory().createJsonParser(JSON_ENTRY).parseAndClose(Entry.class, null);
assertEquals("foo", entry.title);
}
public void testParser_partialEntry() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.nextToken();
// current token is now field_name
Entry result = parser.parseAndClose(Entry.class, null);
assertEquals(JSON_ENTRY, factory.toString(result));
// check types and values
assertEquals("foo", result.title);
}
public void testParseFeed() throws Exception {
JsonParser parser = newFactory().createJsonParser(JSON_FEED);
parser.nextToken();
Feed feed = parser.parseAndClose(Feed.class, null);
Iterator<Entry> iterator = feed.entries.iterator();
assertEquals("foo", iterator.next().title);
assertEquals("bar", iterator.next().title);
assertFalse(iterator.hasNext());
}
@SuppressWarnings("unchecked")
public void testParseEntryAsMap() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
HashMap<String, Object> map = parser.parseAndClose(HashMap.class, null);
assertEquals("foo", map.remove("title"));
assertTrue(map.isEmpty());
}
public void testSkipToKey_missingEmpty() throws IOException {
JsonParser parser = newFactory().createJsonParser(EMPTY_OBJECT);
parser.nextToken();
parser.skipToKey("missing");
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
}
public void testSkipToKey_missing() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.skipToKey("missing");
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
}
public void testSkipToKey_found() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.skipToKey("title");
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
assertEquals("foo", parser.getText());
}
public void testSkipToKey_startWithFieldName() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.nextToken();
parser.skipToKey("title");
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
assertEquals("foo", parser.getText());
}
public void testSkipChildren_string() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.skipToKey("title");
parser.skipChildren();
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
assertEquals("foo", parser.getText());
}
public void testSkipChildren_object() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_ENTRY);
parser.nextToken();
parser.skipChildren();
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
}
public void testSkipChildren_array() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_FEED);
parser.nextToken();
parser.skipToKey("entries");
parser.skipChildren();
assertEquals(JsonToken.END_ARRAY, parser.getCurrentToken());
}
public void testNextToken() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_FEED);
assertEquals(JsonToken.START_OBJECT, parser.nextToken());
assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
assertEquals(JsonToken.START_ARRAY, parser.nextToken());
assertEquals(JsonToken.START_OBJECT, parser.nextToken());
assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
assertEquals(JsonToken.END_OBJECT, parser.nextToken());
assertEquals(JsonToken.START_OBJECT, parser.nextToken());
assertEquals(JsonToken.FIELD_NAME, parser.nextToken());
assertEquals(JsonToken.VALUE_STRING, parser.nextToken());
assertEquals(JsonToken.END_OBJECT, parser.nextToken());
assertEquals(JsonToken.END_ARRAY, parser.nextToken());
assertEquals(JsonToken.END_OBJECT, parser.nextToken());
assertNull(parser.nextToken());
}
public void testCurrentToken() throws IOException {
JsonParser parser = newFactory().createJsonParser(JSON_FEED);
assertNull(parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.START_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.FIELD_NAME, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.START_ARRAY, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.START_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.FIELD_NAME, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.START_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.FIELD_NAME, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.VALUE_STRING, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.END_ARRAY, parser.getCurrentToken());
parser.nextToken();
assertEquals(JsonToken.END_OBJECT, parser.getCurrentToken());
parser.nextToken();
assertNull(parser.getCurrentToken());
}
public static class Entry {
@Key
public String title;
}
public static class Feed {
@Key
public Collection<Entry> entries;
}
public static class A {
@Key
public Map<String, String> map;
}
static final String CONTAINED_MAP = "{\"map\":{\"title\":\"foo\"}}";
public void testParse() throws IOException {
JsonParser parser = newFactory().createJsonParser(CONTAINED_MAP);
parser.nextToken();
A a = parser.parse(A.class, null);
assertEquals(ImmutableMap.of("title", "foo"), a.map);
}
public static class NumberTypes {
@Key
byte byteValue;
@Key
Byte byteObjValue;
@Key
short shortValue;
@Key
Short shortObjValue;
@Key
int intValue;
@Key
Integer intObjValue;
@Key
float floatValue;
@Key
Float floatObjValue;
@Key
long longValue;
@Key
Long longObjValue;
@Key
double doubleValue;
@Key
Double doubleObjValue;
@Key
BigInteger bigIntegerValue;
@Key
UnsignedInteger unsignedIntegerValue;
@Key
UnsignedLong unsignedLongValue;
@Key
BigDecimal bigDecimalValue;
@Key("yetAnotherBigDecimalValue")
BigDecimal anotherBigDecimalValue;
}
public static class NumberTypesAsString {
@Key
@JsonString
byte byteValue;
@Key
@JsonString
Byte byteObjValue;
@Key
@JsonString
short shortValue;
@Key
@JsonString
Short shortObjValue;
@Key
@JsonString
int intValue;
@Key
@JsonString
Integer intObjValue;
@Key
@JsonString
float floatValue;
@Key
@JsonString
Float floatObjValue;
@Key
@JsonString
long longValue;
@Key
@JsonString
Long longObjValue;
@Key
@JsonString
double doubleValue;
@Key
@JsonString
Double doubleObjValue;
@Key
@JsonString
BigInteger bigIntegerValue;
@Key
@JsonString
UnsignedInteger unsignedIntegerValue;
@Key
@JsonString
UnsignedLong unsignedLongValue;
@Key
@JsonString
BigDecimal bigDecimalValue;
@Key("yetAnotherBigDecimalValue")
@JsonString
BigDecimal anotherBigDecimalValue;
}
static final String NUMBER_TYPES =
"{\"bigDecimalValue\":1.0,\"bigIntegerValue\":1,\"byteObjValue\":1,\"byteValue\":1,"
+ "\"doubleObjValue\":1.0,\"doubleValue\":1.0,\"floatObjValue\":1.0,\"floatValue\":1.0,"
+ "\"intObjValue\":1,\"intValue\":1,\"longObjValue\":1,\"longValue\":1,"
+ "\"shortObjValue\":1,\"shortValue\":1,\"unsignedIntegerValue\":1,\"unsignedLongValue\":1,"
+ "\"yetAnotherBigDecimalValue\":1}";
static final String NUMBER_TYPES_AS_STRING =
"{\"bigDecimalValue\":\"1.0\",\"bigIntegerValue\":\"1\",\"byteObjValue\":\"1\","
+ "\"byteValue\":\"1\",\"doubleObjValue\":\"1.0\",\"doubleValue\":\"1.0\","
+ "\"floatObjValue\":\"1.0\",\"floatValue\":\"1.0\",\"intObjValue\":\"1\","
+ "\"intValue\":\"1\",\"longObjValue\":\"1\",\"longValue\":\"1\",\"shortObjValue\":\"1\","
+ "\"shortValue\":\"1\",\"unsignedIntegerValue\":\"1\",\"unsignedLongValue\":\"1\","
+ "\"yetAnotherBigDecimalValue\":\"1\"}";
public void testParser_numberTypes() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
// number types
parser = factory.createJsonParser(NUMBER_TYPES);
parser.nextToken();
NumberTypes result = parser.parse(NumberTypes.class, null);
assertEquals(NUMBER_TYPES, factory.toString(result));
// number types as string
parser = factory.createJsonParser(NUMBER_TYPES_AS_STRING);
parser.nextToken();
NumberTypesAsString resultAsString = parser.parse(NumberTypesAsString.class, null);
assertEquals(NUMBER_TYPES_AS_STRING, factory.toString(resultAsString));
// number types with @JsonString
try {
parser = factory.createJsonParser(NUMBER_TYPES_AS_STRING);
parser.nextToken();
parser.parse(NumberTypes.class, null);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
// number types as string without @JsonString
try {
parser = factory.createJsonParser(NUMBER_TYPES);
parser.nextToken();
parser.parse(NumberTypesAsString.class, null);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
public void testToFromString() throws IOException {
JsonFactory factory = newFactory();
NumberTypes result = factory.fromString(NUMBER_TYPES, NumberTypes.class);
assertEquals(NUMBER_TYPES, factory.toString(result));
}
private static final String UTF8_VALUE = "123\u05D9\u05e0\u05D9\u05D1";
private static final String UTF8_JSON = "{\"value\":\"" + UTF8_VALUE + "\"}";
public void testToFromString_UTF8() throws IOException {
JsonFactory factory = newFactory();
GenericJson result = factory.fromString(UTF8_JSON, GenericJson.class);
assertEquals(UTF8_VALUE, result.get("value"));
assertEquals(UTF8_JSON, factory.toString(result));
}
public static class AnyType {
@Key
public Object arr;
@Key
public Object bool;
@Key
public Object num;
@Key
public Object obj;
@Key
public Object str;
@Key
public Object nul;
}
static final String ANY_TYPE = "{\"arr\":[1],\"bool\":true,\"nul\":null,\"num\":5,"
+ "\"obj\":{\"key\":\"value\"},\"str\":\"value\"}";
public void testParser_anyType() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(ANY_TYPE);
parser.nextToken();
AnyType result = parser.parse(AnyType.class, null);
assertEquals(ANY_TYPE, factory.toString(result));
}
public static class ArrayType {
@Key
int[] arr;
@Key
int[][] arr2;
@Key
public Integer[] integerArr;
}
static final String ARRAY_TYPE = "{\"arr\":[4,5],\"arr2\":[[1,2],[3]],\"integerArr\":[6,7]}";
public void testParser_arrayType() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(ARRAY_TYPE);
parser.nextToken();
ArrayType result = parser.parse(ArrayType.class, null);
assertEquals(ARRAY_TYPE, factory.toString(result));
// check types and values
int[] arr = result.arr;
assertTrue(Arrays.equals(new int[] {4, 5}, arr));
int[][] arr2 = result.arr2;
assertEquals(2, arr2.length);
int[] arr20 = arr2[0];
assertEquals(2, arr20.length);
int arr200 = arr20[0];
assertEquals(1, arr200);
assertEquals(2, arr20[1]);
int[] arr21 = arr2[1];
assertEquals(1, arr21.length);
assertEquals(3, arr21[0]);
Integer[] integerArr = result.integerArr;
assertEquals(2, integerArr.length);
assertEquals(6, integerArr[0].intValue());
}
public static class CollectionOfCollectionType {
@Key
public LinkedList<LinkedList<String>> arr;
}
static final String COLLECTION_TYPE = "{\"arr\":[[\"a\",\"b\"],[\"c\"]]}";
public void testParser_collectionType() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(COLLECTION_TYPE);
parser.nextToken();
CollectionOfCollectionType result = parser.parse(CollectionOfCollectionType.class, null);
assertEquals(COLLECTION_TYPE, factory.toString(result));
// check that it is actually a linked list
LinkedList<LinkedList<String>> arr = result.arr;
LinkedList<String> linkedlist = arr.get(0);
assertEquals("a", linkedlist.get(0));
}
public static class MapOfMapType {
@Key
public Map<String, Map<String, Integer>>[] value;
}
static final String MAP_TYPE =
"{\"value\":[{\"map1\":{\"k1\":1,\"k2\":2},\"map2\":{\"kk1\":3,\"kk2\":4}}]}";
public void testParser_mapType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(MAP_TYPE);
parser.nextToken();
MapOfMapType result = parser.parse(MapOfMapType.class, null);
// serialize
assertEquals(MAP_TYPE, factory.toString(result));
// check parsed result
Map<String, Map<String, Integer>>[] value = result.value;
Map<String, Map<String, Integer>> firstMap = value[0];
Map<String, Integer> map1 = firstMap.get("map1");
Integer integer = map1.get("k1");
assertEquals(1, integer.intValue());
Map<String, Integer> map2 = firstMap.get("map2");
assertEquals(3, map2.get("kk1").intValue());
assertEquals(4, map2.get("kk2").intValue());
}
public void testParser_hashmapForMapType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(MAP_TYPE);
parser.nextToken();
@SuppressWarnings("unchecked")
HashMap<String, ArrayList<ArrayMap<String, ArrayMap<String, BigDecimal>>>> result =
parser.parse(HashMap.class, null);
// serialize
assertEquals(MAP_TYPE, factory.toString(result));
// check parsed result
ArrayList<ArrayMap<String, ArrayMap<String, BigDecimal>>> value = result.get("value");
ArrayMap<String, ArrayMap<String, BigDecimal>> firstMap = value.get(0);
ArrayMap<String, BigDecimal> map1 = firstMap.get("map1");
BigDecimal integer = map1.get("k1");
assertEquals(1, integer.intValue());
}
public static class WildCardTypes {
@Key
public Collection<? super Integer>[] lower;
@Key
public Map<String, ?> map;
@Key
public Collection<? super TreeMap<String, ? extends Integer>> mapInWild;
@Key
public Map<String, ? extends Integer> mapUpper;
@Key
public Collection<?>[] simple;
@Key
public Collection<? extends Integer>[] upper;
}
static final String WILDCARD_TYPE =
"{\"lower\":[[1,2,3]],\"map\":{\"v\":1},\"mapInWild\":[{\"v\":1}],"
+ "\"mapUpper\":{\"v\":1},\"simple\":[[1,2,3]],\"upper\":[[1,2,3]]}";
@SuppressWarnings("unchecked")
public void testParser_wildCardType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(WILDCARD_TYPE);
parser.nextToken();
WildCardTypes result = parser.parse(WildCardTypes.class, null);
// serialize
assertEquals(WILDCARD_TYPE, factory.toString(result));
// check parsed result
Collection<BigDecimal>[] simple = (Collection<BigDecimal>[]) result.simple;
ArrayList<BigDecimal> wildcard = (ArrayList<BigDecimal>) simple[0];
BigDecimal wildcardFirstValue = wildcard.get(0);
assertEquals(1, wildcardFirstValue.intValue());
Collection<Integer>[] upper = (Collection<Integer>[]) result.upper;
ArrayList<Integer> wildcardUpper = (ArrayList<Integer>) upper[0];
Integer wildcardFirstValueUpper = wildcardUpper.get(0);
assertEquals(1, wildcardFirstValueUpper.intValue());
Collection<Integer>[] lower = (Collection<Integer>[]) result.lower;
ArrayList<Integer> wildcardLower = (ArrayList<Integer>) lower[0];
Integer wildcardFirstValueLower = wildcardLower.get(0);
assertEquals(1, wildcardFirstValueLower.intValue());
Map<String, BigDecimal> map = (Map<String, BigDecimal>) result.map;
BigDecimal mapValue = map.get("v");
assertEquals(1, mapValue.intValue());
Map<String, Integer> mapUpper = (Map<String, Integer>) result.mapUpper;
Integer mapUpperValue = mapUpper.get("v");
assertEquals(1, mapUpperValue.intValue());
ArrayList<TreeMap<String, ? extends Integer>> mapInWild =
(ArrayList<TreeMap<String, ? extends Integer>>) result.mapInWild;
TreeMap<String, Integer> mapInWildFirst = (TreeMap<String, Integer>) mapInWild.get(0);
Integer mapInWildFirstValue = mapInWildFirst.get("v");
assertEquals(1, mapInWildFirstValue.intValue());
}
public static class TypeVariableType<T> {
@Key
public T[][] arr;
@Key
public LinkedList<LinkedList<T>> list;
@Key
public T nullValue;
@Key
public T value;
}
public static class IntegerTypeVariableType extends TypeVariableType<Integer> {
}
public static class IntArrayTypeVariableType extends TypeVariableType<int[]> {
}
public static class DoubleListTypeVariableType extends TypeVariableType<List<Double>> {
}
public static class FloatMapTypeVariableType extends TypeVariableType<Map<String, Float>> {
}
static final String INTEGER_TYPE_VARIABLE_TYPE =
"{\"arr\":[null,[null,1]],\"list\":[null,[null,1]],\"nullValue\":null,\"value\":1}";
static final String INT_ARRAY_TYPE_VARIABLE_TYPE =
"{\"arr\":[null,[null,[1]]],\"list\":[null,[null,[1]]],\"nullValue\":null,\"value\":[1]}";
static final String DOUBLE_LIST_TYPE_VARIABLE_TYPE =
"{\"arr\":[null,[null,[1.0]]],\"list\":[null,[null,[1.0]]],"
+ "\"nullValue\":null,\"value\":[1.0]}";
static final String FLOAT_MAP_TYPE_VARIABLE_TYPE =
"{\"arr\":[null,[null,{\"a\":1.0}]],\"list\":[null,[null,{\"a\":1.0}]],"
+ "\"nullValue\":null,\"value\":{\"a\":1.0}}";
public void testParser_integerTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(INTEGER_TYPE_VARIABLE_TYPE);
parser.nextToken();
IntegerTypeVariableType result = parser.parse(IntegerTypeVariableType.class, null);
// serialize
assertEquals(INTEGER_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
Integer[][] arr = result.arr;
assertEquals(2, arr.length);
assertEquals(Data.nullOf(Integer[].class), arr[0]);
Integer[] subArr = arr[1];
assertEquals(2, subArr.length);
assertEquals(Data.NULL_INTEGER, subArr[0]);
Integer arrValue = subArr[1];
assertEquals(1, arrValue.intValue());
// collection
LinkedList<LinkedList<Integer>> list = result.list;
assertEquals(2, list.size());
assertEquals(Data.nullOf(LinkedList.class), list.get(0));
LinkedList<Integer> subList = list.get(1);
assertEquals(2, subList.size());
assertEquals(Data.NULL_INTEGER, subList.get(0));
arrValue = subList.get(1);
assertEquals(1, arrValue.intValue());
// null value
Integer nullValue = result.nullValue;
assertEquals(Data.NULL_INTEGER, nullValue);
// value
Integer value = result.value;
assertEquals(1, value.intValue());
}
public void testParser_intArrayTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(INT_ARRAY_TYPE_VARIABLE_TYPE);
parser.nextToken();
IntArrayTypeVariableType result = parser.parse(IntArrayTypeVariableType.class, null);
// serialize
assertEquals(INT_ARRAY_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
int[][][] arr = result.arr;
assertEquals(2, arr.length);
assertEquals(Data.nullOf(int[][].class), arr[0]);
int[][] subArr = arr[1];
assertEquals(2, subArr.length);
assertEquals(Data.nullOf(int[].class), subArr[0]);
int[] arrValue = subArr[1];
assertTrue(Arrays.equals(new int[] {1}, arrValue));
// collection
LinkedList<LinkedList<int[]>> list = result.list;
assertEquals(2, list.size());
assertEquals(Data.nullOf(LinkedList.class), list.get(0));
LinkedList<int[]> subList = list.get(1);
assertEquals(2, subList.size());
assertEquals(Data.nullOf(int[].class), subList.get(0));
arrValue = subList.get(1);
assertTrue(Arrays.equals(new int[] {1}, arrValue));
// null value
int[] nullValue = result.nullValue;
assertEquals(Data.nullOf(int[].class), nullValue);
// value
int[] value = result.value;
assertTrue(Arrays.equals(new int[] {1}, value));
}
public void testParser_doubleListTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(DOUBLE_LIST_TYPE_VARIABLE_TYPE);
parser.nextToken();
DoubleListTypeVariableType result = parser.parse(DoubleListTypeVariableType.class, null);
// serialize
assertEquals(DOUBLE_LIST_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
List<Double>[][] arr = result.arr;
assertEquals(2, arr.length);
assertEquals(Data.nullOf(List[].class), arr[0]);
List<Double>[] subArr = arr[1];
assertEquals(2, subArr.length);
assertEquals(Data.nullOf(ArrayList.class), subArr[0]);
List<Double> arrValue = subArr[1];
assertEquals(1, arrValue.size());
Double dValue = arrValue.get(0);
assertEquals(1.0, dValue.doubleValue());
// collection
LinkedList<LinkedList<List<Double>>> list = result.list;
assertEquals(2, list.size());
assertEquals(Data.nullOf(LinkedList.class), list.get(0));
LinkedList<List<Double>> subList = list.get(1);
assertEquals(2, subList.size());
assertEquals(Data.nullOf(ArrayList.class), subList.get(0));
arrValue = subList.get(1);
assertEquals(ImmutableList.of(new Double(1)), arrValue);
// null value
List<Double> nullValue = result.nullValue;
assertEquals(Data.nullOf(ArrayList.class), nullValue);
// value
List<Double> value = result.value;
assertEquals(ImmutableList.of(new Double(1)), value);
}
public void testParser_floatMapTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(FLOAT_MAP_TYPE_VARIABLE_TYPE);
parser.nextToken();
FloatMapTypeVariableType result = parser.parse(FloatMapTypeVariableType.class, null);
// serialize
assertEquals(FLOAT_MAP_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
Map<String, Float>[][] arr = result.arr;
assertEquals(2, arr.length);
assertEquals(Data.nullOf(Map[].class), arr[0]);
Map<String, Float>[] subArr = arr[1];
assertEquals(2, subArr.length);
assertEquals(Data.nullOf(HashMap.class), subArr[0]);
Map<String, Float> arrValue = subArr[1];
assertEquals(1, arrValue.size());
Float fValue = arrValue.get("a");
assertEquals(1.0f, fValue.floatValue());
// collection
LinkedList<LinkedList<Map<String, Float>>> list = result.list;
assertEquals(2, list.size());
assertEquals(Data.nullOf(LinkedList.class), list.get(0));
LinkedList<Map<String, Float>> subList = list.get(1);
assertEquals(2, subList.size());
assertEquals(Data.nullOf(HashMap.class), subList.get(0));
arrValue = subList.get(1);
assertEquals(1, arrValue.size());
fValue = arrValue.get("a");
assertEquals(1.0f, fValue.floatValue());
// null value
Map<String, Float> nullValue = result.nullValue;
assertEquals(Data.nullOf(HashMap.class), nullValue);
// value
Map<String, Float> value = result.value;
assertEquals(1, value.size());
fValue = value.get("a");
assertEquals(1.0f, fValue.floatValue());
}
@SuppressWarnings("unchecked")
public void testParser_treemapForTypeVariableType() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(INTEGER_TYPE_VARIABLE_TYPE);
parser.nextToken();
TreeMap<String, Object> result = parser.parse(TreeMap.class, null);
// serialize
assertEquals(INTEGER_TYPE_VARIABLE_TYPE, factory.toString(result));
// check parsed result
// array
ArrayList<Object> arr = (ArrayList<Object>) result.get("arr");
assertEquals(2, arr.size());
assertEquals(Data.nullOf(Object.class), arr.get(0));
ArrayList<BigDecimal> subArr = (ArrayList<BigDecimal>) arr.get(1);
assertEquals(2, subArr.size());
assertEquals(Data.nullOf(Object.class), subArr.get(0));
BigDecimal arrValue = subArr.get(1);
assertEquals(1, arrValue.intValue());
// null value
Object nullValue = result.get("nullValue");
assertEquals(Data.nullOf(Object.class), nullValue);
// value
BigDecimal value = (BigDecimal) result.get("value");
assertEquals(1, value.intValue());
}
public static class StringNullValue {
@Key
public String[][] arr2;
@Key
public String[] arr;
@Key
public String value;
}
static final String NULL_VALUE = "{\"arr\":[null],\"arr2\":[null,[null]],\"value\":null}";
public void testParser_nullValue() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(NULL_VALUE);
parser.nextToken();
StringNullValue result = parser.parse(StringNullValue.class, null);
// serialize
assertEquals(NULL_VALUE, factory.toString(result));
// check parsed result
assertEquals(Data.NULL_STRING, result.value);
String[] arr = result.arr;
assertEquals(1, arr.length);
assertEquals(Data.nullOf(String.class), arr[0]);
String[][] arr2 = result.arr2;
assertEquals(2, arr2.length);
assertEquals(Data.nullOf(String[].class), arr2[0]);
String[] subArr2 = arr2[1];
assertEquals(1, subArr2.length);
assertEquals(Data.NULL_STRING, subArr2[0]);
}
public enum E {
@Value
VALUE,
@Value("other")
OTHER_VALUE,
@NullValue
NULL, IGNORED_VALUE
}
public static class EnumValue {
@Key
public E value;
@Key
public E otherValue;
@Key
public E nullValue;
}
static final String ENUM_VALUE =
"{\"nullValue\":null,\"otherValue\":\"other\",\"value\":\"VALUE\"}";
public void testParser_enumValue() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(ENUM_VALUE);
parser.nextToken();
EnumValue result = parser.parse(EnumValue.class, null);
// serialize
assertEquals(ENUM_VALUE, factory.toString(result));
// check parsed result
assertEquals(E.VALUE, result.value);
assertEquals(E.OTHER_VALUE, result.otherValue);
assertEquals(E.NULL, result.nullValue);
}
public static class X<XT> {
@Key
Y<XT> y;
}
public static class Y<YT> {
@Key
Z<YT> z;
}
public static class Z<ZT> {
@Key
ZT f;
}
public static class TypeVariablesPassedAround extends X<LinkedList<String>> {
}
static final String TYPE_VARS = "{\"y\":{\"z\":{\"f\":[\"abc\"]}}}";
public void testParser_typeVariablesPassAround() throws IOException {
// parse
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(TYPE_VARS);
parser.nextToken();
TypeVariablesPassedAround result = parser.parse(TypeVariablesPassedAround.class, null);
// serialize
assertEquals(TYPE_VARS, factory.toString(result));
// check parsed result
LinkedList<String> f = result.y.z.f;
assertEquals("abc", f.get(0));
}
static final String STRING_ARRAY = "[\"a\",\"b\",\"c\"]";
public void testParser_stringArray() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(STRING_ARRAY);
parser.nextToken();
String[] result = parser.parse(String[].class, null);
assertEquals(STRING_ARRAY, factory.toString(result));
// check types and values
assertTrue(Arrays.equals(new String[] {"a", "b", "c"}, result));
}
static final String INT_ARRAY = "[1,2,3]";
public void testParser_intArray() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(INT_ARRAY);
parser.nextToken();
int[] result = parser.parse(int[].class, null);
assertEquals(INT_ARRAY, factory.toString(result));
// check types and values
assertTrue(Arrays.equals(new int[] {1, 2, 3}, result));
}
private static final String EMPTY_ARRAY = "[]";
public void testParser_emptyArray() throws IOException {
JsonFactory factory = newFactory();
String[] result = factory.createJsonParser(EMPTY_ARRAY).parse(String[].class, null);
assertEquals(EMPTY_ARRAY, factory.toString(result));
// check types and values
assertEquals(0, result.length);
}
public void testParser_partialEmptyArray() throws IOException {
JsonFactory factory = newFactory();
JsonParser parser;
parser = factory.createJsonParser(EMPTY_ARRAY);
parser.nextToken();
parser.nextToken();
// token is now end_array
String[] result = parser.parse(String[].class, null);
assertEquals(EMPTY_ARRAY, factory.toString(result));
// check types and values
assertEquals(0, result.length);
}
private static final String NUMBER_TOP_VALUE = "1";
public void testParser_num() throws IOException {
JsonFactory factory = newFactory();
int result = factory.createJsonParser(NUMBER_TOP_VALUE).parse(int.class, null);
assertEquals(NUMBER_TOP_VALUE, factory.toString(result));
// check types and values
assertEquals(1, result);
}
private static final String STRING_TOP_VALUE = "\"a\"";
public void testParser_string() throws IOException {
JsonFactory factory = newFactory();
String result = factory.createJsonParser(STRING_TOP_VALUE).parse(String.class, null);
assertEquals(STRING_TOP_VALUE, factory.toString(result));
// check types and values
assertEquals("a", result);
}
private static final String NULL_TOP_VALUE = "null";
public void testParser_null() throws IOException {
JsonFactory factory = newFactory();
String result = factory.createJsonParser(NULL_TOP_VALUE).parse(String.class, null);
assertEquals(NULL_TOP_VALUE, factory.toString(result));
// check types and values
assertTrue(Data.isNull(result));
}
private static final String BOOL_TOP_VALUE = "true";
public void testParser_bool() throws IOException {
JsonFactory factory = newFactory();
boolean result = factory.createJsonParser(BOOL_TOP_VALUE).parse(boolean.class, null);
assertEquals(BOOL_TOP_VALUE, factory.toString(result));
// check types and values
assertTrue(result);
}
public final void testGenerateEntry() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonGenerator generator = newFactory().createJsonGenerator(out, Charsets.UTF_8);
Entry entry = new Entry();
entry.title = "foo";
generator.serialize(entry);
generator.flush();
assertEquals(JSON_ENTRY, new String(out.toByteArray()));
}
public final void testGenerateFeed() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonGenerator generator = newFactory().createJsonGenerator(out, Charsets.UTF_8);
Feed feed = new Feed();
Entry entryFoo = new Entry();
entryFoo.title = "foo";
Entry entryBar = new Entry();
entryBar.title = "bar";
feed.entries = new ArrayList<Entry>();
feed.entries.add(entryFoo);
feed.entries.add(entryBar);
generator.serialize(feed);
generator.flush();
assertEquals(JSON_FEED, new String(out.toByteArray()));
}
public final void testToString_entry() throws Exception {
Entry entry = new Entry();
entry.title = "foo";
assertEquals(JSON_ENTRY, newFactory().toString(entry));
}
public final void testToString_Feed() throws Exception {
Feed feed = new Feed();
Entry entryFoo = new Entry();
entryFoo.title = "foo";
Entry entryBar = new Entry();
entryBar.title = "bar";
feed.entries = new ArrayList<Entry>();
feed.entries.add(entryFoo);
feed.entries.add(entryBar);
assertEquals(JSON_FEED, newFactory().toString(feed));
}
public final void testToByteArray_entry() throws Exception {
Entry entry = new Entry();
entry.title = "foo";
assertTrue(
Arrays.equals(StringUtils.getBytesUtf8(JSON_ENTRY), newFactory().toByteArray(entry)));
}
public final void testToPrettyString_entryApproximate() throws Exception {
Entry entry = new Entry();
entry.title = "foo";
JsonFactory factory = newFactory();
String prettyString = factory.toPrettyString(entry);
assertEquals(JSON_ENTRY, factory.toString(factory.fromString(prettyString, Entry.class)));
}
public final void testToPrettyString_FeedApproximate() throws Exception {
Feed feed = new Feed();
Entry entryFoo = new Entry();
entryFoo.title = "foo";
Entry entryBar = new Entry();
entryBar.title = "bar";
feed.entries = new ArrayList<Entry>();
feed.entries.add(entryFoo);
feed.entries.add(entryBar);
JsonFactory factory = newFactory();
String prettyString = factory.toPrettyString(feed);
assertEquals(JSON_FEED, factory.toString(factory.fromString(prettyString, Feed.class)));
}
public void testParser_nullInputStream() throws IOException {
try {
newFactory().createJsonParser((InputStream) null, Charsets.UTF_8);
fail("expected " + NullPointerException.class);
} catch (NullPointerException e) {
// expected
}
}
public void testParser_nullString() throws IOException {
try {
newFactory().createJsonParser((String) null);
fail("expected " + NullPointerException.class);
} catch (NullPointerException e) {
// expected
}
}
public void testParser_nullReader() throws IOException {
try {
newFactory().createJsonParser((Reader) null);
fail("expected " + NullPointerException.class);
} catch (NullPointerException e) {
// expected
}
}
}
| Added tests for the ObjectParser change
http://codereview.appspot.com/6307075/
| google-http-client/src/test/java/com/google/api/client/json/AbstractJsonFactoryTest.java | Added tests for the ObjectParser change http://codereview.appspot.com/6307075/ |
|
Java | apache-2.0 | 6d7abb03148a556d0e2edf90223bdc57dc489911 | 0 | leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* 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.
* </p>
*/
package io.shardingsphere.shardingproxy.runtime;
import com.google.common.eventbus.Subscribe;
import io.shardingsphere.api.config.ShardingRuleConfiguration;
import io.shardingsphere.core.constant.DatabaseType;
import io.shardingsphere.core.constant.ShardingConstant;
import io.shardingsphere.core.executor.ShardingExecuteEngine;
import io.shardingsphere.core.metadata.ShardingMetaData;
import io.shardingsphere.core.rule.DataSourceParameter;
import io.shardingsphere.core.rule.MasterSlaveRule;
import io.shardingsphere.core.rule.ShardingRule;
import io.shardingsphere.orchestration.internal.event.config.ShardingRuleChangedEvent;
import io.shardingsphere.orchestration.internal.event.state.DisabledStateEventBusEvent;
import io.shardingsphere.orchestration.internal.rule.OrchestrationMasterSlaveRule;
import io.shardingsphere.orchestration.internal.rule.OrchestrationShardingRule;
import io.shardingsphere.shardingproxy.backend.BackendExecutorContext;
import io.shardingsphere.shardingproxy.runtime.metadata.ProxyTableMetaDataConnectionManager;
import lombok.Getter;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Sharding schema.
*
* @author zhangliang
* @author zhangyonglun
* @author panjuan
* @author zhaojun
* @author wangkai
*/
@Getter
public final class ShardingSchema extends LogicSchema {
private ShardingRule shardingRule;
public ShardingSchema(final String name, final Map<String, DataSourceParameter> dataSources, final ShardingRuleConfiguration shardingRuleConfig, final boolean isUsingRegistry) {
super(name, dataSources, getShardingRule(shardingRuleConfig, dataSources.keySet(), isUsingRegistry));
shardingRule = getShardingRule(shardingRuleConfig, dataSources.keySet(), isUsingRegistry);
}
private static ShardingRule getShardingRule(final ShardingRuleConfiguration shardingRule, final Collection<String> dataSourceNames, final boolean isUsingRegistry) {
return isUsingRegistry ? new OrchestrationShardingRule(shardingRule, dataSourceNames) : new ShardingRule(shardingRule, dataSourceNames);
}
/**
* Renew sharding rule.
*
* @param shardingEvent sharding event.
*/
@Subscribe
public void renew(final ShardingRuleChangedEvent shardingEvent) {
if (!getName().equals(shardingEvent.getShardingSchemaName())) {
return;
}
shardingRule = new ShardingRule(shardingEvent.getShardingRuleConfiguration(), getDataSources().keySet());
}
/**
* Renew disabled data source names.
*
* @param disabledStateEventBusEvent jdbc disabled event bus event
*/
@Subscribe
public void renew(final DisabledStateEventBusEvent disabledStateEventBusEvent) {
Map<String, Collection<String>> disabledSchemaDataSourceMap = disabledStateEventBusEvent.getDisabledSchemaDataSourceMap();
if (!disabledSchemaDataSourceMap.keySet().contains(getName())) {
return;
}
renew(disabledSchemaDataSourceMap.get(getName()));
}
private void renew(final Collection<String> disabledDataSourceNames) {
for (MasterSlaveRule each : shardingRule.getMasterSlaveRules()) {
DisabledStateEventBusEvent eventBusEvent = new DisabledStateEventBusEvent(Collections.singletonMap(ShardingConstant.LOGIC_SCHEMA_NAME, disabledDataSourceNames));
((OrchestrationMasterSlaveRule) each).renew(eventBusEvent);
}
}
}
| sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/ShardingSchema.java | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* 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.
* </p>
*/
package io.shardingsphere.shardingproxy.runtime;
import com.google.common.eventbus.Subscribe;
import io.shardingsphere.api.config.ShardingRuleConfiguration;
import io.shardingsphere.core.constant.DatabaseType;
import io.shardingsphere.core.constant.ShardingConstant;
import io.shardingsphere.core.executor.ShardingExecuteEngine;
import io.shardingsphere.core.metadata.ShardingMetaData;
import io.shardingsphere.core.rule.DataSourceParameter;
import io.shardingsphere.core.rule.MasterSlaveRule;
import io.shardingsphere.core.rule.ShardingRule;
import io.shardingsphere.orchestration.internal.event.config.ShardingRuleChangedEvent;
import io.shardingsphere.orchestration.internal.event.state.DisabledStateEventBusEvent;
import io.shardingsphere.orchestration.internal.rule.OrchestrationMasterSlaveRule;
import io.shardingsphere.orchestration.internal.rule.OrchestrationShardingRule;
import io.shardingsphere.shardingproxy.backend.BackendExecutorContext;
import io.shardingsphere.shardingproxy.runtime.metadata.ProxyTableMetaDataConnectionManager;
import lombok.Getter;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Sharding schema.
*
* @author zhangliang
* @author zhangyonglun
* @author panjuan
* @author zhaojun
* @author wangkai
*/
@Getter
public final class ShardingSchema extends LogicSchema {
private ShardingRule shardingRule;
public ShardingSchema(final String name, final Map<String, DataSourceParameter> dataSources, final ShardingRuleConfiguration shardingRuleConfig, final boolean isUsingRegistry) {
super(name, dataSources, getShardingRule(shardingRuleConfig, dataSources.keySet(), isUsingRegistry));
shardingRule = getShardingRule(shardingRuleConfig, dataSources.keySet(), isUsingRegistry);
getShardingMetaData(BackendExecutorContext.getInstance().getExecuteEngine());
}
private static ShardingRule getShardingRule(final ShardingRuleConfiguration shardingRule, final Collection<String> dataSourceNames, final boolean isUsingRegistry) {
return isUsingRegistry ? new OrchestrationShardingRule(shardingRule, dataSourceNames) : new ShardingRule(shardingRule, dataSourceNames);
}
private ShardingMetaData getShardingMetaData(final ShardingExecuteEngine executeEngine) {
return new ShardingMetaData(getDataSourceURLs(getDataSources()), shardingRule,
DatabaseType.MySQL, executeEngine, new ProxyTableMetaDataConnectionManager(getBackendDataSource()), GlobalRegistry.getInstance().getMaxConnectionsSizePerQuery());
}
private Map<String, String> getDataSourceURLs(final Map<String, DataSourceParameter> dataSourceParameters) {
Map<String, String> result = new LinkedHashMap<>(dataSourceParameters.size(), 1);
for (Entry<String, DataSourceParameter> entry : dataSourceParameters.entrySet()) {
result.put(entry.getKey(), entry.getValue().getUrl());
}
return result;
}
/**
* Renew sharding rule.
*
* @param shardingEvent sharding event.
*/
@Subscribe
public void renew(final ShardingRuleChangedEvent shardingEvent) {
if (!getName().equals(shardingEvent.getShardingSchemaName())) {
return;
}
shardingRule = new ShardingRule(shardingEvent.getShardingRuleConfiguration(), getDataSources().keySet());
}
/**
* Renew disabled data source names.
*
* @param disabledStateEventBusEvent jdbc disabled event bus event
*/
@Subscribe
public void renew(final DisabledStateEventBusEvent disabledStateEventBusEvent) {
Map<String, Collection<String>> disabledSchemaDataSourceMap = disabledStateEventBusEvent.getDisabledSchemaDataSourceMap();
if (!disabledSchemaDataSourceMap.keySet().contains(getName())) {
return;
}
renew(disabledSchemaDataSourceMap.get(getName()));
}
private void renew(final Collection<String> disabledDataSourceNames) {
for (MasterSlaveRule each : shardingRule.getMasterSlaveRules()) {
DisabledStateEventBusEvent eventBusEvent = new DisabledStateEventBusEvent(Collections.singletonMap(ShardingConstant.LOGIC_SCHEMA_NAME, disabledDataSourceNames));
((OrchestrationMasterSlaveRule) each).renew(eventBusEvent);
}
}
}
| delete getShardingMetaData();
| sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/ShardingSchema.java | delete getShardingMetaData(); |
|
Java | apache-2.0 | 63f32840d50eef8b7e53725c483dc8a6331eef58 | 0 | oldpatricka/Gridway,oldpatricka/Gridway,oldpatricka/Gridway,oldpatricka/Gridway,oldpatricka/Gridway,oldpatricka/Gridway | /* -------------------------------------------------------------------------- */
/* Copyright 2002-2006 GridWay Team, Distributed Systems Architecture */
/* Group, Universidad Complutense de Madrid */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
import java.io.*;
import java.util.*;
import java.net.URL;
import org.apache.axis.components.uuid.UUIDGen;
import org.apache.axis.components.uuid.UUIDGenFactory;
import org.globus.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.client.BaseClient;
import org.globus.gsi.GlobusCredential;
import java.security.cert.X509Certificate;
import org.globus.delegation.DelegationUtil;
import org.globus.exec.client.GramJobListener;
import org.globus.exec.client.GramJob;
import org.globus.exec.utils.client.ManagedJobFactoryClientHelper;
import org.globus.exec.utils.ManagedJobFactoryConstants;
import org.globus.exec.utils.rsl.RSLHelper;
import org.globus.exec.generated.StateEnumeration;
import org.gridforum.jgss.ExtendedGSSCredential;
import org.gridforum.jgss.ExtendedGSSManager;
import org.ietf.jgss.GSSCredential;
class GW_mad_ws extends Thread implements GramJobListener {
private Map job_pool = null; // Job pool
private Map jid_pool = null; // JID pool
// private Long last_goodtill = 0L;
private String portNumber;
public static void main(String args[]) {
int i = 0;
String arg;
String _portNumber = "8443";
boolean error=false;
GW_mad_ws gw_mad_ws;
while (i < args.length && args[i].startsWith("-"))
{
arg = args[i++];
if (arg.equals("-p"))
{
if (i < args.length)
_portNumber = args[i++];
else
{
System.err.println("-p requires a portnumber");
error = true;
}
}
}
if (error == false)
{
gw_mad_ws = new GW_mad_ws(_portNumber);
//gw_mad_ws.start();
gw_mad_ws.loop();
//gw_mad_ws.interrupt();
}
}
// Constructor
GW_mad_ws(String portNumber) {
this.portNumber = portNumber;
// Create the job and JID pool
// Warning! With JDK1.5 should be "new HashMap<Integer,GramJob>()"
job_pool = Collections.synchronizedMap(new HashMap());
jid_pool = Collections.synchronizedMap(new HashMap());
}
void loop() {
String str = null;
String action = null;
String jid_str = null;
String contact;
String rsl_file;
boolean fin = false;
Integer jid = null;
GramJob job = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!fin) {
// Read a line a parse it
try
{
str = in.readLine();
}
catch (IOException e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized (System.out)
{
System.out.println(action + " " + jid_str + " FAILURE " + info);
}
}
String str_split[] = str.split(" ", 4);
if (str_split.length != 4)
{
synchronized (System.out)
{
System.out.println(action + " " + jid_str + " FAILURE "
+ "Error reading line");
}
fin = true;
}
else
{
action = str_split[0].toUpperCase();
jid_str = str_split[1];
contact = str_split[2];
rsl_file = str_split[3];
// Perform the action
if (action.equals("INIT"))
init();
else if (action.equals("FINALIZE"))
{
finalize_mad();
fin = true;
}
else if (action.equals("SUBMIT") || action.equals("RECOVER"))
{
try
{
jid = new Integer(jid_str);
}
catch (NumberFormatException e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized (System.out)
{
System.out.println(action + " " + jid_str + " FAILURE "
+ info);
}
}
// Create a job
try
{
if (action.equals("SUBMIT"))
{
job = new GramJob(new java.io.File(rsl_file));
}
else if (action.equals("RECOVER"))
{
job = new GramJob();
}
// Add state listener
job.addListener(this);
Service s = new Service(action, jid, job, contact, portNumber);
s.start();
// Add job and jid to the pools
job_pool.put(jid, job);
jid_pool.put(job, jid);
}
catch (Exception e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized (System.out)
{
System.out.println(action + " " + jid_str + " FAILURE "
+ info);
}
}
}
else if (action.equals("CANCEL") || action.equals("POLL"))
{
try
{
jid = new Integer(jid_str);
}
catch (NumberFormatException e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized(System.out)
{
System.out.println(action + " " + jid_str + " FAILURE "
+ info);
}
}
job = (GramJob) job_pool.get(jid);
if (job == null)
{
synchronized(System.out)
{
System.out.println(action + " " + jid + " FAILURE Job does not exist jid");
}
}
else
{
Service s = new Service(action, jid, job, contact,portNumber);
s.start();
}
}
else
{
synchronized(System.out)
{
System.out.println(action + " " + jid_str
+ " FAILURE Not valid action");
}
}
}
}
}
void init() {
// Nothing to do here
synchronized(System.out)
{
System.out.println("INIT - SUCCESS -");
}
}
void finalize_mad() {
// Nothing to do here
synchronized(System.out)
{
System.out.println("FINALIZE - SUCCESS -");
}
}
// Method from interface GramJobListener
public void stateChanged(GramJob job) {
int status;
int exitCode;
String info;
// Get job state
StateEnumeration jobState = job.getState();
String jobState_str = jobState.getValue().toUpperCase();
// Get the JID from the job
Integer jid = (Integer) jid_pool.get(job);
if (jid == null)
{
status = 1;
info = "Job " + job.getHandle() + " does not exist";
}
else
{
if (jobState == StateEnumeration.Unsubmitted)
jobState_str = "PENDING";
if (jobState == StateEnumeration.Failed)
{
// Check if the reason is "User cancelled"
if (job.getFault() == null)
{
status = 0;
info = StateEnumeration._Done.toUpperCase();
}
else
{
status = 1;
info = job.getFault()[0].getDescription(0).toString().replace('\n', ' ');
}
}
else
{
status = 0;
info = jobState_str;
// Get job exit code
exitCode = job.getExitCode();
if(info.equals("DONE"))
info = info + ":" + exitCode;
}
}
synchronized (System.out)
{
if (status == 0)
System.out.println("CALLBACK " + jid + " SUCCESS " + info);
else if (jid == null)
System.out.println("CALLBACK - FAILURE " + info);
else
System.out.println("CALLBACK " + jid + " FAILURE " + info);
}
// If the job is done, remove it from the pool
if (jobState == StateEnumeration.Done
|| jobState == StateEnumeration.Failed)
{
job_pool.remove(jid);
jid_pool.remove(job);
try
{
job.destroy();
}
catch (Exception e)
{
//status = 1;
//info = e.getMessage().replace('\n', ' ');
}
}
}
// Not used nor needed
/*
public void run() {
Long goodtill;
GlobusCredential proxy;
ExtendedGSSManager manager;
while (true)
{
try
{
Thread.sleep(30000L);
}
catch (Exception e)
{
}
try
{
//manager = (ExtendedGSSManager)
// ExtendedGSSManager.getInstance();
proxy = GlobusCredential.getDefaultCredential();
// = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
long timeleft = proxy.getTimeLeft();
goodtill = new Long(System.currentTimeMillis() + timeleft*1000);
if (last_goodtill == 0)
{
last_goodtill = goodtill;
}
else if (goodtill > last_goodtill)
{
try
{
Iterator it = job_pool.values().iterator();
while (it.hasNext())
{
GramJob job = (GramJob) it.next();
X509Certificate certToSign =
DelegationUtil.getCertificateChainRP(null, null)[0];
DelegationUtil.refresh(proxy, certToSign, 12*60*60, false, null, null);
synchronized (System.out)
{
System.out.println("TIMER - SUCCESS Credentials refreshed until" + goodtill);
}
}
}
catch (Exception e)
{
synchronized (System.out)
{
System.out.println("TIMER - FAILURE Can't refresh credentials");
}
}
}
}
catch (Exception e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized (System.out)
{
System.out.println("TIMER - FAILURE Exception while obtaining user proxy: " + info);
}
}
}
}*/
}
class Service extends Thread {
String action, contact;
Integer jid;
GramJob job;
int status = 0;
String info;
String portNumber;
Service(String action, Integer jid, GramJob job, String contact, String portNumber) {
this.action = action;
this.jid = jid;
this.job = job;
this.contact = contact;
this.portNumber = portNumber;
}
public void run() {
// Perform the action
if (action.equals("SUBMIT"))
status = submit(jid, job, contact);
else if (action.equals("RECOVER"))
status = recover(jid, job, contact);
else if (action.equals("CANCEL"))
status = cancel(jid, job);
else if (action.equals("POLL"))
status = poll(jid, job);
else
{
status = 1;
info = "Not valid action";
}
synchronized (System.out)
{
if (status == 0)
System.out.println(action + " " + jid + " SUCCESS " + info);
else
System.out.println(action + " " + jid + " FAILURE " + info);
}
}
int submit (Integer jid, GramJob job, String contact) {
int status = 0;
int index = 0;
EndpointReferenceType factoryEndpoint = null;
info = "-";
// Default factory type is Fork
String factoryType = ManagedJobFactoryConstants.DEFAULT_FACTORY_TYPE;
// Parse resource contact string
String resource_split[] = contact.split("/");
String host = resource_split[0];
if (resource_split.length == 2)
factoryType = resource_split[1];
// Create Endpoint Reference to ManagedJobFactoryService with its
//associated ManagedJobFactoryResource
try
{
// Due to Bug 4919: Error in job submission (GRAM-WS)
//URL factoryURL =
// ManagedJobFactoryClientHelper.getServiceURL(host).getURL();
URL factoryURL = new URL("https://" + host
+ ":"+portNumber+"/wsrf/services/ManagedJobFactoryService");
factoryEndpoint =
ManagedJobFactoryClientHelper.getFactoryEndpoint(factoryURL,
factoryType);
}
catch (Exception e)
{
info = e.getMessage().replace('\n', ' ');
status = 1;
}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR , calendar.get(Calendar.WEEK_OF_YEAR) + 1);
job.setTerminationTime(calendar.getTime()); // One week
// Submit the job
try
{
job.submit(factoryEndpoint, false, false, null);
info = job.getHandle();
}
catch (Exception e)
{
info = e.getMessage().replace('\n', ' ');
status = 1;
}
return status;
}
int recover (Integer jid, GramJob job, String handle) {
// Bind to the job and getting its status
try
{
job.setHandle(handle);
job.bind();
job.refreshStatus();
StateEnumeration jobState = job.getState();
info = jobState.getValue().toUpperCase();
if (jobState == StateEnumeration.Unsubmitted)
info = "PENDING";
}
catch (Exception e)
{
info = e.getMessage();
if (info != null)
info = info.replace('\n', ' ');
status = 1;
}
// Get job status
/*try
{
job.refreshStatus();
StateEnumeration jobState = job.getState();
info = jobState.getValue().toUpperCase();
if (jobState == StateEnumeration.Unsubmitted)
info = "PENDING";
}
catch (Exception e)
{
info = e.getMessage();
if (info != null)
info = info.replace('\n', ' ');
status = 1;
}*/
return status;
}
int cancel (Integer jid, GramJob job) {
int status = 0;
info = "-";
// Cancel the job
try
{
job.cancel();
}
catch (Exception e)
{
info = e.getMessage().replace('\n', ' ');
status = 1;
}
return status;
}
int poll(Integer jid, GramJob job) {
int status = 0;
int index = 0;
// Get job status
try
{
job.refreshStatus();
StateEnumeration jobState = job.getState();
info = jobState.getValue().toUpperCase();
if (jobState == StateEnumeration.Unsubmitted)
info = "PENDING";
}
catch (Exception e)
{
info = e.getMessage().replace('\n', ' ');
status = 1;
}
return status;
}
}
| src/em_mad/GW_mad_ws.GT4.2.java | /* -------------------------------------------------------------------------- */
/* Copyright 2002-2006 GridWay Team, Distributed Systems Architecture */
/* Group, Universidad Complutense de Madrid */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
import java.io.*;
import java.util.*;
import java.net.URL;
import org.apache.axis.components.uuid.UUIDGen;
import org.apache.axis.components.uuid.UUIDGenFactory;
import org.globus.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.client.BaseClient;
import org.globus.gsi.GlobusCredential;
import java.security.cert.X509Certificate;
import org.globus.delegation.DelegationUtil;
import org.globus.exec.client.GramJobListener;
import org.globus.exec.client.GramJob;
import org.globus.exec.utils.client.ManagedJobFactoryClientHelper;
import org.globus.exec.utils.ManagedJobFactoryConstants;
import org.globus.exec.utils.rsl.RSLHelper;
import org.globus.exec.generated.StateEnumeration;
import org.gridforum.jgss.ExtendedGSSCredential;
import org.gridforum.jgss.ExtendedGSSManager;
import org.ietf.jgss.GSSCredential;
class GW_mad_ws extends Thread implements GramJobListener {
private Map job_pool = null; // Job pool
private Map jid_pool = null; // JID pool
// private Long last_goodtill = 0L;
private String portNumber;
public static void main(String args[]) {
int i = 0;
String arg;
String _portNumber = "8443";
boolean error=false;
GW_mad_ws gw_mad_ws;
while (i < args.length && args[i].startsWith("-"))
{
arg = args[i++];
if (arg.equals("-p"))
{
if (i < args.length)
_portNumber = args[i++];
else
{
System.err.println("-p requires a portnumber");
error = true;
}
}
}
if (error == false)
{
gw_mad_ws = new GW_mad_ws(_portNumber);
//gw_mad_ws.start();
gw_mad_ws.loop();
//gw_mad_ws.interrupt();
}
}
// Constructor
GW_mad_ws(String portNumber) {
this.portNumber = portNumber;
// Create the job and JID pool
// Warning! With JDK1.5 should be "new HashMap<Integer,GramJob>()"
job_pool = Collections.synchronizedMap(new HashMap());
jid_pool = Collections.synchronizedMap(new HashMap());
}
void loop() {
String str = null;
String action = null;
String jid_str = null;
String contact;
String rsl_file;
boolean fin = false;
Integer jid = null;
GramJob job = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!fin) {
// Read a line a parse it
try
{
str = in.readLine();
}
catch (IOException e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized (System.out)
{
System.out.println(action + " " + jid_str + " FAILURE " + info);
}
}
String str_split[] = str.split(" ", 4);
if (str_split.length != 4)
{
synchronized (System.out)
{
System.out.println(action + " " + jid_str + " FAILURE "
+ "Error reading line");
}
fin = true;
}
else
{
action = str_split[0].toUpperCase();
jid_str = str_split[1];
contact = str_split[2];
rsl_file = str_split[3];
// Perform the action
if (action.equals("INIT"))
init();
else if (action.equals("FINALIZE"))
{
finalize_mad();
fin = true;
}
else if (action.equals("SUBMIT") || action.equals("RECOVER"))
{
try
{
jid = new Integer(jid_str);
}
catch (NumberFormatException e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized (System.out)
{
System.out.println(action + " " + jid_str + " FAILURE "
+ info);
}
}
// Create a job
try
{
if (action.equals("SUBMIT"))
{
job = new GramJob(new java.io.File(rsl_file));
}
else if (action.equals("RECOVER"))
{
job = new GramJob();
}
// Add state listener
job.addListener(this);
Service s = new Service(action, jid, job, contact, portNumber);
s.start();
// Add job and jid to the pools
job_pool.put(jid, job);
jid_pool.put(job, jid);
}
catch (Exception e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized (System.out)
{
System.out.println(action + " " + jid_str + " FAILURE "
+ info);
}
}
}
else if (action.equals("CANCEL") || action.equals("POLL"))
{
try
{
jid = new Integer(jid_str);
}
catch (NumberFormatException e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized(System.out)
{
System.out.println(action + " " + jid_str + " FAILURE "
+ info);
}
}
job = (GramJob) job_pool.get(jid);
if (job == null)
{
synchronized(System.out)
{
System.out.println(action + " " + jid + " FAILURE Job does not exist jid");
}
}
else
{
Service s = new Service(action, jid, job, contact,portNumber);
s.start();
}
}
else
{
synchronized(System.out)
{
System.out.println(action + " " + jid_str
+ " FAILURE Not valid action");
}
}
}
}
}
void init() {
// Nothing to do here
synchronized(System.out)
{
System.out.println("INIT - SUCCESS -");
}
}
void finalize_mad() {
// Nothing to do here
synchronized(System.out)
{
System.out.println("FINALIZE - SUCCESS -");
}
}
// Method from interface GramJobListener
public void stateChanged(GramJob job) {
int status;
int exitCode;
String info;
// Get job state
StateEnumeration jobState = job.getState();
String jobState_str = jobState.getValue().toUpperCase();
// Get the JID from the job
Integer jid = (Integer) jid_pool.get(job);
if (jid == null)
{
status = 1;
info = "Job " + job.getHandle() + " does not exist";
}
else
{
if (jobState == StateEnumeration.Unsubmitted)
jobState_str = "PENDING";
if (jobState == StateEnumeration.Failed)
{
// Check if the reason is "User cancelled"
if (job.getFault() == null)
{
status = 0;
info = StateEnumeration._Done.toUpperCase();
}
else
{
status = 1;
info = job.getFault().getDescription(0).toString().replace('\n', ' ');
}
}
else
{
status = 0;
info = jobState_str;
// Get job exit code
exitCode = job.getExitCode();
if(info.equals("DONE"))
info = info + ":" + exitCode;
}
}
synchronized (System.out)
{
if (status == 0)
System.out.println("CALLBACK " + jid + " SUCCESS " + info);
else if (jid == null)
System.out.println("CALLBACK - FAILURE " + info);
else
System.out.println("CALLBACK " + jid + " FAILURE " + info);
}
// If the job is done, remove it from the pool
if (jobState == StateEnumeration.Done
|| jobState == StateEnumeration.Failed)
{
job_pool.remove(jid);
jid_pool.remove(job);
try
{
job.destroy();
}
catch (Exception e)
{
//status = 1;
//info = e.getMessage().replace('\n', ' ');
}
}
}
// Not used nor needed
/*
public void run() {
Long goodtill;
GlobusCredential proxy;
ExtendedGSSManager manager;
while (true)
{
try
{
Thread.sleep(30000L);
}
catch (Exception e)
{
}
try
{
//manager = (ExtendedGSSManager)
// ExtendedGSSManager.getInstance();
proxy = GlobusCredential.getDefaultCredential();
// = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
long timeleft = proxy.getTimeLeft();
goodtill = new Long(System.currentTimeMillis() + timeleft*1000);
if (last_goodtill == 0)
{
last_goodtill = goodtill;
}
else if (goodtill > last_goodtill)
{
try
{
Iterator it = job_pool.values().iterator();
while (it.hasNext())
{
GramJob job = (GramJob) it.next();
X509Certificate certToSign =
DelegationUtil.getCertificateChainRP(null, null)[0];
DelegationUtil.refresh(proxy, certToSign, 12*60*60, false, null, null);
synchronized (System.out)
{
System.out.println("TIMER - SUCCESS Credentials refreshed until" + goodtill);
}
}
}
catch (Exception e)
{
synchronized (System.out)
{
System.out.println("TIMER - FAILURE Can't refresh credentials");
}
}
}
}
catch (Exception e)
{
String info = e.getMessage().replace('\n', ' ');
synchronized (System.out)
{
System.out.println("TIMER - FAILURE Exception while obtaining user proxy: " + info);
}
}
}
}*/
}
class Service extends Thread {
String action, contact;
Integer jid;
GramJob job;
int status = 0;
String info;
String portNumber;
Service(String action, Integer jid, GramJob job, String contact, String portNumber) {
this.action = action;
this.jid = jid;
this.job = job;
this.contact = contact;
this.portNumber = portNumber;
}
public void run() {
// Perform the action
if (action.equals("SUBMIT"))
status = submit(jid, job, contact);
else if (action.equals("RECOVER"))
status = recover(jid, job, contact);
else if (action.equals("CANCEL"))
status = cancel(jid, job);
else if (action.equals("POLL"))
status = poll(jid, job);
else
{
status = 1;
info = "Not valid action";
}
synchronized (System.out)
{
if (status == 0)
System.out.println(action + " " + jid + " SUCCESS " + info);
else
System.out.println(action + " " + jid + " FAILURE " + info);
}
}
int submit (Integer jid, GramJob job, String contact) {
int status = 0;
int index = 0;
EndpointReferenceType factoryEndpoint = null;
info = "-";
// Default factory type is Fork
String factoryType = ManagedJobFactoryConstants.DEFAULT_FACTORY_TYPE;
// Parse resource contact string
String resource_split[] = contact.split("/");
String host = resource_split[0];
if (resource_split.length == 2)
factoryType = resource_split[1];
// Create Endpoint Reference to ManagedJobFactoryService with its
//associated ManagedJobFactoryResource
try
{
// Due to Bug 4919: Error in job submission (GRAM-WS)
//URL factoryURL =
// ManagedJobFactoryClientHelper.getServiceURL(host).getURL();
URL factoryURL = new URL("https://" + host
+ ":"+portNumber+"/wsrf/services/ManagedJobFactoryService");
factoryEndpoint =
ManagedJobFactoryClientHelper.getFactoryEndpoint(factoryURL,
factoryType);
}
catch (Exception e)
{
info = e.getMessage().replace('\n', ' ');
status = 1;
}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR , calendar.get(Calendar.WEEK_OF_YEAR) + 1);
job.setTerminationTime(calendar.getTime()); // One week
// Submit the job
try
{
job.submit(factoryEndpoint, false, false, null);
info = job.getHandle();
}
catch (Exception e)
{
info = e.getMessage().replace('\n', ' ');
status = 1;
}
return status;
}
int recover (Integer jid, GramJob job, String handle) {
// Bind to the job and getting its status
try
{
job.setHandle(handle);
job.bind();
job.refreshStatus();
StateEnumeration jobState = job.getState();
info = jobState.getValue().toUpperCase();
if (jobState == StateEnumeration.Unsubmitted)
info = "PENDING";
}
catch (Exception e)
{
info = e.getMessage();
if (info != null)
info = info.replace('\n', ' ');
status = 1;
}
// Get job status
/*try
{
job.refreshStatus();
StateEnumeration jobState = job.getState();
info = jobState.getValue().toUpperCase();
if (jobState == StateEnumeration.Unsubmitted)
info = "PENDING";
}
catch (Exception e)
{
info = e.getMessage();
if (info != null)
info = info.replace('\n', ' ');
status = 1;
}*/
return status;
}
int cancel (Integer jid, GramJob job) {
int status = 0;
info = "-";
// Cancel the job
try
{
job.cancel();
}
catch (Exception e)
{
info = e.getMessage().replace('\n', ' ');
status = 1;
}
return status;
}
int poll(Integer jid, GramJob job) {
int status = 0;
int index = 0;
// Get job status
try
{
job.refreshStatus();
StateEnumeration jobState = job.getState();
info = jobState.getValue().toUpperCase();
if (jobState == StateEnumeration.Unsubmitted)
info = "PENDING";
}
catch (Exception e)
{
info = e.getMessage().replace('\n', ' ');
status = 1;
}
return status;
}
}
| [project @ 2008-05-07 17:36:50 by ehuedo]
Changes for GT4.2
git-svn-id: cfe980af5ea9c2e8ec55361f9629c08651448aa3@153 9b4b2aa8-92f0-458a-8103-c3834d721760
| src/em_mad/GW_mad_ws.GT4.2.java | [project @ 2008-05-07 17:36:50 by ehuedo] Changes for GT4.2 |
|
Java | apache-2.0 | f05844a62cc162351ceebecd3abaaa8b9b3b5038 | 0 | esaunders/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy,wschaeferB/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,esaunders/autopsy,esaunders/autopsy,wschaeferB/autopsy,esaunders/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,rcordovano/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2019 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.contentviewers;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.web.WebView;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import net.htmlparser.jericho.Attribute;
import net.htmlparser.jericho.OutputDocument;
import net.htmlparser.jericho.Source;
import org.openide.util.NbBundle.Messages;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.EventTarget;
/**
* A file content viewer for HTML files.
*/
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
final class HtmlPanel extends javax.swing.JPanel {
private static final Logger logger = Logger.getLogger(HtmlPanel.class.getName());
private static final long serialVersionUID = 1L;
private static final String TEXT_TYPE = "text/plain";
private final JFXPanel jfxPanel = new JFXPanel();
private WebView webView;
private String htmlText;
/**
* Creates new form HtmlViewerPanel
*/
HtmlPanel() {
initComponents();
Platform.runLater(() -> {
webView = new WebView();
//disable the context menu so they can't open linked pages by right clicking
webView.setContextMenuEnabled(false);
//disable java script
webView.getEngine().setJavaScriptEnabled(false);
//disable clicking on links
webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
@Override
public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) {
if (newValue == Worker.State.SUCCEEDED) {
disableHyperLinks();
}
}
});
Scene scene = new Scene(webView);
jfxPanel.setScene(scene);
jfxPanel.setPreferredSize(htmlJPanel.getPreferredSize());
htmlJPanel.add(jfxPanel);
});
}
/**
* Set the text pane's HTML text and refresh the view to display it.
*
* @param htmlText The HTML text to be applied to the text pane.
*/
void setHtmlText(String htmlText) {
this.htmlText = htmlText;
refresh();
}
/**
* Clear the HTML in the text pane and disable the show/hide button.
*/
void reset() {
Platform.runLater(() -> {
webView.getEngine().loadContent("", TEXT_TYPE);
});
showImagesToggleButton.setEnabled(false);
}
/**
* Cleans out input HTML string
*
* @param htmlInString The HTML string to cleanse
*
* @return The cleansed HTML String
*/
private String cleanseHTML(String htmlInString) {
String returnString = "";
try {
Source source = new Source(new StringReader(htmlInString));
OutputDocument document = new OutputDocument(source);
//remove background images
source.getAllTags().stream().filter((tag) -> (tag.toString().contains("background-image"))).forEachOrdered((tag) -> {
document.remove(tag);
});
//remove images
source.getAllElements("img").forEach((element) -> {
document.remove(element.getAllTags());
});
//remove other URI elements such as input boxes
List<Attribute> attributesToRemove = source.getURIAttributes();
document.remove(attributesToRemove);
returnString = document.toString();
} catch (IOException ex) {
logger.log(Level.WARNING, "Unable to read html for cleaning out URI elements with Jericho", ex);
}
return returnString;
}
/**
* Refresh the panel to reflect the current show/hide images setting.
*/
@Messages({
"HtmlPanel_showImagesToggleButton_show=Show Images",
"HtmlPanel_showImagesToggleButton_hide=Hide Images",
"Html_text_display_error=The HTML text cannot be displayed, it may not be correctly formed HTML.",})
private void refresh() {
if (false == htmlText.isEmpty()) {
try {
if (showImagesToggleButton.isSelected()) {
showImagesToggleButton.setText(Bundle.HtmlPanel_showImagesToggleButton_hide());
Platform.runLater(() -> {
webView.getEngine().loadContent(htmlText);
});
} else {
showImagesToggleButton.setText(Bundle.HtmlPanel_showImagesToggleButton_show());
Platform.runLater(() -> {
webView.getEngine().loadContent(cleanseHTML(htmlText));
});
}
showImagesToggleButton.setEnabled(true);
} catch (Exception ignored) {
Platform.runLater(() -> {
webView.getEngine().loadContent(Bundle.Html_text_display_error(), TEXT_TYPE);
});
}
}
}
/**
* 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() {
showImagesToggleButton = new javax.swing.JToggleButton();
htmlJPanel = new javax.swing.JPanel();
org.openide.awt.Mnemonics.setLocalizedText(showImagesToggleButton, org.openide.util.NbBundle.getMessage(HtmlPanel.class, "HtmlPanel.showImagesToggleButton.text")); // NOI18N
showImagesToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showImagesToggleButtonActionPerformed(evt);
}
});
htmlJPanel.setLayout(new java.awt.BorderLayout());
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(showImagesToggleButton)
.addGap(0, 95, Short.MAX_VALUE))
.addComponent(htmlJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(showImagesToggleButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(htmlJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void showImagesToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showImagesToggleButtonActionPerformed
refresh();
}//GEN-LAST:event_showImagesToggleButtonActionPerformed
/**
* Disable the click events on hyper links so that new pages can not be
* opened.
*/
private void disableHyperLinks() {
Platform.runLater(() -> {
Document document = webView.getEngine().getDocument();
if (document != null) {
NodeList nodeList = document.getElementsByTagName("a");
for (int i = 0; i < nodeList.getLength(); i++) {
((EventTarget) nodeList.item(i)).addEventListener("click", (evt) -> {
evt.preventDefault();
evt.stopPropagation();
}, true);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel htmlJPanel;
private javax.swing.JToggleButton showImagesToggleButton;
// End of variables declaration//GEN-END:variables
}
| Core/src/org/sleuthkit/autopsy/contentviewers/HtmlPanel.java | /*
* Autopsy Forensic Browser
*
* Copyright 2019 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.contentviewers;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.web.WebView;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Node;
import org.openide.util.NbBundle.Messages;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.events.EventTarget;
/**
* A file content viewer for HTML files.
*/
@SuppressWarnings("PMD.SingularField") // UI widgets cause lots of false positives
final class HtmlPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private static final String TEXT_TYPE = "text/plain";
private final JFXPanel jfxPanel = new JFXPanel();
private WebView webView;
private String htmlText;
/**
* Creates new form HtmlViewerPanel
*/
HtmlPanel() {
initComponents();
Platform.runLater(() -> {
webView = new WebView();
//disable the context menu so they can't open linked pages by right clicking
webView.setContextMenuEnabled(false);
//disable java script
webView.getEngine().setJavaScriptEnabled(false);
//disable clicking on links
webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
@Override
public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) {
if (newValue == Worker.State.SUCCEEDED) {
disableHyperLinks();
}
}
});
Scene scene = new Scene(webView);
jfxPanel.setScene(scene);
jfxPanel.setPreferredSize(htmlJPanel.getPreferredSize());
htmlJPanel.add(jfxPanel);
});
}
/**
* Set the text pane's HTML text and refresh the view to display it.
*
* @param htmlText The HTML text to be applied to the text pane.
*/
void setHtmlText(String htmlText) {
this.htmlText = htmlText;
refresh();
}
/**
* Clear the HTML in the text pane and disable the show/hide button.
*/
void reset() {
Platform.runLater(() -> {
webView.getEngine().loadContent("", TEXT_TYPE);
});
showImagesToggleButton.setEnabled(false);
}
/**
* Cleans out input HTML string
*
* @param htmlInString The HTML string to cleanse
*
* @return The cleansed HTML String
*/
private String cleanseHTML(String htmlInString) {
org.jsoup.nodes.Document doc = Jsoup.parse(htmlInString);
// remove all 'img' tags.
doc.select("img").stream().forEach(Node::remove);
// remove all 'span' tags, these are often images which are ads
doc.select("span").stream().forEach(Node::remove);
return doc.html();
}
/**
* Refresh the panel to reflect the current show/hide images setting.
*/
@Messages({
"HtmlPanel_showImagesToggleButton_show=Show Images",
"HtmlPanel_showImagesToggleButton_hide=Hide Images",
"Html_text_display_error=The HTML text cannot be displayed, it may not be correctly formed HTML.",})
private void refresh() {
if (false == htmlText.isEmpty()) {
try {
if (showImagesToggleButton.isSelected()) {
showImagesToggleButton.setText(Bundle.HtmlPanel_showImagesToggleButton_hide());
Platform.runLater(() -> {
webView.getEngine().loadContent(htmlText);
});
} else {
showImagesToggleButton.setText(Bundle.HtmlPanel_showImagesToggleButton_show());
Platform.runLater(() -> {
webView.getEngine().loadContent(cleanseHTML(htmlText));
});
}
showImagesToggleButton.setEnabled(true);
} catch (Exception ignored) {
Platform.runLater(() -> {
webView.getEngine().loadContent(Bundle.Html_text_display_error(), TEXT_TYPE);
});
}
}
}
/**
* 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() {
showImagesToggleButton = new javax.swing.JToggleButton();
htmlJPanel = new javax.swing.JPanel();
org.openide.awt.Mnemonics.setLocalizedText(showImagesToggleButton, org.openide.util.NbBundle.getMessage(HtmlPanel.class, "HtmlPanel.showImagesToggleButton.text")); // NOI18N
showImagesToggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showImagesToggleButtonActionPerformed(evt);
}
});
htmlJPanel.setLayout(new java.awt.BorderLayout());
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(showImagesToggleButton)
.addGap(0, 95, Short.MAX_VALUE))
.addComponent(htmlJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(showImagesToggleButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(htmlJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 33, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void showImagesToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showImagesToggleButtonActionPerformed
refresh();
}//GEN-LAST:event_showImagesToggleButtonActionPerformed
/**
* Disable the click events on hyper links so that new pages can not be
* opened.
*/
private void disableHyperLinks() {
Platform.runLater(() -> {
Document document = webView.getEngine().getDocument();
if (document != null) {
NodeList nodeList = document.getElementsByTagName("a");
for (int i = 0; i < nodeList.getLength(); i++) {
((EventTarget) nodeList.item(i)).addEventListener("click", (evt) -> {
evt.preventDefault();
evt.stopPropagation();
}, true);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel htmlJPanel;
private javax.swing.JToggleButton showImagesToggleButton;
// End of variables declaration//GEN-END:variables
}
| 5123 remove all images and other uri elements from html by default
| Core/src/org/sleuthkit/autopsy/contentviewers/HtmlPanel.java | 5123 remove all images and other uri elements from html by default |
|
Java | apache-2.0 | 642544f1c6d523b367672a2c5dd3ea52efb68958 | 0 | riversand963/alluxio,maobaolong/alluxio,bf8086/alluxio,wwjiang007/alluxio,madanadit/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,PasaLab/tachyon,riversand963/alluxio,PasaLab/tachyon,ChangerYoung/alluxio,Alluxio/alluxio,maboelhassan/alluxio,EvilMcJerkface/alluxio,yuluo-ding/alluxio,jsimsa/alluxio,Alluxio/alluxio,maobaolong/alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,uronce-cc/alluxio,madanadit/alluxio,jsimsa/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,wwjiang007/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,PasaLab/tachyon,apc999/alluxio,EvilMcJerkface/alluxio,calvinjia/tachyon,calvinjia/tachyon,PasaLab/tachyon,Alluxio/alluxio,EvilMcJerkface/alluxio,aaudiber/alluxio,Reidddddd/mo-alluxio,riversand963/alluxio,Reidddddd/alluxio,aaudiber/alluxio,PasaLab/tachyon,madanadit/alluxio,WilliamZapata/alluxio,jswudi/alluxio,ShailShah/alluxio,jsimsa/alluxio,Reidddddd/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,riversand963/alluxio,jswudi/alluxio,Reidddddd/alluxio,aaudiber/alluxio,bf8086/alluxio,wwjiang007/alluxio,ShailShah/alluxio,apc999/alluxio,riversand963/alluxio,maboelhassan/alluxio,bf8086/alluxio,Alluxio/alluxio,aaudiber/alluxio,Alluxio/alluxio,wwjiang007/alluxio,Reidddddd/alluxio,maboelhassan/alluxio,bf8086/alluxio,uronce-cc/alluxio,calvinjia/tachyon,wwjiang007/alluxio,maboelhassan/alluxio,Reidddddd/mo-alluxio,aaudiber/alluxio,bf8086/alluxio,aaudiber/alluxio,bf8086/alluxio,ChangerYoung/alluxio,yuluo-ding/alluxio,WilliamZapata/alluxio,Alluxio/alluxio,madanadit/alluxio,maobaolong/alluxio,jswudi/alluxio,uronce-cc/alluxio,WilliamZapata/alluxio,PasaLab/tachyon,maboelhassan/alluxio,aaudiber/alluxio,jswudi/alluxio,maobaolong/alluxio,Reidddddd/alluxio,PasaLab/tachyon,calvinjia/tachyon,EvilMcJerkface/alluxio,WilliamZapata/alluxio,yuluo-ding/alluxio,madanadit/alluxio,ChangerYoung/alluxio,jsimsa/alluxio,calvinjia/tachyon,yuluo-ding/alluxio,EvilMcJerkface/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,Reidddddd/mo-alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,ShailShah/alluxio,wwjiang007/alluxio,apc999/alluxio,Alluxio/alluxio,uronce-cc/alluxio,riversand963/alluxio,calvinjia/tachyon,bf8086/alluxio,yuluo-ding/alluxio,maobaolong/alluxio,ShailShah/alluxio,Alluxio/alluxio,apc999/alluxio,Alluxio/alluxio,uronce-cc/alluxio,madanadit/alluxio,maobaolong/alluxio,maobaolong/alluxio,Alluxio/alluxio,apc999/alluxio,madanadit/alluxio,wwjiang007/alluxio,uronce-cc/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,calvinjia/tachyon,ShailShah/alluxio,calvinjia/tachyon,wwjiang007/alluxio,Reidddddd/alluxio,yuluo-ding/alluxio,bf8086/alluxio,maobaolong/alluxio,madanadit/alluxio,ChangerYoung/alluxio,ChangerYoung/alluxio,maboelhassan/alluxio,Reidddddd/alluxio,jswudi/alluxio,ShailShah/alluxio | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.hadoop;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.PropertyKey;
import alluxio.client.file.FileInStream;
import alluxio.client.file.FileSystem;
import alluxio.client.file.FileSystemContext;
import alluxio.client.file.URIStatus;
import alluxio.client.file.options.OpenFileOptions;
import alluxio.exception.AlluxioException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.FileDoesNotExistException;
import org.apache.hadoop.fs.FileSystem.Statistics;
import org.apache.hadoop.fs.PositionedReadable;
import org.apache.hadoop.fs.Seekable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.concurrent.NotThreadSafe;
/**
* An input stream for reading a file from HDFS.
*/
@NotThreadSafe
public class HdfsFileInputStream extends InputStream implements Seekable, PositionedReadable {
private static final Logger LOG = LoggerFactory.getLogger(HdfsFileInputStream.class);
private static final boolean PACKET_STREAMING_ENABLED =
Configuration.getBoolean(PropertyKey.USER_PACKET_STREAMING_ENABLED);
private final Statistics mStatistics;
private final URIStatus mFileInfo;
private final FileInStream mInputStream;
private boolean mClosed = false;
private long mCurrentPosition;
/**
* Constructs a new stream for reading a file from HDFS.
*
* @param context the file system context
* @param uri the Alluxio file URI
* @param stats filesystem statistics
* @throws IOException if the underlying file does not exist or its stream cannot be created
*/
public HdfsFileInputStream(FileSystemContext context, AlluxioURI uri,
org.apache.hadoop.fs.FileSystem.Statistics stats) throws IOException {
LOG.debug("HdfsFileInputStream({}, {})", uri, stats);
mCurrentPosition = 0;
mStatistics = stats;
FileSystem fs = FileSystem.Factory.get(context);
try {
mFileInfo = fs.getStatus(uri);
mInputStream = fs.openFile(uri, OpenFileOptions.defaults());
} catch (FileDoesNotExistException e) {
// Transform the Alluxio exception to a Java exception to satisfy the HDFS API contract.
throw new FileNotFoundException(ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(uri));
} catch (AlluxioException e) {
throw new IOException(e);
}
}
@Override
public int available() throws IOException {
if (mClosed) {
throw new IOException("Cannot query available bytes from a closed stream.");
}
return (int) mInputStream.remaining();
}
@Override
public void close() throws IOException {
if (mClosed) {
return;
}
mInputStream.close();
mClosed = true;
}
@Override
public long getPos() throws IOException {
return mCurrentPosition;
}
@Override
public int read() throws IOException {
if (mClosed) {
throw new IOException(ExceptionMessage.READ_CLOSED_STREAM.getMessage());
}
int ret = mInputStream.read();
if (ret != -1) {
mCurrentPosition++;
if (mStatistics != null) {
mStatistics.incrementBytesRead(1);
}
}
return ret;
}
@Override
public int read(byte[] buffer) throws IOException {
return read(buffer, 0, buffer.length);
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
if (mClosed) {
throw new IOException(ExceptionMessage.READ_CLOSED_STREAM.getMessage());
}
int ret = mInputStream.read(buffer, offset, length);
if (ret != -1) {
mCurrentPosition += ret;
if (mStatistics != null) {
mStatistics.incrementBytesRead(ret);
}
}
return ret;
}
@Override
public int read(long position, byte[] buffer, int offset, int length) throws IOException {
if (mClosed) {
throw new IOException(ExceptionMessage.READ_CLOSED_STREAM.getMessage());
}
if (PACKET_STREAMING_ENABLED) {
return readWithPacketStreaming(position, buffer, offset, length);
} else {
return readWithoutPacketStreaming(position, buffer, offset, length);
}
}
/**
* Reads upto the specified number of bytes, from a given position within a file, and return the
* number of bytes read. This does not change the current offset of a file, and is thread-safe.
* This is used if packet streaming is enabled.
*
* @param position the start position to read from the stream
* @param buffer the buffer to hold the data read
* @param offset the offset in the buffer
* @param length the number of bytes to read from the file
* @return the number of bytes read or -1 if EOF is reached
* @throws IOException if it fails to read
*/
private int readWithPacketStreaming(long position, byte[] buffer, int offset,
int length) throws IOException {
int bytesRead = mInputStream.positionedRead(position, buffer, offset, length);
if (mStatistics != null && bytesRead != -1) {
mStatistics.incrementBytesRead(bytesRead);
}
return bytesRead;
}
/**
* Reads upto the specified number of bytes, from a given position within a file, and return the
* number of bytes read. This does not change the current offset of a file, and is thread-safe.
* This is used if packet streaming is not enabled.
*
* @param position the start position to read from the stream
* @param buffer the buffer to hold the data read
* @param offset the offset in the buffer
* @param length the number of bytes to read from the file
* @return the number of bytes read or -1 if EOF is reached
* @throws IOException if it fails to read
*/
private synchronized int readWithoutPacketStreaming(long position, byte[] buffer, int offset,
int length) throws IOException {
int ret = -1;
long oldPos = getPos();
if ((position < 0) || (position >= mFileInfo.getLength())) {
return ret;
}
try {
mInputStream.seek(position);
ret = mInputStream.read(buffer, offset, length);
if (mStatistics != null && ret != -1) {
mStatistics.incrementBytesRead(ret);
}
return ret;
} finally {
mInputStream.seek(oldPos);
}
}
@Override
public void readFully(long position, byte[] buffer) throws IOException {
readFully(position, buffer, 0, buffer.length);
}
@Override
public void readFully(long position, byte[] buffer, int offset, int length) throws IOException {
int n = 0; // total bytes read
while (n < length) {
int ret = read(position + n, buffer, offset + n, length - n);
if (ret == -1) {
throw new EOFException();
}
n += ret;
}
}
/**
* Seek to the given offset from the start of the file. The next {@link #read()} will be from that
* location. Can't seek past the end of the file.
*
* @param pos the position to seek to
* @throws IOException if the position is negative or exceeds the end of the file
*/
@Override
public void seek(long pos) throws IOException {
if (pos == mCurrentPosition) {
return;
}
if (pos < 0) {
throw new IOException(ExceptionMessage.SEEK_NEGATIVE.getMessage(pos));
}
if (pos > mFileInfo.getLength()) {
throw new IOException(ExceptionMessage.SEEK_PAST_EOF.getMessage(pos, mFileInfo.getLength()));
}
mInputStream.seek(pos);
mCurrentPosition = pos;
}
/**
* This method is not supported in {@link HdfsFileInputStream}.
*
* @param targetPos N/A
* @return N/A
* @throws IOException always
*/
@Override
public boolean seekToNewSource(long targetPos) throws IOException {
throw new IOException(ExceptionMessage.NOT_SUPPORTED.getMessage());
}
/**
* Skips over the given bytes from the current position. Since the inherited
* {@link InputStream#skip(long)} is inefficient, {@link #skip(long)} should be explicitly
* overrided.
*
* @param n the number of bytes to be skipped
* @return the actual number of bytes skipped
* @throws IOException if the after position exceeds the end of the file
*/
@Override
public long skip(long n) throws IOException {
if (mClosed) {
throw new IOException("Cannot skip bytes in a closed stream.");
}
if (n <= 0) {
return 0;
}
long toSkip = Math.min(n, available());
seek(mCurrentPosition + toSkip);
return toSkip;
}
}
| core/client/src/main/java/alluxio/hadoop/HdfsFileInputStream.java | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.hadoop;
import alluxio.AlluxioURI;
import alluxio.Configuration;
import alluxio.PropertyKey;
import alluxio.client.file.FileInStream;
import alluxio.client.file.FileSystem;
import alluxio.client.file.FileSystemContext;
import alluxio.client.file.URIStatus;
import alluxio.client.file.options.OpenFileOptions;
import alluxio.exception.AlluxioException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.FileDoesNotExistException;
import org.apache.hadoop.fs.FileSystem.Statistics;
import org.apache.hadoop.fs.PositionedReadable;
import org.apache.hadoop.fs.Seekable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.concurrent.NotThreadSafe;
/**
* An input stream for reading a file from HDFS.
*/
@NotThreadSafe
public class HdfsFileInputStream extends InputStream implements Seekable, PositionedReadable {
private static final Logger LOG = LoggerFactory.getLogger(HdfsFileInputStream.class);
private static final boolean PACKET_STREAMING_ENABLED =
Configuration.getBoolean(PropertyKey.USER_PACKET_STREAMING_ENABLED);
private final Statistics mStatistics;
private final URIStatus mFileInfo;
private final FileInStream mInputStream;
private boolean mClosed = false;
private long mCurrentPosition;
/**
* Constructs a new stream for reading a file from HDFS.
*
* @param context the file system context
* @param uri the Alluxio file URI
* @param stats filesystem statistics
* @throws IOException if the underlying file does not exist or its stream cannot be created
*/
public HdfsFileInputStream(FileSystemContext context, AlluxioURI uri,
org.apache.hadoop.fs.FileSystem.Statistics stats) throws IOException {
LOG.debug("HdfsFileInputStream({}, {}, {}, {}, {})", uri, stats);
mCurrentPosition = 0;
mStatistics = stats;
FileSystem fs = FileSystem.Factory.get(context);
try {
mFileInfo = fs.getStatus(uri);
mInputStream = fs.openFile(uri, OpenFileOptions.defaults());
} catch (FileDoesNotExistException e) {
// Transform the Alluxio exception to a Java exception to satisfy the Hadoop API contract.
throw new FileNotFoundException(ExceptionMessage.PATH_DOES_NOT_EXIST.getMessage(uri));
} catch (AlluxioException e) {
throw new IOException(e);
}
}
@Override
public int available() throws IOException {
if (mClosed) {
throw new IOException("Cannot query available bytes from a closed stream.");
}
return (int) mInputStream.remaining();
}
@Override
public void close() throws IOException {
if (mClosed) {
return;
}
mInputStream.close();
mClosed = true;
}
@Override
public long getPos() throws IOException {
return mCurrentPosition;
}
@Override
public int read() throws IOException {
if (mClosed) {
throw new IOException(ExceptionMessage.READ_CLOSED_STREAM.getMessage());
}
int ret = mInputStream.read();
if (ret != -1) {
mCurrentPosition++;
if (mStatistics != null) {
mStatistics.incrementBytesRead(1);
}
}
return ret;
}
@Override
public int read(byte[] buffer) throws IOException {
return read(buffer, 0, buffer.length);
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
if (mClosed) {
throw new IOException(ExceptionMessage.READ_CLOSED_STREAM.getMessage());
}
int ret = mInputStream.read(buffer, offset, length);
if (ret != -1) {
mCurrentPosition += ret;
if (mStatistics != null) {
mStatistics.incrementBytesRead(ret);
}
}
return ret;
}
@Override
public int read(long position, byte[] buffer, int offset, int length) throws IOException {
if (mClosed) {
throw new IOException(ExceptionMessage.READ_CLOSED_STREAM.getMessage());
}
if (PACKET_STREAMING_ENABLED) {
return readWithPacketStreaming(position, buffer, offset, length);
} else {
return readWithoutPacketStreaming(position, buffer, offset, length);
}
}
/**
* Reads upto the specified number of bytes, from a given position within a file, and return the
* number of bytes read. This does not change the current offset of a file, and is thread-safe.
* This is used if packet streaming is enabled.
*
* @param position the start position to read from the stream
* @param buffer the buffer to hold the data read
* @param offset the offset in the buffer
* @param length the number of bytes to read from the file
* @return the number of bytes read or -1 if EOF is reached
* @throws IOException if it fails to read
*/
private int readWithPacketStreaming(long position, byte[] buffer, int offset,
int length) throws IOException {
int bytesRead = mInputStream.positionedRead(position, buffer, offset, length);
if (mStatistics != null && bytesRead != -1) {
mStatistics.incrementBytesRead(bytesRead);
}
return bytesRead;
}
/**
* Reads upto the specified number of bytes, from a given position within a file, and return the
* number of bytes read. This does not change the current offset of a file, and is thread-safe.
* This is used if packet streaming is not enabled.
*
* @param position the start position to read from the stream
* @param buffer the buffer to hold the data read
* @param offset the offset in the buffer
* @param length the number of bytes to read from the file
* @return the number of bytes read or -1 if EOF is reached
* @throws IOException if it fails to read
*/
private synchronized int readWithoutPacketStreaming(long position, byte[] buffer, int offset,
int length) throws IOException {
int ret = -1;
long oldPos = getPos();
if ((position < 0) || (position >= mFileInfo.getLength())) {
return ret;
}
try {
mInputStream.seek(position);
ret = mInputStream.read(buffer, offset, length);
if (mStatistics != null && ret != -1) {
mStatistics.incrementBytesRead(ret);
}
return ret;
} finally {
mInputStream.seek(oldPos);
}
}
@Override
public void readFully(long position, byte[] buffer) throws IOException {
readFully(position, buffer, 0, buffer.length);
}
@Override
public void readFully(long position, byte[] buffer, int offset, int length) throws IOException {
int n = 0; // total bytes read
while (n < length) {
int ret = read(position + n, buffer, offset + n, length - n);
if (ret == -1) {
throw new EOFException();
}
n += ret;
}
}
/**
* Seek to the given offset from the start of the file. The next {@link #read()} will be from that
* location. Can't seek past the end of the file.
*
* @param pos the position to seek to
* @throws IOException if the position is negative or exceeds the end of the file
*/
@Override
public void seek(long pos) throws IOException {
if (pos == mCurrentPosition) {
return;
}
if (pos < 0) {
throw new IOException(ExceptionMessage.SEEK_NEGATIVE.getMessage(pos));
}
if (pos > mFileInfo.getLength()) {
throw new IOException(ExceptionMessage.SEEK_PAST_EOF.getMessage(pos, mFileInfo.getLength()));
}
mInputStream.seek(pos);
mCurrentPosition = pos;
}
/**
* This method is not supported in {@link HdfsFileInputStream}.
*
* @param targetPos N/A
* @return N/A
* @throws IOException always
*/
@Override
public boolean seekToNewSource(long targetPos) throws IOException {
throw new IOException(ExceptionMessage.NOT_SUPPORTED.getMessage());
}
/**
* Skips over the given bytes from the current position. Since the inherited
* {@link InputStream#skip(long)} is inefficient, {@link #skip(long)} should be explicitly
* overrided.
*
* @param n the number of bytes to be skipped
* @return the actual number of bytes skipped
* @throws IOException if the after position exceeds the end of the file
*/
@Override
public long skip(long n) throws IOException {
if (mClosed) {
throw new IOException("Cannot skip bytes in a closed stream.");
}
if (n <= 0) {
return 0;
}
long toSkip = Math.min(n, available());
seek(mCurrentPosition + toSkip);
return toSkip;
}
}
| Clean up.
| core/client/src/main/java/alluxio/hadoop/HdfsFileInputStream.java | Clean up. |
|
Java | apache-2.0 | 0b9e407b64907a9eb63a217a233a0db91541c921 | 0 | ceylon/ceylon.language,ceylon/ceylon.language,unratito/ceylon.language,unratito/ceylon.language | package ceylon.language;
import java.util.Locale;
import com.redhat.ceylon.compiler.java.Util;
import com.redhat.ceylon.compiler.java.language.AbstractCallable;
import com.redhat.ceylon.compiler.java.language.StringTokens;
import com.redhat.ceylon.compiler.java.metadata.Annotation;
import com.redhat.ceylon.compiler.java.metadata.Annotations;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Class;
import com.redhat.ceylon.compiler.java.metadata.Defaulted;
import com.redhat.ceylon.compiler.java.metadata.FunctionalParameter;
import com.redhat.ceylon.compiler.java.metadata.Ignore;
import com.redhat.ceylon.compiler.java.metadata.Name;
import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes;
import com.redhat.ceylon.compiler.java.metadata.Transient;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
import com.redhat.ceylon.compiler.java.metadata.TypeParameter;
import com.redhat.ceylon.compiler.java.metadata.TypeParameters;
import com.redhat.ceylon.compiler.java.metadata.ValueType;
import com.redhat.ceylon.compiler.java.runtime.model.ReifiedType;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
import ceylon.language.impl.BaseCharacterList;
import ceylon.language.impl.BaseIterable;
import ceylon.language.impl.BaseIterator;
@Ceylon(major = 8)
@Class(extendsType="ceylon.language::Object",
basic = false, identifiable = false)
@SatisfiedTypes({"ceylon.language::SearchableList<ceylon.language::Character>",
"ceylon.language::Comparable<ceylon.language::String>",
"ceylon.language::Summable<ceylon.language::String>",
"ceylon.language::Ranged<ceylon.language::Integer,ceylon.language::Character,ceylon.language::String>"})
@ValueType
@Annotations({
@Annotation(
value = "doc",
arguments = {"A string of characters..."}),
@Annotation(
value = "by",
arguments = {"Gavin"}),
@Annotation("shared"),
@Annotation("final")})
public final class String
implements Comparable<String>, SearchableList<Character>,
Summable<String>, ReifiedType {
@Ignore
public final static TypeDescriptor $TypeDescriptor$ =
TypeDescriptor.klass(String.class);
@Ignore
public final java.lang.String value;
@Ignore @Override
public Comparable$impl<String> $ceylon$language$Comparable$impl() {
return new Comparable$impl<String>(String.$TypeDescriptor$, this);
}
@SuppressWarnings("rawtypes")
public String(@Name("characters")
@TypeInfo("ceylon.language::Iterable<ceylon.language::Character,ceylon.language::Null>")
final Iterable<? extends Character, ?> characters) {
if (characters instanceof String) {
value = ((String)characters).value;
} else {
java.lang.String s = null;
if (characters instanceof Array.ArrayIterable) {
s = ((Array.ArrayIterable) characters).stringValue();
}
if (s != null) {
value = s;
} else {
java.lang.StringBuilder sb = new java.lang.StringBuilder();
java.lang.Object $tmp;
for (Iterator<? extends Character> $val$iter$0 = characters.iterator();
!(($tmp = $val$iter$0.next()) instanceof Finished);) {
sb.appendCodePoint(((Character)$tmp).codePoint);
}
value = sb.toString();
}
}
}
@Ignore
public String(final java.lang.String string) {
value = string;
}
@Override
@Transient
public java.lang.String toString() {
return value;
}
@Ignore
public static java.lang.String toString(java.lang.String value) {
return value;
}
@Ignore
public static ceylon.language.String instance(java.lang.String s) {
if (s==null) return null;
return new String(s);
}
@Ignore
public static ceylon.language.String instanceJoining(java.lang.String... strings) {
StringBuffer buf = new StringBuffer();
for (java.lang.String s: strings)
buf.append(s);
return instance(buf.toString());
}
@Ignore
public static ceylon.language.String instanceJoining(String... strings) {
StringBuffer buf = new StringBuffer();
for (String s: strings)
buf.append(s.value);
return instance(buf.toString());
}
public java.lang.String getUppercased() {
return getUppercased(value);
}
@Ignore
public static java.lang.String getUppercased(java.lang.String value) {
return value.toUpperCase(Locale.ROOT);
}
public java.lang.String getLowercased() {
return getLowercased(value);
}
@Ignore
public static java.lang.String getLowercased(java.lang.String value) {
return value.replace("\u0130", "i\u0307") //workaround for bug
.toLowerCase(Locale.ROOT);
}
@Override
public boolean equals(@Name("that") java.lang.Object that) {
if (that instanceof String) {
String s = (String) that;
return value.equals(s.value);
}
else {
return false;
}
}
@Ignore
public static boolean equals(java.lang.String value,
java.lang.Object that) {
if (that instanceof String) {
String s = (String) that;
return value.equals(s.value);
}
else {
return false;
}
}
public boolean equalsIgnoringCase(
@Name("that") java.lang.String that) {
return value.equalsIgnoreCase(that);
}
@Ignore
public static boolean equalsIgnoringCase(
java.lang.String value,
java.lang.String that) {
return value.equalsIgnoreCase(that);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Ignore
public static int hashCode(java.lang.String value) {
return value.hashCode();
}
private static Comparison comparison(int c) {
return c < 0 ? smaller_.get_() :
(c == 0 ? equal_.get_() : larger_.get_());
}
@Override
public Comparison compare(@Name("other") String other) {
return comparison(value.compareTo(other.value));
}
@Ignore
public static Comparison compare(java.lang.String value,
java.lang.String otherValue) {
return comparison(value.compareTo(otherValue));
}
public Comparison compareIgnoringCase(
@Name("other") java.lang.String other) {
return comparison(value.compareToIgnoreCase(other));
}
@Ignore
public static Comparison compareIgnoringCase(
java.lang.String value,
java.lang.String otherValue) {
return comparison(value.compareToIgnoreCase(otherValue));
}
@Override
public String plus(@Name("other") String other) {
return instance(value + other.value);
}
@Ignore
public static java.lang.String plus(java.lang.String value,
java.lang.String otherValue) {
return value + otherValue;
}
@Override
@TypeInfo("ceylon.language::Integer")
public long getSize() {
//TODO: should we cache this value in an instvar?
// But remember that we'll mostly be using the static verion
// of this method! So an instvar won't help much.
return value.codePointCount(0, value.length());
}
@Ignore
public static long getSize(java.lang.String value) {
return value.codePointCount(0, value.length());
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
@Transient
public Integer getLastIndex() {
long length = getSize();
return (length == 0) ? null : Integer.instance(length - 1);
}
@Ignore
public static Integer getLastIndex(java.lang.String value) {
long length = getSize(value);
return (length == 0) ? null : Integer.instance(length - 1);
}
@Override
public boolean getEmpty() {
return value.isEmpty();
}
@Ignore
public static boolean getEmpty(java.lang.String value) {
return value.isEmpty();
}
// @Override
// @TypeInfo("ceylon.language::Null|ceylon.language::Character")
// public Character get(@Name("index") Integer key) {
// return getFromFirst(value, key.longValue());
// }
@Ignore
public static Character get(java.lang.String value, long key) {
return getFromFirst(value, key);
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character getFromLast(@Name("index") long key) {
return getFromLast(value, key);
}
@Ignore
public static Character getFromLast(java.lang.String value, long key) {
int index = Util.toInt(key);
int codePoint;
try {
int offset = value.offsetByCodePoints(value.length(), -index-1);
codePoint = value.codePointAt(offset);
}
catch (IndexOutOfBoundsException e) {
return null;
}
return Character.instance(codePoint);
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character getFromFirst(@Name("index") long key) {
return getFromFirst(value, key);
}
@Ignore
public static Character getFromFirst(java.lang.String value, long key) {
int index = Util.toInt(key);
int codePoint;
try {
int offset = value.offsetByCodePoints(0, index);
codePoint = value.codePointAt(offset);
}
catch (IndexOutOfBoundsException e) {
return null;
}
return Character.instance(codePoint);
}
@Override
public boolean defines(@Name("index") Integer key) {
long index = key.longValue();
return index >= 0 && index < getSize();
}
@Ignore
public static boolean defines(java.lang.String value, long key) {
return key >= 0 && key < getSize(value);
}
/*@Override
@TypeInfo("ceylon.language::Entry<ceylon.language::Boolean,ceylon.language::Null|ceylon.language::Character>")
public Entry<? extends Boolean, ? extends Character> lookup(@Name("index") Integer index) {
return lookup(value, index.value);
}
@Ignore
public static Entry<? extends Boolean,? extends Character>
lookup(java.lang.String value, long index) {
Character item = getFromFirst(value, index);
return new Entry<Boolean,Character>(
Boolean.$TypeDescriptor$,
Character.$TypeDescriptor$,
Boolean.instance(item!=null),
item);
}*/
@Override
@Transient
public Sequential<? extends ceylon.language.Integer> getKeys() {
return getKeys(value);
}
@Ignore
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Sequential<? extends ceylon.language.Integer>
getKeys(java.lang.String value) {
long size = value.length();
if (size==0) {
return (Sequential) empty_.get_();
}
else {
return new Span<Integer>(Integer.$TypeDescriptor$,
Integer.instance(0), Integer.instance(size-1));
}
}
@Ignore
public static java.lang.Object indexes(java.lang.String value) {
return getKeys(value);
}
@Ignore
public static boolean definesEvery(java.lang.String value,
Iterable<? extends Integer,?> keys) {
//TODO: inefficient ... better to cache the result
// of getSize()
// TODO We're still boxing here!
return instance(value).definesEvery(keys);
}
@Ignore
public static boolean definesEvery(java.lang.String value) {
return true;
}
@Ignore
public static boolean definesAny(java.lang.String value,
Iterable<? extends Integer, ?> keys) {
//TODO: inefficient ... better to cache the result
// of getSize()
// TODO We're still boxing here!
return instance(value).definesAny(keys);
}
@Ignore
public static boolean definesAny(java.lang.String value) {
return false;
}
@Ignore
public static <Absent extends Null>
Iterable<? extends Character, ? extends Absent>
getAll(TypeDescriptor $reifiedAbsent, java.lang.String value,
Iterable<? extends Integer, Absent> keys) {
// TODO We're still boxing here!
return instance(value).getAll($reifiedAbsent,keys);
}
@Ignore
public static boolean occurs(java.lang.String value,
int element) {
return occurs(value, element, 0);
}
@Ignore
public static boolean occurs(java.lang.String value,
int element, long from) {
return occurs(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static boolean occurs(java.lang.String value,
int element, long from, long length) {
if (from>=value.length() || length<=0) {
return false;
}
if (from<0) {
length+=from;
from = 0;
}
int start;
try {
start = value.offsetByCodePoints(0, (int)from);
}
catch (IndexOutOfBoundsException e) {
return false;
}
int index = value.indexOf(element, start);
return index>=0 && index<length+from;
}
@Override
public boolean occurs(@Name("element")
Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return occurs(value, element.codePoint, from, length);
}
@Ignore
public static boolean occursAt(java.lang.String value,
long index, int element) {
if (index<0 || index>=value.length()) {
return false;
}
try {
int offset;
try {
offset = value.offsetByCodePoints(0, (int)index);
}
catch (IndexOutOfBoundsException e) {
return false;
}
return element == value.codePointAt(offset);
}
catch (IndexOutOfBoundsException e) {
return false;
}
}
@Override
public boolean occursAt(
@Name("index") long index,
@Name("element") Character element) {
return occursAt(value, index, element.codePoint);
}
@Ignore
public static Iterable<? extends Integer, ?>
occurrences(java.lang.String value, int element) {
return occurrences(value, element, 0);
}
@Ignore
public static Iterable<? extends Integer, ?>
occurrences(java.lang.String value, int element,
final long from) {
return occurrences(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static Iterable<? extends Integer, ?>
occurrences(final java.lang.String value, final int element,
final long from, final long length) {
return new BaseIterable<Integer, java.lang.Object>
(Integer.$TypeDescriptor$, Null.$TypeDescriptor$) {
@Override
public Iterator<? extends Integer> iterator() {
return new BaseIterator<Integer>
(Integer.$TypeDescriptor$) {
long count = from;
int len = java.lang.Character.charCount(element);
int index;
{
try {
index = value.offsetByCodePoints(0,
Util.toInt(from));
}
catch (IndexOutOfBoundsException e) {
index = value.length();
}
}
@Override
public java.lang.Object next() {
if (index>=value.length()) {
return finished_.get_();
}
while (true) {
int result = value.indexOf(element, index);
if (result<0) {
return finished_.get_();
}
count += value.codePointCount(index, result);
long c = count;
index = result + len;
if (count-from>=length) {
return finished_.get_();
}
else {
count++;
return Integer.instance(c);
}
}
}
};
}
};
}
@Override
@TypeInfo("ceylon.language::Iterable<ceylon.language::Integer>")
public Iterable<? extends Integer, ? extends java.lang.Object>
occurrences(@Name("element") Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return occurrences(value, element.codePoint, from, length);
}
@Ignore
public static long
countOccurrences(java.lang.String value,
int element) {
return countOccurrences(value, element, 0);
}
@Ignore
public static long
countOccurrences(java.lang.String value,
int element, long from) {
return countOccurrences(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static long
countOccurrences(java.lang.String value,
int element,
long from, long length) {
if (from>=value.length() || length<=0) {
return 0;
}
if (from<0) {
length+=from;
from = 0;
}
int i;
try {
i = value.offsetByCodePoints(0, (int)from);
}
catch (IndexOutOfBoundsException e) {
return 0;
}
int count = 0;
while (true) {
i = value.indexOf(element, i);
if (i<0 || i>=from+length) {
return count;
}
else {
count++;
i++;
}
}
}
@Override
public long countOccurrences(
@Name("sublist")
Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return countOccurrences(value, element.codePoint, from, length);
}
@Ignore
public static boolean includes(java.lang.String value,
List<? extends Character> sublist) {
return includes(value, sublist, 0);
}
@Ignore
public static boolean includes(java.lang.String value,
List<? extends Character> sublist, long from) {
if (from>value.length()) {
return false;
}
if (from<0) {
from = 0;
}
if (sublist instanceof String) {
String string = (String) sublist;
int offset;
try {
offset = value.offsetByCodePoints(0, (int)from);
}
catch (IndexOutOfBoundsException e) {
return value.isEmpty();
}
int index = value.indexOf(string.value, offset);
return index >= 0;
}
else {
return instance(value).includes(sublist, from);
}
}
@Override
public boolean includes(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return includes(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().includes(sublist, from);
}
}
@Ignore
public static boolean includesAt(java.lang.String value,
long index, List<? extends Character> sublist) {
if (index<0 || index>value.length()) {
return false;
}
if (sublist instanceof String) {
String string = (String) sublist;
java.lang.String str = string.value;
try {
int offset;
try {
offset = value.offsetByCodePoints(0, (int)index);
}
catch (IndexOutOfBoundsException e) {
return sublist.getEmpty();
}
return value.regionMatches(offset, str, 0, str.length());
}
catch (IndexOutOfBoundsException e) {
return false;
}
}
else {
return instance(value).includesAt(index, sublist);
}
}
@Override
public boolean includesAt(@Name("index") long index,
@Name("sublist") List<? extends Character> sublist) {
if (sublist instanceof String) {
return includesAt(value, index, sublist);
}
else {
return $ceylon$language$SearchableList$impl().includesAt(index, sublist);
}
}
@Ignore
public static Iterable<? extends Integer, ?>
inclusions(java.lang.String value,
List<? extends Character> substring) {
return inclusions(value, substring, 0);
}
@Ignore
public static Iterable<? extends Integer, ?>
inclusions(final java.lang.String value,
final List<? extends Character> substring,
final long from) {
if (!(substring instanceof String)) {
return instance(value).inclusions(substring);
}
final String string = (String) substring;
return new BaseIterable<Integer, java.lang.Object>
(Integer.$TypeDescriptor$, Null.$TypeDescriptor$) {
@Override
public Iterator<? extends Integer> iterator() {
return new BaseIterator<Integer>
(Integer.$TypeDescriptor$) {
long count = from;
int len = java.lang.Character.charCount(
string.value.codePointAt(0));
int index;
{
try {
index = value.offsetByCodePoints(0,
Util.toInt(from));
}
catch (IndexOutOfBoundsException e) {
index = value.length();
}
}
@Override
public java.lang.Object next() {
if (index>=value.length()) {
return finished_.get_();
}
while (true) {
int result = value.indexOf(string.value, index);
if (result<0) {
return finished_.get_();
}
count += value.codePointCount(index, result);
long c = count;
index = result + len;
count++;
return Integer.instance(c);
}
}
};
}
};
}
@Override
@TypeInfo("ceylon.language::Iterable<ceylon.language::Integer>")
public Iterable<? extends Integer, ? extends java.lang.Object>
inclusions(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return inclusions(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().inclusions(sublist, from);
}
}
@Ignore
public static long
countInclusions(java.lang.String value,
List<? extends Character> sublist) {
return countInclusions(value, sublist, 0);
}
@Ignore
public static long
countInclusions(java.lang.String value,
List<? extends Character> sublist,
long from) {
if (from>value.length()) {
return 0;
}
if (from<0) {
from = 0;
}
if (sublist instanceof String) {
String string = (String) sublist;
java.lang.String str = string.value;
int i;
try {
i = value.offsetByCodePoints(0, (int)from);
}
catch (IndexOutOfBoundsException e) {
return 0;
}
int count = 0;
while (true) {
i = value.indexOf(str, i);
if (i<0) {
return count;
}
else {
i++;
count++;
}
}
}
else {
return instance(value).countInclusions(sublist, from);
}
}
@Override
public long countInclusions(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return countInclusions(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().countInclusions(sublist, from);
}
}
@Ignore
public static Integer firstInclusion(java.lang.String value,
List<? extends Character> sublist) {
return firstInclusion(value, sublist, 0);
}
@Ignore
public static Integer firstInclusion(java.lang.String value,
List<? extends Character> sublist,
long from) {
if (from>value.length()) {
return null;
}
if (from<0) {
from = 0;
}
if (sublist instanceof String) {
String string = (String) sublist;
int start = value.offsetByCodePoints(0, (int)from);
int index = value.indexOf(string.value, start);
if (index >= 0) {
return Integer.instance(from +
value.codePointCount(start, index));
} else {
return null;
}
}
else {
return instance(value).firstInclusion(sublist, from);
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer firstInclusion(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return firstInclusion(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().firstInclusion(sublist, from);
}
}
public static Integer lastInclusion(java.lang.String value,
List<? extends Character> sublist) {
return lastInclusion(value, sublist, 0);
}
public static Integer lastInclusion(java.lang.String value,
List<? extends Character> sublist, long from) {
if (from>value.length()) {
return null;
}
if (from<0) {
from = 0;
}
if (sublist instanceof String) {
String string = (String) sublist;
int start;
try {
start =
value.offsetByCodePoints(value.length(),
-(int)from
- Util.toInt(sublist.getSize()));
}
catch (java.lang.IndexOutOfBoundsException e) {
return null;
}
int index = value.lastIndexOf(string.value, start);
if (index >= 0) {
return Integer.instance(
value.codePointCount(0, index));
}
else {
return null;
}
}
else {
return instance(value).lastInclusion(sublist, from);
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer lastInclusion(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return lastInclusion(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().lastInclusion(sublist, from);
}
}
@Ignore
public static Integer firstOccurrence(java.lang.String value,
int element) {
return firstOccurrence(value, element, 0);
}
@Ignore
public static Integer firstOccurrence(java.lang.String value,
int element, long from) {
return firstOccurrence(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static Integer firstOccurrence(java.lang.String value,
int element,
long from, long length) {
if (from>=value.length() || length<=0) {
return null;
}
if (from<0) {
length+=from;
from = 0;
}
int start;
try {
start = value.offsetByCodePoints(0, (int)from);
}
catch (java.lang.IndexOutOfBoundsException e) {
return null;
}
int index = value.indexOf(element, start);
if (index >= 0) {
int result = value.codePointCount(start, index);
if (result>=length) {
return null;
}
return Integer.instance(from+result);
}
else {
return null;
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer firstOccurrence(
@Name("element") Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return firstOccurrence(value, element.codePoint, from, length);
}
@Ignore
public static Integer lastOccurrence(java.lang.String value,
int element) {
return lastOccurrence(value, element, 0);
}
@Ignore
public static Integer lastOccurrence(java.lang.String value,
int element, long from) {
return lastOccurrence(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static Integer lastOccurrence(java.lang.String value,
int element, long from, long length) {
if (from>=value.length() || length<=0) {
return null;
}
if (from<0) {
length+=from;
from = 0;
}
int start;
try {
start =
value.offsetByCodePoints(value.length(),
-(int)from - 1);
}
catch (java.lang.IndexOutOfBoundsException e) {
return null;
}
int index = value.lastIndexOf(element, start);
if (index >= 0) {
int dist =
value.codePointCount(start,
value.length());
if (dist>length) {
return null;
}
return Integer.instance(
value.codePointCount(0, index));
}
else {
return null;
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer lastOccurrence(
@Name("element") Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return lastOccurrence(value, element.codePoint, from, length);
}
@Override
@TypeInfo("ceylon.language::Iterator<ceylon.language::Character>")
public Iterator<Character> iterator() {
return new StringIterator(value);
}
@Ignore
public static Iterator<Character> iterator(final java.lang.String value) {
return new StringIterator(value);
}
@Ignore
private static class StringIterator
extends BaseIterator<Character>
implements ReifiedType {
private static TypeDescriptor $TypeDescriptor$ =
TypeDescriptor.klass(StringIterator.class);
final java.lang.String value;
public StringIterator(final java.lang.String value) {
super(Character.$TypeDescriptor$);
this.value = value;
}
private int offset = 0;
@Override
public java.lang.Object next() {
if (offset < value.length()) {
int codePoint = value.codePointAt(offset);
offset += java.lang.Character.charCount(codePoint);
return Character.instance(codePoint);
}
else {
return finished_.get_();
}
}
@Override
@Ignore
public TypeDescriptor $getType$() {
return $TypeDescriptor$;
}
@Override
public java.lang.String toString() {
return '"' + value + '"' + ".iterator()";
}
}
@Override
public boolean contains(@Name("element") java.lang.Object element) {
return contains(value, element);
}
@Ignore
public static boolean contains(java.lang.String value,
java.lang.Object element) {
if (element instanceof String) {
return value.indexOf(((String)element).value) >= 0;
}
else if (element instanceof Character) {
return value.indexOf(((Character)element).codePoint) >= 0;
}
else {
return false;
}
}
@Override
public boolean startsWith(@Name("substring") List<?> substring) {
if (substring instanceof String) {
return value.startsWith(((String)substring).value);
}
else {
return $ceylon$language$List$impl().startsWith(substring);
}
}
@Ignore
public static boolean startsWith(java.lang.String value,
List<?> substring) {
if (substring instanceof String) {
return value.startsWith(((String)substring).value);
}
else {
return instance(value).startsWith(substring);
}
}
@Override
public boolean endsWith(@Name("substring") List<?> substring) {
if (substring instanceof String) {
return value.endsWith(((String)substring).value);
}
else {
return $ceylon$language$List$impl().endsWith(substring);
}
}
@Ignore
public static boolean endsWith(java.lang.String value,
List<?> substring) {
if (substring instanceof String) {
return value.endsWith(((String)substring).value);
}
else {
return instance(value).endsWith(substring);
}
}
@Ignore
public static boolean containsAny(java.lang.String value,
Iterable<?,?> elements) {
// TODO We're still boxing here!
return instance(value).containsAny(elements);
}
@Ignore
public static boolean containsEvery(java.lang.String value,
Iterable<?,?> elements) {
// TODO We're still boxing here!
return instance(value).containsEvery(elements);
}
public boolean longerThan(@TypeInfo("ceylon.language::Integer")
@Name("length") long length) {
try {
value.offsetByCodePoints(0, Util.toInt(length+1));
return true;
}
catch (IndexOutOfBoundsException iobe) {
return false;
}
}
@Ignore
public static boolean longerThan(java.lang.String value,
long length) {
try {
value.offsetByCodePoints(0, Util.toInt(length+1));
return true;
}
catch (IndexOutOfBoundsException iobe) {
return false;
}
}
public boolean shorterThan(@TypeInfo("ceylon.language::Integer")
@Name("length") long length) {
try {
value.offsetByCodePoints(0, Util.toInt(length));
return false;
}
catch (IndexOutOfBoundsException iobe) {
return true;
}
}
@Ignore
public static boolean shorterThan(java.lang.String value,
long length) {
try {
value.offsetByCodePoints(0, Util.toInt(length));
return false;
}
catch (IndexOutOfBoundsException iobe) {
return true;
}
}
@Transient
public java.lang.String getTrimmed() {
return getTrimmed(value);
}
@Ignore
public static java.lang.String getTrimmed(java.lang.String value) {
// Don't use value.trim() because that has a definition of ws that is
// inconsistent with ceylon.language::Character.whitespace
return internalTrim(value, WHITESPACE);
}
@Override
public String trimLeading(
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
@Name("trimming")@FunctionalParameter("(element)")
Callable<? extends Boolean> characters) {
return instance(trimLeading(value, characters));
}
@Ignore
public static java.lang.String trimLeading(java.lang.String value,
Callable<? extends Boolean> characters) {
int from = 0;
while (from < value.length()) {
int c = java.lang.Character.codePointAt(value, from);
if (!characters.$call$(Character.instance(c)).booleanValue()) {
break;
}
from += java.lang.Character.charCount(c);
}
return value.substring(from);
}
@Override
public String trimTrailing(
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
@Name("trimming")@FunctionalParameter("(element)")
Callable<? extends Boolean> characters) {
return instance(trimTrailing(value, characters));
}
@Ignore
public static java.lang.String trimTrailing(java.lang.String value,
Callable<? extends Boolean> characters) {
int to = value.length();
while (to > 0) {
int c = java.lang.Character.codePointBefore(value, to);
if (!characters.$call$(Character.instance(c)).booleanValue()) {
break;
}
to -= java.lang.Character.charCount(c);
}
return value.substring(0, to);
}
@Override
public String trim(
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
@Name("trimming")@FunctionalParameter("(element)")
Callable<? extends Boolean> characters) {
return instance(trim(value, characters));
}
@Ignore
public static java.lang.String trim(java.lang.String value,
Callable<? extends Boolean> characters) {
return internalTrim(value, characters);
}
@Ignore
private static java.lang.String internalTrim(java.lang.String value,
Callable<? extends Boolean> characters) {
int from = 0;
while (from < value.length()) {
int c = java.lang.Character.codePointAt(value, from);
if (!characters.$call$(Character.instance(c)).booleanValue()) {
break;
}
from += java.lang.Character.charCount(c);
}
int to = value.length();
while (to > from) {
int c = java.lang.Character.codePointBefore(value, to);
if (!characters.$call$(Character.instance(c)).booleanValue()) {
break;
}
to -= java.lang.Character.charCount(c);
}
return value.substring(from, to);
}
public java.lang.String getNormalized() {
return getNormalized(value);
}
@Ignore
public static java.lang.String getNormalized(java.lang.String value) {
java.lang.StringBuilder result =
new java.lang.StringBuilder(value.length());
boolean previousWasWhitespace=false;
for (int i=0;i<value.length();) {
int c = java.lang.Character.codePointAt(value, i);
boolean isWhitespace = java.lang.Character.isWhitespace(c);
if (!isWhitespace) {
result.appendCodePoint(c);
}
else if (!previousWasWhitespace) {
result.append(" ");
}
previousWasWhitespace = isWhitespace;
i+=java.lang.Character.charCount(c);
}
// TODO Should be able to figure out the indices to
// substring on while iterating
return getTrimmed(result.toString());
}
@Override
public String initial(@TypeInfo("ceylon.language::Integer")
@Name("length") long length) {
return instance(initial(value, length));
}
@Ignore
public static java.lang.String initial(java.lang.String value,
long length) {
if (length <= 0) {
return "";
} else if (length >= getSize(value)) {
return value;
} else {
int offset = value.offsetByCodePoints(0, Util.toInt(length));
return value.substring(0, offset);
}
}
@Override
public String terminal(@Name("length") long length) {
return instance(terminal(value, length));
}
@Ignore
public static java.lang.String terminal(java.lang.String value,
long length) {
if (length <= 0) {
return "";
} else if (length >= getSize(value)) {
return value;
} else {
int offset = value.offsetByCodePoints(0,
Util.toInt(value.length()-length));
return value.substring(offset, value.length());
}
}
public java.lang.String join(@Name("objects")
@TypeInfo("ceylon.language::Iterable<ceylon.language::Object,ceylon.language::Null>")
Iterable<? extends java.lang.Object,?> objects) {
return join(value, objects);
}
@Ignore
public static java.lang.String join(java.lang.String value,
Iterable<? extends java.lang.Object, ?> objects) {
java.lang.StringBuilder result = new java.lang.StringBuilder();
Iterator<? extends java.lang.Object> it = objects.iterator();
java.lang.Object elem = it.next();
if (!(elem instanceof Finished)) {
result.append(elem);
if (value.isEmpty()) {
while (!((elem = it.next()) instanceof Finished)) {
result.append(elem);
}
}
else {
while (!((elem = it.next()) instanceof Finished)) {
result.append(value).append(elem);
}
}
}
return result.toString();
}
@Ignore
public java.lang.String join() {
return "";
}
@Ignore
public static java.lang.String join(java.lang.String value) {
return "";
}
@Override
public String measure(@Name("from") final Integer from,
@Name("length") final long length) {
return instance(measure(value, from.longValue(), length));
}
@Ignore
public static java.lang.String measure(java.lang.String value,
final long from, final long length) {
long fromIndex = from;
long len = getSize(value);
if (fromIndex >= len || length <= 0) {
return "";
}
long resultLength;
if (fromIndex + length > len) {
resultLength = len - fromIndex;
}
else {
resultLength = length;
}
int start = value.offsetByCodePoints(0, Util.toInt(fromIndex));
int end = value.offsetByCodePoints(start, Util.toInt(resultLength));
return value.substring(start, end);
}
@Override
public String span(@Name("from") final Integer from,
@Name("to") final Integer to) {
return instance(span(value, from.longValue(), to.longValue()));
}
@Override
public String spanFrom(@Name("from") final Integer from) {
return instance(spanFrom(value, from.longValue()));
}
@Ignore
public static java.lang.String spanFrom(java.lang.String value,
long from) {
long len = getSize(value);
if (len == 0) {
return "";
}
if (from >= len) {
return "";
}
long toIndex = len - 1;
if (from < 0) {
from = 0;
}
int start = value.offsetByCodePoints(0, Util.toInt(from));
int end = value.offsetByCodePoints(start,
Util.toInt(toIndex - from + 1));
return value.substring(start, end);
}
@Ignore
public static List<? extends Character> sublist(
java.lang.String value, long from, long to) {
return instance(value).sublist(from, to);
}
@Ignore
public static List<? extends Character> sublistTo(
final java.lang.String value, final long to) {
return new BaseCharacterList() {
@Override
public Character getFromFirst(long index) {
if (index>to) {
return null;
}
else {
return String.getFromFirst(value, index);
}
}
@Override
public boolean getEmpty() {
return to<0 || value.isEmpty();
}
@Override
public Integer getLastIndex() {
long size = getSize();
return size>0 ? Integer.instance(size-1) : null;
}
@Override
public long getSize() {
long size = String.getSize(value);
return size>to ? to+1 : size;
}
@Override
public Iterator<? extends Character> iterator() {
return new BaseIterator<Character>
(Character.$TypeDescriptor$) {
int offset = 0;
@Override
public java.lang.Object next() {
if (offset < value.length() && offset<=to) {
int codePoint = value.codePointAt(offset);
offset += java.lang.Character.charCount(codePoint);
return Character.instance(codePoint);
}
else {
return finished_.get_();
}
}
};
}
@Override
public List<? extends Character> sublistTo(long t) {
if (t>=to) {
return this;
}
else {
return String.sublistTo(value, to+t);
}
}
@Override
public boolean contains(java.lang.Object element) {
int index;
if (element instanceof String) {
index = value.indexOf(((String)element).value);
}
else if (element instanceof Character) {
index = value.indexOf(((Character)element).codePoint);
}
else {
return false;
}
if (index<0) {
return false;
}
else {
return value.offsetByCodePoints(0, index)<=to;
}
}
};
}
@Override
public List<? extends Character> sublistTo(
@Name("to") long to) {
return sublistTo(value, to);
}
@Ignore
public static List<? extends Character> sublistFrom(
final java.lang.String value, final long from) {
return new BaseCharacterList() {
int start;
{
if (start<0) {
start = 0;
}
else {
try {
start =
value.offsetByCodePoints(0,
Util.toInt(from));
}
catch (IndexOutOfBoundsException e) {
start = value.length();
}
}
}
@Override
public Character getFromFirst(long index) {
try {
int offset =
start +
value.offsetByCodePoints(start,
Util.toInt(index));
return Character.instance(
value.codePointAt(offset));
}
catch (IndexOutOfBoundsException e) {
return null;
}
}
@Override
public boolean getEmpty() {
return start >= value.length();
}
@Override
public Integer getLastIndex() {
long size = getSize();
return size>0 ? Integer.instance(size-1) : null;
}
@Override
public long getSize() {
return value.codePointCount(start,
value.length());
}
@Override
public Iterator<? extends Character> iterator() {
return new BaseIterator<Character>
(Character.$TypeDescriptor$) {
int offset = start;
@Override
public java.lang.Object next() {
if (offset < value.length()) {
int codePoint = value.codePointAt(offset);
offset += java.lang.Character.charCount(codePoint);
return Character.instance(codePoint);
}
else {
return finished_.get_();
}
}
};
}
@Override
public List<? extends Character> sublistFrom(long f) {
if (f<=0) {
return this;
}
else {
return String.sublistFrom(value, from+f);
}
}
@Override
public boolean contains(java.lang.Object element) {
if (element instanceof String) {
return value.indexOf(((String)element).value, start) >= 0;
}
else if (element instanceof Character) {
return value.indexOf(((Character)element).codePoint, start) >= 0;
}
else {
return false;
}
}
};
}
@Override
public List<? extends Character> sublistFrom(
@Name("from") long from) {
return sublistFrom(value, from);
}
@Override
public String spanTo(@Name("to") final Integer to) {
return instance(spanTo(value, to.longValue()));
}
@Ignore
public static java.lang.String spanTo(java.lang.String value,
final long to) {
long len = getSize(value);
if (len == 0) {
return "";
}
long toIndex = to;
if (toIndex < 0) {
return "";
}
if (toIndex >= len) {
toIndex = len - 1;
}
int start = 0;
int end = value.offsetByCodePoints(start, Util.toInt(toIndex + 1));
return value.substring(start, end);
}
@Ignore
public static java.lang.String span(java.lang.String value,
long from, long to) {
long len = getSize(value);
if (len == 0) {
return "";
}
boolean reverse = to < from;
if (reverse) {
long _tmp = to;
to = from;
from = _tmp;
}
if (to < 0 || from >= len) {
return "";
}
if (to >= len) {
to = len - 1;
}
if (from < 0) {
from = 0;
}
int start = value.offsetByCodePoints(0, Util.toInt(from));
int end = value.offsetByCodePoints(start,
Util.toInt(to - from + 1));
java.lang.String result = value.substring(start, end);
return reverse ? getReversed(result) : result;
}
@Override
public String getReversed() {
return instance(getReversed(value));
}
@Ignore
public static java.lang.String getReversed(java.lang.String value) {
long len = getSize(value);
if (len < 2) {
return value;
}
// FIXME: this would be better to directly build the Sequence<Character>
java.lang.StringBuilder builder
= new java.lang.StringBuilder(value.length());
int offset = value.length();
while (offset > 0) {
int c = value.codePointBefore(offset);
builder.appendCodePoint(c);
offset -= java.lang.Character.charCount(c);
}
return builder.toString();
}
@Override
public String repeat(@Name("times") long times) {
return instance(repeat(value, times));
}
@Ignore
public static java.lang.String repeat(java.lang.String value,
long times) {
int len = value.length();
if (times<=0 || len==0) return "";
if (times==1) return value;
java.lang.StringBuilder builder =
new java.lang.StringBuilder(Util.toInt(len*times));
for (int i=0; i<times; i++) {
builder.append(value);
}
return builder.toString();
}
public java.lang.String replace(
@Name("substring") java.lang.String substring,
@Name("replacement") java.lang.String replacement) {
return replace(value, substring, replacement);
}
@Ignore
public static java.lang.String replace(java.lang.String value,
java.lang.String substring, java.lang.String replacement) {
int index = value.indexOf(substring);
if (index<0) return value;
java.lang.StringBuilder builder =
new java.lang.StringBuilder(value);
while (index>=0) {
builder.replace(index, index+substring.length(), replacement);
index = builder.indexOf(substring, index+replacement.length());
}
return builder.toString();
}
public java.lang.String replaceFirst(
@Name("substring") java.lang.String substring,
@Name("replacement") java.lang.String replacement) {
return replaceFirst(value, substring, replacement);
}
@Ignore
public static java.lang.String replaceFirst(java.lang.String value,
java.lang.String substring, java.lang.String replacement) {
int index = value.indexOf(substring);
if (index<0) {
return value;
}
else {
return value.substring(0,index) + replacement +
value.substring(index+substring.length());
}
}
public java.lang.String replaceLast(
@Name("substring") java.lang.String substring,
@Name("replacement") java.lang.String replacement) {
return replaceLast(value, substring, replacement);
}
@Ignore
public static java.lang.String replaceLast(java.lang.String value,
java.lang.String substring, java.lang.String replacement) {
int index = value.lastIndexOf(substring);
if (index<0) {
return value;
}
else {
return value.substring(0,index) + replacement +
value.substring(index+substring.length());
}
}
@TypeInfo("ceylon.language::Iterable<ceylon.language::String,ceylon.language::Nothing>")
public Iterable<? extends String, ?> split(
@TypeInfo(value="ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
@Defaulted
@Name("splitting")
@FunctionalParameter("(ch)")
Callable<? extends Boolean> splitting,
@Defaulted
@Name("discardSeparators")
boolean discardSeparators,
@Defaulted
@Name("groupSeparators")
boolean groupSeparators) {
if (value.isEmpty()) {
return new Singleton<String>(String.$TypeDescriptor$, this);
}
return new StringTokens(value, splitting,
!discardSeparators, groupSeparators);
}
@Ignore
public static Iterable<? extends String, ?>
split(java.lang.String value,
Callable<? extends Boolean> splitting,
boolean discardSeparators,
boolean groupSeparators) {
if (value.isEmpty()) {
return new Singleton<String>(String.$TypeDescriptor$,
instance(value));
}
return new StringTokens(value, splitting,
!discardSeparators, groupSeparators);
}
@Ignore
public Iterable<? extends String, ?>
split(Callable<? extends Boolean> splitting,
boolean discardSeparators) {
return split(splitting, discardSeparators,
split$groupSeparators(splitting, discardSeparators));
}
@Ignore
public static Iterable<? extends String, ?>
split(java.lang.String value,
Callable<? extends Boolean> splitting,
boolean discardSeparators) {
return split(value, splitting, discardSeparators,
split$groupSeparators(splitting, discardSeparators));
}
@Ignore
public Iterable<? extends String, ?> split(
Callable<? extends Boolean> splitting) {
return split(splitting, split$discardSeparators(splitting));
}
@Ignore
public static Iterable<? extends String, ?>
split(java.lang.String value,
Callable<? extends Boolean> splitting) {
return split(value, splitting, split$discardSeparators(splitting));
}
@Ignore
public Iterable<? extends String, ?> split() {
return split(split$splitting());
}
@Ignore
public static Iterable<? extends String, ?>
split(java.lang.String value) {
return split(value, split$splitting());
}
@Ignore
public static Callable<? extends Boolean> split$splitting(){
return WHITESPACE;
}
@Ignore
public static boolean split$discardSeparators(java.lang.Object separator){
return true;
}
@Ignore
public static boolean split$groupSeparators(java.lang.Object separator,
boolean discardSeparators){
return true;
}
@SuppressWarnings("rawtypes")
@TypeInfo("ceylon.language::Tuple<ceylon.language::String,ceylon.language::String,ceylon.language::Tuple<ceylon.language::String,ceylon.language::String,ceylon.language::Empty>>")
@Override
public Sequence slice(@Name("index") long index) {
return slice(value,index);
}
@Ignore
@SuppressWarnings("rawtypes")
public static Sequence slice(java.lang.String value, long index) {
java.lang.String first;
java.lang.String second;
if (index<=0) {
first = "";
second = value;
}
else if (index>=value.length()) {
first = value;
second = "";
}
else {
int intIndex =
value.offsetByCodePoints(0,
Util.toInt(index));
first = value.substring(0,intIndex);
second = value.substring(intIndex);
}
return new Tuple(String.$TypeDescriptor$,
new String[] { instance(first),
instance(second) });
}
@Ignore
private static Callable<Boolean> WHITESPACE =
new AbstractCallable<Boolean>(Boolean.$TypeDescriptor$,
TypeDescriptor.klass(Tuple.class, Character.$TypeDescriptor$,
Character.$TypeDescriptor$, Empty.$TypeDescriptor$),
"whitespace", (short)-1) {
@Override
public Boolean $call$(java.lang.Object ch) {
return Boolean.instance(((Character) ch).getWhitespace());
}
};
@Ignore
private static Callable<Boolean> NEWLINES =
new AbstractCallable<Boolean>(Boolean.$TypeDescriptor$,
TypeDescriptor.klass(Tuple.class, Character.$TypeDescriptor$,
Character.$TypeDescriptor$, Empty.$TypeDescriptor$),
"newlines", (short)-1) {
@Override
public Boolean $call$(java.lang.Object ch) {
return Boolean.instance(((Character) ch).intValue()=='\n');
}
};
@Ignore
private static Callable<Boolean> RETURNS =
new AbstractCallable<Boolean>(Boolean.$TypeDescriptor$,
TypeDescriptor.klass(Tuple.class, Character.$TypeDescriptor$,
Character.$TypeDescriptor$, Empty.$TypeDescriptor$),
"returns", (short)-1) {
@Override
public Boolean $call$(java.lang.Object ch) {
return Boolean.instance(((Character) ch).intValue()=='\r');
}
};
private static Callable<String> TRIM_RETURNS =
new AbstractCallable<String>($TypeDescriptor$,
TypeDescriptor.klass(Tuple.class, $TypeDescriptor$,
$TypeDescriptor$, Empty.$TypeDescriptor$),
"", (short)-1) {
@Override
public String $call$(java.lang.Object str) {
return instance(trimTrailing(((String)str).value, RETURNS));
}
};
private static Callable<String> CONCAT_LINES_WITH_BREAKS =
new AbstractCallable<String>($TypeDescriptor$,
TypeDescriptor.klass(Tuple.class,
TypeDescriptor.klass(Sequence.class,$TypeDescriptor$),
TypeDescriptor.klass(Sequence.class,$TypeDescriptor$),
Empty.$TypeDescriptor$),
"", (short)-1) {
@Override
public String $call$(java.lang.Object seq) {
@SuppressWarnings("unchecked")
Sequence<? extends String> strings =
(Sequence<? extends String>) seq;
java.lang.String str = strings.getFirst().value;
if (strings.getSize()>1) {
str += strings.getFromFirst(1).value;
}
return instance(str);
}
};
@TypeInfo("ceylon.language::Iterable<ceylon.language::String>")
@Transient
public Iterable<? extends String, ?> getLines() {
return split(NEWLINES, true, false).map($TypeDescriptor$, TRIM_RETURNS);
}
@Ignore
public static Iterable<? extends String, ?>
getLines(java.lang.String value) {
return split(value, NEWLINES, true, false).map($TypeDescriptor$, TRIM_RETURNS);
}
@TypeInfo("ceylon.language::Iterable<ceylon.language::String>")
@Transient
public Iterable<? extends String, ?> getLinesWithBreaks() {
return split(NEWLINES, false, false).partition(2)
.map($TypeDescriptor$, CONCAT_LINES_WITH_BREAKS);
}
@Ignore
public static Iterable<? extends String, ?>
getLinesWithBreaks(java.lang.String value) {
return split(value, NEWLINES, false, false).partition(2)
.map($TypeDescriptor$, CONCAT_LINES_WITH_BREAKS);
}
@Override
public String $clone() {
return this;
}
@Ignore
public static java.lang.String $clone(java.lang.String value) {
return value;
}
@Ignore
public static <Result> Iterable<? extends Result, ?>
map(@Ignore TypeDescriptor $reifiedResult, java.lang.String value,
Callable<? extends Result> f) {
return instance(value).map($reifiedResult, f);
}
@Ignore
public static <Result, OtherAbsent> Iterable<? extends Result, ?>
flatMap(@Ignore TypeDescriptor $reified$Result, @Ignore TypeDescriptor $reified$OtherAbsent, java.lang.String value,
Callable<? extends Iterable<? extends Result, ? extends OtherAbsent>> collecting) {
return instance(value).flatMap($reified$Result, $reified$OtherAbsent, collecting);
}
@SuppressWarnings("rawtypes")
@Ignore
public static <Type> Iterable
narrow(@Ignore TypeDescriptor $reifiedType, java.lang.String value) {
return instance(value).narrow($reifiedType);
}
@Ignore
public static Sequential<? extends Character>
select(java.lang.String value,
Callable<? extends Boolean> f) {
return instance(value).select(f);
}
@Transient
@Override
public String getCoalesced() {
return this; //Can't have null characters
}
@Ignore
public static java.lang.String
getCoalesced(java.lang.String value) {
return value;
}
@Override @Ignore
public <Default> Iterable<?,?>
defaultNullElements(@Ignore TypeDescriptor $reifiedDefault,
Default defaultValue) {
return this;
}
@Ignore
public static <Default> Iterable<?,?>
defaultNullElements(@Ignore TypeDescriptor $reifiedDefault,
java.lang.String string, Default defaultValue) {
return instance(string);
}
@Override
public String getRest() {
return value.isEmpty() ? this :
instance(value.substring(value.offsetByCodePoints(0, 1)));
}
@Ignore
public static java.lang.String getRest(java.lang.String value) {
return value.isEmpty() ? "" :
value.substring(value.offsetByCodePoints(0, 1));
}
@Ignore
public static Iterable<? extends Character,?>
getExceptLast(java.lang.String value) {
return instance(value).getExceptLast();
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character getFirst() {
return getFirst(value);
}
@Ignore
public static Character getFirst(java.lang.String value) {
if (value.isEmpty()) {
return null;
} else {
return Character.instance(value.codePointAt(0));
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character getLast() {
return getLast(value);
}
@Ignore
public static Character getLast(java.lang.String value) {
if (value.isEmpty()) {
return null;
} else {
return Character.instance(value.codePointBefore(value.length()));
}
}
@Ignore
public static Sequential<? extends Character>
sequence(java.lang.String value) {
return instance(value).sequence();
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character find(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return find(value,f);
}
@Ignore
public static Character find(java.lang.String value,
Callable<? extends Boolean> f) {
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
Character ch = Character.instance(codePoint);
if(f.$call$(ch).booleanValue()) {
return ch;
}
offset += java.lang.Character.charCount(codePoint);
}
return null;
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character findLast(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return findLast(value,f);
}
@Ignore
public static Character findLast(java.lang.String value,
Callable<? extends Boolean> f) {
Character result = null;
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
Character ch = Character.instance(codePoint);
if(f.$call$(ch).booleanValue()) {
result = ch;
}
offset += java.lang.Character.charCount(codePoint);
}
return result;
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Entry<ceylon.language::Integer,ceylon.language::Character>")
public Entry<? extends Integer,? extends Character> locate(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return locate(value,f);
}
@Ignore
public static Entry<? extends Integer,? extends Character>
locate(java.lang.String value,
Callable<? extends Boolean> f) {
int index = 0;
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
Character ch = Character.instance(codePoint);
if(f.$call$(ch).booleanValue()) {
return new Entry<Integer,Character>(
Integer.$TypeDescriptor$, Character.$TypeDescriptor$,
Integer.instance(index), ch);
}
offset += java.lang.Character.charCount(codePoint);
index++;
}
return null;
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Entry<ceylon.language::Integer,ceylon.language::Character>")
public Entry<? extends Integer,? extends Character> locateLast(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return locateLast(value,f);
}
@Ignore
public static Entry<? extends Integer,? extends Character>
locateLast(java.lang.String value,
Callable<? extends Boolean> f) {
for (int offset = value.length(); offset > 0;) {
int codePoint = value.codePointBefore(offset);
Character ch = Character.instance(codePoint);
if (f.$call$(ch).booleanValue()) {
int index = value.codePointCount(0, offset);
return new Entry<Integer,Character>(
Integer.$TypeDescriptor$, Character.$TypeDescriptor$,
Integer.instance(index), ch);
}
offset -= java.lang.Character.charCount(codePoint);
}
return null;
}
@Ignore
public static Iterable<? extends Entry<? extends Integer, ? extends Character>, ? extends java.lang.Object>
locations(java.lang.String value,
Callable<? extends Boolean> selecting) {
return instance(value).locations(selecting);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Ignore
public static Sequential<? extends Character>
sort(java.lang.String value, Callable<? extends Comparison> f) {
if (value.isEmpty()) {
return (Sequential)empty_.get_();
} else {
return instance(value).sort(f);
}
}
@Ignore
public static java.lang.Object max(java.lang.String value,
Callable<? extends Comparison> comparing) {
return instance(value).max(comparing);
}
@Ignore
public static Iterable<? extends Integer, ?>
indexesWhere(final java.lang.String value,
final Callable<? extends Boolean> fun) {
return new BaseIterable<Integer, java.lang.Object>
(Integer.$TypeDescriptor$, Null.$TypeDescriptor$) {
@Override
public Iterator<? extends Integer> iterator() {
return new BaseIterator<Integer>
(Integer.$TypeDescriptor$) {
int index = 0;
int count = 0;
@Override
public java.lang.Object next() {
if (index>=value.length()) {
return finished_.get_();
}
while (true) {
int cp = value.codePointAt(index);
index+=java.lang.Character.charCount(cp);
if (index>=value.length()) {
return finished_.get_();
}
else {
if (fun.$call$(Character.instance(cp)).booleanValue()) {
return Integer.instance(count++);
}
count++;
}
}
}
};
}
};
}
@Override
@TypeInfo("ceylon.language::Iterable<ceylon.language::Integer>")
public Iterable<? extends Integer, ? extends java.lang.Object>
indexesWhere(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> fun) {
return indexesWhere(value, fun);
}
@Ignore
public static Integer
firstIndexWhere(java.lang.String value, Callable<? extends Boolean> fun) {
if (value.isEmpty()) {
return null;
}
int index = 0;
int count = 0;
while (true) {
int cp = value.codePointAt(index);
index+=java.lang.Character.charCount(cp);
if (index>=value.length()) {
return null;
}
else {
if (fun.$call$(Character.instance(cp)).booleanValue()) {
return Integer.instance(count);
}
count++;
}
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer firstIndexWhere(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> fun) {
return firstIndexWhere(value, fun);
}
@Ignore
public static Integer
lastIndexWhere(java.lang.String value, Callable<? extends Boolean> fun) {
int index = value.length();
if (index==0) {
return null;
}
long count = getSize(value);
while (true) {
int cp = value.codePointBefore(index);
index-=java.lang.Character.charCount(cp);
if (index<=0) {
return null;
}
else {
count--;
if (fun.$call$(Character.instance(cp)).booleanValue()) {
return Integer.instance(count);
}
}
}
}
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
@Override
public Integer lastIndexWhere(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> fun) {
return lastIndexWhere(value, fun);
}
@Ignore
public static Iterable<? extends Character, ?>
filter(java.lang.String value, Callable<? extends Boolean> f) {
return instance(value).filter(f);
}
@Ignore
public static <Result> Sequential<? extends Result>
collect(@Ignore TypeDescriptor $reifiedResult,
java.lang.String value, Callable<? extends Result> f) {
return instance(value).collect($reifiedResult, f);
}
@Ignore
public static <Result> Callable<? extends Result>
fold(@Ignore TypeDescriptor $reifiedResult,
java.lang.String value, Result ini) {
return instance(value).fold($reifiedResult, ini);
}
@Ignore
public static <Result>
Callable<? extends Iterable<? extends Result,? extends java.lang.Object>>
scan(@Ignore TypeDescriptor $reifiedResult,
java.lang.String value, Result ini) {
return instance(value).scan($reifiedResult, ini);
}
@Override
@TypeInfo("Result|ceylon.language::Character|ceylon.language::Null")
@TypeParameters(@TypeParameter("Result"))
public <Result> java.lang.Object
reduce(@Ignore TypeDescriptor $reifiedResult,
@Name("accumulating")
@FunctionalParameter("(partial,element)")
@TypeInfo("ceylon.language::Callable<Result,ceylon.language::Tuple<Result|ceylon.language::Character,Result|ceylon.language::Character,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>>")
Callable<? extends Result> f) {
return reduce($reifiedResult,value,f);
}
@Ignore
public static <Result> java.lang.Object
reduce(@Ignore TypeDescriptor $reifiedResult,
java.lang.String value,
Callable<? extends Result> f) {
if (value.isEmpty()) {
return null;
}
int initial = value.codePointAt(0);
java.lang.Object partial = Character.instance(initial);
for (int offset = java.lang.Character.charCount(initial);
offset < value.length();) {
int codePoint = value.codePointAt(offset);
partial = f.$call$(partial, Character.instance(codePoint));
offset += java.lang.Character.charCount(codePoint);
}
return partial;
}
@Override
@TypeInfo(declaredVoid=true,
value="ceylon.language::Anything")
public java.lang.Object each(
@Name("step")
@FunctionalParameter("!(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Anything,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends java.lang.Object> step) {
return each(value,step);
}
@Ignore
public static java.lang.Object each(java.lang.String value,
Callable<? extends java.lang.Object> f) {
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
f.$call$(Character.instance(codePoint));
offset += java.lang.Character.charCount(codePoint);
}
return null;
}
@Override
@TypeInfo("ceylon.language::Boolean")
public boolean any(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return any(value,f);
}
@Ignore
public static boolean any(java.lang.String value,
Callable<? extends Boolean> f) {
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
if (f.$call$(Character.instance(codePoint)).booleanValue()) {
return true;
}
offset += java.lang.Character.charCount(codePoint);
}
return false;
}
@Override
@TypeInfo("ceylon.language::Boolean")
public boolean every(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return every(value,f);
}
@Ignore
public static boolean every(java.lang.String value,
Callable<? extends Boolean> f) {
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
if(!f.$call$(Character.instance(codePoint)).booleanValue()) {
return false;
}
offset += java.lang.Character.charCount(codePoint);
}
return true;
}
@Ignore
public static Iterable<? extends Character, ?>
skip(java.lang.String value, long skip) {
return instance(value).skip(skip);
}
@Ignore
public static Iterable<? extends Character, ?>
take(java.lang.String value, long take) {
return instance(value).take(take);
}
@Ignore
public static Iterable<? extends Character, ?>
takeWhile(java.lang.String value, Callable<? extends Boolean> take) {
return instance(value).takeWhile(take);
}
@Ignore
public static Iterable<? extends Character, ?>
skipWhile(java.lang.String value, Callable<? extends Boolean> skip) {
return instance(value).skipWhile(skip);
}
@Ignore
public static Iterable<? extends Character, ?>
by(java.lang.String value, long step) {
return instance(value).by(step);
}
@Override
@TypeInfo("ceylon.language::Integer")
public long count(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return count(value,f);
}
@Ignore
public static long count(java.lang.String value,
Callable<? extends Boolean> f) {
int count = 0;
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
if(f.$call$(Character.instance(codePoint)).booleanValue()) {
count++;
}
offset += java.lang.Character.charCount(codePoint);
}
return count;
}
@Ignore
@SuppressWarnings({"unchecked", "rawtypes"})
public static Iterable<? extends Entry<? extends Integer, ? extends Character>, ?>
getIndexed(java.lang.String value) {
if (value.isEmpty()) {
return (Iterable) instance(value);
} else {
return instance(value).getIndexed();
}
}
@Ignore
@SuppressWarnings("rawtypes")
public static <Other,Absent> Iterable
chain(@Ignore TypeDescriptor $reifiedOther,
@Ignore TypeDescriptor $reifiedOtherAbsent,
java.lang.String value,
Iterable<? extends Other, ? extends Absent> other) {
if (value.isEmpty()) {
return other;
}
else {
return instance(value).chain($reifiedOther,
$reifiedOtherAbsent, other);
}
}
@Ignore
@SuppressWarnings("rawtypes")
public static <Other> Iterable
follow(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, Other other) {
return instance(value).follow($reifiedOther, other);
}
@Ignore
public static <Other> Iterable<? extends java.lang.Object, ? extends java.lang.Object>
interpose(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, Other other) {
return instance(value).interpose($reifiedOther, other);
}
@Ignore
@SuppressWarnings("rawtypes")
public static <Other> Iterable
interpose(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, Other other, long step) {
return instance(value).interpose($reifiedOther, other, step);
}
@Ignore
@SuppressWarnings("rawtypes")
public static <Other, OtherAbsent> Iterable
product(@Ignore TypeDescriptor $reified$Other,
@Ignore TypeDescriptor $reified$OtherAbsent,
java.lang.String value,
Iterable<? extends Other, ? extends OtherAbsent> other) {
return instance(value).product($reified$Other, $reified$OtherAbsent, other);
}
@Ignore @SuppressWarnings({ "rawtypes" })
public static <Other>List patch(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, List<? extends Other> list, long from, long length) {
return instance(value).patch($reifiedOther, list, from, length);
}
@Ignore @SuppressWarnings({ "rawtypes" })
public static <Other>List patch(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, List<? extends Other> list, long from) {
return instance(value).patch($reifiedOther, list, from, 0);
}
@Ignore
public static Iterable<? extends Character,?>
getCycled(java.lang.String value) {
return instance(value).getCycled();
}
@Override
@Ignore
public TypeDescriptor $getType$() {
return $TypeDescriptor$;
}
public static boolean largerThan(java.lang.String value,
String other) {
return value.compareTo(other.value)>0;
}
public static boolean largerThan(java.lang.String value,
java.lang.String other) {
return value.compareTo(other)>0;
}
@Override
public boolean largerThan(@Name("other") String other) {
return value.compareTo(other.value)>0;
}
public static boolean notSmallerThan(java.lang.String value,
String other) {
return value.compareTo(other.value)>=0;
}
public static boolean notSmallerThan(java.lang.String value,
java.lang.String other) {
return value.compareTo(other)>=0;
}
@Override
public boolean notSmallerThan(@Name("other") String other) {
return value.compareTo(other.value)>=0;
}
public static boolean smallerThan(java.lang.String value,
String other) {
return value.compareTo(other.value)<0;
}
public static boolean smallerThan(java.lang.String value,
java.lang.String other) {
return value.compareTo(other)<0;
}
@Override
public boolean smallerThan(@Name("other") String other) {
return value.compareTo(other.value)<0;
}
public static boolean notLargerThan(java.lang.String value,
String other) {
return value.compareTo(other.value)<=0;
}
public static boolean notLargerThan(java.lang.String value,
java.lang.String other) {
return value.compareTo(other)<=0;
}
@Override
public boolean notLargerThan(@Name("other") String other) {
return value.compareTo(other.value)<=0;
}
@Ignore
public static <Result,Args extends Sequential<? extends java.lang.Object>> Callable<? extends Iterable<? extends Result, ?>>
spread(@Ignore TypeDescriptor $reifiedResult,
@Ignore TypeDescriptor $reifiedArgs,
java.lang.String value, Callable<? extends Callable<? extends Result>> method) {
return instance(value).spread($reifiedResult, $reifiedArgs, method);
}
public java.lang.String pad(
@Name("size")
long size,
@Name("character")
@TypeInfo("ceylon.language::Character")
@Defaulted
int character) {
return pad(value, size, character);
}
@Ignore
public java.lang.String pad(long size) {
return pad(value, size, pad$character(size));
}
@Ignore
public static java.lang.String pad(java.lang.String value, long size) {
return pad(value, size, pad$character(size));
}
@Ignore
public static int pad$character(long size) {
return ' ';
}
@Ignore
public static java.lang.String pad(java.lang.String value, long size, int character) {
int length = value.length();
if (size<=length) return value;
long leftPad = (size-length)/2;
long rightPad = leftPad + (size-length)%2;
java.lang.StringBuilder builder = new java.lang.StringBuilder();
for (int i=0;i<leftPad;i++) {
builder.appendCodePoint(character);
}
builder.append(value);
for (int i=0;i<rightPad;i++) {
builder.appendCodePoint(character);
}
return builder.toString();
}
public java.lang.String padLeading(
@Name("size")
long size,
@Name("character")
@TypeInfo("ceylon.language::Character")
@Defaulted
int character) {
return padLeading(value, size, character);
}
@Ignore
public java.lang.String padLeading(long size) {
return padLeading(value, size, padLeading$character(size));
}
@Ignore
public static java.lang.String padLeading(java.lang.String value, long size) {
return padLeading(value, size, padLeading$character(size));
}
@Ignore
public static int padLeading$character(long size) {
return ' ';
}
@Ignore
public static java.lang.String padLeading(java.lang.String value, long size, int character) {
int length = value.length();
if (size<=length) return value;
long leftPad = size-length;
java.lang.StringBuilder builder = new java.lang.StringBuilder();
for (int i=0;i<leftPad;i++) {
builder.appendCodePoint(character);
}
builder.append(value);
return builder.toString();
}
public java.lang.String padTrailing(
@Name("size")
long size,
@Name("character")
@TypeInfo("ceylon.language::Character")
@Defaulted
int character) {
return padTrailing(value, size, character);
}
@Ignore
public java.lang.String padTrailing(long size) {
return padTrailing(value, size, padTrailing$character(size));
}
@Ignore
public static java.lang.String padTrailing(java.lang.String value, long size) {
return padTrailing(value, size, padTrailing$character(size));
}
@Ignore
public static int padTrailing$character(long size) {
return ' ';
}
@Ignore
public static java.lang.String padTrailing(java.lang.String value, long size, int character) {
int length = value.length();
if (size<=length) return value;
long rightPad = size-length;
java.lang.StringBuilder builder = new java.lang.StringBuilder(value);
for (int i=0;i<rightPad;i++) {
builder.appendCodePoint(character);
}
return builder.toString();
}
@Ignore
public static Iterable getPaired(java.lang.String value) {
return instance(value).getPaired();
}
@Ignore
public static Iterable<? extends Sequence<? extends Character>,? extends java.lang.Object>
partition(java.lang.String value, long length) {
return instance(value).partition(length);
}
@Ignore
public long copyTo$sourcePosition(Array<Character> destination){
return 0;
}
@Ignore
public long copyTo$destinationPosition(Array<Character> destination,
long sourcePosition){
return 0;
}
@Ignore
public long copyTo$length(Array<Character> destination,
long sourcePosition, long destinationPosition){
return Math.min(value.length()-sourcePosition,
destination.getSize()-destinationPosition);
}
@Ignore
public static void copyTo(java.lang.String value, Array<Character> destination){
copyTo(value, destination, 0, 0);
}
@Ignore
public static void copyTo(java.lang.String value, Array<Character> destination, long sourcePosition){
copyTo(value, destination, sourcePosition, 0);
}
@Ignore
public static void copyTo(java.lang.String value, Array<Character> destination,
long sourcePosition, long destinationPosition){
copyTo(value, destination,
sourcePosition, destinationPosition,
Math.min(value.length()-sourcePosition,
destination.getSize()-destinationPosition));
}
@Ignore
public void copyTo(Array<Character> destination){
copyTo(value, destination, 0, 0);
}
@Ignore
public void copyTo(Array<Character> destination, long sourcePosition){
copyTo(value, destination, sourcePosition, 0);
}
@Ignore
public void copyTo(Array<Character> destination,
long sourcePosition, long destinationPosition){
copyTo(value, destination,
sourcePosition, destinationPosition,
copyTo$length(destination, sourcePosition, destinationPosition));
}
@Ignore
public static void copyTo(java.lang.String value,
Array<Character> destination,
long sourcePosition,
long destinationPosition,
long length){
int count = 0;
int dest = Util.toInt(destinationPosition);
for (int index = value.offsetByCodePoints(0,Util.toInt(sourcePosition));
count<length;) {
int codePoint = value.codePointAt(index);
((int[])destination.toArray())[count+dest] = codePoint;
index += java.lang.Character.charCount(codePoint);
count++;
}
}
public void copyTo(@Name("destination") Array<Character> destination,
@Name("sourcePosition") @Defaulted long sourcePosition,
@Name("destinationPosition") @Defaulted long destinationPosition,
@Name("length") @Defaulted long length){
copyTo(value, destination, sourcePosition, destinationPosition, length);
}
@Ignore
public static Iterable<? extends Sequence<? extends Character>, ? extends java.lang.Object>
getPermutations(java.lang.String value) {
return instance(value).getPermutations();
}
@Ignore
public static <Group> Iterable<? extends Entry<? extends Group, ? extends Sequence<? extends Character>>, ? extends java.lang.Object>
group(java.lang.String value, TypeDescriptor $reifiedGroup, Callable<? extends Group> fun) {
return instance(value).group($reifiedGroup, fun);
}
@Ignore
public static <Group,Result> Iterable<? extends Entry<? extends Group, ? extends Result>, ? extends java.lang.Object>
summarize(java.lang.String value, TypeDescriptor $reifiedGroup, TypeDescriptor $reifiedResult,
Callable<? extends Group> fun, Callable<? extends Result> fold) {
return instance(value).summarize($reifiedGroup, $reifiedResult, fun, fold);
}
@Ignore
public static Iterable<? extends Character, ? extends java.lang.Object>
getDistinct(java.lang.String value) {
return instance(value).getDistinct();
}
//WARNING: pure boilerplate from here on!
@Override @Ignore
public Collection$impl<? extends Character> $ceylon$language$Collection$impl() {
return new Collection$impl<Character>
(Character.$TypeDescriptor$, this);
}
@Override @Ignore
public Iterable<? extends Sequence<? extends Character>, ? extends java.lang.Object> getPermutations() {
return $ceylon$language$Collection$impl().getPermutations();
}
@Override @Ignore
public Iterable$impl<? extends Character, ? extends java.lang.Object> $ceylon$language$Iterable$impl() {
return new Iterable$impl<Character, java.lang.Object>
(Character.$TypeDescriptor$, Null.$TypeDescriptor$, this);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> by(long step) {
return $ceylon$language$Iterable$impl().by(step);
}
@Override @Ignore
public <Other, OtherAbsent> Iterable chain(TypeDescriptor arg0, TypeDescriptor arg1,
Iterable<? extends Other, ? extends OtherAbsent> arg2) {
return $ceylon$language$Iterable$impl().chain(arg0, arg1, arg2);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> filter(Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().filter(arg0);
}
@Override @Ignore
public <Result, OtherAbsent> Iterable flatMap(TypeDescriptor arg0, TypeDescriptor arg1,
Callable<? extends Iterable<? extends Result, ? extends OtherAbsent>> arg2) {
return $ceylon$language$Iterable$impl().flatMap(arg0, arg1, arg2);
}
@Override @Ignore
public <Result> Callable<? extends Result> fold(TypeDescriptor arg0, Result arg1) {
return $ceylon$language$Iterable$impl().fold(arg0, arg1);
}
@Override @Ignore
public <Other> Iterable follow(TypeDescriptor arg0, Other arg1) {
return $ceylon$language$Iterable$impl().follow(arg0, arg1);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> getCycled() {
return $ceylon$language$Iterable$impl().getCycled();
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> getDistinct() {
return $ceylon$language$Iterable$impl().getDistinct();
}
/*@Ignore
public static Set<? extends Character> elements(java.lang.String value) {
return instance(value).elements();
}
@Override @Ignore
public Set<? extends Character> elements() {
return $ceylon$language$Iterable$impl().elements();
}*/
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> getExceptLast() {
return $ceylon$language$Iterable$impl().getExceptLast();
}
@Override @Ignore
public Iterable<? extends Entry<? extends Integer, ? extends Character>, ? extends java.lang.Object> getIndexed() {
return $ceylon$language$Iterable$impl().getIndexed();
}
@Override @Ignore
public Iterable<? extends Sequence<? extends Character>, ? extends java.lang.Object> getPaired() {
return $ceylon$language$Iterable$impl().getPaired();
}
@Override @Ignore
public <Group> Map<? extends Group, ? extends Sequence<? extends Character>> group(TypeDescriptor arg0,
Callable<? extends Group> arg1) {
return $ceylon$language$Iterable$impl().group(arg0, arg1);
}
@Override @Ignore
public <Group,Result> Map<? extends Group, ? extends Result> summarize(TypeDescriptor arg0,
TypeDescriptor arg1, Callable<? extends Group> arg2, Callable<? extends Result> arg3) {
return $ceylon$language$Iterable$impl().summarize(arg0, arg1, arg2, arg3);
}
@Override @Ignore
public java.lang.Object indexes() {
return $ceylon$language$Iterable$impl().indexes();
}
@Override @Ignore
public <Other> Iterable interpose(TypeDescriptor arg0, Other arg1) {
return $ceylon$language$Iterable$impl().interpose(arg0, arg1);
}
@Override @Ignore
public <Other> Iterable interpose(TypeDescriptor arg0, Other arg1, long arg2) {
return $ceylon$language$Iterable$impl().interpose(arg0, arg1, arg2);
}
@Override @Ignore
public <Other> long interpose$step(TypeDescriptor arg0, Other arg1) {
return $ceylon$language$Iterable$impl().interpose$step(arg0, arg1);
}
@Override @Ignore
public Iterable<? extends Entry<? extends Integer, ? extends Character>, ? extends java.lang.Object> locations(
Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().locations(arg0);
}
@Override @Ignore
public <Result> Iterable<? extends Result, ? extends java.lang.Object> map(TypeDescriptor arg0,
Callable<? extends Result> arg1) {
return $ceylon$language$Iterable$impl().map(arg0, arg1);
}
@Override @Ignore
public java.lang.Object max(Callable<? extends Comparison> arg0) {
return $ceylon$language$Iterable$impl().max(arg0);
}
@Override @Ignore
public <Type> Iterable narrow(TypeDescriptor arg0) {
return $ceylon$language$Iterable$impl().narrow(arg0);
}
@Override @Ignore
public Iterable<? extends Sequence<? extends Character>, ? extends java.lang.Object> partition(long arg0) {
return $ceylon$language$Iterable$impl().partition(arg0);
}
@Override @Ignore
public <Other, OtherAbsent> Iterable product(TypeDescriptor arg0, TypeDescriptor arg1,
Iterable<? extends Other, ? extends OtherAbsent> arg2) {
return $ceylon$language$Iterable$impl().product(arg0, arg1, arg2);
}
@Override @Ignore
public <Result> Callable<? extends Iterable<? extends Result, ? extends java.lang.Object>> scan(TypeDescriptor arg0,
Result arg1) {
return $ceylon$language$Iterable$impl().scan(arg0, arg1);
}
@Override @Ignore
public Sequential<? extends Character> select(Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().select(arg0);
}
@Override @Ignore
public Sequential<? extends Character> sequence() {
return $ceylon$language$Iterable$impl().sequence();
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> skip(long arg0) {
return $ceylon$language$Iterable$impl().skip(arg0);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> skipWhile(Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().skipWhile(arg0);
}
@Override @Ignore
public Sequential<? extends Character> sort(Callable<? extends Comparison> arg0) {
return $ceylon$language$Iterable$impl().sort(arg0);
}
@Override @Ignore
public <Result, Args extends Sequential<? extends java.lang.Object>> Callable<? extends Iterable<? extends Result, ? extends java.lang.Object>> spread(
TypeDescriptor arg0, TypeDescriptor arg1, Callable<? extends Callable<? extends Result>> arg2) {
return $ceylon$language$Iterable$impl().spread(arg0, arg1, arg2);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> take(long arg0) {
return $ceylon$language$Iterable$impl().take(arg0);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> takeWhile(Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().takeWhile(arg0);
}
@Override @Ignore
public Category$impl<? super java.lang.Object> $ceylon$language$Category$impl() {
return new Category$impl<java.lang.Object>(Object.$TypeDescriptor$, this);
}
@Override @Ignore
public boolean containsAny(Iterable<? extends java.lang.Object, ? extends java.lang.Object> arg0) {
return $ceylon$language$Category$impl().containsAny(arg0);
}
@Override @Ignore
public boolean containsEvery(Iterable<? extends java.lang.Object, ? extends java.lang.Object> arg0) {
return $ceylon$language$Category$impl().containsEvery(arg0);
}
@Override @Ignore
public Correspondence$impl<? super Integer, ? extends Character> $ceylon$language$Correspondence$impl() {
return new Correspondence$impl<Integer,Character>(Integer.$TypeDescriptor$, Character.$TypeDescriptor$, this);
}
@Override @Ignore
public boolean definesAny(Iterable<? extends Integer, ? extends java.lang.Object> arg0) {
return $ceylon$language$Correspondence$impl().definesAny(arg0);
}
@Override @Ignore
public boolean definesEvery(Iterable<? extends Integer, ? extends java.lang.Object> arg0) {
return $ceylon$language$Correspondence$impl().definesEvery(arg0);
}
@Override @Ignore
public <Absent> Iterable<? extends Character, ? extends Absent> getAll(TypeDescriptor arg0,
Iterable<? extends Integer, ? extends Absent> arg1) {
return $ceylon$language$Correspondence$impl().getAll(arg0, arg1);
}
@Override @Ignore
public List$impl<? extends Character> $ceylon$language$List$impl() {
return new List$impl<Character>(Character.$TypeDescriptor$, this);
}
@Override @Ignore
public <Result> Sequential<? extends Result> collect(TypeDescriptor arg0, Callable<? extends Result> arg1) {
return $ceylon$language$List$impl().collect(arg0, arg1);
}
@Override @Ignore
public Character get(Integer index) {
//NOTE THIS IMPORTANT PERFORMANCE OPTIMIZATION
return getFromFirst(value, index.value);
}
@Override @Ignore
public <Other> List patch(TypeDescriptor arg0, List<? extends Other> arg1) {
return $ceylon$language$List$impl().patch(arg0, arg1);
}
@Override @Ignore
public <Other> List patch(TypeDescriptor arg0, List<? extends Other> arg1, long arg2) {
return $ceylon$language$List$impl().patch(arg0, arg1, arg2);
}
@Override @Ignore
public <Other> List patch(TypeDescriptor arg0, List<? extends Other> arg1, long arg2, long arg3) {
return $ceylon$language$List$impl().patch(arg0, arg1, arg2, arg3);
}
@Override @Ignore
public <Other> long patch$from(TypeDescriptor arg0, List<? extends Other> arg1) {
return $ceylon$language$List$impl().patch$from(arg0, arg1);
}
@Override @Ignore
public <Other> long patch$length(TypeDescriptor arg0, List<? extends Other> arg1, long arg2) {
return $ceylon$language$List$impl().patch$length(arg0, arg1, arg2);
}
@Override @Ignore
public List<? extends Character> sublist(long arg0, long arg1) {
return $ceylon$language$List$impl().sublist(arg0, arg1);
}
@Override @Ignore
public SearchableList$impl<Character> $ceylon$language$SearchableList$impl() {
return new SearchableList$impl<Character>(Character.$TypeDescriptor$, this);
}
// @Override
// public boolean startsWith(List<? extends java.lang.Object> sublist) {
// return $ceylon$language$SearchableList$impl().startsWith(sublist);
// }
//
// @Override
// public boolean endsWith(List<? extends java.lang.Object> sublist) {
// return $ceylon$language$SearchableList$impl().endsWith(sublist);
// }
@Override @Ignore
public long countInclusions(List<? extends Character> arg0) {
return countInclusions(value, arg0);
}
@Override @Ignore
public long countInclusions$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public long countOccurrences(Character element) {
return countOccurrences(value, element.codePoint);
}
@Override @Ignore
public long countOccurrences(Character element, long from) {
return countOccurrences(value, element.codePoint, from);
}
@Override @Ignore
public long countOccurrences$from(Character arg0) {
return 0;
}
@Override @Ignore
public long countOccurrences$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
@Override @Ignore
public Integer firstInclusion(List<? extends Character> arg0) {
return firstInclusion(value, arg0);
}
@Override @Ignore
public long firstInclusion$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public Integer firstOccurrence(Character element) {
return firstOccurrence(value, element.codePoint);
}
@Override @Ignore
public Integer firstOccurrence(Character element, long from) {
return firstOccurrence(value, element.codePoint, from);
}
@Override @Ignore
public long firstOccurrence$from(Character arg0) {
return 0;
}
@Override @Ignore
public long firstOccurrence$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
@Override @Ignore
public boolean includes(List<? extends Character> arg0) {
return includes(value, arg0);
}
@Override @Ignore
public long includes$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public Iterable<? extends Integer, ? extends java.lang.Object> inclusions(List<? extends Character> arg0) {
return inclusions(value, arg0);
}
@Override @Ignore
public long inclusions$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public Integer lastInclusion(List<? extends Character> arg0) {
return lastInclusion(value, arg0);
}
@Override @Ignore
public long lastInclusion$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public Integer lastOccurrence(Character element) {
return lastOccurrence(value, element.codePoint);
}
@Override @Ignore
public Integer lastOccurrence(Character element, long from) {
return lastOccurrence(value, element.codePoint, from);
}
@Override @Ignore
public long lastOccurrence$from(Character arg0) {
return 0;
}
@Override @Ignore
public long lastOccurrence$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
@Override @Ignore
public Iterable<? extends Integer, ? extends java.lang.Object> occurrences(Character element) {
return occurrences(value, element.codePoint);
}
@Override @Ignore
public Iterable<? extends Integer, ? extends java.lang.Object> occurrences(Character element, long from) {
return occurrences(value, element.codePoint, from);
}
@Override @Ignore
public long occurrences$from(Character arg0) {
return 0;
}
@Override @Ignore
public long occurrences$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
@Override @Ignore
public boolean occurs(Character element) {
return occurs(value, element.codePoint);
}
@Override @Ignore
public boolean occurs(Character element, long arg1) {
return occurs(value, element.codePoint, arg1);
}
@Override @Ignore
public long occurs$from(Character arg0) {
return 0;
}
@Override @Ignore
public long occurs$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
}
| runtime/ceylon/language/String.java | package ceylon.language;
import java.util.Locale;
import com.redhat.ceylon.compiler.java.Util;
import com.redhat.ceylon.compiler.java.language.AbstractCallable;
import com.redhat.ceylon.compiler.java.language.StringTokens;
import com.redhat.ceylon.compiler.java.metadata.Annotation;
import com.redhat.ceylon.compiler.java.metadata.Annotations;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Class;
import com.redhat.ceylon.compiler.java.metadata.Defaulted;
import com.redhat.ceylon.compiler.java.metadata.FunctionalParameter;
import com.redhat.ceylon.compiler.java.metadata.Ignore;
import com.redhat.ceylon.compiler.java.metadata.Name;
import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes;
import com.redhat.ceylon.compiler.java.metadata.Transient;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
import com.redhat.ceylon.compiler.java.metadata.TypeParameter;
import com.redhat.ceylon.compiler.java.metadata.TypeParameters;
import com.redhat.ceylon.compiler.java.metadata.ValueType;
import com.redhat.ceylon.compiler.java.runtime.model.ReifiedType;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
import ceylon.language.impl.BaseCharacterList;
import ceylon.language.impl.BaseIterable;
import ceylon.language.impl.BaseIterator;
@Ceylon(major = 8)
@Class(extendsType="ceylon.language::Object",
basic = false, identifiable = false)
@SatisfiedTypes({"ceylon.language::SearchableList<ceylon.language::Character>",
"ceylon.language::Comparable<ceylon.language::String>",
"ceylon.language::Summable<ceylon.language::String>",
"ceylon.language::Ranged<ceylon.language::Integer,ceylon.language::Character,ceylon.language::String>"})
@ValueType
@Annotations({
@Annotation(
value = "doc",
arguments = {"A string of characters..."}),
@Annotation(
value = "by",
arguments = {"Gavin"}),
@Annotation("shared"),
@Annotation("final")})
public final class String
implements Comparable<String>, SearchableList<Character>,
Summable<String>, ReifiedType {
@Ignore
public final static TypeDescriptor $TypeDescriptor$ =
TypeDescriptor.klass(String.class);
@Ignore
public final java.lang.String value;
@Ignore @Override
public Comparable$impl<String> $ceylon$language$Comparable$impl() {
return new Comparable$impl<String>(String.$TypeDescriptor$, this);
}
@SuppressWarnings("rawtypes")
public String(@Name("characters")
@TypeInfo("ceylon.language::Iterable<ceylon.language::Character,ceylon.language::Null>")
final Iterable<? extends Character, ?> characters) {
if (characters instanceof String) {
value = ((String)characters).value;
} else {
java.lang.String s = null;
if (characters instanceof Array.ArrayIterable) {
s = ((Array.ArrayIterable) characters).stringValue();
}
if (s != null) {
value = s;
} else {
java.lang.StringBuilder sb = new java.lang.StringBuilder();
java.lang.Object $tmp;
for (Iterator<? extends Character> $val$iter$0 = characters.iterator();
!(($tmp = $val$iter$0.next()) instanceof Finished);) {
sb.appendCodePoint(((Character)$tmp).codePoint);
}
value = sb.toString();
}
}
}
@Ignore
public String(final java.lang.String string) {
value = string;
}
@Override
@Transient
public java.lang.String toString() {
return value;
}
@Ignore
public static java.lang.String toString(java.lang.String value) {
return value;
}
@Ignore
public static ceylon.language.String instance(java.lang.String s) {
if (s==null) return null;
return new String(s);
}
@Ignore
public static ceylon.language.String instanceJoining(java.lang.String... strings) {
StringBuffer buf = new StringBuffer();
for (java.lang.String s: strings)
buf.append(s);
return instance(buf.toString());
}
@Ignore
public static ceylon.language.String instanceJoining(String... strings) {
StringBuffer buf = new StringBuffer();
for (String s: strings)
buf.append(s.value);
return instance(buf.toString());
}
public java.lang.String getUppercased() {
return getUppercased(value);
}
@Ignore
public static java.lang.String getUppercased(java.lang.String value) {
return value.toUpperCase(Locale.ROOT);
}
public java.lang.String getLowercased() {
return getLowercased(value);
}
@Ignore
public static java.lang.String getLowercased(java.lang.String value) {
return value.replace("\u0130", "i\u0307") //workaround for bug
.toLowerCase(Locale.ROOT);
}
@Override
public boolean equals(@Name("that") java.lang.Object that) {
if (that instanceof String) {
String s = (String) that;
return value.equals(s.value);
}
else {
return false;
}
}
@Ignore
public static boolean equals(java.lang.String value,
java.lang.Object that) {
if (that instanceof String) {
String s = (String) that;
return value.equals(s.value);
}
else {
return false;
}
}
public boolean equalsIgnoringCase(
@Name("that") java.lang.String that) {
return value.equalsIgnoreCase(that);
}
@Ignore
public static boolean equalsIgnoringCase(
java.lang.String value,
java.lang.String that) {
return value.equalsIgnoreCase(that);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Ignore
public static int hashCode(java.lang.String value) {
return value.hashCode();
}
private static Comparison comparison(int c) {
return c < 0 ? smaller_.get_() :
(c == 0 ? equal_.get_() : larger_.get_());
}
@Override
public Comparison compare(@Name("other") String other) {
return comparison(value.compareTo(other.value));
}
@Ignore
public static Comparison compare(java.lang.String value,
java.lang.String otherValue) {
return comparison(value.compareTo(otherValue));
}
public Comparison compareIgnoringCase(
@Name("other") java.lang.String other) {
return comparison(value.compareToIgnoreCase(other));
}
@Ignore
public static Comparison compareIgnoringCase(
java.lang.String value,
java.lang.String otherValue) {
return comparison(value.compareToIgnoreCase(otherValue));
}
@Override
public String plus(@Name("other") String other) {
return instance(value + other.value);
}
@Ignore
public static java.lang.String plus(java.lang.String value,
java.lang.String otherValue) {
return value + otherValue;
}
@Override
@TypeInfo("ceylon.language::Integer")
public long getSize() {
//TODO: should we cache this value in an instvar?
// But remember that we'll mostly be using the static verion
// of this method! So an instvar won't help much.
return value.codePointCount(0, value.length());
}
@Ignore
public static long getSize(java.lang.String value) {
return value.codePointCount(0, value.length());
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
@Transient
public Integer getLastIndex() {
long length = getSize();
return (length == 0) ? null : Integer.instance(length - 1);
}
@Ignore
public static Integer getLastIndex(java.lang.String value) {
long length = getSize(value);
return (length == 0) ? null : Integer.instance(length - 1);
}
@Override
public boolean getEmpty() {
return value.isEmpty();
}
@Ignore
public static boolean getEmpty(java.lang.String value) {
return value.isEmpty();
}
// @Override
// @TypeInfo("ceylon.language::Null|ceylon.language::Character")
// public Character get(@Name("index") Integer key) {
// return getFromFirst(value, key.longValue());
// }
@Ignore
public static Character get(java.lang.String value, long key) {
return getFromFirst(value, key);
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character getFromLast(@Name("index") long key) {
return getFromLast(value, key);
}
@Ignore
public static Character getFromLast(java.lang.String value, long key) {
int index = Util.toInt(key);
int codePoint;
try {
int offset = value.offsetByCodePoints(value.length(), -index-1);
codePoint = value.codePointAt(offset);
}
catch (IndexOutOfBoundsException e) {
return null;
}
return Character.instance(codePoint);
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character getFromFirst(@Name("index") long key) {
return getFromFirst(value, key);
}
@Ignore
public static Character getFromFirst(java.lang.String value, long key) {
int index = Util.toInt(key);
int codePoint;
try {
int offset = value.offsetByCodePoints(0, index);
codePoint = value.codePointAt(offset);
}
catch (IndexOutOfBoundsException e) {
return null;
}
return Character.instance(codePoint);
}
@Override
public boolean defines(@Name("index") Integer key) {
long index = key.longValue();
return index >= 0 && index < getSize();
}
@Ignore
public static boolean defines(java.lang.String value, long key) {
return key >= 0 && key < getSize(value);
}
/*@Override
@TypeInfo("ceylon.language::Entry<ceylon.language::Boolean,ceylon.language::Null|ceylon.language::Character>")
public Entry<? extends Boolean, ? extends Character> lookup(@Name("index") Integer index) {
return lookup(value, index.value);
}
@Ignore
public static Entry<? extends Boolean,? extends Character>
lookup(java.lang.String value, long index) {
Character item = getFromFirst(value, index);
return new Entry<Boolean,Character>(
Boolean.$TypeDescriptor$,
Character.$TypeDescriptor$,
Boolean.instance(item!=null),
item);
}*/
@Override
@Transient
public Sequential<? extends ceylon.language.Integer> getKeys() {
return getKeys(value);
}
@Ignore
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Sequential<? extends ceylon.language.Integer>
getKeys(java.lang.String value) {
long size = value.length();
if (size==0) {
return (Sequential) empty_.get_();
}
else {
return new Span<Integer>(Integer.$TypeDescriptor$,
Integer.instance(0), Integer.instance(size-1));
}
}
@Ignore
public static java.lang.Object indexes(java.lang.String value) {
return getKeys(value);
}
@Ignore
public static boolean definesEvery(java.lang.String value,
Iterable<? extends Integer,?> keys) {
//TODO: inefficient ... better to cache the result
// of getSize()
// TODO We're still boxing here!
return instance(value).definesEvery(keys);
}
@Ignore
public static boolean definesEvery(java.lang.String value) {
return true;
}
@Ignore
public static boolean definesAny(java.lang.String value,
Iterable<? extends Integer, ?> keys) {
//TODO: inefficient ... better to cache the result
// of getSize()
// TODO We're still boxing here!
return instance(value).definesAny(keys);
}
@Ignore
public static boolean definesAny(java.lang.String value) {
return false;
}
@Ignore
public static <Absent extends Null>
Iterable<? extends Character, ? extends Absent>
getAll(TypeDescriptor $reifiedAbsent, java.lang.String value,
Iterable<? extends Integer, Absent> keys) {
// TODO We're still boxing here!
return instance(value).getAll($reifiedAbsent,keys);
}
@Ignore
public static boolean occurs(java.lang.String value,
int element) {
return occurs(value, element, 0);
}
@Ignore
public static boolean occurs(java.lang.String value,
int element, long from) {
return occurs(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static boolean occurs(java.lang.String value,
int element, long from, long length) {
if (from>=value.length() || length<=0) {
return false;
}
if (from<0) {
length+=from;
from = 0;
}
int start;
try {
start = value.offsetByCodePoints(0, (int)from);
}
catch (IndexOutOfBoundsException e) {
return false;
}
int index = value.indexOf(element, start);
return index>=0 && index<length+from;
}
@Override
public boolean occurs(@Name("element")
Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return occurs(value, element.codePoint, from, length);
}
@Ignore
public static boolean occursAt(java.lang.String value,
long index, int element) {
if (index<0 || index>=value.length()) {
return false;
}
try {
int offset;
try {
offset = value.offsetByCodePoints(0, (int)index);
}
catch (IndexOutOfBoundsException e) {
return false;
}
return element == value.codePointAt(offset);
}
catch (IndexOutOfBoundsException e) {
return false;
}
}
@Override
public boolean occursAt(
@Name("index") long index,
@Name("element") Character element) {
return occursAt(value, index, element.codePoint);
}
@Ignore
public static Iterable<? extends Integer, ?>
occurrences(java.lang.String value, int element) {
return occurrences(value, element, 0);
}
@Ignore
public static Iterable<? extends Integer, ?>
occurrences(java.lang.String value, int element,
final long from) {
return occurrences(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static Iterable<? extends Integer, ?>
occurrences(final java.lang.String value, final int element,
final long from, final long length) {
return new BaseIterable<Integer, java.lang.Object>
(Integer.$TypeDescriptor$, Null.$TypeDescriptor$) {
@Override
public Iterator<? extends Integer> iterator() {
return new BaseIterator<Integer>
(Integer.$TypeDescriptor$) {
long count = from;
int len = java.lang.Character.charCount(element);
int index;
{
try {
index = value.offsetByCodePoints(0,
Util.toInt(from));
}
catch (IndexOutOfBoundsException e) {
index = value.length();
}
}
@Override
public java.lang.Object next() {
if (index>=value.length()) {
return finished_.get_();
}
while (true) {
int result = value.indexOf(element, index);
if (result<0) {
return finished_.get_();
}
count += value.codePointCount(index, result);
long c = count;
index = result + len;
if (count-from>=length) {
return finished_.get_();
}
else {
count++;
return Integer.instance(c);
}
}
}
};
}
};
}
@Override
@TypeInfo("ceylon.language::Iterable<ceylon.language::Integer>")
public Iterable<? extends Integer, ? extends java.lang.Object>
occurrences(@Name("element") Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return occurrences(value, element.codePoint, from, length);
}
@Ignore
public static long
countOccurrences(java.lang.String value,
int element) {
return countOccurrences(value, element, 0);
}
@Ignore
public static long
countOccurrences(java.lang.String value,
int element, long from) {
return countOccurrences(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static long
countOccurrences(java.lang.String value,
int element,
long from, long length) {
if (from>=value.length() || length<=0) {
return 0;
}
if (from<0) {
length+=from;
from = 0;
}
int i;
try {
i = value.offsetByCodePoints(0, (int)from);
}
catch (IndexOutOfBoundsException e) {
return 0;
}
int count = 0;
while (true) {
i = value.indexOf(element, i);
if (i<0 || i>=from+length) {
return count;
}
else {
count++;
i++;
}
}
}
@Override
public long countOccurrences(
@Name("sublist")
Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return countOccurrences(value, element.codePoint, from, length);
}
@Ignore
public static boolean includes(java.lang.String value,
List<? extends Character> sublist) {
return includes(value, sublist, 0);
}
@Ignore
public static boolean includes(java.lang.String value,
List<? extends Character> sublist, long from) {
if (from>value.length()) {
return false;
}
if (from<0) {
from = 0;
}
if (sublist instanceof String) {
String string = (String) sublist;
int offset;
try {
offset = value.offsetByCodePoints(0, (int)from);
}
catch (IndexOutOfBoundsException e) {
return value.isEmpty();
}
int index = value.indexOf(string.value, offset);
return index >= 0;
}
else {
return instance(value).includes(sublist, from);
}
}
@Override
public boolean includes(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return includes(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().includes(sublist, from);
}
}
@Ignore
public static boolean includesAt(java.lang.String value,
long index, List<? extends Character> sublist) {
if (index<0 || index>value.length()) {
return false;
}
if (sublist instanceof String) {
String string = (String) sublist;
java.lang.String str = string.value;
try {
int offset;
try {
offset = value.offsetByCodePoints(0, (int)index);
}
catch (IndexOutOfBoundsException e) {
return sublist.getEmpty();
}
return value.regionMatches(offset, str, 0, str.length());
}
catch (IndexOutOfBoundsException e) {
return false;
}
}
else {
return instance(value).includesAt(index, sublist);
}
}
@Override
public boolean includesAt(@Name("index") long index,
@Name("sublist") List<? extends Character> sublist) {
if (sublist instanceof String) {
return includesAt(value, index, sublist);
}
else {
return $ceylon$language$SearchableList$impl().includesAt(index, sublist);
}
}
@Ignore
public static Iterable<? extends Integer, ?>
inclusions(java.lang.String value,
List<? extends Character> substring) {
return inclusions(value, substring, 0);
}
@Ignore
public static Iterable<? extends Integer, ?>
inclusions(final java.lang.String value,
final List<? extends Character> substring,
final long from) {
if (!(substring instanceof String)) {
return instance(value).inclusions(substring);
}
final String string = (String) substring;
return new BaseIterable<Integer, java.lang.Object>
(Integer.$TypeDescriptor$, Null.$TypeDescriptor$) {
@Override
public Iterator<? extends Integer> iterator() {
return new BaseIterator<Integer>
(Integer.$TypeDescriptor$) {
long count = from;
int len = java.lang.Character.charCount(
string.value.codePointAt(0));
int index;
{
try {
index = value.offsetByCodePoints(0,
Util.toInt(from));
}
catch (IndexOutOfBoundsException e) {
index = value.length();
}
}
@Override
public java.lang.Object next() {
if (index>=value.length()) {
return finished_.get_();
}
while (true) {
int result = value.indexOf(string.value, index);
if (result<0) {
return finished_.get_();
}
count += value.codePointCount(index, result);
long c = count;
index = result + len;
count++;
return Integer.instance(c);
}
}
};
}
};
}
@Override
@TypeInfo("ceylon.language::Iterable<ceylon.language::Integer>")
public Iterable<? extends Integer, ? extends java.lang.Object>
inclusions(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return inclusions(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().inclusions(sublist, from);
}
}
@Ignore
public static long
countInclusions(java.lang.String value,
List<? extends Character> sublist) {
return countInclusions(value, sublist, 0);
}
@Ignore
public static long
countInclusions(java.lang.String value,
List<? extends Character> sublist,
long from) {
if (from>value.length()) {
return 0;
}
if (from<0) {
from = 0;
}
if (sublist instanceof String) {
String string = (String) sublist;
java.lang.String str = string.value;
int i;
try {
i = value.offsetByCodePoints(0, (int)from);
}
catch (IndexOutOfBoundsException e) {
return 0;
}
int count = 0;
while (true) {
i = value.indexOf(str, i);
if (i<0) {
return count;
}
else {
i++;
count++;
}
}
}
else {
return instance(value).countInclusions(sublist, from);
}
}
@Override
public long countInclusions(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return countInclusions(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().countInclusions(sublist, from);
}
}
@Ignore
public static Integer firstInclusion(java.lang.String value,
List<? extends Character> sublist) {
return firstInclusion(value, sublist, 0);
}
@Ignore
public static Integer firstInclusion(java.lang.String value,
List<? extends Character> sublist,
long from) {
if (from>value.length()) {
return null;
}
if (from<0) {
from = 0;
}
if (sublist instanceof String) {
String string = (String) sublist;
int start = value.offsetByCodePoints(0, (int)from);
int index = value.indexOf(string.value, start);
if (index >= 0) {
return Integer.instance(from +
value.codePointCount(start, index));
} else {
return null;
}
}
else {
return instance(value).firstInclusion(sublist, from);
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer firstInclusion(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return firstInclusion(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().firstInclusion(sublist, from);
}
}
public static Integer lastInclusion(java.lang.String value,
List<? extends Character> sublist) {
return lastInclusion(value, sublist, 0);
}
public static Integer lastInclusion(java.lang.String value,
List<? extends Character> sublist, long from) {
if (from>value.length()) {
return null;
}
if (from<0) {
from = 0;
}
if (sublist instanceof String) {
String string = (String) sublist;
int start;
try {
start =
value.offsetByCodePoints(value.length(),
-(int)from
- Util.toInt(sublist.getSize()));
}
catch (java.lang.IndexOutOfBoundsException e) {
return null;
}
int index = value.lastIndexOf(string.value, start);
if (index >= 0) {
return Integer.instance(
value.codePointCount(0, index));
}
else {
return null;
}
}
else {
return instance(value).lastInclusion(sublist, from);
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer lastInclusion(
@Name("sublist") List<? extends Character> sublist,
@Defaulted @Name("from") long from) {
if (sublist instanceof String) {
return lastInclusion(value, sublist, from);
}
else {
return $ceylon$language$SearchableList$impl().lastInclusion(sublist, from);
}
}
@Ignore
public static Integer firstOccurrence(java.lang.String value,
int element) {
return firstOccurrence(value, element, 0);
}
@Ignore
public static Integer firstOccurrence(java.lang.String value,
int element, long from) {
return firstOccurrence(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static Integer firstOccurrence(java.lang.String value,
int element,
long from, long length) {
if (from>=value.length() || length<=0) {
return null;
}
if (from<0) {
length+=from;
from = 0;
}
int start;
try {
start = value.offsetByCodePoints(0, (int)from);
}
catch (java.lang.IndexOutOfBoundsException e) {
return null;
}
int index = value.indexOf(element, start);
if (index >= 0) {
int result = value.codePointCount(start, index);
if (result>=length) {
return null;
}
return Integer.instance(from+result);
}
else {
return null;
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer firstOccurrence(
@Name("element") Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return firstOccurrence(value, element.codePoint, from, length);
}
@Ignore
public static Integer lastOccurrence(java.lang.String value,
int element) {
return lastOccurrence(value, element, 0);
}
@Ignore
public static Integer lastOccurrence(java.lang.String value,
int element, long from) {
return lastOccurrence(value, element, from,
java.lang.Integer.MAX_VALUE);
}
@Ignore
public static Integer lastOccurrence(java.lang.String value,
int element, long from, long length) {
if (from>=value.length() || length<=0) {
return null;
}
if (from<0) {
length+=from;
from = 0;
}
int start;
try {
start =
value.offsetByCodePoints(value.length(),
-(int)from - 1);
}
catch (java.lang.IndexOutOfBoundsException e) {
return null;
}
int index = value.lastIndexOf(element, start);
if (index >= 0) {
int dist =
value.codePointCount(start,
value.length());
if (dist>length) {
return null;
}
return Integer.instance(
value.codePointCount(0, index));
}
else {
return null;
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer lastOccurrence(
@Name("element") Character element,
@Defaulted @Name("from") long from,
@Defaulted @Name("length") long length) {
return lastOccurrence(value, element.codePoint, from, length);
}
@Override
@TypeInfo("ceylon.language::Iterator<ceylon.language::Character>")
public Iterator<Character> iterator() {
return new StringIterator(value);
}
@Ignore
public static Iterator<Character> iterator(final java.lang.String value) {
return new StringIterator(value);
}
@Ignore
private static class StringIterator
extends BaseIterator<Character>
implements ReifiedType {
private static TypeDescriptor $TypeDescriptor$ =
TypeDescriptor.klass(StringIterator.class);
final java.lang.String value;
public StringIterator(final java.lang.String value) {
super(Character.$TypeDescriptor$);
this.value = value;
}
private int offset = 0;
@Override
public java.lang.Object next() {
if (offset < value.length()) {
int codePoint = value.codePointAt(offset);
offset += java.lang.Character.charCount(codePoint);
return Character.instance(codePoint);
}
else {
return finished_.get_();
}
}
@Override
@Ignore
public TypeDescriptor $getType$() {
return $TypeDescriptor$;
}
@Override
public java.lang.String toString() {
return '"' + value + '"' + ".iterator()";
}
}
@Override
public boolean contains(@Name("element") java.lang.Object element) {
return contains(value, element);
}
@Ignore
public static boolean contains(java.lang.String value,
java.lang.Object element) {
if (element instanceof String) {
return value.indexOf(((String)element).value) >= 0;
}
else if (element instanceof Character) {
return value.indexOf(((Character)element).codePoint) >= 0;
}
else {
return false;
}
}
@Override
public boolean startsWith(@Name("substring") List<?> substring) {
if (substring instanceof String) {
return value.startsWith(((String)substring).value);
}
else {
return $ceylon$language$List$impl().startsWith(substring);
}
}
@Ignore
public static boolean startsWith(java.lang.String value,
List<?> substring) {
if (substring instanceof String) {
return value.startsWith(((String)substring).value);
}
else {
return instance(value).startsWith(substring);
}
}
@Override
public boolean endsWith(@Name("substring") List<?> substring) {
if (substring instanceof String) {
return value.endsWith(((String)substring).value);
}
else {
return $ceylon$language$List$impl().endsWith(substring);
}
}
@Ignore
public static boolean endsWith(java.lang.String value,
List<?> substring) {
if (substring instanceof String) {
return value.endsWith(((String)substring).value);
}
else {
return instance(value).endsWith(substring);
}
}
@Ignore
public static boolean containsAny(java.lang.String value,
Iterable<?,?> elements) {
// TODO We're still boxing here!
return instance(value).containsAny(elements);
}
@Ignore
public static boolean containsEvery(java.lang.String value,
Iterable<?,?> elements) {
// TODO We're still boxing here!
return instance(value).containsEvery(elements);
}
public boolean longerThan(@TypeInfo("ceylon.language::Integer")
@Name("length") long length) {
try {
value.offsetByCodePoints(0, Util.toInt(length+1));
return true;
}
catch (IndexOutOfBoundsException iobe) {
return false;
}
}
@Ignore
public static boolean longerThan(java.lang.String value,
long length) {
try {
value.offsetByCodePoints(0, Util.toInt(length+1));
return true;
}
catch (IndexOutOfBoundsException iobe) {
return false;
}
}
public boolean shorterThan(@TypeInfo("ceylon.language::Integer")
@Name("length") long length) {
try {
value.offsetByCodePoints(0, Util.toInt(length));
return false;
}
catch (IndexOutOfBoundsException iobe) {
return true;
}
}
@Ignore
public static boolean shorterThan(java.lang.String value,
long length) {
try {
value.offsetByCodePoints(0, Util.toInt(length));
return false;
}
catch (IndexOutOfBoundsException iobe) {
return true;
}
}
@Transient
public java.lang.String getTrimmed() {
return getTrimmed(value);
}
@Ignore
public static java.lang.String getTrimmed(java.lang.String value) {
// Don't use value.trim() because that has a definition of ws that is
// inconsistent with ceylon.language::Character.whitespace
return internalTrim(value, WHITESPACE);
}
@Override
public String trimLeading(
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
@Name("trimming")@FunctionalParameter("(element)")
Callable<? extends Boolean> characters) {
return instance(trimLeading(value, characters));
}
@Ignore
public static java.lang.String trimLeading(java.lang.String value,
Callable<? extends Boolean> characters) {
int from = 0;
while (from < value.length()) {
int c = java.lang.Character.codePointAt(value, from);
if (!characters.$call$(Character.instance(c)).booleanValue()) {
break;
}
from += java.lang.Character.charCount(c);
}
return value.substring(from);
}
@Override
public String trimTrailing(
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
@Name("trimming")@FunctionalParameter("(element)")
Callable<? extends Boolean> characters) {
return instance(trimTrailing(value, characters));
}
@Ignore
public static java.lang.String trimTrailing(java.lang.String value,
Callable<? extends Boolean> characters) {
int to = value.length();
while (to > 0) {
int c = java.lang.Character.codePointBefore(value, to);
if (!characters.$call$(Character.instance(c)).booleanValue()) {
break;
}
to -= java.lang.Character.charCount(c);
}
return value.substring(0, to);
}
@Override
public String trim(
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
@Name("trimming")@FunctionalParameter("(element)")
Callable<? extends Boolean> characters) {
return instance(trim(value, characters));
}
@Ignore
public static java.lang.String trim(java.lang.String value,
Callable<? extends Boolean> characters) {
return internalTrim(value, characters);
}
@Ignore
private static java.lang.String internalTrim(java.lang.String value,
Callable<? extends Boolean> characters) {
int from = 0;
while (from < value.length()) {
int c = java.lang.Character.codePointAt(value, from);
if (!characters.$call$(Character.instance(c)).booleanValue()) {
break;
}
from += java.lang.Character.charCount(c);
}
int to = value.length();
while (to > from) {
int c = java.lang.Character.codePointBefore(value, to);
if (!characters.$call$(Character.instance(c)).booleanValue()) {
break;
}
to -= java.lang.Character.charCount(c);
}
return value.substring(from, to);
}
public java.lang.String getNormalized() {
return getNormalized(value);
}
@Ignore
public static java.lang.String getNormalized(java.lang.String value) {
java.lang.StringBuilder result =
new java.lang.StringBuilder(value.length());
boolean previousWasWhitespace=false;
for (int i=0;i<value.length();) {
int c = java.lang.Character.codePointAt(value, i);
boolean isWhitespace = java.lang.Character.isWhitespace(c);
if (!isWhitespace) {
result.appendCodePoint(c);
}
else if (!previousWasWhitespace) {
result.append(" ");
}
previousWasWhitespace = isWhitespace;
i+=java.lang.Character.charCount(c);
}
// TODO Should be able to figure out the indices to
// substring on while iterating
return getTrimmed(result.toString());
}
@Override
public String initial(@TypeInfo("ceylon.language::Integer")
@Name("length") long length) {
return instance(initial(value, length));
}
@Ignore
public static java.lang.String initial(java.lang.String value,
long length) {
if (length <= 0) {
return "";
} else if (length >= getSize(value)) {
return value;
} else {
int offset = value.offsetByCodePoints(0, Util.toInt(length));
return value.substring(0, offset);
}
}
@Override
public String terminal(@Name("length") long length) {
return instance(terminal(value, length));
}
@Ignore
public static java.lang.String terminal(java.lang.String value,
long length) {
if (length <= 0) {
return "";
} else if (length >= getSize(value)) {
return value;
} else {
int offset = value.offsetByCodePoints(0,
Util.toInt(value.length()-length));
return value.substring(offset, value.length());
}
}
public java.lang.String join(@Name("objects")
@TypeInfo("ceylon.language::Iterable<ceylon.language::Object,ceylon.language::Null>")
Iterable<? extends java.lang.Object,?> objects) {
return join(value, objects);
}
@Ignore
public static java.lang.String join(java.lang.String value,
Iterable<? extends java.lang.Object, ?> objects) {
java.lang.StringBuilder result = new java.lang.StringBuilder();
Iterator<? extends java.lang.Object> it = objects.iterator();
java.lang.Object elem = it.next();
if (!(elem instanceof Finished)) {
result.append(elem);
if (value.isEmpty()) {
while (!((elem = it.next()) instanceof Finished)) {
result.append(elem);
}
}
else {
while (!((elem = it.next()) instanceof Finished)) {
result.append(value).append(elem);
}
}
}
return result.toString();
}
@Ignore
public java.lang.String join() {
return "";
}
@Ignore
public static java.lang.String join(java.lang.String value) {
return "";
}
@Override
public String measure(@Name("from") final Integer from,
@Name("length") final long length) {
return instance(measure(value, from.longValue(), length));
}
@Ignore
public static java.lang.String measure(java.lang.String value,
final long from, final long length) {
long fromIndex = from;
long len = getSize(value);
if (fromIndex >= len || length <= 0) {
return "";
}
long resultLength;
if (fromIndex + length > len) {
resultLength = len - fromIndex;
}
else {
resultLength = length;
}
int start = value.offsetByCodePoints(0, Util.toInt(fromIndex));
int end = value.offsetByCodePoints(start, Util.toInt(resultLength));
return value.substring(start, end);
}
@Override
public String span(@Name("from") final Integer from,
@Name("to") final Integer to) {
return instance(span(value, from.longValue(), to.longValue()));
}
@Override
public String spanFrom(@Name("from") final Integer from) {
return instance(spanFrom(value, from.longValue()));
}
@Ignore
public static java.lang.String spanFrom(java.lang.String value,
long from) {
long len = getSize(value);
if (len == 0) {
return "";
}
if (from >= len) {
return "";
}
long toIndex = len - 1;
if (from < 0) {
from = 0;
}
int start = value.offsetByCodePoints(0, Util.toInt(from));
int end = value.offsetByCodePoints(start,
Util.toInt(toIndex - from + 1));
return value.substring(start, end);
}
@Ignore
public static List<? extends Character> sublist(
java.lang.String value, long from, long to) {
return instance(value).sublist(from, to);
}
@Ignore
public static List<? extends Character> sublistTo(
final java.lang.String value, final long to) {
return new BaseCharacterList() {
@Override
public Character getFromFirst(long index) {
if (index>to) {
return null;
}
else {
return String.getFromFirst(value, index);
}
}
@Override
public boolean getEmpty() {
return to<0 || value.isEmpty();
}
@Override
public Integer getLastIndex() {
long size = getSize();
return size>0 ? Integer.instance(size-1) : null;
}
@Override
public long getSize() {
long size = String.getSize(value);
return size>to ? to+1 : size;
}
@Override
public Iterator<? extends Character> iterator() {
return new BaseIterator<Character>
(Character.$TypeDescriptor$) {
int offset = 0;
@Override
public java.lang.Object next() {
if (offset < value.length() && offset<=to) {
int codePoint = value.codePointAt(offset);
offset += java.lang.Character.charCount(codePoint);
return Character.instance(codePoint);
}
else {
return finished_.get_();
}
}
};
}
@Override
public List<? extends Character> sublistTo(long t) {
if (t>=to) {
return this;
}
else {
return String.sublistTo(value, to+t);
}
}
@Override
public boolean contains(java.lang.Object element) {
int index;
if (element instanceof String) {
index = value.indexOf(((String)element).value);
}
else if (element instanceof Character) {
index = value.indexOf(((Character)element).codePoint);
}
else {
return false;
}
if (index<0) {
return false;
}
else {
return value.offsetByCodePoints(0, index)<=to;
}
}
};
}
@Override
public List<? extends Character> sublistTo(
@Name("to") long to) {
return sublistTo(value, to);
}
@Ignore
public static List<? extends Character> sublistFrom(
final java.lang.String value, final long from) {
return new BaseCharacterList() {
int start;
{
if (start<0) {
start = 0;
}
else {
try {
start =
value.offsetByCodePoints(0,
Util.toInt(from));
}
catch (IndexOutOfBoundsException e) {
start = value.length();
}
}
}
@Override
public Character getFromFirst(long index) {
try {
int offset =
start +
value.offsetByCodePoints(start,
Util.toInt(index));
return Character.instance(
value.codePointAt(offset));
}
catch (IndexOutOfBoundsException e) {
return null;
}
}
@Override
public boolean getEmpty() {
return start >= value.length();
}
@Override
public Integer getLastIndex() {
long size = getSize();
return size>0 ? Integer.instance(size-1) : null;
}
@Override
public long getSize() {
return value.codePointCount(start,
value.length());
}
@Override
public Iterator<? extends Character> iterator() {
return new BaseIterator<Character>
(Character.$TypeDescriptor$) {
int offset = start;
@Override
public java.lang.Object next() {
if (offset < value.length()) {
int codePoint = value.codePointAt(offset);
offset += java.lang.Character.charCount(codePoint);
return Character.instance(codePoint);
}
else {
return finished_.get_();
}
}
};
}
@Override
public List<? extends Character> sublistFrom(long f) {
if (f<=0) {
return this;
}
else {
return String.sublistFrom(value, from+f);
}
}
@Override
public boolean contains(java.lang.Object element) {
if (element instanceof String) {
return value.indexOf(((String)element).value, start) >= 0;
}
else if (element instanceof Character) {
return value.indexOf(((Character)element).codePoint, start) >= 0;
}
else {
return false;
}
}
};
}
@Override
public List<? extends Character> sublistFrom(
@Name("from") long from) {
return sublistFrom(value, from);
}
@Override
public String spanTo(@Name("to") final Integer to) {
return instance(spanTo(value, to.longValue()));
}
@Ignore
public static java.lang.String spanTo(java.lang.String value,
final long to) {
long len = getSize(value);
if (len == 0) {
return "";
}
long toIndex = to;
if (toIndex < 0) {
return "";
}
if (toIndex >= len) {
toIndex = len - 1;
}
int start = 0;
int end = value.offsetByCodePoints(start, Util.toInt(toIndex + 1));
return value.substring(start, end);
}
@Ignore
public static java.lang.String span(java.lang.String value,
long from, long to) {
long len = getSize(value);
if (len == 0) {
return "";
}
boolean reverse = to < from;
if (reverse) {
long _tmp = to;
to = from;
from = _tmp;
}
if (to < 0 || from >= len) {
return "";
}
if (to >= len) {
to = len - 1;
}
if (from < 0) {
from = 0;
}
int start = value.offsetByCodePoints(0, Util.toInt(from));
int end = value.offsetByCodePoints(start,
Util.toInt(to - from + 1));
java.lang.String result = value.substring(start, end);
return reverse ? getReversed(result) : result;
}
@Override
public String getReversed() {
return instance(getReversed(value));
}
@Ignore
public static java.lang.String getReversed(java.lang.String value) {
long len = getSize(value);
if (len < 2) {
return value;
}
// FIXME: this would be better to directly build the Sequence<Character>
java.lang.StringBuilder builder
= new java.lang.StringBuilder(value.length());
int offset = value.length();
while (offset > 0) {
int c = value.codePointBefore(offset);
builder.appendCodePoint(c);
offset -= java.lang.Character.charCount(c);
}
return builder.toString();
}
@Override
public String repeat(@Name("times") long times) {
return instance(repeat(value, times));
}
@Ignore
public static java.lang.String repeat(java.lang.String value,
long times) {
int len = value.length();
if (times<=0 || len==0) return "";
if (times==1) return value;
java.lang.StringBuilder builder =
new java.lang.StringBuilder(Util.toInt(len*times));
for (int i=0; i<times; i++) {
builder.append(value);
}
return builder.toString();
}
public java.lang.String replace(
@Name("substring") java.lang.String substring,
@Name("replacement") java.lang.String replacement) {
return replace(value, substring, replacement);
}
@Ignore
public static java.lang.String replace(java.lang.String value,
java.lang.String substring, java.lang.String replacement) {
int index = value.indexOf(substring);
if (index<0) return value;
java.lang.StringBuilder builder =
new java.lang.StringBuilder(value);
while (index>=0) {
builder.replace(index, index+substring.length(), replacement);
index = builder.indexOf(substring, index+replacement.length());
}
return builder.toString();
}
public java.lang.String replaceFirst(
@Name("substring") java.lang.String substring,
@Name("replacement") java.lang.String replacement) {
return replaceFirst(value, substring, replacement);
}
@Ignore
public static java.lang.String replaceFirst(java.lang.String value,
java.lang.String substring, java.lang.String replacement) {
int index = value.indexOf(substring);
if (index<0) {
return value;
}
else {
return value.substring(0,index) + replacement +
value.substring(index+substring.length());
}
}
public java.lang.String replaceLast(
@Name("substring") java.lang.String substring,
@Name("replacement") java.lang.String replacement) {
return replaceLast(value, substring, replacement);
}
@Ignore
public static java.lang.String replaceLast(java.lang.String value,
java.lang.String substring, java.lang.String replacement) {
int index = value.lastIndexOf(substring);
if (index<0) {
return value;
}
else {
return value.substring(0,index) + replacement +
value.substring(index+substring.length());
}
}
@TypeInfo("ceylon.language::Iterable<ceylon.language::String,ceylon.language::Nothing>")
public Iterable<? extends String, ?> split(
@TypeInfo(value="ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
@Defaulted
@Name("splitting")
@FunctionalParameter("(ch)")
Callable<? extends Boolean> splitting,
@Defaulted
@Name("discardSeparators")
boolean discardSeparators,
@Defaulted
@Name("groupSeparators")
boolean groupSeparators) {
if (value.isEmpty()) {
return new Singleton<String>(String.$TypeDescriptor$, this);
}
return new StringTokens(value, splitting,
!discardSeparators, groupSeparators);
}
@Ignore
public static Iterable<? extends String, ?>
split(java.lang.String value,
Callable<? extends Boolean> splitting,
boolean discardSeparators,
boolean groupSeparators) {
if (value.isEmpty()) {
return new Singleton<String>(String.$TypeDescriptor$,
instance(value));
}
return new StringTokens(value, splitting,
!discardSeparators, groupSeparators);
}
@Ignore
public Iterable<? extends String, ?>
split(Callable<? extends Boolean> splitting,
boolean discardSeparators) {
return split(splitting, discardSeparators,
split$groupSeparators(splitting, discardSeparators));
}
@Ignore
public static Iterable<? extends String, ?>
split(java.lang.String value,
Callable<? extends Boolean> splitting,
boolean discardSeparators) {
return split(value, splitting, discardSeparators,
split$groupSeparators(splitting, discardSeparators));
}
@Ignore
public Iterable<? extends String, ?> split(
Callable<? extends Boolean> splitting) {
return split(splitting, split$discardSeparators(splitting));
}
@Ignore
public static Iterable<? extends String, ?>
split(java.lang.String value,
Callable<? extends Boolean> splitting) {
return split(value, splitting, split$discardSeparators(splitting));
}
@Ignore
public Iterable<? extends String, ?> split() {
return split(split$splitting());
}
@Ignore
public static Iterable<? extends String, ?>
split(java.lang.String value) {
return split(value, split$splitting());
}
@Ignore
public static Callable<? extends Boolean> split$splitting(){
return WHITESPACE;
}
@Ignore
public static boolean split$discardSeparators(java.lang.Object separator){
return true;
}
@Ignore
public static boolean split$groupSeparators(java.lang.Object separator,
boolean discardSeparators){
return true;
}
@SuppressWarnings("rawtypes")
@TypeInfo("ceylon.language::Tuple<ceylon.language::String,ceylon.language::String,ceylon.language::Tuple<ceylon.language::String,ceylon.language::String,ceylon.language::Empty>>")
@Override
public Sequence slice(@Name("index") long index) {
return slice(value,index);
}
@Ignore
@SuppressWarnings("rawtypes")
public static Sequence slice(java.lang.String value, long index) {
java.lang.String first;
java.lang.String second;
if (index<=0) {
first = "";
second = value;
}
else if (index>=value.length()) {
first = value;
second = "";
}
else {
int intIndex =
value.offsetByCodePoints(0,
Util.toInt(index));
first = value.substring(0,intIndex);
second = value.substring(intIndex);
}
return new Tuple(String.$TypeDescriptor$,
new String[] { instance(first),
instance(second) });
}
@Ignore
private static Callable<Boolean> WHITESPACE =
new AbstractCallable<Boolean>(Boolean.$TypeDescriptor$,
TypeDescriptor.klass(Tuple.class, Character.$TypeDescriptor$,
Character.$TypeDescriptor$, Empty.$TypeDescriptor$),
"whitespace", (short)-1) {
@Override
public Boolean $call$(java.lang.Object ch) {
return Boolean.instance(((Character) ch).getWhitespace());
}
};
@Ignore
private static Callable<Boolean> NEWLINES =
new AbstractCallable<Boolean>(Boolean.$TypeDescriptor$,
TypeDescriptor.klass(Tuple.class, Character.$TypeDescriptor$,
Character.$TypeDescriptor$, Empty.$TypeDescriptor$),
"newlines", (short)-1) {
@Override
public Boolean $call$(java.lang.Object ch) {
return Boolean.instance(((Character) ch).intValue()=='\n');
}
};
@Ignore
private static Callable<Boolean> RETURNS =
new AbstractCallable<Boolean>(Boolean.$TypeDescriptor$,
TypeDescriptor.klass(Tuple.class, Character.$TypeDescriptor$,
Character.$TypeDescriptor$, Empty.$TypeDescriptor$),
"returns", (short)-1) {
@Override
public Boolean $call$(java.lang.Object ch) {
return Boolean.instance(((Character) ch).intValue()=='\r');
}
};
private static Callable<String> TRIM_RETURNS =
new AbstractCallable<String>($TypeDescriptor$,
TypeDescriptor.klass(Tuple.class, $TypeDescriptor$,
$TypeDescriptor$, Empty.$TypeDescriptor$),
"", (short)-1) {
@Override
public String $call$(java.lang.Object str) {
return instance(trimTrailing(((String)str).value, RETURNS));
}
};
private static Callable<String> CONCAT_LINES_WITH_BREAKS =
new AbstractCallable<String>($TypeDescriptor$,
TypeDescriptor.klass(Tuple.class,
TypeDescriptor.klass(Sequence.class,$TypeDescriptor$),
TypeDescriptor.klass(Sequence.class,$TypeDescriptor$),
Empty.$TypeDescriptor$),
"", (short)-1) {
@Override
public String $call$(java.lang.Object seq) {
@SuppressWarnings("unchecked")
Sequence<? extends String> strings =
(Sequence<? extends String>) seq;
java.lang.String str = strings.getFirst().value;
if (strings.getSize()>1) {
str += strings.getFromFirst(1).value;
}
return instance(str);
}
};
@TypeInfo("ceylon.language::Iterable<ceylon.language::String>")
@Transient
public Iterable<? extends String, ?> getLines() {
return split(NEWLINES, true, false).map($TypeDescriptor$, TRIM_RETURNS);
}
@Ignore
public static Iterable<? extends String, ?>
getLines(java.lang.String value) {
return split(value, NEWLINES, true, false).map($TypeDescriptor$, TRIM_RETURNS);
}
@TypeInfo("ceylon.language::Iterable<ceylon.language::String>")
@Transient
public Iterable<? extends String, ?> getLinesWithBreaks() {
return split(NEWLINES, false, false).partition(2)
.map($TypeDescriptor$, CONCAT_LINES_WITH_BREAKS);
}
@Ignore
public static Iterable<? extends String, ?>
getLinesWithBreaks(java.lang.String value) {
return split(value, NEWLINES, false, false).partition(2)
.map($TypeDescriptor$, CONCAT_LINES_WITH_BREAKS);
}
@Override
public String $clone() {
return this;
}
@Ignore
public static java.lang.String $clone(java.lang.String value) {
return value;
}
@Ignore
public static <Result> Iterable<? extends Result, ?>
map(@Ignore TypeDescriptor $reifiedResult, java.lang.String value,
Callable<? extends Result> f) {
return instance(value).map($reifiedResult, f);
}
@Ignore
public static <Result, OtherAbsent> Iterable<? extends Result, ?>
flatMap(@Ignore TypeDescriptor $reified$Result, @Ignore TypeDescriptor $reified$OtherAbsent, java.lang.String value,
Callable<? extends Iterable<? extends Result, ? extends OtherAbsent>> collecting) {
return instance(value).flatMap($reified$Result, $reified$OtherAbsent, collecting);
}
@SuppressWarnings("rawtypes")
@Ignore
public static <Type> Iterable
narrow(@Ignore TypeDescriptor $reifiedType, java.lang.String value) {
return instance(value).narrow($reifiedType);
}
@Ignore
public static Sequential<? extends Character>
select(java.lang.String value,
Callable<? extends Boolean> f) {
return instance(value).select(f);
}
@Transient
@Override
public String getCoalesced() {
return this; //Can't have null characters
}
@Ignore
public static java.lang.String
getCoalesced(java.lang.String value) {
return value;
}
@Override @Ignore
public <Default> Iterable<?,?>
defaultNullElements(@Ignore TypeDescriptor $reifiedDefault,
Default defaultValue) {
return this;
}
@Ignore
public static <Default> Iterable<?,?>
defaultNullElements(@Ignore TypeDescriptor $reifiedDefault,
java.lang.String string, Default defaultValue) {
return instance(string);
}
@Override
public String getRest() {
return value.isEmpty() ? this :
instance(value.substring(value.offsetByCodePoints(0, 1)));
}
@Ignore
public static java.lang.String getRest(java.lang.String value) {
return value.isEmpty() ? "" :
value.substring(value.offsetByCodePoints(0, 1));
}
@Ignore
public static Iterable<? extends Character,?>
getExceptLast(java.lang.String value) {
return instance(value).getExceptLast();
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character getFirst() {
return getFirst(value);
}
@Ignore
public static Character getFirst(java.lang.String value) {
if (value.isEmpty()) {
return null;
} else {
return Character.instance(value.codePointAt(0));
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character getLast() {
return getLast(value);
}
@Ignore
public static Character getLast(java.lang.String value) {
if (value.isEmpty()) {
return null;
} else {
return Character.instance(value.codePointBefore(value.length()));
}
}
@Ignore
public static Sequential<? extends Character>
sequence(java.lang.String value) {
return instance(value).sequence();
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character find(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return find(value,f);
}
@Ignore
public static Character find(java.lang.String value,
Callable<? extends Boolean> f) {
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
Character ch = Character.instance(codePoint);
if(f.$call$(ch).booleanValue()) {
return ch;
}
offset += java.lang.Character.charCount(codePoint);
}
return null;
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Character")
public Character findLast(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return findLast(value,f);
}
@Ignore
public static Character findLast(java.lang.String value,
Callable<? extends Boolean> f) {
Character result = null;
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
Character ch = Character.instance(codePoint);
if(f.$call$(ch).booleanValue()) {
result = ch;
}
offset += java.lang.Character.charCount(codePoint);
}
return result;
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Entry<ceylon.language::Integer,ceylon.language::Character>")
public Entry<? extends Integer,? extends Character> locate(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return locate(value,f);
}
@Ignore
public static Entry<? extends Integer,? extends Character>
locate(java.lang.String value,
Callable<? extends Boolean> f) {
int index = 0;
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
Character ch = Character.instance(codePoint);
if(f.$call$(ch).booleanValue()) {
return new Entry<Integer,Character>(
Integer.$TypeDescriptor$, Character.$TypeDescriptor$,
Integer.instance(index), ch);
}
offset += java.lang.Character.charCount(codePoint);
index++;
}
return null;
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Entry<ceylon.language::Integer,ceylon.language::Character>")
public Entry<? extends Integer,? extends Character> locateLast(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return locateLast(value,f);
}
@Ignore
public static Entry<? extends Integer,? extends Character>
locateLast(java.lang.String value,
Callable<? extends Boolean> f) {
Character result = null;
int resultIndex = -1;
int index = 0;
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
Character ch = Character.instance(codePoint);
if (f.$call$(ch).booleanValue()) {
result = ch;
resultIndex = index;
}
offset += java.lang.Character.charCount(codePoint);
index++;
}
return result==null ? null :
new Entry<Integer,Character>(
Integer.$TypeDescriptor$, Character.$TypeDescriptor$,
Integer.instance(resultIndex), result);
}
@Ignore
public static Iterable<? extends Entry<? extends Integer, ? extends Character>, ? extends java.lang.Object>
locations(java.lang.String value,
Callable<? extends Boolean> selecting) {
return instance(value).locations(selecting);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Ignore
public static Sequential<? extends Character>
sort(java.lang.String value, Callable<? extends Comparison> f) {
if (value.isEmpty()) {
return (Sequential)empty_.get_();
} else {
return instance(value).sort(f);
}
}
@Ignore
public static java.lang.Object max(java.lang.String value,
Callable<? extends Comparison> comparing) {
return instance(value).max(comparing);
}
@Ignore
public static Iterable<? extends Integer, ?>
indexesWhere(final java.lang.String value,
final Callable<? extends Boolean> fun) {
return new BaseIterable<Integer, java.lang.Object>
(Integer.$TypeDescriptor$, Null.$TypeDescriptor$) {
@Override
public Iterator<? extends Integer> iterator() {
return new BaseIterator<Integer>
(Integer.$TypeDescriptor$) {
int index = 0;
int count = 0;
@Override
public java.lang.Object next() {
if (index>=value.length()) {
return finished_.get_();
}
while (true) {
int cp = value.codePointAt(index);
index+=java.lang.Character.charCount(cp);
if (index>=value.length()) {
return finished_.get_();
}
else {
if (fun.$call$(Character.instance(cp)).booleanValue()) {
return Integer.instance(count++);
}
count++;
}
}
}
};
}
};
}
@Override
@TypeInfo("ceylon.language::Iterable<ceylon.language::Integer>")
public Iterable<? extends Integer, ? extends java.lang.Object>
indexesWhere(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> fun) {
return indexesWhere(value, fun);
}
@Ignore
public static Integer
firstIndexWhere(java.lang.String value, Callable<? extends Boolean> fun) {
if (value.isEmpty()) {
return null;
}
int index = 0;
int count = 0;
while (true) {
int cp = value.codePointAt(index);
index+=java.lang.Character.charCount(cp);
if (index>=value.length()) {
return null;
}
else {
if (fun.$call$(Character.instance(cp)).booleanValue()) {
return Integer.instance(count);
}
count++;
}
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer firstIndexWhere(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> fun) {
return firstIndexWhere(value, fun);
}
@Ignore
public static Integer
lastIndexWhere(java.lang.String value, Callable<? extends Boolean> fun) {
int index = value.length();
if (index==0) {
return null;
}
long count = getSize(value);
while (true) {
int cp = value.codePointBefore(index);
index-=java.lang.Character.charCount(cp);
if (index<=0) {
return null;
}
else {
count--;
if (fun.$call$(Character.instance(cp)).booleanValue()) {
return Integer.instance(count);
}
}
}
}
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
@Override
public Integer lastIndexWhere(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> fun) {
return lastIndexWhere(value, fun);
}
@Ignore
public static Iterable<? extends Character, ?>
filter(java.lang.String value, Callable<? extends Boolean> f) {
return instance(value).filter(f);
}
@Ignore
public static <Result> Sequential<? extends Result>
collect(@Ignore TypeDescriptor $reifiedResult,
java.lang.String value, Callable<? extends Result> f) {
return instance(value).collect($reifiedResult, f);
}
@Ignore
public static <Result> Callable<? extends Result>
fold(@Ignore TypeDescriptor $reifiedResult,
java.lang.String value, Result ini) {
return instance(value).fold($reifiedResult, ini);
}
@Ignore
public static <Result>
Callable<? extends Iterable<? extends Result,? extends java.lang.Object>>
scan(@Ignore TypeDescriptor $reifiedResult,
java.lang.String value, Result ini) {
return instance(value).scan($reifiedResult, ini);
}
@Override
@TypeInfo("Result|ceylon.language::Character|ceylon.language::Null")
@TypeParameters(@TypeParameter("Result"))
public <Result> java.lang.Object
reduce(@Ignore TypeDescriptor $reifiedResult,
@Name("accumulating")
@FunctionalParameter("(partial,element)")
@TypeInfo("ceylon.language::Callable<Result,ceylon.language::Tuple<Result|ceylon.language::Character,Result|ceylon.language::Character,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>>")
Callable<? extends Result> f) {
return reduce($reifiedResult,value,f);
}
@Ignore
public static <Result> java.lang.Object
reduce(@Ignore TypeDescriptor $reifiedResult,
java.lang.String value,
Callable<? extends Result> f) {
if (value.isEmpty()) {
return null;
}
int initial = value.codePointAt(0);
java.lang.Object partial = Character.instance(initial);
for (int offset = java.lang.Character.charCount(initial);
offset < value.length();) {
int codePoint = value.codePointAt(offset);
partial = f.$call$(partial, Character.instance(codePoint));
offset += java.lang.Character.charCount(codePoint);
}
return partial;
}
@Override
@TypeInfo(declaredVoid=true,
value="ceylon.language::Anything")
public java.lang.Object each(
@Name("step")
@FunctionalParameter("!(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Anything,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends java.lang.Object> step) {
return each(value,step);
}
@Ignore
public static java.lang.Object each(java.lang.String value,
Callable<? extends java.lang.Object> f) {
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
f.$call$(Character.instance(codePoint));
offset += java.lang.Character.charCount(codePoint);
}
return null;
}
@Override
@TypeInfo("ceylon.language::Boolean")
public boolean any(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return any(value,f);
}
@Ignore
public static boolean any(java.lang.String value,
Callable<? extends Boolean> f) {
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
if (f.$call$(Character.instance(codePoint)).booleanValue()) {
return true;
}
offset += java.lang.Character.charCount(codePoint);
}
return false;
}
@Override
@TypeInfo("ceylon.language::Boolean")
public boolean every(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return every(value,f);
}
@Ignore
public static boolean every(java.lang.String value,
Callable<? extends Boolean> f) {
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
if(!f.$call$(Character.instance(codePoint)).booleanValue()) {
return false;
}
offset += java.lang.Character.charCount(codePoint);
}
return true;
}
@Ignore
public static Iterable<? extends Character, ?>
skip(java.lang.String value, long skip) {
return instance(value).skip(skip);
}
@Ignore
public static Iterable<? extends Character, ?>
take(java.lang.String value, long take) {
return instance(value).take(take);
}
@Ignore
public static Iterable<? extends Character, ?>
takeWhile(java.lang.String value, Callable<? extends Boolean> take) {
return instance(value).takeWhile(take);
}
@Ignore
public static Iterable<? extends Character, ?>
skipWhile(java.lang.String value, Callable<? extends Boolean> skip) {
return instance(value).skipWhile(skip);
}
@Ignore
public static Iterable<? extends Character, ?>
by(java.lang.String value, long step) {
return instance(value).by(step);
}
@Override
@TypeInfo("ceylon.language::Integer")
public long count(
@Name("selecting")
@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<ceylon.language::Character,ceylon.language::Character,ceylon.language::Empty>>")
Callable<? extends Boolean> f) {
return count(value,f);
}
@Ignore
public static long count(java.lang.String value,
Callable<? extends Boolean> f) {
int count = 0;
for (int offset = 0; offset < value.length();) {
int codePoint = value.codePointAt(offset);
if(f.$call$(Character.instance(codePoint)).booleanValue()) {
count++;
}
offset += java.lang.Character.charCount(codePoint);
}
return count;
}
@Ignore
@SuppressWarnings({"unchecked", "rawtypes"})
public static Iterable<? extends Entry<? extends Integer, ? extends Character>, ?>
getIndexed(java.lang.String value) {
if (value.isEmpty()) {
return (Iterable) instance(value);
} else {
return instance(value).getIndexed();
}
}
@Ignore
@SuppressWarnings("rawtypes")
public static <Other,Absent> Iterable
chain(@Ignore TypeDescriptor $reifiedOther,
@Ignore TypeDescriptor $reifiedOtherAbsent,
java.lang.String value,
Iterable<? extends Other, ? extends Absent> other) {
if (value.isEmpty()) {
return other;
}
else {
return instance(value).chain($reifiedOther,
$reifiedOtherAbsent, other);
}
}
@Ignore
@SuppressWarnings("rawtypes")
public static <Other> Iterable
follow(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, Other other) {
return instance(value).follow($reifiedOther, other);
}
@Ignore
public static <Other> Iterable<? extends java.lang.Object, ? extends java.lang.Object>
interpose(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, Other other) {
return instance(value).interpose($reifiedOther, other);
}
@Ignore
@SuppressWarnings("rawtypes")
public static <Other> Iterable
interpose(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, Other other, long step) {
return instance(value).interpose($reifiedOther, other, step);
}
@Ignore
@SuppressWarnings("rawtypes")
public static <Other, OtherAbsent> Iterable
product(@Ignore TypeDescriptor $reified$Other,
@Ignore TypeDescriptor $reified$OtherAbsent,
java.lang.String value,
Iterable<? extends Other, ? extends OtherAbsent> other) {
return instance(value).product($reified$Other, $reified$OtherAbsent, other);
}
@Ignore @SuppressWarnings({ "rawtypes" })
public static <Other>List patch(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, List<? extends Other> list, long from, long length) {
return instance(value).patch($reifiedOther, list, from, length);
}
@Ignore @SuppressWarnings({ "rawtypes" })
public static <Other>List patch(@Ignore TypeDescriptor $reifiedOther,
java.lang.String value, List<? extends Other> list, long from) {
return instance(value).patch($reifiedOther, list, from, 0);
}
@Ignore
public static Iterable<? extends Character,?>
getCycled(java.lang.String value) {
return instance(value).getCycled();
}
@Override
@Ignore
public TypeDescriptor $getType$() {
return $TypeDescriptor$;
}
public static boolean largerThan(java.lang.String value,
String other) {
return value.compareTo(other.value)>0;
}
public static boolean largerThan(java.lang.String value,
java.lang.String other) {
return value.compareTo(other)>0;
}
@Override
public boolean largerThan(@Name("other") String other) {
return value.compareTo(other.value)>0;
}
public static boolean notSmallerThan(java.lang.String value,
String other) {
return value.compareTo(other.value)>=0;
}
public static boolean notSmallerThan(java.lang.String value,
java.lang.String other) {
return value.compareTo(other)>=0;
}
@Override
public boolean notSmallerThan(@Name("other") String other) {
return value.compareTo(other.value)>=0;
}
public static boolean smallerThan(java.lang.String value,
String other) {
return value.compareTo(other.value)<0;
}
public static boolean smallerThan(java.lang.String value,
java.lang.String other) {
return value.compareTo(other)<0;
}
@Override
public boolean smallerThan(@Name("other") String other) {
return value.compareTo(other.value)<0;
}
public static boolean notLargerThan(java.lang.String value,
String other) {
return value.compareTo(other.value)<=0;
}
public static boolean notLargerThan(java.lang.String value,
java.lang.String other) {
return value.compareTo(other)<=0;
}
@Override
public boolean notLargerThan(@Name("other") String other) {
return value.compareTo(other.value)<=0;
}
@Ignore
public static <Result,Args extends Sequential<? extends java.lang.Object>> Callable<? extends Iterable<? extends Result, ?>>
spread(@Ignore TypeDescriptor $reifiedResult,
@Ignore TypeDescriptor $reifiedArgs,
java.lang.String value, Callable<? extends Callable<? extends Result>> method) {
return instance(value).spread($reifiedResult, $reifiedArgs, method);
}
public java.lang.String pad(
@Name("size")
long size,
@Name("character")
@TypeInfo("ceylon.language::Character")
@Defaulted
int character) {
return pad(value, size, character);
}
@Ignore
public java.lang.String pad(long size) {
return pad(value, size, pad$character(size));
}
@Ignore
public static java.lang.String pad(java.lang.String value, long size) {
return pad(value, size, pad$character(size));
}
@Ignore
public static int pad$character(long size) {
return ' ';
}
@Ignore
public static java.lang.String pad(java.lang.String value, long size, int character) {
int length = value.length();
if (size<=length) return value;
long leftPad = (size-length)/2;
long rightPad = leftPad + (size-length)%2;
java.lang.StringBuilder builder = new java.lang.StringBuilder();
for (int i=0;i<leftPad;i++) {
builder.appendCodePoint(character);
}
builder.append(value);
for (int i=0;i<rightPad;i++) {
builder.appendCodePoint(character);
}
return builder.toString();
}
public java.lang.String padLeading(
@Name("size")
long size,
@Name("character")
@TypeInfo("ceylon.language::Character")
@Defaulted
int character) {
return padLeading(value, size, character);
}
@Ignore
public java.lang.String padLeading(long size) {
return padLeading(value, size, padLeading$character(size));
}
@Ignore
public static java.lang.String padLeading(java.lang.String value, long size) {
return padLeading(value, size, padLeading$character(size));
}
@Ignore
public static int padLeading$character(long size) {
return ' ';
}
@Ignore
public static java.lang.String padLeading(java.lang.String value, long size, int character) {
int length = value.length();
if (size<=length) return value;
long leftPad = size-length;
java.lang.StringBuilder builder = new java.lang.StringBuilder();
for (int i=0;i<leftPad;i++) {
builder.appendCodePoint(character);
}
builder.append(value);
return builder.toString();
}
public java.lang.String padTrailing(
@Name("size")
long size,
@Name("character")
@TypeInfo("ceylon.language::Character")
@Defaulted
int character) {
return padTrailing(value, size, character);
}
@Ignore
public java.lang.String padTrailing(long size) {
return padTrailing(value, size, padTrailing$character(size));
}
@Ignore
public static java.lang.String padTrailing(java.lang.String value, long size) {
return padTrailing(value, size, padTrailing$character(size));
}
@Ignore
public static int padTrailing$character(long size) {
return ' ';
}
@Ignore
public static java.lang.String padTrailing(java.lang.String value, long size, int character) {
int length = value.length();
if (size<=length) return value;
long rightPad = size-length;
java.lang.StringBuilder builder = new java.lang.StringBuilder(value);
for (int i=0;i<rightPad;i++) {
builder.appendCodePoint(character);
}
return builder.toString();
}
@Ignore
public static Iterable getPaired(java.lang.String value) {
return instance(value).getPaired();
}
@Ignore
public static Iterable<? extends Sequence<? extends Character>,? extends java.lang.Object>
partition(java.lang.String value, long length) {
return instance(value).partition(length);
}
@Ignore
public long copyTo$sourcePosition(Array<Character> destination){
return 0;
}
@Ignore
public long copyTo$destinationPosition(Array<Character> destination,
long sourcePosition){
return 0;
}
@Ignore
public long copyTo$length(Array<Character> destination,
long sourcePosition, long destinationPosition){
return Math.min(value.length()-sourcePosition,
destination.getSize()-destinationPosition);
}
@Ignore
public static void copyTo(java.lang.String value, Array<Character> destination){
copyTo(value, destination, 0, 0);
}
@Ignore
public static void copyTo(java.lang.String value, Array<Character> destination, long sourcePosition){
copyTo(value, destination, sourcePosition, 0);
}
@Ignore
public static void copyTo(java.lang.String value, Array<Character> destination,
long sourcePosition, long destinationPosition){
copyTo(value, destination,
sourcePosition, destinationPosition,
Math.min(value.length()-sourcePosition,
destination.getSize()-destinationPosition));
}
@Ignore
public void copyTo(Array<Character> destination){
copyTo(value, destination, 0, 0);
}
@Ignore
public void copyTo(Array<Character> destination, long sourcePosition){
copyTo(value, destination, sourcePosition, 0);
}
@Ignore
public void copyTo(Array<Character> destination,
long sourcePosition, long destinationPosition){
copyTo(value, destination,
sourcePosition, destinationPosition,
copyTo$length(destination, sourcePosition, destinationPosition));
}
@Ignore
public static void copyTo(java.lang.String value,
Array<Character> destination,
long sourcePosition,
long destinationPosition,
long length){
int count = 0;
int dest = Util.toInt(destinationPosition);
for (int index = value.offsetByCodePoints(0,Util.toInt(sourcePosition));
count<length;) {
int codePoint = value.codePointAt(index);
((int[])destination.toArray())[count+dest] = codePoint;
index += java.lang.Character.charCount(codePoint);
count++;
}
}
public void copyTo(@Name("destination") Array<Character> destination,
@Name("sourcePosition") @Defaulted long sourcePosition,
@Name("destinationPosition") @Defaulted long destinationPosition,
@Name("length") @Defaulted long length){
copyTo(value, destination, sourcePosition, destinationPosition, length);
}
@Ignore
public static Iterable<? extends Sequence<? extends Character>, ? extends java.lang.Object>
getPermutations(java.lang.String value) {
return instance(value).getPermutations();
}
@Ignore
public static <Group> Iterable<? extends Entry<? extends Group, ? extends Sequence<? extends Character>>, ? extends java.lang.Object>
group(java.lang.String value, TypeDescriptor $reifiedGroup, Callable<? extends Group> fun) {
return instance(value).group($reifiedGroup, fun);
}
@Ignore
public static <Group,Result> Iterable<? extends Entry<? extends Group, ? extends Result>, ? extends java.lang.Object>
summarize(java.lang.String value, TypeDescriptor $reifiedGroup, TypeDescriptor $reifiedResult,
Callable<? extends Group> fun, Callable<? extends Result> fold) {
return instance(value).summarize($reifiedGroup, $reifiedResult, fun, fold);
}
@Ignore
public static Iterable<? extends Character, ? extends java.lang.Object>
getDistinct(java.lang.String value) {
return instance(value).getDistinct();
}
//WARNING: pure boilerplate from here on!
@Override @Ignore
public Collection$impl<? extends Character> $ceylon$language$Collection$impl() {
return new Collection$impl<Character>
(Character.$TypeDescriptor$, this);
}
@Override @Ignore
public Iterable<? extends Sequence<? extends Character>, ? extends java.lang.Object> getPermutations() {
return $ceylon$language$Collection$impl().getPermutations();
}
@Override @Ignore
public Iterable$impl<? extends Character, ? extends java.lang.Object> $ceylon$language$Iterable$impl() {
return new Iterable$impl<Character, java.lang.Object>
(Character.$TypeDescriptor$, Null.$TypeDescriptor$, this);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> by(long step) {
return $ceylon$language$Iterable$impl().by(step);
}
@Override @Ignore
public <Other, OtherAbsent> Iterable chain(TypeDescriptor arg0, TypeDescriptor arg1,
Iterable<? extends Other, ? extends OtherAbsent> arg2) {
return $ceylon$language$Iterable$impl().chain(arg0, arg1, arg2);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> filter(Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().filter(arg0);
}
@Override @Ignore
public <Result, OtherAbsent> Iterable flatMap(TypeDescriptor arg0, TypeDescriptor arg1,
Callable<? extends Iterable<? extends Result, ? extends OtherAbsent>> arg2) {
return $ceylon$language$Iterable$impl().flatMap(arg0, arg1, arg2);
}
@Override @Ignore
public <Result> Callable<? extends Result> fold(TypeDescriptor arg0, Result arg1) {
return $ceylon$language$Iterable$impl().fold(arg0, arg1);
}
@Override @Ignore
public <Other> Iterable follow(TypeDescriptor arg0, Other arg1) {
return $ceylon$language$Iterable$impl().follow(arg0, arg1);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> getCycled() {
return $ceylon$language$Iterable$impl().getCycled();
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> getDistinct() {
return $ceylon$language$Iterable$impl().getDistinct();
}
/*@Ignore
public static Set<? extends Character> elements(java.lang.String value) {
return instance(value).elements();
}
@Override @Ignore
public Set<? extends Character> elements() {
return $ceylon$language$Iterable$impl().elements();
}*/
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> getExceptLast() {
return $ceylon$language$Iterable$impl().getExceptLast();
}
@Override @Ignore
public Iterable<? extends Entry<? extends Integer, ? extends Character>, ? extends java.lang.Object> getIndexed() {
return $ceylon$language$Iterable$impl().getIndexed();
}
@Override @Ignore
public Iterable<? extends Sequence<? extends Character>, ? extends java.lang.Object> getPaired() {
return $ceylon$language$Iterable$impl().getPaired();
}
@Override @Ignore
public <Group> Map<? extends Group, ? extends Sequence<? extends Character>> group(TypeDescriptor arg0,
Callable<? extends Group> arg1) {
return $ceylon$language$Iterable$impl().group(arg0, arg1);
}
@Override @Ignore
public <Group,Result> Map<? extends Group, ? extends Result> summarize(TypeDescriptor arg0,
TypeDescriptor arg1, Callable<? extends Group> arg2, Callable<? extends Result> arg3) {
return $ceylon$language$Iterable$impl().summarize(arg0, arg1, arg2, arg3);
}
@Override @Ignore
public java.lang.Object indexes() {
return $ceylon$language$Iterable$impl().indexes();
}
@Override @Ignore
public <Other> Iterable interpose(TypeDescriptor arg0, Other arg1) {
return $ceylon$language$Iterable$impl().interpose(arg0, arg1);
}
@Override @Ignore
public <Other> Iterable interpose(TypeDescriptor arg0, Other arg1, long arg2) {
return $ceylon$language$Iterable$impl().interpose(arg0, arg1, arg2);
}
@Override @Ignore
public <Other> long interpose$step(TypeDescriptor arg0, Other arg1) {
return $ceylon$language$Iterable$impl().interpose$step(arg0, arg1);
}
@Override @Ignore
public Iterable<? extends Entry<? extends Integer, ? extends Character>, ? extends java.lang.Object> locations(
Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().locations(arg0);
}
@Override @Ignore
public <Result> Iterable<? extends Result, ? extends java.lang.Object> map(TypeDescriptor arg0,
Callable<? extends Result> arg1) {
return $ceylon$language$Iterable$impl().map(arg0, arg1);
}
@Override @Ignore
public java.lang.Object max(Callable<? extends Comparison> arg0) {
return $ceylon$language$Iterable$impl().max(arg0);
}
@Override @Ignore
public <Type> Iterable narrow(TypeDescriptor arg0) {
return $ceylon$language$Iterable$impl().narrow(arg0);
}
@Override @Ignore
public Iterable<? extends Sequence<? extends Character>, ? extends java.lang.Object> partition(long arg0) {
return $ceylon$language$Iterable$impl().partition(arg0);
}
@Override @Ignore
public <Other, OtherAbsent> Iterable product(TypeDescriptor arg0, TypeDescriptor arg1,
Iterable<? extends Other, ? extends OtherAbsent> arg2) {
return $ceylon$language$Iterable$impl().product(arg0, arg1, arg2);
}
@Override @Ignore
public <Result> Callable<? extends Iterable<? extends Result, ? extends java.lang.Object>> scan(TypeDescriptor arg0,
Result arg1) {
return $ceylon$language$Iterable$impl().scan(arg0, arg1);
}
@Override @Ignore
public Sequential<? extends Character> select(Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().select(arg0);
}
@Override @Ignore
public Sequential<? extends Character> sequence() {
return $ceylon$language$Iterable$impl().sequence();
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> skip(long arg0) {
return $ceylon$language$Iterable$impl().skip(arg0);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> skipWhile(Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().skipWhile(arg0);
}
@Override @Ignore
public Sequential<? extends Character> sort(Callable<? extends Comparison> arg0) {
return $ceylon$language$Iterable$impl().sort(arg0);
}
@Override @Ignore
public <Result, Args extends Sequential<? extends java.lang.Object>> Callable<? extends Iterable<? extends Result, ? extends java.lang.Object>> spread(
TypeDescriptor arg0, TypeDescriptor arg1, Callable<? extends Callable<? extends Result>> arg2) {
return $ceylon$language$Iterable$impl().spread(arg0, arg1, arg2);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> take(long arg0) {
return $ceylon$language$Iterable$impl().take(arg0);
}
@Override @Ignore
public Iterable<? extends Character, ? extends java.lang.Object> takeWhile(Callable<? extends Boolean> arg0) {
return $ceylon$language$Iterable$impl().takeWhile(arg0);
}
@Override @Ignore
public Category$impl<? super java.lang.Object> $ceylon$language$Category$impl() {
return new Category$impl<java.lang.Object>(Object.$TypeDescriptor$, this);
}
@Override @Ignore
public boolean containsAny(Iterable<? extends java.lang.Object, ? extends java.lang.Object> arg0) {
return $ceylon$language$Category$impl().containsAny(arg0);
}
@Override @Ignore
public boolean containsEvery(Iterable<? extends java.lang.Object, ? extends java.lang.Object> arg0) {
return $ceylon$language$Category$impl().containsEvery(arg0);
}
@Override @Ignore
public Correspondence$impl<? super Integer, ? extends Character> $ceylon$language$Correspondence$impl() {
return new Correspondence$impl<Integer,Character>(Integer.$TypeDescriptor$, Character.$TypeDescriptor$, this);
}
@Override @Ignore
public boolean definesAny(Iterable<? extends Integer, ? extends java.lang.Object> arg0) {
return $ceylon$language$Correspondence$impl().definesAny(arg0);
}
@Override @Ignore
public boolean definesEvery(Iterable<? extends Integer, ? extends java.lang.Object> arg0) {
return $ceylon$language$Correspondence$impl().definesEvery(arg0);
}
@Override @Ignore
public <Absent> Iterable<? extends Character, ? extends Absent> getAll(TypeDescriptor arg0,
Iterable<? extends Integer, ? extends Absent> arg1) {
return $ceylon$language$Correspondence$impl().getAll(arg0, arg1);
}
@Override @Ignore
public List$impl<? extends Character> $ceylon$language$List$impl() {
return new List$impl<Character>(Character.$TypeDescriptor$, this);
}
@Override @Ignore
public <Result> Sequential<? extends Result> collect(TypeDescriptor arg0, Callable<? extends Result> arg1) {
return $ceylon$language$List$impl().collect(arg0, arg1);
}
@Override @Ignore
public Character get(Integer index) {
//NOTE THIS IMPORTANT PERFORMANCE OPTIMIZATION
return getFromFirst(value, index.value);
}
@Override @Ignore
public <Other> List patch(TypeDescriptor arg0, List<? extends Other> arg1) {
return $ceylon$language$List$impl().patch(arg0, arg1);
}
@Override @Ignore
public <Other> List patch(TypeDescriptor arg0, List<? extends Other> arg1, long arg2) {
return $ceylon$language$List$impl().patch(arg0, arg1, arg2);
}
@Override @Ignore
public <Other> List patch(TypeDescriptor arg0, List<? extends Other> arg1, long arg2, long arg3) {
return $ceylon$language$List$impl().patch(arg0, arg1, arg2, arg3);
}
@Override @Ignore
public <Other> long patch$from(TypeDescriptor arg0, List<? extends Other> arg1) {
return $ceylon$language$List$impl().patch$from(arg0, arg1);
}
@Override @Ignore
public <Other> long patch$length(TypeDescriptor arg0, List<? extends Other> arg1, long arg2) {
return $ceylon$language$List$impl().patch$length(arg0, arg1, arg2);
}
@Override @Ignore
public List<? extends Character> sublist(long arg0, long arg1) {
return $ceylon$language$List$impl().sublist(arg0, arg1);
}
@Override @Ignore
public SearchableList$impl<Character> $ceylon$language$SearchableList$impl() {
return new SearchableList$impl<Character>(Character.$TypeDescriptor$, this);
}
// @Override
// public boolean startsWith(List<? extends java.lang.Object> sublist) {
// return $ceylon$language$SearchableList$impl().startsWith(sublist);
// }
//
// @Override
// public boolean endsWith(List<? extends java.lang.Object> sublist) {
// return $ceylon$language$SearchableList$impl().endsWith(sublist);
// }
@Override @Ignore
public long countInclusions(List<? extends Character> arg0) {
return countInclusions(value, arg0);
}
@Override @Ignore
public long countInclusions$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public long countOccurrences(Character element) {
return countOccurrences(value, element.codePoint);
}
@Override @Ignore
public long countOccurrences(Character element, long from) {
return countOccurrences(value, element.codePoint, from);
}
@Override @Ignore
public long countOccurrences$from(Character arg0) {
return 0;
}
@Override @Ignore
public long countOccurrences$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
@Override @Ignore
public Integer firstInclusion(List<? extends Character> arg0) {
return firstInclusion(value, arg0);
}
@Override @Ignore
public long firstInclusion$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public Integer firstOccurrence(Character element) {
return firstOccurrence(value, element.codePoint);
}
@Override @Ignore
public Integer firstOccurrence(Character element, long from) {
return firstOccurrence(value, element.codePoint, from);
}
@Override @Ignore
public long firstOccurrence$from(Character arg0) {
return 0;
}
@Override @Ignore
public long firstOccurrence$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
@Override @Ignore
public boolean includes(List<? extends Character> arg0) {
return includes(value, arg0);
}
@Override @Ignore
public long includes$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public Iterable<? extends Integer, ? extends java.lang.Object> inclusions(List<? extends Character> arg0) {
return inclusions(value, arg0);
}
@Override @Ignore
public long inclusions$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public Integer lastInclusion(List<? extends Character> arg0) {
return lastInclusion(value, arg0);
}
@Override @Ignore
public long lastInclusion$from(List<? extends Character> arg0) {
return 0;
}
@Override @Ignore
public Integer lastOccurrence(Character element) {
return lastOccurrence(value, element.codePoint);
}
@Override @Ignore
public Integer lastOccurrence(Character element, long from) {
return lastOccurrence(value, element.codePoint, from);
}
@Override @Ignore
public long lastOccurrence$from(Character arg0) {
return 0;
}
@Override @Ignore
public long lastOccurrence$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
@Override @Ignore
public Iterable<? extends Integer, ? extends java.lang.Object> occurrences(Character element) {
return occurrences(value, element.codePoint);
}
@Override @Ignore
public Iterable<? extends Integer, ? extends java.lang.Object> occurrences(Character element, long from) {
return occurrences(value, element.codePoint, from);
}
@Override @Ignore
public long occurrences$from(Character arg0) {
return 0;
}
@Override @Ignore
public long occurrences$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
@Override @Ignore
public boolean occurs(Character element) {
return occurs(value, element.codePoint);
}
@Override @Ignore
public boolean occurs(Character element, long arg1) {
return occurs(value, element.codePoint, arg1);
}
@Override @Ignore
public long occurs$from(Character arg0) {
return 0;
}
@Override @Ignore
public long occurs$length(Character arg0, long arg1) {
return java.lang.Integer.MAX_VALUE;
}
}
| make String.locateLast() work backwards | runtime/ceylon/language/String.java | make String.locateLast() work backwards |
|
Java | apache-2.0 | 2cc0a1d7c3e3114b04be5aa58d7a9d286c6a573c | 0 | birdtsai/pentaho-kettle,HiromuHota/pentaho-kettle,EcoleKeine/pentaho-kettle,HiromuHota/pentaho-kettle,Advent51/pentaho-kettle,ma459006574/pentaho-kettle,Advent51/pentaho-kettle,matthewtckr/pentaho-kettle,nanata1115/pentaho-kettle,aminmkhan/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,birdtsai/pentaho-kettle,flbrino/pentaho-kettle,nantunes/pentaho-kettle,pedrofvteixeira/pentaho-kettle,yshakhau/pentaho-kettle,matrix-stone/pentaho-kettle,ddiroma/pentaho-kettle,matthewtckr/pentaho-kettle,pedrofvteixeira/pentaho-kettle,pymjer/pentaho-kettle,EcoleKeine/pentaho-kettle,tmcsantos/pentaho-kettle,alina-ipatina/pentaho-kettle,matrix-stone/pentaho-kettle,marcoslarsen/pentaho-kettle,HiromuHota/pentaho-kettle,dkincade/pentaho-kettle,mbatchelor/pentaho-kettle,mdamour1976/pentaho-kettle,mbatchelor/pentaho-kettle,andrei-viaryshka/pentaho-kettle,flbrino/pentaho-kettle,eayoungs/pentaho-kettle,mdamour1976/pentaho-kettle,rmansoor/pentaho-kettle,zlcnju/kettle,roboguy/pentaho-kettle,jbrant/pentaho-kettle,aminmkhan/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,denisprotopopov/pentaho-kettle,zlcnju/kettle,nantunes/pentaho-kettle,tkafalas/pentaho-kettle,airy-ict/pentaho-kettle,nicoben/pentaho-kettle,airy-ict/pentaho-kettle,mkambol/pentaho-kettle,bmorrise/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,drndos/pentaho-kettle,mkambol/pentaho-kettle,wseyler/pentaho-kettle,airy-ict/pentaho-kettle,tmcsantos/pentaho-kettle,rmansoor/pentaho-kettle,e-cuellar/pentaho-kettle,skofra0/pentaho-kettle,mattyb149/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,stevewillcock/pentaho-kettle,nicoben/pentaho-kettle,emartin-pentaho/pentaho-kettle,wseyler/pentaho-kettle,mbatchelor/pentaho-kettle,nicoben/pentaho-kettle,rfellows/pentaho-kettle,SergeyTravin/pentaho-kettle,stepanovdg/pentaho-kettle,pminutillo/pentaho-kettle,airy-ict/pentaho-kettle,e-cuellar/pentaho-kettle,pedrofvteixeira/pentaho-kettle,GauravAshara/pentaho-kettle,drndos/pentaho-kettle,matthewtckr/pentaho-kettle,ViswesvarSekar/pentaho-kettle,skofra0/pentaho-kettle,stepanovdg/pentaho-kettle,dkincade/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,alina-ipatina/pentaho-kettle,mkambol/pentaho-kettle,jbrant/pentaho-kettle,MikhailHubanau/pentaho-kettle,pavel-sakun/pentaho-kettle,nantunes/pentaho-kettle,emartin-pentaho/pentaho-kettle,akhayrutdinov/pentaho-kettle,SergeyTravin/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,matthewtckr/pentaho-kettle,denisprotopopov/pentaho-kettle,Advent51/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,CapeSepias/pentaho-kettle,marcoslarsen/pentaho-kettle,hudak/pentaho-kettle,roboguy/pentaho-kettle,YuryBY/pentaho-kettle,alina-ipatina/pentaho-kettle,YuryBY/pentaho-kettle,pminutillo/pentaho-kettle,skofra0/pentaho-kettle,graimundo/pentaho-kettle,e-cuellar/pentaho-kettle,ViswesvarSekar/pentaho-kettle,EcoleKeine/pentaho-kettle,bmorrise/pentaho-kettle,andrei-viaryshka/pentaho-kettle,akhayrutdinov/pentaho-kettle,drndos/pentaho-kettle,nanata1115/pentaho-kettle,matrix-stone/pentaho-kettle,kurtwalker/pentaho-kettle,stevewillcock/pentaho-kettle,ccaspanello/pentaho-kettle,mdamour1976/pentaho-kettle,pminutillo/pentaho-kettle,alina-ipatina/pentaho-kettle,DFieldFL/pentaho-kettle,yshakhau/pentaho-kettle,gretchiemoran/pentaho-kettle,mattyb149/pentaho-kettle,cjsonger/pentaho-kettle,lgrill-pentaho/pentaho-kettle,ddiroma/pentaho-kettle,mkambol/pentaho-kettle,eayoungs/pentaho-kettle,stevewillcock/pentaho-kettle,lgrill-pentaho/pentaho-kettle,lgrill-pentaho/pentaho-kettle,stepanovdg/pentaho-kettle,zlcnju/kettle,DFieldFL/pentaho-kettle,andrei-viaryshka/pentaho-kettle,birdtsai/pentaho-kettle,hudak/pentaho-kettle,ivanpogodin/pentaho-kettle,hudak/pentaho-kettle,SergeyTravin/pentaho-kettle,jbrant/pentaho-kettle,mdamour1976/pentaho-kettle,sajeetharan/pentaho-kettle,codek/pentaho-kettle,yshakhau/pentaho-kettle,kurtwalker/pentaho-kettle,YuryBY/pentaho-kettle,ma459006574/pentaho-kettle,ViswesvarSekar/pentaho-kettle,YuryBY/pentaho-kettle,DFieldFL/pentaho-kettle,flbrino/pentaho-kettle,codek/pentaho-kettle,denisprotopopov/pentaho-kettle,roboguy/pentaho-kettle,cjsonger/pentaho-kettle,SergeyTravin/pentaho-kettle,bmorrise/pentaho-kettle,hudak/pentaho-kettle,rfellows/pentaho-kettle,ivanpogodin/pentaho-kettle,aminmkhan/pentaho-kettle,sajeetharan/pentaho-kettle,CapeSepias/pentaho-kettle,ddiroma/pentaho-kettle,Advent51/pentaho-kettle,EcoleKeine/pentaho-kettle,kurtwalker/pentaho-kettle,ddiroma/pentaho-kettle,CapeSepias/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,nanata1115/pentaho-kettle,mbatchelor/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,nicoben/pentaho-kettle,drndos/pentaho-kettle,matrix-stone/pentaho-kettle,MikhailHubanau/pentaho-kettle,gretchiemoran/pentaho-kettle,graimundo/pentaho-kettle,GauravAshara/pentaho-kettle,aminmkhan/pentaho-kettle,brosander/pentaho-kettle,akhayrutdinov/pentaho-kettle,graimundo/pentaho-kettle,pedrofvteixeira/pentaho-kettle,emartin-pentaho/pentaho-kettle,tmcsantos/pentaho-kettle,emartin-pentaho/pentaho-kettle,roboguy/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,skofra0/pentaho-kettle,ma459006574/pentaho-kettle,pavel-sakun/pentaho-kettle,HiromuHota/pentaho-kettle,bmorrise/pentaho-kettle,denisprotopopov/pentaho-kettle,ccaspanello/pentaho-kettle,ivanpogodin/pentaho-kettle,jbrant/pentaho-kettle,pentaho/pentaho-kettle,ccaspanello/pentaho-kettle,pavel-sakun/pentaho-kettle,graimundo/pentaho-kettle,codek/pentaho-kettle,zlcnju/kettle,stepanovdg/pentaho-kettle,sajeetharan/pentaho-kettle,CapeSepias/pentaho-kettle,kurtwalker/pentaho-kettle,pentaho/pentaho-kettle,sajeetharan/pentaho-kettle,dkincade/pentaho-kettle,cjsonger/pentaho-kettle,pymjer/pentaho-kettle,mattyb149/pentaho-kettle,birdtsai/pentaho-kettle,mattyb149/pentaho-kettle,flbrino/pentaho-kettle,tmcsantos/pentaho-kettle,marcoslarsen/pentaho-kettle,rmansoor/pentaho-kettle,dkincade/pentaho-kettle,pymjer/pentaho-kettle,nantunes/pentaho-kettle,nanata1115/pentaho-kettle,eayoungs/pentaho-kettle,lgrill-pentaho/pentaho-kettle,pentaho/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,rfellows/pentaho-kettle,GauravAshara/pentaho-kettle,akhayrutdinov/pentaho-kettle,wseyler/pentaho-kettle,codek/pentaho-kettle,GauravAshara/pentaho-kettle,tkafalas/pentaho-kettle,e-cuellar/pentaho-kettle,brosander/pentaho-kettle,pminutillo/pentaho-kettle,rmansoor/pentaho-kettle,MikhailHubanau/pentaho-kettle,DFieldFL/pentaho-kettle,ivanpogodin/pentaho-kettle,pavel-sakun/pentaho-kettle,ViswesvarSekar/pentaho-kettle,eayoungs/pentaho-kettle,tkafalas/pentaho-kettle,brosander/pentaho-kettle,stevewillcock/pentaho-kettle,ccaspanello/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,wseyler/pentaho-kettle,brosander/pentaho-kettle,gretchiemoran/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,pentaho/pentaho-kettle,marcoslarsen/pentaho-kettle,tkafalas/pentaho-kettle,cjsonger/pentaho-kettle,pymjer/pentaho-kettle,ma459006574/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,yshakhau/pentaho-kettle,gretchiemoran/pentaho-kettle | /**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.core.dialog;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
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.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import be.ibridge.kettle.core.ColumnInfo;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.WindowProperty;
import be.ibridge.kettle.core.database.BaseDatabaseMeta;
import be.ibridge.kettle.core.database.ConnectionPoolUtil;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseConnectionPoolParameter;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.database.GenericDatabaseMeta;
import be.ibridge.kettle.core.database.PartitionDatabaseMeta;
import be.ibridge.kettle.core.database.SAPR3DatabaseMeta;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.widget.TableView;
import be.ibridge.kettle.core.widget.TextVar;
import be.ibridge.kettle.spoon.Spoon;
import be.ibridge.kettle.trans.step.BaseStepDialog;
/**
*
* Dialog that allows you to edit the settings of a database connection.
*
* @see <code>DatabaseInfo</code>
* @author Matt
* @since 18-05-2003
*
*/
public class DatabaseDialog extends Dialog
{
private DatabaseMeta connection;
private CTabFolder wTabFolder;
private CTabItem wDbTab, wPoolTab, wOracleTab, wIfxTab, wMySQLTab, wSAPTab, wGenericTab, wOptionsTab, wSQLTab, wClusterTab;
private Composite wDbComp, wPoolComp, wOracleComp, wIfxComp, wMySQLComp, wSAPComp, wGenericComp, wOptionsComp, wSQLComp, wClusterComp;
private Shell shell;
// DB
private Label wlConn, wlConnType, wlConnAcc, wlHostName, wlDBName, wlPort, wlUsername, wlPassword, wlData, wlIndex;
private Text wConn;
private TextVar wHostName, wDBName, wPort, wUsername, wPassword, wData, wIndex;
private List wConnType, wConnAcc;
// Informix
private Label wlServername;
private Text wServername;
// MySQL
private Label wlStreamResult;
private Button wStreamResult;
// Pooling
private Label wlUsePool, wlInitPool, wlMaxPool;
private Button wUsePool;
private TextVar wInitPool, wMaxPool;
private TableView wPoolParameters;
private Label wlPoolParameters;
// SAP
private Label wlSAPLanguage, wlSAPSystemNumber, wlSAPClient;
private Text wSAPLanguage, wSAPSystemNumber, wSAPClient;
// Generic
private Label wlURL, wlDriverClass;
private Text wURL, wDriverClass;
// Options
private TableView wOptions;
// SQL
private Label wlSQL;
private Text wSQL;
// Cluster
private Label wlUseCluster;
private Button wUseCluster;
private TableView wCluster;
private Button wOK, wTest, wExp, wList, wCancel, wOptionsHelp;
private String connectionName;
private ModifyListener lsMod;
private boolean changed;
private Props props;
private String previousDatabaseType;
private ArrayList databases;
private Map extraOptions;
private int middle;
private int margin;
private long database_id;
public DatabaseDialog(Shell par, int style, LogWriter lg, DatabaseMeta conn, Props pr)
{
super(par, style);
connection = conn;
connectionName = conn.getName();
props = pr;
this.databases = null;
this.extraOptions = conn.getExtraOptions();
this.database_id = conn.getID();
String path = ""; //$NON-NLS-1$
try
{
File file = new File("simple-jndi"); //$NON-NLS-1$
path = file.getCanonicalPath();
}
catch (Exception e)
{
e.printStackTrace();
}
System.setProperty("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.osjava.sj.root", path); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.osjava.sj.delimiter", "/"); //$NON-NLS-1$ //$NON-NLS-2$
}
public String open()
{
Shell parent = getParent();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
connection.setChanged();
}
};
changed = connection.hasChanged();
middle = props.getMiddlePct();
margin = Const.MARGIN;
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setText(Messages.getString("DatabaseDialog.Shell.title")); //$NON-NLS-1$
shell.setLayout(formLayout);
// First, add the buttons...
// Buttons
wOK = new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK")); //$NON-NLS-1$
wTest = new Button(shell, SWT.PUSH);
wTest.setText(Messages.getString("DatabaseDialog.button.Test")); //$NON-NLS-1$
wExp = new Button(shell, SWT.PUSH);
wExp.setText(Messages.getString("DatabaseDialog.button.Explore")); //$NON-NLS-1$
wList = new Button(shell, SWT.PUSH);
wList.setText(Messages.getString("DatabaseDialog.button.FeatureList")); //$NON-NLS-1$
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel")); //$NON-NLS-1$
Button[] buttons = new Button[] { wOK, wTest, wExp, wList, wCancel };
BaseStepDialog.positionBottomButtons(shell, buttons, margin, null);
// The rest stays above the buttons...
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
addGeneralTab();
addPoolTab();
addMySQLTab();
addOracleTab();
addInformixTab();
addSAPTab();
addGenericTab();
addOptionsTab();
addSQLTab();
addClusterTab();
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(0, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom = new FormAttachment(wOK, -margin);
wTabFolder.setLayoutData(fdTabFolder);
// Add listeners
wOK.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
ok();
}
});
wCancel.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
cancel();
}
});
wTest.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
test();
}
});
wExp.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
explore();
}
});
wList.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
showFeatureList();
}
});
SelectionAdapter selAdapter = new SelectionAdapter()
{
public void widgetDefaultSelected(SelectionEvent e)
{
ok();
}
};
wHostName.addSelectionListener(selAdapter);
wDBName.addSelectionListener(selAdapter);
wPort.addSelectionListener(selAdapter);
wUsername.addSelectionListener(selAdapter);
wPassword.addSelectionListener(selAdapter);
wConn.addSelectionListener(selAdapter);
wData.addSelectionListener(selAdapter);
wIndex.addSelectionListener(selAdapter);
// OK, if the password contains a variable, we don't want to have the password hidden...
wPassword.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
checkPasswordVisible(wPassword.getTextWidget());
}
});
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener(new ShellAdapter()
{
public void shellClosed(ShellEvent e)
{
cancel();
}
});
wTabFolder.setSelection(0);
getData();
enableFields();
SelectionAdapter lsTypeAcc = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
enableFields();
setPortNumber();
}
};
wConnType.addSelectionListener(lsTypeAcc);
wConnAcc.addSelectionListener(lsTypeAcc);
BaseStepDialog.setSize(shell);
connection.setChanged(changed);
shell.open();
Display display = parent.getDisplay();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return connectionName;
}
public static final void checkPasswordVisible(Text wPassword)
{
String password = wPassword.getText();
java.util.List list = new ArrayList();
StringUtil.getUsedVariables(password, list, true);
// ONLY show the variable in clear text if there is ONE variable used
// Also, it has to be the only string in the field.
//
if (list.size() != 1)
{
wPassword.setEchoChar('*');
}
else
{
if ((password.startsWith(StringUtil.UNIX_OPEN) && password.endsWith(StringUtil.UNIX_CLOSE))
|| (password.startsWith(StringUtil.WINDOWS_OPEN) && password.endsWith(StringUtil.WINDOWS_CLOSE)))
{
wPassword.setEchoChar('\0'); // Show it all...
}
else
{
wPassword.setEchoChar('*');
}
}
}
private void addGeneralTab()
{
// ////////////////////////
// START OF DB TAB ///
// ////////////////////////
wDbTab = new CTabItem(wTabFolder, SWT.NONE);
wDbTab.setText(Messages.getString("DatabaseDialog.DbTab.title")); //$NON-NLS-1$
wDbComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wDbComp);
FormLayout GenLayout = new FormLayout();
GenLayout.marginWidth = Const.FORM_MARGIN;
GenLayout.marginHeight = Const.FORM_MARGIN;
wDbComp.setLayout(GenLayout);
// What's the connection name?
wlConn = new Label(wDbComp, SWT.RIGHT);
props.setLook(wlConn);
wlConn.setText(Messages.getString("DatabaseDialog.label.ConnectionName")); //$NON-NLS-1$
FormData fdlConn = new FormData();
fdlConn.top = new FormAttachment(0, 0);
fdlConn.left = new FormAttachment(0, 0); // First one in the left top corner
fdlConn.right = new FormAttachment(middle, -margin);
wlConn.setLayoutData(fdlConn);
wConn = new Text(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wConn);
wConn.addModifyListener(lsMod);
FormData fdConn = new FormData();
fdConn.top = new FormAttachment(0, 0);
fdConn.left = new FormAttachment(middle, 0); // To the right of the label
fdConn.right = new FormAttachment(95, 0);
wConn.setLayoutData(fdConn);
// What types are there?
wlConnType = new Label(wDbComp, SWT.RIGHT);
wlConnType.setText(Messages.getString("DatabaseDialog.label.ConnectionType")); //$NON-NLS-1$
props.setLook(wlConnType);
FormData fdlConnType = new FormData();
fdlConnType.top = new FormAttachment(wConn, margin); // below the line above
fdlConnType.left = new FormAttachment(0, 0);
fdlConnType.right = new FormAttachment(middle, -margin);
wlConnType.setLayoutData(fdlConnType);
wConnType = new List(wDbComp, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE | SWT.V_SCROLL);
props.setLook(wConnType);
String[] dbtypes = DatabaseMeta.getDBTypeDescLongList();
for (int i = 0; i < dbtypes.length; i++)
{
wConnType.add(dbtypes[i]);
}
props.setLook(wConnType);
FormData fdConnType = new FormData();
fdConnType.top = new FormAttachment(wConn, margin);
fdConnType.left = new FormAttachment(middle, 0); // right of the label
fdConnType.right = new FormAttachment(95, 0);
fdConnType.bottom = new FormAttachment(wConn, 150);
wConnType.setLayoutData(fdConnType);
// What access types are there?
wlConnAcc = new Label(wDbComp, SWT.RIGHT);
wlConnAcc.setText(Messages.getString("DatabaseDialog.label.AccessMethod")); //$NON-NLS-1$
props.setLook(wlConnAcc);
FormData fdlConnAcc = new FormData();
fdlConnAcc.top = new FormAttachment(wConnType, margin); // below the line above
fdlConnAcc.left = new FormAttachment(0, 0);
fdlConnAcc.right = new FormAttachment(middle, -margin);
wlConnAcc.setLayoutData(fdlConnAcc);
wConnAcc = new List(wDbComp, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE | SWT.V_SCROLL);
props.setLook(wConnAcc);
props.setLook(wConnAcc);
FormData fdConnAcc = new FormData();
fdConnAcc.top = new FormAttachment(wConnType, margin);
fdConnAcc.left = new FormAttachment(middle, 0); // right of the label
fdConnAcc.right = new FormAttachment(95, 0);
// fdConnAcc.bottom = new FormAttachment(wConnType, 50);
wConnAcc.setLayoutData(fdConnAcc);
// Hostname
wlHostName = new Label(wDbComp, SWT.RIGHT);
wlHostName.setText(Messages.getString("DatabaseDialog.label.ServerHostname")); //$NON-NLS-1$
props.setLook(wlHostName);
FormData fdlHostName = new FormData();
fdlHostName.top = new FormAttachment(wConnAcc, margin);
fdlHostName.left = new FormAttachment(0, 0);
fdlHostName.right = new FormAttachment(middle, -margin);
wlHostName.setLayoutData(fdlHostName);
wHostName = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wHostName);
wHostName.addModifyListener(lsMod);
FormData fdHostName = new FormData();
fdHostName.top = new FormAttachment(wConnAcc, margin);
fdHostName.left = new FormAttachment(middle, 0);
fdHostName.right = new FormAttachment(95, 0);
wHostName.setLayoutData(fdHostName);
// DBName
wlDBName = new Label(wDbComp, SWT.RIGHT);
wlDBName.setText(Messages.getString("DatabaseDialog.label.DatabaseName")); //$NON-NLS-1$
props.setLook(wlDBName);
FormData fdlDBName = new FormData();
fdlDBName.top = new FormAttachment(wHostName, margin);
fdlDBName.left = new FormAttachment(0, 0);
fdlDBName.right = new FormAttachment(middle, -margin);
wlDBName.setLayoutData(fdlDBName);
wDBName = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDBName);
wDBName.addModifyListener(lsMod);
FormData fdDBName = new FormData();
fdDBName.top = new FormAttachment(wHostName, margin);
fdDBName.left = new FormAttachment(middle, 0);
fdDBName.right = new FormAttachment(95, 0);
wDBName.setLayoutData(fdDBName);
// Port
wlPort = new Label(wDbComp, SWT.RIGHT);
wlPort.setText(Messages.getString("DatabaseDialog.label.PortNumber")); //$NON-NLS-1$
props.setLook(wlPort);
FormData fdlPort = new FormData();
fdlPort.top = new FormAttachment(wDBName, margin);
fdlPort.left = new FormAttachment(0, 0);
fdlPort.right = new FormAttachment(middle, -margin);
wlPort.setLayoutData(fdlPort);
wPort = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wPort);
wPort.addModifyListener(lsMod);
FormData fdPort = new FormData();
fdPort.top = new FormAttachment(wDBName, margin);
fdPort.left = new FormAttachment(middle, 0);
fdPort.right = new FormAttachment(95, 0);
wPort.setLayoutData(fdPort);
// Username
wlUsername = new Label(wDbComp, SWT.RIGHT);
wlUsername.setText(Messages.getString("DatabaseDialog.label.Username")); //$NON-NLS-1$
props.setLook(wlUsername);
FormData fdlUsername = new FormData();
fdlUsername.top = new FormAttachment(wPort, margin);
fdlUsername.left = new FormAttachment(0, 0);
fdlUsername.right = new FormAttachment(middle, -margin);
wlUsername.setLayoutData(fdlUsername);
wUsername = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wUsername);
wUsername.addModifyListener(lsMod);
FormData fdUsername = new FormData();
fdUsername.top = new FormAttachment(wPort, margin);
fdUsername.left = new FormAttachment(middle, 0);
fdUsername.right = new FormAttachment(95, 0);
wUsername.setLayoutData(fdUsername);
// Password
wlPassword = new Label(wDbComp, SWT.RIGHT);
wlPassword.setText(Messages.getString("DatabaseDialog.label.Password")); //$NON-NLS-1$
props.setLook(wlPassword);
FormData fdlPassword = new FormData();
fdlPassword.top = new FormAttachment(wUsername, margin);
fdlPassword.left = new FormAttachment(0, 0);
fdlPassword.right = new FormAttachment(middle, -margin);
wlPassword.setLayoutData(fdlPassword);
wPassword = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wPassword);
wPassword.setEchoChar('*');
wPassword.addModifyListener(lsMod);
FormData fdPassword = new FormData();
fdPassword.top = new FormAttachment(wUsername, margin);
fdPassword.left = new FormAttachment(middle, 0);
fdPassword.right = new FormAttachment(95, 0);
wPassword.setLayoutData(fdPassword);
FormData fdDbComp = new FormData();
fdDbComp.left = new FormAttachment(0, 0);
fdDbComp.top = new FormAttachment(0, 0);
fdDbComp.right = new FormAttachment(100, 0);
fdDbComp.bottom = new FormAttachment(100, 0);
wDbComp.setLayoutData(fdDbComp);
wDbComp.layout();
wDbTab.setControl(wDbComp);
// ///////////////////////////////////////////////////////////
// / END OF GEN TAB
// ///////////////////////////////////////////////////////////
}
private void addPoolTab()
{
// ////////////////////////
// START OF POOL TAB///
// /
wPoolTab = new CTabItem(wTabFolder, SWT.NONE);
wPoolTab.setText(Messages.getString("DatabaseDialog.PoolTab.title")); //$NON-NLS-1$
FormLayout poolLayout = new FormLayout();
poolLayout.marginWidth = Const.FORM_MARGIN;
poolLayout.marginHeight = Const.FORM_MARGIN;
wPoolComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wPoolComp);
wPoolComp.setLayout(poolLayout);
// What's the data tablespace name?
wlUsePool = new Label(wPoolComp, SWT.RIGHT);
props.setLook(wlUsePool);
wlUsePool.setText(Messages.getString("DatabaseDialog.label.UseConnectionPool")); //$NON-NLS-1$
FormData fdlUsePool = new FormData();
fdlUsePool.top = new FormAttachment(0, 0);
fdlUsePool.left = new FormAttachment(0, 0); // First one in the left top corner
fdlUsePool.right = new FormAttachment(middle, -margin);
wlUsePool.setLayoutData(fdlUsePool);
wUsePool = new Button(wPoolComp, SWT.CHECK);
wUsePool.setSelection(connection.isUsingConnectionPool());
props.setLook(wUsePool);
wUsePool.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
connection.setChanged();
enableFields();
}
});
FormData fdUsePool = new FormData();
fdUsePool.top = new FormAttachment(0, 0);
fdUsePool.left = new FormAttachment(middle, 0); // To the right of the label
wUsePool.setLayoutData(fdUsePool);
// What's the initial pool size
wlInitPool = new Label(wPoolComp, SWT.RIGHT);
props.setLook(wlInitPool);
wlInitPool.setText(Messages.getString("DatabaseDialog.label.InitialPoolSize")); //$NON-NLS-1$
FormData fdlInitPool = new FormData();
fdlInitPool.top = new FormAttachment(wUsePool, margin);
fdlInitPool.left = new FormAttachment(0, 0); // First one in the left top corner
fdlInitPool.right = new FormAttachment(middle, -margin);
wlInitPool.setLayoutData(fdlInitPool);
wInitPool = new TextVar(wPoolComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wInitPool.setText(Integer.toString(connection.getInitialPoolSize()));
props.setLook(wInitPool);
wInitPool.addModifyListener(lsMod);
FormData fdInitPool = new FormData();
fdInitPool.top = new FormAttachment(wUsePool, margin);
fdInitPool.left = new FormAttachment(middle, 0); // To the right of the label
fdInitPool.right = new FormAttachment(95, 0);
wInitPool.setLayoutData(fdInitPool);
// What's the maximum pool size
wlMaxPool = new Label(wPoolComp, SWT.RIGHT);
props.setLook(wlMaxPool);
wlMaxPool.setText(Messages.getString("DatabaseDialog.label.MaximumPoolSize")); //$NON-NLS-1$
FormData fdlMaxPool = new FormData();
fdlMaxPool.top = new FormAttachment(wInitPool, margin);
fdlMaxPool.left = new FormAttachment(0, 0); // First one in the left top corner
fdlMaxPool.right = new FormAttachment(middle, -margin);
wlMaxPool.setLayoutData(fdlMaxPool);
wMaxPool = new TextVar(wPoolComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wMaxPool.setText(Integer.toString(connection.getMaximumPoolSize()));
props.setLook(wMaxPool);
wMaxPool.addModifyListener(lsMod);
FormData fdMaxPool = new FormData();
fdMaxPool.top = new FormAttachment(wInitPool, margin);
fdMaxPool.left = new FormAttachment(middle, 0); // To the right of the label
fdMaxPool.right = new FormAttachment(95, 0);
wMaxPool.setLayoutData(fdMaxPool);
// What's the maximum pool size
wlPoolParameters = new Label(wPoolComp, SWT.RIGHT);
props.setLook(wlPoolParameters);
wlPoolParameters.setText(Messages.getString("DatabaseDialog.label.PoolParameters")); //$NON-NLS-1$
FormData fdlPoolParameters = new FormData();
fdlPoolParameters.top = new FormAttachment(wInitPool, margin);
fdlPoolParameters.left = new FormAttachment(0, 0); // First one in the left top corner
fdlPoolParameters.right = new FormAttachment(middle, -margin);
wlPoolParameters.setLayoutData(fdlPoolParameters);
// options list
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(Messages.getString("DatabaseDialog.column.PoolParameter"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.PoolDefault"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.PoolValue"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
colinfo[2].setUsingVariables(true);
final ArrayList parameters = DatabaseConnectionPoolParameter.getRowList(BaseDatabaseMeta.poolingParameters, Messages
.getString("DatabaseDialog.column.PoolParameter"), Messages.getString("DatabaseDialog.column.PoolDefault"), Messages
.getString("DatabaseDialog.column.PoolDescription"));
colinfo[0].setSelectionAdapter(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
SelectRowDialog dialog = new SelectRowDialog(shell, SWT.NONE, Messages.getString("DatabaseDialog.column.SelectPoolParameter"),
parameters);
Row row = dialog.open();
if (row != null)
{
// the parameter is the first value
String parameterName = row.getValue(0).getString();
String defaultValue = DatabaseConnectionPoolParameter.findParameter(parameterName, BaseDatabaseMeta.poolingParameters)
.getDefaultValue();
wPoolParameters.setText(Const.NVL(parameterName, ""), e.x, e.y);
wPoolParameters.setText(Const.NVL(defaultValue, ""), e.x + 1, e.y);
}
}
});
wPoolParameters = new TableView(wPoolComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props);
props.setLook(wPoolParameters);
FormData fdOptions = new FormData();
fdOptions.left = new FormAttachment(0, 0);
fdOptions.right = new FormAttachment(100, 0);
fdOptions.top = new FormAttachment(wMaxPool, margin * 2);
fdOptions.bottom = new FormAttachment(100, -20);
wPoolParameters.setLayoutData(fdOptions);
FormData fdPoolComp = new FormData();
fdPoolComp.left = new FormAttachment(0, 0);
fdPoolComp.top = new FormAttachment(0, 0);
fdPoolComp.right = new FormAttachment(100, 0);
fdPoolComp.bottom = new FormAttachment(100, 0);
wPoolComp.setLayoutData(fdPoolComp);
wPoolComp.layout();
wPoolTab.setControl(wPoolComp);
}
private void addOracleTab()
{
// ////////////////////////
// START OF ORACLE TAB///
// /
wOracleTab = new CTabItem(wTabFolder, SWT.NONE);
wOracleTab.setText(Messages.getString("DatabaseDialog.OracleTab.title")); //$NON-NLS-1$
FormLayout oracleLayout = new FormLayout();
oracleLayout.marginWidth = Const.FORM_MARGIN;
oracleLayout.marginHeight = Const.FORM_MARGIN;
wOracleComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wOracleComp);
wOracleComp.setLayout(oracleLayout);
// What's the data tablespace name?
wlData = new Label(wOracleComp, SWT.RIGHT);
props.setLook(wlData);
wlData.setText(Messages.getString("DatabaseDialog.label.TablespaceForData")); //$NON-NLS-1$
FormData fdlData = new FormData();
fdlData.top = new FormAttachment(0, 0);
fdlData.left = new FormAttachment(0, 0); // First one in the left top corner
fdlData.right = new FormAttachment(middle, -margin);
wlData.setLayoutData(fdlData);
wData = new TextVar(wOracleComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wData.setText(NVL(connection.getDataTablespace() == null ? "" : connection.getDataTablespace(), "")); //$NON-NLS-1$ //$NON-NLS-2$
props.setLook(wData);
wData.addModifyListener(lsMod);
FormData fdData = new FormData();
fdData.top = new FormAttachment(0, 0);
fdData.left = new FormAttachment(middle, 0); // To the right of the label
fdData.right = new FormAttachment(95, 0);
wData.setLayoutData(fdData);
// What's the index tablespace name?
wlIndex = new Label(wOracleComp, SWT.RIGHT);
props.setLook(wlIndex);
wlIndex.setText(Messages.getString("DatabaseDialog.label.TablespaceForIndexes")); //$NON-NLS-1$
FormData fdlIndex = new FormData();
fdlIndex.top = new FormAttachment(wData, margin);
fdlIndex.left = new FormAttachment(0, 0); // First one in the left top corner
fdlIndex.right = new FormAttachment(middle, -margin);
wlIndex.setLayoutData(fdlIndex);
wIndex = new TextVar(wOracleComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wIndex.setText(NVL(connection.getIndexTablespace() == null ? "" : connection.getIndexTablespace(), "")); //$NON-NLS-1$ //$NON-NLS-2$
props.setLook(wIndex);
wIndex.addModifyListener(lsMod);
FormData fdIndex = new FormData();
fdIndex.top = new FormAttachment(wData, margin);
fdIndex.left = new FormAttachment(middle, 0); // To the right of the label
fdIndex.right = new FormAttachment(95, 0);
wIndex.setLayoutData(fdIndex);
FormData fdOracleComp = new FormData();
fdOracleComp.left = new FormAttachment(0, 0);
fdOracleComp.top = new FormAttachment(0, 0);
fdOracleComp.right = new FormAttachment(100, 0);
fdOracleComp.bottom = new FormAttachment(100, 0);
wOracleComp.setLayoutData(fdOracleComp);
wOracleComp.layout();
wOracleTab.setControl(wOracleComp);
}
private void addInformixTab()
{
// ////////////////////////
// START OF INFORMIX TAB///
// /
wIfxTab = new CTabItem(wTabFolder, SWT.NONE);
wIfxTab.setText(Messages.getString("DatabaseDialog.IfxTab.title")); //$NON-NLS-1$
FormLayout ifxLayout = new FormLayout();
ifxLayout.marginWidth = Const.FORM_MARGIN;
ifxLayout.marginHeight = Const.FORM_MARGIN;
wIfxComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wIfxComp);
wIfxComp.setLayout(ifxLayout);
// Servername
wlServername = new Label(wIfxComp, SWT.RIGHT);
wlServername.setText(Messages.getString("DatabaseDialog.label.InformixServername")); //$NON-NLS-1$
props.setLook(wlServername);
FormData fdlServername = new FormData();
fdlServername.top = new FormAttachment(0, margin);
fdlServername.left = new FormAttachment(0, 0);
fdlServername.right = new FormAttachment(middle, -margin);
wlServername.setLayoutData(fdlServername);
wServername = new Text(wIfxComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wServername);
wServername.addModifyListener(lsMod);
FormData fdServername = new FormData();
fdServername.top = new FormAttachment(0, margin);
fdServername.left = new FormAttachment(middle, 0);
fdServername.right = new FormAttachment(95, 0);
wServername.setLayoutData(fdServername);
FormData fdIfxComp = new FormData();
fdIfxComp.left = new FormAttachment(0, 0);
fdIfxComp.top = new FormAttachment(0, 0);
fdIfxComp.right = new FormAttachment(100, 0);
fdIfxComp.bottom = new FormAttachment(100, 0);
wIfxComp.setLayoutData(fdIfxComp);
wIfxComp.layout();
wIfxTab.setControl(wIfxComp);
}
private void addMySQLTab()
{
// ////////////////////////
// START OF MySQL TAB///
// /
wMySQLTab = new CTabItem(wTabFolder, SWT.NONE);
wMySQLTab.setText(Messages.getString("DatabaseDialog.MySQLTab.title")); //$NON-NLS-1$
FormLayout MySQLLayout = new FormLayout();
MySQLLayout.marginWidth = Const.FORM_MARGIN;
MySQLLayout.marginHeight = Const.FORM_MARGIN;
wMySQLComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wMySQLComp);
wMySQLComp.setLayout(MySQLLayout);
// StreamResult
wlStreamResult = new Label(wMySQLComp, SWT.RIGHT);
wlStreamResult.setText(Messages.getString("DatabaseDialog.label.MySQLStreamResults")); //$NON-NLS-1$
props.setLook(wlStreamResult);
FormData fdlStreamResult = new FormData();
fdlStreamResult.top = new FormAttachment(0, margin);
fdlStreamResult.left = new FormAttachment(0, 0);
fdlStreamResult.right = new FormAttachment(middle, -margin);
wlStreamResult.setLayoutData(fdlStreamResult);
wStreamResult = new Button(wMySQLComp, SWT.CHECK);
props.setLook(wStreamResult);
FormData fdStreamResult = new FormData();
fdStreamResult.top = new FormAttachment(0, margin);
fdStreamResult.left = new FormAttachment(middle, 0);
fdStreamResult.right = new FormAttachment(95, 0);
wStreamResult.setLayoutData(fdStreamResult);
FormData fdMySQLComp = new FormData();
fdMySQLComp.left = new FormAttachment(0, 0);
fdMySQLComp.top = new FormAttachment(0, 0);
fdMySQLComp.right = new FormAttachment(100, 0);
fdMySQLComp.bottom = new FormAttachment(100, 0);
wMySQLComp.setLayoutData(fdMySQLComp);
wMySQLComp.layout();
wMySQLTab.setControl(wMySQLComp);
}
private void addSAPTab()
{
// ////////////////////////
// START OF SAP TAB///
// /
wSAPTab = new CTabItem(wTabFolder, SWT.NONE);
wSAPTab.setText(Messages.getString("DatabaseDialog.label.Sap")); //$NON-NLS-1$
FormLayout sapLayout = new FormLayout();
sapLayout.marginWidth = Const.FORM_MARGIN;
sapLayout.marginHeight = Const.FORM_MARGIN;
wSAPComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wSAPComp);
wSAPComp.setLayout(sapLayout);
// wSAPLanguage, wSSAPystemNumber, wSAPSystemID
// Language
wlSAPLanguage = new Label(wSAPComp, SWT.RIGHT);
wlSAPLanguage.setText(Messages.getString("DatabaseDialog.label.Language")); //$NON-NLS-1$
props.setLook(wlSAPLanguage);
FormData fdlSAPLanguage = new FormData();
fdlSAPLanguage.top = new FormAttachment(0, margin);
fdlSAPLanguage.left = new FormAttachment(0, 0);
fdlSAPLanguage.right = new FormAttachment(middle, -margin);
wlSAPLanguage.setLayoutData(fdlSAPLanguage);
wSAPLanguage = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSAPLanguage);
wSAPLanguage.addModifyListener(lsMod);
FormData fdSAPLanguage = new FormData();
fdSAPLanguage.top = new FormAttachment(0, margin);
fdSAPLanguage.left = new FormAttachment(middle, 0);
fdSAPLanguage.right = new FormAttachment(95, 0);
wSAPLanguage.setLayoutData(fdSAPLanguage);
// SystemNumber
wlSAPSystemNumber = new Label(wSAPComp, SWT.RIGHT);
wlSAPSystemNumber.setText(Messages.getString("DatabaseDialog.label.SystemNumber")); //$NON-NLS-1$
props.setLook(wlSAPSystemNumber);
FormData fdlSAPSystemNumber = new FormData();
fdlSAPSystemNumber.top = new FormAttachment(wSAPLanguage, margin);
fdlSAPSystemNumber.left = new FormAttachment(0, 0);
fdlSAPSystemNumber.right = new FormAttachment(middle, -margin);
wlSAPSystemNumber.setLayoutData(fdlSAPSystemNumber);
wSAPSystemNumber = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSAPSystemNumber);
wSAPSystemNumber.addModifyListener(lsMod);
FormData fdSAPSystemNumber = new FormData();
fdSAPSystemNumber.top = new FormAttachment(wSAPLanguage, margin);
fdSAPSystemNumber.left = new FormAttachment(middle, 0);
fdSAPSystemNumber.right = new FormAttachment(95, 0);
wSAPSystemNumber.setLayoutData(fdSAPSystemNumber);
// SystemID
wlSAPClient = new Label(wSAPComp, SWT.RIGHT);
wlSAPClient.setText(Messages.getString("DatabaseDialog.label.SapClient")); //$NON-NLS-1$
props.setLook(wlSAPClient);
FormData fdlSAPClient = new FormData();
fdlSAPClient.top = new FormAttachment(wSAPSystemNumber, margin);
fdlSAPClient.left = new FormAttachment(0, 0);
fdlSAPClient.right = new FormAttachment(middle, -margin);
wlSAPClient.setLayoutData(fdlSAPClient);
wSAPClient = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSAPClient);
wSAPClient.addModifyListener(lsMod);
FormData fdSAPClient = new FormData();
fdSAPClient.top = new FormAttachment(wSAPSystemNumber, margin);
fdSAPClient.left = new FormAttachment(middle, 0);
fdSAPClient.right = new FormAttachment(95, 0);
wSAPClient.setLayoutData(fdSAPClient);
FormData fdSAPComp = new FormData();
fdSAPComp.left = new FormAttachment(0, 0);
fdSAPComp.top = new FormAttachment(0, 0);
fdSAPComp.right = new FormAttachment(100, 0);
fdSAPComp.bottom = new FormAttachment(100, 0);
wSAPComp.setLayoutData(fdSAPComp);
wSAPComp.layout();
wSAPTab.setControl(wSAPComp);
}
private void addGenericTab()
{
// ////////////////////////
// START OF DB TAB///
// /
wGenericTab = new CTabItem(wTabFolder, SWT.NONE);
wGenericTab.setText(Messages.getString("DatabaseDialog.GenericTab.title")); //$NON-NLS-1$
wGenericTab.setToolTipText(Messages.getString("DatabaseDialog.GenericTab.tooltip")); //$NON-NLS-1$
FormLayout genericLayout = new FormLayout();
genericLayout.marginWidth = Const.FORM_MARGIN;
genericLayout.marginHeight = Const.FORM_MARGIN;
wGenericComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wGenericComp);
wGenericComp.setLayout(genericLayout);
// URL
wlURL = new Label(wGenericComp, SWT.RIGHT);
wlURL.setText(Messages.getString("DatabaseDialog.label.Url")); //$NON-NLS-1$
props.setLook(wlURL);
FormData fdlURL = new FormData();
fdlURL.top = new FormAttachment(0, margin);
fdlURL.left = new FormAttachment(0, 0);
fdlURL.right = new FormAttachment(middle, -margin);
wlURL.setLayoutData(fdlURL);
wURL = new Text(wGenericComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wURL);
wURL.addModifyListener(lsMod);
FormData fdURL = new FormData();
fdURL.top = new FormAttachment(0, margin);
fdURL.left = new FormAttachment(middle, 0);
fdURL.right = new FormAttachment(95, 0);
wURL.setLayoutData(fdURL);
// Driver class
wlDriverClass = new Label(wGenericComp, SWT.RIGHT);
wlDriverClass.setText(Messages.getString("DatabaseDialog.label.DriverClass")); //$NON-NLS-1$
props.setLook(wlDriverClass);
FormData fdlDriverClass = new FormData();
fdlDriverClass.top = new FormAttachment(wURL, margin);
fdlDriverClass.left = new FormAttachment(0, 0);
fdlDriverClass.right = new FormAttachment(middle, -margin);
wlDriverClass.setLayoutData(fdlDriverClass);
wDriverClass = new Text(wGenericComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDriverClass);
wDriverClass.addModifyListener(lsMod);
FormData fdDriverClass = new FormData();
fdDriverClass.top = new FormAttachment(wURL, margin);
fdDriverClass.left = new FormAttachment(middle, 0);
fdDriverClass.right = new FormAttachment(95, 0);
wDriverClass.setLayoutData(fdDriverClass);
FormData fdGenericComp = new FormData();
fdGenericComp.left = new FormAttachment(0, 0);
fdGenericComp.top = new FormAttachment(0, 0);
fdGenericComp.right = new FormAttachment(100, 0);
fdGenericComp.bottom = new FormAttachment(100, 0);
wGenericComp.setLayoutData(fdGenericComp);
wGenericComp.layout();
wGenericTab.setControl(wGenericComp);
}
private void addOptionsTab()
{
// ////////////////////////
// START OF OPTIONS TAB///
// /
wOptionsTab = new CTabItem(wTabFolder, SWT.NONE);
wOptionsTab.setText(Messages.getString("DatabaseDialog.label.Options")); //$NON-NLS-1$
wOptionsTab.setToolTipText(Messages.getString("DatabaseDialog.tooltip.Options")); //$NON-NLS-1$
FormLayout optionsLayout = new FormLayout();
optionsLayout.marginWidth = margin;
optionsLayout.marginHeight = margin;
wOptionsComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wOptionsComp);
wOptionsComp.setLayout(optionsLayout);
wOptionsHelp = new Button(wOptionsComp, SWT.PUSH);
wOptionsHelp.setText(Messages.getString("DatabaseDialog.button.ShowHelp")); //$NON-NLS-1$
wOptionsHelp.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
showOptionsHelpText();
}
});
BaseStepDialog.positionBottomButtons(wOptionsComp, new Button[] { wOptionsHelp }, margin, null);
// options list
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(
Messages.getString("DatabaseDialog.column.DbType"), ColumnInfo.COLUMN_TYPE_CCOMBO, DatabaseMeta.getDBTypeDescLongList(), true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Parameter"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Value"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
};
colinfo[0].setToolTip(Messages.getString("DatabaseDialog.tooltip.DbType")); //$NON-NLS-1$
colinfo[1].setToolTip(Messages.getString("DatabaseDialog.tooltip.Parameter")); //$NON-NLS-1$
colinfo[2].setUsingVariables(true);
wOptions = new TableView(wOptionsComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props);
props.setLook(wOptions);
FormData fdOptions = new FormData();
fdOptions.left = new FormAttachment(0, 0);
fdOptions.right = new FormAttachment(100, 0);
fdOptions.top = new FormAttachment(0, 0);
fdOptions.bottom = new FormAttachment(wOptionsHelp, -margin);
wOptions.setLayoutData(fdOptions);
FormData fdOptionsComp = new FormData();
fdOptionsComp.left = new FormAttachment(0, 0);
fdOptionsComp.top = new FormAttachment(0, 0);
fdOptionsComp.right = new FormAttachment(100, 0);
fdOptionsComp.bottom = new FormAttachment(100, 0);
wOptionsComp.setLayoutData(fdOptionsComp);
wOptionsComp.layout();
wOptionsTab.setControl(wOptionsComp);
}
private void addSQLTab()
{
// ////////////////////////
// START OF SQL TAB///
// /
wSQLTab = new CTabItem(wTabFolder, SWT.NONE);
wSQLTab.setText(Messages.getString("DatabaseDialog.SQLTab.title")); //$NON-NLS-1$
wSQLTab.setToolTipText(Messages.getString("DatabaseDialog.SQLTab.tooltip")); //$NON-NLS-1$
FormLayout sqlLayout = new FormLayout();
sqlLayout.marginWidth = margin;
sqlLayout.marginHeight = margin;
wSQLComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wSQLComp);
wSQLComp.setLayout(sqlLayout);
wlSQL = new Label(wSQLComp, SWT.LEFT);
props.setLook(wlSQL);
wlSQL.setText(Messages.getString("DatabaseDialog.label.Statements")); //$NON-NLS-1$
FormData fdlSQL = new FormData();
fdlSQL.left = new FormAttachment(0, 0);
fdlSQL.top = new FormAttachment(0, 0);
wlSQL.setLayoutData(fdlSQL);
wSQL = new Text(wSQLComp, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER);
props.setLook(wSQL, Props.WIDGET_STYLE_FIXED);
FormData fdSQL = new FormData();
fdSQL.left = new FormAttachment(0, 0);
fdSQL.right = new FormAttachment(100, 0);
fdSQL.top = new FormAttachment(wlSQL, margin);
fdSQL.bottom = new FormAttachment(100, 0);
wSQL.setLayoutData(fdSQL);
FormData fdSQLComp = new FormData();
fdSQLComp.left = new FormAttachment(0, 0);
fdSQLComp.top = new FormAttachment(0, 0);
fdSQLComp.right = new FormAttachment(100, 0);
fdSQLComp.bottom = new FormAttachment(100, 0);
wSQLComp.setLayoutData(fdSQLComp);
wSQLComp.layout();
wSQLTab.setControl(wSQLComp);
}
private void addClusterTab()
{
// ////////////////////////
// START OF CLUSTER TAB///
// /
// The tab
wClusterTab = new CTabItem(wTabFolder, SWT.NONE);
wClusterTab.setText(Messages.getString("DatabaseDialog.ClusterTab.title")); //$NON-NLS-1$
wClusterTab.setToolTipText(Messages.getString("DatabaseDialog.ClusterTab.tooltip")); //$NON-NLS-1$
FormLayout clusterLayout = new FormLayout();
clusterLayout.marginWidth = margin;
clusterLayout.marginHeight = margin;
// The composite
wClusterComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wClusterComp);
wClusterComp.setLayout(clusterLayout);
// The check box
wlUseCluster = new Label(wClusterComp, SWT.RIGHT);
props.setLook(wlUseCluster);
wlUseCluster.setText(Messages.getString("DatabaseDialog.label.UseClustering")); //$NON-NLS-1$
wlUseCluster.setToolTipText(Messages.getString("DatabaseDialog.tooltip.UseClustering")); //$NON-NLS-1$
FormData fdlUseCluster = new FormData();
fdlUseCluster.left = new FormAttachment(0, 0);
fdlUseCluster.right = new FormAttachment(middle, 0);
fdlUseCluster.top = new FormAttachment(0, 0);
wlUseCluster.setLayoutData(fdlUseCluster);
wUseCluster = new Button(wClusterComp, SWT.CHECK);
props.setLook(wUseCluster);
FormData fdUseCluster = new FormData();
fdUseCluster.left = new FormAttachment(middle, margin);
fdUseCluster.right = new FormAttachment(100, 0);
fdUseCluster.top = new FormAttachment(0, 0);
wUseCluster.setLayoutData(fdUseCluster);
wUseCluster.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
enableFields();
}
});
// Cluster list
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(Messages.getString("DatabaseDialog.column.PartitionId"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Hostname"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Port"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.DatabaseName"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Username"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Password"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
colinfo[0].setToolTip(Messages.getString("DatabaseDialog.tooltip.PartitionId")); //$NON-NLS-1$
colinfo[1].setToolTip(Messages.getString("DatabaseDialog.tooltip.Hostname")); //$NON-NLS-1$
colinfo[5].setPasswordField(true);
colinfo[5].setUsingVariables(true);
wCluster = new TableView(wClusterComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props);
props.setLook(wCluster);
FormData fdCluster = new FormData();
fdCluster.left = new FormAttachment(0, 0);
fdCluster.right = new FormAttachment(100, 0);
fdCluster.top = new FormAttachment(wUseCluster, margin);
fdCluster.bottom = new FormAttachment(100, 0);
wCluster.setLayoutData(fdCluster);
FormData fdClusterComp = new FormData();
fdClusterComp.left = new FormAttachment(0, 0);
fdClusterComp.top = new FormAttachment(0, 0);
fdClusterComp.right = new FormAttachment(100, 0);
fdClusterComp.bottom = new FormAttachment(100, 0);
wClusterComp.setLayoutData(fdClusterComp);
wClusterComp.layout();
wClusterTab.setControl(wClusterComp);
}
private void showOptionsHelpText()
{
DatabaseMeta meta = new DatabaseMeta();
try
{
getInfo(meta);
String helpText = meta.getExtraOptionsHelpText();
if (Const.isEmpty(helpText)) return;
// Try to open a new tab in the Spoon editor.
// If spoon is not available, not in the classpath or can't open the tab, we show the URL in a dialog
//
boolean openedTab = false;
try
{
Spoon spoon = Spoon.getInstance();
if (spoon != null)
{
openedTab = spoon.addSpoonBrowser(meta.getDatabaseTypeDesc() + " : JDBC Options help", helpText);
}
}
catch (Throwable t)
{
}
if (!openedTab)
{
EnterTextDialog dialog = new EnterTextDialog(shell,
Messages.getString("DatabaseDialog.HelpText.title"), Messages.getString("DatabaseDialog.HelpText.description", meta.getDatabaseTypeDesc()), helpText, true); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setReadOnly();
dialog.open();
}
}
catch (KettleException e)
{
new ErrorDialog(shell,
Messages.getString("DatabaseDialog.ErrorHelpText.title"), Messages.getString("DatabaseDialog.ErrorHelpText.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void dispose()
{
props.setScreen(new WindowProperty(shell));
shell.dispose();
}
public void setDatabases(ArrayList databases)
{
this.databases = databases;
}
public void getData()
{
wConn.setText(NVL(connection == null ? "" : connection.getName(), "")); //$NON-NLS-1$ //$NON-NLS-2$
wConnType.select(connection.getDatabaseType() - 1);
wConnType.showSelection();
previousDatabaseType = DatabaseMeta.getDatabaseTypeCode(wConnType.getSelectionIndex() + 1);
setAccessList();
String accessList[] = wConnAcc.getItems();
int accessIndex = Const.indexOfString(connection.getAccessTypeDesc(), accessList);
wConnAcc.select(accessIndex);
wConnAcc.showSelection();
wHostName.setText(NVL(connection.getHostname(), "")); //$NON-NLS-1$
wDBName.setText(NVL(connection.getDatabaseName(), "")); //$NON-NLS-1$
wPort.setText(NVL(connection.getDatabasePortNumberString(), "")); //$NON-NLS-1$
wServername.setText(NVL(connection.getServername(), "")); //$NON-NLS-1$
wUsername.setText(NVL(connection.getUsername(), "")); //$NON-NLS-1$
wPassword.setText(NVL(connection.getPassword(), "")); //$NON-NLS-1$
wData.setText(NVL(connection.getDataTablespace(), "")); //$NON-NLS-1$
wIndex.setText(NVL(connection.getIndexTablespace(), "")); //$NON-NLS-1$
wSAPLanguage.setText(connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_LANGUAGE, "")); //$NON-NLS-1$
wSAPSystemNumber.setText(connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_SYSTEM_NUMBER, "")); //$NON-NLS-1$
wSAPClient.setText(connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_CLIENT, "")); //$NON-NLS-1$
wURL.setText(connection.getAttributes().getProperty(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL, "")); //$NON-NLS-1$
wDriverClass.setText(connection.getAttributes().getProperty(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS, "")); //$NON-NLS-1$
wStreamResult.setSelection( connection.isStreamingResults() );
getOptionsData();
checkPasswordVisible(wPassword.getTextWidget());
wSQL.setText(NVL(connection.getConnectSQL(), "")); //$NON-NLS-1$
getPoolingData();
wConn.setFocus();
wConn.selectAll();
getClusterData();
}
private void getClusterData()
{
// The clustering information
wUseCluster.setSelection(connection.isPartitioned());
PartitionDatabaseMeta[] clusterInformation = connection.getPartitioningInformation();
for (int i = 0; i < clusterInformation.length; i++)
{
PartitionDatabaseMeta meta = clusterInformation[i];
TableItem tableItem = new TableItem(wCluster.table, SWT.NONE);
tableItem.setText(1, Const.NVL(meta.getPartitionId(), "")); //$NON-NLS-1$
tableItem.setText(2, Const.NVL(meta.getHostname(), "")); //$NON-NLS-1$
tableItem.setText(3, Const.NVL(meta.getPort(), "")); //$NON-NLS-1$
tableItem.setText(4, Const.NVL(meta.getDatabaseName(), "")); //$NON-NLS-1$
tableItem.setText(5, Const.NVL(meta.getUsername(), "")); //$NON-NLS-1$
tableItem.setText(5, Const.NVL(meta.getPassword(), "")); //$NON-NLS-1$
}
wCluster.removeEmptyRows();
wCluster.setRowNums();
wCluster.optWidth(true);
}
private void getOptionsData()
{
// The extra options as well...
Iterator keys = extraOptions.keySet().iterator();
while (keys.hasNext())
{
String parameter = (String) keys.next();
String value = (String) extraOptions.get(parameter);
if (!Const.isEmpty(value) && value.equals(DatabaseMeta.EMPTY_OPTIONS_STRING)) value = ""; //$NON-NLS-1$
// If the paremeter starts with a database type code we add it...
//
// For example MySQL.defaultFetchSize
int dotIndex = parameter.indexOf("."); //$NON-NLS-1$
if (dotIndex >= 0 && wConnType.getSelectionCount() == 1)
{
String databaseTypeString = parameter.substring(0, dotIndex);
String parameterOption = parameter.substring(dotIndex + 1);
int databaseType = DatabaseMeta.getDatabaseType(databaseTypeString);
TableItem item = new TableItem(wOptions.table, SWT.NONE);
item.setText(1, DatabaseMeta.getDatabaseTypeDesc(databaseType));
item.setText(2, parameterOption);
if (value != null) item.setText(3, value);
}
}
wOptions.removeEmptyRows();
wOptions.setRowNums();
wOptions.optWidth(true);
}
private void getPoolingData()
{
// The extra options as well...
Properties properties = connection.getConnectionPoolingProperties();
Iterator keys = properties.keySet().iterator();
while (keys.hasNext())
{
String parameter = (String) keys.next();
String value = (String) properties.get(parameter);
String defValue = DatabaseConnectionPoolParameter.findParameter(parameter, BaseDatabaseMeta.poolingParameters).getDefaultValue();
TableItem item = new TableItem(wPoolParameters.table, SWT.NONE);
item.setText(1, Const.NVL(parameter, ""));
item.setText(2, Const.NVL(defValue, ""));
item.setText(3, Const.NVL(value, ""));
}
wPoolParameters.removeEmptyRows();
wPoolParameters.setRowNums();
wPoolParameters.optWidth(true);
}
public void enableFields()
{
// See if we need to refresh the access list...
String type = DatabaseMeta.getDatabaseTypeCode(wConnType.getSelectionIndex() + 1);
if (!type.equalsIgnoreCase(previousDatabaseType)) setAccessList();
previousDatabaseType = type;
int idxAccType = wConnAcc.getSelectionIndex();
int acctype = -1;
if (idxAccType >= 0)
{
acctype = DatabaseMeta.getAccessType(wConnAcc.getItem(idxAccType));
}
// Hide the fields not relevent to JNDI data sources
wlHostName.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wHostName.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlPort.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wPort.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlURL.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wURL.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlDriverClass.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wDriverClass.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlUsername.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wUsername.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlPassword.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wPassword.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
if (acctype == DatabaseMeta.TYPE_ACCESS_JNDI) { return; }
int idxDBType = wConnType.getSelectionIndex();
if (idxDBType >= 0)
{
int dbtype = DatabaseMeta.getDatabaseType(wConnType.getItem(idxDBType));
// If the type is not Informix: disable the servername field!
wlServername.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_INFORMIX);
wServername.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_INFORMIX);
// If this is an Oracle connection enable the Oracle tab
wlData.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_ORACLE);
wData.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_ORACLE);
wlIndex.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_ORACLE);
wIndex.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_ORACLE);
wlSAPLanguage.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wSAPLanguage.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wlSAPSystemNumber.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wSAPSystemNumber.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wlSAPClient.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wSAPClient.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wlDBName.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wDBName.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wlPort.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wPort.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wTest.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wExp.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wlHostName.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE)
|| (dbtype == DatabaseMeta.TYPE_ACCESS_JNDI));
wHostName.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlDBName.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wDBName.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlPort.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wPort.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlURL.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wURL.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wlDriverClass.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wDriverClass.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
}
// The connection pooling options: do those as well...
wlMaxPool.setEnabled(wUsePool.getSelection());
wMaxPool.setEnabled(wUsePool.getSelection());
wlInitPool.setEnabled(wUsePool.getSelection());
wInitPool.setEnabled(wUsePool.getSelection());
wlPoolParameters.setEnabled(wUsePool.getSelection());
wPoolParameters.setEnabled(wUsePool.getSelection());
wPoolParameters.table.setEnabled(wUsePool.getSelection());
// How about the clustering stuff?
wCluster.table.setEnabled(wUseCluster.getSelection());
}
public void setPortNumber()
{
String type = DatabaseMeta.getDatabaseTypeCode(wConnType.getSelectionIndex() + 1);
// What port should we select?
String acce = wConnAcc.getItem(wConnAcc.getSelectionIndex());
int port = DatabaseMeta.getPortForDBType(type, acce);
if (port < 0)
wPort.setText(""); //$NON-NLS-1$
else
wPort.setText("" + port); //$NON-NLS-1$
}
public void setAccessList()
{
if (wConnType.getSelectionCount() < 1) return;
int acc[] = DatabaseMeta.getAccessTypeList(wConnType.getSelection()[0]);
wConnAcc.removeAll();
for (int i = 0; i < acc.length; i++)
{
wConnAcc.add(DatabaseMeta.getAccessTypeDescLong(acc[i]));
}
// If nothing is selected: select the first item (mostly the native driver)
if (wConnAcc.getSelectionIndex() < 0)
{
wConnAcc.select(0);
}
}
private void cancel()
{
connectionName = null;
connection.setChanged(changed);
dispose();
}
public void getInfo(DatabaseMeta databaseMeta) throws KettleException
{
// Before we put all attributes back in, clear the old list to make sure...
// Warning: the port is an attribute too now.
//
databaseMeta.getAttributes().clear();
// Name:
databaseMeta.setName(wConn.getText());
// Connection type:
String contype[] = wConnType.getSelection();
if (contype.length > 0)
{
databaseMeta.setDatabaseType(contype[0]);
}
// Access type:
String acctype[] = wConnAcc.getSelection();
if (acctype.length > 0)
{
databaseMeta.setAccessType(DatabaseMeta.getAccessType(acctype[0]));
}
// Hostname
databaseMeta.setHostname(wHostName.getText());
// Database name
databaseMeta.setDBName(wDBName.getText());
// Port number
databaseMeta.setDBPort(wPort.getText());
// Username
databaseMeta.setUsername(wUsername.getText());
// Password
databaseMeta.setPassword(wPassword.getText());
// Servername
databaseMeta.setServername(wServername.getText());
// MySQL
databaseMeta.setStreamingResults(wStreamResult.getSelection());
// Data tablespace
databaseMeta.setDataTablespace(wData.getText());
// Index tablespace
databaseMeta.setIndexTablespace(wIndex.getText());
// SAP Attributes...
databaseMeta.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_LANGUAGE, wSAPLanguage.getText());
databaseMeta.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_SYSTEM_NUMBER, wSAPSystemNumber.getText());
databaseMeta.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_CLIENT, wSAPClient.getText());
// Generic settings...
databaseMeta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL, wURL.getText());
databaseMeta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS, wDriverClass.getText());
String[] remarks = databaseMeta.checkParameters();
if (remarks.length != 0)
{
String message = ""; //$NON-NLS-1$
for (int i = 0; i < remarks.length; i++)
message += " * " + remarks[i] + Const.CR; //$NON-NLS-1$
throw new KettleException(Messages.getString("DatabaseDialog.Exception.IncorrectParameter") + Const.CR + message); //$NON-NLS-1$
}
// Now put in the extra options...
for (int i = 0; i < wOptions.nrNonEmpty(); i++)
{
TableItem item = wOptions.getNonEmpty(i);
String dbTypeStr = item.getText(1);
String parameter = item.getText(2);
String value = item.getText(3);
int dbType = DatabaseMeta.getDatabaseType(dbTypeStr);
// Only if both parameters are supplied, we will add to the map...
if (!Const.isEmpty(parameter) && dbType != DatabaseMeta.TYPE_DATABASE_NONE)
{
if (Const.isEmpty(value)) value = DatabaseMeta.EMPTY_OPTIONS_STRING;
String typedParameter = BaseDatabaseMeta.ATTRIBUTE_PREFIX_EXTRA_OPTION + DatabaseMeta.getDatabaseTypeCode(dbType) + "." + parameter; //$NON-NLS-1$
databaseMeta.getAttributes().put(typedParameter, value);
}
}
// The SQL to execute...
databaseMeta.setConnectSQL(wSQL.getText());
// The connection pooling stuff...
databaseMeta.setUsingConnectionPool(wUsePool.getSelection());
databaseMeta.setInitialPoolSize(Const.toInt(wInitPool.getText(), ConnectionPoolUtil.defaultInitialNrOfConnections));
databaseMeta.setMaximumPoolSize(Const.toInt(wMaxPool.getText(), ConnectionPoolUtil.defaultMaximumNrOfConnections));
Properties poolProperties = new Properties();
for (int i = 0; i < wPoolParameters.nrNonEmpty(); i++)
{
TableItem item = wPoolParameters.getNonEmpty(i);
String parameterName = item.getText(1);
String value = item.getText(3);
if (!Const.isEmpty(parameterName) && !Const.isEmpty(value))
{
poolProperties.setProperty(parameterName, value);
}
}
databaseMeta.setConnectionPoolingProperties(poolProperties);
// Now grab the clustering information...
databaseMeta.setPartitioned(wUseCluster.getSelection());
PartitionDatabaseMeta[] clusterInfo = new PartitionDatabaseMeta[wCluster.nrNonEmpty()];
for (int i = 0; i < clusterInfo.length; i++)
{
TableItem tableItem = wCluster.getNonEmpty(i);
String partitionId = tableItem.getText(1);
String hostname = tableItem.getText(2);
String port = tableItem.getText(3);
String dbName = tableItem.getText(4);
String username = tableItem.getText(5);
String password = tableItem.getText(6);
clusterInfo[i] = new PartitionDatabaseMeta(partitionId, hostname, port, dbName);
clusterInfo[i].setUsername(username);
clusterInfo[i].setPassword(password);
}
databaseMeta.setPartitioningInformation(clusterInfo);
}
/**
* @deprecated use ok() in stead, like in most dialogs
*/
public void handleOK()
{
ok();
}
public void ok()
{
try
{
getInfo(connection);
connectionName = connection.getName();
connection.setID(database_id);
dispose();
}
catch (KettleException e)
{
new ErrorDialog(shell,
Messages.getString("DatabaseDialog.ErrorParameters.title"), Messages.getString("DatabaseDialog.ErrorParameters.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public String NVL(String str, String rep)
{
if (str == null) return rep;
return str;
}
public void test()
{
try
{
DatabaseMeta dbinfo = new DatabaseMeta();
getInfo(dbinfo);
test(shell, dbinfo, props);
}
catch (KettleException e)
{
new ErrorDialog(
shell,
Messages.getString("DatabaseDialog.ErrorParameters.title"), Messages.getString("DatabaseDialog.ErrorConnectionInfo.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Test the database connection
*/
public static final void test(Shell shell, DatabaseMeta dbinfo, Props props)
{
String[] remarks = dbinfo.checkParameters();
if (remarks.length == 0)
{
StringBuffer report = new StringBuffer();
Database db = new Database(dbinfo);
if (dbinfo.isPartitioned())
{
PartitionDatabaseMeta[] partitioningInformation = dbinfo.getPartitioningInformation();
for (int i = 0; i < partitioningInformation.length; i++)
{
try
{
db.connect(partitioningInformation[i].getPartitionId());
report
.append(Messages.getString(
"DatabaseDialog.report.ConnectionWithPartOk", dbinfo.getName(), partitioningInformation[i].getPartitionId()) + Const.CR); //$NON-NLS-1$
}
catch (KettleException e)
{
report
.append(Messages
.getString(
"DatabaseDialog.report.ConnectionWithPartError", dbinfo.getName(), partitioningInformation[i].getPartitionId(), e.toString()) + Const.CR); //$NON-NLS-1$
report.append(Const.getStackTracker(e) + Const.CR);
}
finally
{
db.disconnect();
}
report.append(Messages.getString("DatabaseDialog.report.Hostname") + partitioningInformation[i].getHostname() + Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseDialog.report.Port") + partitioningInformation[i].getPort() + Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseDialog.report.DatabaseName") + partitioningInformation[i].getDatabaseName() + Const.CR); //$NON-NLS-1$
report.append(Const.CR);
}
}
else
{
try
{
db.connect();
report.append(Messages.getString("DatabaseDialog.report.ConnectionOk", dbinfo.getName()) + Const.CR); //$NON-NLS-1$
}
catch (KettleException e)
{
report.append(Messages.getString("DatabaseDialog.report.ConnectionError", dbinfo.getName()) + e.toString() + Const.CR); //$NON-NLS-1$
report.append(Const.getStackTracker(e) + Const.CR);
}
finally
{
db.disconnect();
}
report.append(Messages.getString("DatabaseDialog.report.Hostname") + dbinfo.getHostname() + Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseDialog.report.Port") + dbinfo.getDatabasePortNumberString() + Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseDialog.report.DatabaseName") + dbinfo.getDatabaseName() + Const.CR); //$NON-NLS-1$
report.append(Const.CR);
}
EnterTextDialog dialog = new EnterTextDialog(
shell,
Messages.getString("DatabaseDialog.ConnectionReport.title"), Messages.getString("DatabaseDialog.ConnectionReport.description"), report.toString()); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setReadOnly();
dialog.setFixed(true);
dialog.open();
}
else
{
String message = ""; //$NON-NLS-1$
for (int i = 0; i < remarks.length; i++)
message += " * " + remarks[i] + Const.CR; //$NON-NLS-1$
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setText(Messages.getString("DatabaseDialog.ErrorParameters2.title")); //$NON-NLS-1$
mb.setMessage(Messages.getString("DatabaseDialog.ErrorParameters2.description", message)); //$NON-NLS-1$
mb.open();
}
}
public void explore()
{
DatabaseMeta dbinfo = new DatabaseMeta();
try
{
getInfo(dbinfo);
DatabaseExplorerDialog ded = new DatabaseExplorerDialog(shell, SWT.NONE, dbinfo, databases, true);
ded.open();
}
catch (KettleException e)
{
new ErrorDialog(shell,
Messages.getString("DatabaseDialog.ErrorParameters,title"), Messages.getString("DatabaseDialog.ErrorParameters.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void showFeatureList()
{
DatabaseMeta dbinfo = new DatabaseMeta();
try
{
getInfo(dbinfo);
ArrayList buffer = (ArrayList) dbinfo.getFeatureSummary();
PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, Messages.getString("DatabaseDialog.FeatureList.title"), buffer); //$NON-NLS-1$
prd.setTitleMessage(Messages.getString("DatabaseDialog.FeatureList.title"), Messages.getString("DatabaseDialog.FeatureList.title2")); //$NON-NLS-1$ //$NON-NLS-2$
prd.open();
}
catch (KettleException e)
{
new ErrorDialog(shell,
Messages.getString("DatabaseDialog.FeatureListError.title"), Messages.getString("DatabaseDialog.FeatureListError.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
| src/be/ibridge/kettle/core/dialog/DatabaseDialog.java | /**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.core.dialog;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
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.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import be.ibridge.kettle.core.ColumnInfo;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Props;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.WindowProperty;
import be.ibridge.kettle.core.database.BaseDatabaseMeta;
import be.ibridge.kettle.core.database.ConnectionPoolUtil;
import be.ibridge.kettle.core.database.Database;
import be.ibridge.kettle.core.database.DatabaseConnectionPoolParameter;
import be.ibridge.kettle.core.database.DatabaseMeta;
import be.ibridge.kettle.core.database.GenericDatabaseMeta;
import be.ibridge.kettle.core.database.PartitionDatabaseMeta;
import be.ibridge.kettle.core.database.SAPR3DatabaseMeta;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.widget.TableView;
import be.ibridge.kettle.core.widget.TextVar;
import be.ibridge.kettle.spoon.Spoon;
import be.ibridge.kettle.trans.step.BaseStepDialog;
/**
*
* Dialog that allows you to edit the settings of a database connection.
*
* @see <code>DatabaseInfo</code>
* @author Matt
* @since 18-05-2003
*
*/
public class DatabaseDialog extends Dialog
{
private DatabaseMeta connection;
private CTabFolder wTabFolder;
private CTabItem wDbTab, wPoolTab, wOracleTab, wIfxTab, wMySQLTab, wSAPTab, wGenericTab, wOptionsTab, wSQLTab, wClusterTab;
private Composite wDbComp, wPoolComp, wOracleComp, wIfxComp, wMySQLComp, wSAPComp, wGenericComp, wOptionsComp, wSQLComp, wClusterComp;
private Shell shell;
// DB
private Label wlConn, wlConnType, wlConnAcc, wlHostName, wlDBName, wlPort, wlUsername, wlPassword, wlData, wlIndex;
private Text wConn;
private TextVar wHostName, wDBName, wPort, wUsername, wPassword, wData, wIndex;
private List wConnType, wConnAcc;
// Informix
private Label wlServername;
private Text wServername;
// MySQL
private Label wlStreamResult;
private Button wStreamResult;
// Pooling
private Label wlUsePool, wlInitPool, wlMaxPool;
private Button wUsePool;
private TextVar wInitPool, wMaxPool;
private TableView wPoolParameters;
private Label wlPoolParameters;
// SAP
private Label wlSAPLanguage, wlSAPSystemNumber, wlSAPClient;
private Text wSAPLanguage, wSAPSystemNumber, wSAPClient;
// Generic
private Label wlURL, wlDriverClass;
private Text wURL, wDriverClass;
// Options
private TableView wOptions;
// SQL
private Label wlSQL;
private Text wSQL;
// Cluster
private Label wlUseCluster;
private Button wUseCluster;
private TableView wCluster;
private Button wOK, wTest, wExp, wList, wCancel, wOptionsHelp;
private String connectionName;
private ModifyListener lsMod;
private boolean changed;
private Props props;
private String previousDatabaseType;
private ArrayList databases;
private Map extraOptions;
private int middle;
private int margin;
private long database_id;
public DatabaseDialog(Shell par, int style, LogWriter lg, DatabaseMeta conn, Props pr)
{
super(par, style);
connection = conn;
connectionName = conn.getName();
props = pr;
this.databases = null;
this.extraOptions = conn.getExtraOptions();
this.database_id = conn.getID();
String path = ""; //$NON-NLS-1$
try
{
File file = new File("simple-jndi"); //$NON-NLS-1$
path = file.getCanonicalPath();
}
catch (Exception e)
{
e.printStackTrace();
}
System.setProperty("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.osjava.sj.root", path); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.osjava.sj.delimiter", "/"); //$NON-NLS-1$ //$NON-NLS-2$
}
public String open()
{
Shell parent = getParent();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
connection.setChanged();
}
};
changed = connection.hasChanged();
middle = props.getMiddlePct();
margin = Const.MARGIN;
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setText(Messages.getString("DatabaseDialog.Shell.title")); //$NON-NLS-1$
shell.setLayout(formLayout);
// First, add the buttons...
// Buttons
wOK = new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK")); //$NON-NLS-1$
wTest = new Button(shell, SWT.PUSH);
wTest.setText(Messages.getString("DatabaseDialog.button.Test")); //$NON-NLS-1$
wExp = new Button(shell, SWT.PUSH);
wExp.setText(Messages.getString("DatabaseDialog.button.Explore")); //$NON-NLS-1$
wList = new Button(shell, SWT.PUSH);
wList.setText(Messages.getString("DatabaseDialog.button.FeatureList")); //$NON-NLS-1$
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel")); //$NON-NLS-1$
Button[] buttons = new Button[] { wOK, wTest, wExp, wList, wCancel };
BaseStepDialog.positionBottomButtons(shell, buttons, margin, null);
// The rest stays above the buttons...
wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
addGeneralTab();
addPoolTab();
addMySQLTab();
addOracleTab();
addInformixTab();
addSAPTab();
addGenericTab();
addOptionsTab();
addSQLTab();
addClusterTab();
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(0, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom = new FormAttachment(wOK, -margin);
wTabFolder.setLayoutData(fdTabFolder);
// Add listeners
wOK.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
ok();
}
});
wCancel.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
cancel();
}
});
wTest.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
test();
}
});
wExp.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
explore();
}
});
wList.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event e)
{
showFeatureList();
}
});
SelectionAdapter selAdapter = new SelectionAdapter()
{
public void widgetDefaultSelected(SelectionEvent e)
{
ok();
}
};
wHostName.addSelectionListener(selAdapter);
wDBName.addSelectionListener(selAdapter);
wPort.addSelectionListener(selAdapter);
wUsername.addSelectionListener(selAdapter);
wPassword.addSelectionListener(selAdapter);
wConn.addSelectionListener(selAdapter);
wData.addSelectionListener(selAdapter);
wIndex.addSelectionListener(selAdapter);
// OK, if the password contains a variable, we don't want to have the password hidden...
wPassword.addModifyListener(new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
checkPasswordVisible(wPassword.getTextWidget());
}
});
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener(new ShellAdapter()
{
public void shellClosed(ShellEvent e)
{
cancel();
}
});
wTabFolder.setSelection(0);
getData();
enableFields();
SelectionAdapter lsTypeAcc = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
enableFields();
setPortNumber();
}
};
wConnType.addSelectionListener(lsTypeAcc);
wConnAcc.addSelectionListener(lsTypeAcc);
BaseStepDialog.setSize(shell);
connection.setChanged(changed);
shell.open();
Display display = parent.getDisplay();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return connectionName;
}
public static final void checkPasswordVisible(Text wPassword)
{
String password = wPassword.getText();
java.util.List list = new ArrayList();
StringUtil.getUsedVariables(password, list, true);
// ONLY show the variable in clear text if there is ONE variable used
// Also, it has to be the only string in the field.
//
if (list.size() != 1)
{
wPassword.setEchoChar('*');
}
else
{
if ((password.startsWith(StringUtil.UNIX_OPEN) && password.endsWith(StringUtil.UNIX_CLOSE))
|| (password.startsWith(StringUtil.WINDOWS_OPEN) && password.endsWith(StringUtil.WINDOWS_CLOSE)))
{
wPassword.setEchoChar('\0'); // Show it all...
}
else
{
wPassword.setEchoChar('*');
}
}
}
private void addGeneralTab()
{
// ////////////////////////
// START OF DB TAB ///
// ////////////////////////
wDbTab = new CTabItem(wTabFolder, SWT.NONE);
wDbTab.setText(Messages.getString("DatabaseDialog.DbTab.title")); //$NON-NLS-1$
wDbComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wDbComp);
FormLayout GenLayout = new FormLayout();
GenLayout.marginWidth = Const.FORM_MARGIN;
GenLayout.marginHeight = Const.FORM_MARGIN;
wDbComp.setLayout(GenLayout);
// What's the connection name?
wlConn = new Label(wDbComp, SWT.RIGHT);
props.setLook(wlConn);
wlConn.setText(Messages.getString("DatabaseDialog.label.ConnectionName")); //$NON-NLS-1$
FormData fdlConn = new FormData();
fdlConn.top = new FormAttachment(0, 0);
fdlConn.left = new FormAttachment(0, 0); // First one in the left top corner
fdlConn.right = new FormAttachment(middle, -margin);
wlConn.setLayoutData(fdlConn);
wConn = new Text(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wConn);
wConn.addModifyListener(lsMod);
FormData fdConn = new FormData();
fdConn.top = new FormAttachment(0, 0);
fdConn.left = new FormAttachment(middle, 0); // To the right of the label
fdConn.right = new FormAttachment(95, 0);
wConn.setLayoutData(fdConn);
// What types are there?
wlConnType = new Label(wDbComp, SWT.RIGHT);
wlConnType.setText(Messages.getString("DatabaseDialog.label.ConnectionType")); //$NON-NLS-1$
props.setLook(wlConnType);
FormData fdlConnType = new FormData();
fdlConnType.top = new FormAttachment(wConn, margin); // below the line above
fdlConnType.left = new FormAttachment(0, 0);
fdlConnType.right = new FormAttachment(middle, -margin);
wlConnType.setLayoutData(fdlConnType);
wConnType = new List(wDbComp, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE | SWT.V_SCROLL);
props.setLook(wConnType);
String[] dbtypes = DatabaseMeta.getDBTypeDescLongList();
for (int i = 0; i < dbtypes.length; i++)
{
wConnType.add(dbtypes[i]);
}
props.setLook(wConnType);
FormData fdConnType = new FormData();
fdConnType.top = new FormAttachment(wConn, margin);
fdConnType.left = new FormAttachment(middle, 0); // right of the label
fdConnType.right = new FormAttachment(95, 0);
fdConnType.bottom = new FormAttachment(wConn, 150);
wConnType.setLayoutData(fdConnType);
// What access types are there?
wlConnAcc = new Label(wDbComp, SWT.RIGHT);
wlConnAcc.setText(Messages.getString("DatabaseDialog.label.AccessMethod")); //$NON-NLS-1$
props.setLook(wlConnAcc);
FormData fdlConnAcc = new FormData();
fdlConnAcc.top = new FormAttachment(wConnType, margin); // below the line above
fdlConnAcc.left = new FormAttachment(0, 0);
fdlConnAcc.right = new FormAttachment(middle, -margin);
wlConnAcc.setLayoutData(fdlConnAcc);
wConnAcc = new List(wDbComp, SWT.BORDER | SWT.READ_ONLY | SWT.SINGLE | SWT.V_SCROLL);
props.setLook(wConnAcc);
props.setLook(wConnAcc);
FormData fdConnAcc = new FormData();
fdConnAcc.top = new FormAttachment(wConnType, margin);
fdConnAcc.left = new FormAttachment(middle, 0); // right of the label
fdConnAcc.right = new FormAttachment(95, 0);
// fdConnAcc.bottom = new FormAttachment(wConnType, 50);
wConnAcc.setLayoutData(fdConnAcc);
// Hostname
wlHostName = new Label(wDbComp, SWT.RIGHT);
wlHostName.setText(Messages.getString("DatabaseDialog.label.ServerHostname")); //$NON-NLS-1$
props.setLook(wlHostName);
FormData fdlHostName = new FormData();
fdlHostName.top = new FormAttachment(wConnAcc, margin);
fdlHostName.left = new FormAttachment(0, 0);
fdlHostName.right = new FormAttachment(middle, -margin);
wlHostName.setLayoutData(fdlHostName);
wHostName = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wHostName);
wHostName.addModifyListener(lsMod);
FormData fdHostName = new FormData();
fdHostName.top = new FormAttachment(wConnAcc, margin);
fdHostName.left = new FormAttachment(middle, 0);
fdHostName.right = new FormAttachment(95, 0);
wHostName.setLayoutData(fdHostName);
// DBName
wlDBName = new Label(wDbComp, SWT.RIGHT);
wlDBName.setText(Messages.getString("DatabaseDialog.label.DatabaseName")); //$NON-NLS-1$
props.setLook(wlDBName);
FormData fdlDBName = new FormData();
fdlDBName.top = new FormAttachment(wHostName, margin);
fdlDBName.left = new FormAttachment(0, 0);
fdlDBName.right = new FormAttachment(middle, -margin);
wlDBName.setLayoutData(fdlDBName);
wDBName = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDBName);
wDBName.addModifyListener(lsMod);
FormData fdDBName = new FormData();
fdDBName.top = new FormAttachment(wHostName, margin);
fdDBName.left = new FormAttachment(middle, 0);
fdDBName.right = new FormAttachment(95, 0);
wDBName.setLayoutData(fdDBName);
// Port
wlPort = new Label(wDbComp, SWT.RIGHT);
wlPort.setText(Messages.getString("DatabaseDialog.label.PortNumber")); //$NON-NLS-1$
props.setLook(wlPort);
FormData fdlPort = new FormData();
fdlPort.top = new FormAttachment(wDBName, margin);
fdlPort.left = new FormAttachment(0, 0);
fdlPort.right = new FormAttachment(middle, -margin);
wlPort.setLayoutData(fdlPort);
wPort = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wPort);
wPort.addModifyListener(lsMod);
FormData fdPort = new FormData();
fdPort.top = new FormAttachment(wDBName, margin);
fdPort.left = new FormAttachment(middle, 0);
fdPort.right = new FormAttachment(95, 0);
wPort.setLayoutData(fdPort);
// Username
wlUsername = new Label(wDbComp, SWT.RIGHT);
wlUsername.setText(Messages.getString("DatabaseDialog.label.Username")); //$NON-NLS-1$
props.setLook(wlUsername);
FormData fdlUsername = new FormData();
fdlUsername.top = new FormAttachment(wPort, margin);
fdlUsername.left = new FormAttachment(0, 0);
fdlUsername.right = new FormAttachment(middle, -margin);
wlUsername.setLayoutData(fdlUsername);
wUsername = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wUsername);
wUsername.addModifyListener(lsMod);
FormData fdUsername = new FormData();
fdUsername.top = new FormAttachment(wPort, margin);
fdUsername.left = new FormAttachment(middle, 0);
fdUsername.right = new FormAttachment(95, 0);
wUsername.setLayoutData(fdUsername);
// Password
wlPassword = new Label(wDbComp, SWT.RIGHT);
wlPassword.setText(Messages.getString("DatabaseDialog.label.Password")); //$NON-NLS-1$
props.setLook(wlPassword);
FormData fdlPassword = new FormData();
fdlPassword.top = new FormAttachment(wUsername, margin);
fdlPassword.left = new FormAttachment(0, 0);
fdlPassword.right = new FormAttachment(middle, -margin);
wlPassword.setLayoutData(fdlPassword);
wPassword = new TextVar(wDbComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wPassword);
wPassword.setEchoChar('*');
wPassword.addModifyListener(lsMod);
FormData fdPassword = new FormData();
fdPassword.top = new FormAttachment(wUsername, margin);
fdPassword.left = new FormAttachment(middle, 0);
fdPassword.right = new FormAttachment(95, 0);
wPassword.setLayoutData(fdPassword);
FormData fdDbComp = new FormData();
fdDbComp.left = new FormAttachment(0, 0);
fdDbComp.top = new FormAttachment(0, 0);
fdDbComp.right = new FormAttachment(100, 0);
fdDbComp.bottom = new FormAttachment(100, 0);
wDbComp.setLayoutData(fdDbComp);
wDbComp.layout();
wDbTab.setControl(wDbComp);
// ///////////////////////////////////////////////////////////
// / END OF GEN TAB
// ///////////////////////////////////////////////////////////
}
private void addPoolTab()
{
// ////////////////////////
// START OF POOL TAB///
// /
wPoolTab = new CTabItem(wTabFolder, SWT.NONE);
wPoolTab.setText(Messages.getString("DatabaseDialog.PoolTab.title")); //$NON-NLS-1$
FormLayout poolLayout = new FormLayout();
poolLayout.marginWidth = Const.FORM_MARGIN;
poolLayout.marginHeight = Const.FORM_MARGIN;
wPoolComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wPoolComp);
wPoolComp.setLayout(poolLayout);
// What's the data tablespace name?
wlUsePool = new Label(wPoolComp, SWT.RIGHT);
props.setLook(wlUsePool);
wlUsePool.setText(Messages.getString("DatabaseDialog.label.UseConnectionPool")); //$NON-NLS-1$
FormData fdlUsePool = new FormData();
fdlUsePool.top = new FormAttachment(0, 0);
fdlUsePool.left = new FormAttachment(0, 0); // First one in the left top corner
fdlUsePool.right = new FormAttachment(middle, -margin);
wlUsePool.setLayoutData(fdlUsePool);
wUsePool = new Button(wPoolComp, SWT.CHECK);
wUsePool.setSelection(connection.isUsingConnectionPool());
props.setLook(wUsePool);
wUsePool.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent event)
{
connection.setChanged();
enableFields();
}
});
FormData fdUsePool = new FormData();
fdUsePool.top = new FormAttachment(0, 0);
fdUsePool.left = new FormAttachment(middle, 0); // To the right of the label
wUsePool.setLayoutData(fdUsePool);
// What's the initial pool size
wlInitPool = new Label(wPoolComp, SWT.RIGHT);
props.setLook(wlInitPool);
wlInitPool.setText(Messages.getString("DatabaseDialog.label.InitialPoolSize")); //$NON-NLS-1$
FormData fdlInitPool = new FormData();
fdlInitPool.top = new FormAttachment(wUsePool, margin);
fdlInitPool.left = new FormAttachment(0, 0); // First one in the left top corner
fdlInitPool.right = new FormAttachment(middle, -margin);
wlInitPool.setLayoutData(fdlInitPool);
wInitPool = new TextVar(wPoolComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wInitPool.setText(Integer.toString(connection.getInitialPoolSize()));
props.setLook(wInitPool);
wInitPool.addModifyListener(lsMod);
FormData fdInitPool = new FormData();
fdInitPool.top = new FormAttachment(wUsePool, margin);
fdInitPool.left = new FormAttachment(middle, 0); // To the right of the label
fdInitPool.right = new FormAttachment(95, 0);
wInitPool.setLayoutData(fdInitPool);
// What's the maximum pool size
wlMaxPool = new Label(wPoolComp, SWT.RIGHT);
props.setLook(wlMaxPool);
wlMaxPool.setText(Messages.getString("DatabaseDialog.label.MaximumPoolSize")); //$NON-NLS-1$
FormData fdlMaxPool = new FormData();
fdlMaxPool.top = new FormAttachment(wInitPool, margin);
fdlMaxPool.left = new FormAttachment(0, 0); // First one in the left top corner
fdlMaxPool.right = new FormAttachment(middle, -margin);
wlMaxPool.setLayoutData(fdlMaxPool);
wMaxPool = new TextVar(wPoolComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wMaxPool.setText(Integer.toString(connection.getMaximumPoolSize()));
props.setLook(wMaxPool);
wMaxPool.addModifyListener(lsMod);
FormData fdMaxPool = new FormData();
fdMaxPool.top = new FormAttachment(wInitPool, margin);
fdMaxPool.left = new FormAttachment(middle, 0); // To the right of the label
fdMaxPool.right = new FormAttachment(95, 0);
wMaxPool.setLayoutData(fdMaxPool);
// What's the maximum pool size
wlPoolParameters = new Label(wPoolComp, SWT.RIGHT);
props.setLook(wlPoolParameters);
wlPoolParameters.setText(Messages.getString("DatabaseDialog.label.PoolParameters")); //$NON-NLS-1$
FormData fdlPoolParameters = new FormData();
fdlPoolParameters.top = new FormAttachment(wInitPool, margin);
fdlPoolParameters.left = new FormAttachment(0, 0); // First one in the left top corner
fdlPoolParameters.right = new FormAttachment(middle, -margin);
wlPoolParameters.setLayoutData(fdlPoolParameters);
// options list
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(Messages.getString("DatabaseDialog.column.PoolParameter"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.PoolDefault"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.PoolValue"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
colinfo[2].setUsingVariables(true);
final ArrayList parameters = DatabaseConnectionPoolParameter.getRowList(BaseDatabaseMeta.poolingParameters, Messages
.getString("DatabaseDialog.column.PoolParameter"), Messages.getString("DatabaseDialog.column.PoolDefault"), Messages
.getString("DatabaseDialog.column.PoolDescription"));
colinfo[0].setSelectionAdapter(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
SelectRowDialog dialog = new SelectRowDialog(shell, SWT.NONE, Messages.getString("DatabaseDialog.column.SelectPoolParameter"),
parameters);
Row row = dialog.open();
if (row != null)
{
// the parameter is the first value
String parameterName = row.getValue(0).getString();
String defaultValue = DatabaseConnectionPoolParameter.findParameter(parameterName, BaseDatabaseMeta.poolingParameters)
.getDefaultValue();
wPoolParameters.setText(Const.NVL(parameterName, ""), e.x, e.y);
wPoolParameters.setText(Const.NVL(defaultValue, ""), e.x + 1, e.y);
}
}
});
wPoolParameters = new TableView(wPoolComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props);
props.setLook(wPoolParameters);
FormData fdOptions = new FormData();
fdOptions.left = new FormAttachment(0, 0);
fdOptions.right = new FormAttachment(100, 0);
fdOptions.top = new FormAttachment(wMaxPool, margin * 2);
fdOptions.bottom = new FormAttachment(100, -20);
wPoolParameters.setLayoutData(fdOptions);
FormData fdPoolComp = new FormData();
fdPoolComp.left = new FormAttachment(0, 0);
fdPoolComp.top = new FormAttachment(0, 0);
fdPoolComp.right = new FormAttachment(100, 0);
fdPoolComp.bottom = new FormAttachment(100, 0);
wPoolComp.setLayoutData(fdPoolComp);
wPoolComp.layout();
wPoolTab.setControl(wPoolComp);
}
private void addOracleTab()
{
// ////////////////////////
// START OF ORACLE TAB///
// /
wOracleTab = new CTabItem(wTabFolder, SWT.NONE);
wOracleTab.setText(Messages.getString("DatabaseDialog.OracleTab.title")); //$NON-NLS-1$
FormLayout oracleLayout = new FormLayout();
oracleLayout.marginWidth = Const.FORM_MARGIN;
oracleLayout.marginHeight = Const.FORM_MARGIN;
wOracleComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wOracleComp);
wOracleComp.setLayout(oracleLayout);
// What's the data tablespace name?
wlData = new Label(wOracleComp, SWT.RIGHT);
props.setLook(wlData);
wlData.setText(Messages.getString("DatabaseDialog.label.TablespaceForData")); //$NON-NLS-1$
FormData fdlData = new FormData();
fdlData.top = new FormAttachment(0, 0);
fdlData.left = new FormAttachment(0, 0); // First one in the left top corner
fdlData.right = new FormAttachment(middle, -margin);
wlData.setLayoutData(fdlData);
wData = new TextVar(wOracleComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wData.setText(NVL(connection.getDataTablespace() == null ? "" : connection.getDataTablespace(), "")); //$NON-NLS-1$ //$NON-NLS-2$
props.setLook(wData);
wData.addModifyListener(lsMod);
FormData fdData = new FormData();
fdData.top = new FormAttachment(0, 0);
fdData.left = new FormAttachment(middle, 0); // To the right of the label
fdData.right = new FormAttachment(95, 0);
wData.setLayoutData(fdData);
// What's the index tablespace name?
wlIndex = new Label(wOracleComp, SWT.RIGHT);
props.setLook(wlIndex);
wlIndex.setText(Messages.getString("DatabaseDialog.label.TablespaceForIndexes")); //$NON-NLS-1$
FormData fdlIndex = new FormData();
fdlIndex.top = new FormAttachment(wData, margin);
fdlIndex.left = new FormAttachment(0, 0); // First one in the left top corner
fdlIndex.right = new FormAttachment(middle, -margin);
wlIndex.setLayoutData(fdlIndex);
wIndex = new TextVar(wOracleComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wIndex.setText(NVL(connection.getIndexTablespace() == null ? "" : connection.getIndexTablespace(), "")); //$NON-NLS-1$ //$NON-NLS-2$
props.setLook(wIndex);
wIndex.addModifyListener(lsMod);
FormData fdIndex = new FormData();
fdIndex.top = new FormAttachment(wData, margin);
fdIndex.left = new FormAttachment(middle, 0); // To the right of the label
fdIndex.right = new FormAttachment(95, 0);
wIndex.setLayoutData(fdIndex);
FormData fdOracleComp = new FormData();
fdOracleComp.left = new FormAttachment(0, 0);
fdOracleComp.top = new FormAttachment(0, 0);
fdOracleComp.right = new FormAttachment(100, 0);
fdOracleComp.bottom = new FormAttachment(100, 0);
wOracleComp.setLayoutData(fdOracleComp);
wOracleComp.layout();
wOracleTab.setControl(wOracleComp);
}
private void addInformixTab()
{
// ////////////////////////
// START OF INFORMIX TAB///
// /
wIfxTab = new CTabItem(wTabFolder, SWT.NONE);
wIfxTab.setText(Messages.getString("DatabaseDialog.IfxTab.title")); //$NON-NLS-1$
FormLayout ifxLayout = new FormLayout();
ifxLayout.marginWidth = Const.FORM_MARGIN;
ifxLayout.marginHeight = Const.FORM_MARGIN;
wIfxComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wIfxComp);
wIfxComp.setLayout(ifxLayout);
// Servername
wlServername = new Label(wIfxComp, SWT.RIGHT);
wlServername.setText(Messages.getString("DatabaseDialog.label.InformixServername")); //$NON-NLS-1$
props.setLook(wlServername);
FormData fdlServername = new FormData();
fdlServername.top = new FormAttachment(0, margin);
fdlServername.left = new FormAttachment(0, 0);
fdlServername.right = new FormAttachment(middle, -margin);
wlServername.setLayoutData(fdlServername);
wServername = new Text(wIfxComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wServername);
wServername.addModifyListener(lsMod);
FormData fdServername = new FormData();
fdServername.top = new FormAttachment(0, margin);
fdServername.left = new FormAttachment(middle, 0);
fdServername.right = new FormAttachment(95, 0);
wServername.setLayoutData(fdServername);
FormData fdIfxComp = new FormData();
fdIfxComp.left = new FormAttachment(0, 0);
fdIfxComp.top = new FormAttachment(0, 0);
fdIfxComp.right = new FormAttachment(100, 0);
fdIfxComp.bottom = new FormAttachment(100, 0);
wIfxComp.setLayoutData(fdIfxComp);
wIfxComp.layout();
wIfxTab.setControl(wIfxComp);
}
private void addMySQLTab()
{
// ////////////////////////
// START OF MySQL TAB///
// /
wMySQLTab = new CTabItem(wTabFolder, SWT.NONE);
wMySQLTab.setText(Messages.getString("DatabaseDialog.MySQLTab.title")); //$NON-NLS-1$
FormLayout MySQLLayout = new FormLayout();
MySQLLayout.marginWidth = Const.FORM_MARGIN;
MySQLLayout.marginHeight = Const.FORM_MARGIN;
wMySQLComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wMySQLComp);
wMySQLComp.setLayout(MySQLLayout);
// Servername
wlServername = new Label(wMySQLComp, SWT.RIGHT);
wlServername.setText(Messages.getString("DatabaseDialog.label.MySQLStreamResults")); //$NON-NLS-1$
props.setLook(wlStreamResult);
FormData fdlStreamResult = new FormData();
fdlStreamResult.top = new FormAttachment(0, margin);
fdlStreamResult.left = new FormAttachment(0, 0);
fdlStreamResult.right = new FormAttachment(middle, -margin);
wlStreamResult.setLayoutData(fdlStreamResult);
wStreamResult = new Button(wMySQLComp, SWT.CHECK);
props.setLook(wStreamResult);
FormData fdStreamResult = new FormData();
fdStreamResult.top = new FormAttachment(0, margin);
fdStreamResult.left = new FormAttachment(middle, 0);
fdStreamResult.right = new FormAttachment(95, 0);
wStreamResult.setLayoutData(fdStreamResult);
FormData fdMySQLComp = new FormData();
fdMySQLComp.left = new FormAttachment(0, 0);
fdMySQLComp.top = new FormAttachment(0, 0);
fdMySQLComp.right = new FormAttachment(100, 0);
fdMySQLComp.bottom = new FormAttachment(100, 0);
wMySQLComp.setLayoutData(fdMySQLComp);
wMySQLComp.layout();
wMySQLTab.setControl(wMySQLComp);
}
private void addSAPTab()
{
// ////////////////////////
// START OF SAP TAB///
// /
wSAPTab = new CTabItem(wTabFolder, SWT.NONE);
wSAPTab.setText(Messages.getString("DatabaseDialog.label.Sap")); //$NON-NLS-1$
FormLayout sapLayout = new FormLayout();
sapLayout.marginWidth = Const.FORM_MARGIN;
sapLayout.marginHeight = Const.FORM_MARGIN;
wSAPComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wSAPComp);
wSAPComp.setLayout(sapLayout);
// wSAPLanguage, wSSAPystemNumber, wSAPSystemID
// Language
wlSAPLanguage = new Label(wSAPComp, SWT.RIGHT);
wlSAPLanguage.setText(Messages.getString("DatabaseDialog.label.Language")); //$NON-NLS-1$
props.setLook(wlSAPLanguage);
FormData fdlSAPLanguage = new FormData();
fdlSAPLanguage.top = new FormAttachment(0, margin);
fdlSAPLanguage.left = new FormAttachment(0, 0);
fdlSAPLanguage.right = new FormAttachment(middle, -margin);
wlSAPLanguage.setLayoutData(fdlSAPLanguage);
wSAPLanguage = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSAPLanguage);
wSAPLanguage.addModifyListener(lsMod);
FormData fdSAPLanguage = new FormData();
fdSAPLanguage.top = new FormAttachment(0, margin);
fdSAPLanguage.left = new FormAttachment(middle, 0);
fdSAPLanguage.right = new FormAttachment(95, 0);
wSAPLanguage.setLayoutData(fdSAPLanguage);
// SystemNumber
wlSAPSystemNumber = new Label(wSAPComp, SWT.RIGHT);
wlSAPSystemNumber.setText(Messages.getString("DatabaseDialog.label.SystemNumber")); //$NON-NLS-1$
props.setLook(wlSAPSystemNumber);
FormData fdlSAPSystemNumber = new FormData();
fdlSAPSystemNumber.top = new FormAttachment(wSAPLanguage, margin);
fdlSAPSystemNumber.left = new FormAttachment(0, 0);
fdlSAPSystemNumber.right = new FormAttachment(middle, -margin);
wlSAPSystemNumber.setLayoutData(fdlSAPSystemNumber);
wSAPSystemNumber = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSAPSystemNumber);
wSAPSystemNumber.addModifyListener(lsMod);
FormData fdSAPSystemNumber = new FormData();
fdSAPSystemNumber.top = new FormAttachment(wSAPLanguage, margin);
fdSAPSystemNumber.left = new FormAttachment(middle, 0);
fdSAPSystemNumber.right = new FormAttachment(95, 0);
wSAPSystemNumber.setLayoutData(fdSAPSystemNumber);
// SystemID
wlSAPClient = new Label(wSAPComp, SWT.RIGHT);
wlSAPClient.setText(Messages.getString("DatabaseDialog.label.SapClient")); //$NON-NLS-1$
props.setLook(wlSAPClient);
FormData fdlSAPClient = new FormData();
fdlSAPClient.top = new FormAttachment(wSAPSystemNumber, margin);
fdlSAPClient.left = new FormAttachment(0, 0);
fdlSAPClient.right = new FormAttachment(middle, -margin);
wlSAPClient.setLayoutData(fdlSAPClient);
wSAPClient = new Text(wSAPComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSAPClient);
wSAPClient.addModifyListener(lsMod);
FormData fdSAPClient = new FormData();
fdSAPClient.top = new FormAttachment(wSAPSystemNumber, margin);
fdSAPClient.left = new FormAttachment(middle, 0);
fdSAPClient.right = new FormAttachment(95, 0);
wSAPClient.setLayoutData(fdSAPClient);
FormData fdSAPComp = new FormData();
fdSAPComp.left = new FormAttachment(0, 0);
fdSAPComp.top = new FormAttachment(0, 0);
fdSAPComp.right = new FormAttachment(100, 0);
fdSAPComp.bottom = new FormAttachment(100, 0);
wSAPComp.setLayoutData(fdSAPComp);
wSAPComp.layout();
wSAPTab.setControl(wSAPComp);
}
private void addGenericTab()
{
// ////////////////////////
// START OF DB TAB///
// /
wGenericTab = new CTabItem(wTabFolder, SWT.NONE);
wGenericTab.setText(Messages.getString("DatabaseDialog.GenericTab.title")); //$NON-NLS-1$
wGenericTab.setToolTipText(Messages.getString("DatabaseDialog.GenericTab.tooltip")); //$NON-NLS-1$
FormLayout genericLayout = new FormLayout();
genericLayout.marginWidth = Const.FORM_MARGIN;
genericLayout.marginHeight = Const.FORM_MARGIN;
wGenericComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wGenericComp);
wGenericComp.setLayout(genericLayout);
// URL
wlURL = new Label(wGenericComp, SWT.RIGHT);
wlURL.setText(Messages.getString("DatabaseDialog.label.Url")); //$NON-NLS-1$
props.setLook(wlURL);
FormData fdlURL = new FormData();
fdlURL.top = new FormAttachment(0, margin);
fdlURL.left = new FormAttachment(0, 0);
fdlURL.right = new FormAttachment(middle, -margin);
wlURL.setLayoutData(fdlURL);
wURL = new Text(wGenericComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wURL);
wURL.addModifyListener(lsMod);
FormData fdURL = new FormData();
fdURL.top = new FormAttachment(0, margin);
fdURL.left = new FormAttachment(middle, 0);
fdURL.right = new FormAttachment(95, 0);
wURL.setLayoutData(fdURL);
// Driver class
wlDriverClass = new Label(wGenericComp, SWT.RIGHT);
wlDriverClass.setText(Messages.getString("DatabaseDialog.label.DriverClass")); //$NON-NLS-1$
props.setLook(wlDriverClass);
FormData fdlDriverClass = new FormData();
fdlDriverClass.top = new FormAttachment(wURL, margin);
fdlDriverClass.left = new FormAttachment(0, 0);
fdlDriverClass.right = new FormAttachment(middle, -margin);
wlDriverClass.setLayoutData(fdlDriverClass);
wDriverClass = new Text(wGenericComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wDriverClass);
wDriverClass.addModifyListener(lsMod);
FormData fdDriverClass = new FormData();
fdDriverClass.top = new FormAttachment(wURL, margin);
fdDriverClass.left = new FormAttachment(middle, 0);
fdDriverClass.right = new FormAttachment(95, 0);
wDriverClass.setLayoutData(fdDriverClass);
FormData fdGenericComp = new FormData();
fdGenericComp.left = new FormAttachment(0, 0);
fdGenericComp.top = new FormAttachment(0, 0);
fdGenericComp.right = new FormAttachment(100, 0);
fdGenericComp.bottom = new FormAttachment(100, 0);
wGenericComp.setLayoutData(fdGenericComp);
wGenericComp.layout();
wGenericTab.setControl(wGenericComp);
}
private void addOptionsTab()
{
// ////////////////////////
// START OF OPTIONS TAB///
// /
wOptionsTab = new CTabItem(wTabFolder, SWT.NONE);
wOptionsTab.setText(Messages.getString("DatabaseDialog.label.Options")); //$NON-NLS-1$
wOptionsTab.setToolTipText(Messages.getString("DatabaseDialog.tooltip.Options")); //$NON-NLS-1$
FormLayout optionsLayout = new FormLayout();
optionsLayout.marginWidth = margin;
optionsLayout.marginHeight = margin;
wOptionsComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wOptionsComp);
wOptionsComp.setLayout(optionsLayout);
wOptionsHelp = new Button(wOptionsComp, SWT.PUSH);
wOptionsHelp.setText(Messages.getString("DatabaseDialog.button.ShowHelp")); //$NON-NLS-1$
wOptionsHelp.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
showOptionsHelpText();
}
});
BaseStepDialog.positionBottomButtons(wOptionsComp, new Button[] { wOptionsHelp }, margin, null);
// options list
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(
Messages.getString("DatabaseDialog.column.DbType"), ColumnInfo.COLUMN_TYPE_CCOMBO, DatabaseMeta.getDBTypeDescLongList(), true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Parameter"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Value"), ColumnInfo.COLUMN_TYPE_TEXT, false), //$NON-NLS-1$
};
colinfo[0].setToolTip(Messages.getString("DatabaseDialog.tooltip.DbType")); //$NON-NLS-1$
colinfo[1].setToolTip(Messages.getString("DatabaseDialog.tooltip.Parameter")); //$NON-NLS-1$
colinfo[2].setUsingVariables(true);
wOptions = new TableView(wOptionsComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props);
props.setLook(wOptions);
FormData fdOptions = new FormData();
fdOptions.left = new FormAttachment(0, 0);
fdOptions.right = new FormAttachment(100, 0);
fdOptions.top = new FormAttachment(0, 0);
fdOptions.bottom = new FormAttachment(wOptionsHelp, -margin);
wOptions.setLayoutData(fdOptions);
FormData fdOptionsComp = new FormData();
fdOptionsComp.left = new FormAttachment(0, 0);
fdOptionsComp.top = new FormAttachment(0, 0);
fdOptionsComp.right = new FormAttachment(100, 0);
fdOptionsComp.bottom = new FormAttachment(100, 0);
wOptionsComp.setLayoutData(fdOptionsComp);
wOptionsComp.layout();
wOptionsTab.setControl(wOptionsComp);
}
private void addSQLTab()
{
// ////////////////////////
// START OF SQL TAB///
// /
wSQLTab = new CTabItem(wTabFolder, SWT.NONE);
wSQLTab.setText(Messages.getString("DatabaseDialog.SQLTab.title")); //$NON-NLS-1$
wSQLTab.setToolTipText(Messages.getString("DatabaseDialog.SQLTab.tooltip")); //$NON-NLS-1$
FormLayout sqlLayout = new FormLayout();
sqlLayout.marginWidth = margin;
sqlLayout.marginHeight = margin;
wSQLComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wSQLComp);
wSQLComp.setLayout(sqlLayout);
wlSQL = new Label(wSQLComp, SWT.LEFT);
props.setLook(wlSQL);
wlSQL.setText(Messages.getString("DatabaseDialog.label.Statements")); //$NON-NLS-1$
FormData fdlSQL = new FormData();
fdlSQL.left = new FormAttachment(0, 0);
fdlSQL.top = new FormAttachment(0, 0);
wlSQL.setLayoutData(fdlSQL);
wSQL = new Text(wSQLComp, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.BORDER);
props.setLook(wSQL, Props.WIDGET_STYLE_FIXED);
FormData fdSQL = new FormData();
fdSQL.left = new FormAttachment(0, 0);
fdSQL.right = new FormAttachment(100, 0);
fdSQL.top = new FormAttachment(wlSQL, margin);
fdSQL.bottom = new FormAttachment(100, 0);
wSQL.setLayoutData(fdSQL);
FormData fdSQLComp = new FormData();
fdSQLComp.left = new FormAttachment(0, 0);
fdSQLComp.top = new FormAttachment(0, 0);
fdSQLComp.right = new FormAttachment(100, 0);
fdSQLComp.bottom = new FormAttachment(100, 0);
wSQLComp.setLayoutData(fdSQLComp);
wSQLComp.layout();
wSQLTab.setControl(wSQLComp);
}
private void addClusterTab()
{
// ////////////////////////
// START OF CLUSTER TAB///
// /
// The tab
wClusterTab = new CTabItem(wTabFolder, SWT.NONE);
wClusterTab.setText(Messages.getString("DatabaseDialog.ClusterTab.title")); //$NON-NLS-1$
wClusterTab.setToolTipText(Messages.getString("DatabaseDialog.ClusterTab.tooltip")); //$NON-NLS-1$
FormLayout clusterLayout = new FormLayout();
clusterLayout.marginWidth = margin;
clusterLayout.marginHeight = margin;
// The composite
wClusterComp = new Composite(wTabFolder, SWT.NONE);
props.setLook(wClusterComp);
wClusterComp.setLayout(clusterLayout);
// The check box
wlUseCluster = new Label(wClusterComp, SWT.RIGHT);
props.setLook(wlUseCluster);
wlUseCluster.setText(Messages.getString("DatabaseDialog.label.UseClustering")); //$NON-NLS-1$
wlUseCluster.setToolTipText(Messages.getString("DatabaseDialog.tooltip.UseClustering")); //$NON-NLS-1$
FormData fdlUseCluster = new FormData();
fdlUseCluster.left = new FormAttachment(0, 0);
fdlUseCluster.right = new FormAttachment(middle, 0);
fdlUseCluster.top = new FormAttachment(0, 0);
wlUseCluster.setLayoutData(fdlUseCluster);
wUseCluster = new Button(wClusterComp, SWT.CHECK);
props.setLook(wUseCluster);
FormData fdUseCluster = new FormData();
fdUseCluster.left = new FormAttachment(middle, margin);
fdUseCluster.right = new FormAttachment(100, 0);
fdUseCluster.top = new FormAttachment(0, 0);
wUseCluster.setLayoutData(fdUseCluster);
wUseCluster.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent arg0)
{
enableFields();
}
});
// Cluster list
ColumnInfo[] colinfo = new ColumnInfo[] {
new ColumnInfo(Messages.getString("DatabaseDialog.column.PartitionId"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Hostname"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Port"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.DatabaseName"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Username"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
new ColumnInfo(Messages.getString("DatabaseDialog.column.Password"), ColumnInfo.COLUMN_TYPE_TEXT, false, false), //$NON-NLS-1$
};
colinfo[0].setToolTip(Messages.getString("DatabaseDialog.tooltip.PartitionId")); //$NON-NLS-1$
colinfo[1].setToolTip(Messages.getString("DatabaseDialog.tooltip.Hostname")); //$NON-NLS-1$
colinfo[5].setPasswordField(true);
colinfo[5].setUsingVariables(true);
wCluster = new TableView(wClusterComp, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props);
props.setLook(wCluster);
FormData fdCluster = new FormData();
fdCluster.left = new FormAttachment(0, 0);
fdCluster.right = new FormAttachment(100, 0);
fdCluster.top = new FormAttachment(wUseCluster, margin);
fdCluster.bottom = new FormAttachment(100, 0);
wCluster.setLayoutData(fdCluster);
FormData fdClusterComp = new FormData();
fdClusterComp.left = new FormAttachment(0, 0);
fdClusterComp.top = new FormAttachment(0, 0);
fdClusterComp.right = new FormAttachment(100, 0);
fdClusterComp.bottom = new FormAttachment(100, 0);
wClusterComp.setLayoutData(fdClusterComp);
wClusterComp.layout();
wClusterTab.setControl(wClusterComp);
}
private void showOptionsHelpText()
{
DatabaseMeta meta = new DatabaseMeta();
try
{
getInfo(meta);
String helpText = meta.getExtraOptionsHelpText();
if (Const.isEmpty(helpText)) return;
// Try to open a new tab in the Spoon editor.
// If spoon is not available, not in the classpath or can't open the tab, we show the URL in a dialog
//
boolean openedTab = false;
try
{
Spoon spoon = Spoon.getInstance();
if (spoon != null)
{
openedTab = spoon.addSpoonBrowser(meta.getDatabaseTypeDesc() + " : JDBC Options help", helpText);
}
}
catch (Throwable t)
{
}
if (!openedTab)
{
EnterTextDialog dialog = new EnterTextDialog(shell,
Messages.getString("DatabaseDialog.HelpText.title"), Messages.getString("DatabaseDialog.HelpText.description", meta.getDatabaseTypeDesc()), helpText, true); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setReadOnly();
dialog.open();
}
}
catch (KettleException e)
{
new ErrorDialog(shell,
Messages.getString("DatabaseDialog.ErrorHelpText.title"), Messages.getString("DatabaseDialog.ErrorHelpText.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void dispose()
{
props.setScreen(new WindowProperty(shell));
shell.dispose();
}
public void setDatabases(ArrayList databases)
{
this.databases = databases;
}
public void getData()
{
wConn.setText(NVL(connection == null ? "" : connection.getName(), "")); //$NON-NLS-1$ //$NON-NLS-2$
wConnType.select(connection.getDatabaseType() - 1);
wConnType.showSelection();
previousDatabaseType = DatabaseMeta.getDatabaseTypeCode(wConnType.getSelectionIndex() + 1);
setAccessList();
String accessList[] = wConnAcc.getItems();
int accessIndex = Const.indexOfString(connection.getAccessTypeDesc(), accessList);
wConnAcc.select(accessIndex);
wConnAcc.showSelection();
wHostName.setText(NVL(connection.getHostname(), "")); //$NON-NLS-1$
wDBName.setText(NVL(connection.getDatabaseName(), "")); //$NON-NLS-1$
wPort.setText(NVL(connection.getDatabasePortNumberString(), "")); //$NON-NLS-1$
wServername.setText(NVL(connection.getServername(), "")); //$NON-NLS-1$
wUsername.setText(NVL(connection.getUsername(), "")); //$NON-NLS-1$
wPassword.setText(NVL(connection.getPassword(), "")); //$NON-NLS-1$
wData.setText(NVL(connection.getDataTablespace(), "")); //$NON-NLS-1$
wIndex.setText(NVL(connection.getIndexTablespace(), "")); //$NON-NLS-1$
wSAPLanguage.setText(connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_LANGUAGE, "")); //$NON-NLS-1$
wSAPSystemNumber.setText(connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_SYSTEM_NUMBER, "")); //$NON-NLS-1$
wSAPClient.setText(connection.getAttributes().getProperty(SAPR3DatabaseMeta.ATTRIBUTE_SAP_CLIENT, "")); //$NON-NLS-1$
wURL.setText(connection.getAttributes().getProperty(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL, "")); //$NON-NLS-1$
wDriverClass.setText(connection.getAttributes().getProperty(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS, "")); //$NON-NLS-1$
wStreamResult.setSelection( connection.isStreamingResults() );
getOptionsData();
checkPasswordVisible(wPassword.getTextWidget());
wSQL.setText(NVL(connection.getConnectSQL(), "")); //$NON-NLS-1$
getPoolingData();
wConn.setFocus();
wConn.selectAll();
getClusterData();
}
private void getClusterData()
{
// The clustering information
wUseCluster.setSelection(connection.isPartitioned());
PartitionDatabaseMeta[] clusterInformation = connection.getPartitioningInformation();
for (int i = 0; i < clusterInformation.length; i++)
{
PartitionDatabaseMeta meta = clusterInformation[i];
TableItem tableItem = new TableItem(wCluster.table, SWT.NONE);
tableItem.setText(1, Const.NVL(meta.getPartitionId(), "")); //$NON-NLS-1$
tableItem.setText(2, Const.NVL(meta.getHostname(), "")); //$NON-NLS-1$
tableItem.setText(3, Const.NVL(meta.getPort(), "")); //$NON-NLS-1$
tableItem.setText(4, Const.NVL(meta.getDatabaseName(), "")); //$NON-NLS-1$
tableItem.setText(5, Const.NVL(meta.getUsername(), "")); //$NON-NLS-1$
tableItem.setText(5, Const.NVL(meta.getPassword(), "")); //$NON-NLS-1$
}
wCluster.removeEmptyRows();
wCluster.setRowNums();
wCluster.optWidth(true);
}
private void getOptionsData()
{
// The extra options as well...
Iterator keys = extraOptions.keySet().iterator();
while (keys.hasNext())
{
String parameter = (String) keys.next();
String value = (String) extraOptions.get(parameter);
if (!Const.isEmpty(value) && value.equals(DatabaseMeta.EMPTY_OPTIONS_STRING)) value = ""; //$NON-NLS-1$
// If the paremeter starts with a database type code we add it...
//
// For example MySQL.defaultFetchSize
int dotIndex = parameter.indexOf("."); //$NON-NLS-1$
if (dotIndex >= 0 && wConnType.getSelectionCount() == 1)
{
String databaseTypeString = parameter.substring(0, dotIndex);
String parameterOption = parameter.substring(dotIndex + 1);
int databaseType = DatabaseMeta.getDatabaseType(databaseTypeString);
TableItem item = new TableItem(wOptions.table, SWT.NONE);
item.setText(1, DatabaseMeta.getDatabaseTypeDesc(databaseType));
item.setText(2, parameterOption);
if (value != null) item.setText(3, value);
}
}
wOptions.removeEmptyRows();
wOptions.setRowNums();
wOptions.optWidth(true);
}
private void getPoolingData()
{
// The extra options as well...
Properties properties = connection.getConnectionPoolingProperties();
Iterator keys = properties.keySet().iterator();
while (keys.hasNext())
{
String parameter = (String) keys.next();
String value = (String) properties.get(parameter);
String defValue = DatabaseConnectionPoolParameter.findParameter(parameter, BaseDatabaseMeta.poolingParameters).getDefaultValue();
TableItem item = new TableItem(wPoolParameters.table, SWT.NONE);
item.setText(1, Const.NVL(parameter, ""));
item.setText(2, Const.NVL(defValue, ""));
item.setText(3, Const.NVL(value, ""));
}
wPoolParameters.removeEmptyRows();
wPoolParameters.setRowNums();
wPoolParameters.optWidth(true);
}
public void enableFields()
{
// See if we need to refresh the access list...
String type = DatabaseMeta.getDatabaseTypeCode(wConnType.getSelectionIndex() + 1);
if (!type.equalsIgnoreCase(previousDatabaseType)) setAccessList();
previousDatabaseType = type;
int idxAccType = wConnAcc.getSelectionIndex();
int acctype = -1;
if (idxAccType >= 0)
{
acctype = DatabaseMeta.getAccessType(wConnAcc.getItem(idxAccType));
}
// Hide the fields not relevent to JNDI data sources
wlHostName.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wHostName.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlPort.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wPort.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlURL.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wURL.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlDriverClass.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wDriverClass.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlUsername.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wUsername.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wlPassword.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
wPassword.setEnabled(acctype != DatabaseMeta.TYPE_ACCESS_JNDI);
if (acctype == DatabaseMeta.TYPE_ACCESS_JNDI) { return; }
int idxDBType = wConnType.getSelectionIndex();
if (idxDBType >= 0)
{
int dbtype = DatabaseMeta.getDatabaseType(wConnType.getItem(idxDBType));
// If the type is not Informix: disable the servername field!
wlServername.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_INFORMIX);
wServername.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_INFORMIX);
// If this is an Oracle connection enable the Oracle tab
wlData.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_ORACLE);
wData.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_ORACLE);
wlIndex.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_ORACLE);
wIndex.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_ORACLE);
wlSAPLanguage.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wSAPLanguage.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wlSAPSystemNumber.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wSAPSystemNumber.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wlSAPClient.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wSAPClient.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_SAPR3);
wlDBName.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wDBName.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wlPort.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wPort.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wTest.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wExp.setEnabled(dbtype != DatabaseMeta.TYPE_DATABASE_SAPR3);
wlHostName.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE)
|| (dbtype == DatabaseMeta.TYPE_ACCESS_JNDI));
wHostName.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlDBName.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wDBName.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlPort.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wPort.setEnabled(!(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE));
wlURL.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wURL.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wlDriverClass.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
wDriverClass.setEnabled(dbtype == DatabaseMeta.TYPE_DATABASE_GENERIC && acctype == DatabaseMeta.TYPE_ACCESS_NATIVE);
}
// The connection pooling options: do those as well...
wlMaxPool.setEnabled(wUsePool.getSelection());
wMaxPool.setEnabled(wUsePool.getSelection());
wlInitPool.setEnabled(wUsePool.getSelection());
wInitPool.setEnabled(wUsePool.getSelection());
wlPoolParameters.setEnabled(wUsePool.getSelection());
wPoolParameters.setEnabled(wUsePool.getSelection());
wPoolParameters.table.setEnabled(wUsePool.getSelection());
// How about the clustering stuff?
wCluster.table.setEnabled(wUseCluster.getSelection());
}
public void setPortNumber()
{
String type = DatabaseMeta.getDatabaseTypeCode(wConnType.getSelectionIndex() + 1);
// What port should we select?
String acce = wConnAcc.getItem(wConnAcc.getSelectionIndex());
int port = DatabaseMeta.getPortForDBType(type, acce);
if (port < 0)
wPort.setText(""); //$NON-NLS-1$
else
wPort.setText("" + port); //$NON-NLS-1$
}
public void setAccessList()
{
if (wConnType.getSelectionCount() < 1) return;
int acc[] = DatabaseMeta.getAccessTypeList(wConnType.getSelection()[0]);
wConnAcc.removeAll();
for (int i = 0; i < acc.length; i++)
{
wConnAcc.add(DatabaseMeta.getAccessTypeDescLong(acc[i]));
}
// If nothing is selected: select the first item (mostly the native driver)
if (wConnAcc.getSelectionIndex() < 0)
{
wConnAcc.select(0);
}
}
private void cancel()
{
connectionName = null;
connection.setChanged(changed);
dispose();
}
public void getInfo(DatabaseMeta databaseMeta) throws KettleException
{
// Before we put all attributes back in, clear the old list to make sure...
// Warning: the port is an attribute too now.
//
databaseMeta.getAttributes().clear();
// Name:
databaseMeta.setName(wConn.getText());
// Connection type:
String contype[] = wConnType.getSelection();
if (contype.length > 0)
{
databaseMeta.setDatabaseType(contype[0]);
}
// Access type:
String acctype[] = wConnAcc.getSelection();
if (acctype.length > 0)
{
databaseMeta.setAccessType(DatabaseMeta.getAccessType(acctype[0]));
}
// Hostname
databaseMeta.setHostname(wHostName.getText());
// Database name
databaseMeta.setDBName(wDBName.getText());
// Port number
databaseMeta.setDBPort(wPort.getText());
// Username
databaseMeta.setUsername(wUsername.getText());
// Password
databaseMeta.setPassword(wPassword.getText());
// Servername
databaseMeta.setServername(wServername.getText());
// MySQL
databaseMeta.setStreamingResults(wStreamResult.getSelection());
// Data tablespace
databaseMeta.setDataTablespace(wData.getText());
// Index tablespace
databaseMeta.setIndexTablespace(wIndex.getText());
// SAP Attributes...
databaseMeta.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_LANGUAGE, wSAPLanguage.getText());
databaseMeta.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_SYSTEM_NUMBER, wSAPSystemNumber.getText());
databaseMeta.getAttributes().put(SAPR3DatabaseMeta.ATTRIBUTE_SAP_CLIENT, wSAPClient.getText());
// Generic settings...
databaseMeta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL, wURL.getText());
databaseMeta.getAttributes().put(GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS, wDriverClass.getText());
String[] remarks = databaseMeta.checkParameters();
if (remarks.length != 0)
{
String message = ""; //$NON-NLS-1$
for (int i = 0; i < remarks.length; i++)
message += " * " + remarks[i] + Const.CR; //$NON-NLS-1$
throw new KettleException(Messages.getString("DatabaseDialog.Exception.IncorrectParameter") + Const.CR + message); //$NON-NLS-1$
}
// Now put in the extra options...
for (int i = 0; i < wOptions.nrNonEmpty(); i++)
{
TableItem item = wOptions.getNonEmpty(i);
String dbTypeStr = item.getText(1);
String parameter = item.getText(2);
String value = item.getText(3);
int dbType = DatabaseMeta.getDatabaseType(dbTypeStr);
// Only if both parameters are supplied, we will add to the map...
if (!Const.isEmpty(parameter) && dbType != DatabaseMeta.TYPE_DATABASE_NONE)
{
if (Const.isEmpty(value)) value = DatabaseMeta.EMPTY_OPTIONS_STRING;
String typedParameter = BaseDatabaseMeta.ATTRIBUTE_PREFIX_EXTRA_OPTION + DatabaseMeta.getDatabaseTypeCode(dbType) + "." + parameter; //$NON-NLS-1$
databaseMeta.getAttributes().put(typedParameter, value);
}
}
// The SQL to execute...
databaseMeta.setConnectSQL(wSQL.getText());
// The connection pooling stuff...
databaseMeta.setUsingConnectionPool(wUsePool.getSelection());
databaseMeta.setInitialPoolSize(Const.toInt(wInitPool.getText(), ConnectionPoolUtil.defaultInitialNrOfConnections));
databaseMeta.setMaximumPoolSize(Const.toInt(wMaxPool.getText(), ConnectionPoolUtil.defaultMaximumNrOfConnections));
Properties poolProperties = new Properties();
for (int i = 0; i < wPoolParameters.nrNonEmpty(); i++)
{
TableItem item = wPoolParameters.getNonEmpty(i);
String parameterName = item.getText(1);
String value = item.getText(3);
if (!Const.isEmpty(parameterName) && !Const.isEmpty(value))
{
poolProperties.setProperty(parameterName, value);
}
}
databaseMeta.setConnectionPoolingProperties(poolProperties);
// Now grab the clustering information...
databaseMeta.setPartitioned(wUseCluster.getSelection());
PartitionDatabaseMeta[] clusterInfo = new PartitionDatabaseMeta[wCluster.nrNonEmpty()];
for (int i = 0; i < clusterInfo.length; i++)
{
TableItem tableItem = wCluster.getNonEmpty(i);
String partitionId = tableItem.getText(1);
String hostname = tableItem.getText(2);
String port = tableItem.getText(3);
String dbName = tableItem.getText(4);
String username = tableItem.getText(5);
String password = tableItem.getText(6);
clusterInfo[i] = new PartitionDatabaseMeta(partitionId, hostname, port, dbName);
clusterInfo[i].setUsername(username);
clusterInfo[i].setPassword(password);
}
databaseMeta.setPartitioningInformation(clusterInfo);
}
/**
* @deprecated use ok() in stead, like in most dialogs
*/
public void handleOK()
{
ok();
}
public void ok()
{
try
{
getInfo(connection);
connectionName = connection.getName();
connection.setID(database_id);
dispose();
}
catch (KettleException e)
{
new ErrorDialog(shell,
Messages.getString("DatabaseDialog.ErrorParameters.title"), Messages.getString("DatabaseDialog.ErrorParameters.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public String NVL(String str, String rep)
{
if (str == null) return rep;
return str;
}
public void test()
{
try
{
DatabaseMeta dbinfo = new DatabaseMeta();
getInfo(dbinfo);
test(shell, dbinfo, props);
}
catch (KettleException e)
{
new ErrorDialog(
shell,
Messages.getString("DatabaseDialog.ErrorParameters.title"), Messages.getString("DatabaseDialog.ErrorConnectionInfo.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Test the database connection
*/
public static final void test(Shell shell, DatabaseMeta dbinfo, Props props)
{
String[] remarks = dbinfo.checkParameters();
if (remarks.length == 0)
{
StringBuffer report = new StringBuffer();
Database db = new Database(dbinfo);
if (dbinfo.isPartitioned())
{
PartitionDatabaseMeta[] partitioningInformation = dbinfo.getPartitioningInformation();
for (int i = 0; i < partitioningInformation.length; i++)
{
try
{
db.connect(partitioningInformation[i].getPartitionId());
report
.append(Messages.getString(
"DatabaseDialog.report.ConnectionWithPartOk", dbinfo.getName(), partitioningInformation[i].getPartitionId()) + Const.CR); //$NON-NLS-1$
}
catch (KettleException e)
{
report
.append(Messages
.getString(
"DatabaseDialog.report.ConnectionWithPartError", dbinfo.getName(), partitioningInformation[i].getPartitionId(), e.toString()) + Const.CR); //$NON-NLS-1$
report.append(Const.getStackTracker(e) + Const.CR);
}
finally
{
db.disconnect();
}
report.append(Messages.getString("DatabaseDialog.report.Hostname") + partitioningInformation[i].getHostname() + Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseDialog.report.Port") + partitioningInformation[i].getPort() + Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseDialog.report.DatabaseName") + partitioningInformation[i].getDatabaseName() + Const.CR); //$NON-NLS-1$
report.append(Const.CR);
}
}
else
{
try
{
db.connect();
report.append(Messages.getString("DatabaseDialog.report.ConnectionOk", dbinfo.getName()) + Const.CR); //$NON-NLS-1$
}
catch (KettleException e)
{
report.append(Messages.getString("DatabaseDialog.report.ConnectionError", dbinfo.getName()) + e.toString() + Const.CR); //$NON-NLS-1$
report.append(Const.getStackTracker(e) + Const.CR);
}
finally
{
db.disconnect();
}
report.append(Messages.getString("DatabaseDialog.report.Hostname") + dbinfo.getHostname() + Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseDialog.report.Port") + dbinfo.getDatabasePortNumberString() + Const.CR); //$NON-NLS-1$
report.append(Messages.getString("DatabaseDialog.report.DatabaseName") + dbinfo.getDatabaseName() + Const.CR); //$NON-NLS-1$
report.append(Const.CR);
}
EnterTextDialog dialog = new EnterTextDialog(
shell,
Messages.getString("DatabaseDialog.ConnectionReport.title"), Messages.getString("DatabaseDialog.ConnectionReport.description"), report.toString()); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setReadOnly();
dialog.setFixed(true);
dialog.open();
}
else
{
String message = ""; //$NON-NLS-1$
for (int i = 0; i < remarks.length; i++)
message += " * " + remarks[i] + Const.CR; //$NON-NLS-1$
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
mb.setText(Messages.getString("DatabaseDialog.ErrorParameters2.title")); //$NON-NLS-1$
mb.setMessage(Messages.getString("DatabaseDialog.ErrorParameters2.description", message)); //$NON-NLS-1$
mb.open();
}
}
public void explore()
{
DatabaseMeta dbinfo = new DatabaseMeta();
try
{
getInfo(dbinfo);
DatabaseExplorerDialog ded = new DatabaseExplorerDialog(shell, SWT.NONE, dbinfo, databases, true);
ded.open();
}
catch (KettleException e)
{
new ErrorDialog(shell,
Messages.getString("DatabaseDialog.ErrorParameters,title"), Messages.getString("DatabaseDialog.ErrorParameters.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void showFeatureList()
{
DatabaseMeta dbinfo = new DatabaseMeta();
try
{
getInfo(dbinfo);
ArrayList buffer = (ArrayList) dbinfo.getFeatureSummary();
PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, Messages.getString("DatabaseDialog.FeatureList.title"), buffer); //$NON-NLS-1$
prd.setTitleMessage(Messages.getString("DatabaseDialog.FeatureList.title"), Messages.getString("DatabaseDialog.FeatureList.title2")); //$NON-NLS-1$ //$NON-NLS-2$
prd.open();
}
catch (KettleException e)
{
new ErrorDialog(shell,
Messages.getString("DatabaseDialog.FeatureListError.title"), Messages.getString("DatabaseDialog.FeatureListError.description"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
| Extra MySQL tab to allow the result streaming to be enabled/disabled.
git-svn-id: 9499f031eb5c9fb9d11553a06c92651e5446d292@2323 5fb7f6ec-07c1-534a-b4ca-9155e429e800
| src/be/ibridge/kettle/core/dialog/DatabaseDialog.java | Extra MySQL tab to allow the result streaming to be enabled/disabled. |
|
Java | apache-2.0 | 5f6fa11032b3456595d7c1b3d8f39b883feab7e6 | 0 | freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM | /* Copyright 2006 The Apache Software Foundation or its licensors, as applicable
*
* 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.apache.harmony.tests.java.nio.channels;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.NonWritableChannelException;
import java.util.Arrays;
import junit.framework.TestCase;
public class FileChannelTest extends TestCase {
private static final String CONTENT = "MYTESTSTRING";
private static final int CONTENT_LENGTH = CONTENT.length();
private static final byte[] CONTENT_AS_BYTES = CONTENT.getBytes();
private static final int CONTENT_AS_BYTES_LENGTH = CONTENT_AS_BYTES.length;
private FileChannel readOnlyFileChannel;
private FileChannel writeOnlyFileChannel;
private FileChannel readWriteFileChannel;
private File fileOfReadOnlyFileChannel;
private File fileOfWriteOnlyFileChannel;
private File fileOfReadWriteFileChannel;
// to read content from FileChannel
private FileInputStream fis;
protected void setUp() throws Exception {
fileOfReadOnlyFileChannel = File.createTempFile(
"File_of_readOnlyFileChannel", "tmp");
fileOfReadOnlyFileChannel.deleteOnExit();
fileOfWriteOnlyFileChannel = File.createTempFile(
"File_of_writeOnlyFileChannel", "tmp");
fileOfWriteOnlyFileChannel.deleteOnExit();
fileOfReadWriteFileChannel = File.createTempFile(
"File_of_readWriteFileChannel", "tmp");
fileOfReadWriteFileChannel.deleteOnExit();
fis = null;
readOnlyFileChannel = new FileInputStream(fileOfReadOnlyFileChannel)
.getChannel();
writeOnlyFileChannel = new FileOutputStream(fileOfWriteOnlyFileChannel)
.getChannel();
readWriteFileChannel = new RandomAccessFile(fileOfReadWriteFileChannel,
"rw").getChannel();
}
protected void tearDown() {
if (null != readOnlyFileChannel) {
try {
readOnlyFileChannel.close();
} catch (IOException e) {
// do nothing
}
}
if (null != writeOnlyFileChannel) {
try {
writeOnlyFileChannel.close();
} catch (IOException e) {
// do nothing
}
}
if (null != readWriteFileChannel) {
try {
readWriteFileChannel.close();
} catch (IOException e) {
// do nothing
}
}
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
// do nothing
}
}
if (null != fileOfReadOnlyFileChannel) {
fileOfReadOnlyFileChannel.delete();
}
if (null != fileOfWriteOnlyFileChannel) {
fileOfWriteOnlyFileChannel.delete();
}
if (null != fileOfReadWriteFileChannel) {
fileOfReadWriteFileChannel.delete();
}
}
/**
* @tests java.nio.channels.FileChannel#force(boolean)
*/
public void test_forceJ() throws Exception {
ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
writeOnlyFileChannel.write(writeBuffer);
writeOnlyFileChannel.force(true);
byte[] readBuffer = new byte[CONTENT_AS_BYTES_LENGTH];
fis = new FileInputStream(fileOfWriteOnlyFileChannel);
fis.read(readBuffer);
assertTrue(Arrays.equals(CONTENT_AS_BYTES, readBuffer));
}
/**
* @tests java.nio.channels.FileChannel#force(boolean)
*/
public void test_forceJ_closed() throws Exception {
writeOnlyFileChannel.close();
try {
writeOnlyFileChannel.force(true);
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
try {
writeOnlyFileChannel.force(false);
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
}
/**
* @tests java.nio.channels.FileChannel#force(boolean)
*/
public void test_forceJ_ReadOnlyChannel() throws Exception {
// force on a read only file channel has no effect.
readOnlyFileChannel.force(true);
readOnlyFileChannel.force(false);
}
/**
* @tests java.nio.channels.FileChannel#position()
*/
public void test_position_Init() throws Exception {
assertEquals(0, readOnlyFileChannel.position());
assertEquals(0, writeOnlyFileChannel.position());
assertEquals(0, readWriteFileChannel.position());
}
/**
* @tests java.nio.channels.FileChannel#position()
*/
public void test_position_ReadOnly() throws Exception {
writeDataToFile(fileOfReadOnlyFileChannel);
assertEquals(0, readOnlyFileChannel.position());
ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
readOnlyFileChannel.read(readBuffer);
assertEquals(CONTENT_LENGTH, readOnlyFileChannel.position());
}
/**
* Initializes test file.
*
* @param file
* @throws FileNotFoundException
* @throws IOException
*/
private void writeDataToFile(File file) throws FileNotFoundException,
IOException {
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(CONTENT_AS_BYTES);
} finally {
fos.close();
}
}
/**
* @tests java.nio.channels.FileChannel#position()
*/
public void test_position_WriteOnly() throws Exception {
ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
writeOnlyFileChannel.write(writeBuffer);
assertEquals(CONTENT_LENGTH, writeOnlyFileChannel.position());
}
/**
* @tests java.nio.channels.FileChannel#position()
*/
public void test_position_ReadWrite() throws Exception {
writeDataToFile(fileOfReadWriteFileChannel);
assertEquals(0, readWriteFileChannel.position());
ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
readWriteFileChannel.read(readBuffer);
assertEquals(CONTENT_LENGTH, readWriteFileChannel.position());
ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
readWriteFileChannel.write(writeBuffer);
assertEquals(CONTENT_LENGTH * 2, readWriteFileChannel.position());
}
/**
* @tests java.nio.channels.FileChannel#position()
*/
public void test_position_Closed() throws Exception {
readOnlyFileChannel.close();
try {
readOnlyFileChannel.position();
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
writeOnlyFileChannel.close();
try {
writeOnlyFileChannel.position();
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
readWriteFileChannel.close();
try {
readWriteFileChannel.position();
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
}
/**
* @tests java.nio.channels.FileChannel#position(long)
*/
public void test_positionJ_Closed() throws Exception {
final long POSITION = 100;
readOnlyFileChannel.close();
try {
readOnlyFileChannel.position(POSITION);
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
writeOnlyFileChannel.close();
try {
writeOnlyFileChannel.position(POSITION);
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
readWriteFileChannel.close();
try {
readWriteFileChannel.position(POSITION);
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
}
/**
* @tests java.nio.channels.FileChannel#position(long)
*/
public void test_positionJ_Negative() throws Exception {
final long NEGATIVE_POSITION = -1;
try {
readOnlyFileChannel.position(NEGATIVE_POSITION);
fail("should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
writeOnlyFileChannel.position(NEGATIVE_POSITION);
fail("should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
readWriteFileChannel.position(NEGATIVE_POSITION);
fail("should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
/**
* @tests java.nio.channels.FileChannel#position(long)
*/
public void test_positionJ_ReadOnly() throws Exception {
writeDataToFile(fileOfReadOnlyFileChannel);
// set the position of the read only file channel to POSITION
final int POSITION = 4;
readOnlyFileChannel.position(POSITION);
// reads the content left to readBuffer through read only file channel
ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
int count = readOnlyFileChannel.read(readBuffer);
assertEquals(CONTENT_LENGTH - POSITION, count);
// asserts the content read is the part which stays beyond the POSITION
readBuffer.flip();
int i = POSITION;
while (readBuffer.hasRemaining()) {
assertEquals(CONTENT_AS_BYTES[i], readBuffer.get());
i++;
}
}
/**
* @tests java.nio.channels.FileChannel#position(long)
*/
public void test_positionJ_WriteOnly() throws Exception {
writeDataToFile(fileOfWriteOnlyFileChannel);
// init data to write
ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
// set the position of the write only file channel to POSITION
final int POSITION = 4;
writeOnlyFileChannel.position(POSITION);
// writes to the write only file channel
writeOnlyFileChannel.write(writeBuffer);
// force to write out.
writeOnlyFileChannel.close();
// gets the result of the write only file channel
byte[] result = new byte[POSITION + CONTENT_LENGTH];
fis = new FileInputStream(fileOfWriteOnlyFileChannel);
fis.read(result);
// constructs the expected result which has content[0... POSITION] plus
// content[0...length()]
byte[] expectedResult = new byte[POSITION + CONTENT_LENGTH];
System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, 0, POSITION);
System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, POSITION,
CONTENT_LENGTH);
// asserts result of the write only file channel same as expected
assertTrue(Arrays.equals(expectedResult, result));
}
/**
* @tests java.nio.channels.FileChannel#size()
*/
public void test_size_Init() throws Exception {
assertEquals(0, readOnlyFileChannel.size());
assertEquals(0, writeOnlyFileChannel.size());
assertEquals(0, readWriteFileChannel.size());
}
/**
* @tests java.nio.channels.FileChannel#size()
*/
public void test_size() throws Exception {
writeDataToFile(fileOfReadOnlyFileChannel);
assertEquals(fileOfReadOnlyFileChannel.length(), readOnlyFileChannel
.size());
}
/**
* @tests java.nio.channels.FileChannel#size()
*/
public void test_size_Closed() throws Exception {
readOnlyFileChannel.close();
try {
readOnlyFileChannel.size();
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
writeOnlyFileChannel.close();
try {
writeOnlyFileChannel.size();
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
readWriteFileChannel.close();
try {
readWriteFileChannel.size();
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
}
/**
* @tests java.nio.channels.FileChannel#truncate(long)
*/
public void test_truncateJ_Closed() throws Exception {
readOnlyFileChannel.close();
try {
readOnlyFileChannel.truncate(0);
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
writeOnlyFileChannel.close();
try {
writeOnlyFileChannel.truncate(0);
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
readWriteFileChannel.close();
try {
readWriteFileChannel.truncate(-1);
fail("should throw ClosedChannelException");
} catch (ClosedChannelException e) {
// expected
}
}
/**
* @tests java.nio.channels.FileChannel#truncate(long)
*/
public void test_truncateJ_IllegalArgument() throws Exception {
try {
writeOnlyFileChannel.truncate(-1);
fail("should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
try {
readWriteFileChannel.truncate(-1);
fail("should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
/**
* @tests java.nio.channels.FileChannel#truncate(long)
*/
public void test_truncateJ_ReadOnly() throws Exception {
writeDataToFile(fileOfReadOnlyFileChannel);
try {
readOnlyFileChannel.truncate(readOnlyFileChannel.size());
fail("should throw NonWritableChannelException.");
} catch (NonWritableChannelException e) {
// expected
}
try {
readOnlyFileChannel.truncate(0);
fail("should throw NonWritableChannelException.");
} catch (NonWritableChannelException e) {
// expected
}
}
/**
* @tests java.nio.channels.FileChannel#truncate(long)
*/
public void test_truncateJ() throws Exception {
writeDataToFile(fileOfReadWriteFileChannel);
int truncateLength = CONTENT_LENGTH + 2;
assertEquals(readWriteFileChannel, readWriteFileChannel
.truncate(truncateLength));
assertEquals(CONTENT_LENGTH, fileOfReadWriteFileChannel.length());
truncateLength = CONTENT_LENGTH;
assertEquals(readWriteFileChannel, readWriteFileChannel
.truncate(truncateLength));
assertEquals(CONTENT_LENGTH, fileOfReadWriteFileChannel.length());
truncateLength = CONTENT_LENGTH / 2;
assertEquals(readWriteFileChannel, readWriteFileChannel
.truncate(truncateLength));
assertEquals(truncateLength, fileOfReadWriteFileChannel.length());
}
/**
* @tests java.nio.channels.FileChannel#isOpen()
*/
public void test_isOpen() throws Exception {
// Regression for HARMONY-40
File logFile = File.createTempFile("out", "tmp");
logFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(logFile, true);
FileChannel channel = out.getChannel();
out.write(1);
out.close();
assertFalse("Assert 0: Channel is still open", channel.isOpen());
}
/**
* @tests java.nio.channels.FileChannel#position()
*/
public void test_position_append() throws Exception {
// Regression test for Harmony-508
File tmpfile = File.createTempFile("FileOutputStream", "tmp");
tmpfile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpfile);
byte[] b = new byte[10];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) i;
}
fos.write(b);
fos.flush();
fos.close();
FileOutputStream f = new FileOutputStream(tmpfile, true);
// Below assertion fails on RI. RI behaviour is counter to spec.
assertEquals(10, f.getChannel().position());
}
}
| modules/nio/src/test/java/org/apache/harmony/tests/java/nio/channels/FileChannelTest.java | /* Copyright 2006 The Apache Software Foundation or its licensors, as applicable
*
* 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.apache.harmony.tests.java.nio.channels;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import junit.framework.TestCase;
public class FileChannelTest extends TestCase {
/**
* @tests java.nio.channels.FileChannel#isOpen()
*/
public void test_isOpen() throws Exception {
// Regression for HARMONY-40
File logFile = File.createTempFile("out", "tmp");
logFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(logFile, true);
FileChannel channel = out.getChannel();
out.write(1);
out.close();
assertFalse("Assert 0: Channel is still open", channel.isOpen());
}
/**
* @tests java.nio.channels.FileChannel#position()
*/
public void test_Position() throws Exception {
// Regression test for Harmony-508
File tmpfile = File.createTempFile("FileOutputStream", "tmp");
tmpfile.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tmpfile);
byte[] b = new byte[10];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) i;
}
fos.write(b);
fos.flush();
fos.close();
FileOutputStream f = new FileOutputStream(tmpfile, true);
assertEquals(10, f.getChannel().position());
}
}
| HARMONY 760 : [nio] Supplement tests for java.nio.channels.FileChannel -- step 1
svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=419234
| modules/nio/src/test/java/org/apache/harmony/tests/java/nio/channels/FileChannelTest.java | HARMONY 760 : [nio] Supplement tests for java.nio.channels.FileChannel -- step 1 |
|
Java | apache-2.0 | c799274e0b6f4051884165176859914a6eef8d8f | 0 | Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services | package org.sagebionetworks.repo.model.dbo.dao;
import org.sagebionetworks.repo.model.UserGroup;
public class UserGroupTestUtils {
public static UserGroup createUser() {
UserGroup user = new UserGroup();
user.setIsIndividual(true);
return user;
}
public static UserGroup createGroup() {
UserGroup group = new UserGroup();
group.setIsIndividual(false);
return group;
}
}
| lib/jdomodels/src/test/java/org/sagebionetworks/repo/model/dbo/dao/UserGroupTestUtils.java | package org.sagebionetworks.repo.model.dbo.dao;
import org.sagebionetworks.repo.model.UserGroup;
public class UserGroupTestUtils {
public static UserGroup createUser() {
UserGroup user = new UserGroup();
user.setIsIndividual(true);
return user;
}
public static UserGroup createGroup() {
// need an arbitrary user to own the project
UserGroup group = new UserGroup();
group.setIsIndividual(false);
return group;
}
}
| remove rogue comment
| lib/jdomodels/src/test/java/org/sagebionetworks/repo/model/dbo/dao/UserGroupTestUtils.java | remove rogue comment |
|
Java | apache-2.0 | 71ac2cf2797c52967afb32395ff38b6b2dd55286 | 0 | darkforestzero/buck,darkforestzero/buck,k21/buck,robbertvanginkel/buck,vschs007/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,marcinkwiatkowski/buck,grumpyjames/buck,romanoid/buck,vschs007/buck,LegNeato/buck,ilya-klyuchnikov/buck,ilya-klyuchnikov/buck,LegNeato/buck,SeleniumHQ/buck,JoelMarcey/buck,zhan-xiong/buck,Addepar/buck,kageiit/buck,brettwooldridge/buck,marcinkwiatkowski/buck,dsyang/buck,Addepar/buck,k21/buck,k21/buck,brettwooldridge/buck,romanoid/buck,dsyang/buck,dsyang/buck,marcinkwiatkowski/buck,vschs007/buck,SeleniumHQ/buck,grumpyjames/buck,shybovycha/buck,Addepar/buck,k21/buck,darkforestzero/buck,romanoid/buck,ilya-klyuchnikov/buck,robbertvanginkel/buck,zhan-xiong/buck,robbertvanginkel/buck,vschs007/buck,brettwooldridge/buck,shybovycha/buck,shybovycha/buck,clonetwin26/buck,vschs007/buck,shs96c/buck,SeleniumHQ/buck,nguyentruongtho/buck,clonetwin26/buck,ilya-klyuchnikov/buck,rmaz/buck,LegNeato/buck,rmaz/buck,LegNeato/buck,nguyentruongtho/buck,k21/buck,robbertvanginkel/buck,grumpyjames/buck,brettwooldridge/buck,facebook/buck,SeleniumHQ/buck,darkforestzero/buck,shs96c/buck,Addepar/buck,kageiit/buck,darkforestzero/buck,shs96c/buck,facebook/buck,clonetwin26/buck,LegNeato/buck,zpao/buck,grumpyjames/buck,rmaz/buck,marcinkwiatkowski/buck,robbertvanginkel/buck,marcinkwiatkowski/buck,ilya-klyuchnikov/buck,clonetwin26/buck,dsyang/buck,zhan-xiong/buck,marcinkwiatkowski/buck,vschs007/buck,JoelMarcey/buck,kageiit/buck,darkforestzero/buck,rmaz/buck,zpao/buck,brettwooldridge/buck,Addepar/buck,romanoid/buck,k21/buck,nguyentruongtho/buck,clonetwin26/buck,facebook/buck,grumpyjames/buck,rmaz/buck,Addepar/buck,brettwooldridge/buck,zhan-xiong/buck,JoelMarcey/buck,JoelMarcey/buck,clonetwin26/buck,Addepar/buck,shs96c/buck,darkforestzero/buck,zhan-xiong/buck,SeleniumHQ/buck,rmaz/buck,Addepar/buck,k21/buck,clonetwin26/buck,shs96c/buck,facebook/buck,Addepar/buck,dsyang/buck,romanoid/buck,zpao/buck,dsyang/buck,grumpyjames/buck,SeleniumHQ/buck,dsyang/buck,SeleniumHQ/buck,darkforestzero/buck,grumpyjames/buck,Addepar/buck,zhan-xiong/buck,darkforestzero/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,shs96c/buck,SeleniumHQ/buck,shybovycha/buck,dsyang/buck,LegNeato/buck,LegNeato/buck,zhan-xiong/buck,facebook/buck,LegNeato/buck,zhan-xiong/buck,facebook/buck,marcinkwiatkowski/buck,shybovycha/buck,zhan-xiong/buck,LegNeato/buck,nguyentruongtho/buck,k21/buck,vschs007/buck,k21/buck,shs96c/buck,dsyang/buck,grumpyjames/buck,rmaz/buck,zpao/buck,Addepar/buck,JoelMarcey/buck,brettwooldridge/buck,grumpyjames/buck,brettwooldridge/buck,clonetwin26/buck,grumpyjames/buck,dsyang/buck,romanoid/buck,k21/buck,zhan-xiong/buck,JoelMarcey/buck,shybovycha/buck,kageiit/buck,vschs007/buck,SeleniumHQ/buck,dsyang/buck,LegNeato/buck,robbertvanginkel/buck,robbertvanginkel/buck,shs96c/buck,brettwooldridge/buck,JoelMarcey/buck,robbertvanginkel/buck,romanoid/buck,k21/buck,grumpyjames/buck,marcinkwiatkowski/buck,brettwooldridge/buck,vschs007/buck,romanoid/buck,romanoid/buck,SeleniumHQ/buck,SeleniumHQ/buck,marcinkwiatkowski/buck,marcinkwiatkowski/buck,rmaz/buck,shybovycha/buck,SeleniumHQ/buck,shs96c/buck,robbertvanginkel/buck,shybovycha/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,rmaz/buck,robbertvanginkel/buck,JoelMarcey/buck,rmaz/buck,marcinkwiatkowski/buck,clonetwin26/buck,nguyentruongtho/buck,vschs007/buck,shs96c/buck,JoelMarcey/buck,shybovycha/buck,romanoid/buck,dsyang/buck,shs96c/buck,LegNeato/buck,shybovycha/buck,brettwooldridge/buck,JoelMarcey/buck,k21/buck,shybovycha/buck,robbertvanginkel/buck,robbertvanginkel/buck,marcinkwiatkowski/buck,rmaz/buck,clonetwin26/buck,kageiit/buck,ilya-klyuchnikov/buck,nguyentruongtho/buck,vschs007/buck,brettwooldridge/buck,zhan-xiong/buck,ilya-klyuchnikov/buck,kageiit/buck,zpao/buck,zhan-xiong/buck,darkforestzero/buck,darkforestzero/buck,rmaz/buck,JoelMarcey/buck,clonetwin26/buck,LegNeato/buck,romanoid/buck,Addepar/buck,zpao/buck,clonetwin26/buck,zhan-xiong/buck,darkforestzero/buck,shs96c/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,darkforestzero/buck,Addepar/buck,romanoid/buck,k21/buck,grumpyjames/buck,ilya-klyuchnikov/buck,romanoid/buck,dsyang/buck,marcinkwiatkowski/buck,zpao/buck,shs96c/buck,vschs007/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,shybovycha/buck,facebook/buck,clonetwin26/buck,rmaz/buck,LegNeato/buck,vschs007/buck,shybovycha/buck,kageiit/buck,robbertvanginkel/buck | /*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.event.listener;
import com.facebook.buck.artifact_cache.ArtifactCacheEvent;
import com.facebook.buck.artifact_cache.CacheResultType;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent;
import com.facebook.buck.event.BuckEventListener;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.log.InvocationInfo;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.BuildRuleEvent;
import com.facebook.buck.rules.BuildRuleKeys;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.util.BuckConstant;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.GuardedBy;
public class RuleKeyLoggerListener implements BuckEventListener {
private static final Logger LOG = Logger.get(RuleKeyLoggerListener.class);
private static final int DEFAULT_MIN_LINES_FOR_AUTO_FLUSH = 100;
private final InvocationInfo info;
private final ExecutorService outputExecutor;
private final int minLinesForAutoFlush;
private final ProjectFilesystem projectFilesystem;
private final Object lock;
@GuardedBy("lock")
private List<String> logLines;
public RuleKeyLoggerListener(
ProjectFilesystem projectFilesystem,
InvocationInfo info,
ExecutorService outputExecutor) {
this(projectFilesystem, info, outputExecutor, DEFAULT_MIN_LINES_FOR_AUTO_FLUSH);
}
public RuleKeyLoggerListener(
ProjectFilesystem projectFilesystem,
InvocationInfo info,
ExecutorService outputExecutor,
int minLinesForAutoFlush) {
this.projectFilesystem = projectFilesystem;
this.minLinesForAutoFlush = minLinesForAutoFlush;
this.info = info;
this.lock = new Object();
this.outputExecutor = outputExecutor;
this.logLines = Lists.newArrayList();
}
@Subscribe
public void onArtifactCacheEvent(HttpArtifactCacheEvent.Finished event) {
if (event.getOperation() != ArtifactCacheEvent.Operation.FETCH ||
!event.getCacheResult().isPresent()) {
return;
}
CacheResultType cacheResultType = event.getCacheResult().get().getType();
if (cacheResultType != CacheResultType.MISS && cacheResultType != CacheResultType.ERROR) {
return;
}
List<String> newLogLines = Lists.newArrayList();
for (RuleKey key : event.getRuleKeys()) {
newLogLines.add(toTsv(key, cacheResultType));
}
synchronized (lock) {
logLines.addAll(newLogLines);
}
flushLogLinesIfNeeded();
}
@Subscribe
public void onBuildRuleEvent(BuildRuleEvent.Finished event) {
BuildRuleKeys ruleKeys = event.getRuleKeys();
BuildTarget target = event.getBuildRule().getBuildTarget();
String ruleKeyLine = toTsv(target, ruleKeys.getRuleKey());
String inputRuleKeyLine = null;
if (ruleKeys.getInputRuleKey().isPresent()) {
inputRuleKeyLine = toTsv(target, ruleKeys.getInputRuleKey().get());
}
synchronized (lock) {
logLines.add(ruleKeyLine);
if (inputRuleKeyLine != null) {
logLines.add(inputRuleKeyLine);
}
}
flushLogLinesIfNeeded();
}
private static String toTsv(RuleKey key, CacheResultType cacheResultType) {
return String.format("http\t%s\t%s", key.toString(), cacheResultType.toString());
}
private static String toTsv(BuildTarget target, RuleKey ruleKey) {
return String.format("target\t%s\t%s", target.toString(), ruleKey.toString());
}
@Override
public void outputTrace(BuildId buildId) throws InterruptedException {
submitFlushLogLines();
outputExecutor.shutdown();
outputExecutor.awaitTermination(1, TimeUnit.HOURS);
}
public Path getLogFilePath() {
Path logDir = projectFilesystem.resolve(info.getLogDirectoryPath());
return logDir.resolve(BuckConstant.RULE_KEY_LOGGER_FILE_NAME);
}
private void flushLogLinesIfNeeded() {
synchronized (lock) {
if (logLines.size() > minLinesForAutoFlush) {
submitFlushLogLines();
}
}
}
private void submitFlushLogLines() {
List<String> linesToFlush;
synchronized (lock) {
linesToFlush = logLines;
logLines = Lists.newArrayList();
}
if (!linesToFlush.isEmpty()) {
@SuppressWarnings("unused") Future<?> unused =
outputExecutor.submit(() -> actuallyFlushLogLines(linesToFlush));
}
}
private void actuallyFlushLogLines(List<String> linesToFlush) {
Path logFile = getLogFilePath();
try {
projectFilesystem.createParentDirs(logFile);
try (FileOutputStream stream = new FileOutputStream(logFile.toString(), /* append */ true);
OutputStreamWriter streamWriter = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
PrintWriter writer = new PrintWriter(streamWriter)) {
for (String line : linesToFlush) {
writer.println(line);
}
}
} catch (IOException e) {
LOG.error(e, "Failed to flush [%d] logLines to file [%s].", linesToFlush.size(), logFile);
}
}
}
| src/com/facebook/buck/event/listener/RuleKeyLoggerListener.java | /*
* Copyright 2016-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.event.listener;
import com.facebook.buck.artifact_cache.ArtifactCacheEvent;
import com.facebook.buck.artifact_cache.CacheResultType;
import com.facebook.buck.artifact_cache.HttpArtifactCacheEvent;
import com.facebook.buck.event.BuckEventListener;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.log.InvocationInfo;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildId;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.BuildRuleEvent;
import com.facebook.buck.rules.BuildRuleKeys;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.util.BuckConstant;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class RuleKeyLoggerListener implements BuckEventListener {
private static final Logger LOG = Logger.get(RuleKeyLoggerListener.class);
private static final int DEFAULT_MIN_LINES_FOR_AUTO_FLUSH = 100;
private final InvocationInfo info;
private final Object lock;
private final ExecutorService outputExecutor;
private final int minLinesForAutoFlush;
private final ProjectFilesystem projectFilesystem;
private List<String> logLines;
private volatile long logLinesCount;
public RuleKeyLoggerListener(
ProjectFilesystem projectFilesystem,
InvocationInfo info,
ExecutorService outputExecutor) {
this(projectFilesystem, info, outputExecutor, DEFAULT_MIN_LINES_FOR_AUTO_FLUSH);
}
public RuleKeyLoggerListener(
ProjectFilesystem projectFilesystem,
InvocationInfo info,
ExecutorService outputExecutor,
int minLinesForAutoFlush) {
this.logLinesCount = 0;
this.projectFilesystem = projectFilesystem;
this.minLinesForAutoFlush = minLinesForAutoFlush;
this.info = info;
this.lock = new Object();
this.outputExecutor = outputExecutor;
this.logLines = Lists.newArrayList();
}
@Subscribe
public void onArtifactCacheEvent(HttpArtifactCacheEvent.Finished event) {
if (event.getOperation() != ArtifactCacheEvent.Operation.FETCH ||
!event.getCacheResult().isPresent()) {
return;
}
CacheResultType cacheResultType = event.getCacheResult().get().getType();
if (cacheResultType != CacheResultType.MISS && cacheResultType != CacheResultType.ERROR) {
return;
}
List<String> newLogLines = Lists.newArrayList();
for (RuleKey key : event.getRuleKeys()) {
newLogLines.add(toTsv(key, cacheResultType));
}
synchronized (lock) {
logLines.addAll(newLogLines);
logLinesCount = logLines.size();
}
flushLogLinesIfNeeded();
}
@Subscribe
public void onBuildRuleEvent(BuildRuleEvent.Finished event) {
BuildRuleKeys ruleKeys = event.getRuleKeys();
BuildTarget target = event.getBuildRule().getBuildTarget();
String ruleKeyLine = toTsv(target, ruleKeys.getRuleKey());
String inputRuleKeyLine = null;
if (ruleKeys.getInputRuleKey().isPresent()) {
inputRuleKeyLine = toTsv(target, ruleKeys.getInputRuleKey().get());
}
synchronized (lock) {
logLines.add(ruleKeyLine);
if (inputRuleKeyLine != null) {
logLines.add(inputRuleKeyLine);
}
logLinesCount = logLines.size();
}
flushLogLinesIfNeeded();
}
private static String toTsv(RuleKey key, CacheResultType cacheResultType) {
return String.format("http\t%s\t%s", key.toString(), cacheResultType.toString());
}
private static String toTsv(BuildTarget target, RuleKey ruleKey) {
return String.format("target\t%s\t%s", target.toString(), ruleKey.toString());
}
@Override
public void outputTrace(BuildId buildId) {
outputExecutor.shutdown();
try {
flushLogLines();
} catch (IOException exception) {
LOG.error(
exception,
"Failed to flush [%d] logLines to file [%s].",
logLines.size(),
getLogFilePath().toAbsolutePath());
}
}
public Path getLogFilePath() {
Path logDir = projectFilesystem.resolve(info.getLogDirectoryPath());
Path logFile = logDir.resolve(BuckConstant.RULE_KEY_LOGGER_FILE_NAME);
return logFile;
}
private void flushLogLinesIfNeeded() {
if (logLinesCount > minLinesForAutoFlush) {
@SuppressWarnings("unused") Future<?> unused =
outputExecutor.submit(() -> {
try {
flushLogLines();
} catch (IOException e) {
LOG.error(e, "Failed to flush logLines from the outputExecutor.");
}
return null;
});
}
}
private void flushLogLines() throws IOException {
List<String> linesToFlush;
synchronized (lock) {
linesToFlush = logLines;
logLines = Lists.newArrayList();
logLinesCount = logLines.size();
}
if (linesToFlush.isEmpty()) {
return;
}
Path logFile = getLogFilePath();
projectFilesystem.createParentDirs(logFile);
try (FileOutputStream stream = new FileOutputStream(logFile.toString(), /* append */ true);
OutputStreamWriter streamWriter = new OutputStreamWriter(stream, StandardCharsets.UTF_8);
PrintWriter writer = new PrintWriter(streamWriter)) {
for (String line : linesToFlush) {
writer.println(line);
}
}
}
}
| improve synchronization & execution in RuleKeyLoggerListener
Summary:
There was a race condition where we would possibly make several unnecessery submissions to the executor. That's because we accessed size outside of lock. Separate size counter is unnecessary. We should use the same executor to submit the final flush, else we might write to the file in an unorderly fashion. It should be safe to submit and shutdown executor as documentation for `ExecutorService.shutdown` says:
/*
* Initiates an orderly shutdown in which previously submitted
* tasks are executed, but no new tasks will be accepted.
* Invocation has no additional effect if already shut down.
*
* <p>This method does not wait for previously submitted tasks to
* complete execution. Use {link #awaitTermination awaitTermination}
* to do that.
*/
Test Plan: check rule_key_logger.tsv
Reviewed By: illicitonion
fbshipit-source-id: 5beaae7
| src/com/facebook/buck/event/listener/RuleKeyLoggerListener.java | improve synchronization & execution in RuleKeyLoggerListener |
|
Java | apache-2.0 | daa0eb7ddfa8866ed37438e95889ac8a24925508 | 0 | GerritCodeReview/plugins_imagare,GerritCodeReview/plugins_imagare,GerritCodeReview/plugins_imagare | // Copyright (C) 2014 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.googlesource.gerrit.plugins.imagare.client;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
public class UploadByDropOrPastePanel extends VerticalPanel {
UploadByDropOrPastePanel() {
init0();
setStyleName("imagare-image-upload-panel");
getElement().setAttribute("contenteditable", "true");
getElement().setAttribute("onpaste", "imagarePasteHandler(this, event)");
getElement().setAttribute("ondrop", "imagareDropHandler(this, event)");
getElement().setAttribute("onkeypress", "imagarePreventKeyPress(event)");
add(new Label("drag and drop image here"));
add(new Label("or"));
add(new Label("paste image from clipboard with " + (isMac() ? "Cmd+V" : "Ctrl+V")));
}
private static native boolean isMac() /*-{
return navigator.platform.toUpperCase().indexOf('MAC') >= 0;
}-*/;
private static native void init0() /*-{
$wnd.imagarePreventKeyPress = function preventKeys(event) {
event = event || window.event;
var ctrlDown = event.ctrlKey || event.metaKey;
if (!ctrlDown) {
event.preventDefault();
}
}
var imagareSavedContent;
$wnd.imagarePasteHandler = function handlePaste(elem, e) {
if (!imagareSavedContent) {
imagareSavedContent = elem.innerHTML;
}
var clipboardData = e.clipboardData || e.originalEvent.clipboardData;
var items = clipboardData.items;
if (JSON.stringify(items)) {
// Chrome
var blob;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
if (blob) {
var reader = new FileReader();
reader.onload = function(e) {
@com.googlesource.gerrit.plugins.imagare.client.ImageUploader::stageImage(Ljava/lang/String;)(e.target.result);
};
reader.readAsDataURL(blob);
} else {
e.preventDefault();
$wnd.Gerrit.showError('no image data');
}
} else if (e && e.clipboardData && e.clipboardData.getData) {
// Webkit
if ((/text\/html/.test(e.clipboardData.types[0]))
|| (/text\/plain/.test(e.clipboardData.types[0]))) {
elem.innerHTML = '<div>' + e.clipboardData.getData(e.clipboardData.types[0]) + '</div>';
} else {
elem.innerHTML = "";
}
waitOnPaste(10, elem);
} else {
// other browser
elem.innerHTML = "";
waitOnPaste(10, elem);
}
}
function waitOnPaste(max, elem) {
if (elem.childNodes && elem.childNodes.length > 0) {
stageImage(elem);
} else if (max > 0) {
that = {
m: max - 1,
e: elem,
}
that.callself = function () {
waitOnPaste(that.m, that.e)
}
setTimeout(that.callself, 20);
}
}
function stageImage(elem) {
var imageData = elem.childNodes[0].getAttribute("src");
elem.innerHTML = imagareSavedContent;
@com.googlesource.gerrit.plugins.imagare.client.ImageUploader::stageImage(Ljava/lang/String;)(imageData);
}
$wnd.imagareDropHandler = function handleDrop(elem, event) {
if (window.chrome) {
event.preventDefault();
}
if (!imagareSavedContent) {
imagareSavedContent = elem.innerHTML;
}
var f = event.dataTransfer.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
elem.innerHTML = imagareSavedContent;
if (f.type.match('image/.*')) {
@com.googlesource.gerrit.plugins.imagare.client.ImageUploader::stageImage(Ljava/lang/String;Ljava/lang/String;)(e.target.result, f.name);
} else {
$wnd.Gerrit.showError('no image file');
}
}
r.readAsDataURL(f);
} else {
$wnd.Gerrit.showError('Failed to load file.');
}
}
}-*/;
public void focus() {
focus(getElement());
}
private static native void focus(Element elem) /*-{
var range = document.createRange();
var sel = window.getSelection();
range.selectNode(elem);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
elem.focus();
}-*/;
}
| src/main/java/com/googlesource/gerrit/plugins/imagare/client/UploadByDropOrPastePanel.java | // Copyright (C) 2014 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.googlesource.gerrit.plugins.imagare.client;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
public class UploadByDropOrPastePanel extends VerticalPanel {
UploadByDropOrPastePanel() {
init0();
setStyleName("imagare-image-upload-panel");
getElement().setAttribute("contenteditable", "true");
getElement().setAttribute("onpaste", "imagarePasteHandler(this, event)");
getElement().setAttribute("ondrop", "imagareDropHandler(this, event)");
getElement().setAttribute("onkeypress", "imagarePreventKeyPress(event)");
add(new Label("drag and drop image here"));
add(new Label("or"));
add(new Label("paste image from clipboard with " + (isMac() ? "Cmd+V" : "Ctrl+V")));
}
private static native boolean isMac() /*-{
return navigator.platform.toUpperCase().indexOf('MAC') >= 0;
}-*/;
private static native void init0() /*-{
$wnd.imagarePreventKeyPress = function preventKeys(event) {
event = event || window.event;
var ctrlDown = event.ctrlKey || event.metaKey;
if (!ctrlDown) {
event.preventDefault();
}
}
$wnd.imagarePasteHandler = function handlePaste(elem, e) {
var savedContent = elem.innerHTML;
var clipboardData = e.clipboardData || e.originalEvent.clipboardData;
var items = clipboardData.items;
if (JSON.stringify(items)) {
// Chrome
var blob;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
if (blob) {
var reader = new FileReader();
reader.onload = function(e) {
@com.googlesource.gerrit.plugins.imagare.client.ImageUploader::stageImage(Ljava/lang/String;)(e.target.result);
};
reader.readAsDataURL(blob);
} else {
e.preventDefault();
$wnd.Gerrit.showError('no image data');
}
} else if (e && e.clipboardData && e.clipboardData.getData) {
// Webkit
if ((/text\/html/.test(e.clipboardData.types[0]))
|| (/text\/plain/.test(e.clipboardData.types[0]))) {
elem.innerHTML = '<div>' + e.clipboardData.getData(e.clipboardData.types[0]) + '</div>';
} else {
elem.innerHTML = "";
}
waitOnPaste(10, elem, savedContent);
} else {
// other browser
elem.innerHTML = "";
waitOnPaste(10, elem, savedContent);
}
}
function waitOnPaste(max, elem, savedContent) {
if (elem.childNodes && elem.childNodes.length > 0) {
stageImage(elem, savedContent);
} else if (max > 0) {
that = {
m: max - 1,
e: elem,
s: savedContent
}
that.callself = function () {
waitOnPaste(that.m, that.e, that.s)
}
setTimeout(that.callself, 20);
}
}
function stageImage(elem, savedContent) {
var imageData = elem.childNodes[0].getAttribute("src");
elem.innerHTML = savedContent;
@com.googlesource.gerrit.plugins.imagare.client.ImageUploader::stageImage(Ljava/lang/String;)(imageData);
}
$wnd.imagareDropHandler = function handleDrop(elem, event) {
if (window.chrome) {
event.preventDefault();
}
var savedContent = elem.innerHTML;
var f = event.dataTransfer.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
elem.innerHTML = savedContent;
if (f.type.match('image/.*')) {
@com.googlesource.gerrit.plugins.imagare.client.ImageUploader::stageImage(Ljava/lang/String;Ljava/lang/String;)(e.target.result, f.name);
} else {
$wnd.Gerrit.showError('no image file');
}
}
r.readAsDataURL(f);
} else {
$wnd.Gerrit.showError('Failed to load file.');
}
}
}-*/;
public void focus() {
focus(getElement());
}
private static native void focus(Element elem) /*-{
var range = document.createRange();
var sel = window.getSelection();
range.selectNode(elem);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
elem.focus();
}-*/;
}
| Prevent that content of upload box is lost on fast pasting many images
Change-Id: I41369e8fde03111143102eb04fee4fbc65aae7f0
Signed-off-by: Edwin Kempin <[email protected]>
| src/main/java/com/googlesource/gerrit/plugins/imagare/client/UploadByDropOrPastePanel.java | Prevent that content of upload box is lost on fast pasting many images |
|
Java | apache-2.0 | bea790d851f17080ad5bb7434e8592529485e523 | 0 | hsaputra/cdap,anthcp/cdap,mpouttuclarke/cdap,chtyim/cdap,hsaputra/cdap,mpouttuclarke/cdap,anthcp/cdap,chtyim/cdap,hsaputra/cdap,caskdata/cdap,mpouttuclarke/cdap,caskdata/cdap,hsaputra/cdap,chtyim/cdap,caskdata/cdap,anthcp/cdap,caskdata/cdap,caskdata/cdap,chtyim/cdap,hsaputra/cdap,mpouttuclarke/cdap,anthcp/cdap,anthcp/cdap,chtyim/cdap,chtyim/cdap,mpouttuclarke/cdap,caskdata/cdap | /*
* Copyright © 2014 Cask Data, 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 co.cask.cdap.examples.helloworld;
import co.cask.cdap.test.ApplicationManager;
import co.cask.cdap.test.FlowManager;
import co.cask.cdap.test.RuntimeMetrics;
import co.cask.cdap.test.RuntimeStats;
import co.cask.cdap.test.ServiceManager;
import co.cask.cdap.test.StreamWriter;
import co.cask.cdap.test.TestBase;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Test for {@link HelloWorld}.
*/
public class HelloWorldTest extends TestBase {
@Test
public void test() throws TimeoutException, InterruptedException, IOException {
// Deploy the HelloWorld application
ApplicationManager appManager = deployApplication(HelloWorld.class);
// Start WhoFlow
FlowManager flowManager = appManager.startFlow("WhoFlow");
// Send stream events to the "who" Stream
StreamWriter streamWriter = appManager.getStreamWriter("who");
streamWriter.send("1");
streamWriter.send("2");
streamWriter.send("3");
streamWriter.send("4");
streamWriter.send("5");
try {
// Wait for the last Flowlet processing 5 events, or at most 5 seconds
RuntimeMetrics metrics = RuntimeStats.getFlowletMetrics("HelloWorld", "WhoFlow", "saver");
metrics.waitForProcessed(5, 5, TimeUnit.SECONDS);
} finally {
flowManager.stop();
}
// Start Greeting service and use it
ServiceManager serviceManager = appManager.startService(HelloWorld.Greeting.SERVICE_NAME);
// Wait service startup
serviceStatusCheck(serviceManager, true);
URL url = new URL(serviceManager.getServiceURL(), "greet");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
String response;
try {
response = new String(ByteStreams.toByteArray(connection.getInputStream()), Charsets.UTF_8);
} finally {
connection.disconnect();
}
Assert.assertEquals("Hello 5!", response);
appManager.stopAll();
}
private void serviceStatusCheck(ServiceManager serviceManger, boolean running) throws InterruptedException {
int trial = 0;
while (trial++ < 5) {
if (serviceManger.isRunning() == running) {
return;
}
TimeUnit.SECONDS.sleep(1);
}
throw new IllegalStateException("Service state not executed. Expected " + running);
}
}
| cdap-examples/HelloWorld/src/test/java/co/cask/cdap/examples/helloworld/HelloWorldTest.java | /*
* Copyright © 2014 Cask Data, 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 co.cask.cdap.examples.helloworld;
import co.cask.cdap.test.ApplicationManager;
import co.cask.cdap.test.FlowManager;
import co.cask.cdap.test.RuntimeMetrics;
import co.cask.cdap.test.RuntimeStats;
import co.cask.cdap.test.ServiceManager;
import co.cask.cdap.test.StreamWriter;
import co.cask.cdap.test.TestBase;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Test for {@link HelloWorld}.
*/
public class HelloWorldTest extends TestBase {
@Test
public void test() throws TimeoutException, InterruptedException, IOException {
// Deploy the HelloWorld application
ApplicationManager appManager = deployApplication(HelloWorld.class);
// Start WhoFlow
FlowManager flowManager = appManager.startFlow("WhoFlow");
// Send stream events to the "who" Stream
StreamWriter streamWriter = appManager.getStreamWriter("who");
streamWriter.send("1");
streamWriter.send("2");
streamWriter.send("3");
streamWriter.send("4");
streamWriter.send("5");
try {
// Wait for the last Flowlet processing 5 events, or at most 5 seconds
RuntimeMetrics metrics = RuntimeStats.getFlowletMetrics("HelloWorld", "WhoFlow", "saver");
metrics.waitForProcessed(5, 5, TimeUnit.SECONDS);
} finally {
flowManager.stop();
}
// Start Greeting service and use it
ServiceManager serviceManager = appManager.startService(HelloWorld.Greeting.SERVICE_NAME);
// Wait up to 5 seconds to start service
waitServiceStartup(serviceManager, 5);
URL url = new URL(serviceManager.getServiceURL(), "greet");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
String response;
try {
response = new String(ByteStreams.toByteArray(connection.getInputStream()), Charsets.UTF_8);
} finally {
connection.disconnect();
}
Assert.assertEquals("Hello 5!", response);
appManager.stopAll();
}
private void waitServiceStartup(ServiceManager serviceManager, int timeout) throws InterruptedException {
int trial = 0;
while (trial++ < timeout) {
if (serviceManager.isRunning()) {
return;
}
TimeUnit.SECONDS.sleep(1);
}
Assert.fail("Service startup failed");
}
}
| CDAP-538: Used method from TestFrameworkTest to wait service startup.
| cdap-examples/HelloWorld/src/test/java/co/cask/cdap/examples/helloworld/HelloWorldTest.java | CDAP-538: Used method from TestFrameworkTest to wait service startup. |
|
Java | apache-2.0 | b7c61434dcff197ac630f0b26eee7fbe3995a53a | 0 | chinmaykolhatkar/incubator-apex-malhar,patilvikram/apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,siyuanh/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,brightchen/apex-malhar,vrozov/apex-malhar,trusli/apex-malhar,ilganeli/incubator-apex-malhar,apache/incubator-apex-malhar,chandnisingh/apex-malhar,yogidevendra/apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,skekre98/apex-mlhr,ananthc/apex-malhar,vrozov/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,brightchen/apex-malhar,trusli/apex-malhar,brightchen/apex-malhar,tweise/apex-malhar,yogidevendra/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,DataTorrent/Megh,prasannapramod/apex-malhar,siyuanh/incubator-apex-malhar,siyuanh/apex-malhar,prasannapramod/apex-malhar,prasannapramod/apex-malhar,PramodSSImmaneni/apex-malhar,DataTorrent/incubator-apex-malhar,vrozov/apex-malhar,chandnisingh/apex-malhar,ananthc/apex-malhar,davidyan74/apex-malhar,sandeep-n/incubator-apex-malhar,ilganeli/incubator-apex-malhar,vrozov/apex-malhar,ilganeli/incubator-apex-malhar,tweise/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,vrozov/apex-malhar,apache/incubator-apex-malhar,skekre98/apex-mlhr,chinmaykolhatkar/apex-malhar,PramodSSImmaneni/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,tweise/apex-malhar,tweise/incubator-apex-malhar,chandnisingh/apex-malhar,prasannapramod/apex-malhar,chandnisingh/apex-malhar,patilvikram/apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/apex-malhar,skekre98/apex-mlhr,vrozov/incubator-apex-malhar,ilganeli/incubator-apex-malhar,apache/incubator-apex-malhar,siyuanh/apex-malhar,tweise/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,ilganeli/incubator-apex-malhar,siyuanh/apex-malhar,tweise/incubator-apex-malhar,siyuanh/incubator-apex-malhar,tweise/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,apache/incubator-apex-malhar,patilvikram/apex-malhar,ilganeli/incubator-apex-malhar,davidyan74/apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,patilvikram/apex-malhar,tushargosavi/incubator-apex-malhar,vrozov/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,vrozov/incubator-apex-malhar,siyuanh/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,prasannapramod/apex-malhar,siyuanh/incubator-apex-malhar,yogidevendra/apex-malhar,trusli/apex-malhar,tweise/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/apex-malhar,chandnisingh/apex-malhar,yogidevendra/apex-malhar,sandeep-n/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tweise/incubator-apex-malhar,davidyan74/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,prasannapramod/apex-malhar,chandnisingh/apex-malhar,patilvikram/apex-malhar,PramodSSImmaneni/apex-malhar,apache/incubator-apex-malhar,siyuanh/apex-malhar,apache/incubator-apex-malhar,trusli/apex-malhar,tweise/apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,siyuanh/incubator-apex-malhar,ananthc/apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,vrozov/incubator-apex-malhar,trusli/apex-malhar,PramodSSImmaneni/apex-malhar,siyuanh/apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,davidyan74/apex-malhar,tweise/apex-malhar,ilganeli/incubator-apex-malhar,vrozov/apex-malhar,davidyan74/apex-malhar,skekre98/apex-mlhr,tushargosavi/incubator-apex-malhar,trusli/apex-malhar,brightchen/apex-malhar,DataTorrent/Megh,vrozov/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,skekre98/apex-mlhr,brightchen/apex-malhar,patilvikram/apex-malhar,tushargosavi/incubator-apex-malhar,tweise/apex-malhar,tweise/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/incubator-apex-malhar,skekre98/apex-mlhr,tushargosavi/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,ananthc/apex-malhar,yogidevendra/apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/apex-malhar,siyuanh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,patilvikram/apex-malhar,apache/incubator-apex-malhar,vrozov/incubator-apex-malhar,ananthc/apex-malhar,sandeep-n/incubator-apex-malhar,vrozov/incubator-apex-malhar,brightchen/apex-malhar,ananthc/apex-malhar,davidyan74/apex-malhar,yogidevendra/apex-malhar,trusli/apex-malhar,brightchen/apex-malhar | /*
* Copyright (c) 2012 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.demos.twitter;
import com.malhartech.api.StreamCodec;
import java.nio.ByteBuffer;
import malhar.netlet.Client.Fragment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Chetan Narsude <[email protected]>
*/
public class URLSerDe implements StreamCodec<byte[]>
{
private static final Logger logger = LoggerFactory.getLogger(URLSerDe.class);
/**
* Covert the bytes into object useful for downstream node.
*
* @return WindowedURLHolder object which represents the bytes.
*/
@Override
public byte[] fromByteArray(DataStatePair dspair)
{
Fragment f = dspair.data;
if (f == null || f.buffer == null) {
return null;
}
else if (f.offset == 0 && f.length == f.buffer.length) {
return f.buffer;
}
else {
byte[] buffer = new byte[f.buffer.length];
System.arraycopy(f.buffer, f.offset, buffer, 0, f.length);
return buffer;
}
}
/**
* Cast the input object to byte[].
*
* @param o - byte array representing the bytes of the string
* @return the same object as input
*/
@Override
public DataStatePair toByteArray(byte[] o)
{
DataStatePair dspair = new DataStatePair();
dspair.data = new Fragment(o, 0, o.length);
dspair.state = null;
return dspair;
}
@Override
public int getPartition(byte[] o)
{
ByteBuffer bb = ByteBuffer.wrap(o);
return bb.hashCode();
}
@Override
public void resetState()
{
/* there is nothing to reset in this serde */
}
}
| demos/src/main/java/com/malhartech/demos/twitter/URLSerDe.java | /*
* Copyright (c) 2012 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.demos.twitter;
import com.malhartech.api.StreamCodec;
import java.nio.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Chetan Narsude <[email protected]>
*/
public class URLSerDe implements StreamCodec<byte[]>
{
private static final Logger logger = LoggerFactory.getLogger(URLSerDe.class);
/**
* Covert the bytes into object useful for downstream node.
* @return WindowedURLHolder object which represents the bytes.
*/
@Override
public byte[] fromByteArray(DataStatePair dspair)
{
return dspair.data;
}
/**
* Cast the input object to byte[].
* @param o - byte array representing the bytes of the string
* @return the same object as input
*/
@Override
public DataStatePair toByteArray(byte[] o)
{
DataStatePair dspair = new DataStatePair();
dspair.data = o;
dspair.state = null;
return dspair;
}
@Override
public int getPartition(byte[] o)
{
ByteBuffer bb = ByteBuffer.wrap(o);
return bb.hashCode();
}
@Override
public void resetState()
{
/* there is nothing to reset in this serde */
}
}
| fixed URLSerde
| demos/src/main/java/com/malhartech/demos/twitter/URLSerDe.java | fixed URLSerde |
|
Java | apache-2.0 | 5752706861127595953914a8aec55c5725c61547 | 0 | tobiasge/cgeo,tobiasge/cgeo,rsudev/c-geo-opensource,cgeo/cgeo,rsudev/c-geo-opensource,rsudev/c-geo-opensource,cgeo/cgeo,tobiasge/cgeo,cgeo/cgeo,cgeo/cgeo | package cgeo.geocaching.activity;
import cgeo.geocaching.R;
import cgeo.geocaching.utils.functions.Action1;
import android.util.DisplayMetrics;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.android.material.tabs.TabLayoutMediator;
public abstract class TabbedViewPagerActivity extends AbstractActionBarActivity {
@SuppressWarnings("rawtypes")
private final Map<Long, TabbedViewPagerFragment> fragmentMap = new LinkedHashMap<>();
private long currentPageId;
private long[] orderedPages;
private ViewPager2 viewPager = null;
private Action1<Long> onPageChangeListener = null;
/**
* The {@link SwipeRefreshLayout} for this activity. Might be null if page is not refreshable.
*/
private SwipeRefreshLayout swipeRefreshLayout;
/**
* Set if the content is refreshable. Defaults to true if the Activity contains a {@link SwipeRefreshLayout}.
*/
private boolean isRefreshable = true;
protected void createViewPager(final long initialPageId, final long[] orderedPages, final Action1<Long> onPageChangeListener, final boolean isRefreshable) {
this.isRefreshable = isRefreshable;
this.currentPageId = initialPageId;
setOrderedPages(orderedPages);
this.onPageChangeListener = onPageChangeListener;
setContentView(isRefreshable ? R.layout.tabbed_viewpager_activity_refreshable : R.layout.tabbed_viewpager_activity);
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new ViewPagerAdapter(this));
viewPager.registerOnPageChangeCallback(pageChangeCallback);
viewPager.setCurrentItem(pageIdToPosition(currentPageId));
viewPager.setOffscreenPageLimit(10);
swipeRefreshLayout = findViewById(R.id.swipe_refresh);
if (swipeRefreshLayout != null) {
final DisplayMetrics outMetrics = new DisplayMetrics ();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
final float dpHeight = outMetrics.heightPixels / getResources().getDisplayMetrics().density;
final int mDistanceToTriggerSync = (int) (dpHeight * 0.7);
// initialize and register listener for pull-to-refresh gesture
swipeRefreshLayout.setDistanceToTriggerSync(mDistanceToTriggerSync);
swipeRefreshLayout.setOnRefreshListener(() -> {
swipeRefreshLayout.setRefreshing(false);
pullToRefreshActionTrigger();
}
);
}
new TabLayoutMediator(findViewById(R.id.tab_layout), viewPager, (tab, position) -> tab.setText(getTitle(getItemId(position)))).attach();
}
private final ViewPager2.OnPageChangeCallback pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
/*
@Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
*/
@Override
public void onPageSelected(final int position) {
super.onPageSelected(position);
currentPageId = getItemId(position);
if (onPageChangeListener != null) {
onPageChangeListener.call(currentPageId);
}
}
@Override
public void onPageScrollStateChanged(final int state) {
super.onPageScrollStateChanged(state);
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setEnabled(state == ViewPager2.SCROLL_STATE_IDLE && isRefreshable);
}
}
};
@SuppressWarnings("rawtypes")
protected void setOrderedPages(final long[] orderedPages) {
this.orderedPages = orderedPages;
for (TabbedViewPagerFragment fragment : fragmentMap.values()) {
fragment.notifyDataSetChanged();
}
notifyAdapterDataSetChanged();
if (viewPager != null) {
viewPager.setCurrentItem(pageIdToPosition(currentPageId));
}
}
public long getItemId(final int position) {
return orderedPages[Math.max(0, Math.min(position, orderedPages.length - 1))];
}
private int pageIdToPosition(final long page) {
if (orderedPages == null) {
return 0;
}
for (int i = 0; i < orderedPages.length; i++) {
if (orderedPages[i] == page) {
return i;
}
}
return 0;
}
protected abstract String getTitle(long pageId);
@SuppressWarnings("rawtypes")
protected abstract TabbedViewPagerFragment createNewFragment(long pageId);
private class ViewPagerAdapter extends FragmentStateAdapter {
private final WeakReference<FragmentActivity> fragmentActivityWeakReference;
ViewPagerAdapter(final FragmentActivity fa) {
super(fa);
fragmentActivityWeakReference = new WeakReference<>(fa);
}
@Override
@NonNull
@SuppressWarnings("rawtypes")
public Fragment createFragment(final int position) {
final long pageId = getItemId(position);
TabbedViewPagerFragment fragment = fragmentMap.get(pageId);
if (fragment != null) {
return fragment;
}
fragment = createNewFragment(pageId);
fragment.setActivity(fragmentActivityWeakReference.get());
fragmentMap.put(pageId, fragment);
return fragment;
}
@Override
public long getItemId(final int position) {
return orderedPages[Math.max(0, Math.min(position, orderedPages.length - 1))];
}
@Override
public boolean containsItem(final long pageId) {
for (long orderedPage : orderedPages) {
if (orderedPage == pageId) {
return true;
}
}
return false;
}
@Override
public int getItemCount() {
return orderedPages == null ? 0 : orderedPages.length;
}
}
@SuppressWarnings("rawtypes")
private void notifyAdapterDataSetChanged() {
if (viewPager != null) {
final RecyclerView.Adapter adapter = viewPager.getAdapter();
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
}
protected long getCurrentPageId() {
return currentPageId;
}
protected boolean isCurrentPage(final int pageId) {
return currentPageId == pageId;
}
@SuppressWarnings("rawtypes")
protected void reinitializePage(final long pageId) {
final TabbedViewPagerFragment fragment = fragmentMap.get(pageId);
if (fragment != null) {
fragment.notifyDataSetChanged();
}
notifyAdapterDataSetChanged();
}
@SuppressWarnings("rawtypes")
protected void reinitializeViewPager() {
for (TabbedViewPagerFragment fragment : fragmentMap.values()) {
fragment.notifyDataSetChanged();
}
// force update current page, as this is not done automatically by the adapter
final TabbedViewPagerFragment current = fragmentMap.get(currentPageId);
if (current != null) {
current.setContent();
}
notifyAdapterDataSetChanged();
}
/**
* will be called, when refresh is triggered via the pull-to-refresh gesture
*/
protected void pullToRefreshActionTrigger() {
// do nothing by default. Should be overwritten by the activity if page is refreshable
}
/**
* set if the pull-to-refresh gesture should be enabled for the displayed content
*/
protected void setIsContentRefreshable(final boolean isRefreshable) {
this.isRefreshable = isRefreshable;
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setEnabled(isRefreshable);
}
}
@Override
protected void onDestroy() {
viewPager.unregisterOnPageChangeCallback(pageChangeCallback);
super.onDestroy();
}
}
| main/src/cgeo/geocaching/activity/TabbedViewPagerActivity.java | package cgeo.geocaching.activity;
import cgeo.geocaching.R;
import cgeo.geocaching.utils.functions.Action1;
import android.util.DisplayMetrics;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.android.material.tabs.TabLayoutMediator;
public abstract class TabbedViewPagerActivity extends AbstractActionBarActivity {
@SuppressWarnings("rawtypes")
private final Map<Long, TabbedViewPagerFragment> fragmentMap = new LinkedHashMap<>();
private long currentPageId;
private long[] orderedPages;
private ViewPager2 viewPager = null;
private Action1<Long> onPageChangeListener = null;
/**
* The {@link SwipeRefreshLayout} for this activity. Might be null if page is not refreshable.
*/
private SwipeRefreshLayout swipeRefreshLayout;
/**
* Set if the content is refreshable. Defaults to true if the Activity contains a {@link SwipeRefreshLayout}.
*/
private boolean isRefreshable = true;
protected void createViewPager(final long initialPageId, final long[] orderedPages, final Action1<Long> onPageChangeListener, final boolean isRefreshable) {
this.isRefreshable = isRefreshable;
this.currentPageId = initialPageId;
setOrderedPages(orderedPages);
this.onPageChangeListener = onPageChangeListener;
setContentView(isRefreshable ? R.layout.tabbed_viewpager_activity_refreshable : R.layout.tabbed_viewpager_activity);
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new ViewPagerAdapter(this));
viewPager.registerOnPageChangeCallback(pageChangeCallback);
viewPager.setCurrentItem(pageIdToPosition(currentPageId));
swipeRefreshLayout = findViewById(R.id.swipe_refresh);
if (swipeRefreshLayout != null) {
final DisplayMetrics outMetrics = new DisplayMetrics ();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
final float dpHeight = outMetrics.heightPixels / getResources().getDisplayMetrics().density;
final int mDistanceToTriggerSync = (int) (dpHeight * 0.7);
// initialize and register listener for pull-to-refresh gesture
swipeRefreshLayout.setDistanceToTriggerSync(mDistanceToTriggerSync);
swipeRefreshLayout.setOnRefreshListener(() -> {
swipeRefreshLayout.setRefreshing(false);
pullToRefreshActionTrigger();
}
);
}
new TabLayoutMediator(findViewById(R.id.tab_layout), viewPager, (tab, position) -> tab.setText(getTitle(getItemId(position)))).attach();
}
private final ViewPager2.OnPageChangeCallback pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
/*
@Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
*/
@Override
public void onPageSelected(final int position) {
super.onPageSelected(position);
currentPageId = getItemId(position);
if (onPageChangeListener != null) {
onPageChangeListener.call(currentPageId);
}
}
@Override
public void onPageScrollStateChanged(final int state) {
super.onPageScrollStateChanged(state);
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setEnabled(state == ViewPager2.SCROLL_STATE_IDLE && isRefreshable);
}
}
};
@SuppressWarnings("rawtypes")
protected void setOrderedPages(final long[] orderedPages) {
this.orderedPages = orderedPages;
for (TabbedViewPagerFragment fragment : fragmentMap.values()) {
fragment.notifyDataSetChanged();
}
notifyAdapterDataSetChanged();
if (viewPager != null) {
viewPager.setCurrentItem(pageIdToPosition(currentPageId));
}
}
public long getItemId(final int position) {
return orderedPages[Math.max(0, Math.min(position, orderedPages.length - 1))];
}
private int pageIdToPosition(final long page) {
if (orderedPages == null) {
return 0;
}
for (int i = 0; i < orderedPages.length; i++) {
if (orderedPages[i] == page) {
return i;
}
}
return 0;
}
protected abstract String getTitle(long pageId);
@SuppressWarnings("rawtypes")
protected abstract TabbedViewPagerFragment createNewFragment(long pageId);
private class ViewPagerAdapter extends FragmentStateAdapter {
private final WeakReference<FragmentActivity> fragmentActivityWeakReference;
ViewPagerAdapter(final FragmentActivity fa) {
super(fa);
fragmentActivityWeakReference = new WeakReference<>(fa);
}
@Override
@NonNull
@SuppressWarnings("rawtypes")
public Fragment createFragment(final int position) {
final long pageId = getItemId(position);
TabbedViewPagerFragment fragment = fragmentMap.get(pageId);
if (fragment != null) {
return fragment;
}
fragment = createNewFragment(pageId);
fragment.setActivity(fragmentActivityWeakReference.get());
fragmentMap.put(pageId, fragment);
return fragment;
}
@Override
public long getItemId(final int position) {
return orderedPages[Math.max(0, Math.min(position, orderedPages.length - 1))];
}
@Override
public boolean containsItem(final long pageId) {
for (long orderedPage : orderedPages) {
if (orderedPage == pageId) {
return true;
}
}
return false;
}
@Override
public int getItemCount() {
return orderedPages == null ? 0 : orderedPages.length;
}
}
@SuppressWarnings("rawtypes")
private void notifyAdapterDataSetChanged() {
if (viewPager != null) {
final RecyclerView.Adapter adapter = viewPager.getAdapter();
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
}
protected long getCurrentPageId() {
return currentPageId;
}
protected boolean isCurrentPage(final int pageId) {
return currentPageId == pageId;
}
@SuppressWarnings("rawtypes")
protected void reinitializePage(final long pageId) {
final TabbedViewPagerFragment fragment = fragmentMap.get(pageId);
if (fragment != null) {
fragment.notifyDataSetChanged();
}
notifyAdapterDataSetChanged();
}
@SuppressWarnings("rawtypes")
protected void reinitializeViewPager() {
for (TabbedViewPagerFragment fragment : fragmentMap.values()) {
fragment.notifyDataSetChanged();
}
// force update current page, as this is not done automatically by the adapter
final TabbedViewPagerFragment current = fragmentMap.get(currentPageId);
if (current != null) {
current.setContent();
}
notifyAdapterDataSetChanged();
}
/**
* will be called, when refresh is triggered via the pull-to-refresh gesture
*/
protected void pullToRefreshActionTrigger() {
// do nothing by default. Should be overwritten by the activity if page is refreshable
}
/**
* set if the pull-to-refresh gesture should be enabled for the displayed content
*/
protected void setIsContentRefreshable(final boolean isRefreshable) {
this.isRefreshable = isRefreshable;
if (swipeRefreshLayout != null) {
swipeRefreshLayout.setEnabled(isRefreshable);
}
}
@Override
protected void onDestroy() {
viewPager.unregisterOnPageChangeCallback(pageChangeCallback);
super.onDestroy();
}
}
| enlarge cache size for TabbedViewPagerActivity (#11012)
| main/src/cgeo/geocaching/activity/TabbedViewPagerActivity.java | enlarge cache size for TabbedViewPagerActivity (#11012) |
|
Java | apache-2.0 | 4688dab6b6d9856ebc902f9709392f78182685f5 | 0 | inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service | package org.slc.sli.search.process.impl;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slc.sli.search.process.Extractor;
import org.slc.sli.search.util.IndexEntityConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
/**
* Extractor pulls data from mongo and writes it to file.
*
* @author dwu
*
*/
public class ExtractorImpl implements Extractor {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final static String DEFAULT_EXTRACT_DIR = "tmp";
private final static int DEFAULT_LINE_PER_FILE = 500000;
private final static int DEFAULT_EXECUTOR_THREADS = 2;
private int maxLinePerFile = DEFAULT_LINE_PER_FILE;
@Autowired
private MongoTemplate template;
private IndexEntityConfig indexEntityConfig;
private String extractDir = DEFAULT_EXTRACT_DIR;
private String inboxDir;
private ExecutorService executor;
private int executorThreads = DEFAULT_EXECUTOR_THREADS;
public void init() {
new File(extractDir).mkdirs();
// create thread pool to process files
executor = Executors.newFixedThreadPool(executorThreads);
}
public void destroy() {
}
/*
* (non-Javadoc)
*
* @see org.slc.sli.search.process.Extractor#execute()
*/
public void execute() {
for (String collection : indexEntityConfig.collections()) {
executor.execute(new ExtractWorker(collection, indexEntityConfig.getFields(collection)));
extractCollection(collection, indexEntityConfig.getFields(collection));
}
}
public void extractCollection(String collectionName, List<String> fields) {
logger.info("Extracting " + collectionName);
// execute query, get cursor of results
BasicDBObject keys = new BasicDBObject();
for (String field : fields) {
keys.put(field, 1);
}
DBCollection collection = template.getCollection(collectionName);
DBCursor cursor = collection.find(new BasicDBObject(), keys);
BufferedWriter bw = null;
DBObject obj;
int numberOfLineWritten = 0;
File outFile = null;
try {
// write each record to file
while (cursor.hasNext()) {
if (numberOfLineWritten % maxLinePerFile == 0) {
numberOfLineWritten = 0;
IOUtils.closeQuietly(bw);
// move file to inbox for indexer
if (outFile != null) {
FileUtils.moveFileToDirectory(outFile, new File(inboxDir), true);
}
// open file to write
outFile = createTempFile(collectionName);
bw = new BufferedWriter(new FileWriter(outFile));
logger.info("File [" + outFile.getName() + "] was created");
}
obj = cursor.next();
bw.write(JSON.serialize(obj));
bw.newLine();
numberOfLineWritten++;
}
// finish up
IOUtils.closeQuietly(bw);
// move file to inbox for indexer
if (outFile != null) {
FileUtils.moveFileToDirectory(outFile, new File(inboxDir), true);
}
} catch (FileNotFoundException e) {
logger.error("Error writing entities file", e);
} catch (IOException e) {
logger.error("Error writing entities file", e);
} finally {
// close file
IOUtils.closeQuietly(bw);
// close cursor
cursor.close();
logger.info("Finished extracting " + collectionName);
}
}
private File createTempFile(String collectionName) {
return new File(extractDir, collectionName + "." + UUID.randomUUID() + ".json");
}
public void setIndexEntityConfig(IndexEntityConfig config) {
this.indexEntityConfig = config;
}
public void setExtractDir(String extractDir) {
this.extractDir = extractDir;
}
public void setInboxDir(String inboxDir) {
this.inboxDir = inboxDir;
}
public void setMaxLinePerFile(int maxLinePerFile) {
this.maxLinePerFile = maxLinePerFile;
}
public void setExecutorThreads(int executorThreads) {
this.executorThreads = executorThreads;
}
/**
* Runnable Thread class to write into file read from Mongo.
*
* @author tosako
*
*/
private class ExtractWorker implements Runnable {
private String collectionName;
private List<String> fields;
public ExtractWorker(String collectionName, List<String> fields) {
this.collectionName = collectionName;
this.fields = fields;
}
public void run() {
extractCollection(collectionName, fields);
}
}
} | sli/opstools/search-indexer/src/main/java/org/slc/sli/search/process/impl/ExtractorImpl.java | package org.slc.sli.search.process.impl;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slc.sli.search.process.Extractor;
import org.slc.sli.search.util.IndexEntityConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
/**
* Extractor pulls data from mongo and writes it to file.
*
* @author dwu
*
*/
public class ExtractorImpl implements Extractor {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final static String DEFAULT_EXTRACT_DIR = "tmp";
private final static int DEFAULT_LINE_PER_FILE = 500000;
private final static int DEFAULT_EXECUTOR_THREADS = 2;
private int maxLinePerFile = DEFAULT_LINE_PER_FILE;
@Autowired
private MongoTemplate template;
private IndexEntityConfig indexEntityConfig;
private String extractDir = DEFAULT_EXTRACT_DIR;
private String inboxDir;
private ExecutorService executor;
private int executorThreads = DEFAULT_EXECUTOR_THREADS;
public void init() {
new File(extractDir).mkdirs();
// create thread pool to process files
executor = Executors.newFixedThreadPool(executorThreads);
}
public void destroy() {
}
/*
* (non-Javadoc)
*
* @see org.slc.sli.search.process.Extractor#execute()
*/
public void execute() {
for (String collection : indexEntityConfig.collections()) {
executor.execute(new ExtractWorker(collection, indexEntityConfig.getFields(collection)));
extractCollection(collection, indexEntityConfig.getFields(collection));
}
}
public void extractCollection(String collectionName, List<String> fields) {
logger.info("Extracting " + collectionName);
// execute query, get cursor of results
BasicDBObject keys = new BasicDBObject();
for (String field : fields) {
keys.put(field, 1);
}
DBCollection collection = template.getCollection(collectionName);
DBCursor cursor = collection.find(new BasicDBObject(), keys);
BufferedWriter bw = null;
DBObject obj;
int numberOfLineWritten = 0;
File outFile = null;
try {
// write each record to file
while (cursor.hasNext()) {
if (numberOfLineWritten % maxLinePerFile == 0) {
numberOfLineWritten = 0;
IOUtils.closeQuietly(bw);
// move file to inbox for indexer
if (outFile != null) {
FileUtils.moveFileToDirectory(outFile, new File(inboxDir), true);
}
// open file to write
outFile = createTempFile(collectionName);
bw = new BufferedWriter(new FileWriter(outFile));
logger.info("File [" + outFile.getName() + "] was created");
}
obj = cursor.next();
bw.write(JSON.serialize(obj));
bw.newLine();
numberOfLineWritten++;
}
} catch (FileNotFoundException e) {
logger.error("Error writing entities file", e);
} catch (IOException e) {
logger.error("Error writing entities file", e);
} finally {
// close file
IOUtils.closeQuietly(bw);
// close cursor
cursor.close();
logger.info("Finished extracting " + collectionName);
}
}
private File createTempFile(String collectionName) {
return new File(extractDir, collectionName + "." + UUID.randomUUID() + ".json");
}
public void setIndexEntityConfig(IndexEntityConfig config) {
this.indexEntityConfig = config;
}
public void setExtractDir(String extractDir) {
this.extractDir = extractDir;
}
public void setInboxDir(String inboxDir) {
this.inboxDir = inboxDir;
}
public void setMaxLinePerFile(int maxLinePerFile) {
this.maxLinePerFile = maxLinePerFile;
}
public void setExecutorThreads(int executorThreads) {
this.executorThreads = executorThreads;
}
/**
* Runnable Thread class to write into file read from Mongo.
*
* @author tosako
*
*/
private class ExtractWorker implements Runnable {
private String collectionName;
private List<String> fields;
public ExtractWorker(String collectionName, List<String> fields) {
this.collectionName = collectionName;
this.fields = fields;
}
public void run() {
extractCollection(collectionName, fields);
}
}
} | extractor fix - handle final file
| sli/opstools/search-indexer/src/main/java/org/slc/sli/search/process/impl/ExtractorImpl.java | extractor fix - handle final file |
|
Java | apache-2.0 | eb31d7d556a357b15681482f8d15f9448e503f68 | 0 | TremoloSecurity/OpenUnison,TremoloSecurity/OpenUnison,TremoloSecurity/OpenUnison,TremoloSecurity/OpenUnison,TremoloSecurity/OpenUnison | /*
Copyright 2015 Tremolo Security, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.tremolosecurity.provisioning.tasks;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import com.cedarsoftware.util.io.JsonWriter;
import com.google.gson.Gson;
import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPAttributeSet;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPReferralException;
import com.novell.ldap.LDAPSearchResults;
import com.tremolosecurity.config.util.ConfigManager;
import com.tremolosecurity.config.xml.ApprovalType;
import com.tremolosecurity.config.xml.AzRuleType;
import com.tremolosecurity.config.xml.EscalationType;
import com.tremolosecurity.config.xml.WorkflowTaskType;
import com.tremolosecurity.json.Token;
import com.tremolosecurity.provisioning.core.ProvisioningException;
import com.tremolosecurity.provisioning.core.User;
import com.tremolosecurity.provisioning.core.Workflow;
import com.tremolosecurity.provisioning.core.WorkflowTaskImpl;
import com.tremolosecurity.provisioning.tasks.Approval.ApproverType;
import com.tremolosecurity.provisioning.tasks.escalation.EsclationRuleImpl;
import com.tremolosecurity.provisioning.util.AzUtils;
import com.tremolosecurity.provisioning.util.EscalationRule;
import com.tremolosecurity.provisioning.util.EscalationRule.RunOptions;
import com.tremolosecurity.proxy.az.AzRule;
import com.tremolosecurity.proxy.az.CustomAuthorization;
import com.tremolosecurity.proxy.az.VerifyEscalation;
import com.tremolosecurity.proxy.az.AzRule.ScopeType;
public class Approval extends WorkflowTaskImpl implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4449491970307931192L;
public static final String SEND_NOTIFICATION = "APPROVAL_SEND_NOTIFICATION";
static Logger logger = Logger.getLogger(Approval.class.getName());
public enum ApproverType {
StaticGroup,
DynamicGroup,
Filter,
DN,
Custom
};
String emailTemplate;
String label;
ArrayList<Approver> approvers;
List<AzRule> azRules;
List<EscalationRule> escalationRules;
String mailAttr;
String failureEmailSubject;
String failureEmailMsg;
boolean failOnNoAZ;
int id;
transient ConfigManager cfg;
private ArrayList<AzRule> failureAzRules;
boolean failed;
public Approval() {
}
public Approval(WorkflowTaskType taskConfig, ConfigManager cfg,Workflow wf)
throws ProvisioningException {
super(taskConfig, cfg,wf);
this.approvers = new ArrayList<Approver>();
this.azRules = new ArrayList<AzRule>();
this.failed = false;
ApprovalType att = (ApprovalType) taskConfig;
for (AzRuleType azr : att.getApprovers().getRule()) {
Approver approver = new Approver();
if (azr.getScope().equalsIgnoreCase("filter")) {
approver.type = ApproverType.Filter;
} else if (azr.getScope().equalsIgnoreCase("group")) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope().equalsIgnoreCase("dn")) {
approver.type = ApproverType.DN;
} else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope().equalsIgnoreCase("custom")) {
approver.type = ApproverType.Custom;
}
approver.constraint = azr.getConstraint();
this.approvers.add(approver);
AzRule rule = new AzRule(azr.getScope(),azr.getConstraint(),azr.getClassName(),cfg,wf);
this.azRules.add(rule);
approver.customAz = rule.getCustomAuthorization();
}
this.label = att.getLabel();
this.emailTemplate = att.getEmailTemplate();
this.mailAttr = att.getMailAttr();
this.failureEmailSubject = att.getFailureEmailSubject();
this.failureEmailMsg = att.getFailureEmailMsg();
this.escalationRules = new ArrayList<EscalationRule>();
if (att.getEscalationPolicy() != null) {
DateTime now = new DateTime();
for (EscalationType ert : att.getEscalationPolicy().getEscalation()) {
EscalationRule erule = new EsclationRuleImpl();
DateTime when;
if (ert.getExecuteAfterUnits().equalsIgnoreCase("sec")) {
when = now.plusSeconds(ert.getExecuteAfterTime());
} else if (ert.getExecuteAfterUnits().equals("min")) {
when = now.plusMinutes(ert.getExecuteAfterTime());
} else if (ert.getExecuteAfterUnits().equals("hr")) {
when = now.plusHours(ert.getExecuteAfterTime());
} else if (ert.getExecuteAfterUnits().equals("day")) {
when = now.plusDays(ert.getExecuteAfterTime());
} else if (ert.getExecuteAfterUnits().equals("wk")) {
when = now.plusWeeks(ert.getExecuteAfterTime());
} else {
throw new ProvisioningException("Unknown time unit : " + ert.getExecuteAfterUnits());
}
erule.setCompleted(false);
erule.setExecuteTS(when.getMillis());
if (ert.getValidateEscalationClass() != null && ! ert.getValidateEscalationClass().isEmpty() ) {
try {
erule.setVerify((VerifyEscalation) Class.forName(ert.getValidateEscalationClass()).newInstance());
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
throw new ProvisioningException("Could not initialize escalation rule",e);
}
} else {
erule.setVerify(null);
}
erule.setAzRules(new ArrayList<AzRule>());
for (AzRuleType azr : ert.getAzRules().getRule()) {
Approver approver = new Approver();
if (azr.getScope().equalsIgnoreCase("filter")) {
approver.type = ApproverType.Filter;
} else if (azr.getScope().equalsIgnoreCase("group")) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope().equalsIgnoreCase("dn")) {
approver.type = ApproverType.DN;
} else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope().equalsIgnoreCase("custom")) {
approver.type = ApproverType.Custom;
}
approver.constraint = azr.getConstraint();
//this.approvers.add(approver);
AzRule rule = new AzRule(azr.getScope(),azr.getConstraint(),azr.getClassName(),cfg,wf);
erule.getAzRules().add(rule);
approver.customAz = rule.getCustomAuthorization();
}
this.escalationRules.add(erule);
now = when;
}
if (att.getEscalationPolicy().getEscalationFailure().getAction() != null) {
switch (att.getEscalationPolicy().getEscalationFailure().getAction()) {
case "leave" :
this.failureAzRules = null;
this.failOnNoAZ = false;
break;
case "assign" :
this.failOnNoAZ = true;
this.failureAzRules = new ArrayList<AzRule>();
for (AzRuleType azr : att.getEscalationPolicy().getEscalationFailure().getAzRules().getRule()) {
Approver approver = new Approver();
if (azr.getScope().equalsIgnoreCase("filter")) {
approver.type = ApproverType.Filter;
} else if (azr.getScope().equalsIgnoreCase("group")) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope().equalsIgnoreCase("dn")) {
approver.type = ApproverType.DN;
} else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope().equalsIgnoreCase("custom")) {
approver.type = ApproverType.Custom;
}
approver.constraint = azr.getConstraint();
//this.approvers.add(approver);
AzRule rule = new AzRule(azr.getScope(),azr.getConstraint(),azr.getClassName(),cfg,wf);
this.failureAzRules.add(rule);
approver.customAz = rule.getCustomAuthorization();
}
break;
default : throw new ProvisioningException("Unknown escalation failure action : " + att.getEscalationPolicy().getEscalationFailure().getAction());
}
}
}
}
@Override
public void init(WorkflowTaskType taskConfig) throws ProvisioningException {
}
@Override
public void reInit() throws ProvisioningException {
}
@Override
public boolean doTask(User user,Map<String,Object> request) throws ProvisioningException {
if (this.isOnHold()) {
this.setOnHold(false);
HashMap<String,Object> nrequest = new HashMap<String,Object>();
nrequest.putAll(request);
nrequest.put("APPROVAL_ID", this.id);
return this.runChildren(user,nrequest);
} else {
Connection con = null;
try {
con = this.getConfigManager().getProvisioningEngine().getApprovalDBConn();
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("INSERT INTO approvals (label,workflow,createTS) VALUES (?,?,?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1, this.label);
ps.setLong(2, this.getWorkflow().getId());
DateTime now = new DateTime();
ps.setTimestamp(3, new Timestamp(now.getMillis()));
ps.executeUpdate();
ResultSet keys = ps.getGeneratedKeys();
keys.next();
this.id = keys.getInt(1);
//request.put("APPROVAL_ID", Integer.toString(this.id));
request.put("APPROVAL_ID", this.id);
keys.close();
ps.close();
this.setOnHold(true);
Gson gson = new Gson();
String json = "";
synchronized (this.getWorkflow()) {
json = JsonWriter.objectToJson(this.getWorkflow());
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, this.getConfigManager().getSecretKey(this.getConfigManager().getCfg().getProvisioning().getApprovalDB().getEncryptionKey()));
byte[] encJson = cipher.doFinal(json.getBytes("UTF-8"));
String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));
Token token = new Token();
token.setEncryptedRequest(base64d);
token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));
//String base64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray()));
ps = con.prepareStatement("UPDATE approvals SET workflowObj=? WHERE id=?");
ps.setString(1, gson.toJson(token));
ps.setInt(2, this.id);
ps.executeUpdate();
boolean sendNotification = true;
if (request.containsKey(Approval.SEND_NOTIFICATION) && request.get(Approval.SEND_NOTIFICATION).equals("false")) {
sendNotification = false;
}
for (Approver approver : this.approvers) {
switch (approver.type) {
case StaticGroup : AzUtils.loadStaticGroupApprovers(this.id,this.emailTemplate,this.getConfigManager(),con,id,approver.constraint,sendNotification); break;
case Filter : AzUtils.loadFilterApprovers(this.id,this.emailTemplate,this.getConfigManager(),con,id,approver.constraint,sendNotification); break;
case DN : AzUtils.loadDNApprovers(this.id,this.emailTemplate,this.getConfigManager(),con,id,approver.constraint,sendNotification);break;
case Custom : AzUtils.loadCustomApprovers(this.id,this.emailTemplate,this.getConfigManager(),con,id,approver.constraint,sendNotification,approver.customAz);break;
}
}
con.commit();
return false;
} catch (SQLException e) {
throw new ProvisioningException("Could not create approval",e);
} catch (IOException e) {
throw new ProvisioningException("Could not store approval",e);
} catch (NoSuchAlgorithmException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} catch (NoSuchPaddingException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} catch (InvalidKeyException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} catch (IllegalBlockSizeException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} catch (BadPaddingException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} finally {
if (con != null) {
try {
con.rollback();
} catch (SQLException e1) {
}
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}
@Override
public boolean restartChildren() throws ProvisioningException {
return super.restartChildren(this.getWorkflow().getUser(),this.getWorkflow().getRequest());
}
public List<AzRule> getAzRules() {
return this.azRules;
}
public String getMailAttr() {
return mailAttr;
}
public String getFailureEmailSubject() {
return failureEmailSubject;
}
public String getFailureEmailMsg() {
return failureEmailMsg;
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("Approval - ").append(this.label).append(" - ").append(this.isOnHold());
return b.toString();
}
@Override
public String getLabel() {
StringBuffer b = new StringBuffer();
b.append("Approval ").append(this.label);
return b.toString();
}
public boolean updateAllowedApprovals(Connection con,ConfigManager cfg) throws ProvisioningException, SQLException {
boolean updateObj = false;
boolean localFail = false;
if (! this.failed && this.escalationRules != null && ! this.escalationRules.isEmpty()) {
boolean continueLooking = true;
for (EscalationRule rule : this.escalationRules) {
if (! rule.isCompleted() && continueLooking) {
RunOptions res = rule.shouldExecute(this.getWorkflow().getUser());
switch (res) {
case notReadyYet :
continueLooking = false;
break;
case run :
continueLooking = false;
this.azRules.clear();
this.azRules.addAll(rule.getAzRules());
this.approvers = new ArrayList<Approver>();
for (AzRule azr : this.azRules) {
Approver approver = new Approver();
if (azr.getScope() == ScopeType.Filter) {
approver.type = ApproverType.Filter;
} else if (azr.getScope() == ScopeType.Group) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope() == ScopeType.DN) {
approver.type = ApproverType.DN;
} else if (azr.getScope() == ScopeType.DynamicGroup) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope() == ScopeType.Custom) {
approver.type = ApproverType.Custom;
approver.customAz = azr.getCustomAuthorization();
}
approver.constraint = azr.getConstraint();
this.approvers.add(approver);
}
if (this.approvers.size() == 0 && this.failOnNoAZ) {
this.azRules = this.failureAzRules;
this.approvers = new ArrayList<Approver>();
for (AzRule azr : this.azRules) {
Approver approver = new Approver();
if (azr.getScope() == ScopeType.Filter) {
approver.type = ApproverType.Filter;
} else if (azr.getScope() == ScopeType.Group) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope() == ScopeType.DN) {
approver.type = ApproverType.DN;
} else if (azr.getScope() == ScopeType.DynamicGroup) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope() == ScopeType.Custom) {
approver.type = ApproverType.Custom;
approver.customAz = azr.getCustomAuthorization();
}
approver.constraint = azr.getConstraint();
this.approvers.add(approver);
}
}
updateObj = true;
rule.setCompleted(true);
PreparedStatement psAddEscalation = con.prepareStatement("INSERT INTO escalation (approval,whenTS) VALUES (?,?)");
psAddEscalation.setInt(1, this.id);
psAddEscalation.setTimestamp(2, new Timestamp(new DateTime().getMillis()));
psAddEscalation.executeUpdate();
psAddEscalation.close();
break;
case stopEscalating :
continueLooking = false;
localFail = true;
updateObj = true;
break;
}
}
}
}
boolean foundApprovers = false;
for (Approver approver : this.approvers) {
switch (approver.type) {
case StaticGroup : foundApprovers |= AzUtils.loadStaticGroupApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false); break;
case Filter : foundApprovers |= AzUtils.loadFilterApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false); break;
case DN : foundApprovers |= AzUtils.loadDNApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false);break;
case Custom : foundApprovers |= AzUtils.loadCustomApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false,approver.customAz);break;
}
}
if (! this.failed && (! foundApprovers || localFail)) {
if (this.failOnNoAZ) {
this.azRules = this.failureAzRules;
this.approvers = new ArrayList<Approver>();
for (AzRule azr : this.azRules) {
Approver approver = new Approver();
if (azr.getScope() == ScopeType.Filter) {
approver.type = ApproverType.Filter;
} else if (azr.getScope() == ScopeType.Group) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope() == ScopeType.DN) {
approver.type = ApproverType.DN;
} else if (azr.getScope() == ScopeType.DynamicGroup) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope() == ScopeType.Custom) {
approver.type = ApproverType.Custom;
approver.customAz = azr.getCustomAuthorization();
}
approver.constraint = azr.getConstraint();
this.approvers.add(approver);
}
}
for (Approver approver : this.approvers) {
switch (approver.type) {
case StaticGroup : AzUtils.loadStaticGroupApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false); break;
case Filter : AzUtils.loadFilterApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false); break;
case DN : AzUtils.loadDNApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false);break;
case Custom : AzUtils.loadCustomApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false,approver.customAz);break;
}
}
this.failed = true;
}
return updateObj;
}
public String getEmailTemplate() {
return emailTemplate;
}
public void setEmailTemplate(String emailTemplate) {
this.emailTemplate = emailTemplate;
}
public ArrayList<Approver> getApprovers() {
return approvers;
}
public void setApprovers(ArrayList<Approver> approvers) {
this.approvers = approvers;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setLabel(String label) {
this.label = label;
}
public void setAzRules(ArrayList<AzRule> azRules) {
this.azRules = azRules;
}
public void setMailAttr(String mailAttr) {
this.mailAttr = mailAttr;
}
public void setFailureEmailSubject(String failureEmailSubject) {
this.failureEmailSubject = failureEmailSubject;
}
public void setFailureEmailMsg(String failureEmailMsg) {
this.failureEmailMsg = failureEmailMsg;
}
public List<EscalationRule> getEscalationRules() {
return escalationRules;
}
public void setEscalationRules(List<EscalationRule> escalationRules) {
this.escalationRules = escalationRules;
}
public List<AzRule> getFailureAzRules() {
return failureAzRules;
}
public void setFailureAzRules(ArrayList<AzRule> failureAzRules) {
this.failureAzRules = failureAzRules;
}
public boolean isFailed() {
return failed;
}
public void setFailed(boolean failed) {
this.failed = failed;
}
}
class Approver {
ApproverType type;
String constraint;
CustomAuthorization customAz;
} | unison/unison-server-core/src/main/java/com/tremolosecurity/provisioning/tasks/Approval.java | /*
Copyright 2015 Tremolo Security, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.tremolosecurity.provisioning.tasks;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import com.cedarsoftware.util.io.JsonWriter;
import com.google.gson.Gson;
import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPAttributeSet;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPReferralException;
import com.novell.ldap.LDAPSearchResults;
import com.tremolosecurity.config.util.ConfigManager;
import com.tremolosecurity.config.xml.ApprovalType;
import com.tremolosecurity.config.xml.AzRuleType;
import com.tremolosecurity.config.xml.EscalationType;
import com.tremolosecurity.config.xml.WorkflowTaskType;
import com.tremolosecurity.json.Token;
import com.tremolosecurity.provisioning.core.ProvisioningException;
import com.tremolosecurity.provisioning.core.User;
import com.tremolosecurity.provisioning.core.Workflow;
import com.tremolosecurity.provisioning.core.WorkflowTaskImpl;
import com.tremolosecurity.provisioning.tasks.Approval.ApproverType;
import com.tremolosecurity.provisioning.tasks.escalation.EsclationRuleImpl;
import com.tremolosecurity.provisioning.util.AzUtils;
import com.tremolosecurity.provisioning.util.EscalationRule;
import com.tremolosecurity.provisioning.util.EscalationRule.RunOptions;
import com.tremolosecurity.proxy.az.AzRule;
import com.tremolosecurity.proxy.az.CustomAuthorization;
import com.tremolosecurity.proxy.az.VerifyEscalation;
import com.tremolosecurity.proxy.az.AzRule.ScopeType;
public class Approval extends WorkflowTaskImpl implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4449491970307931192L;
public static final String SEND_NOTIFICATION = "APPROVAL_SEND_NOTIFICATION";
static Logger logger = Logger.getLogger(Approval.class.getName());
public enum ApproverType {
StaticGroup,
DynamicGroup,
Filter,
DN,
Custom
};
String emailTemplate;
String label;
ArrayList<Approver> approvers;
List<AzRule> azRules;
List<EscalationRule> escalationRules;
String mailAttr;
String failureEmailSubject;
String failureEmailMsg;
boolean failOnNoAZ;
int id;
transient ConfigManager cfg;
private ArrayList<AzRule> failureAzRules;
boolean failed;
public Approval() {
}
public Approval(WorkflowTaskType taskConfig, ConfigManager cfg,Workflow wf)
throws ProvisioningException {
super(taskConfig, cfg,wf);
this.approvers = new ArrayList<Approver>();
this.azRules = new ArrayList<AzRule>();
this.failed = false;
ApprovalType att = (ApprovalType) taskConfig;
for (AzRuleType azr : att.getApprovers().getRule()) {
Approver approver = new Approver();
if (azr.getScope().equalsIgnoreCase("filter")) {
approver.type = ApproverType.Filter;
} else if (azr.getScope().equalsIgnoreCase("group")) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope().equalsIgnoreCase("dn")) {
approver.type = ApproverType.DN;
} else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope().equalsIgnoreCase("custom")) {
approver.type = ApproverType.Custom;
}
approver.constraint = azr.getConstraint();
this.approvers.add(approver);
AzRule rule = new AzRule(azr.getScope(),azr.getConstraint(),azr.getClassName(),cfg,wf);
this.azRules.add(rule);
approver.customAz = rule.getCustomAuthorization();
}
this.label = att.getLabel();
this.emailTemplate = att.getEmailTemplate();
this.mailAttr = att.getMailAttr();
this.failureEmailSubject = att.getFailureEmailSubject();
this.failureEmailMsg = att.getFailureEmailMsg();
this.escalationRules = new ArrayList<EscalationRule>();
if (att.getEscalationPolicy() != null) {
DateTime now = new DateTime();
for (EscalationType ert : att.getEscalationPolicy().getEscalation()) {
EscalationRule erule = new EsclationRuleImpl();
DateTime when;
if (ert.getExecuteAfterUnits().equalsIgnoreCase("sec")) {
when = now.plusSeconds(ert.getExecuteAfterTime());
} else if (ert.getExecuteAfterUnits().equals("min")) {
when = now.plusMinutes(ert.getExecuteAfterTime());
} else if (ert.getExecuteAfterUnits().equals("hr")) {
when = now.plusHours(ert.getExecuteAfterTime());
} else if (ert.getExecuteAfterUnits().equals("day")) {
when = now.plusDays(ert.getExecuteAfterTime());
} else if (ert.getExecuteAfterUnits().equals("wk")) {
when = now.plusWeeks(ert.getExecuteAfterTime());
} else {
throw new ProvisioningException("Unknown time unit : " + ert.getExecuteAfterUnits());
}
erule.setCompleted(false);
erule.setExecuteTS(when.getMillis());
if (ert.getValidateEscalationClass() != null && ! ert.getValidateEscalationClass().isEmpty() ) {
try {
erule.setVerify((VerifyEscalation) Class.forName(ert.getValidateEscalationClass()).newInstance());
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException e) {
throw new ProvisioningException("Could not initialize escalation rule",e);
}
} else {
erule.setVerify(null);
}
erule.setAzRules(new ArrayList<AzRule>());
for (AzRuleType azr : ert.getAzRules().getRule()) {
Approver approver = new Approver();
if (azr.getScope().equalsIgnoreCase("filter")) {
approver.type = ApproverType.Filter;
} else if (azr.getScope().equalsIgnoreCase("group")) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope().equalsIgnoreCase("dn")) {
approver.type = ApproverType.DN;
} else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope().equalsIgnoreCase("custom")) {
approver.type = ApproverType.Custom;
}
approver.constraint = azr.getConstraint();
//this.approvers.add(approver);
AzRule rule = new AzRule(azr.getScope(),azr.getConstraint(),azr.getClassName(),cfg,wf);
erule.getAzRules().add(rule);
approver.customAz = rule.getCustomAuthorization();
}
this.escalationRules.add(erule);
now = when;
}
switch (att.getEscalationPolicy().getEscalationFailure().getAction()) {
case "leave" :
this.failureAzRules = null;
this.failOnNoAZ = false;
break;
case "assign" :
this.failOnNoAZ = true;
this.failureAzRules = new ArrayList<AzRule>();
for (AzRuleType azr : att.getEscalationPolicy().getEscalationFailure().getAzRules().getRule()) {
Approver approver = new Approver();
if (azr.getScope().equalsIgnoreCase("filter")) {
approver.type = ApproverType.Filter;
} else if (azr.getScope().equalsIgnoreCase("group")) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope().equalsIgnoreCase("dn")) {
approver.type = ApproverType.DN;
} else if (azr.getScope().equalsIgnoreCase("dynamicGroup")) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope().equalsIgnoreCase("custom")) {
approver.type = ApproverType.Custom;
}
approver.constraint = azr.getConstraint();
//this.approvers.add(approver);
AzRule rule = new AzRule(azr.getScope(),azr.getConstraint(),azr.getClassName(),cfg,wf);
this.failureAzRules.add(rule);
approver.customAz = rule.getCustomAuthorization();
}
break;
default : throw new ProvisioningException("Unknown escalation failure action : " + att.getEscalationPolicy().getEscalationFailure().getAction());
}
}
}
@Override
public void init(WorkflowTaskType taskConfig) throws ProvisioningException {
}
@Override
public void reInit() throws ProvisioningException {
}
@Override
public boolean doTask(User user,Map<String,Object> request) throws ProvisioningException {
if (this.isOnHold()) {
this.setOnHold(false);
HashMap<String,Object> nrequest = new HashMap<String,Object>();
nrequest.putAll(request);
nrequest.put("APPROVAL_ID", this.id);
return this.runChildren(user,nrequest);
} else {
Connection con = null;
try {
con = this.getConfigManager().getProvisioningEngine().getApprovalDBConn();
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("INSERT INTO approvals (label,workflow,createTS) VALUES (?,?,?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1, this.label);
ps.setLong(2, this.getWorkflow().getId());
DateTime now = new DateTime();
ps.setTimestamp(3, new Timestamp(now.getMillis()));
ps.executeUpdate();
ResultSet keys = ps.getGeneratedKeys();
keys.next();
this.id = keys.getInt(1);
//request.put("APPROVAL_ID", Integer.toString(this.id));
request.put("APPROVAL_ID", this.id);
keys.close();
ps.close();
this.setOnHold(true);
Gson gson = new Gson();
String json = "";
synchronized (this.getWorkflow()) {
json = JsonWriter.objectToJson(this.getWorkflow());
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, this.getConfigManager().getSecretKey(this.getConfigManager().getCfg().getProvisioning().getApprovalDB().getEncryptionKey()));
byte[] encJson = cipher.doFinal(json.getBytes("UTF-8"));
String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));
Token token = new Token();
token.setEncryptedRequest(base64d);
token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));
//String base64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray()));
ps = con.prepareStatement("UPDATE approvals SET workflowObj=? WHERE id=?");
ps.setString(1, gson.toJson(token));
ps.setInt(2, this.id);
ps.executeUpdate();
boolean sendNotification = true;
if (request.containsKey(Approval.SEND_NOTIFICATION) && request.get(Approval.SEND_NOTIFICATION).equals("false")) {
sendNotification = false;
}
for (Approver approver : this.approvers) {
switch (approver.type) {
case StaticGroup : AzUtils.loadStaticGroupApprovers(this.id,this.emailTemplate,this.getConfigManager(),con,id,approver.constraint,sendNotification); break;
case Filter : AzUtils.loadFilterApprovers(this.id,this.emailTemplate,this.getConfigManager(),con,id,approver.constraint,sendNotification); break;
case DN : AzUtils.loadDNApprovers(this.id,this.emailTemplate,this.getConfigManager(),con,id,approver.constraint,sendNotification);break;
case Custom : AzUtils.loadCustomApprovers(this.id,this.emailTemplate,this.getConfigManager(),con,id,approver.constraint,sendNotification,approver.customAz);break;
}
}
con.commit();
return false;
} catch (SQLException e) {
throw new ProvisioningException("Could not create approval",e);
} catch (IOException e) {
throw new ProvisioningException("Could not store approval",e);
} catch (NoSuchAlgorithmException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} catch (NoSuchPaddingException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} catch (InvalidKeyException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} catch (IllegalBlockSizeException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} catch (BadPaddingException e) {
throw new ProvisioningException("Could not encrypt workflow object",e);
} finally {
if (con != null) {
try {
con.rollback();
} catch (SQLException e1) {
}
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}
@Override
public boolean restartChildren() throws ProvisioningException {
return super.restartChildren(this.getWorkflow().getUser(),this.getWorkflow().getRequest());
}
public List<AzRule> getAzRules() {
return this.azRules;
}
public String getMailAttr() {
return mailAttr;
}
public String getFailureEmailSubject() {
return failureEmailSubject;
}
public String getFailureEmailMsg() {
return failureEmailMsg;
}
public String toString() {
StringBuffer b = new StringBuffer();
b.append("Approval - ").append(this.label).append(" - ").append(this.isOnHold());
return b.toString();
}
@Override
public String getLabel() {
StringBuffer b = new StringBuffer();
b.append("Approval ").append(this.label);
return b.toString();
}
public boolean updateAllowedApprovals(Connection con,ConfigManager cfg) throws ProvisioningException, SQLException {
boolean updateObj = false;
boolean localFail = false;
if (! this.failed && this.escalationRules != null && ! this.escalationRules.isEmpty()) {
boolean continueLooking = true;
for (EscalationRule rule : this.escalationRules) {
if (! rule.isCompleted() && continueLooking) {
RunOptions res = rule.shouldExecute(this.getWorkflow().getUser());
switch (res) {
case notReadyYet :
continueLooking = false;
break;
case run :
continueLooking = false;
this.azRules.clear();
this.azRules.addAll(rule.getAzRules());
this.approvers = new ArrayList<Approver>();
for (AzRule azr : this.azRules) {
Approver approver = new Approver();
if (azr.getScope() == ScopeType.Filter) {
approver.type = ApproverType.Filter;
} else if (azr.getScope() == ScopeType.Group) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope() == ScopeType.DN) {
approver.type = ApproverType.DN;
} else if (azr.getScope() == ScopeType.DynamicGroup) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope() == ScopeType.Custom) {
approver.type = ApproverType.Custom;
approver.customAz = azr.getCustomAuthorization();
}
approver.constraint = azr.getConstraint();
this.approvers.add(approver);
}
if (this.approvers.size() == 0 && this.failOnNoAZ) {
this.azRules = this.failureAzRules;
this.approvers = new ArrayList<Approver>();
for (AzRule azr : this.azRules) {
Approver approver = new Approver();
if (azr.getScope() == ScopeType.Filter) {
approver.type = ApproverType.Filter;
} else if (azr.getScope() == ScopeType.Group) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope() == ScopeType.DN) {
approver.type = ApproverType.DN;
} else if (azr.getScope() == ScopeType.DynamicGroup) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope() == ScopeType.Custom) {
approver.type = ApproverType.Custom;
approver.customAz = azr.getCustomAuthorization();
}
approver.constraint = azr.getConstraint();
this.approvers.add(approver);
}
}
updateObj = true;
rule.setCompleted(true);
PreparedStatement psAddEscalation = con.prepareStatement("INSERT INTO escalation (approval,whenTS) VALUES (?,?)");
psAddEscalation.setInt(1, this.id);
psAddEscalation.setTimestamp(2, new Timestamp(new DateTime().getMillis()));
psAddEscalation.executeUpdate();
psAddEscalation.close();
break;
case stopEscalating :
continueLooking = false;
localFail = true;
updateObj = true;
break;
}
}
}
}
boolean foundApprovers = false;
for (Approver approver : this.approvers) {
switch (approver.type) {
case StaticGroup : foundApprovers |= AzUtils.loadStaticGroupApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false); break;
case Filter : foundApprovers |= AzUtils.loadFilterApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false); break;
case DN : foundApprovers |= AzUtils.loadDNApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false);break;
case Custom : foundApprovers |= AzUtils.loadCustomApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false,approver.customAz);break;
}
}
if (! this.failed && (! foundApprovers || localFail)) {
if (this.failOnNoAZ) {
this.azRules = this.failureAzRules;
this.approvers = new ArrayList<Approver>();
for (AzRule azr : this.azRules) {
Approver approver = new Approver();
if (azr.getScope() == ScopeType.Filter) {
approver.type = ApproverType.Filter;
} else if (azr.getScope() == ScopeType.Group) {
approver.type = ApproverType.StaticGroup;
} else if (azr.getScope() == ScopeType.DN) {
approver.type = ApproverType.DN;
} else if (azr.getScope() == ScopeType.DynamicGroup) {
approver.type = ApproverType.DynamicGroup;
} else if (azr.getScope() == ScopeType.Custom) {
approver.type = ApproverType.Custom;
approver.customAz = azr.getCustomAuthorization();
}
approver.constraint = azr.getConstraint();
this.approvers.add(approver);
}
}
for (Approver approver : this.approvers) {
switch (approver.type) {
case StaticGroup : AzUtils.loadStaticGroupApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false); break;
case Filter : AzUtils.loadFilterApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false); break;
case DN : AzUtils.loadDNApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false);break;
case Custom : AzUtils.loadCustomApprovers(this.id,this.emailTemplate,cfg,con,id,approver.constraint,false,approver.customAz);break;
}
}
this.failed = true;
}
return updateObj;
}
public String getEmailTemplate() {
return emailTemplate;
}
public void setEmailTemplate(String emailTemplate) {
this.emailTemplate = emailTemplate;
}
public ArrayList<Approver> getApprovers() {
return approvers;
}
public void setApprovers(ArrayList<Approver> approvers) {
this.approvers = approvers;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setLabel(String label) {
this.label = label;
}
public void setAzRules(ArrayList<AzRule> azRules) {
this.azRules = azRules;
}
public void setMailAttr(String mailAttr) {
this.mailAttr = mailAttr;
}
public void setFailureEmailSubject(String failureEmailSubject) {
this.failureEmailSubject = failureEmailSubject;
}
public void setFailureEmailMsg(String failureEmailMsg) {
this.failureEmailMsg = failureEmailMsg;
}
public List<EscalationRule> getEscalationRules() {
return escalationRules;
}
public void setEscalationRules(List<EscalationRule> escalationRules) {
this.escalationRules = escalationRules;
}
public List<AzRule> getFailureAzRules() {
return failureAzRules;
}
public void setFailureAzRules(ArrayList<AzRule> failureAzRules) {
this.failureAzRules = failureAzRules;
}
public boolean isFailed() {
return failed;
}
public void setFailed(boolean failed) {
this.failed = failed;
}
}
class Approver {
ApproverType type;
String constraint;
CustomAuthorization customAz;
} | Added a check for an escalation | unison/unison-server-core/src/main/java/com/tremolosecurity/provisioning/tasks/Approval.java | Added a check for an escalation |
|
Java | apache-2.0 | 6ac668deb555c9439559072043249848187200a9 | 0 | GIP-RECIA/esco-portail,doodelicious/uPortal,chasegawa/uPortal,jhelmer-unicon/uPortal,vbonamy/esup-uportal,chasegawa/uPortal,doodelicious/uPortal,ASU-Capstone/uPortal-Forked,pspaude/uPortal,bjagg/uPortal,drewwills/uPortal,GIP-RECIA/esup-uportal,drewwills/uPortal,andrewstuart/uPortal,timlevett/uPortal,mgillian/uPortal,jonathanmtran/uPortal,stalele/uPortal,vbonamy/esup-uportal,Jasig/uPortal-start,ASU-Capstone/uPortal,jl1955/uPortal5,jameswennmacher/uPortal,andrewstuart/uPortal,vertein/uPortal,Jasig/SSP-Platform,vertein/uPortal,phillips1021/uPortal,doodelicious/uPortal,jhelmer-unicon/uPortal,stalele/uPortal,MichaelVose2/uPortal,phillips1021/uPortal,kole9273/uPortal,vertein/uPortal,ASU-Capstone/uPortal-Forked,vbonamy/esup-uportal,ChristianMurphy/uPortal,GIP-RECIA/esco-portail,Mines-Albi/esup-uportal,jl1955/uPortal5,ASU-Capstone/uPortal,groybal/uPortal,jameswennmacher/uPortal,apetro/uPortal,ASU-Capstone/uPortal,jonathanmtran/uPortal,MichaelVose2/uPortal,joansmith/uPortal,ASU-Capstone/uPortal-Forked,kole9273/uPortal,EsupPortail/esup-uportal,cousquer/uPortal,timlevett/uPortal,MichaelVose2/uPortal,MichaelVose2/uPortal,ASU-Capstone/uPortal,ASU-Capstone/uPortal-Forked,mgillian/uPortal,jl1955/uPortal5,Jasig/uPortal,EsupPortail/esup-uportal,jameswennmacher/uPortal,timlevett/uPortal,bjagg/uPortal,chasegawa/uPortal,EsupPortail/esup-uportal,Mines-Albi/esup-uportal,jameswennmacher/uPortal,andrewstuart/uPortal,doodelicious/uPortal,kole9273/uPortal,phillips1021/uPortal,groybal/uPortal,GIP-RECIA/esup-uportal,jonathanmtran/uPortal,jl1955/uPortal5,Mines-Albi/esup-uportal,drewwills/uPortal,Jasig/SSP-Platform,groybal/uPortal,phillips1021/uPortal,EdiaEducationTechnology/uPortal,Mines-Albi/esup-uportal,vbonamy/esup-uportal,doodelicious/uPortal,kole9273/uPortal,jhelmer-unicon/uPortal,phillips1021/uPortal,jhelmer-unicon/uPortal,Jasig/uPortal-start,stalele/uPortal,jameswennmacher/uPortal,Jasig/SSP-Platform,EsupPortail/esup-uportal,Jasig/uPortal,MichaelVose2/uPortal,groybal/uPortal,cousquer/uPortal,apetro/uPortal,jl1955/uPortal5,joansmith/uPortal,ChristianMurphy/uPortal,andrewstuart/uPortal,drewwills/uPortal,apetro/uPortal,EdiaEducationTechnology/uPortal,EdiaEducationTechnology/uPortal,pspaude/uPortal,ChristianMurphy/uPortal,andrewstuart/uPortal,apetro/uPortal,jhelmer-unicon/uPortal,joansmith/uPortal,cousquer/uPortal,GIP-RECIA/esup-uportal,vbonamy/esup-uportal,vertein/uPortal,kole9273/uPortal,Mines-Albi/esup-uportal,joansmith/uPortal,pspaude/uPortal,joansmith/uPortal,Jasig/SSP-Platform,apetro/uPortal,pspaude/uPortal,EsupPortail/esup-uportal,Jasig/uPortal,EdiaEducationTechnology/uPortal,stalele/uPortal,Jasig/SSP-Platform,timlevett/uPortal,chasegawa/uPortal,GIP-RECIA/esup-uportal,ASU-Capstone/uPortal,ASU-Capstone/uPortal-Forked,groybal/uPortal,mgillian/uPortal,GIP-RECIA/esup-uportal,stalele/uPortal,GIP-RECIA/esco-portail,bjagg/uPortal,chasegawa/uPortal | /* Copyright 2003 - 2005 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package org.jasig.portal.channels.portlet;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pluto.PortletContainer;
import org.apache.pluto.PortletContainerImpl;
import org.apache.pluto.PortletContainerServices;
import org.apache.pluto.om.entity.PortletEntity;
import org.apache.pluto.om.portlet.PortletDefinition;
import org.apache.pluto.om.window.PortletWindow;
import org.apache.pluto.services.information.DynamicInformationProvider;
import org.apache.pluto.services.information.InformationProviderAccess;
import org.apache.pluto.services.information.PortletActionProvider;
import org.apache.pluto.services.property.PropertyManager;
import org.apache.pluto.services.property.PropertyManagerService;
import org.jasig.portal.ChannelCacheKey;
import org.jasig.portal.ChannelDefinition;
import org.jasig.portal.ChannelRegistryStoreFactory;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.ChannelRuntimeProperties;
import org.jasig.portal.ChannelStaticData;
import org.jasig.portal.ICacheable;
import org.jasig.portal.ICharacterChannel;
import org.jasig.portal.IDirectResponse;
import org.jasig.portal.IPrivileged;
import org.jasig.portal.PortalControlStructures;
import org.jasig.portal.PortalEvent;
import org.jasig.portal.PortalException;
import org.jasig.portal.container.PortletServlet;
import org.jasig.portal.container.om.common.ObjectIDImpl;
import org.jasig.portal.container.om.entity.PortletApplicationEntityImpl;
import org.jasig.portal.container.om.entity.PortletEntityImpl;
import org.jasig.portal.container.om.portlet.PortletApplicationDefinitionImpl;
import org.jasig.portal.container.om.portlet.PortletDefinitionImpl;
import org.jasig.portal.container.om.portlet.UserAttributeImpl;
import org.jasig.portal.container.om.portlet.UserAttributeListImpl;
import org.jasig.portal.container.om.window.PortletWindowImpl;
import org.jasig.portal.container.services.FactoryManagerServiceImpl;
import org.jasig.portal.container.services.PortletContainerEnvironmentImpl;
import org.jasig.portal.container.services.information.DynamicInformationProviderImpl;
import org.jasig.portal.container.services.information.InformationProviderServiceImpl;
import org.jasig.portal.container.services.information.PortletStateManager;
import org.jasig.portal.container.services.log.LogServiceImpl;
import org.jasig.portal.container.services.property.PropertyManagerServiceImpl;
import org.jasig.portal.container.servlet.DummyParameterRequestWrapper;
import org.jasig.portal.container.servlet.PortletAttributeRequestWrapper;
import org.jasig.portal.container.servlet.PortletParameterRequestWrapper;
import org.jasig.portal.container.servlet.ServletObjectAccess;
import org.jasig.portal.container.servlet.ServletRequestImpl;
import org.jasig.portal.layout.node.IUserLayoutChannelDescription;
import org.jasig.portal.properties.PropertiesManager;
import org.jasig.portal.security.IOpaqueCredentials;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.security.ISecurityContext;
import org.jasig.portal.security.provider.NotSoOpaqueCredentials;
import org.jasig.portal.utils.NullOutputStream;
import org.jasig.portal.utils.SAXHelper;
import org.xml.sax.ContentHandler;
/**
* A JSR 168 Portlet adapter that presents a portlet
* through the uPortal channel interface.
* <p>
* There is a related channel type called
* "Portlet Adapter" that is included with uPortal, so to use
* this channel, just select the "Portlet" type when publishing.
* </p>
* <p>
* Note: A portlet can specify the String "password" in the
* user attributes section of the portlet.xml. In this is done,
* this adapter will look for the user's cached password. If
* the user's password is being stored in memory by a caching
* security context, the adapter will consult the cache to fill the
* request for the attribute. If the user's password is not cached,
* <code>null</code> will be set for the attributes value.
* </p>
* @author Ken Weiner, [email protected]
* @version $Revision$
*/
public class CPortletAdapter
implements ICharacterChannel, IPrivileged, ICacheable, IDirectResponse, IPortletAdaptor {
protected final Log log = LogFactory.getLog(getClass());
private static boolean portletContainerInitialized;
private static PortletContainer portletContainer;
private static ServletConfig servletConfig;
private static final ChannelCacheKey systemCacheKey;
private static final ChannelCacheKey instanceCacheKey;
private static final String uniqueContainerName =
PropertiesManager.getProperty("org.jasig.portal.channels.portlet.CPortletAdapter.uniqueContainerName", "Pluto-in-uPortal");
// Publish parameters expected by this channel
private static final String portletDefinitionIdParamName = "portletDefinitionId";
public static final String portletPreferenceNamePrefix = "PORTLET.";
private ChannelStaticData staticData = null;
private ChannelRuntimeData runtimeData = null;
private PortalControlStructures pcs = null;
private boolean portletWindowInitialized = false;
private PortletWindow portletWindow = null;
private Map userInfo = null;
private boolean receivedEvent = false;
private boolean focused = false;
private PortletMode newPortletMode = null;
private long lastRenderTime = Long.MIN_VALUE;
private String expirationCache = null;
private WindowState newWindowState = null;
private PortletSession portletSession = null;
private Map requestParams = null;
static {
portletContainerInitialized = false;
// Initialize cache keys
ChannelCacheKey key = new ChannelCacheKey();
key.setKeyScope(ChannelCacheKey.SYSTEM_KEY_SCOPE);
key.setKey("SYSTEM_SCOPE_KEY");
systemCacheKey = key;
key = new ChannelCacheKey();
key.setKeyScope(ChannelCacheKey.INSTANCE_KEY_SCOPE);
key.setKey("INSTANCE_SCOPE_KEY");
instanceCacheKey = key;
}
/**
* Receive the servlet config from uPortal's PortalSessionManager servlet.
* Pluto needs access to this object from serveral places.
* @param config the servlet config
*/
public static void setServletConfig(ServletConfig config) {
servletConfig = config;
}
/**
*
* @throws PortalException
*/
private synchronized static void initPortletContainer() throws PortalException {
if (!portletContainerInitialized) {
portletContainerInitialized = true;
try {
PortletContainerEnvironmentImpl environment = new PortletContainerEnvironmentImpl();
LogServiceImpl logService = new LogServiceImpl();
FactoryManagerServiceImpl factorManagerService = new FactoryManagerServiceImpl();
InformationProviderServiceImpl informationProviderService = new InformationProviderServiceImpl();
PropertyManagerService propertyManagerService = new PropertyManagerServiceImpl();
logService.init(servletConfig, null);
factorManagerService.init(servletConfig, null);
informationProviderService.init(servletConfig, null);
environment.addContainerService(logService);
environment.addContainerService(factorManagerService);
environment.addContainerService(informationProviderService);
environment.addContainerService(propertyManagerService);
//Call added in case the context has been re-loaded
PortletContainerServices.destroyReference(uniqueContainerName);
portletContainer = new PortletContainerImpl();
portletContainer.init(uniqueContainerName, servletConfig, environment, new Properties());
} catch (Exception e) {
String message = "Initialization of the portlet container failed.";
//log.error( message, e);
throw new PortalException(message, e);
}
}
}
protected void initPortletWindow() throws PortalException {
try {
initPortletContainer();
PortletContainerServices.prepare(uniqueContainerName);
// Get the portlet definition Id which must be specified as a publish
// parameter. The syntax of the ID is [portlet-context-name].[portlet-name]
String portletDefinitionId = staticData.getParameter(portletDefinitionIdParamName);
if (portletDefinitionId == null) {
throw new PortalException("Missing publish parameter '" + portletDefinitionIdParamName + "'");
}
// Create the PortletDefinition
PortletDefinitionImpl portletDefinition = (PortletDefinitionImpl)InformationProviderAccess.getStaticProvider().getPortletDefinition(ObjectIDImpl.createFromString(portletDefinitionId));
if (portletDefinition == null) {
throw new PortalException("Unable to find portlet definition for ID '" + portletDefinitionId + "'");
}
ChannelDefinition channelDefinition = ChannelRegistryStoreFactory.getChannelRegistryStoreImpl().getChannelDefinition(Integer.parseInt(staticData.getChannelPublishId()));
portletDefinition.setChannelDefinition(channelDefinition);
portletDefinition.loadPreferences();
// Create the PortletApplicationEntity
final PortletApplicationEntityImpl portAppEnt = new PortletApplicationEntityImpl();
portAppEnt.setId(portletDefinition.getId().toString());
portAppEnt.setPortletApplicationDefinition(portletDefinition.getPortletApplicationDefinition());
// Create the PortletEntity
PortletEntityImpl portletEntity = new PortletEntityImpl();
portletEntity.setId(staticData.getChannelPublishId());
portletEntity.setPortletDefinition(portletDefinition);
portletEntity.setPortletApplicationEntity(portAppEnt);
portletEntity.setUserLayout(pcs.getUserPreferencesManager().getUserLayoutManager().getUserLayout());
portletEntity.setChannelDescription((IUserLayoutChannelDescription)pcs.getUserPreferencesManager().getUserLayoutManager().getNode(staticData.getChannelSubscribeId()));
portletEntity.setPerson(staticData.getPerson());
portletEntity.loadPreferences();
// Add the user information into the request See PLT.17.2.
if (userInfo == null) {
UserAttributeListImpl userAttributeList = ((PortletApplicationDefinitionImpl)portletDefinition.getPortletApplicationDefinition()).getUserAttributes();
// here we ask an overridable method to get the user attributes.
// you can extend CPortletAdapter to change the implementation of
// how we get user attributes. This whole initPortletWindow method
// is also overridable.
//
// Note that we will only call getUserInfo() once.
userInfo = getUserInfo(staticData, userAttributeList);
if (log.isTraceEnabled()) {
//log.trace("For user [" + uid + "] got user info : [" + userInfo + "]");
}
}
// Wrap the request
ServletRequestImpl wrappedRequest = new ServletRequestImpl(pcs.getHttpServletRequest(), staticData.getPerson(), portletDefinition.getInitSecurityRoleRefSet());
// Now create the PortletWindow and hold a reference to it
PortletWindowImpl pw = new PortletWindowImpl();
pw.setId(staticData.getChannelSubscribeId());
pw.setPortletEntity(portletEntity);
pw.setChannelRuntimeData(runtimeData);
pw.setHttpServletRequest(wrappedRequest);
portletWindow = pw;
// Ask the container to load the portlet
synchronized(this) {
portletContainer.portletLoad(portletWindow, wrappedRequest, pcs.getHttpServletResponse());
}
portletWindowInitialized = true;
} catch (Exception e) {
String message = "Initialization of the portlet container failed.";
log.error( message, e);
throw new PortalException(message, e);
} finally {
PortletContainerServices.release();
}
}
/**
* Sets channel runtime properties.
* @return channel runtime properties
*/
public ChannelRuntimeProperties getRuntimeProperties() {
return new ChannelRuntimeProperties();
}
/**
* React to portal events.
* Removes channel state from the channel state map when the session expires.
* @param ev a portal event
*/
public void receiveEvent(PortalEvent ev) {
try {
PortletContainerServices.prepare(uniqueContainerName);
receivedEvent =true;
switch (ev.getEventNumber()) {
// Detect portlet mode changes
// Cannot use the PortletActionProvider to change modes here. It uses
// PortletWindow information to store the changes and the window is
// not current at this point.
case PortalEvent.EDIT_BUTTON_EVENT:
newPortletMode = PortletMode.EDIT;
break;
case PortalEvent.HELP_BUTTON_EVENT:
newPortletMode = PortletMode.HELP;
break;
case PortalEvent.ABOUT_BUTTON_EVENT:
// We might want to consider a custom ABOUT mode here
break;
//Detect portlet window state changes
case PortalEvent.MINIMIZE_EVENT:
newWindowState = WindowState.MINIMIZED;
break;
case PortalEvent.MAXIMIZE_EVENT:
newWindowState = WindowState.NORMAL;
break;
case PortalEvent.DETACH_BUTTON_EVENT:
newWindowState = WindowState.MAXIMIZED;
break;
//Detect end of session or portlet removed from layout
case PortalEvent.UNSUBSCRIBE:
//User is removing this portlet from their layout, remove all
//the preferences they have stored for it.
PortletEntityImpl pe = (PortletEntityImpl)portletWindow.getPortletEntity();
try {
pe.removePreferences();
}
catch (Exception e) {
log.error(e,e);
}
case PortalEvent.SESSION_DONE:
// For both SESSION_DONE and UNSUBSCRIBE, we might want to
// release resources here if we need to
PortletWindowImpl windowImpl = (PortletWindowImpl)portletWindow;
try {
PortletStateManager.clearState(windowImpl);
}
catch (IllegalStateException ise) {
//Ignore an illegal state when the PortletStateManager tries to
//access the session if it has already been destroyed.
if (log.isDebugEnabled()) {
log.debug("IllegalStateException attempting to clear portlet state for windowImpl " + windowImpl);
}
} catch (Exception e) {
// regardless of what went wrong clearing portlet state, need to continue the event handling workflow
// therefore, log error and ignore
log.error("Exception attempting to clear portlet state for windowImpl " + windowImpl);
}
// Invalidate portlet session
if (portletSession != null) {
try {
portletSession.invalidate();
}
catch (Exception e) {
log.error(e,e);
}
}
break;
default:
break;
}
} finally {
PortletContainerServices.release();
}
}
/**
* Sets the channel static data.
* @param sd the channel static data
* @throws org.jasig.portal.PortalException
*/
public void setStaticData(ChannelStaticData sd) throws PortalException {
staticData = sd;
try {
// Register this portlet's channel subscribe ID in the JNDI context
// this is probably not necessary since afaik nothing other than this
// portlet is reading this List. -andrew petro
List portletIds = (List)sd.getJNDIContext().lookup("/portlet-ids");
portletIds.add(sd.getChannelSubscribeId());
} catch (Exception e) {
throw new PortalException("Error accessing /portlet-ids JNDI context.", e);
}
}
/**
* Sets the channel runtime data.
* @param rd the channel runtime data
* @throws org.jasig.portal.PortalException
*/
public void setRuntimeData(ChannelRuntimeData rd) throws PortalException {
runtimeData =rd;
if (!this.portletWindowInitialized) {
this.initPortletWindow();
}
try {
PortletContainerServices.prepare(uniqueContainerName);
final PortletWindowImpl portletWindowimp = (PortletWindowImpl)portletWindow;
final PortletEntity portletEntity = portletWindow.getPortletEntity();
final PortletDefinition portletDef = portletEntity.getPortletDefinition();
final HttpServletRequest baseRequest = pcs.getHttpServletRequest();
HttpServletRequest wrappedRequest = new ServletRequestImpl(baseRequest, staticData.getPerson(), portletDef.getInitSecurityRoleRefSet());
//Wrap the request to scope attributes to this portlet instance
wrappedRequest = new PortletAttributeRequestWrapper(wrappedRequest);
//Set up request attributes (user info, portal session, etc...)
setupRequestAttributes(wrappedRequest);
// Put the current runtime data and wrapped request into the portlet window
portletWindowimp.setChannelRuntimeData(rd);
portletWindowimp.setHttpServletRequest(wrappedRequest);
// Get the portlet url manager which will analyze the request parameters
DynamicInformationProvider dip = InformationProviderAccess.getDynamicProvider(wrappedRequest);
PortletStateManager psm = ((DynamicInformationProviderImpl)dip).getPortletStateManager(portletWindow);
PortletActionProvider pap = dip.getPortletActionProvider(portletWindow);
//If portlet is rendering as root, change mode to maximized, otherwise minimized
if (!psm.isAction() && rd.isRenderingAsRoot()) {
if (WindowState.MINIMIZED.equals(newWindowState)) {
pap.changePortletWindowState(WindowState.MINIMIZED);
}
else {
pap.changePortletWindowState(WindowState.MAXIMIZED);
}
} else if (newWindowState != null) {
pap.changePortletWindowState(newWindowState);
}
else if (!psm.isAction()) {
pap.changePortletWindowState(WindowState.NORMAL);
}
newWindowState =null;
//Check for a portlet mode change
if (newPortletMode != null) {
pap.changePortletMode(newPortletMode);
PortletStateManager.setMode(portletWindow, newPortletMode);
}
newPortletMode = null;
// Process action if this is the targeted channel and the URL is an action URL
if (rd.isTargeted() && psm.isAction()) {
//Create a sink to throw out and output (portlets can't output content during an action)
PrintWriter pw = new PrintWriter(new NullOutputStream());
HttpServletResponse wrappedResponse = ServletObjectAccess.getStoredServletResponse(pcs.getHttpServletResponse(), pw);
try {
//See if a WindowState change was requested for an ActionURL
final String newWindowStateName = wrappedRequest.getParameter(PortletStateManager.UP_WINDOW_STATE);
if (newWindowStateName != null) {
pap.changePortletWindowState(new WindowState(newWindowStateName));
}
HttpServletRequest wrappedPortletRequest = new PortletParameterRequestWrapper(wrappedRequest);
portletContainer.processPortletAction(portletWindow, wrappedPortletRequest, wrappedResponse);
} catch (Exception e) {
throw new PortalException(e);
}
}
} finally {
PortletContainerServices.release();
}
}
/**
* Sets the portal control structures.
* @param pcs1 the portal control structures
* @throws org.jasig.portal.PortalException
*/
public void setPortalControlStructures(PortalControlStructures pcs1) throws PortalException {
this.pcs = pcs1;
}
/**
* Output channel content to the portal as raw characters
* @param pw a print writer
*/
public void renderCharacters(PrintWriter pw) throws PortalException {
if (!portletWindowInitialized) {
initPortletWindow();
}
try {
String markupString = getMarkup();
pw.print(markupString);
} catch (Exception e) {
throw new PortalException(e);
}
}
/**
* Output channel content to the portal. This version of the
* render method is normally not used since this is a "character channel".
* @param out a sax document handler
*/
public void renderXML(ContentHandler out) throws PortalException {
if (!portletWindowInitialized) {
initPortletWindow();
}
try {
String markupString = getMarkup();
// Output content. This assumes that markupString
// is well-formed. Consider changing to a character
// channel when it becomes available. Until we use the
// character channel, these <div> tags will be necessary.
SAXHelper.outputContent(out, "<div>" + markupString + "</div>");
} catch (Exception e) {
throw new PortalException(e);
}
}
/**
* This is where we do the real work of getting the markup.
* This is called from both renderXML() and renderCharacters().
* @return markup representing channel content
*/
protected synchronized String getMarkup() throws PortalException {
try {
PortletContainerServices.prepare(uniqueContainerName);
final PortletEntity portletEntity = portletWindow.getPortletEntity();
final PortletDefinition portletDef = portletEntity.getPortletDefinition();
final HttpServletRequest baseRequest = pcs.getHttpServletRequest();
HttpServletRequest wrappedRequest = new ServletRequestImpl(baseRequest, staticData.getPerson(), portletDef.getInitSecurityRoleRefSet());
//Wrap the request to scope attributes to this portlet instance
wrappedRequest = new PortletAttributeRequestWrapper(wrappedRequest);
//Set up request attributes (user info, portal session, etc...)
setupRequestAttributes(wrappedRequest);
final StringWriter sw = new StringWriter();
HttpServletResponse wrappedResponse = ServletObjectAccess.getStoredServletResponse(pcs.getHttpServletResponse(), new PrintWriter(sw));
//Use the parameters from the last request so the portlet maintains it's state
final ChannelRuntimeData rd = runtimeData;
if (!rd.isTargeted() && requestParams != null) {
wrappedRequest = new DummyParameterRequestWrapper(wrappedRequest, requestParams);
}
//Hide the request parameters if this portlet isn't targeted
else {
wrappedRequest = new PortletParameterRequestWrapper(wrappedRequest);
requestParams = wrappedRequest.getParameterMap();
}
portletContainer.renderPortlet(portletWindow, wrappedRequest, wrappedResponse);
// Track PortletSession object
PortletSession ps = (PortletSession)wrappedRequest.getAttribute(PortletServlet.SESSION_MONITOR_ATTRIBUTE);
if (ps != null) {
portletSession = ps;
}
//Support for the portlet modifying it's cache timeout
final Map properties = PropertyManager.getRequestProperties(portletWindow, wrappedRequest);
final String[] exprCacheTimeStr = (String[])properties.get(RenderResponse.EXPIRATION_CACHE);
if (exprCacheTimeStr != null && exprCacheTimeStr.length > 0) {
try {
Integer.parseInt(exprCacheTimeStr[0]); //Check for valid number
expirationCache = exprCacheTimeStr[0];
}
catch (NumberFormatException nfe) {
log.error("The specified RenderResponse.EXPIRATION_CACHE value of (" + exprCacheTimeStr + ") is not a number.", nfe);
throw nfe;
}
}
//Keep track of the last time the portlet was successfully rendered
lastRenderTime = System.currentTimeMillis();
//Return the content
return sw.toString();
} catch (Throwable t) {
log.error(t, t);
throw new PortalException(t);
} finally {
PortletContainerServices.release();
}
}
/**
* Generates a channel cache key. The key scope is set to be system-wide
* when the channel is anonymously accessed, otherwise it is set to be
* instance-wide. The caching implementation here is simple and may not
* handle all cases. It may also violate the Portlet Specification so
* this obviously needs further discussion.
* @return the channel cache key
*/
public ChannelCacheKey generateKey() {
ChannelCacheKey cck = null;
// Anonymously accessed pages can be cached system-wide
if(staticData.getPerson().isGuest()) {
cck = systemCacheKey;
} else {
cck = instanceCacheKey;
}
return cck;
}
/**
* Determines whether the cached content for this channel is still valid.
* <p>
* Return <code>true</code> when:<br>
* <ol>
* <li>We have not just received an event</li>
* <li>No runtime parameters are sent to the channel</li>
* <li>The focus hasn't switched.</li>
* </ol>
* Otherwise, return <code>false</code>.
* <p>
* In other words, cache the content in all cases <b>except</b>
* for when a user clicks a channel button, a link or form button within the channel,
* or the <i>focus</i> or <i>unfocus</i> button.
* @param validity the validity object
* @return <code>true</code> if the cache is still valid, otherwise <code>false</code>
*/
public boolean isCacheValid(Object validity) {
PortletEntity pe = portletWindow.getPortletEntity();
PortletDefinition pd = pe.getPortletDefinition();
//Expiration based caching support for the portlet.
String exprCacheTimeStr = pd.getExpirationCache();
try {
if (expirationCache != null)
exprCacheTimeStr = expirationCache;
int exprCacheTime = Integer.parseInt(exprCacheTimeStr);
if (exprCacheTime == 0) {
return false;
}
else if (exprCacheTime > 0) {
if ((lastRenderTime + (exprCacheTime * 1000)) < System.currentTimeMillis())
return false;
}
}
catch (Exception e) {
if (log.isWarnEnabled()) {
String portletId = staticData.getParameter(portletDefinitionIdParamName);
log.warn("Error parsing portlet expiration time (" + exprCacheTimeStr + ") for portlet (" + portletId + ").", e);
}
}
// Determine if the channel focus has changed
boolean previouslyFocused = focused;
focused = runtimeData.isRenderingAsRoot();
boolean focusHasSwitched = focused != previouslyFocused;
// Dirty cache only when we receive an event, one or more request params, or a change in focus
boolean cacheValid = !(receivedEvent || runtimeData.isTargeted() || focusHasSwitched);
receivedEvent = false;
return cacheValid;
}
//***************************************************************
// IDirectResponse methods
//***************************************************************
public synchronized void setResponse(HttpServletResponse response) {
try {
PortletContainerServices.prepare(uniqueContainerName);
final PortletEntity portletEntity = portletWindow.getPortletEntity();
final PortletDefinition portletDef = portletEntity.getPortletDefinition();
final HttpServletRequest baseRequest = pcs.getHttpServletRequest();
HttpServletRequest wrappedRequest = new ServletRequestImpl(baseRequest, staticData.getPerson(), portletDef.getInitSecurityRoleRefSet());
//Wrap the request to scope attributes to this portlet instance
wrappedRequest = new PortletAttributeRequestWrapper(wrappedRequest);
//Set up request attributes (user info, portal session, etc...)
setupRequestAttributes(wrappedRequest);
//Hide the request parameters if this portlet isn't targeted
wrappedRequest = new PortletParameterRequestWrapper(wrappedRequest);
//Since the portlet is rendering through IDirectResponse change the window state to "exclusive"
DynamicInformationProvider dip = InformationProviderAccess.getDynamicProvider(pcs.getHttpServletRequest());
PortletActionProvider pap = dip.getPortletActionProvider(portletWindow);
pap.changePortletWindowState(new WindowState("exclusive"));
HttpServletResponse wrappedResponse = new OutputStreamResponseWrapper(response);
//render the portlet
portletContainer.renderPortlet(portletWindow, wrappedRequest, wrappedResponse);
// Track PortletSession object
PortletSession ps = (PortletSession)wrappedRequest.getAttribute(PortletServlet.SESSION_MONITOR_ATTRIBUTE);
if (ps != null) {
portletSession = ps;
}
//Ensure all the data gets written out
wrappedResponse.flushBuffer();
} catch (Throwable t) {
log.error(t, t);
} finally {
PortletContainerServices.release();
}
}
//***************************************************************
// Helper methods
//***************************************************************
/**
* Retrieves the users password by iterating over
* the user's security contexts and returning the first
* available cached password.
*
* @param baseContext The security context to start looking for a password from.
* @return the users password
*/
private String getPassword(ISecurityContext baseContext) {
String password = null;
IOpaqueCredentials oc = baseContext.getOpaqueCredentials();
if (oc instanceof NotSoOpaqueCredentials) {
NotSoOpaqueCredentials nsoc = (NotSoOpaqueCredentials)oc;
password = nsoc.getCredentials();
}
// If still no password, loop through subcontexts to find cached credentials
Enumeration en = baseContext.getSubContexts();
while (password == null && en.hasMoreElements()) {
ISecurityContext subContext = (ISecurityContext)en.nextElement();
password = this.getPassword(subContext);
}
return password;
}
/**
* Adds the appropriate information to the request attributes of the portlet.
*
* This is an extension point. You can override this method to set other
* request attributes.
*
* @param request The request to add the attributes to
*/
protected void setupRequestAttributes(final HttpServletRequest request) {
//Add the user information map
request.setAttribute(PortletRequest.USER_INFO, userInfo);
}
/**
* Get the Map of portlet user attribute names to portlet user attribute values.
*
* This is an extension point. You can extend CPortletAdapter and override this
* method to implement the particular user attribute Map creation strategy that
* you need to implement. Such strategies might rename uPortal
* user attributes to names that your particular portlet knows how to consume,
* transform the user attribute values to forms expected by your portlet, add
* additional attributes, convey a CAS proxy ticket or other security token.
* This extension point is the way to accomodate the particular user attributes
* particular portlets require.
*
* The default implementation of this method includes in the userInfo Map
* those uPortal IPerson attributes matching entries in the list of attributes the
* Portlet declared it wanted. Additionally, the default implementation copies
* the cached user password if the Portlet declares it wants the user attribute
* 'password'.
*
* @param staticData data associated with the particular instance of the portlet window for the particular
* user session
* @param userAttributes the user attributes requested by the Portlet
* @return a Map from portlet user attribute names to portlet user attribute values.
*/
protected Map getUserInfo(ChannelStaticData staticData, UserAttributeListImpl userAttributes) {
final String PASSWORD_ATTR = "password";
Map userInfo = new HashMap();
IPerson person = staticData.getPerson();
if (person.getSecurityContext().isAuthenticated()) {
// for each attribute the Portlet requested
for (Iterator iter = userAttributes.iterator(); iter.hasNext(); ) {
UserAttributeImpl userAttribute = (UserAttributeImpl)iter.next();
String attName = userAttribute.getName();
String attValue = (String)person.getAttribute(attName);
if ((attValue == null || attValue.equals("")) && attName.equals(PASSWORD_ATTR)) {
attValue = getPassword(person.getSecurityContext());
}
userInfo.put(attName, attValue);
}
}
return userInfo;
}
}
| source/org/jasig/portal/channels/portlet/CPortletAdapter.java | /* Copyright 2003 - 2005 The JA-SIG Collaborative. All rights reserved.
* See license distributed with this file and
* available online at http://www.uportal.org/license.html
*/
package org.jasig.portal.channels.portlet;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pluto.PortletContainer;
import org.apache.pluto.PortletContainerImpl;
import org.apache.pluto.PortletContainerServices;
import org.apache.pluto.om.entity.PortletEntity;
import org.apache.pluto.om.portlet.PortletDefinition;
import org.apache.pluto.om.window.PortletWindow;
import org.apache.pluto.services.information.DynamicInformationProvider;
import org.apache.pluto.services.information.InformationProviderAccess;
import org.apache.pluto.services.information.PortletActionProvider;
import org.apache.pluto.services.property.PropertyManager;
import org.apache.pluto.services.property.PropertyManagerService;
import org.jasig.portal.ChannelCacheKey;
import org.jasig.portal.ChannelDefinition;
import org.jasig.portal.ChannelRegistryStoreFactory;
import org.jasig.portal.ChannelRuntimeData;
import org.jasig.portal.ChannelRuntimeProperties;
import org.jasig.portal.ChannelStaticData;
import org.jasig.portal.ICacheable;
import org.jasig.portal.ICharacterChannel;
import org.jasig.portal.IDirectResponse;
import org.jasig.portal.IPrivileged;
import org.jasig.portal.PortalControlStructures;
import org.jasig.portal.PortalEvent;
import org.jasig.portal.PortalException;
import org.jasig.portal.container.PortletServlet;
import org.jasig.portal.container.om.common.ObjectIDImpl;
import org.jasig.portal.container.om.entity.PortletApplicationEntityImpl;
import org.jasig.portal.container.om.entity.PortletEntityImpl;
import org.jasig.portal.container.om.portlet.PortletApplicationDefinitionImpl;
import org.jasig.portal.container.om.portlet.PortletDefinitionImpl;
import org.jasig.portal.container.om.portlet.UserAttributeImpl;
import org.jasig.portal.container.om.portlet.UserAttributeListImpl;
import org.jasig.portal.container.om.window.PortletWindowImpl;
import org.jasig.portal.container.services.FactoryManagerServiceImpl;
import org.jasig.portal.container.services.PortletContainerEnvironmentImpl;
import org.jasig.portal.container.services.information.DynamicInformationProviderImpl;
import org.jasig.portal.container.services.information.InformationProviderServiceImpl;
import org.jasig.portal.container.services.information.PortletStateManager;
import org.jasig.portal.container.services.log.LogServiceImpl;
import org.jasig.portal.container.services.property.PropertyManagerServiceImpl;
import org.jasig.portal.container.servlet.DummyParameterRequestWrapper;
import org.jasig.portal.container.servlet.PortletAttributeRequestWrapper;
import org.jasig.portal.container.servlet.PortletParameterRequestWrapper;
import org.jasig.portal.container.servlet.ServletObjectAccess;
import org.jasig.portal.container.servlet.ServletRequestImpl;
import org.jasig.portal.layout.node.IUserLayoutChannelDescription;
import org.jasig.portal.properties.PropertiesManager;
import org.jasig.portal.security.IOpaqueCredentials;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.security.ISecurityContext;
import org.jasig.portal.security.provider.NotSoOpaqueCredentials;
import org.jasig.portal.utils.NullOutputStream;
import org.jasig.portal.utils.SAXHelper;
import org.xml.sax.ContentHandler;
/**
* A JSR 168 Portlet adapter that presents a portlet
* through the uPortal channel interface.
* <p>
* There is a related channel type called
* "Portlet Adapter" that is included with uPortal, so to use
* this channel, just select the "Portlet" type when publishing.
* </p>
* <p>
* Note: A portlet can specify the String "password" in the
* user attributes section of the portlet.xml. In this is done,
* this adapter will look for the user's cached password. If
* the user's password is being stored in memory by a caching
* security context, the adapter will consult the cache to fill the
* request for the attribute. If the user's password is not cached,
* <code>null</code> will be set for the attributes value.
* </p>
* @author Ken Weiner, [email protected]
* @version $Revision$
*/
public class CPortletAdapter
implements ICharacterChannel, IPrivileged, ICacheable, IDirectResponse, IPortletAdaptor {
protected final Log log = LogFactory.getLog(getClass());
private static boolean portletContainerInitialized;
private static PortletContainer portletContainer;
private static ServletConfig servletConfig;
private static final ChannelCacheKey systemCacheKey;
private static final ChannelCacheKey instanceCacheKey;
private static final String uniqueContainerName =
PropertiesManager.getProperty("org.jasig.portal.channels.portlet.CPortletAdapter.uniqueContainerName", "Pluto-in-uPortal");
// Publish parameters expected by this channel
private static final String portletDefinitionIdParamName = "portletDefinitionId";
public static final String portletPreferenceNamePrefix = "PORTLET.";
private ChannelStaticData staticData = null;
private ChannelRuntimeData runtimeData = null;
private PortalControlStructures pcs = null;
private boolean portletWindowInitialized = false;
private PortletWindow portletWindow = null;
private Map userInfo = null;
private boolean receivedEvent = false;
private boolean focused = false;
private PortletMode newPortletMode = null;
private long lastRenderTime = Long.MIN_VALUE;
private String expirationCache = null;
private WindowState newWindowState = null;
private PortletSession portletSession = null;
private Map requestParams = null;
static {
portletContainerInitialized = false;
// Initialize cache keys
ChannelCacheKey key = new ChannelCacheKey();
key.setKeyScope(ChannelCacheKey.SYSTEM_KEY_SCOPE);
key.setKey("SYSTEM_SCOPE_KEY");
systemCacheKey = key;
key = new ChannelCacheKey();
key.setKeyScope(ChannelCacheKey.INSTANCE_KEY_SCOPE);
key.setKey("INSTANCE_SCOPE_KEY");
instanceCacheKey = key;
}
/**
* Receive the servlet config from uPortal's PortalSessionManager servlet.
* Pluto needs access to this object from serveral places.
* @param config the servlet config
*/
public static void setServletConfig(ServletConfig config) {
servletConfig = config;
}
/**
*
* @throws PortalException
*/
private synchronized static void initPortletContainer() throws PortalException {
if (!portletContainerInitialized) {
portletContainerInitialized = true;
try {
PortletContainerEnvironmentImpl environment = new PortletContainerEnvironmentImpl();
LogServiceImpl logService = new LogServiceImpl();
FactoryManagerServiceImpl factorManagerService = new FactoryManagerServiceImpl();
InformationProviderServiceImpl informationProviderService = new InformationProviderServiceImpl();
PropertyManagerService propertyManagerService = new PropertyManagerServiceImpl();
logService.init(servletConfig, null);
factorManagerService.init(servletConfig, null);
informationProviderService.init(servletConfig, null);
environment.addContainerService(logService);
environment.addContainerService(factorManagerService);
environment.addContainerService(informationProviderService);
environment.addContainerService(propertyManagerService);
//Call added in case the context has been re-loaded
PortletContainerServices.destroyReference(uniqueContainerName);
portletContainer = new PortletContainerImpl();
portletContainer.init(uniqueContainerName, servletConfig, environment, new Properties());
} catch (Exception e) {
String message = "Initialization of the portlet container failed.";
//log.error( message, e);
throw new PortalException(message, e);
}
}
}
protected void initPortletWindow() throws PortalException {
try {
initPortletContainer();
PortletContainerServices.prepare(uniqueContainerName);
// Get the portlet definition Id which must be specified as a publish
// parameter. The syntax of the ID is [portlet-context-name].[portlet-name]
String portletDefinitionId = staticData.getParameter(portletDefinitionIdParamName);
if (portletDefinitionId == null) {
throw new PortalException("Missing publish parameter '" + portletDefinitionIdParamName + "'");
}
// Create the PortletDefinition
PortletDefinitionImpl portletDefinition = (PortletDefinitionImpl)InformationProviderAccess.getStaticProvider().getPortletDefinition(ObjectIDImpl.createFromString(portletDefinitionId));
if (portletDefinition == null) {
throw new PortalException("Unable to find portlet definition for ID '" + portletDefinitionId + "'");
}
ChannelDefinition channelDefinition = ChannelRegistryStoreFactory.getChannelRegistryStoreImpl().getChannelDefinition(Integer.parseInt(staticData.getChannelPublishId()));
portletDefinition.setChannelDefinition(channelDefinition);
portletDefinition.loadPreferences();
// Create the PortletApplicationEntity
final PortletApplicationEntityImpl portAppEnt = new PortletApplicationEntityImpl();
portAppEnt.setId(portletDefinition.getId().toString());
portAppEnt.setPortletApplicationDefinition(portletDefinition.getPortletApplicationDefinition());
// Create the PortletEntity
PortletEntityImpl portletEntity = new PortletEntityImpl();
portletEntity.setId(staticData.getChannelPublishId());
portletEntity.setPortletDefinition(portletDefinition);
portletEntity.setPortletApplicationEntity(portAppEnt);
portletEntity.setUserLayout(pcs.getUserPreferencesManager().getUserLayoutManager().getUserLayout());
portletEntity.setChannelDescription((IUserLayoutChannelDescription)pcs.getUserPreferencesManager().getUserLayoutManager().getNode(staticData.getChannelSubscribeId()));
portletEntity.setPerson(staticData.getPerson());
portletEntity.loadPreferences();
// Add the user information into the request See PLT.17.2.
if (userInfo == null) {
UserAttributeListImpl userAttributeList = ((PortletApplicationDefinitionImpl)portletDefinition.getPortletApplicationDefinition()).getUserAttributes();
// here we ask an overridable method to get the user attributes.
// you can extend CPortletAdapter to change the implementation of
// how we get user attributes. This whole initPortletWindow method
// is also overridable.
//
// Note that we will only call getUserInfo() once.
userInfo = getUserInfo(staticData, userAttributeList);
if (log.isTraceEnabled()) {
//log.trace("For user [" + uid + "] got user info : [" + userInfo + "]");
}
}
// Wrap the request
ServletRequestImpl wrappedRequest = new ServletRequestImpl(pcs.getHttpServletRequest(), staticData.getPerson(), portletDefinition.getInitSecurityRoleRefSet());
// Now create the PortletWindow and hold a reference to it
PortletWindowImpl pw = new PortletWindowImpl();
pw.setId(staticData.getChannelSubscribeId());
pw.setPortletEntity(portletEntity);
pw.setChannelRuntimeData(runtimeData);
pw.setHttpServletRequest(wrappedRequest);
portletWindow = pw;
// Ask the container to load the portlet
synchronized(this) {
portletContainer.portletLoad(portletWindow, wrappedRequest, pcs.getHttpServletResponse());
}
portletWindowInitialized = true;
} catch (Exception e) {
String message = "Initialization of the portlet container failed.";
log.error( message, e);
throw new PortalException(message, e);
} finally {
PortletContainerServices.release();
}
}
/**
* Sets channel runtime properties.
* @return channel runtime properties
*/
public ChannelRuntimeProperties getRuntimeProperties() {
return new ChannelRuntimeProperties();
}
/**
* React to portal events.
* Removes channel state from the channel state map when the session expires.
* @param ev a portal event
*/
public void receiveEvent(PortalEvent ev) {
try {
PortletContainerServices.prepare(uniqueContainerName);
receivedEvent =true;
switch (ev.getEventNumber()) {
// Detect portlet mode changes
// Cannot use the PortletActionProvider to change modes here. It uses
// PortletWindow information to store the changes and the window is
// not current at this point.
case PortalEvent.EDIT_BUTTON_EVENT:
newPortletMode = PortletMode.EDIT;
break;
case PortalEvent.HELP_BUTTON_EVENT:
newPortletMode = PortletMode.HELP;
break;
case PortalEvent.ABOUT_BUTTON_EVENT:
// We might want to consider a custom ABOUT mode here
break;
//Detect portlet window state changes
case PortalEvent.MINIMIZE_EVENT:
newWindowState = WindowState.MINIMIZED;
break;
case PortalEvent.MAXIMIZE_EVENT:
newWindowState = WindowState.NORMAL;
break;
case PortalEvent.DETACH_BUTTON_EVENT:
newWindowState = WindowState.MAXIMIZED;
break;
//Detect end of session or portlet removed from layout
case PortalEvent.UNSUBSCRIBE:
//User is removing this portlet from their layout, remove all
//the preferences they have stored for it.
PortletEntityImpl pe = (PortletEntityImpl)portletWindow.getPortletEntity();
try {
pe.removePreferences();
}
catch (Exception e) {
log.error(e,e);
}
case PortalEvent.SESSION_DONE:
// For both SESSION_DONE and UNSUBSCRIBE, we might want to
// release resources here if we need to
PortletWindowImpl windowImpl = (PortletWindowImpl)portletWindow;
try {
PortletStateManager.clearState(windowImpl);
}
catch (IllegalStateException ise) {
//Ignore an illegal state when the PortletStateManager tries to
//access the session if it has already been destroyed.
}
// Invalidate portlet session
if (portletSession != null) {
try {
portletSession.invalidate();
}
catch (Exception e) {
log.error(e,e);
}
}
break;
default:
break;
}
} finally {
PortletContainerServices.release();
}
}
/**
* Sets the channel static data.
* @param sd the channel static data
* @throws org.jasig.portal.PortalException
*/
public void setStaticData(ChannelStaticData sd) throws PortalException {
staticData = sd;
try {
// Register this portlet's channel subscribe ID in the JNDI context
// this is probably not necessary since afaik nothing other than this
// portlet is reading this List. -andrew petro
List portletIds = (List)sd.getJNDIContext().lookup("/portlet-ids");
portletIds.add(sd.getChannelSubscribeId());
} catch (Exception e) {
throw new PortalException("Error accessing /portlet-ids JNDI context.", e);
}
}
/**
* Sets the channel runtime data.
* @param rd the channel runtime data
* @throws org.jasig.portal.PortalException
*/
public void setRuntimeData(ChannelRuntimeData rd) throws PortalException {
runtimeData =rd;
if (!this.portletWindowInitialized) {
this.initPortletWindow();
}
try {
PortletContainerServices.prepare(uniqueContainerName);
final PortletWindowImpl portletWindowimp = (PortletWindowImpl)portletWindow;
final PortletEntity portletEntity = portletWindow.getPortletEntity();
final PortletDefinition portletDef = portletEntity.getPortletDefinition();
final HttpServletRequest baseRequest = pcs.getHttpServletRequest();
HttpServletRequest wrappedRequest = new ServletRequestImpl(baseRequest, staticData.getPerson(), portletDef.getInitSecurityRoleRefSet());
//Wrap the request to scope attributes to this portlet instance
wrappedRequest = new PortletAttributeRequestWrapper(wrappedRequest);
//Set up request attributes (user info, portal session, etc...)
setupRequestAttributes(wrappedRequest);
// Put the current runtime data and wrapped request into the portlet window
portletWindowimp.setChannelRuntimeData(rd);
portletWindowimp.setHttpServletRequest(wrappedRequest);
// Get the portlet url manager which will analyze the request parameters
DynamicInformationProvider dip = InformationProviderAccess.getDynamicProvider(wrappedRequest);
PortletStateManager psm = ((DynamicInformationProviderImpl)dip).getPortletStateManager(portletWindow);
PortletActionProvider pap = dip.getPortletActionProvider(portletWindow);
//If portlet is rendering as root, change mode to maximized, otherwise minimized
if (!psm.isAction() && rd.isRenderingAsRoot()) {
if (WindowState.MINIMIZED.equals(newWindowState)) {
pap.changePortletWindowState(WindowState.MINIMIZED);
}
else {
pap.changePortletWindowState(WindowState.MAXIMIZED);
}
} else if (newWindowState != null) {
pap.changePortletWindowState(newWindowState);
}
else if (!psm.isAction()) {
pap.changePortletWindowState(WindowState.NORMAL);
}
newWindowState =null;
//Check for a portlet mode change
if (newPortletMode != null) {
pap.changePortletMode(newPortletMode);
PortletStateManager.setMode(portletWindow, newPortletMode);
}
newPortletMode = null;
// Process action if this is the targeted channel and the URL is an action URL
if (rd.isTargeted() && psm.isAction()) {
//Create a sink to throw out and output (portlets can't output content during an action)
PrintWriter pw = new PrintWriter(new NullOutputStream());
HttpServletResponse wrappedResponse = ServletObjectAccess.getStoredServletResponse(pcs.getHttpServletResponse(), pw);
try {
//See if a WindowState change was requested for an ActionURL
final String newWindowStateName = wrappedRequest.getParameter(PortletStateManager.UP_WINDOW_STATE);
if (newWindowStateName != null) {
pap.changePortletWindowState(new WindowState(newWindowStateName));
}
HttpServletRequest wrappedPortletRequest = new PortletParameterRequestWrapper(wrappedRequest);
portletContainer.processPortletAction(portletWindow, wrappedPortletRequest, wrappedResponse);
} catch (Exception e) {
throw new PortalException(e);
}
}
} finally {
PortletContainerServices.release();
}
}
/**
* Sets the portal control structures.
* @param pcs1 the portal control structures
* @throws org.jasig.portal.PortalException
*/
public void setPortalControlStructures(PortalControlStructures pcs1) throws PortalException {
this.pcs = pcs1;
}
/**
* Output channel content to the portal as raw characters
* @param pw a print writer
*/
public void renderCharacters(PrintWriter pw) throws PortalException {
if (!portletWindowInitialized) {
initPortletWindow();
}
try {
String markupString = getMarkup();
pw.print(markupString);
} catch (Exception e) {
throw new PortalException(e);
}
}
/**
* Output channel content to the portal. This version of the
* render method is normally not used since this is a "character channel".
* @param out a sax document handler
*/
public void renderXML(ContentHandler out) throws PortalException {
if (!portletWindowInitialized) {
initPortletWindow();
}
try {
String markupString = getMarkup();
// Output content. This assumes that markupString
// is well-formed. Consider changing to a character
// channel when it becomes available. Until we use the
// character channel, these <div> tags will be necessary.
SAXHelper.outputContent(out, "<div>" + markupString + "</div>");
} catch (Exception e) {
throw new PortalException(e);
}
}
/**
* This is where we do the real work of getting the markup.
* This is called from both renderXML() and renderCharacters().
* @return markup representing channel content
*/
protected synchronized String getMarkup() throws PortalException {
try {
PortletContainerServices.prepare(uniqueContainerName);
final PortletEntity portletEntity = portletWindow.getPortletEntity();
final PortletDefinition portletDef = portletEntity.getPortletDefinition();
final HttpServletRequest baseRequest = pcs.getHttpServletRequest();
HttpServletRequest wrappedRequest = new ServletRequestImpl(baseRequest, staticData.getPerson(), portletDef.getInitSecurityRoleRefSet());
//Wrap the request to scope attributes to this portlet instance
wrappedRequest = new PortletAttributeRequestWrapper(wrappedRequest);
//Set up request attributes (user info, portal session, etc...)
setupRequestAttributes(wrappedRequest);
final StringWriter sw = new StringWriter();
HttpServletResponse wrappedResponse = ServletObjectAccess.getStoredServletResponse(pcs.getHttpServletResponse(), new PrintWriter(sw));
//Use the parameters from the last request so the portlet maintains it's state
final ChannelRuntimeData rd = runtimeData;
if (!rd.isTargeted() && requestParams != null) {
wrappedRequest = new DummyParameterRequestWrapper(wrappedRequest, requestParams);
}
//Hide the request parameters if this portlet isn't targeted
else {
wrappedRequest = new PortletParameterRequestWrapper(wrappedRequest);
requestParams = wrappedRequest.getParameterMap();
}
portletContainer.renderPortlet(portletWindow, wrappedRequest, wrappedResponse);
// Track PortletSession object
PortletSession ps = (PortletSession)wrappedRequest.getAttribute(PortletServlet.SESSION_MONITOR_ATTRIBUTE);
if (ps != null) {
portletSession = ps;
}
//Support for the portlet modifying it's cache timeout
final Map properties = PropertyManager.getRequestProperties(portletWindow, wrappedRequest);
final String[] exprCacheTimeStr = (String[])properties.get(RenderResponse.EXPIRATION_CACHE);
if (exprCacheTimeStr != null && exprCacheTimeStr.length > 0) {
try {
Integer.parseInt(exprCacheTimeStr[0]); //Check for valid number
expirationCache = exprCacheTimeStr[0];
}
catch (NumberFormatException nfe) {
log.error("The specified RenderResponse.EXPIRATION_CACHE value of (" + exprCacheTimeStr + ") is not a number.", nfe);
throw nfe;
}
}
//Keep track of the last time the portlet was successfully rendered
lastRenderTime = System.currentTimeMillis();
//Return the content
return sw.toString();
} catch (Throwable t) {
log.error(t, t);
throw new PortalException(t);
} finally {
PortletContainerServices.release();
}
}
/**
* Generates a channel cache key. The key scope is set to be system-wide
* when the channel is anonymously accessed, otherwise it is set to be
* instance-wide. The caching implementation here is simple and may not
* handle all cases. It may also violate the Portlet Specification so
* this obviously needs further discussion.
* @return the channel cache key
*/
public ChannelCacheKey generateKey() {
ChannelCacheKey cck = null;
// Anonymously accessed pages can be cached system-wide
if(staticData.getPerson().isGuest()) {
cck = systemCacheKey;
} else {
cck = instanceCacheKey;
}
return cck;
}
/**
* Determines whether the cached content for this channel is still valid.
* <p>
* Return <code>true</code> when:<br>
* <ol>
* <li>We have not just received an event</li>
* <li>No runtime parameters are sent to the channel</li>
* <li>The focus hasn't switched.</li>
* </ol>
* Otherwise, return <code>false</code>.
* <p>
* In other words, cache the content in all cases <b>except</b>
* for when a user clicks a channel button, a link or form button within the channel,
* or the <i>focus</i> or <i>unfocus</i> button.
* @param validity the validity object
* @return <code>true</code> if the cache is still valid, otherwise <code>false</code>
*/
public boolean isCacheValid(Object validity) {
PortletEntity pe = portletWindow.getPortletEntity();
PortletDefinition pd = pe.getPortletDefinition();
//Expiration based caching support for the portlet.
String exprCacheTimeStr = pd.getExpirationCache();
try {
if (expirationCache != null)
exprCacheTimeStr = expirationCache;
int exprCacheTime = Integer.parseInt(exprCacheTimeStr);
if (exprCacheTime == 0) {
return false;
}
else if (exprCacheTime > 0) {
if ((lastRenderTime + (exprCacheTime * 1000)) < System.currentTimeMillis())
return false;
}
}
catch (Exception e) {
if (log.isWarnEnabled()) {
String portletId = staticData.getParameter(portletDefinitionIdParamName);
log.warn("Error parsing portlet expiration time (" + exprCacheTimeStr + ") for portlet (" + portletId + ").", e);
}
}
// Determine if the channel focus has changed
boolean previouslyFocused = focused;
focused = runtimeData.isRenderingAsRoot();
boolean focusHasSwitched = focused != previouslyFocused;
// Dirty cache only when we receive an event, one or more request params, or a change in focus
boolean cacheValid = !(receivedEvent || runtimeData.isTargeted() || focusHasSwitched);
receivedEvent = false;
return cacheValid;
}
//***************************************************************
// IDirectResponse methods
//***************************************************************
public synchronized void setResponse(HttpServletResponse response) {
try {
PortletContainerServices.prepare(uniqueContainerName);
final PortletEntity portletEntity = portletWindow.getPortletEntity();
final PortletDefinition portletDef = portletEntity.getPortletDefinition();
final HttpServletRequest baseRequest = pcs.getHttpServletRequest();
HttpServletRequest wrappedRequest = new ServletRequestImpl(baseRequest, staticData.getPerson(), portletDef.getInitSecurityRoleRefSet());
//Wrap the request to scope attributes to this portlet instance
wrappedRequest = new PortletAttributeRequestWrapper(wrappedRequest);
//Set up request attributes (user info, portal session, etc...)
setupRequestAttributes(wrappedRequest);
//Hide the request parameters if this portlet isn't targeted
wrappedRequest = new PortletParameterRequestWrapper(wrappedRequest);
//Since the portlet is rendering through IDirectResponse change the window state to "exclusive"
DynamicInformationProvider dip = InformationProviderAccess.getDynamicProvider(pcs.getHttpServletRequest());
PortletActionProvider pap = dip.getPortletActionProvider(portletWindow);
pap.changePortletWindowState(new WindowState("exclusive"));
HttpServletResponse wrappedResponse = new OutputStreamResponseWrapper(response);
//render the portlet
portletContainer.renderPortlet(portletWindow, wrappedRequest, wrappedResponse);
// Track PortletSession object
PortletSession ps = (PortletSession)wrappedRequest.getAttribute(PortletServlet.SESSION_MONITOR_ATTRIBUTE);
if (ps != null) {
portletSession = ps;
}
//Ensure all the data gets written out
wrappedResponse.flushBuffer();
} catch (Throwable t) {
log.error(t, t);
} finally {
PortletContainerServices.release();
}
}
//***************************************************************
// Helper methods
//***************************************************************
/**
* Retrieves the users password by iterating over
* the user's security contexts and returning the first
* available cached password.
*
* @param baseContext The security context to start looking for a password from.
* @return the users password
*/
private String getPassword(ISecurityContext baseContext) {
String password = null;
IOpaqueCredentials oc = baseContext.getOpaqueCredentials();
if (oc instanceof NotSoOpaqueCredentials) {
NotSoOpaqueCredentials nsoc = (NotSoOpaqueCredentials)oc;
password = nsoc.getCredentials();
}
// If still no password, loop through subcontexts to find cached credentials
Enumeration en = baseContext.getSubContexts();
while (password == null && en.hasMoreElements()) {
ISecurityContext subContext = (ISecurityContext)en.nextElement();
password = this.getPassword(subContext);
}
return password;
}
/**
* Adds the appropriate information to the request attributes of the portlet.
*
* This is an extension point. You can override this method to set other
* request attributes.
*
* @param request The request to add the attributes to
*/
protected void setupRequestAttributes(final HttpServletRequest request) {
//Add the user information map
request.setAttribute(PortletRequest.USER_INFO, userInfo);
}
/**
* Get the Map of portlet user attribute names to portlet user attribute values.
*
* This is an extension point. You can extend CPortletAdapter and override this
* method to implement the particular user attribute Map creation strategy that
* you need to implement. Such strategies might rename uPortal
* user attributes to names that your particular portlet knows how to consume,
* transform the user attribute values to forms expected by your portlet, add
* additional attributes, convey a CAS proxy ticket or other security token.
* This extension point is the way to accomodate the particular user attributes
* particular portlets require.
*
* The default implementation of this method includes in the userInfo Map
* those uPortal IPerson attributes matching entries in the list of attributes the
* Portlet declared it wanted. Additionally, the default implementation copies
* the cached user password if the Portlet declares it wants the user attribute
* 'password'.
*
* @param staticData data associated with the particular instance of the portlet window for the particular
* user session
* @param userAttributes the user attributes requested by the Portlet
* @return a Map from portlet user attribute names to portlet user attribute values.
*/
protected Map getUserInfo(ChannelStaticData staticData, UserAttributeListImpl userAttributes) {
final String PASSWORD_ATTR = "password";
Map userInfo = new HashMap();
IPerson person = staticData.getPerson();
if (person.getSecurityContext().isAuthenticated()) {
// for each attribute the Portlet requested
for (Iterator iter = userAttributes.iterator(); iter.hasNext(); ) {
UserAttributeImpl userAttribute = (UserAttributeImpl)iter.next();
String attName = userAttribute.getName();
String attValue = (String)person.getAttribute(attName);
if ((attValue == null || attValue.equals("")) && attName.equals(PASSWORD_ATTR)) {
attValue = getPassword(person.getSecurityContext());
}
userInfo.put(attName, attValue);
}
}
return userInfo;
}
}
| UP-1685 handle exceptions other than NPE on attempt to clear portlet session.
git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@13901 f5dbab47-78f9-eb45-b975-e544023573eb
| source/org/jasig/portal/channels/portlet/CPortletAdapter.java | UP-1685 handle exceptions other than NPE on attempt to clear portlet session. |
|
Java | bsd-2-clause | 9a038f5025169923536e3b4ea6a6b4bc2eac74f5 | 0 | runelite/runelite,runelite/runelite,runelite/runelite | /*
* Copyright (c) 2018, terminatusx <[email protected]>
* Copyright (c) 2018, Adam <[email protected]>
* Copyright (c) 2020, loldudester <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.wintertodt;
import com.google.inject.Provides;
import java.time.Duration;
import java.time.Instant;
import javax.inject.Inject;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import static net.runelite.api.AnimationID.CONSTRUCTION;
import static net.runelite.api.AnimationID.CONSTRUCTION_IMCANDO;
import static net.runelite.api.AnimationID.FIREMAKING;
import static net.runelite.api.AnimationID.FLETCHING_BOW_CUTTING;
import static net.runelite.api.AnimationID.IDLE;
import static net.runelite.api.AnimationID.LOOKING_INTO;
import static net.runelite.api.AnimationID.WOODCUTTING_3A_AXE;
import static net.runelite.api.AnimationID.WOODCUTTING_ADAMANT;
import static net.runelite.api.AnimationID.WOODCUTTING_BLACK;
import static net.runelite.api.AnimationID.WOODCUTTING_BRONZE;
import static net.runelite.api.AnimationID.WOODCUTTING_CRYSTAL;
import static net.runelite.api.AnimationID.WOODCUTTING_DRAGON;
import static net.runelite.api.AnimationID.WOODCUTTING_DRAGON_OR;
import static net.runelite.api.AnimationID.WOODCUTTING_GILDED;
import static net.runelite.api.AnimationID.WOODCUTTING_INFERNAL;
import static net.runelite.api.AnimationID.WOODCUTTING_IRON;
import static net.runelite.api.AnimationID.WOODCUTTING_MITHRIL;
import static net.runelite.api.AnimationID.WOODCUTTING_RUNE;
import static net.runelite.api.AnimationID.WOODCUTTING_STEEL;
import static net.runelite.api.AnimationID.WOODCUTTING_TRAILBLAZER;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.InventoryID;
import net.runelite.api.Item;
import net.runelite.api.ItemContainer;
import static net.runelite.api.ItemID.BRUMA_KINDLING;
import static net.runelite.api.ItemID.BRUMA_ROOT;
import net.runelite.api.MessageNode;
import net.runelite.api.Player;
import net.runelite.api.Varbits;
import net.runelite.api.events.AnimationChanged;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.ItemContainerChanged;
import net.runelite.api.events.VarbitChanged;
import net.runelite.client.Notifier;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.wintertodt.config.WintertodtNotifyDamage;
import static net.runelite.client.plugins.wintertodt.config.WintertodtNotifyDamage.ALWAYS;
import static net.runelite.client.plugins.wintertodt.config.WintertodtNotifyDamage.INTERRUPT;
import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.util.ColorUtil;
@PluginDescriptor(
name = "Wintertodt",
description = "Show helpful information for the Wintertodt boss",
tags = {"minigame", "firemaking", "boss"}
)
@Slf4j
public class WintertodtPlugin extends Plugin
{
private static final int WINTERTODT_REGION = 6462;
@Inject
private Notifier notifier;
@Inject
private Client client;
@Inject
private OverlayManager overlayManager;
@Inject
private WintertodtOverlay overlay;
@Inject
private WintertodtConfig config;
@Inject
private ChatMessageManager chatMessageManager;
@Getter(AccessLevel.PACKAGE)
private WintertodtActivity currentActivity = WintertodtActivity.IDLE;
@Getter(AccessLevel.PACKAGE)
private int inventoryScore;
@Getter(AccessLevel.PACKAGE)
private int totalPotentialinventoryScore;
@Getter(AccessLevel.PACKAGE)
private int numLogs;
@Getter(AccessLevel.PACKAGE)
private int numKindling;
@Getter(AccessLevel.PACKAGE)
private boolean isInWintertodt;
private Instant lastActionTime;
private int previousTimerValue;
@Provides
WintertodtConfig getConfig(ConfigManager configManager)
{
return configManager.getConfig(WintertodtConfig.class);
}
@Override
protected void startUp() throws Exception
{
reset();
overlayManager.add(overlay);
}
@Override
protected void shutDown() throws Exception
{
overlayManager.remove(overlay);
reset();
}
private void reset()
{
inventoryScore = 0;
totalPotentialinventoryScore = 0;
numLogs = 0;
numKindling = 0;
currentActivity = WintertodtActivity.IDLE;
lastActionTime = null;
}
private boolean isInWintertodtRegion()
{
if (client.getLocalPlayer() != null)
{
return client.getLocalPlayer().getWorldLocation().getRegionID() == WINTERTODT_REGION;
}
return false;
}
@Subscribe
public void onGameTick(GameTick gameTick)
{
if (!isInWintertodtRegion())
{
if (isInWintertodt)
{
log.debug("Left Wintertodt!");
reset();
}
isInWintertodt = false;
return;
}
if (!isInWintertodt)
{
reset();
log.debug("Entered Wintertodt!");
}
isInWintertodt = true;
checkActionTimeout();
}
@Subscribe
public void onVarbitChanged(VarbitChanged varbitChanged)
{
int timerValue = client.getVar(Varbits.WINTERTODT_TIMER);
if (timerValue != previousTimerValue)
{
int timeToNotify = config.roundNotification();
if (timeToNotify > 0)
{
int timeInSeconds = timerValue * 30 / 50;
int prevTimeInSeconds = previousTimerValue * 30 / 50;
log.debug("Seconds left until round start: {}", timeInSeconds);
if (prevTimeInSeconds > timeToNotify && timeInSeconds <= timeToNotify)
{
notifier.notify("Wintertodt round is about to start");
}
}
previousTimerValue = timerValue;
}
}
private void checkActionTimeout()
{
if (currentActivity == WintertodtActivity.IDLE)
{
return;
}
int currentAnimation = client.getLocalPlayer() != null ? client.getLocalPlayer().getAnimation() : -1;
if (currentAnimation != IDLE || lastActionTime == null)
{
return;
}
Duration actionTimeout = Duration.ofSeconds(3);
Duration sinceAction = Duration.between(lastActionTime, Instant.now());
if (sinceAction.compareTo(actionTimeout) >= 0)
{
log.debug("Activity timeout!");
currentActivity = WintertodtActivity.IDLE;
}
}
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (!isInWintertodt)
{
return;
}
ChatMessageType chatMessageType = chatMessage.getType();
if (chatMessageType != ChatMessageType.GAMEMESSAGE && chatMessageType != ChatMessageType.SPAM)
{
return;
}
MessageNode messageNode = chatMessage.getMessageNode();
final WintertodtInterruptType interruptType;
if (messageNode.getValue().startsWith("You carefully fletch the root"))
{
setActivity(WintertodtActivity.FLETCHING);
return;
}
if (messageNode.getValue().startsWith("The cold of"))
{
interruptType = WintertodtInterruptType.COLD;
}
else if (messageNode.getValue().startsWith("The freezing cold attack"))
{
interruptType = WintertodtInterruptType.SNOWFALL;
}
else if (messageNode.getValue().startsWith("The brazier is broken and shrapnel"))
{
interruptType = WintertodtInterruptType.BRAZIER;
}
else if (messageNode.getValue().startsWith("You have run out of bruma roots"))
{
interruptType = WintertodtInterruptType.OUT_OF_ROOTS;
}
else if (messageNode.getValue().startsWith("Your inventory is too full"))
{
interruptType = WintertodtInterruptType.INVENTORY_FULL;
}
else if (messageNode.getValue().startsWith("You fix the brazier"))
{
interruptType = WintertodtInterruptType.FIXED_BRAZIER;
}
else if (messageNode.getValue().startsWith("You light the brazier"))
{
interruptType = WintertodtInterruptType.LIT_BRAZIER;
}
else if (messageNode.getValue().startsWith("The brazier has gone out."))
{
interruptType = WintertodtInterruptType.BRAZIER_WENT_OUT;
}
else
{
return;
}
boolean wasInterrupted = false;
boolean neverNotify = false;
switch (interruptType)
{
case COLD:
case BRAZIER:
case SNOWFALL:
// Recolor message for damage notification
messageNode.setRuneLiteFormatMessage(ColorUtil.wrapWithColorTag(messageNode.getValue(), config.damageNotificationColor()));
chatMessageManager.update(messageNode);
client.refreshChat();
// all actions except woodcutting and idle are interrupted from damage
if (currentActivity != WintertodtActivity.WOODCUTTING && currentActivity != WintertodtActivity.IDLE)
{
wasInterrupted = true;
}
break;
case INVENTORY_FULL:
case OUT_OF_ROOTS:
case BRAZIER_WENT_OUT:
wasInterrupted = true;
break;
case LIT_BRAZIER:
case FIXED_BRAZIER:
wasInterrupted = true;
neverNotify = true;
break;
}
if (!neverNotify)
{
boolean shouldNotify = false;
switch (interruptType)
{
case COLD:
WintertodtNotifyDamage notify = config.notifyCold();
shouldNotify = notify == ALWAYS || (notify == INTERRUPT && wasInterrupted);
break;
case SNOWFALL:
notify = config.notifySnowfall();
shouldNotify = notify == ALWAYS || (notify == INTERRUPT && wasInterrupted);
break;
case BRAZIER:
notify = config.notifyBrazierDamage();
shouldNotify = notify == ALWAYS || (notify == INTERRUPT && wasInterrupted);
break;
case INVENTORY_FULL:
shouldNotify = config.notifyFullInv();
break;
case OUT_OF_ROOTS:
shouldNotify = config.notifyEmptyInv();
break;
case BRAZIER_WENT_OUT:
shouldNotify = config.notifyBrazierOut();
break;
}
if (shouldNotify)
{
notifyInterrupted(interruptType, wasInterrupted);
}
}
if (wasInterrupted)
{
currentActivity = WintertodtActivity.IDLE;
}
}
private void notifyInterrupted(WintertodtInterruptType interruptType, boolean wasActivityInterrupted)
{
final StringBuilder str = new StringBuilder();
str.append("Wintertodt: ");
if (wasActivityInterrupted)
{
str.append(currentActivity.getActionString());
str.append(" interrupted! ");
}
str.append(interruptType.getInterruptSourceString());
String notification = str.toString();
log.debug("Sending notification: {}", notification);
notifier.notify(notification);
}
@Subscribe
public void onAnimationChanged(final AnimationChanged event)
{
if (!isInWintertodt)
{
return;
}
final Player local = client.getLocalPlayer();
if (event.getActor() != local)
{
return;
}
final int animId = local.getAnimation();
switch (animId)
{
case WOODCUTTING_BRONZE:
case WOODCUTTING_IRON:
case WOODCUTTING_STEEL:
case WOODCUTTING_BLACK:
case WOODCUTTING_MITHRIL:
case WOODCUTTING_ADAMANT:
case WOODCUTTING_RUNE:
case WOODCUTTING_GILDED:
case WOODCUTTING_DRAGON:
case WOODCUTTING_DRAGON_OR:
case WOODCUTTING_INFERNAL:
case WOODCUTTING_3A_AXE:
case WOODCUTTING_CRYSTAL:
case WOODCUTTING_TRAILBLAZER:
setActivity(WintertodtActivity.WOODCUTTING);
break;
case FLETCHING_BOW_CUTTING:
setActivity(WintertodtActivity.FLETCHING);
break;
case LOOKING_INTO:
setActivity(WintertodtActivity.FEEDING_BRAZIER);
break;
case FIREMAKING:
setActivity(WintertodtActivity.LIGHTING_BRAZIER);
break;
case CONSTRUCTION:
case CONSTRUCTION_IMCANDO:
setActivity(WintertodtActivity.FIXING_BRAZIER);
break;
}
}
@Subscribe
public void onItemContainerChanged(ItemContainerChanged event)
{
final ItemContainer container = event.getItemContainer();
if (!isInWintertodt || container != client.getItemContainer(InventoryID.INVENTORY))
{
return;
}
final Item[] inv = container.getItems();
inventoryScore = 0;
totalPotentialinventoryScore = 0;
numLogs = 0;
numKindling = 0;
for (Item item : inv)
{
inventoryScore += getPoints(item.getId());
totalPotentialinventoryScore += getPotentialPoints(item.getId());
switch (item.getId())
{
case BRUMA_ROOT:
++numLogs;
break;
case BRUMA_KINDLING:
++numKindling;
break;
}
}
//If we're currently fletching but there are no more logs, go ahead and abort fletching immediately
if (numLogs == 0 && currentActivity == WintertodtActivity.FLETCHING)
{
currentActivity = WintertodtActivity.IDLE;
}
//Otherwise, if we're currently feeding the brazier but we've run out of both logs and kindling, abort the feeding activity
else if (numLogs == 0 && numKindling == 0 && currentActivity == WintertodtActivity.FEEDING_BRAZIER)
{
currentActivity = WintertodtActivity.IDLE;
}
}
private void setActivity(WintertodtActivity action)
{
currentActivity = action;
lastActionTime = Instant.now();
}
private static int getPoints(int id)
{
switch (id)
{
case BRUMA_ROOT:
return 10;
case BRUMA_KINDLING:
return 25;
default:
return 0;
}
}
private static int getPotentialPoints(int id)
{
switch (id)
{
case BRUMA_ROOT:
case BRUMA_KINDLING:
return 25;
default:
return 0;
}
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/wintertodt/WintertodtPlugin.java | /*
* Copyright (c) 2018, terminatusx <[email protected]>
* Copyright (c) 2018, Adam <[email protected]>
* Copyright (c) 2020, loldudester <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.wintertodt;
import com.google.inject.Provides;
import java.time.Duration;
import java.time.Instant;
import javax.inject.Inject;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import static net.runelite.api.AnimationID.CONSTRUCTION;
import static net.runelite.api.AnimationID.CONSTRUCTION_IMCANDO;
import static net.runelite.api.AnimationID.FIREMAKING;
import static net.runelite.api.AnimationID.FLETCHING_BOW_CUTTING;
import static net.runelite.api.AnimationID.IDLE;
import static net.runelite.api.AnimationID.LOOKING_INTO;
import static net.runelite.api.AnimationID.WOODCUTTING_3A_AXE;
import static net.runelite.api.AnimationID.WOODCUTTING_ADAMANT;
import static net.runelite.api.AnimationID.WOODCUTTING_BLACK;
import static net.runelite.api.AnimationID.WOODCUTTING_BRONZE;
import static net.runelite.api.AnimationID.WOODCUTTING_CRYSTAL;
import static net.runelite.api.AnimationID.WOODCUTTING_DRAGON;
import static net.runelite.api.AnimationID.WOODCUTTING_DRAGON_OR;
import static net.runelite.api.AnimationID.WOODCUTTING_GILDED;
import static net.runelite.api.AnimationID.WOODCUTTING_INFERNAL;
import static net.runelite.api.AnimationID.WOODCUTTING_IRON;
import static net.runelite.api.AnimationID.WOODCUTTING_MITHRIL;
import static net.runelite.api.AnimationID.WOODCUTTING_RUNE;
import static net.runelite.api.AnimationID.WOODCUTTING_STEEL;
import static net.runelite.api.AnimationID.WOODCUTTING_TRAILBLAZER;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.InventoryID;
import net.runelite.api.Item;
import net.runelite.api.ItemContainer;
import static net.runelite.api.ItemID.BRUMA_KINDLING;
import static net.runelite.api.ItemID.BRUMA_ROOT;
import net.runelite.api.MessageNode;
import net.runelite.api.Player;
import net.runelite.api.Varbits;
import net.runelite.api.events.AnimationChanged;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameTick;
import net.runelite.api.events.ItemContainerChanged;
import net.runelite.api.events.VarbitChanged;
import net.runelite.client.Notifier;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.wintertodt.config.WintertodtNotifyDamage;
import static net.runelite.client.plugins.wintertodt.config.WintertodtNotifyDamage.ALWAYS;
import static net.runelite.client.plugins.wintertodt.config.WintertodtNotifyDamage.INTERRUPT;
import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.util.ColorUtil;
@PluginDescriptor(
name = "Wintertodt",
description = "Show helpful information for the Wintertodt boss",
tags = {"minigame", "firemaking", "boss"}
)
@Slf4j
public class WintertodtPlugin extends Plugin
{
private static final int WINTERTODT_REGION = 6462;
@Inject
private Notifier notifier;
@Inject
private Client client;
@Inject
private OverlayManager overlayManager;
@Inject
private WintertodtOverlay overlay;
@Inject
private WintertodtConfig config;
@Inject
private ChatMessageManager chatMessageManager;
@Getter(AccessLevel.PACKAGE)
private WintertodtActivity currentActivity = WintertodtActivity.IDLE;
@Getter(AccessLevel.PACKAGE)
private int inventoryScore;
@Getter(AccessLevel.PACKAGE)
private int totalPotentialinventoryScore;
@Getter(AccessLevel.PACKAGE)
private int numLogs;
@Getter(AccessLevel.PACKAGE)
private int numKindling;
@Getter(AccessLevel.PACKAGE)
private boolean isInWintertodt;
private Instant lastActionTime;
private int previousTimerValue;
@Provides
WintertodtConfig getConfig(ConfigManager configManager)
{
return configManager.getConfig(WintertodtConfig.class);
}
@Override
protected void startUp() throws Exception
{
reset();
overlayManager.add(overlay);
}
@Override
protected void shutDown() throws Exception
{
overlayManager.remove(overlay);
reset();
}
private void reset()
{
inventoryScore = 0;
totalPotentialinventoryScore = 0;
numLogs = 0;
numKindling = 0;
currentActivity = WintertodtActivity.IDLE;
lastActionTime = null;
}
private boolean isInWintertodtRegion()
{
if (client.getLocalPlayer() != null)
{
return client.getLocalPlayer().getWorldLocation().getRegionID() == WINTERTODT_REGION;
}
return false;
}
@Subscribe
public void onGameTick(GameTick gameTick)
{
if (!isInWintertodtRegion())
{
if (isInWintertodt)
{
log.debug("Left Wintertodt!");
reset();
}
isInWintertodt = false;
return;
}
if (!isInWintertodt)
{
reset();
log.debug("Entered Wintertodt!");
}
isInWintertodt = true;
checkActionTimeout();
}
@Subscribe
public void onVarbitChanged(VarbitChanged varbitChanged)
{
int timerValue = client.getVar(Varbits.WINTERTODT_TIMER);
if (timerValue != previousTimerValue)
{
int timeToNotify = config.roundNotification();
if (timeToNotify > 0)
{
int timeInSeconds = timerValue * 30 / 50;
int prevTimeInSeconds = previousTimerValue * 30 / 50;
log.debug("Seconds left until round start: {}", timeInSeconds);
if (prevTimeInSeconds > timeToNotify && timeInSeconds <= timeToNotify)
{
notifier.notify("Wintertodt round is about to start");
}
}
previousTimerValue = timerValue;
}
}
private void checkActionTimeout()
{
if (currentActivity == WintertodtActivity.IDLE)
{
return;
}
int currentAnimation = client.getLocalPlayer() != null ? client.getLocalPlayer().getAnimation() : -1;
if (currentAnimation != IDLE || lastActionTime == null)
{
return;
}
Duration actionTimeout = Duration.ofSeconds(3);
Duration sinceAction = Duration.between(lastActionTime, Instant.now());
if (sinceAction.compareTo(actionTimeout) >= 0)
{
log.debug("Activity timeout!");
currentActivity = WintertodtActivity.IDLE;
}
}
@Subscribe
public void onChatMessage(ChatMessage chatMessage)
{
if (!isInWintertodt)
{
return;
}
ChatMessageType chatMessageType = chatMessage.getType();
if (chatMessageType != ChatMessageType.GAMEMESSAGE && chatMessageType != ChatMessageType.SPAM)
{
return;
}
MessageNode messageNode = chatMessage.getMessageNode();
final WintertodtInterruptType interruptType;
if (messageNode.getValue().startsWith("The cold of"))
{
interruptType = WintertodtInterruptType.COLD;
}
else if (messageNode.getValue().startsWith("The freezing cold attack"))
{
interruptType = WintertodtInterruptType.SNOWFALL;
}
else if (messageNode.getValue().startsWith("The brazier is broken and shrapnel"))
{
interruptType = WintertodtInterruptType.BRAZIER;
}
else if (messageNode.getValue().startsWith("You have run out of bruma roots"))
{
interruptType = WintertodtInterruptType.OUT_OF_ROOTS;
}
else if (messageNode.getValue().startsWith("Your inventory is too full"))
{
interruptType = WintertodtInterruptType.INVENTORY_FULL;
}
else if (messageNode.getValue().startsWith("You fix the brazier"))
{
interruptType = WintertodtInterruptType.FIXED_BRAZIER;
}
else if (messageNode.getValue().startsWith("You light the brazier"))
{
interruptType = WintertodtInterruptType.LIT_BRAZIER;
}
else if (messageNode.getValue().startsWith("The brazier has gone out."))
{
interruptType = WintertodtInterruptType.BRAZIER_WENT_OUT;
}
else
{
return;
}
boolean wasInterrupted = false;
boolean neverNotify = false;
switch (interruptType)
{
case COLD:
case BRAZIER:
case SNOWFALL:
// Recolor message for damage notification
messageNode.setRuneLiteFormatMessage(ColorUtil.wrapWithColorTag(messageNode.getValue(), config.damageNotificationColor()));
chatMessageManager.update(messageNode);
client.refreshChat();
// all actions except woodcutting and idle are interrupted from damage
if (currentActivity != WintertodtActivity.WOODCUTTING && currentActivity != WintertodtActivity.IDLE)
{
wasInterrupted = true;
}
break;
case INVENTORY_FULL:
case OUT_OF_ROOTS:
case BRAZIER_WENT_OUT:
wasInterrupted = true;
break;
case LIT_BRAZIER:
case FIXED_BRAZIER:
wasInterrupted = true;
neverNotify = true;
break;
}
if (!neverNotify)
{
boolean shouldNotify = false;
switch (interruptType)
{
case COLD:
WintertodtNotifyDamage notify = config.notifyCold();
shouldNotify = notify == ALWAYS || (notify == INTERRUPT && wasInterrupted);
break;
case SNOWFALL:
notify = config.notifySnowfall();
shouldNotify = notify == ALWAYS || (notify == INTERRUPT && wasInterrupted);
break;
case BRAZIER:
notify = config.notifyBrazierDamage();
shouldNotify = notify == ALWAYS || (notify == INTERRUPT && wasInterrupted);
break;
case INVENTORY_FULL:
shouldNotify = config.notifyFullInv();
break;
case OUT_OF_ROOTS:
shouldNotify = config.notifyEmptyInv();
break;
case BRAZIER_WENT_OUT:
shouldNotify = config.notifyBrazierOut();
break;
}
if (shouldNotify)
{
notifyInterrupted(interruptType, wasInterrupted);
}
}
if (wasInterrupted)
{
currentActivity = WintertodtActivity.IDLE;
}
}
private void notifyInterrupted(WintertodtInterruptType interruptType, boolean wasActivityInterrupted)
{
final StringBuilder str = new StringBuilder();
str.append("Wintertodt: ");
if (wasActivityInterrupted)
{
str.append(currentActivity.getActionString());
str.append(" interrupted! ");
}
str.append(interruptType.getInterruptSourceString());
String notification = str.toString();
log.debug("Sending notification: {}", notification);
notifier.notify(notification);
}
@Subscribe
public void onAnimationChanged(final AnimationChanged event)
{
if (!isInWintertodt)
{
return;
}
final Player local = client.getLocalPlayer();
if (event.getActor() != local)
{
return;
}
final int animId = local.getAnimation();
switch (animId)
{
case WOODCUTTING_BRONZE:
case WOODCUTTING_IRON:
case WOODCUTTING_STEEL:
case WOODCUTTING_BLACK:
case WOODCUTTING_MITHRIL:
case WOODCUTTING_ADAMANT:
case WOODCUTTING_RUNE:
case WOODCUTTING_GILDED:
case WOODCUTTING_DRAGON:
case WOODCUTTING_DRAGON_OR:
case WOODCUTTING_INFERNAL:
case WOODCUTTING_3A_AXE:
case WOODCUTTING_CRYSTAL:
case WOODCUTTING_TRAILBLAZER:
setActivity(WintertodtActivity.WOODCUTTING);
break;
case FLETCHING_BOW_CUTTING:
setActivity(WintertodtActivity.FLETCHING);
break;
case LOOKING_INTO:
setActivity(WintertodtActivity.FEEDING_BRAZIER);
break;
case FIREMAKING:
setActivity(WintertodtActivity.LIGHTING_BRAZIER);
break;
case CONSTRUCTION:
case CONSTRUCTION_IMCANDO:
setActivity(WintertodtActivity.FIXING_BRAZIER);
break;
}
}
@Subscribe
public void onItemContainerChanged(ItemContainerChanged event)
{
final ItemContainer container = event.getItemContainer();
if (!isInWintertodt || container != client.getItemContainer(InventoryID.INVENTORY))
{
return;
}
final Item[] inv = container.getItems();
inventoryScore = 0;
totalPotentialinventoryScore = 0;
numLogs = 0;
numKindling = 0;
for (Item item : inv)
{
inventoryScore += getPoints(item.getId());
totalPotentialinventoryScore += getPotentialPoints(item.getId());
switch (item.getId())
{
case BRUMA_ROOT:
++numLogs;
break;
case BRUMA_KINDLING:
++numKindling;
break;
}
}
//If we're currently fletching but there are no more logs, go ahead and abort fletching immediately
if (numLogs == 0 && currentActivity == WintertodtActivity.FLETCHING)
{
currentActivity = WintertodtActivity.IDLE;
}
//Otherwise, if we're currently feeding the brazier but we've run out of both logs and kindling, abort the feeding activity
else if (numLogs == 0 && numKindling == 0 && currentActivity == WintertodtActivity.FEEDING_BRAZIER)
{
currentActivity = WintertodtActivity.IDLE;
}
}
private void setActivity(WintertodtActivity action)
{
currentActivity = action;
lastActionTime = Instant.now();
}
private static int getPoints(int id)
{
switch (id)
{
case BRUMA_ROOT:
return 10;
case BRUMA_KINDLING:
return 25;
default:
return 0;
}
}
private static int getPotentialPoints(int id)
{
switch (id)
{
case BRUMA_ROOT:
case BRUMA_KINDLING:
return 25;
default:
return 0;
}
}
}
| wintertodt: improve fletching activity status detection
| runelite-client/src/main/java/net/runelite/client/plugins/wintertodt/WintertodtPlugin.java | wintertodt: improve fletching activity status detection |
|
Java | bsd-3-clause | ff61f58ab5939ab66a9b2da2e4785c5d1a675a41 | 0 | muloem/xins,muloem/xins,muloem/xins | /*
* $Id$
*/
package org.xins.client;
import java.io.IOException;
import java.util.Map;
/**
* Interface for API function calling functionality.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
public interface FunctionCaller {
/**
* Calls the specified session-less API function with the specified
* parameters.
*
* @param functionName
* the name of the function to be called, not <code>null</code>.
*
* @param parameters
* the parameters to be passed to that function, or
* <code>null</code>; keys must be {@link String Strings}, values can be
* of any class.
*
* @return
* the call result, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>functionName == null</code>.
*
* @throws IOException
* if the API could not be contacted due to an I/O error.
*
* @throws InvalidCallResultException
* if the calling of the function failed or if the result from the
* function was invalid.
*/
CallResult call(String functionName,
Map parameters)
throws IllegalArgumentException, IOException, InvalidCallResultException;
}
| src/java-client-framework/org/xins/client/FunctionCaller.java | /*
* $Id$
*/
package org.xins.client;
import java.io.IOException;
import java.util.Map;
/**
* Interface for API function calling functionality.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
public interface FunctionCaller {
/**
* Calls the specified API function.
*
* @param functionName
* the name of the function to be called, not <code>null</code>.
*
* @param parameters
* the parameters which are passed to that function, or
* <code>null</code>; keys must be {@link String Strings}, values can be
* of any class.
*
* @return
* the call result, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>functionName == null</code>.
*
* @throws IOException
* if the API could not be contacted due to an I/O error.
*
* @throws InvalidCallResultException
* if the calling of the function failed or if the result from the
* function was invalid.
*/
CallResult call(String functionName,
Map parameters)
throws IllegalArgumentException, IOException, InvalidCallResultException;
}
| Improved the Javadoc comment for call(String,Map).
| src/java-client-framework/org/xins/client/FunctionCaller.java | Improved the Javadoc comment for call(String,Map). |
|
Java | apache-2.0 | 7a548900ab2f49c8d3d5decbcba34189170b498b | 0 | peopleware/java-ppwcode-vernacular-persistence,peopleware/java-ppwcode-vernacular-persistence | src/main/java/be/peopleware/persistence_II/dao/PagingList.java | /*<license>
Copyright 2004, PeopleWare n.v.
NO RIGHTS ARE GRANTED FOR THE USE OF THIS SOFTWARE, EXCEPT, IN WRITING,
TO SELECTED PARTIES.
</license>*/
package be.peopleware.persistence_II.dao;
import java.util.AbstractSequentialList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ppwcode.vernacular.exception_N.TechnicalException;
import org.ppwcode.vernacular.persistence_III.PersistentBean;
/**
* A list of lists, that contains the result of a query
* using paging. Each page, except for the last,
* has size {@link #getPageSize()}.
* When the virtual resultset on the DB changes during iteration,
* we throw a {@link ConcurrentModificationException} when the next
* page is requested.
*
* @author Jan Dockx
* @author Peopleware n.v.
*
* @invar getPageSize() > 0;
*/
public abstract class PagingList extends AbstractSequentialList {
/*<section name="Meta Information">*/
//------------------------------------------------------------------
/** {@value} */
public static final String CVS_REVISION = "$Revision$";
/** {@value} */
public static final String CVS_DATE = "$Date$";
/** {@value} */
public static final String CVS_STATE = "$State$";
/** {@value} */
public static final String CVS_TAG = "$Name$";
/*</section>*/
private static final Log LOG = LogFactory.getLog(PagingList.class);
/*<construction>*/
//------------------------------------------------------------------
/**
* @pre pageSize > 0;
* @pre recordCount >= 0;
* @post new.getPageSize() == pageSize;
*
* @throws TechnicalException
*/
protected PagingList(int pageSize, int recordCount) throws TechnicalException {
assert pageSize > 0;
assert recordCount >= 0;
$pageSize = pageSize;
$recordCount = recordCount;
$size = ($recordCount == 0) ? 0 : (($recordCount - 1) / getPageSize()) + 1;
}
/*</construction>*/
protected abstract int retrieveRecordCount() throws TechnicalException;
protected abstract List retrievePage(int retrieveSize, int startOfPage) throws TechnicalException;
/*<property name="page size">*/
//------------------------------------------------------------------
/**
* @basic
*/
public final int getPageSize() {
return $pageSize;
}
/**
* @invar $pageSize > 0;
*/
private int $pageSize;
/*</property>*/
/*<property name="record count">*/
//------------------------------------------------------------------
/**
* This must be the same on the next DB access,
* or we give a {@link java.util.ConcurrentModificationException}.
*
* @basic
*/
public final int getRecordCount() {
return $recordCount;
}
/**
* @invar $recordCount >= 0;
*/
private int $recordCount;
/*</property>*/
/*<property name="size">*/
//------------------------------------------------------------------
/**
* The number of pages. This might change,
* when a next page is requested.
*
* @basic
*/
public final int size() {
return $size;
}
/**
* @invar $pageSize > 0;
*/
private int $size;
/*</property>*/
/**
* @result result instanceof PagesIterator;
*/
public final ListIterator listIterator(int index) {
return new PagesIterator(index);
}
public final class PagesIterator implements ListIterator {
/*<construction>*/
//------------------------------------------------------------------
/**
* @pre page >= 0;
* @pre page < size();
* @post new.nextIndex() == page;
*/
public PagesIterator(int page) {
assert page >= 0;
assert page < size();
$nextPage = page;
}
/*</construction>*/
/*<property name="currentPage">*/
//------------------------------------------------------------------
/**
* @basic
*/
public final int nextIndex() {
return $nextPage;
}
/**
* @return = nextIndex() - 1;
*/
public final int previousIndex() {
return $nextPage - 1;
}
/**
* @return nextIndex() < size() - 1;
*/
public final boolean hasNext() {
return $nextPage < size();
}
/**
* @return nextIndex() > 0;
*/
public final boolean hasPrevious() {
return $nextPage > 0;
}
private int $nextPage;
/*</property>*/
/*<property name="expected pk of next and previous page">*/
//------------------------------------------------------------------
private Object $expectedFirstPkOfNextPage;
private Object $expectedLastPkOfPreviousPage;
/*</property>*/
/**
* We will retrieve 1 record extra before and after this page,
* and remember it's PK; for the next or previous page, we can
* check that it is the expected record; we cannot do this
* for the first retrieval, or for the first or last page
*/
public Object next() throws ConcurrentModificationException {
LOG.debug("retrieving next page (" + $nextPage + ")");
try {
validateCount();
boolean isFirstPage = $nextPage <= 0;
boolean isLastPage = $nextPage >= size() - 1;
List page = retrievePage(isFirstPage, isLastPage, $nextPage);
validateOverlap($expectedFirstPkOfNextPage, page, 1);
/* real first page record is at 1 (0 is a dummy for
* the previous after this, which we will remember in a
* moment; nothing will happen for the first page,
* where this is not true.
*/
rememberPks(isFirstPage, isLastPage, page);
$nextPage++; // update cursor info
return page;
}
catch (TechnicalException hExc) {
throw new TechnicalProblemException(hExc);
}
}
/**
* We will retrieve 1 record extra before and after this page,
* and remember it's PK; for the next or previous page, we can
* check that it is the expected record; we cannot do this
* for the first retrieval, or for the first or last page
*/
public Object previous() throws ConcurrentModificationException {
int pageToRetrieve = $nextPage - 1;
LOG.debug("retrieving previous page (" + pageToRetrieve + ")");
try {
validateCount();
boolean isFirstPage = pageToRetrieve <= 0;
boolean isLastPage = pageToRetrieve >= size() - 1;
List page = retrievePage(isFirstPage, isLastPage, pageToRetrieve);
validateOverlap($expectedLastPkOfPreviousPage, page, size() - 2);
/* real first page record is at size() - 2 (size() - 1 is a dummy for
* the next after this, which we will remember in a
* moment; nothing will happen for the last page,
* where this is not true.
*/
rememberPks(isFirstPage, isLastPage, page);
$nextPage--; // update cursor info
return page;
}
catch (TechnicalException hExc) {
throw new TechnicalProblemException(hExc);
}
}
private List retrievePage(boolean isFirstPage, boolean isLastPage, int pageToRetrieve)
throws TechnicalException, ConcurrentModificationException {
LOG.debug("retrieving page " + pageToRetrieve);
int retrieveSize = getPageSize() + (isFirstPage ? 0 : 1) + (isLastPage ? 0 : 1);
int realStartOfPage = pageToRetrieve * getPageSize();
int startOfPage = isFirstPage ? realStartOfPage : realStartOfPage - 1;
List page = PagingList.this.retrievePage(retrieveSize, startOfPage);
LOG.debug("page retrieved successfully");
if (page.isEmpty()) {
throw new ConcurrentModificationException("page is empty: resultset for this query changed since last DB access");
}
return page;
}
public class TechnicalProblemException extends RuntimeException {
public TechnicalProblemException(Throwable cause) {
super(cause);
}
}
private void validateCount() throws ConcurrentModificationException, TechnicalException {
LOG.debug("validating that count of total set has not changed");
int newRecordCount = retrieveRecordCount();
if (newRecordCount != getRecordCount()) {
throw new ConcurrentModificationException("total record count for this query changed since last DB access");
}
}
/**
* With a next page, we want to check the first real record: is it what we expected?
* With a previous page, we want to check the last real record: is it what we expected?
* We do not have an expected PK though, when this is the first page to access
* (which could be in the middle of things).
*
* This does nothing if <code>expectedKey</code> is <code>null</code>.
*
* For a next, the position to check is 1 (at position 0 there is a dummy
* to store for the "previous" after this). For a previous, the position to
* check is size() - 2 (at position size() - 1 there is a dummy to store for
* the "next" after this). For the first page however, there is no dummy at
* the start, and for the last there is no dummy at the end, so we would need
* to differ the position at which to look in the list. However, this method will
* never be called for those cases: the last page can only be retrieved with
* next, or with a previous when <code>!hasNext()</code>, that potentially follows a next.
* For a next, we only check the first record, which follows the rules. The last
* next overwrites the remembered PK with null (see {@link #rememberPks(boolean, boolean, List)},
* so no check will be done with the previous that follows. The first page
* can only be retrieved with a next when <code>!hasPrevious()</code>,
* that potentially follows a previous, or with a previous. For a previous,
* we only check the last record, which follows the rules. The last previous
* overwrites the remembered PK with null (see {@link #rememberPks(boolean, boolean, List)},
* so no check will be done in the next that follows. Both remembered PK's are null
* initially.
* The last issue arises when a page is both the first and the last page. This
* page can be reached with both a next and a previous, but always with
* either !hasPrevious or !hasNext(). In this case, nothing is remembered, ever,
* and there will be no test.
* In conclusion we can say that using 1 and size() - 2 as the positions to test
* is ok in all cases, and diversification is not needed.
*/
private void validateOverlap(Object expectedKey, List page, int overlapPosition) throws ConcurrentModificationException {
LOG.debug("validating overlap: expectedKey = " + expectedKey + " for position = " + overlapPosition);
if ($expectedLastPkOfPreviousPage != null) {
PersistentBean pb = (PersistentBean)page.get(overlapPosition);
LOG.debug("actual id = " + pb.getId());
if (! expectedKey.equals(pb.getId())) {
throw new ConcurrentModificationException("resultset for this query changed since last DB access");
}
}
}
private void rememberPks(boolean isFirstPage, boolean isLastPage, List page) {
LOG.debug("remembering PK of first and last record");
/*
* remember the potential extra records at start and end for the
* next retrieve, and remove them from the result
*/
if (! isLastPage) {
int lastIndex = page.size() - 1;
PersistentBean pb = (PersistentBean)page.get(lastIndex);
$expectedFirstPkOfNextPage = pb.getId();
LOG.debug("new $expectedFirstPkOfNextPage: " + $expectedFirstPkOfNextPage);
page.remove(lastIndex);
}
else {
$expectedFirstPkOfNextPage = null;
}
if (! isFirstPage) {
PersistentBean pb = (PersistentBean)page.get(0);
$expectedLastPkOfPreviousPage = pb.getId();
LOG.debug("new $expectedLastPkOfPreviousPage: " + $expectedLastPkOfPreviousPage);
page.remove(0);
}
else {
$expectedLastPkOfPreviousPage = null;
}
}
/**
* @post false;
* @throws UnsupportedOperationException
* true;
*/
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* @post false;
* @throws UnsupportedOperationException
* true;
*/
public void set(Object o) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* @post false;
* @throws UnsupportedOperationException
* true;
*/
public void add(Object o) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
}
| remove old PagingList
git-svn-id: 380e98d998f12029d9780e105f217f907d976ae8@1392 6057c1f7-a7c9-48c9-a9a6-1240b2ac66dc
| src/main/java/be/peopleware/persistence_II/dao/PagingList.java | remove old PagingList |
||
Java | mit | ff9416a9fdc8c8b8f13ce8b0783b68a7011e371d | 0 | jklingsporn/vertx-jooq | package io.github.jklingsporn.vertx.jooq.generate.rx;
import io.github.jklingsporn.vertx.jooq.rx.RXQueryExecutor;
import io.github.jklingsporn.vertx.jooq.shared.internal.AbstractVertxDAO;
import io.github.jklingsporn.vertx.jooq.shared.internal.GenericVertxDAO;
import io.github.jklingsporn.vertx.jooq.shared.internal.QueryResult;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import org.jooq.*;
import org.jooq.exception.TooManyRowsException;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Created by jensklingsporn on 09.02.18.
*/
public abstract class RXTestBase<P,T,O, DAO extends GenericVertxDAO<?,P, T, Single<List<P>>, Single<Optional<P>>, Single<Integer>, Single<T>>> {
private final TableField<?,O> otherfield;
protected final DAO dao;
protected RXTestBase(TableField<?, O> otherfield, DAO dao) {
this.otherfield = otherfield;
this.dao = dao;
}
protected abstract P create();
protected abstract P createWithId();
protected abstract P setId(P pojo, T id);
protected abstract P setSomeO(P pojo, O someO);
protected abstract T getId(P pojo);
protected abstract O createSomeO();
protected abstract Condition eqPrimaryKey(T id);
protected abstract void assertDuplicateKeyException(Throwable x);
protected void await(CountDownLatch latch) {
try {
if(!latch.await(3, TimeUnit.SECONDS)){
Assert.fail("latch not triggered");
}
} catch (InterruptedException e) {
Assert.fail(e.getMessage());
}
}
/**
* Recursively checks if cause or cause's cause is of type expected.
* @param expected
* @param cause
*/
protected void assertException(Class<? extends Throwable> expected, Throwable cause){
assertException(expected, cause, c->{});
}
protected <X extends Throwable> void assertException(Class<X> expected, Throwable cause, Consumer<X> checker){
if(!expected.equals(cause.getClass())){
if(cause.getCause()!=null){
assertException(expected,cause.getCause(),checker);
}else{
Assert.assertEquals(expected, cause.getClass());
checker.accept(expected.cast(cause));
}
}
//Cool, same class
}
protected <T> SingleObserver<T> countdownLatchHandler(final CountDownLatch latch){
return new SingleObserver<T>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(T t) {
latch.countDown();
}
@Override
public void onError(Throwable x) {
x.printStackTrace();
Assert.fail(x.getMessage());
latch.countDown();
}
};
}
protected Single<T> insertAndReturn(P something) {
return dao.insertReturningPrimary(something);
}
protected RXQueryExecutor queryExecutor(){
return (RXQueryExecutor) dao.queryExecutor();
}
@Test
public void asyncCRUDShouldSucceed() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
insertAndReturn(create())
.flatMap(dao::findOneById)
.flatMap(something -> dao
.update(setSomeO(something.get(), createSomeO()))
.flatMap(updatedRows -> {
Assert.assertEquals(1l, updatedRows.longValue());
return dao
.deleteById(getId(something.get()))
.doOnSuccess(deletedRows -> Assert.assertEquals(1l, deletedRows.longValue()));
}))
.subscribe(countdownLatchHandler(latch))
;
await(latch);
}
@Test
public void asyncCRUDMultipleSucceed() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
P something1 = createWithId();
P something2 = createWithId();
dao.insert(Arrays.asList(something1, something2))
.doOnSuccess(inserted -> Assert.assertEquals(2L, inserted.longValue()))
.flatMap(v -> dao.findManyByIds(Arrays.asList(getId(something1), getId(something2))))
.flatMap(values -> {
Assert.assertEquals(2L, values.size());
return dao.deleteByIds(values.stream().map(this::getId).collect(Collectors.toList()));
})
.doOnSuccess(deleted -> Assert.assertEquals(2L, deleted.longValue()))
.subscribe(countdownLatchHandler(latch))
;
await(latch);
}
@Test
public void insertReturningShouldFailOnDuplicateKey() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
P something = create();
insertAndReturn(something)
.flatMap(id -> insertAndReturn(setId(something, id)))
.doOnSuccess(v-> Assert.fail("Expected DuplicateKey"))
.onErrorResumeNext((x) -> {
Assert.assertNotNull(x);
assertDuplicateKeyException(x);
return Single.just(getId(something));
})
.flatMap(v -> dao.deleteByCondition(DSL.trueCondition()))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void asyncCRUDConditionShouldSucceed() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
P something = create();
Single<T> insertFuture = insertAndReturn(something);
insertFuture
.doOnSuccess(t->setId(something,t))
.flatMap(v -> dao.findOneByCondition(eqPrimaryKey(getId(something))))
.doOnSuccess(this::optionalAssertNotNull)
.flatMap(v -> dao.deleteByCondition(eqPrimaryKey(getId(something))))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findOneByConditionWithMultipleMatchesShouldFail() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
O someO = createSomeO();
Single<T> insertFuture1 = insertAndReturn(setSomeO(create(), someO));
Single<T> insertFuture2 = insertAndReturn(setSomeO(create(), someO));
Single.zip(insertFuture1, insertFuture2, (i1, i2) -> i1)
.flatMap(v -> dao.findOneByCondition(otherfield.eq(someO)))
.doOnSuccess(v -> Assert.fail("Expected TooManyRowsException"))
.onErrorResumeNext(x -> {
Assert.assertNotNull(x);
//cursor found more than one row
assertException(TooManyRowsException.class, x);
return Single.just(Optional.of(create()));
})
.flatMap(v -> dao.deleteByCondition(otherfield.eq(someO)))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findManyByConditionWithMultipleMatchesShouldSucceed() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
O someO = createSomeO();
Single<T> insertFuture1 = insertAndReturn(setSomeO(create(), someO));
Single<T> insertFuture2 = insertAndReturn(setSomeO(create(), someO));
Single.zip(insertFuture1, insertFuture2, (i1, i2) -> i1).
flatMap(v -> dao.findManyByCondition(otherfield.eq(someO))).
doOnSuccess(values -> Assert.assertEquals(2, values.size())).
flatMap(v -> dao.deleteByCondition(otherfield.eq(someO))).
subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findAllShouldReturnValues() throws InterruptedException{
CountDownLatch latch = new CountDownLatch(1);
Single<T> insertFuture1 = insertAndReturn(create());
Single<T> insertFuture2 = insertAndReturn(create());
Single.zip(insertFuture1, insertFuture2,(i1, i2) -> i1).
flatMap(v -> dao.findAll()).
doOnSuccess(list -> {
Assert.assertNotNull(list);
Assert.assertEquals(2, list.size());
}).
flatMap(v -> dao.deleteByCondition(DSL.trueCondition())).
subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findOneNoMatchShouldReturnEmptyOptional() throws InterruptedException {
//because Single does not permit null values, RX-API has to return Optional<P> for findOne
CountDownLatch latch = new CountDownLatch(1);
dao.findOneByCondition(DSL.falseCondition())
.doOnSuccess(opt->Assert.assertFalse(opt.isPresent()))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findManyNoMatchShouldReturnEmptyCollection() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
dao.findManyByCondition(DSL.falseCondition())
.doOnSuccess(res->Assert.assertTrue(res.isEmpty()))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void insertPojoOnDuplicateKeyShouldSucceedOnDuplicateEntry() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
P withId = createWithId();
dao
.insert(withId)
.doOnSuccess(i -> Assert.assertEquals(1L, i.longValue()))
.flatMap(v -> dao.insert(withId, true))
.doOnSuccess(i -> Assert.assertEquals(0L, i.longValue()))
.flatMap(v->dao.deleteById(getId(withId)))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
@SuppressWarnings("unchecked")
public void unifiedQueryExecutorCRUDTest() throws InterruptedException {
Table<? extends UpdatableRecord<?>> table = ((AbstractVertxDAO) dao).getTable();
P pojo = createWithId();
CountDownLatch latch = new CountDownLatch(1);
queryExecutor()
.execute(dslContext -> dslContext
.insertInto(table).set(dslContext.newRecord(table, pojo)))
.doOnSuccess((i -> Assert.assertEquals(1L, i.longValue())))
.flatMap(v -> queryExecutor().query(dslContext -> dslContext
.selectFrom(table)
.where(eqPrimaryKey(getId(pojo)))
.limit(1)))
.doOnSuccess((queryResult -> {
Assert.assertTrue(queryResult.hasResults());
Field<?>[] fields = table.fieldsRow().fields();
UpdatableRecord<?> record = DSL.using(new DefaultConfiguration()).newRecord(table, pojo);
for (int i = 0; i < fields.length; i++) {
boolean hasValidValue = record.get(fields[i]) != null;
if (hasValidValue)
assertQueryResultReturnsValidValue(fields[i], queryResult, i);
}
List<QueryResult> queryResults = queryResult.asList();
Assert.assertEquals(1L, queryResults.size());
queryResults.forEach(res -> {
for (int i = 0; i < fields.length; i++) {
boolean hasValidValue = record.get(fields[i]) != null;
if (hasValidValue)
assertQueryResultReturnsValidValue(fields[i], res, i);
}
});
}))
.flatMap(v -> queryExecutor().execute(dslContext -> dslContext.deleteFrom(table).where(eqPrimaryKey(getId(pojo)))))
.doOnSuccess((i -> Assert.assertEquals(1L, i.longValue())))
.subscribe(countdownLatchHandler(latch))
;
await(latch);
}
private void assertQueryResultReturnsValidValue(Field<?> field, QueryResult queryResult, int index) {
Assert.assertNotNull(queryResult.get(field));
//can't guarantee correct conversion for get(String,Class<?>) and get(Integer,Class<?>)
if(field.getConverter().fromType().equals(field.getConverter().toType())){
Assert.assertNotNull(queryResult.get(index, field.getType()));
Assert.assertNotNull(queryResult.get(field.getName(), field.getType()));
}
}
protected <T> void optionalAssertNotNull(Optional<T> value){
Assert.assertTrue(value.isPresent());
}
protected <T> void optionalAssertNull(Optional<T> value){
Assert.assertFalse(value.isPresent());
}
@Test
@SuppressWarnings("unchecked")
public void unifiedQueryExecutorNoResultShouldThrowNSEException() throws InterruptedException {
Table<? extends UpdatableRecord<?>> table = ((AbstractVertxDAO) dao).getTable();
P pojo = createWithId();
CountDownLatch latch = new CountDownLatch(1);
queryExecutor()
.query(dslContext -> dslContext
.selectFrom(table)
.where(eqPrimaryKey(getId(pojo)))
.limit(1))
.doOnSuccess(queryResult -> {
Assert.assertFalse(queryResult.hasResults());
Field<?>[] fields = table.fieldsRow().fields();
for (int i=0;i<fields.length;i++) {
Field<?> field = fields[i];
try {
queryResult.get(field);
} catch (NoSuchElementException e) {
//ok
}
try {
queryResult.get(field.getName(), field.getType());
} catch (NoSuchElementException e) {
//ok
}
try {
queryResult.get(i, field.getType());
} catch (NoSuchElementException e) {
//ok
continue;
}
Assert.fail("Expected NoSuchElementException");
}
})
.subscribe(countdownLatchHandler(latch))
;
await(latch);
}
@Test
public void findManyWithLimitShouldReturnLimitedResults() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Single<T> insertFuture1 = insertAndReturn(create());
Single<T> insertFuture2 = insertAndReturn(create());
Single.zip(insertFuture1, insertFuture2,(i1, i2) -> i1).
flatMap(v -> dao.findManyByCondition(DSL.trueCondition(),1)).
doOnSuccess(list -> {
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
}).
flatMap(v -> dao.deleteByCondition(DSL.trueCondition())).
subscribe(countdownLatchHandler(latch));
await(latch);
}
}
| vertx-jooq-generate/src/test/java/io/github/jklingsporn/vertx/jooq/generate/rx/RXTestBase.java | package io.github.jklingsporn.vertx.jooq.generate.rx;
import io.github.jklingsporn.vertx.jooq.rx.RXQueryExecutor;
import io.github.jklingsporn.vertx.jooq.shared.internal.AbstractVertxDAO;
import io.github.jklingsporn.vertx.jooq.shared.internal.GenericVertxDAO;
import io.github.jklingsporn.vertx.jooq.shared.internal.QueryResult;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import org.jooq.*;
import org.jooq.exception.TooManyRowsException;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* Created by jensklingsporn on 09.02.18.
*/
public abstract class RXTestBase<P,T,O, DAO extends GenericVertxDAO<?,P, T, Single<List<P>>, Single<Optional<P>>, Single<Integer>, Single<T>>> {
private final TableField<?,O> otherfield;
protected final DAO dao;
protected RXTestBase(TableField<?, O> otherfield, DAO dao) {
this.otherfield = otherfield;
this.dao = dao;
}
protected abstract P create();
protected abstract P createWithId();
protected abstract P setId(P pojo, T id);
protected abstract P setSomeO(P pojo, O someO);
protected abstract T getId(P pojo);
protected abstract O createSomeO();
protected abstract Condition eqPrimaryKey(T id);
protected abstract void assertDuplicateKeyException(Throwable x);
protected void await(CountDownLatch latch) {
try {
if(!latch.await(3, TimeUnit.SECONDS)){
Assert.fail("latch not triggered");
}
} catch (InterruptedException e) {
Assert.fail(e.getMessage());
}
}
/**
* Recursively checks if cause or cause's cause is of type expected.
* @param expected
* @param cause
*/
protected void assertException(Class<? extends Throwable> expected, Throwable cause){
assertException(expected, cause, c->{});
}
protected <X extends Throwable> void assertException(Class<X> expected, Throwable cause, Consumer<X> checker){
if(!expected.equals(cause.getClass())){
if(cause.getCause()!=null){
assertException(expected,cause.getCause(),checker);
}else{
Assert.assertEquals(expected, cause.getClass());
checker.accept(expected.cast(cause));
}
}
//Cool, same class
}
protected <T> SingleObserver<T> countdownLatchHandler(final CountDownLatch latch){
return new SingleObserver<T>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onSuccess(T t) {
latch.countDown();
}
@Override
public void onError(Throwable x) {
x.printStackTrace();
// Assert.fail(x.getMessage());
latch.countDown();
}
};
}
protected Single<T> insertAndReturn(P something) {
return dao.insertReturningPrimary(something);
}
protected RXQueryExecutor queryExecutor(){
return (RXQueryExecutor) dao.queryExecutor();
}
@Test
public void asyncCRUDShouldSucceed() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
insertAndReturn(create())
.flatMap(dao::findOneById)
.flatMap(something -> dao
.update(setSomeO(something.get(), createSomeO()))
.flatMap(updatedRows -> {
Assert.assertEquals(1l, updatedRows.longValue());
return dao
.deleteById(getId(something.get()))
.doOnSuccess(deletedRows -> Assert.assertEquals(1l, deletedRows.longValue()));
}))
.subscribe(countdownLatchHandler(latch))
;
await(latch);
}
@Test
public void asyncCRUDMultipleSucceed() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
P something1 = createWithId();
P something2 = createWithId();
dao.insert(Arrays.asList(something1, something2))
.doOnSuccess(inserted -> Assert.assertEquals(2L, inserted.longValue()))
.flatMap(v -> dao.findManyByIds(Arrays.asList(getId(something1), getId(something2))))
.flatMap(values -> {
Assert.assertEquals(2L, values.size());
return dao.deleteByIds(values.stream().map(this::getId).collect(Collectors.toList()));
})
.doOnSuccess(deleted -> Assert.assertEquals(2L, deleted.longValue()))
.subscribe(countdownLatchHandler(latch))
;
await(latch);
}
@Test
public void insertReturningShouldFailOnDuplicateKey() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
P something = create();
insertAndReturn(something)
.flatMap(id -> insertAndReturn(setId(something, id)))
.doOnSuccess(v-> Assert.fail("Expected DuplicateKey"))
.onErrorResumeNext((x) -> {
Assert.assertNotNull(x);
assertDuplicateKeyException(x);
return Single.just(getId(something));
})
.flatMap(v -> dao.deleteByCondition(DSL.trueCondition()))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void asyncCRUDConditionShouldSucceed() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
P something = create();
Single<T> insertFuture = insertAndReturn(something);
insertFuture
.doOnSuccess(t->setId(something,t))
.flatMap(v -> dao.findOneByCondition(eqPrimaryKey(getId(something))))
.doOnSuccess(this::optionalAssertNotNull)
.flatMap(v -> dao.deleteByCondition(eqPrimaryKey(getId(something))))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findOneByConditionWithMultipleMatchesShouldFail() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
O someO = createSomeO();
Single<T> insertFuture1 = insertAndReturn(setSomeO(create(), someO));
Single<T> insertFuture2 = insertAndReturn(setSomeO(create(), someO));
Single.zip(insertFuture1, insertFuture2, (i1, i2) -> i1)
.flatMap(v -> dao.findOneByCondition(otherfield.eq(someO)))
.doOnSuccess(v -> Assert.fail("Expected TooManyRowsException"))
.onErrorResumeNext(x -> {
Assert.assertNotNull(x);
//cursor found more than one row
assertException(TooManyRowsException.class, x);
return Single.just(Optional.of(create()));
})
.flatMap(v -> dao.deleteByCondition(otherfield.eq(someO)))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findManyByConditionWithMultipleMatchesShouldSucceed() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
O someO = createSomeO();
Single<T> insertFuture1 = insertAndReturn(setSomeO(create(), someO));
Single<T> insertFuture2 = insertAndReturn(setSomeO(create(), someO));
Single.zip(insertFuture1, insertFuture2, (i1, i2) -> i1).
flatMap(v -> dao.findManyByCondition(otherfield.eq(someO))).
doOnSuccess(values -> Assert.assertEquals(2, values.size())).
flatMap(v -> dao.deleteByCondition(otherfield.eq(someO))).
subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findAllShouldReturnValues() throws InterruptedException{
CountDownLatch latch = new CountDownLatch(1);
Single<T> insertFuture1 = insertAndReturn(create());
Single<T> insertFuture2 = insertAndReturn(create());
Single.zip(insertFuture1, insertFuture2,(i1, i2) -> i1).
flatMap(v -> dao.findAll()).
doOnSuccess(list -> {
Assert.assertNotNull(list);
Assert.assertEquals(2, list.size());
}).
flatMap(v -> dao.deleteByCondition(DSL.trueCondition())).
subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findOneNoMatchShouldReturnEmptyOptional() throws InterruptedException {
//because Single does not permit null values, RX-API has to return Optional<P> for findOne
CountDownLatch latch = new CountDownLatch(1);
dao.findOneByCondition(DSL.falseCondition())
.doOnSuccess(opt->Assert.assertFalse(opt.isPresent()))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void findManyNoMatchShouldReturnEmptyCollection() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
dao.findManyByCondition(DSL.falseCondition())
.doOnSuccess(res->Assert.assertTrue(res.isEmpty()))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
public void insertPojoOnDuplicateKeyShouldSucceedOnDuplicateEntry() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
P withId = createWithId();
dao
.insert(withId)
.doOnSuccess(i -> Assert.assertEquals(1L, i.longValue()))
.flatMap(v -> dao.insert(withId, true))
.doOnSuccess(i -> Assert.assertEquals(0L, i.longValue()))
.flatMap(v->dao.deleteById(getId(withId)))
.subscribe(countdownLatchHandler(latch));
await(latch);
}
@Test
@SuppressWarnings("unchecked")
public void unifiedQueryExecutorCRUDTest() throws InterruptedException {
Table<? extends UpdatableRecord<?>> table = ((AbstractVertxDAO) dao).getTable();
P pojo = createWithId();
CountDownLatch latch = new CountDownLatch(1);
queryExecutor()
.execute(dslContext -> dslContext
.insertInto(table).set(dslContext.newRecord(table, pojo)))
.doOnSuccess((i -> Assert.assertEquals(1L, i.longValue())))
.flatMap(v -> queryExecutor().query(dslContext -> dslContext
.selectFrom(table)
.where(eqPrimaryKey(getId(pojo)))
.limit(1)))
.doOnSuccess((queryResult -> {
Assert.assertTrue(queryResult.hasResults());
Field<?>[] fields = table.fieldsRow().fields();
UpdatableRecord<?> record = DSL.using(new DefaultConfiguration()).newRecord(table, pojo);
for (int i = 0; i < fields.length; i++) {
boolean hasValidValue = record.get(fields[i]) != null;
if (hasValidValue)
assertQueryResultReturnsValidValue(fields[i], queryResult, i);
}
List<QueryResult> queryResults = queryResult.asList();
Assert.assertEquals(1L, queryResults.size());
queryResults.forEach(res -> {
for (int i = 0; i < fields.length; i++) {
boolean hasValidValue = record.get(fields[i]) != null;
if (hasValidValue)
assertQueryResultReturnsValidValue(fields[i], res, i);
}
});
}))
.flatMap(v -> queryExecutor().execute(dslContext -> dslContext.deleteFrom(table).where(eqPrimaryKey(getId(pojo)))))
.doOnSuccess((i -> Assert.assertEquals(1L, i.longValue())))
.subscribe(countdownLatchHandler(latch))
;
await(latch);
}
private void assertQueryResultReturnsValidValue(Field<?> field, QueryResult queryResult, int index) {
Assert.assertNotNull(queryResult.get(field));
//can't guarantee correct conversion for get(String,Class<?>) and get(Integer,Class<?>)
if(field.getConverter().fromType().equals(field.getConverter().toType())){
Assert.assertNotNull(queryResult.get(index, field.getType()));
Assert.assertNotNull(queryResult.get(field.getName(), field.getType()));
}
}
protected <T> void optionalAssertNotNull(Optional<T> value){
Assert.assertTrue(value.isPresent());
}
protected <T> void optionalAssertNull(Optional<T> value){
Assert.assertFalse(value.isPresent());
}
@Test
@SuppressWarnings("unchecked")
public void unifiedQueryExecutorNoResultShouldThrowNSEException() throws InterruptedException {
Table<? extends UpdatableRecord<?>> table = ((AbstractVertxDAO) dao).getTable();
P pojo = createWithId();
CountDownLatch latch = new CountDownLatch(1);
queryExecutor()
.query(dslContext -> dslContext
.selectFrom(table)
.where(eqPrimaryKey(getId(pojo)))
.limit(1))
.doOnSuccess(queryResult -> {
Assert.assertFalse(queryResult.hasResults());
Field<?>[] fields = table.fieldsRow().fields();
for (int i=0;i<fields.length;i++) {
Field<?> field = fields[i];
try {
queryResult.get(field);
} catch (NoSuchElementException e) {
//ok
}
try {
queryResult.get(field.getName(), field.getType());
} catch (NoSuchElementException e) {
//ok
}
try {
queryResult.get(i, field.getType());
} catch (NoSuchElementException e) {
//ok
continue;
}
Assert.fail("Expected NoSuchElementException");
}
})
.subscribe(countdownLatchHandler(latch))
;
await(latch);
}
@Test
public void findManyWithLimitShouldReturnLimitedResults() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
Single<T> insertFuture1 = insertAndReturn(create());
Single<T> insertFuture2 = insertAndReturn(create());
Single.zip(insertFuture1, insertFuture2,(i1, i2) -> i1).
flatMap(v -> dao.findManyByCondition(DSL.trueCondition(),1)).
doOnSuccess(list -> {
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
}).
flatMap(v -> dao.deleteByCondition(DSL.trueCondition())).
subscribe(countdownLatchHandler(latch));
await(latch);
}
}
| test should fail
| vertx-jooq-generate/src/test/java/io/github/jklingsporn/vertx/jooq/generate/rx/RXTestBase.java | test should fail |
|
Java | mit | f94c6fd58f0653046781d6bd6535ead29dd3caa3 | 0 | bugsnag/bugsnag-java,bugsnag/bugsnag-java,bugsnag/bugsnag-java | package com.bugsnag.callbacks;
import com.bugsnag.Report;
import com.bugsnag.util.DaemonThreadFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class DeviceCallback implements Callback {
private static volatile String hostname;
private static transient volatile boolean hostnameInitialised;
private static final Object LOCK = new Object();
private static final int HOSTNAME_LOOKUP_TIMEOUT = 10000;
/**
* Memoises the hostname, as lookup can be expensive
*/
public static String getHostnameValue() {
if (!hostnameInitialised) {
synchronized (LOCK) {
if (!hostnameInitialised) {
hostname = lookupHostname();
hostnameInitialised = true;
}
}
}
return hostname;
}
private static String lookupHostname() {
// Windows always sets COMPUTERNAME
if (System.getProperty("os.name").startsWith("Windows")) {
return System.getenv("COMPUTERNAME");
}
// Try the HOSTNAME env variable (most unix systems)
String hostname = System.getenv("HOSTNAME");
if (hostname != null) {
return hostname;
}
// Resort to dns hostname lookup.
// Look up the hostname in a daemon thread, with a timeout of HOSTNAME_LOOKUP_TIMEOUT.
// This is to prevent applications hanging waiting for the dns lookup to resolve
ExecutorService lookupService = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
Future<String> future = lookupService.submit(new Callable<String>() {
@Override
public String call() throws UnknownHostException {
return InetAddress.getLocalHost().getHostName();
}
});
try {
return future.get(HOSTNAME_LOOKUP_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (ExecutionException ex) {
// Give up
} catch (InterruptedException ex) {
// Give up
} catch (TimeoutException ex) {
// Give up
}
return null;
}
public static void initializeCache() {
getHostnameValue();
}
@Override
public void beforeNotify(Report report) {
report
.addToTab("device", "osArch", System.getProperty("os.arch"))
.addToTab("device", "locale", Locale.getDefault())
.setDeviceInfo("hostname", getHostnameValue())
.setDeviceInfo("osName", System.getProperty("os.name"))
.setDeviceInfo("osVersion", System.getProperty("os.version"));
}
}
| bugsnag/src/main/java/com/bugsnag/callbacks/DeviceCallback.java | package com.bugsnag.callbacks;
import com.bugsnag.Report;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
public class DeviceCallback implements Callback {
private static volatile String hostname;
private static transient volatile boolean hostnameInitialised;
private static final Object LOCK = new Object();
/**
* Memoises the hostname, as lookup can be expensive
*/
public static String getHostnameValue() {
if (!hostnameInitialised) {
synchronized (LOCK) {
if (!hostnameInitialised) {
hostname = lookupHostname();
hostnameInitialised = true;
}
}
}
return hostname;
}
private static String lookupHostname() {
// Windows always sets COMPUTERNAME
if (System.getProperty("os.name").startsWith("Windows")) {
return System.getenv("COMPUTERNAME");
}
// Try the HOSTNAME env variable (most unix systems)
String hostname = System.getenv("HOSTNAME");
if (hostname != null) {
return hostname;
}
// Resort to dns hostname lookup
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException ex) {
// Give up
}
return null;
}
public static void initializeCache() {
getHostnameValue();
}
@Override
public void beforeNotify(Report report) {
report
.addToTab("device", "osArch", System.getProperty("os.arch"))
.addToTab("device", "locale", Locale.getDefault())
.setDeviceInfo("hostname", getHostnameValue())
.setDeviceInfo("osName", System.getProperty("os.name"))
.setDeviceInfo("osVersion", System.getProperty("os.version"));
}
}
| Implement timeout for dns hostname lookup
| bugsnag/src/main/java/com/bugsnag/callbacks/DeviceCallback.java | Implement timeout for dns hostname lookup |
|
Java | mit | 355426f8f0eaad83dc58018b3bd546a0d1c35614 | 0 | nilsschmidt1337/ldparteditor,nilsschmidt1337/ldparteditor | /* MIT - License
Copyright (c) 2012 - this year, Nils Schmidt
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 org.nschmidt.ldparteditor.shells.editor3d;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.custom.CTabFolder2Listener;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.opengl.GLCanvas;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.SWTResourceManager;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;
import org.nschmidt.ldparteditor.composites.Composite3D;
import org.nschmidt.ldparteditor.composites.CompositeContainer;
import org.nschmidt.ldparteditor.composites.CompositeScale;
import org.nschmidt.ldparteditor.composites.ToolItem;
import org.nschmidt.ldparteditor.composites.compositetab.CompositeTab;
import org.nschmidt.ldparteditor.composites.compositetab.CompositeTabFolder;
import org.nschmidt.ldparteditor.composites.primitive.CompositePrimitive;
import org.nschmidt.ldparteditor.data.BFC;
import org.nschmidt.ldparteditor.data.DatFile;
import org.nschmidt.ldparteditor.data.DatType;
import org.nschmidt.ldparteditor.data.GColour;
import org.nschmidt.ldparteditor.data.GData;
import org.nschmidt.ldparteditor.data.GData0;
import org.nschmidt.ldparteditor.data.GData1;
import org.nschmidt.ldparteditor.data.GDataBFC;
import org.nschmidt.ldparteditor.data.GDataCSG;
import org.nschmidt.ldparteditor.data.GDataPNG;
import org.nschmidt.ldparteditor.data.GraphicalDataTools;
import org.nschmidt.ldparteditor.data.LibraryManager;
import org.nschmidt.ldparteditor.data.Matrix;
import org.nschmidt.ldparteditor.data.ParsingResult;
import org.nschmidt.ldparteditor.data.Primitive;
import org.nschmidt.ldparteditor.data.ReferenceParser;
import org.nschmidt.ldparteditor.data.RingsAndCones;
import org.nschmidt.ldparteditor.data.Vertex;
import org.nschmidt.ldparteditor.data.VertexManager;
import org.nschmidt.ldparteditor.dialogs.colour.ColourDialog;
import org.nschmidt.ldparteditor.dialogs.copy.CopyDialog;
import org.nschmidt.ldparteditor.dialogs.edger2.EdgerDialog;
import org.nschmidt.ldparteditor.dialogs.intersector.IntersectorDialog;
import org.nschmidt.ldparteditor.dialogs.isecalc.IsecalcDialog;
import org.nschmidt.ldparteditor.dialogs.lines2pattern.Lines2PatternDialog;
import org.nschmidt.ldparteditor.dialogs.logupload.LogUploadDialog;
import org.nschmidt.ldparteditor.dialogs.newproject.NewProjectDialog;
import org.nschmidt.ldparteditor.dialogs.options.OptionsDialog;
import org.nschmidt.ldparteditor.dialogs.partreview.PartReviewDialog;
import org.nschmidt.ldparteditor.dialogs.pathtruder.PathTruderDialog;
import org.nschmidt.ldparteditor.dialogs.rectifier.RectifierDialog;
import org.nschmidt.ldparteditor.dialogs.ringsandcones.RingsAndConesDialog;
import org.nschmidt.ldparteditor.dialogs.rotate.RotateDialog;
import org.nschmidt.ldparteditor.dialogs.round.RoundDialog;
import org.nschmidt.ldparteditor.dialogs.scale.ScaleDialog;
import org.nschmidt.ldparteditor.dialogs.selectvertex.VertexDialog;
import org.nschmidt.ldparteditor.dialogs.setcoordinates.CoordinatesDialog;
import org.nschmidt.ldparteditor.dialogs.slicerpro.SlicerProDialog;
import org.nschmidt.ldparteditor.dialogs.smooth.SmoothDialog;
import org.nschmidt.ldparteditor.dialogs.symsplitter.SymSplitterDialog;
import org.nschmidt.ldparteditor.dialogs.tjunction.TJunctionDialog;
import org.nschmidt.ldparteditor.dialogs.translate.TranslateDialog;
import org.nschmidt.ldparteditor.dialogs.txt2dat.Txt2DatDialog;
import org.nschmidt.ldparteditor.dialogs.unificator.UnificatorDialog;
import org.nschmidt.ldparteditor.dialogs.value.ValueDialog;
import org.nschmidt.ldparteditor.dialogs.value.ValueDialogInt;
import org.nschmidt.ldparteditor.enums.GLPrimitives;
import org.nschmidt.ldparteditor.enums.ManipulatorScope;
import org.nschmidt.ldparteditor.enums.MergeTo;
import org.nschmidt.ldparteditor.enums.MouseButton;
import org.nschmidt.ldparteditor.enums.MyLanguage;
import org.nschmidt.ldparteditor.enums.ObjectMode;
import org.nschmidt.ldparteditor.enums.OpenInWhat;
import org.nschmidt.ldparteditor.enums.Perspective;
import org.nschmidt.ldparteditor.enums.Threshold;
import org.nschmidt.ldparteditor.enums.TransformationMode;
import org.nschmidt.ldparteditor.enums.View;
import org.nschmidt.ldparteditor.enums.WorkingMode;
import org.nschmidt.ldparteditor.helpers.FileHelper;
import org.nschmidt.ldparteditor.helpers.Manipulator;
import org.nschmidt.ldparteditor.helpers.ShellHelper;
import org.nschmidt.ldparteditor.helpers.Sphere;
import org.nschmidt.ldparteditor.helpers.Version;
import org.nschmidt.ldparteditor.helpers.WidgetSelectionHelper;
import org.nschmidt.ldparteditor.helpers.composite3d.Edger2Settings;
import org.nschmidt.ldparteditor.helpers.composite3d.GuiManager;
import org.nschmidt.ldparteditor.helpers.composite3d.IntersectorSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.IsecalcSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.PathTruderSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.RectifierSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.RingsAndConesSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.SelectorSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.SlicerProSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.SymSplitterSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.TJunctionSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.TreeData;
import org.nschmidt.ldparteditor.helpers.composite3d.Txt2DatSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.UnificatorSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.ViewIdleManager;
import org.nschmidt.ldparteditor.helpers.compositetext.ProjectActions;
import org.nschmidt.ldparteditor.helpers.compositetext.SubfileCompiler;
import org.nschmidt.ldparteditor.helpers.math.MathHelper;
import org.nschmidt.ldparteditor.helpers.math.Vector3d;
import org.nschmidt.ldparteditor.i18n.I18n;
import org.nschmidt.ldparteditor.logger.NLogger;
import org.nschmidt.ldparteditor.opengl.OpenGLRenderer;
import org.nschmidt.ldparteditor.project.Project;
import org.nschmidt.ldparteditor.resources.ResourceManager;
import org.nschmidt.ldparteditor.shells.editormeta.EditorMetaWindow;
import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow;
import org.nschmidt.ldparteditor.shells.searchnreplace.SearchWindow;
import org.nschmidt.ldparteditor.text.DatParser;
import org.nschmidt.ldparteditor.text.LDParsingException;
import org.nschmidt.ldparteditor.text.References;
import org.nschmidt.ldparteditor.text.StringHelper;
import org.nschmidt.ldparteditor.text.TextTriangulator;
import org.nschmidt.ldparteditor.text.UTF8BufferedReader;
import org.nschmidt.ldparteditor.text.UTF8PrintWriter;
import org.nschmidt.ldparteditor.widgets.BigDecimalSpinner;
import org.nschmidt.ldparteditor.widgets.TreeItem;
import org.nschmidt.ldparteditor.widgets.ValueChangeAdapter;
import org.nschmidt.ldparteditor.workbench.Composite3DState;
import org.nschmidt.ldparteditor.workbench.Editor3DWindowState;
import org.nschmidt.ldparteditor.workbench.WorkbenchManager;
/**
* The 3D editor window
* <p>
* Note: This class should be instantiated once, it defines all listeners and
* part of the business logic.
*
* @author nils
*
*/
public class Editor3DWindow extends Editor3DDesign {
/** The window state of this window */
private Editor3DWindowState editor3DWindowState;
/** The reference to this window */
private static Editor3DWindow window;
/** The window state of this window */
private SearchWindow searchWindow;
public static final ArrayList<GLCanvas> canvasList = new ArrayList<GLCanvas>();
public static final ArrayList<OpenGLRenderer> renders = new ArrayList<OpenGLRenderer>();
final private static AtomicBoolean alive = new AtomicBoolean(true);
final private static AtomicBoolean no_sync_deadlock = new AtomicBoolean(false);
private boolean addingSomething = false;
private boolean addingVertices = false;
private boolean addingLines = false;
private boolean addingTriangles = false;
private boolean addingQuads = false;
private boolean addingCondlines = false;
private boolean addingDistance = false;
private boolean addingProtractor = false;
private boolean addingSubfiles = false;
private boolean movingAdjacentData = false;
private boolean noTransparentSelection = false;
private boolean bfcToggle = false;
private boolean insertingAtCursorPosition = false;
private ObjectMode workingType = ObjectMode.VERTICES;
private WorkingMode workingAction = WorkingMode.SELECT;
private GColour lastUsedColour = new GColour(16, .5f, .5f, .5f, 1f);
private ManipulatorScope transformationMode = ManipulatorScope.LOCAL;
private int snapSize = 1;
private Txt2DatSettings ts = new Txt2DatSettings();
private Edger2Settings es = new Edger2Settings();
private RectifierSettings rs = new RectifierSettings();
private IsecalcSettings is = new IsecalcSettings();
private SlicerProSettings ss = new SlicerProSettings();
private IntersectorSettings ins = new IntersectorSettings();
private PathTruderSettings ps = new PathTruderSettings();
private SymSplitterSettings sims = new SymSplitterSettings();
private UnificatorSettings us = new UnificatorSettings();
private RingsAndConesSettings ris = new RingsAndConesSettings();
private SelectorSettings sels = new SelectorSettings();
private TJunctionSettings tjs = new TJunctionSettings();
private boolean updatingPngPictureTab;
private int pngPictureUpdateCounter = 0;
private final EditorMetaWindow metaWindow = new EditorMetaWindow();
private boolean updatingSelectionTab = true;
private ArrayList<String> recentItems = new ArrayList<String>();
private HashMap<DatFile, HashMap<Composite3D, org.nschmidt.ldparteditor.composites.Composite3DViewState>> c3dStates = new HashMap<>();
/**
* Create the application window.
*/
public Editor3DWindow() {
super();
final int[] i = new int[1];
final int[] j = new int[1];
final GLCanvas[] first1 = ViewIdleManager.firstCanvas;
final OpenGLRenderer[] first2 = ViewIdleManager.firstRender;
final int[] intervall = new int[] { 10 };
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
if (ViewIdleManager.pause[0].get()) {
ViewIdleManager.pause[0].set(false);
intervall[0] = 500;
} else {
final int cs = canvasList.size();
if (i[0] < cs && cs > 0) {
GLCanvas canvas;
if (!canvasList.get(i[0]).equals(first1[0])) {
canvas = first1[0];
if (canvas != null && !canvas.isDisposed()) {
first2[0].drawScene();
first1[0] = null;
first2[0] = null;
}
}
canvas = canvasList.get(i[0]);
if (!canvas.isDisposed()) {
boolean stdMode = ViewIdleManager.renderLDrawStandard[0].get();
// FIXME Needs workaround since SWT upgrade to 4.5!
if (renders.get(i[0]).getC3D().getRenderMode() != 5 || cs == 1 || stdMode) {
renders.get(i[0]).drawScene();
if (stdMode) {
j[0]++;
}
}
} else {
canvasList.remove(i[0]);
renders.remove(i[0]);
}
i[0]++;
} else {
i[0] = 0;
if (j[0] > cs) {
j[0] = 0;
ViewIdleManager.renderLDrawStandard[0].set(false);
}
}
}
Display.getCurrent().timerExec(intervall[0], this);
intervall[0] = 10;
}
});
}
/**
* Run a fresh instance of this window
*/
public void run() {
window = this;
// Load colours
WorkbenchManager.getUserSettingState().loadColours();
// Load recent files
recentItems = WorkbenchManager.getUserSettingState().getRecentItems();
if (recentItems == null) recentItems = new ArrayList<String>();
// Adjust the last visited path according to what was last opened (and exists on the harddrive)
{
final int rc = recentItems.size() - 1;
boolean foundPath = false;
for (int i = rc; i > -1; i--) {
final String path = recentItems.get(i);
final File f = new File(path);
if (f.exists()) {
if (f.isFile() && f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
foundPath = true;
break;
} else if (f.isDirectory()) {
Project.setLastVisitedPath(path);
foundPath = true;
break;
}
}
}
if (!foundPath) {
final File f = new File(WorkbenchManager.getUserSettingState().getAuthoringFolderPath());
if (f.exists() && f.isDirectory()) {
Project.setLastVisitedPath(WorkbenchManager.getUserSettingState().getAuthoringFolderPath());
}
}
}
// Load the window state data
editor3DWindowState = WorkbenchManager.getEditor3DWindowState();
WorkbenchManager.setEditor3DWindow(this);
// Closing this window causes the whole application to quit
this.setBlockOnOpen(true);
// Creating the window to get the shell
this.create();
final Shell sh = this.getShell();
sh.setText(Version.getApplicationName() + " " + Version.getVersion()); //$NON-NLS-1$
sh.setImage(ResourceManager.getImage("imgDuke2.png")); //$NON-NLS-1$
sh.setMinimumSize(640, 480);
sh.setBounds(this.editor3DWindowState.getWindowState().getSizeAndPosition());
if (this.editor3DWindowState.getWindowState().isCentered()) {
ShellHelper.centerShellOnPrimaryScreen(sh);
}
// Maximize / tab creation on text editor has to be called asynchronously
sh.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
sh.setMaximized(editor3DWindowState.getWindowState().isMaximized());
if ((WorkbenchManager.getUserSettingState().getTextWinArr() != TEXT_3D_SEPARATE)) {
for (EditorTextWindow w : Project.getOpenTextWindows()) {
if (!w.isSeperateWindow()) {
Project.getParsedFiles().add(Project.getFileToEdit());
Project.addOpenedFile(Project.getFileToEdit());
{
CompositeTab tbtmnewItem = new CompositeTab(w.getTabFolder(), SWT.CLOSE);
tbtmnewItem.setFolderAndWindow(w.getTabFolder(), Editor3DWindow.getWindow());
tbtmnewItem.getState().setFileNameObj(Project.getFileToEdit());
w.getTabFolder().setSelection(tbtmnewItem);
tbtmnewItem.parseForErrorAndHints();
tbtmnewItem.getTextComposite().redraw();
}
break;
}
}
}
}
});
// Set the snapping
Manipulator.setSnap(
WorkbenchManager.getUserSettingState().getMedium_move_snap(),
WorkbenchManager.getUserSettingState().getMedium_rotate_snap(),
WorkbenchManager.getUserSettingState().getMedium_scale_snap()
);
// MARK All final listeners will be configured here..
NLogger.writeVersion();
sh.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent consumed) {}
@Override
public void focusGained(FocusEvent e) {
regainFocus();
}
});
tabFolder_Settings[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
regainFocus();
}
});
btn_Sync[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetSearch();
int[][] stats = new int[15][3];
stats[0] = LibraryManager.syncProjectElements(treeItem_Project[0]);
stats[5] = LibraryManager.syncUnofficialParts(treeItem_UnofficialParts[0]);
stats[6] = LibraryManager.syncUnofficialSubparts(treeItem_UnofficialSubparts[0]);
stats[7] = LibraryManager.syncUnofficialPrimitives(treeItem_UnofficialPrimitives[0]);
stats[8] = LibraryManager.syncUnofficialHiResPrimitives(treeItem_UnofficialPrimitives48[0]);
stats[9] = LibraryManager.syncUnofficialLowResPrimitives(treeItem_UnofficialPrimitives8[0]);
stats[10] = LibraryManager.syncOfficialParts(treeItem_OfficialParts[0]);
stats[11] = LibraryManager.syncOfficialSubparts(treeItem_OfficialSubparts[0]);
stats[12] = LibraryManager.syncOfficialPrimitives(treeItem_OfficialPrimitives[0]);
stats[13] = LibraryManager.syncOfficialHiResPrimitives(treeItem_OfficialPrimitives48[0]);
stats[14] = LibraryManager.syncOfficialLowResPrimitives(treeItem_OfficialPrimitives8[0]);
int additions = 0;
int deletions = 0;
int conflicts = 0;
for (int[] is : stats) {
additions += is[0];
deletions += is[1];
conflicts += is[2];
}
txt_Search[0].setText(" "); //$NON-NLS-1$
txt_Search[0].setText(""); //$NON-NLS-1$
Set<DatFile> dfs = new HashSet<DatFile>();
for (OpenGLRenderer renderer : renders) {
dfs.add(renderer.getC3D().getLockableDatFileReference());
}
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj();
if (txtDat != null) {
dfs.add(txtDat);
}
}
}
for (DatFile df : dfs) {
SubfileCompiler.compile(df, false, false);
}
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj();
if (txtDat != null) {
((CompositeTab) t).parseForErrorAndHints();
((CompositeTab) t).getTextComposite().redraw();
((CompositeTab) t).getState().getTab().setText(((CompositeTab) t).getState().getFilenameWithStar());
}
}
}
updateTree_unsavedEntries();
treeParts[0].getTree().showItem(treeParts[0].getTree().getItem(0));
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_SyncTitle);
Object[] messageArguments = {additions, deletions, conflicts};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_Sync);
messageBox.setMessage(formatter.format(messageArguments));
messageBox.open();
regainFocus();
}
});
btn_LastOpen[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Menu lastOpenedMenu = new Menu(treeParts[0].getTree());
btn_LastOpen[0].setMenu(lastOpenedMenu);
final int size = recentItems.size() - 1;
for (int i = size; i > -1; i--) {
final String path = recentItems.get(i);
File f = new File(path);
if (f.exists() && f.canRead()) {
if (f.isFile()) {
MenuItem mntmItem = new MenuItem(lastOpenedMenu, I18n.I18N_NON_BIDIRECT());
mntmItem.setEnabled(true);
mntmItem.setText(path);
mntmItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
File f = new File(path);
if (f.exists() && f.isFile() && f.canRead()) {
DatFile df = openDatFile(getShell(), OpenInWhat.EDITOR_3D, path, false);
if (df != null && !df.equals(View.DUMMY_DATFILE) && WorkbenchManager.getUserSettingState().isSyncingTabs()) {
boolean fileIsOpenInTextEditor = false;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
fileIsOpenInTextEditor = true;
}
if (fileIsOpenInTextEditor) break;
}
if (fileIsOpenInTextEditor) break;
}
if (Project.getOpenTextWindows().isEmpty() || fileIsOpenInTextEditor) {
openDatFile(df, OpenInWhat.EDITOR_TEXT, null);
} else {
Project.getOpenTextWindows().iterator().next().openNewDatFileTab(df, true);
}
}
cleanupClosedData();
regainFocus();
}
}
});
} else if (f.isDirectory()) {
MenuItem mntmItem = new MenuItem(lastOpenedMenu, I18n.I18N_NON_BIDIRECT());
mntmItem.setEnabled(true);
Object[] messageArguments = {path};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.E3D_LastProject);
mntmItem.setText(formatter.format(messageArguments));
mntmItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
File f = new File(path);
if (f.exists() && f.isDirectory() && f.canRead() && ProjectActions.openProject(path)) {
Project.create(false);
treeItem_Project[0].setData(Project.getProjectPath());
resetSearch();
LibraryManager.readProjectPartsParent(treeItem_ProjectParts[0]);
LibraryManager.readProjectParts(treeItem_ProjectParts[0]);
LibraryManager.readProjectSubparts(treeItem_ProjectSubparts[0]);
LibraryManager.readProjectPrimitives(treeItem_ProjectPrimitives[0]);
LibraryManager.readProjectHiResPrimitives(treeItem_ProjectPrimitives48[0]);
LibraryManager.readProjectLowResPrimitives(treeItem_ProjectPrimitives8[0]);
treeItem_OfficialParts[0].setData(null);
txt_Search[0].setText(" "); //$NON-NLS-1$
txt_Search[0].setText(""); //$NON-NLS-1$
updateTree_unsavedEntries();
}
regainFocus();
}
});
}
}
}
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
lastOpenedMenu.setLocation(x, y);
lastOpenedMenu.setVisible(true);
regainFocus();
}
});
btn_New[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (ProjectActions.createNewProject(Editor3DWindow.getWindow(), false)) {
addRecentFile(Project.getProjectPath());
}
regainFocus();
}
});
btn_Open[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (ProjectActions.openProject(null)) {
addRecentFile(Project.getProjectPath());
Project.setLastVisitedPath(Project.getProjectPath());
Project.create(false);
treeItem_Project[0].setData(Project.getProjectPath());
resetSearch();
LibraryManager.readProjectPartsParent(treeItem_ProjectParts[0]);
LibraryManager.readProjectParts(treeItem_ProjectParts[0]);
LibraryManager.readProjectSubparts(treeItem_ProjectSubparts[0]);
LibraryManager.readProjectPrimitives(treeItem_ProjectPrimitives[0]);
LibraryManager.readProjectHiResPrimitives(treeItem_ProjectPrimitives48[0]);
LibraryManager.readProjectLowResPrimitives(treeItem_ProjectPrimitives8[0]);
treeItem_OfficialParts[0].setData(null);
txt_Search[0].setText(" "); //$NON-NLS-1$
txt_Search[0].setText(""); //$NON-NLS-1$
updateTree_unsavedEntries();
}
regainFocus();
}
});
btn_Save[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1) {
if (treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
Editor3DWindow.getWindow().updateTree_unsavedEntries();
}
}
} else if (treeParts[0].getSelection()[0].getData() instanceof ArrayList<?>) {
NLogger.debug(getClass(), "Saving all files from this group"); //$NON-NLS-1$
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> dfs = (ArrayList<DatFile>) treeParts[0].getSelection()[0].getData();
for (DatFile df : dfs) {
if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Project.removeUnsavedFile(df);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
Editor3DWindow.getWindow().updateTree_unsavedEntries();
}
}
}
}
} else if (treeParts[0].getSelection()[0].getData() instanceof String) {
if (treeParts[0].getSelection()[0].equals(treeItem_Project[0])) {
NLogger.debug(getClass(), "Save the project..."); //$NON-NLS-1$
if (Project.isDefaultProject()) {
if (ProjectActions.createNewProject(Editor3DWindow.getWindow(), true)) {
Project.setLastVisitedPath(Project.getProjectPath());
}
}
iterateOverItems(treeItem_ProjectParts[0]);
iterateOverItems(treeItem_ProjectSubparts[0]);
iterateOverItems(treeItem_ProjectPrimitives[0]);
iterateOverItems(treeItem_ProjectPrimitives48[0]);
iterateOverItems(treeItem_ProjectPrimitives8[0]);
} else if (treeParts[0].getSelection()[0].equals(treeItem_Unofficial[0])) {
iterateOverItems(treeItem_UnofficialParts[0]);
iterateOverItems(treeItem_UnofficialSubparts[0]);
iterateOverItems(treeItem_UnofficialPrimitives[0]);
iterateOverItems(treeItem_UnofficialPrimitives48[0]);
iterateOverItems(treeItem_UnofficialPrimitives8[0]);
}
NLogger.debug(getClass(), "Saving all files from this group to {0}", treeParts[0].getSelection()[0].getData()); //$NON-NLS-1$
}
} else {
NLogger.debug(getClass(), "Save the project..."); //$NON-NLS-1$
if (Project.isDefaultProject()) {
if (ProjectActions.createNewProject(Editor3DWindow.getWindow(), true)) {
Project.setLastVisitedPath(Project.getProjectPath());
}
}
}
regainFocus();
}
private void iterateOverItems(TreeItem ti) {
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> dfs = (ArrayList<DatFile>) ti.getData();
for (DatFile df : dfs) {
if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Project.removeUnsavedFile(df);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
Editor3DWindow.getWindow().updateTree_unsavedEntries();
}
}
}
}
}
});
btn_SaveAll[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
HashSet<DatFile> dfs = new HashSet<DatFile>(Project.getUnsavedFiles());
for (DatFile df : dfs) {
if (!df.isReadOnly()) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Project.removeUnsavedFile(df);
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
}
}
}
if (Project.isDefaultProject()) {
if (ProjectActions.createNewProject(getWindow(), true)) {
addRecentFile(Project.getProjectPath());
}
}
Editor3DWindow.getWindow().updateTree_unsavedEntries();
regainFocus();
}
});
btn_NewDat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
DatFile dat = createNewDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D);
if (dat != null) {
addRecentFile(dat);
final File f = new File(dat.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
}
regainFocus();
}
});
btn_OpenDat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean tabSync = WorkbenchManager.getUserSettingState().isSyncingTabs();
WorkbenchManager.getUserSettingState().setSyncingTabs(false);
DatFile dat = openDatFile(getShell(), OpenInWhat.EDITOR_3D, null, true);
if (dat != null) {
addRecentFile(dat);
final File f = new File(dat.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
boolean fileIsOpenInTextEditor = false;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (dat.equals(((CompositeTab) t).getState().getFileNameObj())) {
fileIsOpenInTextEditor = true;
}
if (fileIsOpenInTextEditor) break;
}
if (fileIsOpenInTextEditor) break;
}
if (Project.getOpenTextWindows().isEmpty() || fileIsOpenInTextEditor) {
openDatFile(dat, OpenInWhat.EDITOR_TEXT, null);
} else {
Project.getOpenTextWindows().iterator().next().openNewDatFileTab(dat, true);
}
Project.setFileToEdit(dat);
updateTabs();
}
WorkbenchManager.getUserSettingState().setSyncingTabs(tabSync);
regainFocus();
}
});
btn_SaveDat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().equals(View.DUMMY_DATFILE)) {
final DatFile df = Project.getFileToEdit();
Editor3DWindow.getWindow().addRecentFile(df);
if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
}
}
}
regainFocus();
}
});
btn_SaveAsDat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().equals(View.DUMMY_DATFILE)) {
final DatFile df2 = Project.getFileToEdit();
FileDialog fd = new FileDialog(sh, SWT.SAVE);
fd.setText(I18n.E3D_SaveDatFileAs);
{
File f = new File(df2.getNewName()).getParentFile();
if (f.exists()) {
fd.setFilterPath(f.getAbsolutePath());
} else {
fd.setFilterPath(Project.getLastVisitedPath());
}
}
String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = {I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles};
fd.setFilterNames(filterNames);
while (true) {
try {
String selected = fd.open();
if (selected != null) {
if (Editor3DWindow.getWindow().isFileNameAllocated(selected, new DatFile(selected), true)) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
int result = messageBox.open();
if (result == SWT.CANCEL) {
break;
} else if (result == SWT.RETRY) {
continue;
}
}
df2.saveAs(selected);
DatFile df = Editor3DWindow.getWindow().openDatFile(getShell(), OpenInWhat.EDITOR_3D, selected, false);
if (df != null) {
Editor3DWindow.getWindow().addRecentFile(df);
final File f = new File(df.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
}
}
} catch (Exception ex) {
NLogger.error(getClass(), ex);
}
break;
}
}
regainFocus();
}
});
btn_Undo[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().undo(null);
}
regainFocus();
}
});
btn_Redo[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().redo(null);
}
regainFocus();
}
});
if (NLogger.DEBUG) {
btn_AddHistory[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().addHistory();
}
}
});
}
btn_Select[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Select[0]);
workingAction = WorkingMode.SELECT;
disableAddAction();
regainFocus();
}
});
btn_Move[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Move[0]);
workingAction = WorkingMode.MOVE;
disableAddAction();
regainFocus();
}
});
btn_Rotate[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Rotate[0]);
workingAction = WorkingMode.ROTATE;
disableAddAction();
regainFocus();
}
});
btn_Scale[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Scale[0]);
workingAction = WorkingMode.SCALE;
disableAddAction();
regainFocus();
}
});
btn_Combined[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Combined[0]);
workingAction = WorkingMode.COMBINED;
disableAddAction();
regainFocus();
}
});
btn_Local[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Local[0]);
transformationMode = ManipulatorScope.LOCAL;
regainFocus();
}
});
btn_Global[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Global[0]);
transformationMode = ManipulatorScope.GLOBAL;
regainFocus();
}
});
btn_Vertices[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Vertices[0]);
setWorkingType(ObjectMode.VERTICES);
if ((e.stateMask & SWT.ALT) == SWT.ALT && Project.getFileToEdit() != null && !Project.getFileToEdit().getVertexManager().getSelectedVertices().isEmpty()) {
final VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.getSelectedVertices().clear();
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
vm.reSelectSubFiles();
} else {
vm.getSelectedData().removeAll(vm.getSelectedSubfiles());
vm.getSelectedSubfiles().clear();
}
vm.setModified(true, true);
}
regainFocus();
}
});
btn_TrisNQuads[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_TrisNQuads[0]);
setWorkingType(ObjectMode.FACES);
if ((e.stateMask & SWT.ALT) == SWT.ALT && Project.getFileToEdit() != null && (!Project.getFileToEdit().getVertexManager().getSelectedQuads().isEmpty() || !Project.getFileToEdit().getVertexManager().getSelectedTriangles().isEmpty())) {
final VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.getSelectedData().removeAll(vm.getSelectedTriangles());
vm.getSelectedData().removeAll(vm.getSelectedQuads());
vm.getSelectedTriangles().clear();
vm.getSelectedQuads().clear();
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
vm.reSelectSubFiles();
} else {
vm.getSelectedData().removeAll(vm.getSelectedSubfiles());
vm.getSelectedSubfiles().clear();
}
vm.setModified(true, true);
}
regainFocus();
}
});
btn_Lines[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Lines[0]);
setWorkingType(ObjectMode.LINES);
if ((e.stateMask & SWT.ALT) == SWT.ALT && Project.getFileToEdit() != null && (!Project.getFileToEdit().getVertexManager().getSelectedLines().isEmpty() || !Project.getFileToEdit().getVertexManager().getSelectedCondlines().isEmpty())) {
final VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.getSelectedData().removeAll(vm.getSelectedCondlines());
vm.getSelectedData().removeAll(vm.getSelectedLines());
vm.getSelectedCondlines().clear();
vm.getSelectedLines().clear();
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
vm.reSelectSubFiles();
} else {
vm.getSelectedData().removeAll(vm.getSelectedSubfiles());
vm.getSelectedSubfiles().clear();
}
vm.setModified(true, true);
}
regainFocus();
}
});
btn_Subfiles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Subfiles[0]);
setWorkingType(ObjectMode.SUBFILES);
if ((e.stateMask & SWT.ALT) == SWT.ALT && (e.stateMask & SWT.CTRL) != SWT.CTRL && Project.getFileToEdit() != null && !Project.getFileToEdit().getVertexManager().getSelectedSubfiles().isEmpty()) {
final VertexManager vm = Project.getFileToEdit().getVertexManager();
final ArrayList<GData1> subfiles = new ArrayList<GData1>();
subfiles.addAll(vm.getSelectedSubfiles());
for (GData1 g1 : subfiles) {
vm.removeSubfileFromSelection(g1);
}
vm.getSelectedSubfiles().clear();
vm.setModified(true, true);
}
regainFocus();
}
});
btn_AddComment[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!metaWindow.isOpened()) {
metaWindow.run();
} else {
metaWindow.open();
}
}
});
btn_AddVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
clickSingleBtn(btn_AddVertex[0]);
setAddingVertices(btn_AddVertex[0].getSelection());
setAddingSomething(isAddingVertices());
regainFocus();
}
});
btn_AddPrimitive[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingSubfiles(btn_AddPrimitive[0].getSelection());
clickSingleBtn(btn_AddPrimitive[0]);
if (Project.getFileToEdit() != null) {
final boolean readOnly = Project.getFileToEdit().isReadOnly();
final VertexManager vm = Project.getFileToEdit().getVertexManager();
if (vm.getSelectedData().size() > 0 || vm.getSelectedVertices().size() > 0) {
final boolean insertSubfileFromSelection;
final boolean cutTheSelection;
{
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox.setText(I18n.E3D_SubfileFromSelection);
messageBox.setMessage(I18n.E3D_SubfileFromSelectionQuestion);
int result = messageBox.open();
insertSubfileFromSelection = result == SWT.YES;
if (result != SWT.NO && result != SWT.YES) {
resetAddState();
btn_AddPrimitive[0].setSelection(false);
setAddingSubfiles(false);
addingSomething = false;
regainFocus();
return;
}
}
if (insertSubfileFromSelection) {
if (!readOnly) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox.setText(I18n.E3D_SubfileFromSelection);
messageBox.setMessage(I18n.E3D_SubfileFromSelectionQuestionCut);
int result = messageBox.open();
cutTheSelection = result == SWT.YES;
if (result != SWT.NO && result != SWT.YES) {
resetAddState();
btn_AddPrimitive[0].setSelection(false);
setAddingSubfiles(false);
addingSomething = false;
regainFocus();
return;
}
} else {
cutTheSelection = false;
}
vm.addSnapshot();
vm.copy();
vm.extendClipboardContent(cutTheSelection);
FileDialog fd = new FileDialog(sh, SWT.SAVE);
fd.setText(I18n.E3D_SaveDatFileAs);
{
File f = new File(Project.getFileToEdit().getNewName()).getParentFile();
if (f.exists()) {
fd.setFilterPath(f.getAbsolutePath());
} else {
fd.setFilterPath(Project.getLastVisitedPath());
}
}
String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = {I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles};
fd.setFilterNames(filterNames);
while (true) {
try {
String selected = fd.open();
if (selected != null) {
if (Editor3DWindow.getWindow().isFileNameAllocated(selected, new DatFile(selected), true)) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
int result = messageBox.open();
if (result == SWT.CANCEL) {
break;
} else if (result == SWT.RETRY) {
continue;
}
}
SearchWindow sw = Editor3DWindow.getWindow().getSearchWindow();
if (sw != null) {
sw.setTextComposite(null);
sw.setScopeToAll();
}
boolean hasIOerror = false;
UTF8PrintWriter r = null;
try {
String typeSuffix = ""; //$NON-NLS-1$
String folderPrefix = ""; //$NON-NLS-1$
String subfilePrefix = ""; //$NON-NLS-1$
String path = new File(selected).getParent();
if (path.endsWith(File.separator + "S") || path.endsWith(File.separator + "s")) { //$NON-NLS-1$ //$NON-NLS-2$
typeSuffix = "Unofficial_Subpart"; //$NON-NLS-1$
folderPrefix = "s\\"; //$NON-NLS-1$
subfilePrefix = "~"; //$NON-NLS-1$
} else if (path.endsWith(File.separator + "P" + File.separator + "48") || path.endsWith(File.separator + "p" + File.separator + "48")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
typeSuffix = "Unofficial_48_Primitive"; //$NON-NLS-1$
folderPrefix = "48\\"; //$NON-NLS-1$
} else if (path.endsWith(File.separator + "P" + File.separator + "8") || path.endsWith(File.separator + "p" + File.separator + "8")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
typeSuffix = "Unofficial_8_Primitive"; //$NON-NLS-1$
folderPrefix = "8\\"; //$NON-NLS-1$
} else if (path.endsWith(File.separator + "P") || path.endsWith(File.separator + "p")) { //$NON-NLS-1$ //$NON-NLS-2$
typeSuffix = "Unofficial_Primitive"; //$NON-NLS-1$
}
r = new UTF8PrintWriter(selected);
r.println("0 " + subfilePrefix); //$NON-NLS-1$
r.println("0 Name: " + folderPrefix + new File(selected).getName()); //$NON-NLS-1$
String ldrawName = WorkbenchManager.getUserSettingState().getLdrawUserName();
if (ldrawName == null || ldrawName.isEmpty()) {
r.println("0 Author: " + WorkbenchManager.getUserSettingState().getRealUserName()); //$NON-NLS-1$
} else {
r.println("0 Author: " + WorkbenchManager.getUserSettingState().getRealUserName() + " [" + WorkbenchManager.getUserSettingState().getLdrawUserName() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
r.println("0 !LDRAW_ORG " + typeSuffix); //$NON-NLS-1$
String license = WorkbenchManager.getUserSettingState().getLicense();
if (license == null || license.isEmpty()) {
r.println("0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt"); //$NON-NLS-1$
} else {
r.println(license);
}
r.println(""); //$NON-NLS-1$
{
byte bfc_type = BFC.NOCERTIFY;
GData g = Project.getFileToEdit().getDrawChainStart();
while ((g = g.getNext()) != null) {
if (g.type() == 6) {
byte bfc = ((GDataBFC) g).getType();
switch (bfc) {
case BFC.CCW_CLIP:
bfc_type = bfc;
r.println("0 BFC CERTIFY CCW"); //$NON-NLS-1$
break;
case BFC.CW_CLIP:
bfc_type = bfc;
r.println("0 BFC CERTIFY CW"); //$NON-NLS-1$
break;
}
if (bfc_type != BFC.NOCERTIFY) break;
}
}
if (bfc_type == BFC.NOCERTIFY) {
r.println("0 BFC NOCERTIFY"); //$NON-NLS-1$
}
}
r.println(""); //$NON-NLS-1$
r.println(vm.getClipboardText());
r.flush();
r.close();
} catch (Exception ex) {
hasIOerror = true;
} finally {
if (r != null) {
r.close();
}
}
if (hasIOerror) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
} else {
if (cutTheSelection) {
// Insert a reference to the subfile in the old file
Set<String> alreadyParsed = new HashSet<String>();
alreadyParsed.add(Project.getFileToEdit().getShortName());
ArrayList<ParsingResult> subfileLine = DatParser
.parseLine(
"1 16 0 0 0 1 0 0 0 1 0 0 0 1 s\\" + new File(selected).getName(), -1, 0, 0.5f, 0.5f, 0.5f, 1.1f, View.DUMMY_REFERENCE, View.ID, View.ACCURATE_ID, Project.getFileToEdit(), false, alreadyParsed, false); //$NON-NLS-1$
GData1 gd1 = (GData1) subfileLine.get(0).getGraphicalData();
if (gd1 != null) {
if (isInsertingAtCursorPosition()) {
Project.getFileToEdit().insertAfterCursor(gd1);
} else {
Set<GData> sd = vm.getSelectedData();
GData g = Project.getFileToEdit().getDrawChainStart();
GData whereToInsert = null;
while ((g = g.getNext()) != null) {
if (sd.contains(g)) {
whereToInsert = g.getBefore();
break;
}
}
if (whereToInsert == null) {
whereToInsert = Project.getFileToEdit().getDrawChainTail();
}
Project.getFileToEdit().insertAfter(whereToInsert, gd1);
}
}
vm.delete(false, true);
}
DatFile df = Editor3DWindow.getWindow().openDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D, selected, false);
if (df != null) {
addRecentFile(df);
final File f = new File(df.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
}
}
updateTree_unsavedEntries();
}
} catch (Exception ex) {
NLogger.error(getClass(), ex);
}
break;
}
resetAddState();
btn_AddPrimitive[0].setSelection(false);
setAddingSubfiles(false);
addingSomething = false;
regainFocus();
return;
}
}
}
setAddingSomething(isAddingSubfiles());
regainFocus();
}
});
btn_AddLine[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingLines(btn_AddLine[0].getSelection());
setAddingSomething(isAddingLines());
clickSingleBtn(btn_AddLine[0]);
regainFocus();
}
});
btn_AddTriangle[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingTriangles(btn_AddTriangle[0].getSelection());
setAddingSomething(isAddingTriangles());
clickSingleBtn(btn_AddTriangle[0]);
regainFocus();
}
});
btn_AddQuad[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingQuads(btn_AddQuad[0].getSelection());
setAddingSomething(isAddingQuads());
clickSingleBtn(btn_AddQuad[0]);
regainFocus();
}
});
btn_AddCondline[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingCondlines(btn_AddCondline[0].getSelection());
setAddingSomething(isAddingCondlines());
clickSingleBtn(btn_AddCondline[0]);
regainFocus();
}
});
btn_AddDistance[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingDistance(btn_AddDistance[0].getSelection());
setAddingSomething(isAddingDistance());
clickSingleBtn(btn_AddDistance[0]);
regainFocus();
}
});
btn_AddProtractor[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingProtractor(btn_AddProtractor[0].getSelection());
setAddingSomething(isAddingProtractor());
clickSingleBtn(btn_AddProtractor[0]);
regainFocus();
}
});
btn_MoveAdjacentData[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickSingleBtn(btn_MoveAdjacentData[0]);
setMovingAdjacentData(btn_MoveAdjacentData[0].getSelection());
GuiManager.updateStatus();
regainFocus();
}
});
btn_CompileSubfile[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
SubfileCompiler.compile(Project.getFileToEdit(), false, false);
}
regainFocus();
}
});
btn_ToggleLinesOpenGL[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (btn_ToggleLinesOpenGL[0].getSelection()) {
View.edge_threshold = 5e6f;
} else {
View.edge_threshold = 5e-6f;
}
regainFocus();
}
});
btn_lineSize1[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setLineSize(GLPrimitives.SPHERE1, GLPrimitives.SPHERE_INV1, 25f, .025f, .375f, btn_lineSize1[0]);
regainFocus();
}
});
btn_lineSize2[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setLineSize(GLPrimitives.SPHERE2, GLPrimitives.SPHERE_INV2, 50f, .050f, .75f, btn_lineSize2[0]);
regainFocus();
}
});
btn_lineSize3[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setLineSize(GLPrimitives.SPHERE3, GLPrimitives.SPHERE_INV3, 100f, .100f, 1.5f, btn_lineSize3[0]);
regainFocus();
}
});
btn_lineSize4[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setLineSize(GLPrimitives.SPHERE4, GLPrimitives.SPHERE_INV4, 200f, .200f, 3f, btn_lineSize4[0]);
regainFocus();
}
});
btn_ShowSelectionInTextEditor[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Composite3D.showSelectionInTextEditor(Project.getFileToEdit(), true);
}
regainFocus();
}
});
btn_BFCswap[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().backupHideShowState();
Project.getFileToEdit().getVertexManager().windingChangeSelection(true);
}
regainFocus();
}
});
btn_RoundSelection[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
if (new RoundDialog(getShell()).open() == IDialogConstants.CANCEL_ID) return;
}
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().backupHideShowState();
Project.getFileToEdit().getVertexManager()
.roundSelection(WorkbenchManager.getUserSettingState().getCoordsPrecision(), WorkbenchManager.getUserSettingState().getTransMatrixPrecision(), isMovingAdjacentData(), true);
}
regainFocus();
}
});
btn_Pipette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.addSnapshot();
final GColour gColour2;
{
GColour gColour3 = vm.getRandomSelectedColour(lastUsedColour);
if (gColour3.getColourNumber() == 16) {
gColour2 = View.getLDConfigColour(16);
} else {
gColour2 = gColour3;
}
lastUsedColour = gColour2;
}
setLastUsedColour(gColour2);
btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]);
btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]);
final Color col = SWTResourceManager.getColor((int) (gColour2.getR() * 255f), (int) (gColour2.getG() * 255f), (int) (gColour2.getB() * 255f));
final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT);
final int x = Math.round(size.x / 5f);
final int y = Math.round(size.y / 5f);
final int w = Math.round(size.x * (3f / 5f));
final int h = Math.round(size.y * (3f / 5f));
int num = gColour2.getColourNumber();
btn_LastUsedColour[0].addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.setBackground(col);
e.gc.fillRectangle(x, y, w, h);
if (gColour2.getA() == 1f) {
e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
} else {
e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
}
}
});
btn_LastUsedColour[0].addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
int num = gColour2.getColourNumber();
if (!View.hasLDConfigColour(num)) {
num = -1;
}
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2.getR(), gColour2.getG(), gColour2.getB(), gColour2.getA(), true);
}
regainFocus();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
if (num != -1) {
Object[] messageArguments = {num, View.getLDConfigColourName(num)};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour1);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
} else {
StringBuilder colourBuilder = new StringBuilder();
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getB())).toUpperCase());
Object[] messageArguments = {colourBuilder.toString()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour2);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
}
btn_LastUsedColour[0].redraw();
}
regainFocus();
}
});
btn_Decolour[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.addSnapshot();
vm.selectAll(new SelectorSettings(), true);
GDataCSG.clearSelection(Project.getFileToEdit());
GColour c = View.getLDConfigColour(16);
vm.colourChangeSelection(c.getColourNumber(), c.getR(), c.getG(), c.getB(), c.getA(), false);
vm.getSelectedData().removeAll(vm.getTriangles().keySet());
vm.getSelectedData().removeAll(vm.getQuads().keySet());
vm.getSelectedData().removeAll(vm.getSelectedSubfiles());
vm.getSelectedSubfiles().clear();
vm.getSelectedTriangles().removeAll(vm.getTriangles().keySet());
vm.getSelectedQuads().removeAll(vm.getQuads().keySet());
c = View.getLDConfigColour(24);
vm.colourChangeSelection(c.getColourNumber(), c.getR(), c.getG(), c.getB(), c.getA(), true);
}
}
});
btn_Palette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
final GColour[] gColour2 = new GColour[1];
new ColourDialog(getShell(), gColour2, true).open();
if (gColour2[0] != null) {
setLastUsedColour(gColour2[0]);
int num = gColour2[0].getColourNumber();
if (!View.hasLDConfigColour(num)) {
num = -1;
}
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA(), true);
btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]);
btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]);
final Color col = SWTResourceManager.getColor((int) (gColour2[0].getR() * 255f), (int) (gColour2[0].getG() * 255f), (int) (gColour2[0].getB() * 255f));
final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT);
final int x = Math.round(size.x / 5f);
final int y = Math.round(size.y / 5f);
final int w = Math.round(size.x * (3f / 5f));
final int h = Math.round(size.y * (3f / 5f));
btn_LastUsedColour[0].addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.setBackground(col);
e.gc.fillRectangle(x, y, w, h);
if (gColour2[0].getA() == 1f) {
e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
} else if (gColour2[0].getA() == 0f) {
e.gc.drawImage(ResourceManager.getImage("icon16_randomColours.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
} else {
e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
}
}
});
btn_LastUsedColour[0].addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
int num = gColour2[0].getColourNumber();
if (!View.hasLDConfigColour(num)) {
num = -1;
}
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA(), true);
}
regainFocus();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
if (num != -1) {
Object[] messageArguments = {num, View.getLDConfigColourName(num)};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour1);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
} else {
StringBuilder colourBuilder = new StringBuilder();
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getB())).toUpperCase());
Object[] messageArguments = {colourBuilder.toString()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour2);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
if (gColour2[0].getA() == 0f) btn_LastUsedColour[0].setToolTipText(I18n.COLOURDIALOG_RandomColours);
}
btn_LastUsedColour[0].redraw();
}
}
regainFocus();
}
});
btn_Coarse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
BigDecimal m = WorkbenchManager.getUserSettingState().getCoarse_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap();
snapSize = 2;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
regainFocus();
}
});
btn_Medium[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
BigDecimal m = WorkbenchManager.getUserSettingState().getMedium_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getMedium_scale_snap();
snapSize = 1;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
regainFocus();
}
});
btn_Fine[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
BigDecimal m = WorkbenchManager.getUserSettingState().getFine_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getFine_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getFine_scale_snap();
snapSize = 0;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
regainFocus();
}
});
btn_Coarse[0].addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == MouseButton.RIGHT) {
try {
if (btn_Coarse[0].getMenu() != null) {
btn_Coarse[0].getMenu().dispose();
}
} catch (Exception ex) {}
Menu gridMenu = new Menu(btn_Coarse[0]);
btn_Coarse[0].setMenu(gridMenu);
mnu_coarseMenu[0] = gridMenu;
MenuItem mntmGridCoarseDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT());
mntm_gridCoarseDefault[0] = mntmGridCoarseDefault;
mntmGridCoarseDefault.setEnabled(true);
mntmGridCoarseDefault.setText(I18n.E3D_GridCoarseDefault);
mntm_gridCoarseDefault[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setCoarse_move_snap(new BigDecimal("1")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setCoarse_rotate_snap(new BigDecimal("90")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setCoarse_scale_snap(new BigDecimal("2")); //$NON-NLS-1$
BigDecimal m = WorkbenchManager.getUserSettingState().getCoarse_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap();
snapSize = 2;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
btn_Coarse[0].setSelection(true);
btn_Medium[0].setSelection(false);
btn_Fine[0].setSelection(false);
regainFocus();
}
});
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
Menu menu = mnu_coarseMenu[0];
menu.setLocation(x, y);
menu.setVisible(true);
regainFocus();
}
}
});
btn_Medium[0].addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == MouseButton.RIGHT) {
try {
if (btn_Medium[0].getMenu() != null) {
btn_Medium[0].getMenu().dispose();
}
} catch (Exception ex) {}
Menu gridMenu = new Menu(btn_Medium[0]);
btn_Medium[0].setMenu(gridMenu);
mnu_mediumMenu[0] = gridMenu;
MenuItem mntmGridMediumDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT());
mntm_gridMediumDefault[0] = mntmGridMediumDefault;
mntmGridMediumDefault.setEnabled(true);
mntmGridMediumDefault.setText(I18n.E3D_GridMediumDefault);
mntm_gridMediumDefault[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setMedium_move_snap(new BigDecimal("0.01")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setMedium_rotate_snap(new BigDecimal("11.25")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setMedium_scale_snap(new BigDecimal("1.1")); //$NON-NLS-1$
BigDecimal m = WorkbenchManager.getUserSettingState().getMedium_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getMedium_scale_snap();
snapSize = 1;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
btn_Coarse[0].setSelection(false);
btn_Medium[0].setSelection(true);
btn_Fine[0].setSelection(false);
regainFocus();
}
});
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
Menu menu = mnu_mediumMenu[0];
menu.setLocation(x, y);
menu.setVisible(true);
regainFocus();
}
}
});
btn_Fine[0].addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == MouseButton.RIGHT) {
try {
if (btn_Fine[0].getMenu() != null) {
btn_Fine[0].getMenu().dispose();
}
} catch (Exception ex) {}
Menu gridMenu = new Menu(btn_Fine[0]);
btn_Fine[0].setMenu(gridMenu);
mnu_fineMenu[0] = gridMenu;
MenuItem mntmGridFineDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT());
mntm_gridFineDefault[0] = mntmGridFineDefault;
mntmGridFineDefault.setEnabled(true);
mntmGridFineDefault.setText(I18n.E3D_GridFineDefault);
mntm_gridFineDefault[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setFine_move_snap(new BigDecimal("0.0001")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setFine_rotate_snap(BigDecimal.ONE);
WorkbenchManager.getUserSettingState().setFine_scale_snap(new BigDecimal("1.001")); //$NON-NLS-1$
BigDecimal m = WorkbenchManager.getUserSettingState().getFine_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getFine_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getFine_scale_snap();
snapSize = 0;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
btn_Coarse[0].setSelection(false);
btn_Medium[0].setSelection(false);
btn_Fine[0].setSelection(true);
regainFocus();
}
});
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
Menu menu = mnu_fineMenu[0];
menu.setLocation(x, y);
menu.setVisible(true);
regainFocus();
}
}
});
btn_SplitQuad[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().splitQuads(true);
}
regainFocus();
}
});
btn_MergeQuad[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
RectifierSettings rs = new RectifierSettings();
rs.setScope(1);
rs.setNoBorderedQuadToRectConversation(true);
Project.getFileToEdit().getVertexManager().rectify(rs, true, true);
}
regainFocus();
}
});
btn_CondlineToLine[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().condlineToLine();
}
regainFocus();
}
});
btn_LineToCondline[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().lineToCondline();
}
regainFocus();
}
});
btn_MoveOnLine[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Set<Vertex> verts = Project.getFileToEdit().getVertexManager().getSelectedVertices();
CoordinatesDialog.setStart(null);
CoordinatesDialog.setEnd(null);
if (verts.size() == 2) {
Iterator<Vertex> it = verts.iterator();
CoordinatesDialog.setStart(new Vector3d(it.next()));
CoordinatesDialog.setEnd(new Vector3d(it.next()));
}
}
regainFocus();
}
});
spn_Move[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
BigDecimal m, r, s;
m = spn.getValue();
switch (snapSize) {
case 0:
WorkbenchManager.getUserSettingState().setFine_move_snap(m);
r = WorkbenchManager.getUserSettingState().getFine_rotate_snap();
s = WorkbenchManager.getUserSettingState().getFine_scale_snap();
break;
case 2:
WorkbenchManager.getUserSettingState().setCoarse_move_snap(m);
r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap();
s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap();
break;
default:
WorkbenchManager.getUserSettingState().setMedium_move_snap(m);
r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap();
s = WorkbenchManager.getUserSettingState().getMedium_scale_snap();
break;
}
Manipulator.setSnap(m, r, s);
}
});
spn_Rotate[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
BigDecimal m, r, s;
r = spn.getValue();
switch (snapSize) {
case 0:
m = WorkbenchManager.getUserSettingState().getFine_move_snap();
WorkbenchManager.getUserSettingState().setFine_rotate_snap(r);
s = WorkbenchManager.getUserSettingState().getFine_scale_snap();
break;
case 2:
m = WorkbenchManager.getUserSettingState().getCoarse_move_snap();
WorkbenchManager.getUserSettingState().setCoarse_rotate_snap(r);
s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap();
break;
default:
m = WorkbenchManager.getUserSettingState().getMedium_move_snap();
WorkbenchManager.getUserSettingState().setMedium_rotate_snap(r);
s = WorkbenchManager.getUserSettingState().getMedium_scale_snap();
break;
}
Manipulator.setSnap(m, r, s);
}
});
spn_Scale[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
BigDecimal m, r, s;
s = spn.getValue();
switch (snapSize) {
case 0:
m = WorkbenchManager.getUserSettingState().getFine_move_snap();
r = WorkbenchManager.getUserSettingState().getFine_rotate_snap();
WorkbenchManager.getUserSettingState().setFine_scale_snap(s);
break;
case 2:
m = WorkbenchManager.getUserSettingState().getCoarse_move_snap();
r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap();
WorkbenchManager.getUserSettingState().setCoarse_scale_snap(s);
break;
default:
m = WorkbenchManager.getUserSettingState().getMedium_move_snap();
r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap();
WorkbenchManager.getUserSettingState().setMedium_scale_snap(s);
break;
}
Manipulator.setSnap(m, r, s);
}
});
btn_PreviousSelection[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updatingSelectionTab = true;
NLogger.debug(getClass(), "Previous Selection..."); //$NON-NLS-1$
final DatFile df = Project.getFileToEdit();
if (df != null && !df.isReadOnly()) {
final VertexManager vm = df.getVertexManager();
vm.addSnapshot();
final int count = vm.getSelectedData().size();
if (count > 0) {
boolean breakIt = false;
boolean firstRun = true;
while (true) {
int index = vm.getSelectedItemIndex();
index--;
if (index < 0) {
index = count - 1;
if (!firstRun) breakIt = true;
}
if (index > count - 1) index = count - 1;
firstRun = false;
vm.setSelectedItemIndex(index);
final GData gdata = (GData) vm.getSelectedData().toArray()[index];
if (vm.isNotInSubfileAndLinetype1to5(gdata)) {
vm.setSelectedLine(gdata);
disableSelectionTab();
updatingSelectionTab = true;
switch (gdata.type()) {
case 1:
case 5:
case 4:
spn_SelectionX4[0].setEnabled(true);
spn_SelectionY4[0].setEnabled(true);
spn_SelectionZ4[0].setEnabled(true);
case 3:
spn_SelectionX3[0].setEnabled(true);
spn_SelectionY3[0].setEnabled(true);
spn_SelectionZ3[0].setEnabled(true);
case 2:
spn_SelectionX1[0].setEnabled(true);
spn_SelectionY1[0].setEnabled(true);
spn_SelectionZ1[0].setEnabled(true);
spn_SelectionX2[0].setEnabled(true);
spn_SelectionY2[0].setEnabled(true);
spn_SelectionZ2[0].setEnabled(true);
txt_Line[0].setText(gdata.toString());
breakIt = true;
btn_MoveAdjacentData2[0].setEnabled(true);
switch (gdata.type()) {
case 5:
BigDecimal[] g5 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g5[0]);
spn_SelectionY1[0].setValue(g5[1]);
spn_SelectionZ1[0].setValue(g5[2]);
spn_SelectionX2[0].setValue(g5[3]);
spn_SelectionY2[0].setValue(g5[4]);
spn_SelectionZ2[0].setValue(g5[5]);
spn_SelectionX3[0].setValue(g5[6]);
spn_SelectionY3[0].setValue(g5[7]);
spn_SelectionZ3[0].setValue(g5[8]);
spn_SelectionX4[0].setValue(g5[9]);
spn_SelectionY4[0].setValue(g5[10]);
spn_SelectionZ4[0].setValue(g5[11]);
break;
case 4:
BigDecimal[] g4 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g4[0]);
spn_SelectionY1[0].setValue(g4[1]);
spn_SelectionZ1[0].setValue(g4[2]);
spn_SelectionX2[0].setValue(g4[3]);
spn_SelectionY2[0].setValue(g4[4]);
spn_SelectionZ2[0].setValue(g4[5]);
spn_SelectionX3[0].setValue(g4[6]);
spn_SelectionY3[0].setValue(g4[7]);
spn_SelectionZ3[0].setValue(g4[8]);
spn_SelectionX4[0].setValue(g4[9]);
spn_SelectionY4[0].setValue(g4[10]);
spn_SelectionZ4[0].setValue(g4[11]);
break;
case 3:
BigDecimal[] g3 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g3[0]);
spn_SelectionY1[0].setValue(g3[1]);
spn_SelectionZ1[0].setValue(g3[2]);
spn_SelectionX2[0].setValue(g3[3]);
spn_SelectionY2[0].setValue(g3[4]);
spn_SelectionZ2[0].setValue(g3[5]);
spn_SelectionX3[0].setValue(g3[6]);
spn_SelectionY3[0].setValue(g3[7]);
spn_SelectionZ3[0].setValue(g3[8]);
break;
case 2:
BigDecimal[] g2 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g2[0]);
spn_SelectionY1[0].setValue(g2[1]);
spn_SelectionZ1[0].setValue(g2[2]);
spn_SelectionX2[0].setValue(g2[3]);
spn_SelectionY2[0].setValue(g2[4]);
spn_SelectionZ2[0].setValue(g2[5]);
break;
case 1:
vm.getSelectedVertices().clear();
btn_MoveAdjacentData2[0].setEnabled(false);
GData1 g1 = (GData1) gdata;
spn_SelectionX1[0].setValue(g1.getAccurateProductMatrix().M30);
spn_SelectionY1[0].setValue(g1.getAccurateProductMatrix().M31);
spn_SelectionZ1[0].setValue(g1.getAccurateProductMatrix().M32);
spn_SelectionX2[0].setValue(g1.getAccurateProductMatrix().M00);
spn_SelectionY2[0].setValue(g1.getAccurateProductMatrix().M01);
spn_SelectionZ2[0].setValue(g1.getAccurateProductMatrix().M02);
spn_SelectionX3[0].setValue(g1.getAccurateProductMatrix().M10);
spn_SelectionY3[0].setValue(g1.getAccurateProductMatrix().M11);
spn_SelectionZ3[0].setValue(g1.getAccurateProductMatrix().M12);
spn_SelectionX4[0].setValue(g1.getAccurateProductMatrix().M20);
spn_SelectionY4[0].setValue(g1.getAccurateProductMatrix().M21);
spn_SelectionZ4[0].setValue(g1.getAccurateProductMatrix().M22);
break;
default:
disableSelectionTab();
updatingSelectionTab = true;
break;
}
lbl_SelectionX1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX1 : "") + " {" + spn_SelectionX1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY1 : "") + " {" + spn_SelectionY1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ1 : "") + " {" + spn_SelectionZ1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX2 : "") + " {" + spn_SelectionX2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY2 : "") + " {" + spn_SelectionY2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ2 : "") + " {" + spn_SelectionZ2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX3 : "") + " {" + spn_SelectionX3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY3 : "") + " {" + spn_SelectionY3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ3 : "") + " {" + spn_SelectionZ3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX4 : "") + " {" + spn_SelectionX4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY4 : "") + " {" + spn_SelectionY4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ4 : "") + " {" + spn_SelectionZ4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX1[0].getParent().layout();
updatingSelectionTab = false;
break;
default:
disableSelectionTab();
break;
}
} else {
disableSelectionTab();
}
if (breakIt) break;
}
} else {
disableSelectionTab();
}
} else {
disableSelectionTab();
}
updatingSelectionTab = false;
regainFocus();
}
});
btn_NextSelection[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updatingSelectionTab = true;
NLogger.debug(getClass(), "Next Selection..."); //$NON-NLS-1$
final DatFile df = Project.getFileToEdit();
if (df != null && !df.isReadOnly()) {
final VertexManager vm = df.getVertexManager();
vm.addSnapshot();
final int count = vm.getSelectedData().size();
if (count > 0) {
boolean breakIt = false;
boolean firstRun = true;
while (true) {
int index = vm.getSelectedItemIndex();
index++;
if (index >= count) {
index = 0;
if (!firstRun) breakIt = true;
}
firstRun = false;
vm.setSelectedItemIndex(index);
final GData gdata = (GData) vm.getSelectedData().toArray()[index];
if (vm.isNotInSubfileAndLinetype1to5(gdata)) {
vm.setSelectedLine(gdata);
disableSelectionTab();
updatingSelectionTab = true;
switch (gdata.type()) {
case 1:
case 5:
case 4:
spn_SelectionX4[0].setEnabled(true);
spn_SelectionY4[0].setEnabled(true);
spn_SelectionZ4[0].setEnabled(true);
case 3:
spn_SelectionX3[0].setEnabled(true);
spn_SelectionY3[0].setEnabled(true);
spn_SelectionZ3[0].setEnabled(true);
case 2:
spn_SelectionX1[0].setEnabled(true);
spn_SelectionY1[0].setEnabled(true);
spn_SelectionZ1[0].setEnabled(true);
spn_SelectionX2[0].setEnabled(true);
spn_SelectionY2[0].setEnabled(true);
spn_SelectionZ2[0].setEnabled(true);
txt_Line[0].setText(gdata.toString());
breakIt = true;
btn_MoveAdjacentData2[0].setEnabled(true);
switch (gdata.type()) {
case 5:
BigDecimal[] g5 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g5[0]);
spn_SelectionY1[0].setValue(g5[1]);
spn_SelectionZ1[0].setValue(g5[2]);
spn_SelectionX2[0].setValue(g5[3]);
spn_SelectionY2[0].setValue(g5[4]);
spn_SelectionZ2[0].setValue(g5[5]);
spn_SelectionX3[0].setValue(g5[6]);
spn_SelectionY3[0].setValue(g5[7]);
spn_SelectionZ3[0].setValue(g5[8]);
spn_SelectionX4[0].setValue(g5[9]);
spn_SelectionY4[0].setValue(g5[10]);
spn_SelectionZ4[0].setValue(g5[11]);
break;
case 4:
BigDecimal[] g4 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g4[0]);
spn_SelectionY1[0].setValue(g4[1]);
spn_SelectionZ1[0].setValue(g4[2]);
spn_SelectionX2[0].setValue(g4[3]);
spn_SelectionY2[0].setValue(g4[4]);
spn_SelectionZ2[0].setValue(g4[5]);
spn_SelectionX3[0].setValue(g4[6]);
spn_SelectionY3[0].setValue(g4[7]);
spn_SelectionZ3[0].setValue(g4[8]);
spn_SelectionX4[0].setValue(g4[9]);
spn_SelectionY4[0].setValue(g4[10]);
spn_SelectionZ4[0].setValue(g4[11]);
break;
case 3:
BigDecimal[] g3 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g3[0]);
spn_SelectionY1[0].setValue(g3[1]);
spn_SelectionZ1[0].setValue(g3[2]);
spn_SelectionX2[0].setValue(g3[3]);
spn_SelectionY2[0].setValue(g3[4]);
spn_SelectionZ2[0].setValue(g3[5]);
spn_SelectionX3[0].setValue(g3[6]);
spn_SelectionY3[0].setValue(g3[7]);
spn_SelectionZ3[0].setValue(g3[8]);
break;
case 2:
BigDecimal[] g2 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g2[0]);
spn_SelectionY1[0].setValue(g2[1]);
spn_SelectionZ1[0].setValue(g2[2]);
spn_SelectionX2[0].setValue(g2[3]);
spn_SelectionY2[0].setValue(g2[4]);
spn_SelectionZ2[0].setValue(g2[5]);
break;
case 1:
vm.getSelectedVertices().clear();
btn_MoveAdjacentData2[0].setEnabled(false);
GData1 g1 = (GData1) gdata;
spn_SelectionX1[0].setValue(g1.getAccurateProductMatrix().M30);
spn_SelectionY1[0].setValue(g1.getAccurateProductMatrix().M31);
spn_SelectionZ1[0].setValue(g1.getAccurateProductMatrix().M32);
spn_SelectionX2[0].setValue(g1.getAccurateProductMatrix().M00);
spn_SelectionY2[0].setValue(g1.getAccurateProductMatrix().M01);
spn_SelectionZ2[0].setValue(g1.getAccurateProductMatrix().M02);
spn_SelectionX3[0].setValue(g1.getAccurateProductMatrix().M10);
spn_SelectionY3[0].setValue(g1.getAccurateProductMatrix().M11);
spn_SelectionZ3[0].setValue(g1.getAccurateProductMatrix().M12);
spn_SelectionX4[0].setValue(g1.getAccurateProductMatrix().M20);
spn_SelectionY4[0].setValue(g1.getAccurateProductMatrix().M21);
spn_SelectionZ4[0].setValue(g1.getAccurateProductMatrix().M22);
break;
default:
disableSelectionTab();
updatingSelectionTab = true;
break;
}
lbl_SelectionX1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX1 : "X :") + " {" + spn_SelectionX1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY1 : "Y :") + " {" + spn_SelectionY1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ1 : "Z :") + " {" + spn_SelectionZ1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX2 : "M00:") + " {" + spn_SelectionX2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY2 : "M01:") + " {" + spn_SelectionY2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ2 : "M02:") + " {" + spn_SelectionZ2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX3 : "M10:") + " {" + spn_SelectionX3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY3 : "M11:") + " {" + spn_SelectionY3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ3 : "M12:") + " {" + spn_SelectionZ3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX4 : "M20:") + " {" + spn_SelectionX4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY4 : "M21:") + " {" + spn_SelectionY4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ4 : "M22:") + " {" + spn_SelectionZ4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX1[0].getParent().layout();
break;
default:
disableSelectionTab();
break;
}
} else {
disableSelectionTab();
}
if (breakIt) break;
}
} else {
disableSelectionTab();
}
} else {
disableSelectionTab();
}
updatingSelectionTab = false;
regainFocus();
}
});
final ValueChangeAdapter va = new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
if (updatingSelectionTab || Project.getFileToEdit() == null) return;
Project.getFileToEdit().getVertexManager().addSnapshot();
final GData newLine = Project.getFileToEdit().getVertexManager().updateSelectedLine(
spn_SelectionX1[0].getValue(), spn_SelectionY1[0].getValue(), spn_SelectionZ1[0].getValue(),
spn_SelectionX2[0].getValue(), spn_SelectionY2[0].getValue(), spn_SelectionZ2[0].getValue(),
spn_SelectionX3[0].getValue(), spn_SelectionY3[0].getValue(), spn_SelectionZ3[0].getValue(),
spn_SelectionX4[0].getValue(), spn_SelectionY4[0].getValue(), spn_SelectionZ4[0].getValue(),
btn_MoveAdjacentData2[0].getSelection()
);
if (newLine == null) {
disableSelectionTab();
} else {
txt_Line[0].setText(newLine.toString());
}
}
};
spn_SelectionX1[0].addValueChangeListener(va);
spn_SelectionY1[0].addValueChangeListener(va);
spn_SelectionZ1[0].addValueChangeListener(va);
spn_SelectionX2[0].addValueChangeListener(va);
spn_SelectionY2[0].addValueChangeListener(va);
spn_SelectionZ2[0].addValueChangeListener(va);
spn_SelectionX3[0].addValueChangeListener(va);
spn_SelectionY3[0].addValueChangeListener(va);
spn_SelectionZ3[0].addValueChangeListener(va);
spn_SelectionX4[0].addValueChangeListener(va);
spn_SelectionY4[0].addValueChangeListener(va);
spn_SelectionZ4[0].addValueChangeListener(va);
btn_MoveAdjacentData2[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
regainFocus();
}
});
treeParts[0].addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == MouseButton.RIGHT) {
NLogger.debug(getClass(), "Showing context menu."); //$NON-NLS-1$
try {
if (treeParts[0].getTree().getMenu() != null) {
treeParts[0].getTree().getMenu().dispose();
}
} catch (Exception ex) {}
Menu treeMenu = new Menu(treeParts[0].getTree());
treeParts[0].getTree().setMenu(treeMenu);
mnu_treeMenu[0] = treeMenu;
MenuItem mntmOpenIn3DEditor = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_OpenIn3DEditor[0] = mntmOpenIn3DEditor;
mntmOpenIn3DEditor.setEnabled(true);
mntmOpenIn3DEditor.setText(I18n.E3D_OpenIn3DEditor);
MenuItem mntmOpenInTextEditor = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_OpenInTextEditor[0] = mntmOpenInTextEditor;
mntmOpenInTextEditor.setEnabled(true);
mntmOpenInTextEditor.setText(I18n.E3D_OpenInTextEditor);
@SuppressWarnings("unused")
MenuItem mntm_Separator = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR);
MenuItem mntmClose = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_Close[0] = mntmClose;
mntmClose.setEnabled(true);
mntmClose.setText(I18n.E3D_Close);
@SuppressWarnings("unused")
MenuItem mntm_Separator2 = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR);
MenuItem mntmRename = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_Rename[0] = mntmRename;
mntmRename.setEnabled(true);
mntmRename.setText(I18n.E3D_RenameMove);
MenuItem mntmRevert = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_Revert[0] = mntmRevert;
mntmRevert.setEnabled(true);
mntmRevert.setText(I18n.E3D_RevertAllChanges);
@SuppressWarnings("unused")
MenuItem mntm_Separator3 = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR);
MenuItem mntmCopyToUnofficial = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_CopyToUnofficial[0] = mntmCopyToUnofficial;
mntmCopyToUnofficial.setEnabled(true);
mntmCopyToUnofficial.setText(I18n.E3D_CopyToUnofficialLibrary);
mntm_OpenInTextEditor[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
w.getTabFolder().setSelection(t);
((CompositeTab) t).getControl().getShell().forceActive();
if (w.isSeperateWindow()) {
w.open();
}
df.getVertexManager().setUpdated(true);
return;
}
}
}
EditorTextWindow w = null;
for (EditorTextWindow w2 : Project.getOpenTextWindows()) {
if (w2.getTabFolder().getItems().length == 0) {
w = w2;
break;
}
}
// Project.getParsedFiles().add(df); IS NECESSARY HERE
Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
if (!Project.getOpenTextWindows().isEmpty() && w != null || !(w = Project.getOpenTextWindows().iterator().next()).isSeperateWindow()) {
w.openNewDatFileTab(df, true);
} else {
new EditorTextWindow().run(df, false);
}
df.getVertexManager().addSnapshot();
}
cleanupClosedData();
updateTabs();
}
});
mntm_OpenIn3DEditor[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
openFileIn3DEditor(df);
updateTree_unsavedEntries();
cleanupClosedData();
regainFocus();
}
}
});
mntm_Revert[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
revert(df);
}
regainFocus();
}
});
mntm_Close[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
Project.removeOpenedFile(df);
if (!closeDatfile(df)) {
Project.addOpenedFile(df);
updateTabs();
}
}
}
});
mntm_Rename[0].addSelectionListener(new SelectionAdapter() {
@SuppressWarnings("unchecked")
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
if (df.isReadOnly()) {
regainFocus();
return;
}
df.getVertexManager().addSnapshot();
FileDialog dlg = new FileDialog(Editor3DWindow.getWindow().getShell(), SWT.SAVE);
File tmp = new File(df.getNewName());
dlg.setFilterPath(tmp.getAbsolutePath().substring(0, tmp.getAbsolutePath().length() - tmp.getName().length()));
dlg.setFileName(tmp.getName());
dlg.setFilterExtensions(new String[]{"*.dat"}); //$NON-NLS-1$
dlg.setOverwrite(true);
// Change the title bar text
dlg.setText(I18n.DIALOG_RenameOrMove);
// Calling open() will open and run the dialog.
// It will return the selected file, or
// null if user cancels
String newPath = dlg.open();
if (newPath != null) {
while (isFileNameAllocated(newPath, df, false)) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
int result = messageBox.open();
if (result == SWT.CANCEL) {
regainFocus();
return;
}
newPath = dlg.open();
if (newPath == null) {
regainFocus();
return;
}
}
if (df.isProjectFile() && !newPath.startsWith(Project.getProjectPath())) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO);
messageBox.setText(I18n.DIALOG_NoProjectLocationTitle);
Object[] messageArguments = {new File(newPath).getName()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_NoProjectLocation);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.NO) {
regainFocus();
return;
}
}
df.setNewName(newPath);
if (!df.getOldName().equals(df.getNewName())) {
if (!Project.getUnsavedFiles().contains(df)) {
df.parseForData(true);
df.getVertexManager().setModified(true, true);
Project.getUnsavedFiles().add(df);
}
} else {
if (df.getText().equals(df.getOriginalText()) && df.getOldName().equals(df.getNewName())) {
Project.removeUnsavedFile(df);
}
}
df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath()));
final File f = new File(df.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
HashSet<EditorTextWindow> windows = new HashSet<EditorTextWindow>(Project.getOpenTextWindows());
for (EditorTextWindow win : windows) {
win.updateTabWithDatfile(df);
}
updateTree_renamedEntries();
updateTree_unsavedEntries();
}
} else if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].equals(treeItem_Project[0])) {
if (Project.isDefaultProject()) {
if (ProjectActions.createNewProject(Editor3DWindow.getWindow(), true)) {
Project.setLastVisitedPath(Project.getProjectPath());
}
} else {
int result = new NewProjectDialog(true).open();
if (result == IDialogConstants.OK_ID && !Project.getTempProjectPath().equals(Project.getProjectPath())) {
try {
while (new File(Project.getTempProjectPath()).isDirectory()) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.YES | SWT.CANCEL | SWT.NO);
messageBoxError.setText(I18n.PROJECT_ProjectOverwriteTitle);
messageBoxError.setMessage(I18n.PROJECT_ProjectOverwrite);
int result2 = messageBoxError.open();
if (result2 == SWT.CANCEL) {
regainFocus();
return;
} else if (result2 == SWT.YES) {
break;
} else {
result = new NewProjectDialog(true).open();
if (result == IDialogConstants.CANCEL_ID) {
regainFocus();
return;
}
}
}
Project.copyFolder(new File(Project.getProjectPath()), new File(Project.getTempProjectPath()));
Project.deleteFolder(new File(Project.getProjectPath()));
// Linked project parts need a new path, because they were copied to a new directory
String defaultPrefix = new File(Project.getProjectPath()).getAbsolutePath() + File.separator;
String projectPrefix = new File(Project.getTempProjectPath()).getAbsolutePath() + File.separator;
Editor3DWindow.getWindow().getProjectParts().getParentItem().setData(Project.getTempProjectPath());
HashSet<DatFile> projectFiles = new HashSet<DatFile>();
projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectParts().getData());
projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectSubparts().getData());
projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives().getData());
projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives48().getData());
for (DatFile df : projectFiles) {
df.getVertexManager().addSnapshot();
boolean isUnsaved = Project.getUnsavedFiles().contains(df);
boolean isParsed = Project.getParsedFiles().contains(df);
Project.getParsedFiles().remove(df);
Project.getUnsavedFiles().remove(df);
String newName = df.getNewName();
String oldName = df.getOldName();
df.updateLastModified();
if (!newName.startsWith(projectPrefix) && newName.startsWith(defaultPrefix)) {
df.setNewName(projectPrefix + newName.substring(defaultPrefix.length()));
}
if (!oldName.startsWith(projectPrefix) && oldName.startsWith(defaultPrefix)) {
df.setOldName(projectPrefix + oldName.substring(defaultPrefix.length()));
}
df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath()));
if (isUnsaved) Project.addUnsavedFile(df);
if (isParsed) Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
}
Project.setProjectName(Project.getTempProjectName());
Project.setProjectPath(Project.getTempProjectPath());
Editor3DWindow.getWindow().getProjectParts().getParentItem().setText(Project.getProjectName());
updateTree_unsavedEntries();
Project.updateEditor();
Editor3DWindow.getWindow().getShell().update();
Project.setLastVisitedPath(Project.getProjectPath());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
} else {
// MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
// messageBoxError.setText(I18n.DIALOG_UnavailableTitle);
// messageBoxError.setMessage(I18n.DIALOG_Unavailable);
// messageBoxError.open();
}
regainFocus();
}
});
mntm_CopyToUnofficial[0] .addSelectionListener(new SelectionAdapter() {
@SuppressWarnings("unchecked")
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
TreeItem p = treeParts[0].getSelection()[0].getParentItem();
String targetPath_u;
String targetPath_l;
String targetPathDir_u;
String targetPathDir_l;
TreeItem targetTreeItem;
boolean projectIsFileOrigin = false;
if (treeItem_ProjectParts[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"; //$NON-NLS-1$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"; //$NON-NLS-1$
targetTreeItem = treeItem_UnofficialParts[0];
projectIsFileOrigin = true;
} else if (treeItem_ProjectPrimitives[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P"; //$NON-NLS-1$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p"; //$NON-NLS-1$
targetTreeItem = treeItem_UnofficialPrimitives[0];
projectIsFileOrigin = true;
} else if (treeItem_ProjectPrimitives48[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialPrimitives48[0];
projectIsFileOrigin = true;
} else if (treeItem_ProjectPrimitives8[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialPrimitives8[0];
projectIsFileOrigin = true;
} else if (treeItem_ProjectSubparts[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"+ File.separator + "S"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"+ File.separator + "s"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialSubparts[0];
projectIsFileOrigin = true;
} else if (treeItem_OfficialParts[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"; //$NON-NLS-1$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"; //$NON-NLS-1$
targetTreeItem = treeItem_UnofficialParts[0];
} else if (treeItem_OfficialPrimitives[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P"; //$NON-NLS-1$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p"; //$NON-NLS-1$
targetTreeItem = treeItem_UnofficialPrimitives[0];
} else if (treeItem_OfficialPrimitives48[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialPrimitives48[0];
} else if (treeItem_OfficialPrimitives8[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialPrimitives8[0];
} else if (treeItem_OfficialSubparts[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"+ File.separator + "S"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"+ File.separator + "s"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialSubparts[0];
} else {
// MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
// messageBoxError.setText(I18n.DIALOG_UnavailableTitle);
// messageBoxError.setMessage(I18n.DIALOG_Unavailable);
// messageBoxError.open();
regainFocus();
return;
}
targetPathDir_l = targetPath_l;
targetPathDir_u = targetPath_u;
final String newName = new File(df.getNewName()).getName();
targetPath_u = targetPath_u + File.separator + newName;
targetPath_l = targetPath_l + File.separator + newName;
DatFile fileToOverwrite_u = new DatFile(targetPath_u);
DatFile fileToOverwrite_l = new DatFile(targetPath_l);
DatFile targetFile = null;
TreeItem[] folders = new TreeItem[5];
folders[0] = treeItem_UnofficialParts[0];
folders[1] = treeItem_UnofficialPrimitives[0];
folders[2] = treeItem_UnofficialPrimitives48[0];
folders[3] = treeItem_UnofficialPrimitives8[0];
folders[4] = treeItem_UnofficialSubparts[0];
for (TreeItem folder : folders) {
ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData();
for (DatFile d : cachedReferences) {
if (fileToOverwrite_u.equals(d) || fileToOverwrite_l.equals(d)) {
targetFile = d;
break;
}
}
}
if (new File(targetPath_u).exists() || new File(targetPath_l).exists() || targetFile != null) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_ReplaceTitle);
Object[] messageArguments = {newName};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_Replace);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.CANCEL) {
regainFocus();
return;
}
}
ArrayList<ArrayList<DatFile>> refResult = null;
if (new File(targetPathDir_l).exists() || new File(targetPathDir_u).exists()) {
if (targetFile == null) {
int result = new CopyDialog(getShell(), new File(df.getNewName()).getName()).open();
switch (result) {
case IDialogConstants.OK_ID:
// Copy File Only
break;
case IDialogConstants.NO_ID:
// Copy File and required and related
if (projectIsFileOrigin) {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]);
} else {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]);
}
break;
case IDialogConstants.YES_ID:
// Copy File and required
if (projectIsFileOrigin) {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]);
} else {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]);
}
break;
default:
regainFocus();
return;
}
DatFile newDatFile = new DatFile(new File(targetPathDir_l).exists() ? targetPath_l : targetPath_u);
// Text exchange includes description exchange
newDatFile.setText(df.getText());
newDatFile.saveForced();
newDatFile.setType(df.getType());
((ArrayList<DatFile>) targetTreeItem.getData()).add(newDatFile);
TreeItem ti = new TreeItem(targetTreeItem, SWT.NONE);
ti.setText(new File(df.getNewName()).getName());
ti.setData(newDatFile);
} else if (targetFile.equals(df)) { // This can only happen if the user opens the unofficial parts folder as a project
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
messageBox.open();
regainFocus();
return;
} else {
int result = new CopyDialog(getShell(), new File(df.getNewName()).getName()).open();
switch (result) {
case IDialogConstants.OK_ID:
// Copy File Only
break;
case IDialogConstants.NO_ID:
// Copy File and required and related
if (projectIsFileOrigin) {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]);
} else {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]);
}
break;
case IDialogConstants.YES_ID:
// Copy File and required
if (projectIsFileOrigin) {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]);
} else {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]);
}
break;
default:
regainFocus();
return;
}
targetFile.disposeData();
updateTree_removeEntry(targetFile);
DatFile newDatFile = new DatFile(new File(targetPathDir_l).exists() ? targetPath_l : targetPath_u);
newDatFile.setText(df.getText());
newDatFile.saveForced();
((ArrayList<DatFile>) targetTreeItem.getData()).add(newDatFile);
TreeItem ti = new TreeItem(targetTreeItem, SWT.NONE);
ti.setText(new File(df.getNewName()).getName());
ti.setData(newDatFile);
}
if (refResult != null) {
// Remove old data
for(int i = 0; i < 5; i++) {
ArrayList<DatFile> toRemove = refResult.get(i);
for (DatFile datToRemove : toRemove) {
datToRemove.disposeData();
updateTree_removeEntry(datToRemove);
}
}
// Create new data
TreeItem[] targetTrees = new TreeItem[]{treeItem_UnofficialParts[0], treeItem_UnofficialSubparts[0], treeItem_UnofficialPrimitives[0], treeItem_UnofficialPrimitives48[0], treeItem_UnofficialPrimitives8[0]};
for(int i = 5; i < 10; i++) {
ArrayList<DatFile> toCreate = refResult.get(i);
for (DatFile datToCreate : toCreate) {
DatFile newDatFile = new DatFile(datToCreate.getOldName());
String source = datToCreate.getTextDirect();
newDatFile.setText(source);
newDatFile.setOriginalText(source);
newDatFile.saveForced();
newDatFile.setType(datToCreate.getType());
((ArrayList<DatFile>) targetTrees[i - 5].getData()).add(newDatFile);
TreeItem ti = new TreeItem(targetTrees[i - 5], SWT.NONE);
ti.setText(new File(datToCreate.getOldName()).getName());
ti.setData(newDatFile);
}
}
}
updateTree_unsavedEntries();
}
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBoxError.setText(I18n.DIALOG_UnavailableTitle);
messageBoxError.setMessage(I18n.DIALOG_Unavailable);
messageBoxError.open();
}
regainFocus();
}
});
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
Menu menu = mnu_treeMenu[0];
menu.setLocation(x, y);
menu.setVisible(true);
}
regainFocus();
}
});
treeParts[0].addListener(SWT.MouseDoubleClick, new Listener() {
@Override
public void handleEvent(Event event) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null) {
treeParts[0].getSelection()[0].setVisible(!treeParts[0].getSelection()[0].isVisible());
TreeItem sel = treeParts[0].getSelection()[0];
sh.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
treeParts[0].build();
}
});
treeParts[0].redraw();
treeParts[0].update();
treeParts[0].getTree().select(treeParts[0].getMapInv().get(sel));
}
regainFocus();
}
});
txt_Search[0].addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
search(txt_Search[0].getText());
}
});
btn_ResetSearch[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
txt_Search[0].setText(""); //$NON-NLS-1$
txt_Search[0].setFocus();
}
});
txt_primitiveSearch[0].addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
getCompositePrimitive().collapseAll();
ArrayList<Primitive> prims = getCompositePrimitive().getPrimitives();
final String crit = txt_primitiveSearch[0].getText();
if (crit.trim().isEmpty()) {
getCompositePrimitive().setSearchResults(new ArrayList<Primitive>());
Matrix4f.setIdentity(getCompositePrimitive().getTranslation());
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
return;
}
String criteria = ".*" + crit + ".*"; //$NON-NLS-1$ //$NON-NLS-2$
try {
"DUMMY".matches(criteria); //$NON-NLS-1$
} catch (PatternSyntaxException pe) {
getCompositePrimitive().setSearchResults(new ArrayList<Primitive>());
Matrix4f.setIdentity(getCompositePrimitive().getTranslation());
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
return;
}
final Pattern pattern = Pattern.compile(criteria);
ArrayList<Primitive> results = new ArrayList<Primitive>();
for (Primitive p : prims) {
p.search(pattern, results);
}
if (results.isEmpty()) {
results.add(null);
}
getCompositePrimitive().setSearchResults(results);
Matrix4f.setIdentity(getCompositePrimitive().getTranslation());
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
}
});
btn_resetPrimitiveSearch[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
txt_primitiveSearch[0].setText(""); //$NON-NLS-1$
txt_primitiveSearch[0].setFocus();
}
});
btn_zoomInPrimitives[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getCompositePrimitive().zoomIn();
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
}
});
btn_zoomOutPrimitives[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getCompositePrimitive().zoomOut();
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
}
});
btn_Hide[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
if (Project.getFileToEdit().getVertexManager().getSelectedData().size() > 0) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().hideSelection();
Project.getFileToEdit().addHistory();
}
}
regainFocus();
}
});
btn_ShowAll[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().showAll();
Project.getFileToEdit().addHistory();
}
regainFocus();
}
});
btn_NoTransparentSelection[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setNoTransparentSelection(btn_NoTransparentSelection[0].getSelection());
regainFocus();
}
});
btn_BFCToggle[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setBfcToggle(btn_BFCToggle[0].getSelection());
regainFocus();
}
});
btn_InsertAtCursorPosition[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setInsertingAtCursorPosition(btn_InsertAtCursorPosition[0].getSelection());
regainFocus();
}
});
btn_Delete[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().delete(Editor3DWindow.getWindow().isMovingAdjacentData(), true);
}
regainFocus();
}
});
btn_Copy[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().copy();
}
regainFocus();
}
});
btn_Cut[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().copy();
Project.getFileToEdit().getVertexManager().delete(false, true);
}
regainFocus();
}
});
btn_Paste[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().paste();
if (WorkbenchManager.getUserSettingState().isDisableMAD3D()) {
setMovingAdjacentData(false);
GuiManager.updateStatus();
}
}
regainFocus();
}
});
if (btn_Manipulator_0_toOrigin[0] != null) btn_Manipulator_0_toOrigin[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_0();
}
});
if (btn_Manipulator_XIII_toWorld[0] != null) btn_Manipulator_XIII_toWorld[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XIII();
}
});
if (btn_Manipulator_X_XReverse[0] != null) btn_Manipulator_X_XReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_X();
}
});
if (btn_Manipulator_XI_YReverse[0] != null) btn_Manipulator_XI_YReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XI();
}
});
if (btn_Manipulator_XII_ZReverse[0] != null) btn_Manipulator_XII_ZReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XII();
}
});
if (btn_Manipulator_SwitchXY[0] != null) btn_Manipulator_SwitchXY[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XY();
}
});
if (btn_Manipulator_SwitchXZ[0] != null) btn_Manipulator_SwitchXZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XZ();
}
});
if (btn_Manipulator_SwitchYZ[0] != null) btn_Manipulator_SwitchYZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_YZ();
}
});
if (btn_Manipulator_1_cameraToPos[0] != null) btn_Manipulator_1_cameraToPos[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_1();
}
});
if (btn_Manipulator_2_toAverage[0] != null) btn_Manipulator_2_toAverage[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_2();
}
});
if (btn_Manipulator_3_toSubfile[0] != null) btn_Manipulator_3_toSubfile[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_3();
}
});
if (btn_Manipulator_32_subfileTo[0] != null) btn_Manipulator_32_subfileTo[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_32();
}
});
if (btn_Manipulator_4_toVertex[0] != null) btn_Manipulator_4_toVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_4();
}
});
if (btn_Manipulator_5_toEdge[0] != null) btn_Manipulator_5_toEdge[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_5();
}
});
if (btn_Manipulator_6_toSurface[0] != null) btn_Manipulator_6_toSurface[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_6();
}
});
if (btn_Manipulator_7_toVertexNormal[0] != null) btn_Manipulator_7_toVertexNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_7();
}
});
if (btn_Manipulator_8_toEdgeNormal[0] != null) btn_Manipulator_8_toEdgeNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_8();
}
});
if (btn_Manipulator_9_toSurfaceNormal[0] != null) btn_Manipulator_9_toSurfaceNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_9();
}
});
if (btn_Manipulator_XIV_adjustRotationCenter[0] != null) btn_Manipulator_XIV_adjustRotationCenter[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XIV();
}
});
if (btn_Manipulator_XV_toVertexPosition[0] != null) btn_Manipulator_XV_toVertexPosition[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XV();
}
});
if (mntm_Manipulator_0_toOrigin[0] != null) mntm_Manipulator_0_toOrigin[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_0();
}
});
if (mntm_Manipulator_XIII_toWorld[0] != null) mntm_Manipulator_XIII_toWorld[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XIII();
}
});
if (mntm_Manipulator_X_XReverse[0] != null) mntm_Manipulator_X_XReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_X();
}
});
if (mntm_Manipulator_XI_YReverse[0] != null) mntm_Manipulator_XI_YReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XI();
}
});
if (mntm_Manipulator_XII_ZReverse[0] != null) mntm_Manipulator_XII_ZReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XII();
}
});
if (mntm_Manipulator_SwitchXY[0] != null) mntm_Manipulator_SwitchXY[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XY();
}
});
if (mntm_Manipulator_SwitchXZ[0] != null) mntm_Manipulator_SwitchXZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XZ();
}
});
if (mntm_Manipulator_SwitchYZ[0] != null) mntm_Manipulator_SwitchYZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_YZ();
}
});
if (mntm_Manipulator_1_cameraToPos[0] != null) mntm_Manipulator_1_cameraToPos[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_1();
}
});
if (mntm_Manipulator_2_toAverage[0] != null) mntm_Manipulator_2_toAverage[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_2();
}
});
if (mntm_Manipulator_3_toSubfile[0] != null) mntm_Manipulator_3_toSubfile[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_3();
}
});
if (mntm_Manipulator_32_subfileTo[0] != null) mntm_Manipulator_32_subfileTo[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_32();
}
});
if (mntm_Manipulator_4_toVertex[0] != null) mntm_Manipulator_4_toVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_4();
}
});
if (mntm_Manipulator_5_toEdge[0] != null) mntm_Manipulator_5_toEdge[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_5();
}
});
if (mntm_Manipulator_6_toSurface[0] != null) mntm_Manipulator_6_toSurface[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_6();
}
});
if (mntm_Manipulator_7_toVertexNormal[0] != null) mntm_Manipulator_7_toVertexNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_7();
}
});
if (mntm_Manipulator_8_toEdgeNormal[0] != null) mntm_Manipulator_8_toEdgeNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_8();
}
});
if (mntm_Manipulator_9_toSurfaceNormal[0] != null) mntm_Manipulator_9_toSurfaceNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_9();
}
});
if (mntm_Manipulator_XIV_adjustRotationCenter[0] != null) mntm_Manipulator_XIV_adjustRotationCenter[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XIV();
}
});
if (mntm_Manipulator_XV_toVertexPosition[0] != null) mntm_Manipulator_XV_toVertexPosition[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XV();
}
});
mntm_SelectAll[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectAll(sels, true);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectAllVisible[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectAll(sels, false);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectAllWithColours[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectAllWithSameColours(sels, true);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectAllVisibleWithColours[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectAllWithSameColours(sels, false);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectNone[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.clearSelection();
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectInverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectInverse(sels);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_WithSameColour[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithSameOrientation[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
if (mntm_WithSameOrientation[0].getSelection()) {
new ValueDialog(getShell(), I18n.E3D_AngleDiff, I18n.E3D_ThreshInDeg) {
@Override
public void initializeSpinner() {
this.spn_Value[0].setMinimum(new BigDecimal("-90")); //$NON-NLS-1$
this.spn_Value[0].setMaximum(new BigDecimal("180")); //$NON-NLS-1$
this.spn_Value[0].setValue(sels.getAngle());
}
@Override
public void applyValue() {
sels.setAngle(this.spn_Value[0].getValue());
}
}.open();
}
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithAccuracy[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
if (mntm_WithAccuracy[0].getSelection()) {
new ValueDialog(getShell(), I18n.E3D_SetAccuracy, I18n.E3D_ThreshInLdu) {
@Override
public void initializeSpinner() {
this.spn_Value[0].setMinimum(new BigDecimal("0")); //$NON-NLS-1$
this.spn_Value[0].setMaximum(new BigDecimal("1000")); //$NON-NLS-1$
this.spn_Value[0].setValue(sels.getEqualDistance());
}
@Override
public void applyValue() {
sels.setEqualDistance(this.spn_Value[0].getValue());
}
}.open();
}
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithHiddenData[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithWholeSubfiles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithAdjacency[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_ExceptSubfiles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
mntm_WithWholeSubfiles[0].setEnabled(!mntm_ExceptSubfiles[0].getSelection());
showSelectMenu();
}
});
regainFocus();
}
});
mntm_StopAtEdges[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_STriangles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SQuads[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SCLines[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SVertices[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SLines[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SelectEverything[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
sels.setScope(SelectorSettings.EVERYTHING);
loadSelectorSettings();
vm.selector(sels);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectConnected[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
sels.setScope(SelectorSettings.CONNECTED);
loadSelectorSettings();
vm.selector(sels);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectTouching[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
sels.setScope(SelectorSettings.TOUCHING);
loadSelectorSettings();
vm.selector(sels);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectIsolatedVertices[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.selectIsolatedVertices();
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
}
});
regainFocus();
}
});
mntm_Split[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.split(2);
regainFocus();
return;
}
}
}
});
regainFocus();
}
});
mntm_SplitNTimes[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
final int[] frac = new int[]{2};
if (new ValueDialogInt(getShell(), I18n.E3D_SplitEdges, I18n.E3D_NumberOfFractions) {
@Override
public void initializeSpinner() {
this.spn_Value[0].setMinimum(2);
this.spn_Value[0].setMaximum(1000);
this.spn_Value[0].setValue(2);
}
@Override
public void applyValue() {
frac[0] = this.spn_Value[0].getValue();
}
}.open() == OK) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.split(frac[0]);
regainFocus();
return;
}
}
}
}
});
regainFocus();
}
});
mntm_Smooth[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
OpenGLRenderer.getSmoothing().set(true);
if (new SmoothDialog(getShell()).open() == OK) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.smooth(SmoothDialog.isX(), SmoothDialog.isY(), SmoothDialog.isZ(), SmoothDialog.getFactor(), SmoothDialog.getIterations());
regainFocus();
}
OpenGLRenderer.getSmoothing().set(false);
return;
}
}
}
});
regainFocus();
}
});
mntm_MergeToAverage[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.AVERAGE, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MergeToLastSelected[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.LAST_SELECTED, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MergeToNearestVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.NEAREST_VERTEX, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MergeToNearestEdge[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.NEAREST_EDGE, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MergeToNearestFace[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.NEAREST_FACE, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectSingleVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
final VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
final Set<Vertex> sv = vm.getSelectedVertices();
if (new VertexDialog(getShell()).open() == IDialogConstants.OK_ID) {
Vertex v = VertexDialog.getVertex();
if (vm.getVertices().contains(v)) {
sv.add(v);
vm.syncWithTextEditors(true);
}
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_setXYZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final boolean noReset = (e.stateMask & SWT.CTRL) != SWT.CTRL;
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
Vertex v = null;
final VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
final Set<Vertex> sv = vm.getSelectedVertices();
if (VertexManager.getClipboard().size() == 1) {
GData vertex = VertexManager.getClipboard().get(0);
if (vertex.type() == 0) {
String line = vertex.toString();
line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$
String[] data_segments = line.split("\\s+"); //$NON-NLS-1$
if (line.startsWith("0 !LPE")) { //$NON-NLS-1$
if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$
Vector3d start = new Vector3d();
boolean numberError = false;
if (data_segments.length == 6) {
try {
start.setX(new BigDecimal(data_segments[3], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setY(new BigDecimal(data_segments[4], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setZ(new BigDecimal(data_segments[5], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
} else {
numberError = true;
}
if (!numberError) {
v = new Vertex(start);
}
}
}
}
} else if (sv.size() == 1) {
v = sv.iterator().next();
}
final Vertex mani = new Vertex(c3d.getManipulator().getAccuratePosition());
if (new CoordinatesDialog(getShell(), v, mani).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
int coordCount = 0;
coordCount += CoordinatesDialog.isX() ? 1 : 0;
coordCount += CoordinatesDialog.isY() ? 1 : 0;
coordCount += CoordinatesDialog.isZ() ? 1 : 0;
if (coordCount == 1 && CoordinatesDialog.getStart() != null) {
TreeSet<Vertex> verts = new TreeSet<Vertex>();
verts.addAll(vm.getSelectedVertices());
vm.clearSelection();
for (Vertex v2 : verts) {
final boolean a = CoordinatesDialog.isX();
final boolean b = CoordinatesDialog.isY();
final boolean c = CoordinatesDialog.isZ();
vm.getSelectedVertices().add(v2);
Vector3d delta = Vector3d.sub(CoordinatesDialog.getEnd(), CoordinatesDialog.getStart());
boolean doMoveOnLine = false;
BigDecimal s = BigDecimal.ZERO;
Vector3d v1 = CoordinatesDialog.getStart();
if (CoordinatesDialog.isX() && delta.X.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.X.subtract(CoordinatesDialog.getStart().X).divide(delta.X, Threshold.mc);
} else if (CoordinatesDialog.isY() && delta.Y.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.Y.subtract(CoordinatesDialog.getStart().Y).divide(delta.Y, Threshold.mc);
} else if (CoordinatesDialog.isZ() && delta.Z.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.Z.subtract(CoordinatesDialog.getStart().Z).divide(delta.Z, Threshold.mc);
}
if (doMoveOnLine) {
CoordinatesDialog.setVertex(new Vertex(v1.X.add(delta.X.multiply(s)), v1.Y.add(delta.Y.multiply(s)), v1.Z.add(delta.Z.multiply(s))));
CoordinatesDialog.setX(true);
CoordinatesDialog.setY(true);
CoordinatesDialog.setZ(true);
}
vm.setXyzOrTranslateOrTransform(CoordinatesDialog.getVertex(), null, TransformationMode.SET, CoordinatesDialog.isX(), CoordinatesDialog.isY(), CoordinatesDialog.isZ(), isMovingAdjacentData() || vm.getSelectedVertices().size() == 1, true);
vm.clearSelection();
CoordinatesDialog.setX(a);
CoordinatesDialog.setY(b);
CoordinatesDialog.setZ(c);
}
}else if (coordCount == 2 && CoordinatesDialog.getStart() != null) {
TreeSet<Vertex> verts = new TreeSet<Vertex>();
verts.addAll(vm.getSelectedVertices());
vm.clearSelection();
for (Vertex v2 : verts) {
final boolean a = CoordinatesDialog.isX();
final boolean b = CoordinatesDialog.isY();
final boolean c = CoordinatesDialog.isZ();
vm.getSelectedVertices().add(v2);
Vector3d delta = Vector3d.sub(CoordinatesDialog.getEnd(), CoordinatesDialog.getStart());
boolean doMoveOnLine = false;
BigDecimal s = BigDecimal.ZERO;
Vector3d v1 = CoordinatesDialog.getStart();
if (CoordinatesDialog.isX() && delta.X.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.X.subtract(CoordinatesDialog.getStart().X).divide(delta.X, Threshold.mc);
} else if (CoordinatesDialog.isY() && delta.Y.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.Y.subtract(CoordinatesDialog.getStart().Y).divide(delta.Y, Threshold.mc);
} else if (CoordinatesDialog.isZ() && delta.Z.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.Z.subtract(CoordinatesDialog.getStart().Z).divide(delta.Z, Threshold.mc);
}
BigDecimal X = !CoordinatesDialog.isX() ? v1.X.add(delta.X.multiply(s)) : v2.X;
BigDecimal Y = !CoordinatesDialog.isY() ? v1.Y.add(delta.Y.multiply(s)) : v2.Y;
BigDecimal Z = !CoordinatesDialog.isZ() ? v1.Z.add(delta.Z.multiply(s)) : v2.Z;
if (doMoveOnLine) {
CoordinatesDialog.setVertex(new Vertex(X, Y, Z));
CoordinatesDialog.setX(true);
CoordinatesDialog.setY(true);
CoordinatesDialog.setZ(true);
}
vm.setXyzOrTranslateOrTransform(CoordinatesDialog.getVertex(), null, TransformationMode.SET, CoordinatesDialog.isX(), CoordinatesDialog.isY(), CoordinatesDialog.isZ(), isMovingAdjacentData() || vm.getSelectedVertices().size() == 1, true);
vm.clearSelection();
CoordinatesDialog.setX(a);
CoordinatesDialog.setY(b);
CoordinatesDialog.setZ(c);
}
} else {
vm.setXyzOrTranslateOrTransform(CoordinatesDialog.getVertex(), null, TransformationMode.SET, CoordinatesDialog.isX(), CoordinatesDialog.isY(), CoordinatesDialog.isZ(), isMovingAdjacentData() || vm.getSelectedVertices().size() == 1, true);
}
if (noReset) {
CoordinatesDialog.setStart(null);
CoordinatesDialog.setEnd(null);
}
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Translate[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
if (new TranslateDialog(getShell(), null).open() == IDialogConstants.OK_ID) {
c3d.getLockableDatFileReference().getVertexManager().addSnapshot();
c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(TranslateDialog.getOffset(), null, TransformationMode.TRANSLATE, TranslateDialog.isX(), TranslateDialog.isY(), TranslateDialog.isZ(), isMovingAdjacentData(), true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Rotate[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
TreeSet<Vertex> clipboard = new TreeSet<Vertex>();
if (VertexManager.getClipboard().size() == 1) {
GData vertex = VertexManager.getClipboard().get(0);
if (vertex.type() == 0) {
String line = vertex.toString();
line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$
String[] data_segments = line.split("\\s+"); //$NON-NLS-1$
if (line.startsWith("0 !LPE")) { //$NON-NLS-1$
if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$
Vector3d start = new Vector3d();
boolean numberError = false;
if (data_segments.length == 6) {
try {
start.setX(new BigDecimal(data_segments[3], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setY(new BigDecimal(data_segments[4], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setZ(new BigDecimal(data_segments[5], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
} else {
numberError = true;
}
if (!numberError) {
clipboard.add(new Vertex(start));
}
}
}
}
}
final Vertex mani = new Vertex(c3d.getManipulator().getAccuratePosition());
if (new RotateDialog(getShell(), null, clipboard, mani).open() == IDialogConstants.OK_ID) {
c3d.getLockableDatFileReference().getVertexManager().addSnapshot();
c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(RotateDialog.getAngles(), RotateDialog.getPivot(), TransformationMode.ROTATE, RotateDialog.isX(), RotateDialog.isY(), RotateDialog.isZ(), isMovingAdjacentData(), true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Scale[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
TreeSet<Vertex> clipboard = new TreeSet<Vertex>();
if (VertexManager.getClipboard().size() == 1) {
GData vertex = VertexManager.getClipboard().get(0);
if (vertex.type() == 0) {
String line = vertex.toString();
line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$
String[] data_segments = line.split("\\s+"); //$NON-NLS-1$
if (line.startsWith("0 !LPE")) { //$NON-NLS-1$
if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$
Vector3d start = new Vector3d();
boolean numberError = false;
if (data_segments.length == 6) {
try {
start.setX(new BigDecimal(data_segments[3], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setY(new BigDecimal(data_segments[4], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setZ(new BigDecimal(data_segments[5], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
} else {
numberError = true;
}
if (!numberError) {
clipboard.add(new Vertex(start));
}
}
}
}
}
final Vertex mani = new Vertex(c3d.getManipulator().getAccuratePosition());
if (new ScaleDialog(getShell(), null, clipboard, mani).open() == IDialogConstants.OK_ID) {
c3d.getLockableDatFileReference().getVertexManager().addSnapshot();
c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(ScaleDialog.getScaleFactors(), ScaleDialog.getPivot(), TransformationMode.SCALE, ScaleDialog.isX(), ScaleDialog.isY(), ScaleDialog.isZ(), isMovingAdjacentData(), true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_PartReview[0].addSelectionListener(new SelectionAdapter() {
final Pattern WHITESPACE = Pattern.compile("\\s+"); //$NON-NLS-1$
final Pattern pattern = Pattern.compile("\r?\n|\r"); //$NON-NLS-1$
@Override
public void widgetSelected(SelectionEvent e) {
if (new PartReviewDialog(getShell()).open() == IDialogConstants.OK_ID) {
try {
new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(false, false, new IRunnableWithProgress() {
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask(I18n.E3D_PartReview, IProgressMonitor.UNKNOWN);
String fileName = PartReviewDialog.getFileName().toLowerCase(Locale.ENGLISH);
if (!fileName.endsWith(".dat")) fileName = fileName + ".dat"; //$NON-NLS-1$ //$NON-NLS-2$
String oldFileName = fileName;
try {
oldFileName = oldFileName.replaceAll("\\\\", File.separator); //$NON-NLS-1$
} catch (Exception ex) {
// Workaround for windows OS / JVM BUG
oldFileName = oldFileName.replace("\\", File.separator); //$NON-NLS-1$
}
try {
fileName = fileName.replaceAll("\\\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (Exception ex) {
// Workaround for windows OS / JVM BUG
fileName = fileName.replace("\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
}
// Download first, then build the views
// http://www.ldraw.org/library/unofficial
monitor.subTask(fileName);
String source = FileHelper.downloadPartFile("parts/" + fileName); //$NON-NLS-1$
if (source == null) source = FileHelper.downloadPartFile("parts/s/" + fileName); //$NON-NLS-1$
if (source == null) source = FileHelper.downloadPartFile("p/" + fileName); //$NON-NLS-1$
if (source == null) source = FileHelper.downloadPartFile("p/8/" + fileName); //$NON-NLS-1$
if (source == null) source = FileHelper.downloadPartFile("p/48/" + fileName); //$NON-NLS-1$
if (source == null) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setText(I18n.DIALOG_Error);
messageBox.setMessage(I18n.E3D_PartReviewError);
messageBox.open();
return;
}
HashSet<String> files = new HashSet<String>();
files.add(fileName);
ArrayList<String> list = buildFileList(source, new ArrayList<String>(), files, monitor);
final String fileName2 = fileName;
final String source2 = source;
final String oldFileName2 = oldFileName;
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
String fileName = fileName2;
String source = source2;
closeAllComposite3D();
for (EditorTextWindow txtwin : Project.getOpenTextWindows()) {
if (txtwin.isSeperateWindow()) {
txtwin.getShell().close();
} else {
txtwin.closeAllTabs();
}
}
Project.setDefaultProject(true);
Project.setProjectPath(new File("project").getAbsolutePath()); //$NON-NLS-1$
getShell().setText(Version.getApplicationName() + " " + Version.getVersion()); //$NON-NLS-1$
getShell().update();
treeItem_Project[0].setText(fileName);
treeItem_Project[0].setData(Project.getProjectPath());
treeItem_ProjectParts[0].getItems().clear();
treeItem_ProjectSubparts[0].getItems().clear();
treeItem_ProjectPrimitives[0].getItems().clear();
treeItem_OfficialParts[0].setData(null);
list.add(0, new File("project").getAbsolutePath() + File.separator + oldFileName2); //$NON-NLS-1$
list.add(1, source);
DatFile main = View.DUMMY_DATFILE;
HashSet<DatFile> dfsToOpen = new HashSet<DatFile>();
for (int i = list.size() - 2; i >= 0; i -= 2) {
DatFile df;
TreeItem n;
fileName = list.get(i);
source = list.get(i + 1);
df = new DatFile(fileName);
monitor.beginTask(fileName, IProgressMonitor.UNKNOWN);
Display.getCurrent().readAndDispatch();
dfsToOpen.add(df);
df.setText(source);
// Add / remove from unsaved files is mandatory!
Project.addUnsavedFile(df);
df.parseForData(true);
Project.removeUnsavedFile(df);
Project.getParsedFiles().remove(df);
if (source.contains("0 !LDRAW_ORG Unofficial_Subpart")) { //$NON-NLS-1$
int ind = fileName.lastIndexOf(File.separator + "s" + File.separator); //$NON-NLS-1$
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length() * 2 + 1, File.separator + "parts" + File.separator + "s" + File.separator).toString(); //$NON-NLS-1$ //$NON-NLS-2$
}
n = new TreeItem(treeItem_ProjectSubparts[0], SWT.NONE);
df.setType(DatType.SUBPART);
} else if (source.contains("0 !LDRAW_ORG Unofficial_Primitive")) { //$NON-NLS-1$
int ind = fileName.lastIndexOf(File.separator);
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length(), File.separator + "p" + File.separator).toString(); //$NON-NLS-1$
}
n = new TreeItem(treeItem_ProjectPrimitives[0], SWT.NONE);
df.setType(DatType.PRIMITIVE);
} else if (source.contains("0 !LDRAW_ORG Unofficial_48_Primitive")) { //$NON-NLS-1$
int ind = fileName.lastIndexOf(File.separator + "48" + File.separator); //$NON-NLS-1$
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length() * 2 + 2, File.separator + "p" + File.separator + "48" + File.separator).toString(); //$NON-NLS-1$ //$NON-NLS-2$
}
n = new TreeItem(treeItem_ProjectPrimitives48[0], SWT.NONE);
df.setType(DatType.PRIMITIVE48);
} else if (source.contains("0 !LDRAW_ORG Unofficial_8_Primitive")) { //$NON-NLS-1$
int ind = fileName.lastIndexOf(File.separator + "8" + File.separator); //$NON-NLS-1$
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length() * 2 + 1, File.separator + "p" + File.separator + "8" + File.separator).toString(); //$NON-NLS-1$ //$NON-NLS-2$
}
n = new TreeItem(treeItem_ProjectPrimitives8[0], SWT.NONE);
df.setType(DatType.PRIMITIVE8);
} else {
int ind = fileName.lastIndexOf(File.separator);
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length(), File.separator + "parts" + File.separator).toString(); //$NON-NLS-1$
}
n = new TreeItem(treeItem_ProjectParts[0], SWT.NONE);
df.setType(DatType.PART);
}
df.setNewName(fileName);
df.setOldName(fileName);
Project.addUnsavedFile(df);
Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
n.setText(fileName2);
n.setData(df);
if (i == 0) {
main = df;
}
}
dfsToOpen.remove(main);
resetSearch();
treeItem_Project[0].getParent().build();
treeItem_Project[0].getParent().redraw();
treeItem_Project[0].getParent().update();
{
int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights();
Editor3DWindow.getSashForm().getChildren()[1].dispose();
CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false, true, true, true);
cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]);
DatFile df = main;
Project.setFileToEdit(df);
cmp_Container.getComposite3D().setLockableDatFileReference(df);
Editor3DWindow.getSashForm().getParent().layout();
Editor3DWindow.getSashForm().setWeights(mainSashWeights);
SashForm s = cmp_Container.getComposite3D().getModifier().splitViewHorizontally();
((CompositeContainer) s.getChildren()[0]).getComposite3D().getModifier().splitViewVertically();
((CompositeContainer) s.getChildren()[1]).getComposite3D().getModifier().splitViewVertically();
}
int state = 0;
for (OpenGLRenderer renderer : getRenders()) {
Composite3D c3d = renderer.getC3D();
WidgetSelectionHelper.unselectAllChildButtons(c3d.mnu_renderMode);
if (state == 0) {
c3d.mntmNoBFC[0].setSelection(true);
c3d.getModifier().setRenderMode(0);
}
if (state == 1) {
c3d.mntmRandomColours[0].setSelection(true);
c3d.getModifier().setRenderMode(1);
}
if (state == 2) {
c3d.mntmCondlineMode[0].setSelection(true);
c3d.getModifier().setRenderMode(6);
}
if (state == 3) {
c3d.mntmWireframeMode[0].setSelection(true);
c3d.getModifier().setRenderMode(-1);
}
state++;
}
updateTree_unsavedEntries();
EditorTextWindow txt;
if (Project.getOpenTextWindows().isEmpty()) {
txt = new EditorTextWindow();
txt.run(main, false);
} else {
txt = Project.getOpenTextWindows().iterator().next();
}
for (DatFile df : dfsToOpen) {
txt.openNewDatFileTab(df, false);
}
regainFocus();
}
});
}
});
} catch (InvocationTargetException consumed) {
} catch (InterruptedException consumed) {
}
}
}
private ArrayList<String> buildFileList(String source, ArrayList<String> result, HashSet<String> files, final IProgressMonitor monitor) {
String[] lines;
lines = pattern.split(source, -1);
for (String line : lines) {
line = line.trim();
if (line.startsWith("1 ")) { //$NON-NLS-1$
final String[] data_segments = WHITESPACE.split(line.trim());
if (data_segments.length > 14) {
StringBuilder sb = new StringBuilder();
for (int s = 14; s < data_segments.length - 1; s++) {
sb.append(data_segments[s]);
sb.append(" "); //$NON-NLS-1$
}
sb.append(data_segments[data_segments.length - 1]);
String fileName = sb.toString();
fileName = fileName.toLowerCase(Locale.ENGLISH);
try {
fileName = fileName.replaceAll("\\\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (Exception e) {
// Workaround for windows OS / JVM BUG
fileName = fileName.replace("\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (files.contains(fileName)) continue;
files.add(fileName);
monitor.subTask(fileName);
String source2 = FileHelper.downloadPartFile("parts/" + fileName); //$NON-NLS-1$
if (source2 == null) source2 = FileHelper.downloadPartFile("parts/s/" + fileName); //$NON-NLS-1$
if (source2 == null) source2 = FileHelper.downloadPartFile("p/" + fileName); //$NON-NLS-1$
if (source2 != null) {
try {
fileName = fileName.replaceAll("/", File.separator); //$NON-NLS-1$
} catch (Exception ex) {
// Workaround for windows OS / JVM BUG
fileName = fileName.replace("/", File.separator); //$NON-NLS-1$
}
try {
fileName = fileName.replaceAll("\\\\", File.separator); //$NON-NLS-1$
} catch (Exception ex) {
// Workaround for windows OS / JVM BUG
fileName = fileName.replace("\\", File.separator); //$NON-NLS-1$
}
result.add(new File("project").getAbsolutePath() + File.separator + fileName); //$NON-NLS-1$
result.add(source2);
buildFileList(source2, result, files, monitor);
}
}
}
}
return result;
}
});
mntm_Edger2[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new EdgerDialog(getShell(), es).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.addEdges(es);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Rectifier[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new RectifierDialog(getShell(), rs).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.rectify(rs, true, true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Isecalc[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new IsecalcDialog(getShell(), is).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.isecalc(is);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SlicerPro[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new SlicerProDialog(getShell(), ss).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.slicerpro(ss);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Intersector[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new IntersectorDialog(getShell(), ins).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.intersector(ins, true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Lines2Pattern[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new Lines2PatternDialog(getShell()).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.lines2pattern();
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_PathTruder[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new PathTruderDialog(getShell(), ps).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.pathTruder(ps, true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SymSplitter[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new SymSplitterDialog(getShell(), sims).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.symSplitter(sims);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Unificator[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new UnificatorDialog(getShell(), us).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.unificator(us);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_RingsAndCones[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
if (new RingsAndConesDialog(getShell(), ris).open() == IDialogConstants.OK_ID) {
c3d.getLockableDatFileReference().getVertexManager().addSnapshot();
RingsAndCones.solve(Editor3DWindow.getWindow().getShell(), c3d.getLockableDatFileReference(), cmp_Primitives[0].getPrimitives(), ris, true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_TJunctionFinder[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
if (df.equals(Project.getFileToEdit()) && !df.isReadOnly()) {
if (new TJunctionDialog(getShell(), tjs).open() == IDialogConstants.OK_ID) {
VertexManager vm = df.getVertexManager();
vm.addSnapshot();
vm.fixTjunctions(tjs.getMode());
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MeshReducer[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
if (df.equals(Project.getFileToEdit()) && !df.isReadOnly()) {
VertexManager vm = df.getVertexManager();
vm.addSnapshot();
vm.meshReduce(0);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Txt2Dat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
DatFile df = c3d.getLockableDatFileReference();
if (df.isReadOnly()) {
regainFocus();
return;
}
VertexManager vm = df.getVertexManager();
vm.addSnapshot();
if (new Txt2DatDialog(getShell(), ts).open() == IDialogConstants.OK_ID && !ts.getText().trim().isEmpty()) {
java.awt.Font myFont;
if (ts.getFontData() == null) {
myFont = new java.awt.Font(org.nschmidt.ldparteditor.enums.Font.MONOSPACE.getFontData()[0].getName(), java.awt.Font.PLAIN, 32);
} else {
FontData fd = ts.getFontData();
int style = 0;
final int c2 = SWT.BOLD | SWT.ITALIC;
switch (fd.getStyle()) {
case c2:
style = java.awt.Font.BOLD | java.awt.Font.ITALIC;
break;
case SWT.BOLD:
style = java.awt.Font.BOLD;
break;
case SWT.ITALIC:
style = java.awt.Font.ITALIC;
break;
case SWT.NORMAL:
style = java.awt.Font.PLAIN;
break;
}
myFont = new java.awt.Font(fd.getName(), style, fd.getHeight());
}
GData anchorData = df.getDrawChainTail();
int lineNumber = df.getDrawPerLine_NOCLONE().getKey(anchorData);
Set<GData> triangleSet = TextTriangulator.triangulateText(myFont, ts.getText().trim(), ts.getFlatness().doubleValue(), ts.getInterpolateFlatness().doubleValue(), View.DUMMY_REFERENCE, df, ts.getFontHeight().intValue(), ts.getDeltaAngle().doubleValue());
for (GData gda3 : triangleSet) {
lineNumber++;
df.getDrawPerLine_NOCLONE().put(lineNumber, gda3);
GData gdata = gda3;
anchorData.setNext(gda3);
anchorData = gdata;
}
anchorData.setNext(null);
df.setDrawChainTail(anchorData);
vm.setModified(true, true);
regainFocus();
return;
}
}
}
regainFocus();
}
});
// MARK Options
mntm_ResetSettingsOnRestart[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_Warning);
messageBox.setMessage(I18n.E3D_DeleteConfig);
int result = messageBox.open();
if (result == SWT.CANCEL) {
regainFocus();
return;
}
WorkbenchManager.getUserSettingState().setResetOnStart(true);
regainFocus();
}
});
mntm_Options[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
OptionsDialog dialog = new OptionsDialog(getShell());
dialog.run();
// KeyTableDialog dialog = new KeyTableDialog(getShell());
// if (dialog.open() == IDialogConstants.OK_ID) {
//
// }
regainFocus();
}
});
mntm_SelectAnotherLDConfig[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fd = new FileDialog(sh, SWT.OPEN);
fd.setText(I18n.E3D_OpenLDConfig);
fd.setFilterPath(WorkbenchManager.getUserSettingState().getLdrawFolderPath());
String[] filterExt = { "*.ldr", "LDConfig.ldr", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
fd.setFilterExtensions(filterExt);
String[] filterNames = { I18n.E3D_LDrawConfigurationFile1, I18n.E3D_LDrawConfigurationFile2, I18n.E3D_AllFiles };
fd.setFilterNames(filterNames);
String selected = fd.open();
System.out.println(selected);
if (selected != null && View.loadLDConfig(selected)) {
GData.CACHE_warningsAndErrors.clear();
WorkbenchManager.getUserSettingState().setLdConfigPath(selected);
Set<DatFile> dfs = new HashSet<DatFile>();
for (OpenGLRenderer renderer : renders) {
dfs.add(renderer.getC3D().getLockableDatFileReference());
}
for (DatFile df : dfs) {
df.getVertexManager().addSnapshot();
SubfileCompiler.compile(df, false, false);
}
}
regainFocus();
}
});
mntm_SavePalette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog dlg = new FileDialog(Editor3DWindow.getWindow().getShell(), SWT.SAVE);
dlg.setFilterPath(Project.getLastVisitedPath());
dlg.setFilterExtensions(new String[]{"*_pal.dat"}); //$NON-NLS-1$
dlg.setOverwrite(true);
// Change the title bar text
dlg.setText(I18n.E3D_PaletteSave);
// Calling open() will open and run the dialog.
// It will return the selected file, or
// null if user cancels
String newPath = dlg.open();
if (newPath != null) {
final File f = new File(newPath);
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
UTF8PrintWriter r = null;
try {
r = new UTF8PrintWriter(newPath);
int x = 0;
for (GColour col : WorkbenchManager.getUserSettingState().getUserPalette()) {
r.println("1 " + col + " " + x + " 0 0 1 0 0 0 1 0 0 0 1 rect.dat"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
x += 2;
}
r.flush();
r.close();
} catch (Exception ex) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
} finally {
if (r != null) {
r.close();
}
}
}
regainFocus();
}
});
mntm_LoadPalette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog dlg = new FileDialog(Editor3DWindow.getWindow().getShell(), SWT.OPEN);
dlg.setFilterPath(Project.getLastVisitedPath());
dlg.setFilterExtensions(new String[]{"*_pal.dat"}); //$NON-NLS-1$
dlg.setOverwrite(true);
// Change the title bar text
dlg.setText(I18n.E3D_PaletteLoad);
// Calling open() will open and run the dialog.
// It will return the selected file, or
// null if user cancels
String newPath = dlg.open();
if (newPath != null) {
final File f = new File(newPath);
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
final Pattern WHITESPACE = Pattern.compile("\\s+"); //$NON-NLS-1$
ArrayList<GColour> pal = WorkbenchManager.getUserSettingState().getUserPalette();
ArrayList<GColour> newPal = new ArrayList<GColour>();
UTF8BufferedReader reader = null;
try {
reader = new UTF8BufferedReader(newPath);
String line;
while ((line = reader.readLine()) != null) {
final String[] data_segments = WHITESPACE.split(line.trim());
if (data_segments.length > 1) {
GColour c = DatParser.validateColour(data_segments[1], 0f, 0f, 0f, 1f);
if (c != null) {
newPal.add(c.clone());
}
}
}
pal.clear();
pal.addAll(newPal);
} catch (LDParsingException ex) {
} catch (FileNotFoundException ex) {
} catch (UnsupportedEncodingException ex) {
} finally {
try {
if (reader != null)
reader.close();
} catch (LDParsingException ex2) {
}
}
reloadAllColours();
}
regainFocus();
}
});
mntm_SetPaletteSize[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final List<GColour> colours = WorkbenchManager.getUserSettingState().getUserPalette();
final int[] frac = new int[]{2};
if (new ValueDialogInt(getShell(), I18n.E3D_PaletteSetSize, "") { //$NON-NLS-1$
@Override
public void initializeSpinner() {
this.spn_Value[0].setMinimum(1);
this.spn_Value[0].setMaximum(100);
this.spn_Value[0].setValue(colours.size());
}
@Override
public void applyValue() {
frac[0] = this.spn_Value[0].getValue();
}
}.open() == OK) {
final boolean reBuild = frac[0] != colours.size();
if (frac[0] > colours.size()) {
while (frac[0] > colours.size()) {
if (colours.size() < 17) {
if (colours.size() == 8) {
colours.add(View.getLDConfigColour(72));
} else {
colours.add(View.getLDConfigColour(colours.size()));
}
} else {
colours.add(View.getLDConfigColour(16));
}
}
} else {
while (frac[0] < colours.size()) {
colours.remove(colours.size() - 1);
}
}
if (reBuild) {
reloadAllColours();
}
}
regainFocus();
}
});
mntm_ResetPalette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final List<GColour> colours = WorkbenchManager.getUserSettingState().getUserPalette();
colours.clear();
while (colours.size() < 17) {
if (colours.size() == 8) {
colours.add(View.getLDConfigColour(72));
} else {
colours.add(View.getLDConfigColour(colours.size()));
}
}
reloadAllColours();
regainFocus();
}
});
mntm_UploadLogs[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String source = ""; //$NON-NLS-1$
{
UTF8BufferedReader b1 = null, b2 = null;
StringBuilder code = new StringBuilder();
File l1 = new File("error_log.txt");//$NON-NLS-1$
File l2 = new File("error_log2.txt");//$NON-NLS-1$
if (l1.exists() || l2.exists()) {
try {
if (l1.exists()) {
b1 = new UTF8BufferedReader("error_log.txt"); //$NON-NLS-1$
String line;
while ((line = b1.readLine()) != null) {
code.append(line);
code.append(StringHelper.getLineDelimiter());
}
}
if (l2.exists()) {
b2 = new UTF8BufferedReader("error_log2.txt"); //$NON-NLS-1$
String line;
while ((line = b2.readLine()) != null) {
code.append(line);
code.append(StringHelper.getLineDelimiter());
}
}
source = code.toString();
} catch (Exception e1) {
if (b1 != null) {
try {
b1.close();
} catch (Exception consumend) {}
}
if (b2 != null) {
try {
b2.close();
} catch (Exception consumend) {}
}
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setText(I18n.DIALOG_Error);
messageBox.setMessage(I18n.E3D_LogUploadUnexpectedException);
messageBox.open();
regainFocus();
return;
} finally {
if (b1 != null) {
try {
b1.close();
} catch (Exception consumend) {}
}
if (b2 != null) {
try {
b2.close();
} catch (Exception consumend) {}
}
}
} else {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_Info);
messageBox.setMessage(I18n.E3D_LogUploadNoLogFiles);
messageBox.open();
regainFocus();
return;
}
}
LogUploadDialog dialog = new LogUploadDialog(getShell(), source);
if (dialog.open() == IDialogConstants.OK_ID) {
UTF8BufferedReader b1 = null, b2 = null;
if (mntm_UploadLogs[0].getData() == null) {
mntm_UploadLogs[0].setData(0);
} else {
int uploadCount = (int) mntm_UploadLogs[0].getData();
uploadCount++;
if (uploadCount > 16) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_Warning);
messageBox.setMessage(I18n.E3D_LogUploadLimit);
messageBox.open();
regainFocus();
return;
}
mntm_UploadLogs[0].setData(uploadCount);
}
try {
Thread.sleep(2000);
String url = "http://pastebin.com/api/api_post.php"; //$NON-NLS-1$
String charset = StandardCharsets.UTF_8.name(); // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String title = "[LDPartEditor " + I18n.VERSION_Version + "]"; //$NON-NLS-1$ //$NON-NLS-2$
String devKey = "79cf77977cd2d798dd02f07d93b01ddb"; //$NON-NLS-1$
StringBuilder code = new StringBuilder();
File l1 = new File("error_log.txt");//$NON-NLS-1$
File l2 = new File("error_log2.txt");//$NON-NLS-1$
if (l1.exists() || l2.exists()) {
if (l1.exists()) {
b1 = new UTF8BufferedReader("error_log.txt"); //$NON-NLS-1$
String line;
while ((line = b1.readLine()) != null) {
code.append(line);
code.append(StringHelper.getLineDelimiter());
}
}
if (l2.exists()) {
b2 = new UTF8BufferedReader("error_log2.txt"); //$NON-NLS-1$
String line;
while ((line = b2.readLine()) != null) {
code.append(line);
code.append(StringHelper.getLineDelimiter());
}
}
String query = String.format("api_option=paste&api_user_key=%s&api_paste_private=%s&api_paste_name=%s&api_dev_key=%s&api_paste_code=%s", //$NON-NLS-1$
URLEncoder.encode("4cc892c8052bd17d805a1a2907ee8014", charset), //$NON-NLS-1$
URLEncoder.encode("0", charset),//$NON-NLS-1$
URLEncoder.encode(title, charset),
URLEncoder.encode(devKey, charset),
URLEncoder.encode(code.toString(), charset)
);
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset); //$NON-NLS-1$
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); //$NON-NLS-1$ //$NON-NLS-2$
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
BufferedReader response =new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); //$NON-NLS-1$
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_Info);
Object[] messageArguments = {response.readLine()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.E3D_LogUploadSuccess);
messageBox.setMessage(formatter.format(messageArguments));
messageBox.open();
} else {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_Info);
messageBox.setMessage(I18n.E3D_LogUploadNoLogFiles);
messageBox.open();
}
} catch (Exception e1) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setText(I18n.DIALOG_Info);
messageBox.setMessage(I18n.E3D_LogUploadUnexpectedException);
messageBox.open();
} finally {
if (b1 != null) {
try {
b1.close();
} catch (Exception consumend) {}
}
if (b2 != null) {
try {
b2.close();
} catch (Exception consumend) {}
}
}
}
regainFocus();
}
});
mntm_AntiAliasing[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setAntiAliasing(mntm_AntiAliasing[0].getSelection());
regainFocus();
}
});
// mntm_SyncWithTextEditor[0].addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent e) {
// WorkbenchManager.getUserSettingState().getSyncWithTextEditor().set(mntm_SyncWithTextEditor[0].getSelection());
// mntm_SyncLpeInline[0].setEnabled(mntm_SyncWithTextEditor[0].getSelection());
// regainFocus();
// }
// });
mntm_SyncLpeInline[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().getSyncWithLpeInline().set(mntm_SyncLpeInline[0].getSelection());
regainFocus();
}
});
// MARK Merge, split...
mntm_Flip[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.flipSelection();
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SubdivideCatmullClark[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.subdivideCatmullClark();
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SubdivideLoop[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.subdivideLoop();
regainFocus();
return;
}
}
regainFocus();
}
});
// MARK Background PNG
btn_PngFocus[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Composite3D c3d = null;
for (OpenGLRenderer renderer : renders) {
c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d = c3d.getLockableDatFileReference().getLastSelectedComposite();
if (c3d == null) {
c3d = renderer.getC3D();
}
break;
}
}
if (c3d == null) {
regainFocus();
return;
}
c3d.setClassicPerspective(false);
WidgetSelectionHelper.unselectAllChildButtons(c3d.getViewAnglesMenu());
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Matrix4f tMatrix = new Matrix4f();
tMatrix.setIdentity();
tMatrix = tMatrix.scale(new Vector3f(png.scale.x, png.scale.y, png.scale.z));
Matrix4f dMatrix = new Matrix4f();
dMatrix.setIdentity();
Matrix4f.rotate((float) (png.angleB.doubleValue() / 180.0 * Math.PI), new Vector3f(1f, 0f, 0f), dMatrix, dMatrix);
Matrix4f.rotate((float) (png.angleA.doubleValue() / 180.0 * Math.PI), new Vector3f(0f, 1f, 0f), dMatrix, dMatrix);
Matrix4f.mul(dMatrix, tMatrix, tMatrix);
Vector4f vx = Matrix4f.transform(dMatrix, new Vector4f(png.offset.x, 0f, 0f, 1f), null);
Vector4f vy = Matrix4f.transform(dMatrix, new Vector4f(0f, png.offset.y, 0f, 1f), null);
Vector4f vz = Matrix4f.transform(dMatrix, new Vector4f(0f, 0f, png.offset.z, 1f), null);
Matrix4f transMatrix = new Matrix4f();
transMatrix.setIdentity();
transMatrix.m30 = -vx.x;
transMatrix.m31 = -vx.y;
transMatrix.m32 = -vx.z;
transMatrix.m30 -= vy.x;
transMatrix.m31 -= vy.y;
transMatrix.m32 -= vy.z;
transMatrix.m30 -= vz.x;
transMatrix.m31 -= vz.y;
transMatrix.m32 -= vz.z;
Matrix4f rotMatrixD = new Matrix4f();
rotMatrixD.setIdentity();
Matrix4f.rotate((float) (png.angleB.doubleValue() / 180.0 * Math.PI), new Vector3f(1f, 0f, 0f), rotMatrixD, rotMatrixD);
Matrix4f.rotate((float) (png.angleA.doubleValue() / 180.0 * Math.PI), new Vector3f(0f, 1f, 0f), rotMatrixD, rotMatrixD);
rotMatrixD = rotMatrixD.scale(new Vector3f(-1f, 1f, -1f));
rotMatrixD.invert();
c3d.getRotation().load(rotMatrixD);
c3d.getTranslation().load(transMatrix);
c3d.getPerspectiveCalculator().calculateOriginData();
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
regainFocus();
}
});
btn_PngImage[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
FileDialog fd = new FileDialog(getShell(), SWT.SAVE);
fd.setText(I18n.E3D_OpenPngImage);
try {
File f = new File(png.texturePath);
fd.setFilterPath(f.getParent());
fd.setFileName(f.getName());
} catch (Exception ex) {
}
String[] filterExt = { "*.png", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = { I18n.E3D_PortableNetworkGraphics, I18n.E3D_AllFiles};
fd.setFilterNames(filterNames);
String texturePath = fd.open();
if (texturePath != null) {
String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, png.scale, texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, png.scale, texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
}
return;
}
}
}
});
btn_PngNext[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
if (df.equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = df.getVertexManager();
GDataPNG sp = vm.getSelectedBgPicture();
boolean noBgPictures = df.hasNoBackgroundPictures();
vm.setSelectedBgPictureIndex(vm.getSelectedBgPictureIndex() + 1);
boolean indexOutOfBounds = vm.getSelectedBgPictureIndex() >= df.getBackgroundPictureCount();
boolean noRealData = df.getDrawPerLine_NOCLONE().getKey(sp) == null;
if (noBgPictures) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
} else {
if (indexOutOfBounds) vm.setSelectedBgPictureIndex(0);
if (noRealData) {
vm.setSelectedBgPictureIndex(0);
vm.setSelectedBgPicture(df.getBackgroundPicture(0));
} else {
vm.setSelectedBgPicture(df.getBackgroundPicture(vm.getSelectedBgPictureIndex()));
}
}
updateBgPictureTab();
}
}
regainFocus();
}
});
btn_PngPrevious[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
if (df.equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = df.getVertexManager();
GDataPNG sp = vm.getSelectedBgPicture();
boolean noBgPictures = df.hasNoBackgroundPictures();
vm.setSelectedBgPictureIndex(vm.getSelectedBgPictureIndex() - 1);
boolean indexOutOfBounds = vm.getSelectedBgPictureIndex() < 0;
boolean noRealData = df.getDrawPerLine_NOCLONE().getKey(sp) == null;
if (noBgPictures) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
} else {
if (indexOutOfBounds) vm.setSelectedBgPictureIndex(df.getBackgroundPictureCount() - 1);
if (noRealData) {
vm.setSelectedBgPictureIndex(0);
vm.setSelectedBgPicture(df.getBackgroundPicture(0));
} else {
vm.setSelectedBgPicture(df.getBackgroundPicture(vm.getSelectedBgPictureIndex()));
}
}
updateBgPictureTab();
}
}
regainFocus();
}
});
spn_PngA1[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
String newText = png.getString(png.offset, spn.getValue(), png.angleB, png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, spn.getValue(), png.angleB, png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngA2[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
String newText = png.getString(png.offset, png.angleA, spn.getValue(), png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, spn.getValue(), png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngA3[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
String newText = png.getString(png.offset, png.angleA, png.angleB, spn.getValue(), png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, spn.getValue(), png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngSX[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newScale = new Vertex(spn.getValue(), png.scale.Y, png.scale.Z);
String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngSY[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newScale = new Vertex(png.scale.X, spn.getValue(), png.scale.Z);
String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngX[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newOffset = new Vertex(spn.getValue(), png.offset.Y, png.offset.Z);
String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngY[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newOffset = new Vertex(png.offset.X, spn.getValue(), png.offset.Z);
String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngZ[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newOffset = new Vertex(png.offset.X, png.offset.Y, spn.getValue());
String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
mntm_IconSize1[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(0);
regainFocus();
}
});
mntm_IconSize2[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(1);
regainFocus();
}
});
mntm_IconSize3[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(2);
regainFocus();
}
});
mntm_IconSize4[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(3);
regainFocus();
}
});
mntm_IconSize5[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(4);
regainFocus();
}
});
mntm_IconSize6[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(5);
regainFocus();
}
});
Project.createDefault();
treeItem_Project[0].setData(Project.getProjectPath());
treeItem_Official[0].setData(WorkbenchManager.getUserSettingState().getLdrawFolderPath());
treeItem_Unofficial[0].setData(WorkbenchManager.getUserSettingState().getUnofficialFolderPath());
try {
new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, false, new IRunnableWithProgress() {
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask(I18n.E3D_LoadingLibrary, IProgressMonitor.UNKNOWN);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
LibraryManager.readUnofficialParts(treeItem_UnofficialParts[0]);
LibraryManager.readUnofficialSubparts(treeItem_UnofficialSubparts[0]);
LibraryManager.readUnofficialPrimitives(treeItem_UnofficialPrimitives[0]);
LibraryManager.readUnofficialHiResPrimitives(treeItem_UnofficialPrimitives48[0]);
LibraryManager.readUnofficialLowResPrimitives(treeItem_UnofficialPrimitives8[0]);
LibraryManager.readOfficialParts(treeItem_OfficialParts[0]);
LibraryManager.readOfficialSubparts(treeItem_OfficialSubparts[0]);
LibraryManager.readOfficialPrimitives(treeItem_OfficialPrimitives[0]);
LibraryManager.readOfficialHiResPrimitives(treeItem_OfficialPrimitives48[0]);
LibraryManager.readOfficialLowResPrimitives(treeItem_OfficialPrimitives8[0]);
}
});
Thread.sleep(1500);
}
});
} catch (InvocationTargetException consumed) {
} catch (InterruptedException consumed) {
}
tabFolder_OpenDatFiles[0].getItem(0).setData(View.DUMMY_DATFILE);
tabFolder_OpenDatFiles[0].getItem(1).setData(Project.getFileToEdit());
Project.addOpenedFile(Project.getFileToEdit());
tabFolder_OpenDatFiles[0].addCTabFolder2Listener(new CTabFolder2Listener() {
@Override
public void showList(CTabFolderEvent event) {}
@Override
public void restore(CTabFolderEvent event) {}
@Override
public void minimize(CTabFolderEvent event) {}
@Override
public void maximize(CTabFolderEvent event) {
// TODO Auto-generated method stub
}
@Override
public void close(CTabFolderEvent event) {
DatFile df = null;
if (event.item != null && (df = (DatFile) event.item.getData()) != null) {
if (df.equals(View.DUMMY_DATFILE)) {
event.doit = false;
} else {
event.item.dispose();
Project.removeOpenedFile(df);
if (!closeDatfile(df)) {
Project.addOpenedFile(df);
updateTabs();
}
Editor3DWindow.getWindow().getShell().forceFocus();
regainFocus();
}
}
}
});
tabFolder_OpenDatFiles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Editor3DWindow.getNoSyncDeadlock().compareAndSet(false, true)) {
if (tabFolder_OpenDatFiles[0].getData() != null) {
Editor3DWindow.getNoSyncDeadlock().set(false);
return;
}
DatFile df = null;
if (tabFolder_OpenDatFiles[0].getSelection() != null && (df = (DatFile) tabFolder_OpenDatFiles[0].getSelection().getData()) != null) {
openFileIn3DEditor(df);
if (!df.equals(View.DUMMY_DATFILE) && WorkbenchManager.getUserSettingState().isSyncingTabs()) {
boolean fileIsOpenInTextEditor = false;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
fileIsOpenInTextEditor = true;
}
if (fileIsOpenInTextEditor) break;
}
if (fileIsOpenInTextEditor) break;
}
if (fileIsOpenInTextEditor) {
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (final CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
w.getTabFolder().setSelection(t);
((CompositeTab) t).getControl().getShell().forceActive();
if (w.isSeperateWindow()) {
w.open();
}
}
}
}
} else if (Project.getOpenTextWindows().isEmpty()) {
openDatFile(df, OpenInWhat.EDITOR_TEXT, null);
} else {
Project.getOpenTextWindows().iterator().next().openNewDatFileTab(df, false);
}
}
cleanupClosedData();
regainFocus();
}
Editor3DWindow.getNoSyncDeadlock().set(false);
}
}
});
btn_SyncTabs[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setSyncingTabs(btn_SyncTabs[0].getSelection());
}
});
txt_Search[0].setText(" "); //$NON-NLS-1$
txt_Search[0].setText(""); //$NON-NLS-1$
Project.getFileToEdit().setLastSelectedComposite(Editor3DWindow.renders.get(0).getC3D());
new EditorTextWindow().run(Project.getFileToEdit(), true);
updateBgPictureTab();
Project.getFileToEdit().addHistory();
this.open();
// Dispose all resources (never delete this!)
ResourceManager.dispose();
SWTResourceManager.dispose();
// Dispose the display (never delete this, too!)
Display.getCurrent().dispose();
}
protected void addRecentFile(String projectPath) {
final int index = recentItems.indexOf(projectPath);
if (index > -1) {
recentItems.remove(index);
} else if (recentItems.size() > 20) {
recentItems.remove(0);
}
recentItems.add(projectPath);
}
public void addRecentFile(DatFile dat) {
addRecentFile(dat.getNewName());
}
private void replaceBgPicture(GDataPNG selectedBgPicture, GDataPNG newBgPicture, DatFile linkedDatFile) {
if (linkedDatFile.getDrawPerLine_NOCLONE().getKey(selectedBgPicture) == null) return;
GData before = selectedBgPicture.getBefore();
GData next = selectedBgPicture.getNext();
int index = linkedDatFile.getDrawPerLine_NOCLONE().getKey(selectedBgPicture);
selectedBgPicture.setGoingToBeReplaced(true);
linkedDatFile.getVertexManager().remove(selectedBgPicture);
linkedDatFile.getDrawPerLine_NOCLONE().put(index, newBgPicture);
before.setNext(newBgPicture);
newBgPicture.setNext(next);
linkedDatFile.getVertexManager().setSelectedBgPicture(newBgPicture);
updateBgPictureTab();
return;
}
private void resetAddState() {
setAddingSubfiles(false);
setAddingVertices(false);
setAddingLines(false);
setAddingTriangles(false);
setAddingQuads(false);
setAddingCondlines(false);
setAddingDistance(false);
setAddingProtractor(false);
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
df.setObjVertex1(null);
df.setObjVertex2(null);
df.setObjVertex3(null);
df.setObjVertex4(null);
df.setNearestObjVertex1(null);
df.setNearestObjVertex2(null);
}
}
public void setAddState(int type) {
if (isAddingSomething()) {
resetAddState();
btn_AddVertex[0].setSelection(false);
btn_AddLine[0].setSelection(false);
btn_AddTriangle[0].setSelection(false);
btn_AddQuad[0].setSelection(false);
btn_AddCondline[0].setSelection(false);
btn_AddDistance[0].setSelection(false);
btn_AddProtractor[0].setSelection(false);
btn_AddPrimitive[0].setSelection(false);
setAddingSomething(false);
}
switch (type) {
case 0:
btn_AddComment[0].notifyListeners(SWT.Selection, new Event());
break;
case 1:
setAddingVertices(!isAddingVertices());
btn_AddVertex[0].setSelection(isAddingVertices());
setAddingSomething(isAddingVertices());
clickSingleBtn(btn_AddVertex[0]);
break;
case 2:
setAddingLines(!isAddingLines());
btn_AddLine[0].setSelection(isAddingLines());
setAddingSomething(isAddingLines());
clickSingleBtn(btn_AddLine[0]);
break;
case 3:
setAddingTriangles(!isAddingTriangles());
btn_AddTriangle[0].setSelection(isAddingTriangles());
setAddingSomething(isAddingTriangles());
clickSingleBtn(btn_AddTriangle[0]);
break;
case 4:
setAddingQuads(!isAddingQuads());
btn_AddQuad[0].setSelection(isAddingQuads());
setAddingSomething(isAddingQuads());
clickSingleBtn(btn_AddQuad[0]);
break;
case 5:
setAddingCondlines(!isAddingCondlines());
btn_AddCondline[0].setSelection(isAddingCondlines());
setAddingSomething(isAddingCondlines());
clickSingleBtn(btn_AddCondline[0]);
case 6:
setAddingDistance(!isAddingDistance());
btn_AddDistance[0].setSelection(isAddingDistance());
setAddingSomething(isAddingDistance());
clickSingleBtn(btn_AddDistance[0]);
break;
case 7:
setAddingProtractor(!isAddingProtractor());
btn_AddProtractor[0].setSelection(isAddingProtractor());
setAddingSomething(isAddingProtractor());
clickSingleBtn(btn_AddProtractor[0]);
break;
}
}
public void toggleInsertAtCursor() {
setInsertingAtCursorPosition(!isInsertingAtCursorPosition());
btn_InsertAtCursorPosition[0].setSelection(isInsertingAtCursorPosition());
clickSingleBtn(btn_InsertAtCursorPosition[0]);
}
public void setObjMode(int type) {
switch (type) {
case 0:
btn_Vertices[0].setSelection(true);
setWorkingType(ObjectMode.VERTICES);
clickSingleBtn(btn_Vertices[0]);
break;
case 1:
btn_TrisNQuads[0].setSelection(true);
setWorkingType(ObjectMode.FACES);
clickSingleBtn(btn_TrisNQuads[0]);
break;
case 2:
btn_Lines[0].setSelection(true);
setWorkingType(ObjectMode.LINES);
clickSingleBtn(btn_Lines[0]);
break;
case 3:
btn_Subfiles[0].setSelection(true);
setWorkingType(ObjectMode.SUBFILES);
clickSingleBtn(btn_Subfiles[0]);
break;
}
}
/**
* The Shell-Close-Event
*/
@Override
protected void handleShellCloseEvent() {
boolean unsavedProjectFiles = false;
Set<DatFile> unsavedFiles = new HashSet<DatFile>(Project.getUnsavedFiles());
for (DatFile df : unsavedFiles) {
final String text = df.getText();
if ((!text.equals(df.getOriginalText()) || df.isVirtual() && !text.trim().isEmpty()) && !text.equals(WorkbenchManager.getDefaultFileHeader())) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO);
messageBox.setText(I18n.DIALOG_UnsavedChangesTitle);
Object[] messageArguments = {df.getShortName()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_UnsavedChanges);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.NO) {
// Remove file from tree
updateTree_removeEntry(df);
} else if (result == SWT.YES) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
cleanupClosedData();
updateTree_unsavedEntries();
return;
}
} else {
cleanupClosedData();
updateTree_unsavedEntries();
return;
}
}
}
Set<EditorTextWindow> ow = new HashSet<EditorTextWindow>(Project.getOpenTextWindows());
for (EditorTextWindow w : ow) {
if (w.isSeperateWindow()) {
w.getShell().close();
} else {
w.closeAllTabs();
}
}
{
ArrayList<TreeItem> ta = getProjectParts().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); //$NON-NLS-1$
}
}
{
ArrayList<TreeItem> ta = getProjectSubparts().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$
}
}
{
ArrayList<TreeItem> ta = getProjectPrimitives().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$
}
}
{
ArrayList<TreeItem> ta = getProjectPrimitives48().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$
}
}
{
ArrayList<TreeItem> ta = getProjectPrimitives8().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$
}
}
final boolean ENABLE_DEFAULT_PROJECT_SAVE = !(Math.random() + 1 > 0);
if (unsavedProjectFiles && Project.isDefaultProject() && ENABLE_DEFAULT_PROJECT_SAVE) {
// Save new project here, if the project contains at least one non-empty file
boolean cancelIt = false;
boolean secondRun = false;
while (true) {
int result = IDialogConstants.CANCEL_ID;
if (secondRun) result = new NewProjectDialog(true).open();
if (result == IDialogConstants.OK_ID) {
while (new File(Project.getTempProjectPath()).isDirectory()) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.YES | SWT.CANCEL | SWT.NO);
messageBoxError.setText(I18n.PROJECT_ProjectOverwriteTitle);
messageBoxError.setMessage(I18n.PROJECT_ProjectOverwrite);
int result2 = messageBoxError.open();
if (result2 == SWT.NO) {
result = new NewProjectDialog(true).open();
} else if (result2 == SWT.YES) {
break;
} else {
cancelIt = true;
break;
}
}
if (!cancelIt) {
Project.setProjectName(Project.getTempProjectName());
Project.setProjectPath(Project.getTempProjectPath());
NLogger.debug(getClass(), "Saving new project..."); //$NON-NLS-1$
if (!Project.save()) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveProject);
}
}
break;
} else {
secondRun = true;
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO);
messageBox.setText(I18n.DIALOG_UnsavedChangesTitle);
Object[] messageArguments = {I18n.DIALOG_TheNewProject};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_UnsavedChanges);
messageBox.setMessage(formatter.format(messageArguments));
int result2 = messageBox.open();
if (result2 == SWT.CANCEL) {
cancelIt = true;
break;
} else if (result2 == SWT.NO) {
break;
}
}
}
if (cancelIt) {
cleanupClosedData();
updateTree_unsavedEntries();
return;
}
}
// NEVER DELETE THIS!
final int s = renders.size();
for (int i = 0; i < s; i++) {
try {
GLCanvas canvas = canvasList.get(i);
OpenGLRenderer renderer = renders.get(i);
if (!canvas.isCurrent()) {
canvas.setCurrent();
try {
GLContext.useContext(canvas);
} catch (LWJGLException e) {
NLogger.error(Editor3DWindow.class, e);
}
}
renderer.dispose();
} catch (SWTException swtEx) {
NLogger.error(Editor3DWindow.class, swtEx);
}
}
// All "history threads" needs to know that the main window was closed
alive.set(false);
final Editor3DWindowState winState = WorkbenchManager.getEditor3DWindowState();
// Traverse the sash forms to store the 3D configuration
final ArrayList<Composite3DState> c3dStates = new ArrayList<Composite3DState>();
Control c = Editor3DDesign.getSashForm().getChildren()[1];
if (c != null) {
if (c instanceof SashForm|| c instanceof CompositeContainer) {
// c instanceof CompositeContainer: Simple case, since its only one 3D view open -> No recursion!
saveComposite3DStates(c, c3dStates, "", "|"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
// There is no 3D window open at the moment
}
} else {
// There is no 3D window open at the moment
}
winState.setThreeDwindowConfig(c3dStates);
winState.setLeftSashWeights(((SashForm) Editor3DDesign.getSashForm().getChildren()[0]).getWeights());
winState.setLeftSashWidth(Editor3DDesign.getSashForm().getWeights());
winState.setPrimitiveZoom(cmp_Primitives[0].getZoom());
winState.setPrimitiveZoomExponent(cmp_Primitives[0].getZoom_exponent());
winState.setPrimitiveViewport(cmp_Primitives[0].getViewport2());
WorkbenchManager.getPrimitiveCache().setPrimitiveCache(CompositePrimitive.getCache());
WorkbenchManager.getPrimitiveCache().setPrimitiveFileCache(CompositePrimitive.getFileCache());
WorkbenchManager.getUserSettingState().setRecentItems(getRecentItems());
// Save the workbench
WorkbenchManager.saveWorkbench();
setReturnCode(CANCEL);
close();
}
private void saveComposite3DStates(Control c, ArrayList<Composite3DState> c3dStates, String parentPath, String path) {
Composite3DState st = new Composite3DState();
st.setParentPath(parentPath);
st.setPath(path);
if (c instanceof CompositeContainer) {
NLogger.debug(getClass(), "{0}C", path); //$NON-NLS-1$
final Composite3D c3d = ((CompositeContainer) c).getComposite3D();
st.setSash(false);
st.setScales(c3d.getParent() instanceof CompositeScale);
st.setVertical(false);
st.setWeights(null);
fillC3DState(st, c3d);
} else if (c instanceof SashForm) {
NLogger.debug(getClass(), path);
SashForm s = (SashForm) c;
st.setSash(true);
st.setVertical((s.getStyle() & SWT.VERTICAL) != 0);
st.setWeights(s.getWeights());
Control c1 = s.getChildren()[0];
Control c2 = s.getChildren()[1];
saveComposite3DStates(c1, c3dStates, path, path + "s1|"); //$NON-NLS-1$
saveComposite3DStates(c2, c3dStates, path, path + "s2|"); //$NON-NLS-1$
} else {
return;
}
c3dStates.add(st);
}
public void fillC3DState(Composite3DState st, Composite3D c3d) {
st.setPerspective(c3d.isClassicPerspective() ? c3d.getPerspectiveIndex() : Perspective.TWO_THIRDS);
st.setRenderMode(c3d.getRenderMode());
st.setShowLabel(c3d.isShowingLabels());
st.setShowAxis(c3d.isShowingAxis());
st.setShowGrid(c3d.isGridShown());
st.setShowOrigin(c3d.isOriginShown());
st.setLights(c3d.isLightOn());
st.setMeshlines(c3d.isMeshLines());
st.setSubfileMeshlines(c3d.isSubMeshLines());
st.setVertices(c3d.isShowingVertices());
st.setCondlineControlPoints(c3d.isShowingCondlineControlPoints());
st.setHiddenVertices(c3d.isShowingHiddenVertices());
st.setStudLogo(c3d.isShowingLogo());
st.setLineMode(c3d.getLineMode());
st.setAlwaysBlackLines(c3d.isBlackEdges());
st.setAnaglyph3d(c3d.isAnaglyph3d());
st.setGridScale(c3d.getGrid_scale());
st.setSyncManipulator(c3d.isSyncManipulator());
st.setSyncTranslation(c3d.isSyncTranslation());
st.setSyncZoom(c3d.isSyncZoom());
}
/**
* @return The serializable window state of the Editor3DWindow
*/
public Editor3DWindowState getEditor3DWindowState() {
return this.editor3DWindowState;
}
/**
* @param editor3DWindowState
* The serializable window state of the Editor3DWindow
*/
public void setEditor3DWindowState(Editor3DWindowState editor3DWindowState) {
this.editor3DWindowState = editor3DWindowState;
}
/**
* @return The current Editor3DWindow instance
*/
public static Editor3DWindow getWindow() {
return Editor3DWindow.window;
}
/**
* Updates the tree for new unsaved entries
*/
public void updateTree_unsavedEntries() {
ArrayList<TreeItem> categories = new ArrayList<TreeItem>();
categories.add(this.treeItem_ProjectParts[0]);
categories.add(this.treeItem_ProjectSubparts[0]);
categories.add(this.treeItem_ProjectPrimitives[0]);
categories.add(this.treeItem_ProjectPrimitives48[0]);
categories.add(this.treeItem_ProjectPrimitives8[0]);
categories.add(this.treeItem_UnofficialParts[0]);
categories.add(this.treeItem_UnofficialSubparts[0]);
categories.add(this.treeItem_UnofficialPrimitives[0]);
categories.add(this.treeItem_UnofficialPrimitives48[0]);
categories.add(this.treeItem_UnofficialPrimitives8[0]);
int counter = 0;
for (TreeItem item : categories) {
counter++;
ArrayList<TreeItem> datFileTreeItems = item.getItems();
for (TreeItem df : datFileTreeItems) {
DatFile d = (DatFile) df.getData();
StringBuilder nameSb = new StringBuilder(new File(d.getNewName()).getName());
final String d2 = d.getDescription();
if (counter < 6 && (!d.getNewName().startsWith(Project.getProjectPath()) || !d.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$
nameSb.insert(0, "(!) "); //$NON-NLS-1$
}
// MARK For Debug Only!
// DatType t = d.getType();
// if (t == DatType.PART) {
// nameSb.append(" PART"); //$NON-NLS-1$
// } else if (t == DatType.SUBPART) {
// nameSb.append(" SUBPART"); //$NON-NLS-1$
// } else if (t == DatType.PRIMITIVE) {
// nameSb.append(" PRIMITIVE"); //$NON-NLS-1$
// } else if (t == DatType.PRIMITIVE48) {
// nameSb.append(" PRIMITIVE48"); //$NON-NLS-1$
// } else if (t == DatType.PRIMITIVE8) {
// nameSb.append(" PRIMITIVE8"); //$NON-NLS-1$
// }
if (d2 != null)
nameSb.append(d2);
if (Project.getUnsavedFiles().contains(d)) {
df.setText("* " + nameSb.toString()); //$NON-NLS-1$
} else {
df.setText(nameSb.toString());
}
}
}
this.treeItem_Unsaved[0].removeAll();
Set<DatFile> unsaved = Project.getUnsavedFiles();
for (DatFile df : unsaved) {
TreeItem ti = new TreeItem(this.treeItem_Unsaved[0], SWT.NONE);
StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName());
final String d = df.getDescription();
if (d != null)
nameSb.append(d);
ti.setText(nameSb.toString());
ti.setData(df);
}
this.treeParts[0].build();
this.treeParts[0].redraw();
updateTabs();
}
/**
* Updates the tree for new unsaved entries
*/
public void updateTree_selectedDatFile(DatFile sdf) {
ArrayList<TreeItem> categories = new ArrayList<TreeItem>();
categories.add(this.treeItem_ProjectParts[0]);
categories.add(this.treeItem_ProjectSubparts[0]);
categories.add(this.treeItem_ProjectPrimitives[0]);
categories.add(this.treeItem_ProjectPrimitives48[0]);
categories.add(this.treeItem_ProjectPrimitives8[0]);
categories.add(this.treeItem_UnofficialParts[0]);
categories.add(this.treeItem_UnofficialSubparts[0]);
categories.add(this.treeItem_UnofficialPrimitives[0]);
categories.add(this.treeItem_UnofficialPrimitives48[0]);
categories.add(this.treeItem_UnofficialPrimitives8[0]);
categories.add(this.treeItem_OfficialParts[0]);
categories.add(this.treeItem_OfficialSubparts[0]);
categories.add(this.treeItem_OfficialPrimitives[0]);
categories.add(this.treeItem_OfficialPrimitives48[0]);
categories.add(this.treeItem_OfficialPrimitives8[0]);
for (TreeItem item : categories) {
ArrayList<TreeItem> datFileTreeItems = item.getItems();
for (TreeItem df : datFileTreeItems) {
DatFile d = (DatFile) df.getData();
if (d.equals(sdf)) {
item.setVisible(true);
item.getParentItem().setVisible(true);
this.treeParts[0].build();
this.treeParts[0].setSelection(df);
this.treeParts[0].redraw();
updateTabs();
return;
}
}
}
updateTabs();
}
/**
* Updates the tree for renamed entries
*/
@SuppressWarnings("unchecked")
public void updateTree_renamedEntries() {
HashMap<String, TreeItem> categories = new HashMap<String, TreeItem>();
HashMap<String, DatType> types = new HashMap<String, DatType>();
ArrayList<String> validPrefixes = new ArrayList<String>();
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS" + File.separator + "S" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialSubparts[0]);
types.put(s, DatType.SUBPART);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts" + File.separator + "s" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialSubparts[0]);
types.put(s, DatType.SUBPART);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialParts[0]);
types.put(s, DatType.PART);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s,this.treeItem_UnofficialParts[0]);
types.put(s, DatType.PART);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives48[0]);
types.put(s, DatType.PRIMITIVE48);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives48[0]);
types.put(s, DatType.PRIMITIVE48);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives8[0]);
types.put(s, DatType.PRIMITIVE8);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives8[0]);
types.put(s, DatType.PRIMITIVE8);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives[0]);
types.put(s, DatType.PRIMITIVE);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives[0]);
types.put(s, DatType.PRIMITIVE);
}
{
String s = Project.getProjectPath() + File.separator + "PARTS" + File.separator + "S" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectSubparts[0]);
types.put(s, DatType.SUBPART);
}
{
String s = Project.getProjectPath() + File.separator + "parts" + File.separator + "s" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectSubparts[0]);
types.put(s, DatType.SUBPART);
}
{
String s = Project.getProjectPath() + File.separator + "PARTS" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectParts[0]);
types.put(s, DatType.PART);
}
{
String s = Project.getProjectPath() + File.separator + "parts" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectParts[0]);
types.put(s, DatType.PART);
}
{
String s = Project.getProjectPath() + File.separator + "P" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives48[0]);
types.put(s, DatType.PRIMITIVE48);
}
{
String s = Project.getProjectPath() + File.separator + "p" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives48[0]);
types.put(s, DatType.PRIMITIVE48);
}
{
String s = Project.getProjectPath() + File.separator + "P" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives8[0]);
types.put(s, DatType.PRIMITIVE8);
}
{
String s = Project.getProjectPath() + File.separator + "p" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives8[0]);
types.put(s, DatType.PRIMITIVE8);
}
{
String s = Project.getProjectPath() + File.separator + "P" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives[0]);
types.put(s, DatType.PRIMITIVE);
}
{
String s = Project.getProjectPath() + File.separator + "p" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives[0]);
types.put(s, DatType.PRIMITIVE);
}
Collections.sort(validPrefixes, new Comp());
for (String prefix : validPrefixes) {
TreeItem item = categories.get(prefix);
ArrayList<DatFile> dats = (ArrayList<DatFile>) item.getData();
ArrayList<TreeItem> datFileTreeItems = item.getItems();
Set<TreeItem> itemsToRemove = new HashSet<TreeItem>();
for (TreeItem df : datFileTreeItems) {
DatFile d = (DatFile) df.getData();
String newName = d.getNewName();
String validPrefix = null;
for (String p2 : validPrefixes) {
if (newName.startsWith(p2)) {
validPrefix = p2;
break;
}
}
if (validPrefix != null) {
TreeItem item2 = categories.get(validPrefix);
if (!item2.equals(item)) {
itemsToRemove.add(df);
dats.remove(d);
((ArrayList<DatFile>) item2.getData()).add(d);
TreeItem nt = new TreeItem(item2, SWT.NONE);
nt.setText(df.getText());
d.setType(types.get(validPrefix));
nt.setData(d);
}
}
}
datFileTreeItems.removeAll(itemsToRemove);
}
this.treeParts[0].build();
this.treeParts[0].redraw();
updateTabs();
}
private class Comp implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if (o1.length() < o2.length()) {
return 1;
} else if (o1.length() > o2.length()) {
return -1;
} else {
return 0;
}
}
}
/**
* Removes an item from the tree,<br><br>
* If it is open in a {@linkplain Composite3D}, this composite will be linked with a dummy file
* If it is open in a {@linkplain CompositeTab}, this composite will be closed
*
*/
public void updateTree_removeEntry(DatFile e) {
ArrayList<TreeItem> categories = new ArrayList<TreeItem>();
categories.add(this.treeItem_ProjectParts[0]);
categories.add(this.treeItem_ProjectSubparts[0]);
categories.add(this.treeItem_ProjectPrimitives[0]);
categories.add(this.treeItem_ProjectPrimitives8[0]);
categories.add(this.treeItem_ProjectPrimitives48[0]);
categories.add(this.treeItem_UnofficialParts[0]);
categories.add(this.treeItem_UnofficialSubparts[0]);
categories.add(this.treeItem_UnofficialPrimitives[0]);
categories.add(this.treeItem_UnofficialPrimitives8[0]);
categories.add(this.treeItem_UnofficialPrimitives48[0]);
int counter = 0;
for (TreeItem item : categories) {
counter++;
ArrayList<TreeItem> datFileTreeItems = new ArrayList<TreeItem>(item.getItems());
for (TreeItem df : datFileTreeItems) {
DatFile d = (DatFile) df.getData();
if (e.equals(d)) {
item.getItems().remove(df);
} else {
StringBuilder nameSb = new StringBuilder(new File(d.getNewName()).getName());
final String d2 = d.getDescription();
if (counter < 6 && (!d.getNewName().startsWith(Project.getProjectPath()) || !d.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$
nameSb.insert(0, "(!) "); //$NON-NLS-1$
}
if (d2 != null)
nameSb.append(d2);
if (Project.getUnsavedFiles().contains(d)) {
df.setText("* " + nameSb.toString()); //$NON-NLS-1$
} else {
df.setText(nameSb.toString());
}
}
}
}
this.treeItem_Unsaved[0].removeAll();
Project.removeUnsavedFile(e);
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(e)) {
c3d.unlinkData();
}
}
HashSet<EditorTextWindow> windows = new HashSet<EditorTextWindow>(Project.getOpenTextWindows());
for (EditorTextWindow win : windows) {
win.closeTabWithDatfile(e);
}
Set<DatFile> unsaved = Project.getUnsavedFiles();
for (DatFile df : unsaved) {
TreeItem ti = new TreeItem(this.treeItem_Unsaved[0], SWT.NONE);
StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName());
final String d = df.getDescription();
if (d != null)
nameSb.append(d);
ti.setText(nameSb.toString());
ti.setData(df);
}
TreeItem[] folders = new TreeItem[10];
folders[0] = treeItem_ProjectParts[0];
folders[1] = treeItem_ProjectPrimitives[0];
folders[2] = treeItem_ProjectPrimitives8[0];
folders[3] = treeItem_ProjectPrimitives48[0];
folders[4] = treeItem_ProjectSubparts[0];
folders[5] = treeItem_UnofficialParts[0];
folders[6] = treeItem_UnofficialPrimitives[0];
folders[7] = treeItem_UnofficialPrimitives8[0];
folders[8] = treeItem_UnofficialPrimitives48[0];
folders[9] = treeItem_UnofficialSubparts[0];
for (TreeItem folder : folders) {
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData();
cachedReferences.remove(e);
}
this.treeParts[0].build();
this.treeParts[0].redraw();
updateTabs();
}
private synchronized void updateTabs() {
boolean isSelected = false;
if (tabFolder_OpenDatFiles[0].getData() != null) {
return;
}
tabFolder_OpenDatFiles[0].setData(true);
for (CTabItem c : tabFolder_OpenDatFiles[0].getItems()) {
c.dispose();
}
{
CTabItem tItem = new CTabItem(tabFolder_OpenDatFiles[0], SWT.NONE);
tItem.setText(I18n.E3D_NoFileSelected);
tItem.setData(View.DUMMY_DATFILE);
}
for (Iterator<DatFile> iterator = Project.getOpenedFiles().iterator(); iterator.hasNext();) {
DatFile df3 = iterator.next();
if (View.DUMMY_DATFILE.equals(df3)) {
iterator.remove();
}
}
for (DatFile df2 : Project.getOpenedFiles()) {
CTabItem tItem = new CTabItem(tabFolder_OpenDatFiles[0], SWT.NONE);
tItem.setText(df2.getShortName() + (Project.getUnsavedFiles().contains(df2) ? "*" : "")); //$NON-NLS-1$ //$NON-NLS-2$
tItem.setData(df2);
if (df2.equals(Project.getFileToEdit())) {
tabFolder_OpenDatFiles[0].setSelection(tItem);
isSelected = true;
}
}
if (!isSelected) {
tabFolder_OpenDatFiles[0].setSelection(0);
Project.setFileToEdit(View.DUMMY_DATFILE);
}
tabFolder_OpenDatFiles[0].setData(null);
tabFolder_OpenDatFiles[0].layout();
tabFolder_OpenDatFiles[0].redraw();
}
// Helper functions
private void clickBtnTest(Button btn) {
WidgetSelectionHelper.unselectAllChildButtons((ToolItem) btn.getParent());
btn.setSelection(true);
}
private void clickSingleBtn(Button btn) {
boolean state = btn.getSelection();
WidgetSelectionHelper.unselectAllChildButtons((ToolItem) btn.getParent());
btn.setSelection(state);
}
public boolean isAddingSomething() {
return addingSomething;
}
public void setAddingSomething(boolean addingSomething) {
this.addingSomething = addingSomething;
for (OpenGLRenderer renderer : renders) {
renderer.getC3D().getLockableDatFileReference().getVertexManager().clearSelection();
}
}
public boolean isAddingVertices() {
return addingVertices;
}
public void setAddingVertices(boolean addingVertices) {
this.addingVertices = addingVertices;
}
public boolean isAddingLines() {
return addingLines;
}
public void setAddingLines(boolean addingLines) {
this.addingLines = addingLines;
}
public boolean isAddingTriangles() {
return addingTriangles;
}
public void setAddingTriangles(boolean addingTriangles) {
this.addingTriangles = addingTriangles;
}
public boolean isAddingQuads() {
return addingQuads;
}
public void setAddingQuads(boolean addingQuads) {
this.addingQuads = addingQuads;
}
public boolean isAddingCondlines() {
return addingCondlines;
}
public void setAddingCondlines(boolean addingCondlines) {
this.addingCondlines = addingCondlines;
}
public boolean isAddingSubfiles() {
return addingSubfiles;
}
public void setAddingSubfiles(boolean addingSubfiles) {
this.addingSubfiles = addingSubfiles;
}
public boolean isAddingDistance() {
return addingDistance;
}
public void setAddingDistance(boolean addingDistance) {
this.addingDistance = addingDistance;
}
public boolean isAddingProtractor() {
return addingProtractor;
}
public void setAddingProtractor(boolean addingProtractor) {
this.addingProtractor = addingProtractor;
}
public void disableAddAction() {
addingSomething = false;
addingVertices = false;
addingLines = false;
addingTriangles = false;
addingQuads = false;
addingCondlines = false;
addingSubfiles = false;
addingDistance = false;
addingProtractor = false;
btn_AddVertex[0].setSelection(false);
btn_AddLine[0].setSelection(false);
btn_AddTriangle[0].setSelection(false);
btn_AddQuad[0].setSelection(false);
btn_AddCondline[0].setSelection(false);
btn_AddDistance[0].setSelection(false);
btn_AddProtractor[0].setSelection(false);
btn_AddPrimitive[0].setSelection(false);
}
public TreeItem getProjectParts() {
return treeItem_ProjectParts[0];
}
public TreeItem getProjectPrimitives() {
return treeItem_ProjectPrimitives[0];
}
public TreeItem getProjectPrimitives48() {
return treeItem_ProjectPrimitives48[0];
}
public TreeItem getProjectPrimitives8() {
return treeItem_ProjectPrimitives8[0];
}
public TreeItem getProjectSubparts() {
return treeItem_ProjectSubparts[0];
}
public TreeItem getUnofficialParts() {
return treeItem_UnofficialParts[0];
}
public TreeItem getUnofficialPrimitives() {
return treeItem_UnofficialPrimitives[0];
}
public TreeItem getUnofficialPrimitives48() {
return treeItem_UnofficialPrimitives48[0];
}
public TreeItem getUnofficialPrimitives8() {
return treeItem_UnofficialPrimitives8[0];
}
public TreeItem getUnofficialSubparts() {
return treeItem_UnofficialSubparts[0];
}
public TreeItem getOfficialParts() {
return treeItem_OfficialParts[0];
}
public TreeItem getOfficialPrimitives() {
return treeItem_OfficialPrimitives[0];
}
public TreeItem getOfficialPrimitives48() {
return treeItem_OfficialPrimitives48[0];
}
public TreeItem getOfficialPrimitives8() {
return treeItem_OfficialPrimitives8[0];
}
public TreeItem getOfficialSubparts() {
return treeItem_OfficialSubparts[0];
}
public TreeItem getUnsaved() {
return treeItem_Unsaved[0];
}
public ObjectMode getWorkingType() {
return workingType;
}
public void setWorkingType(ObjectMode workingMode) {
this.workingType = workingMode;
}
public boolean isMovingAdjacentData() {
return movingAdjacentData;
}
public void setMovingAdjacentData(boolean movingAdjacentData) {
btn_MoveAdjacentData[0].setSelection(movingAdjacentData);
this.movingAdjacentData = movingAdjacentData;
}
public WorkingMode getWorkingAction() {
return workingAction;
}
public void setWorkingAction(WorkingMode workingAction) {
this.workingAction = workingAction;
switch (workingAction) {
case COMBINED:
clickBtnTest(btn_Combined[0]);
workingAction = WorkingMode.COMBINED;
break;
case MOVE:
clickBtnTest(btn_Move[0]);
workingAction = WorkingMode.MOVE;
break;
case ROTATE:
clickBtnTest(btn_Rotate[0]);
workingAction = WorkingMode.ROTATE;
break;
case SCALE:
clickBtnTest(btn_Scale[0]);
workingAction = WorkingMode.SCALE;
break;
case SELECT:
clickBtnTest(btn_Select[0]);
workingAction = WorkingMode.SELECT;
break;
default:
break;
}
}
public ManipulatorScope getTransformationMode() {
return transformationMode;
}
public boolean hasNoTransparentSelection() {
return noTransparentSelection;
}
public void setNoTransparentSelection(boolean noTransparentSelection) {
this.noTransparentSelection = noTransparentSelection;
}
public boolean hasBfcToggle() {
return bfcToggle;
}
public void setBfcToggle(boolean bfcToggle) {
this.bfcToggle = bfcToggle;
}
public boolean isInsertingAtCursorPosition() {
return insertingAtCursorPosition;
}
public void setInsertingAtCursorPosition(boolean insertAtCursor) {
this.insertingAtCursorPosition = insertAtCursor;
}
public GColour getLastUsedColour() {
return lastUsedColour;
}
public void setLastUsedColour(GColour lastUsedColour) {
this.lastUsedColour = lastUsedColour;
}
public void setLastUsedColour2(GColour lastUsedColour) {
final int imgSize;
switch (Editor3DWindow.getIconsize()) {
case 0:
imgSize = 16;
break;
case 1:
imgSize = 24;
break;
case 2:
imgSize = 32;
break;
case 3:
imgSize = 48;
break;
case 4:
imgSize = 64;
break;
case 5:
imgSize = 72;
break;
default:
imgSize = 16;
break;
}
final GColour[] gColour2 = new GColour[] { lastUsedColour };
int num = gColour2[0].getColourNumber();
if (View.hasLDConfigColour(num)) {
gColour2[0] = View.getLDConfigColour(num);
} else {
num = -1;
}
Editor3DWindow.getWindow().setLastUsedColour(gColour2[0]);
btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]);
btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]);
final Color col = SWTResourceManager.getColor((int) (gColour2[0].getR() * 255f), (int) (gColour2[0].getG() * 255f), (int) (gColour2[0].getB() * 255f));
final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT);
final int x = size.x / 4;
final int y = size.y / 4;
final int w = size.x / 2;
final int h = size.y / 2;
btn_LastUsedColour[0].addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.setBackground(col);
e.gc.fillRectangle(x, y, w, h);
if (gColour2[0].getA() == 1f) {
e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, imgSize, imgSize, x, y, w, h); //$NON-NLS-1$
} else if (gColour2[0].getA() == 0f) {
e.gc.drawImage(ResourceManager.getImage("icon16_randomColours.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
} else {
e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, imgSize, imgSize, x, y, w, h); //$NON-NLS-1$
}
}
});
btn_LastUsedColour[0].addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Editor3DWindow.getWindow().setLastUsedColour(gColour2[0]);
int num = gColour2[0].getColourNumber();
if (!View.hasLDConfigColour(num)) {
num = -1;
}
Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA(), true);
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
if (num != -1) {
Object[] messageArguments = {num, View.getLDConfigColourName(num)};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour1);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
} else {
StringBuilder colourBuilder = new StringBuilder();
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getB())).toUpperCase());
Object[] messageArguments = {colourBuilder.toString()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour2);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
if (gColour2[0].getA() == 0f) btn_LastUsedColour[0].setToolTipText(I18n.COLOURDIALOG_RandomColours);
}
btn_LastUsedColour[0].redraw();
}
public void cleanupClosedData() {
Set<DatFile> openFiles = new HashSet<DatFile>(Project.getUnsavedFiles());
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
openFiles.add(c3d.getLockableDatFileReference());
}
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
openFiles.add(((CompositeTab) t).getState().getFileNameObj());
}
}
Set<DatFile> deadFiles = new HashSet<DatFile>(Project.getParsedFiles());
deadFiles.removeAll(openFiles);
if (!deadFiles.isEmpty()) {
GData.CACHE_viewByProjection.clear();
GData.parsedLines.clear();
GData.CACHE_parsedFilesSource.clear();
}
for (DatFile datFile : deadFiles) {
datFile.disposeData();
}
if (!deadFiles.isEmpty()) {
// TODO Debug only System.gc();
}
}
public String getSearchCriteria() {
return txt_Search[0].getText();
}
public void resetSearch() {
search(""); //$NON-NLS-1$
}
public void search(final String word) {
this.getShell().getDisplay().asyncExec(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
String criteria = ".*" + word + ".*"; //$NON-NLS-1$ //$NON-NLS-2$
TreeItem[] folders = new TreeItem[15];
folders[0] = treeItem_OfficialParts[0];
folders[1] = treeItem_OfficialPrimitives[0];
folders[2] = treeItem_OfficialPrimitives8[0];
folders[3] = treeItem_OfficialPrimitives48[0];
folders[4] = treeItem_OfficialSubparts[0];
folders[5] = treeItem_UnofficialParts[0];
folders[6] = treeItem_UnofficialPrimitives[0];
folders[7] = treeItem_UnofficialPrimitives8[0];
folders[8] = treeItem_UnofficialPrimitives48[0];
folders[9] = treeItem_UnofficialSubparts[0];
folders[10] = treeItem_ProjectParts[0];
folders[11] = treeItem_ProjectPrimitives[0];
folders[12] = treeItem_ProjectPrimitives8[0];
folders[13] = treeItem_ProjectPrimitives48[0];
folders[14] = treeItem_ProjectSubparts[0];
if (folders[0].getData() == null) {
for (TreeItem folder : folders) {
folder.setData(new ArrayList<DatFile>());
for (TreeItem part : folder.getItems()) {
((ArrayList<DatFile>) folder.getData()).add((DatFile) part.getData());
}
}
}
try {
"42".matches(criteria); //$NON-NLS-1$
} catch (Exception ex) {
criteria = ".*"; //$NON-NLS-1$
}
final Pattern pattern = Pattern.compile(criteria);
for (int i = 0; i < 15; i++) {
TreeItem folder = folders[i];
folder.removeAll();
for (DatFile part : (ArrayList<DatFile>) folder.getData()) {
StringBuilder nameSb = new StringBuilder(new File(part.getNewName()).getName());
if (i > 9 && (!part.getNewName().startsWith(Project.getProjectPath()) || !part.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$
nameSb.insert(0, "(!) "); //$NON-NLS-1$
}
final String d = part.getDescription();
if (d != null)
nameSb.append(d);
String name = nameSb.toString();
TreeItem finding = new TreeItem(folder, SWT.NONE);
// Save the path
finding.setData(part);
// Set the filename
if (Project.getUnsavedFiles().contains(part) || !part.getOldName().equals(part.getNewName())) {
// Insert asterisk if the file was
// modified
finding.setText("* " + name); //$NON-NLS-1$
} else {
finding.setText(name);
}
finding.setShown(!(d != null && d.startsWith(" - ~Moved to")) && pattern.matcher(name).matches()); //$NON-NLS-1$
}
}
folders[0].getParent().build();
folders[0].getParent().redraw();
folders[0].getParent().update();
}
});
}
public void closeAllComposite3D() {
canvasList.clear();
ArrayList<OpenGLRenderer> renders2 = new ArrayList<OpenGLRenderer>(renders);
for (OpenGLRenderer renderer : renders2) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().closeView();
}
renders.clear();
}
public TreeData getDatFileTreeData(DatFile df) {
TreeData result = new TreeData();
ArrayList<TreeItem> categories = new ArrayList<TreeItem>();
categories.add(this.treeItem_ProjectParts[0]);
categories.add(this.treeItem_ProjectSubparts[0]);
categories.add(this.treeItem_ProjectPrimitives[0]);
categories.add(this.treeItem_ProjectPrimitives48[0]);
categories.add(this.treeItem_ProjectPrimitives8[0]);
categories.add(this.treeItem_UnofficialParts[0]);
categories.add(this.treeItem_UnofficialSubparts[0]);
categories.add(this.treeItem_UnofficialPrimitives[0]);
categories.add(this.treeItem_UnofficialPrimitives48[0]);
categories.add(this.treeItem_UnofficialPrimitives8[0]);
categories.add(this.treeItem_OfficialParts[0]);
categories.add(this.treeItem_OfficialSubparts[0]);
categories.add(this.treeItem_OfficialPrimitives[0]);
categories.add(this.treeItem_OfficialPrimitives48[0]);
categories.add(this.treeItem_OfficialPrimitives8[0]);
categories.add(this.treeItem_Unsaved[0]);
for (TreeItem item : categories) {
ArrayList<TreeItem> datFileTreeItems = item.getItems();
for (TreeItem ti : datFileTreeItems) {
DatFile d = (DatFile) ti.getData();
if (df.equals(d)) {
result.setLocation(ti);
} else if (d.getShortName().equals(df.getShortName())) {
result.getLocationsWithSameShortFilenames().add(ti);
}
}
}
return result;
}
/**
* Updates the background picture tab
*/
public void updateBgPictureTab() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (png == null) {
updatingPngPictureTab = true;
txt_PngPath[0].setText("---"); //$NON-NLS-1$
txt_PngPath[0].setToolTipText("---"); //$NON-NLS-1$
spn_PngX[0].setValue(BigDecimal.ZERO);
spn_PngY[0].setValue(BigDecimal.ZERO);
spn_PngZ[0].setValue(BigDecimal.ZERO);
spn_PngA1[0].setValue(BigDecimal.ZERO);
spn_PngA2[0].setValue(BigDecimal.ZERO);
spn_PngA3[0].setValue(BigDecimal.ZERO);
spn_PngSX[0].setValue(BigDecimal.ONE);
spn_PngSY[0].setValue(BigDecimal.ONE);
txt_PngPath[0].setEnabled(false);
btn_PngFocus[0].setEnabled(false);
btn_PngImage[0].setEnabled(false);
spn_PngX[0].setEnabled(false);
spn_PngY[0].setEnabled(false);
spn_PngZ[0].setEnabled(false);
spn_PngA1[0].setEnabled(false);
spn_PngA2[0].setEnabled(false);
spn_PngA3[0].setEnabled(false);
spn_PngSX[0].setEnabled(false);
spn_PngSY[0].setEnabled(false);
spn_PngA1[0].getParent().update();
updatingPngPictureTab = false;
return;
}
updatingPngPictureTab = true;
txt_PngPath[0].setEnabled(true);
btn_PngFocus[0].setEnabled(true);
btn_PngImage[0].setEnabled(true);
spn_PngX[0].setEnabled(true);
spn_PngY[0].setEnabled(true);
spn_PngZ[0].setEnabled(true);
spn_PngA1[0].setEnabled(true);
spn_PngA2[0].setEnabled(true);
spn_PngA3[0].setEnabled(true);
spn_PngSX[0].setEnabled(true);
spn_PngSY[0].setEnabled(true);
txt_PngPath[0].setText(png.texturePath);
txt_PngPath[0].setToolTipText(png.texturePath);
spn_PngX[0].setValue(png.offset.X);
spn_PngY[0].setValue(png.offset.Y);
spn_PngZ[0].setValue(png.offset.Z);
spn_PngA1[0].setValue(png.angleA);
spn_PngA2[0].setValue(png.angleB);
spn_PngA3[0].setValue(png.angleC);
spn_PngSX[0].setValue(png.scale.X);
spn_PngSY[0].setValue(png.scale.Y);
spn_PngA1[0].getParent().update();
updatingPngPictureTab = false;
return;
}
}
}
public void unselectAddSubfile() {
resetAddState();
btn_AddPrimitive[0].setSelection(false);
setAddingSubfiles(false);
setAddingSomething(false);
}
public DatFile createNewDatFile(Shell sh, OpenInWhat where) {
FileDialog fd = new FileDialog(sh, SWT.SAVE);
fd.setText(I18n.E3D_CreateNewDat);
fd.setFilterPath(Project.getLastVisitedPath());
String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = { I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles };
fd.setFilterNames(filterNames);
while (true) {
String selected = fd.open();
System.out.println(selected);
if (selected != null) {
// Check if its already created
DatFile df = new DatFile(selected);
if (isFileNameAllocated(selected, df, true)) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
int result = messageBox.open();
if (result == SWT.CANCEL) {
break;
}
} else {
String typeSuffix = ""; //$NON-NLS-1$
String folderPrefix = ""; //$NON-NLS-1$
String subfilePrefix = ""; //$NON-NLS-1$
String path = new File(selected).getParent();
TreeItem parent = this.treeItem_ProjectParts[0];
if (path.endsWith(File.separator + "S") || path.endsWith(File.separator + "s")) { //$NON-NLS-1$ //$NON-NLS-2$
typeSuffix = "Unofficial_Subpart"; //$NON-NLS-1$
folderPrefix = "s\\"; //$NON-NLS-1$
subfilePrefix = "~"; //$NON-NLS-1$
parent = this.treeItem_ProjectSubparts[0];
} else if (path.endsWith(File.separator + "P" + File.separator + "48") || path.endsWith(File.separator + "p" + File.separator + "48")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
typeSuffix = "Unofficial_48_Primitive"; //$NON-NLS-1$
folderPrefix = "48\\"; //$NON-NLS-1$
parent = this.treeItem_ProjectPrimitives48[0];
} else if (path.endsWith(File.separator + "P" + File.separator + "8") || path.endsWith(File.separator + "p" + File.separator + "8")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
typeSuffix = "Unofficial_8_Primitive"; //$NON-NLS-1$
folderPrefix = "8\\"; //$NON-NLS-1$
parent = this.treeItem_ProjectPrimitives8[0];
} else if (path.endsWith(File.separator + "P") || path.endsWith(File.separator + "p")) { //$NON-NLS-1$ //$NON-NLS-2$
typeSuffix = "Unofficial_Primitive"; //$NON-NLS-1$
parent = this.treeItem_ProjectPrimitives[0];
}
df.addToTail(new GData0("0 " + subfilePrefix)); //$NON-NLS-1$
df.addToTail(new GData0("0 Name: " + folderPrefix + new File(selected).getName())); //$NON-NLS-1$
String ldrawName = WorkbenchManager.getUserSettingState().getLdrawUserName();
if (ldrawName == null || ldrawName.isEmpty()) {
df.addToTail(new GData0("0 Author: " + WorkbenchManager.getUserSettingState().getRealUserName())); //$NON-NLS-1$
} else {
df.addToTail(new GData0("0 Author: " + WorkbenchManager.getUserSettingState().getRealUserName() + " [" + WorkbenchManager.getUserSettingState().getLdrawUserName() + "]")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
df.addToTail(new GData0("0 !LDRAW_ORG " + typeSuffix)); //$NON-NLS-1$
String license = WorkbenchManager.getUserSettingState().getLicense();
if (license == null || license.isEmpty()) {
df.addToTail(new GData0("0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt")); //$NON-NLS-1$
} else {
df.addToTail(new GData0(license));
}
df.addToTail(new GData0("")); //$NON-NLS-1$
df.addToTail(new GDataBFC(BFC.CCW_CLIP));
df.addToTail(new GData0("")); //$NON-NLS-1$
df.addToTail(new GData0("")); //$NON-NLS-1$
df.getVertexManager().setModified(true, true);
TreeItem ti = new TreeItem(parent, SWT.NONE);
StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName());
nameSb.append(I18n.E3D_NewFile);
ti.setText(nameSb.toString());
ti.setData(df);
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData();
cachedReferences.add(df);
Project.addUnsavedFile(df);
updateTree_renamedEntries();
updateTree_unsavedEntries();
updateTree_selectedDatFile(df);
openDatFile(df, where, null);
return df;
}
} else {
break;
}
}
return null;
}
public DatFile openDatFile(Shell sh, OpenInWhat where, String filePath, boolean canRevert) {
FileDialog fd = new FileDialog(sh, SWT.OPEN);
fd.setText(I18n.E3D_OpenDatFile);
fd.setFilterPath(Project.getLastVisitedPath());
String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = {I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles};
fd.setFilterNames(filterNames);
String selected = filePath == null ? fd.open() : filePath;
System.out.println(selected);
if (selected != null) {
// Check if its already created
DatType type = DatType.PART;
DatFile df = new DatFile(selected);
DatFile original = isFileNameAllocated2(selected, df);
if (original == null) {
// Type Check and Description Parsing!!
StringBuilder titleSb = new StringBuilder();
UTF8BufferedReader reader = null;
File f = new File(selected);
try {
reader = new UTF8BufferedReader(f.getAbsolutePath());
String title = reader.readLine();
if (title != null) {
title = title.trim();
if (title.length() > 0) {
titleSb.append(" -"); //$NON-NLS-1$
titleSb.append(title.substring(1));
}
}
while (true) {
String typ = reader.readLine();
if (typ != null) {
typ = typ.trim();
if (!typ.startsWith("0")) { //$NON-NLS-1$
break;
} else {
int i1 = typ.indexOf("!LDRAW_ORG"); //$NON-NLS-1$
if (i1 > -1) {
int i2;
i2 = typ.indexOf("Subpart"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.SUBPART;
break;
}
i2 = typ.indexOf("Part"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.PART;
break;
}
i2 = typ.indexOf("48_Primitive"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.PRIMITIVE48;
break;
}
i2 = typ.indexOf("8_Primitive"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.PRIMITIVE8;
break;
}
i2 = typ.indexOf("Primitive"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.PRIMITIVE;
break;
}
}
}
} else {
break;
}
}
} catch (LDParsingException e) {
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {
} finally {
try {
if (reader != null)
reader.close();
} catch (LDParsingException e1) {
}
}
df = new DatFile(selected, titleSb.toString(), false, type);
df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath()));
} else {
// FIXME Needs code cleanup!!
df = original;
if (canRevert && Project.getUnsavedFiles().contains(df)) {
if (Editor3DWindow.getWindow().revert(df)) {
updateTree_unsavedEntries();
boolean foundTab = false;
for (EditorTextWindow win : Project.getOpenTextWindows()) {
for (CTabItem ci : win.getTabFolder().getItems()) {
CompositeTab ct = (CompositeTab) ci;
if (df.equals(ct.getState().getFileNameObj())) {
foundTab = true;
break;
}
}
if (foundTab) {
break;
}
}
if (foundTab && OpenInWhat.EDITOR_3D != where) {
return null;
}
}
}
df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath()));
if (original.isProjectFile()) {
openDatFile(df, where, null);
return df;
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectSubparts[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives48[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives8[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
type = original.getType();
df = original;
}
TreeItem ti;
switch (type) {
case PART:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE);
break;
case SUBPART:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectSubparts[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectSubparts[0], SWT.NONE);
break;
case PRIMITIVE:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectPrimitives[0], SWT.NONE);
break;
case PRIMITIVE48:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives48[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectPrimitives48[0], SWT.NONE);
break;
case PRIMITIVE8:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives8[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectPrimitives8[0], SWT.NONE);
break;
default:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE);
break;
}
StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName());
nameSb.append(I18n.E3D_NewFile);
ti.setText(nameSb.toString());
ti.setData(df);
if (canRevert && Project.getUnsavedFiles().contains(df)) {
if (Editor3DWindow.getWindow().revert(df)) {
boolean foundTab = false;
for (EditorTextWindow win : Project.getOpenTextWindows()) {
for (CTabItem ci : win.getTabFolder().getItems()) {
CompositeTab ct = (CompositeTab) ci;
if (df.equals(ct.getState().getFileNameObj())) {
foundTab = true;
break;
}
}
if (foundTab) {
break;
}
}
if (foundTab && OpenInWhat.EDITOR_3D != where) {
updateTree_unsavedEntries();
return null;
}
}
}
updateTree_unsavedEntries();
openDatFile(df, where, null);
return df;
}
return null;
}
public boolean openDatFile(DatFile df, OpenInWhat where, ApplicationWindow tWin) {
if (where == OpenInWhat.EDITOR_3D || where == OpenInWhat.EDITOR_TEXT_AND_3D) {
if (renders.isEmpty()) {
if ("%EMPTY%".equals(Editor3DWindow.getSashForm().getChildren()[1].getData())) { //$NON-NLS-1$
int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights();
Editor3DWindow.getSashForm().getChildren()[1].dispose();
CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false);
cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]);
df.parseForData(true);
Project.setFileToEdit(df);
boolean hasState = hasState(df, cmp_Container.getComposite3D());
cmp_Container.getComposite3D().setLockableDatFileReference(df);
if (!hasState) cmp_Container.getComposite3D().getModifier().zoomToFit();
Editor3DWindow.getSashForm().getParent().layout();
Editor3DWindow.getSashForm().setWeights(mainSashWeights);
}
} else {
boolean canUpdate = false;
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (!c3d.isDatFileLockedOnDisplay()) {
canUpdate = true;
break;
}
}
if (!canUpdate) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().switchLockedDat(false);
}
}
final VertexManager vm = df.getVertexManager();
if (vm.isModified()) {
df.setText(df.getText());
}
df.parseForData(true);
Project.setFileToEdit(df);
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (!c3d.isDatFileLockedOnDisplay()) {
boolean hasState = hasState(df, c3d);
c3d.setLockableDatFileReference(df);
if (!hasState) c3d.getModifier().zoomToFit();
}
}
if (!canUpdate) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().switchLockedDat(true);
}
}
}
updateTree_selectedDatFile(df);
}
if (where == OpenInWhat.EDITOR_TEXT || where == OpenInWhat.EDITOR_TEXT_AND_3D) {
for (EditorTextWindow w : Project.getOpenTextWindows()) {
final CompositeTabFolder cTabFolder = w.getTabFolder();
for (CTabItem t : cTabFolder.getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
if (Project.getUnsavedFiles().contains(df)) {
cTabFolder.setSelection(t);
((CompositeTab) t).getControl().getShell().forceActive();
} else {
CompositeTab tbtmnewItem = new CompositeTab(cTabFolder, SWT.CLOSE);
tbtmnewItem.setFolderAndWindow(cTabFolder, w);
tbtmnewItem.getState().setFileNameObj(View.DUMMY_DATFILE);
w.closeTabWithDatfile(df);
tbtmnewItem.getState().setFileNameObj(df);
cTabFolder.setSelection(tbtmnewItem);
tbtmnewItem.getControl().getShell().forceActive();
if (w.isSeperateWindow()) {
w.open();
}
Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
tbtmnewItem.parseForErrorAndHints();
tbtmnewItem.getTextComposite().redraw();
return true;
}
if (w.isSeperateWindow()) {
w.open();
}
return w == tWin;
}
}
}
if (tWin == null) {
EditorTextWindow w;
// Project.getParsedFiles().add(df); IS NECESSARY HERE
Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
if (!Project.getOpenTextWindows().isEmpty() && !(w = Project.getOpenTextWindows().iterator().next()).isSeperateWindow()) {
w.openNewDatFileTab(df, true);
} else {
new EditorTextWindow().run(df, false);
}
}
}
return false;
}
public void disableSelectionTab() {
if (Thread.currentThread() == Display.getDefault().getThread()) {
updatingSelectionTab = true;
txt_Line[0].setText(""); //$NON-NLS-1$
spn_SelectionX1[0].setEnabled(false);
spn_SelectionY1[0].setEnabled(false);
spn_SelectionZ1[0].setEnabled(false);
spn_SelectionX2[0].setEnabled(false);
spn_SelectionY2[0].setEnabled(false);
spn_SelectionZ2[0].setEnabled(false);
spn_SelectionX3[0].setEnabled(false);
spn_SelectionY3[0].setEnabled(false);
spn_SelectionZ3[0].setEnabled(false);
spn_SelectionX4[0].setEnabled(false);
spn_SelectionY4[0].setEnabled(false);
spn_SelectionZ4[0].setEnabled(false);
spn_SelectionX1[0].setValue(BigDecimal.ZERO);
spn_SelectionY1[0].setValue(BigDecimal.ZERO);
spn_SelectionZ1[0].setValue(BigDecimal.ZERO);
spn_SelectionX2[0].setValue(BigDecimal.ZERO);
spn_SelectionY2[0].setValue(BigDecimal.ZERO);
spn_SelectionZ2[0].setValue(BigDecimal.ZERO);
spn_SelectionX3[0].setValue(BigDecimal.ZERO);
spn_SelectionY3[0].setValue(BigDecimal.ZERO);
spn_SelectionZ3[0].setValue(BigDecimal.ZERO);
spn_SelectionX4[0].setValue(BigDecimal.ZERO);
spn_SelectionY4[0].setValue(BigDecimal.ZERO);
spn_SelectionZ4[0].setValue(BigDecimal.ZERO);
lbl_SelectionX1[0].setText(I18n.E3D_PositionX1);
lbl_SelectionY1[0].setText(I18n.E3D_PositionY1);
lbl_SelectionZ1[0].setText(I18n.E3D_PositionZ1);
lbl_SelectionX2[0].setText(I18n.E3D_PositionX2);
lbl_SelectionY2[0].setText(I18n.E3D_PositionY2);
lbl_SelectionZ2[0].setText(I18n.E3D_PositionZ2);
lbl_SelectionX3[0].setText(I18n.E3D_PositionX3);
lbl_SelectionY3[0].setText(I18n.E3D_PositionY3);
lbl_SelectionZ3[0].setText(I18n.E3D_PositionZ3);
lbl_SelectionX4[0].setText(I18n.E3D_PositionX4);
lbl_SelectionY4[0].setText(I18n.E3D_PositionY4);
lbl_SelectionZ4[0].setText(I18n.E3D_PositionZ4);
updatingSelectionTab = false;
} else {
NLogger.error(getClass(), new SWTException(SWT.ERROR_THREAD_INVALID_ACCESS, "A wrong thread tries to access the GUI!")); //$NON-NLS-1$
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
updatingSelectionTab = true;
txt_Line[0].setText(""); //$NON-NLS-1$
spn_SelectionX1[0].setEnabled(false);
spn_SelectionY1[0].setEnabled(false);
spn_SelectionZ1[0].setEnabled(false);
spn_SelectionX2[0].setEnabled(false);
spn_SelectionY2[0].setEnabled(false);
spn_SelectionZ2[0].setEnabled(false);
spn_SelectionX3[0].setEnabled(false);
spn_SelectionY3[0].setEnabled(false);
spn_SelectionZ3[0].setEnabled(false);
spn_SelectionX4[0].setEnabled(false);
spn_SelectionY4[0].setEnabled(false);
spn_SelectionZ4[0].setEnabled(false);
spn_SelectionX1[0].setValue(BigDecimal.ZERO);
spn_SelectionY1[0].setValue(BigDecimal.ZERO);
spn_SelectionZ1[0].setValue(BigDecimal.ZERO);
spn_SelectionX2[0].setValue(BigDecimal.ZERO);
spn_SelectionY2[0].setValue(BigDecimal.ZERO);
spn_SelectionZ2[0].setValue(BigDecimal.ZERO);
spn_SelectionX3[0].setValue(BigDecimal.ZERO);
spn_SelectionY3[0].setValue(BigDecimal.ZERO);
spn_SelectionZ3[0].setValue(BigDecimal.ZERO);
spn_SelectionX4[0].setValue(BigDecimal.ZERO);
spn_SelectionY4[0].setValue(BigDecimal.ZERO);
spn_SelectionZ4[0].setValue(BigDecimal.ZERO);
lbl_SelectionX1[0].setText(I18n.E3D_PositionX1);
lbl_SelectionY1[0].setText(I18n.E3D_PositionY1);
lbl_SelectionZ1[0].setText(I18n.E3D_PositionZ1);
lbl_SelectionX2[0].setText(I18n.E3D_PositionX2);
lbl_SelectionY2[0].setText(I18n.E3D_PositionY2);
lbl_SelectionZ2[0].setText(I18n.E3D_PositionZ2);
lbl_SelectionX3[0].setText(I18n.E3D_PositionX3);
lbl_SelectionY3[0].setText(I18n.E3D_PositionY3);
lbl_SelectionZ3[0].setText(I18n.E3D_PositionZ3);
lbl_SelectionX4[0].setText(I18n.E3D_PositionX4);
lbl_SelectionY4[0].setText(I18n.E3D_PositionY4);
lbl_SelectionZ4[0].setText(I18n.E3D_PositionZ4);
updatingSelectionTab = false;
} catch (Exception ex) {
NLogger.error(getClass(), ex);
}
}
});
}
}
public static ArrayList<OpenGLRenderer> getRenders() {
return renders;
}
public SearchWindow getSearchWindow() {
return searchWindow;
}
public void setSearchWindow(SearchWindow searchWindow) {
this.searchWindow = searchWindow;
}
public SelectorSettings loadSelectorSettings() {
sels.setColour(mntm_WithSameColour[0].getSelection());
sels.setEdgeAdjacency(mntm_WithAdjacency[0].getSelection());
sels.setEdgeStop(mntm_StopAtEdges[0].getSelection());
sels.setHidden(mntm_WithHiddenData[0].getSelection());
sels.setNoSubfiles(mntm_ExceptSubfiles[0].getSelection());
sels.setOrientation(mntm_WithSameOrientation[0].getSelection());
sels.setDistance(mntm_WithAccuracy[0].getSelection());
sels.setWholeSubfiles(mntm_WithWholeSubfiles[0].getSelection());
sels.setVertices(mntm_SVertices[0].getSelection());
sels.setLines(mntm_SLines[0].getSelection());
sels.setTriangles(mntm_STriangles[0].getSelection());
sels.setQuads(mntm_SQuads[0].getSelection());
sels.setCondlines(mntm_SCLines[0].getSelection());
return sels;
}
public boolean isFileNameAllocated(String dir, DatFile df, boolean createNew) {
TreeItem[] folders = new TreeItem[15];
folders[0] = treeItem_OfficialParts[0];
folders[1] = treeItem_OfficialPrimitives[0];
folders[2] = treeItem_OfficialPrimitives8[0];
folders[3] = treeItem_OfficialPrimitives48[0];
folders[4] = treeItem_OfficialSubparts[0];
folders[5] = treeItem_UnofficialParts[0];
folders[6] = treeItem_UnofficialPrimitives[0];
folders[7] = treeItem_UnofficialPrimitives8[0];
folders[8] = treeItem_UnofficialPrimitives48[0];
folders[9] = treeItem_UnofficialSubparts[0];
folders[10] = treeItem_ProjectParts[0];
folders[11] = treeItem_ProjectPrimitives[0];
folders[12] = treeItem_ProjectPrimitives8[0];
folders[13] = treeItem_ProjectPrimitives48[0];
folders[14] = treeItem_ProjectSubparts[0];
for (TreeItem folder : folders) {
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData();
for (DatFile d : cachedReferences) {
if (createNew || !df.equals(d)) {
if (dir.equals(d.getOldName()) || dir.equals(d.getNewName())) {
return true;
}
}
}
}
return false;
}
/**
* @return null if the file is not allocated
*/
private DatFile isFileNameAllocated2(String dir, DatFile df) {
TreeItem[] folders = new TreeItem[15];
folders[0] = treeItem_OfficialParts[0];
folders[1] = treeItem_OfficialPrimitives[0];
folders[2] = treeItem_OfficialPrimitives8[0];
folders[3] = treeItem_OfficialPrimitives48[0];
folders[4] = treeItem_OfficialSubparts[0];
folders[5] = treeItem_UnofficialParts[0];
folders[6] = treeItem_UnofficialPrimitives[0];
folders[7] = treeItem_UnofficialPrimitives8[0];
folders[8] = treeItem_UnofficialPrimitives48[0];
folders[9] = treeItem_UnofficialSubparts[0];
folders[10] = treeItem_ProjectParts[0];
folders[11] = treeItem_ProjectPrimitives[0];
folders[12] = treeItem_ProjectPrimitives8[0];
folders[13] = treeItem_ProjectPrimitives48[0];
folders[14] = treeItem_ProjectSubparts[0];
for (TreeItem folder : folders) {
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData();
for (DatFile d : cachedReferences) {
if (dir.equals(d.getOldName()) || dir.equals(d.getNewName())) {
return d;
}
}
}
return null;
}
public void updatePrimitiveLabel(Primitive p) {
if (lbl_selectedPrimitiveItem[0] == null) return;
if (p == null) {
lbl_selectedPrimitiveItem[0].setText(I18n.E3D_NoPrimitiveSelected);
} else {
lbl_selectedPrimitiveItem[0].setText(p.toString());
}
lbl_selectedPrimitiveItem[0].getParent().layout();
}
public CompositePrimitive getCompositePrimitive() {
return cmp_Primitives[0];
}
public static AtomicBoolean getAlive() {
return alive;
}
public MenuItem getMntmWithSameColour() {
return mntm_WithSameColour[0];
}
public ArrayList<String> getRecentItems() {
return recentItems;
}
private void setLineSize(Sphere sp, Sphere sp_inv, float line_width1000, float line_width, float line_width_gl, Button btn) {
GLPrimitives.SPHERE = sp;
GLPrimitives.SPHERE_INV = sp_inv;
View.lineWidth1000[0] = line_width1000;
View.lineWidth[0] = line_width;
View.lineWidthGL[0] = line_width_gl;
compileAll();
clickSingleBtn(btn);
}
public void compileAll() {
Set<DatFile> dfs = new HashSet<DatFile>();
for (OpenGLRenderer renderer : renders) {
dfs.add(renderer.getC3D().getLockableDatFileReference());
}
for (DatFile df : dfs) {
df.getVertexManager().addSnapshot();
SubfileCompiler.compile(df, false, false);
}
}
public void initAllRenderers() {
for (OpenGLRenderer renderer : renders) {
final GLCanvas canvas = renderer.getC3D().getCanvas();
if (!canvas.isCurrent()) {
canvas.setCurrent();
try {
GLContext.useContext(canvas);
} catch (LWJGLException e) {
NLogger.error(OpenGLRenderer.class, e);
}
}
renderer.init();
}
final GLCanvas canvas = getCompositePrimitive().getCanvas();
if (!canvas.isCurrent()) {
canvas.setCurrent();
try {
GLContext.useContext(canvas);
} catch (LWJGLException e) {
NLogger.error(OpenGLRenderer.class, e);
}
}
getCompositePrimitive().getOpenGL().init();
}
public void regainFocus() {
for (OpenGLRenderer r : renders) {
if (r.getC3D().getLockableDatFileReference().equals(Project.getFileToEdit())) {
r.getC3D().getCanvas().setFocus();
return;
}
}
}
private void mntm_Manipulator_0() {
if (Project.getFileToEdit() != null) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d.getManipulator().reset();
}
}
}
regainFocus();
}
private void mntm_Manipulator_XIII() {
if (Project.getFileToEdit() != null) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f t = new Vector4f(c3d.getManipulator().getPosition());
BigDecimal[] T = c3d.getManipulator().getAccuratePosition();
c3d.getManipulator().reset();
c3d.getManipulator().getPosition().set(t);
c3d.getManipulator().setAccuratePosition(T[0], T[1], T[2]);
;
}
}
}
regainFocus();
}
private void mntm_Manipulator_X() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getXaxis(), c3d.getManipulator().getXaxis());
BigDecimal[] a = c3d.getManipulator().getAccurateXaxis();
c3d.getManipulator().setAccurateXaxis(a[0].negate(), a[1].negate(), a[2].negate());
}
}
regainFocus();
}
private void mntm_Manipulator_XI() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getYaxis(), c3d.getManipulator().getYaxis());
BigDecimal[] a = c3d.getManipulator().getAccurateYaxis();
c3d.getManipulator().setAccurateYaxis(a[0].negate(), a[1].negate(), a[2].negate());
}
}
regainFocus();
}
private void mntm_Manipulator_XII() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getZaxis(), c3d.getManipulator().getZaxis());
BigDecimal[] a = c3d.getManipulator().getAccurateZaxis();
c3d.getManipulator().setAccurateZaxis(a[0].negate(), a[1].negate(), a[2].negate());
}
}
regainFocus();
}
private void mntm_Manipulator_1() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
Vector4f pos = c3d.getManipulator().getPosition();
Vector4f a1 = c3d.getManipulator().getXaxis();
Vector4f a2 = c3d.getManipulator().getYaxis();
Vector4f a3 = c3d.getManipulator().getZaxis();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d.setClassicPerspective(false);
WidgetSelectionHelper.unselectAllChildButtons(c3d.getViewAnglesMenu());
Matrix4f rot = new Matrix4f();
Matrix4f.setIdentity(rot);
rot.m00 = a1.x;
rot.m10 = a1.y;
rot.m20 = a1.z;
rot.m01 = a2.x;
rot.m11 = a2.y;
rot.m21 = a2.z;
rot.m02 = a3.x;
rot.m12 = a3.y;
rot.m22 = a3.z;
c3d.getRotation().load(rot);
Matrix4f trans = new Matrix4f();
Matrix4f.setIdentity(trans);
trans.translate(new Vector3f(-pos.x, -pos.y, -pos.z));
c3d.getTranslation().load(trans);
c3d.getPerspectiveCalculator().calculateOriginData();
}
}
regainFocus();
}
public void mntm_Manipulator_2() {
if (Project.getFileToEdit() != null) {
Vector4f avg = Project.getFileToEdit().getVertexManager().getSelectionCenter();
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d.getManipulator().getPosition().set(avg.x, avg.y, avg.z, 1f);
c3d.getManipulator().setAccuratePosition(new BigDecimal(avg.x / 1000f), new BigDecimal(avg.y / 1000f), new BigDecimal(avg.z / 1000f));
}
}
}
regainFocus();
}
private void mntm_Manipulator_3() {
if (Project.getFileToEdit() != null) {
Set<GData1> subfiles = Project.getFileToEdit().getVertexManager().getSelectedSubfiles();
if (!subfiles.isEmpty()) {
GData1 subfile = null;
for (GData1 g1 : subfiles) {
subfile = g1;
break;
}
Matrix4f m = subfile.getProductMatrix();
Matrix M = subfile.getAccurateProductMatrix();
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d.getManipulator().getPosition().set(m.m30, m.m31, m.m32, 1f);
c3d.getManipulator().setAccuratePosition(M.M30, M.M31, M.M32);
Vector3f x = new Vector3f(m.m00, m.m01, m.m02);
x.normalise();
Vector3f y = new Vector3f(m.m10, m.m11, m.m12);
y.normalise();
Vector3f z = new Vector3f(m.m20, m.m21, m.m22);
z.normalise();
c3d.getManipulator().getXaxis().set(x.x, x.y, x.z, 1f);
c3d.getManipulator().getYaxis().set(y.x, y.y, y.z, 1f);
c3d.getManipulator().getZaxis().set(z.x, z.y, z.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
}
}
regainFocus();
}
private void mntm_Manipulator_32() {
if (Project.getFileToEdit() != null) {
VertexManager vm = Project.getFileToEdit().getVertexManager();
Set<GData1> subfiles = vm.getSelectedSubfiles();
if (!subfiles.isEmpty()) {
GData1 subfile = null;
for (GData1 g1 : subfiles) {
if (vm.getLineLinkedToVertices().containsKey(g1)) {
subfile = g1;
break;
}
}
if (subfile == null) {
return;
}
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
vm.addSnapshot();
vm.backupHideShowState();
Manipulator ma = c3d.getManipulator();
vm.transformSubfile(subfile, ma.getAccurateMatrix(), true, true);
break;
}
}
}
}
regainFocus();
}
private void mntm_Manipulator_4() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
float minDist = Float.MAX_VALUE;
Vector4f next = new Vector4f(c3d.getManipulator().getPosition());
Vector4f min = new Vector4f(c3d.getManipulator().getPosition());
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Set<Vertex> vertices;
if (vm.getSelectedVertices().isEmpty()) {
vertices = vm.getVertices();
} else {
vertices = vm.getSelectedVertices();
}
Vertex minVertex = new Vertex(0f, 0f, 0f);
for (Vertex vertex : vertices) {
Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null);
float d2 = sub.lengthSquared();
if (d2 < minDist) {
minVertex = vertex;
minDist = d2;
min = vertex.toVector4f();
}
}
c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f);
c3d.getManipulator().setAccuratePosition(minVertex.X, minVertex.Y, minVertex.Z);
}
}
regainFocus();
}
private void mntm_Manipulator_5() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f min = new Vector4f(c3d.getManipulator().getPosition());
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
min = vm.getMinimalDistanceVertexToLines(new Vertex(c3d.getManipulator().getPosition())).toVector4f();
c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f);
c3d.getManipulator().setAccuratePosition(new BigDecimal(min.x / 1000f), new BigDecimal(min.y / 1000f), new BigDecimal(min.z / 1000f));
}
}
regainFocus();
}
private void mntm_Manipulator_6() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f min = new Vector4f(c3d.getManipulator().getPosition());
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
min = vm.getMinimalDistanceVertexToSurfaces(new Vertex(c3d.getManipulator().getPosition())).toVector4f();
c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f);
c3d.getManipulator().setAccuratePosition(new BigDecimal(min.x / 1000f), new BigDecimal(min.y / 1000f), new BigDecimal(min.z / 1000f));
}
}
regainFocus();
}
private void mntm_Manipulator_7() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
float minDist = Float.MAX_VALUE;
Vector4f next = new Vector4f(c3d.getManipulator().getPosition());
Vertex min = null;
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Set<Vertex> vertices;
if (vm.getSelectedVertices().isEmpty()) {
vertices = vm.getVertices();
} else {
vertices = vm.getSelectedVertices();
}
for (Vertex vertex : vertices) {
Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null);
float d2 = sub.lengthSquared();
if (d2 < minDist) {
minDist = d2;
min = vertex;
}
}
vm = c3d.getLockableDatFileReference().getVertexManager();
Vector4f n = vm.getVertexNormal(min);
float tx = 1f;
float ty = 0f;
float tz = 0f;
if (n.x <= 0f) {
tx = -1;
}
if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
tz = tx;
tx = 0f;
ty = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) {
// ty = 0f;
// tz = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
ty = tx;
tx = 0f;
tz = 0f;
} else {
regainFocus();
return;
}
Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise();
c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f);
c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f);
Vector4f zaxis = c3d.getManipulator().getZaxis();
Vector4f xaxis = c3d.getManipulator().getXaxis();
cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null);
c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
regainFocus();
}
private void mntm_Manipulator_8() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Vector4f n = vm.getMinimalDistanceEdgeNormal(new Vertex(c3d.getManipulator().getPosition()));
float tx = 1f;
float ty = 0f;
float tz = 0f;
if (n.x <= 0f) {
tx = -1;
}
if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
tz = tx;
tx = 0f;
ty = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) {
// ty = 0f;
// tz = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
ty = tx;
tx = 0f;
tz = 0f;
} else {
regainFocus();
return;
}
Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise();
c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f);
c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f);
Vector4f zaxis = c3d.getManipulator().getZaxis();
Vector4f xaxis = c3d.getManipulator().getXaxis();
cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null);
c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
regainFocus();
}
private void mntm_Manipulator_9() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Vector4f n = vm.getMinimalDistanceSurfaceNormal(new Vertex(c3d.getManipulator().getPosition()));
float tx = 1f;
float ty = 0f;
float tz = 0f;
if (n.x <= 0f) {
tx = -1;
}
if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
tz = tx;
tx = 0f;
ty = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) {
// ty = 0f;
// tz = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
ty = tx;
tx = 0f;
tz = 0f;
} else {
regainFocus();
return;
}
Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise();
c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f);
c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f);
Vector4f zaxis = c3d.getManipulator().getZaxis();
Vector4f xaxis = c3d.getManipulator().getXaxis();
cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null);
c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
regainFocus();
}
private void mntm_Manipulator_XIV() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.adjustRotationCenter(c3d, null);
}
}
regainFocus();
}
private void mntm_Manipulator_XV() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
float minDist = Float.MAX_VALUE;
Vector4f next = new Vector4f(c3d.getManipulator().getPosition());
Vertex min = null;
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Set<Vertex> vertices;
if (vm.getSelectedVertices().isEmpty()) {
vertices = vm.getVertices();
} else {
vertices = vm.getSelectedVertices();
}
for (Vertex vertex : vertices) {
Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null);
float d2 = sub.lengthSquared();
if (d2 < minDist) {
minDist = d2;
min = vertex;
}
}
vm = c3d.getLockableDatFileReference().getVertexManager();
Vector4f n = new Vector4f(min.x, min.y, min.z, 0f);
if (min.x == 0f && min.y == 0f && min.z == 0f) {
n = new Vector4f(0f, 0f, 1f, 0f);
}
n.normalise();
n.setW(1f);
float tx = 1f;
float ty = 0f;
float tz = 0f;
if (n.x <= 0f) {
tx = -1;
}
if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
tz = tx;
tx = 0f;
ty = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) {
// ty = 0f;
// tz = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
ty = tx;
tx = 0f;
tz = 0f;
} else {
regainFocus();
return;
}
Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise();
c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f);
c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f);
Vector4f zaxis = c3d.getManipulator().getZaxis();
Vector4f xaxis = c3d.getManipulator().getXaxis();
cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null);
c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
regainFocus();
}
private void mntm_Manipulator_YZ() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f temp = new Vector4f(c3d.getManipulator().getZaxis());
c3d.getManipulator().getZaxis().set(c3d.getManipulator().getYaxis());
c3d.getManipulator().getYaxis().set(temp);
BigDecimal[] a = c3d.getManipulator().getAccurateYaxis().clone();
BigDecimal[] b = c3d.getManipulator().getAccurateZaxis().clone();
c3d.getManipulator().setAccurateYaxis(b[0], b[1], b[2]);
c3d.getManipulator().setAccurateZaxis(a[0], a[1], a[2]);
}
}
regainFocus();
}
private void mntm_Manipulator_XZ() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f temp = new Vector4f(c3d.getManipulator().getXaxis());
c3d.getManipulator().getXaxis().set(c3d.getManipulator().getZaxis());
c3d.getManipulator().getZaxis().set(temp);
BigDecimal[] a = c3d.getManipulator().getAccurateXaxis().clone();
BigDecimal[] b = c3d.getManipulator().getAccurateZaxis().clone();
c3d.getManipulator().setAccurateXaxis(b[0], b[1], b[2]);
c3d.getManipulator().setAccurateZaxis(a[0], a[1], a[2]);
}
}
regainFocus();
}
private void mntm_Manipulator_XY() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f temp = new Vector4f(c3d.getManipulator().getXaxis());
c3d.getManipulator().getXaxis().set(c3d.getManipulator().getYaxis());
c3d.getManipulator().getYaxis().set(temp);
BigDecimal[] a = c3d.getManipulator().getAccurateXaxis().clone();
BigDecimal[] b = c3d.getManipulator().getAccurateYaxis().clone();
c3d.getManipulator().setAccurateXaxis(b[0], b[1], b[2]);
c3d.getManipulator().setAccurateYaxis(a[0], a[1], a[2]);
}
}
regainFocus();
}
public boolean closeDatfile(DatFile df) {
boolean result2 = false;
if (Project.getUnsavedFiles().contains(df) && !df.isReadOnly()) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO);
messageBox.setText(I18n.DIALOG_UnsavedChangesTitle);
Object[] messageArguments = {df.getShortName()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_UnsavedChanges);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.NO) {
result2 = true;
} else if (result == SWT.YES) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
result2 = true;
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
cleanupClosedData();
updateTree_unsavedEntries();
regainFocus();
return false;
}
} else {
cleanupClosedData();
updateTree_unsavedEntries();
regainFocus();
return false;
}
} else {
result2 = true;
}
updateTree_removeEntry(df);
cleanupClosedData();
regainFocus();
return result2;
}
private void openFileIn3DEditor(final DatFile df) {
if (renders.isEmpty()) {
if ("%EMPTY%".equals(Editor3DWindow.getSashForm().getChildren()[1].getData())) { //$NON-NLS-1$
int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights();
Editor3DWindow.getSashForm().getChildren()[1].dispose();
CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false);
cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]);
df.parseForData(true);
Project.setFileToEdit(df);
cmp_Container.getComposite3D().setLockableDatFileReference(df);
df.getVertexManager().addSnapshot();
Editor3DWindow.getSashForm().getParent().layout();
Editor3DWindow.getSashForm().setWeights(mainSashWeights);
}
} else {
boolean canUpdate = false;
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (!c3d.isDatFileLockedOnDisplay()) {
canUpdate = true;
break;
}
}
if (!canUpdate) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().switchLockedDat(false);
}
}
final VertexManager vm = df.getVertexManager();
if (vm.isModified()) {
df.setText(df.getText());
}
df.parseForData(true);
Project.setFileToEdit(df);
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (!c3d.isDatFileLockedOnDisplay()) {
boolean hasState = hasState(df, c3d);
c3d.setLockableDatFileReference(df);
if (!hasState) c3d.getModifier().zoomToFit();
}
}
df.getVertexManager().addSnapshot();
if (!canUpdate) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().switchLockedDat(true);
}
}
}
}
public void selectTabWithDatFile(DatFile df) {
for (CTabItem ti : tabFolder_OpenDatFiles[0].getItems()) {
if (df.equals(ti.getData())) {
tabFolder_OpenDatFiles[0].setSelection(ti);
openFileIn3DEditor(df);
cleanupClosedData();
regainFocus();
break;
}
}
}
public static AtomicBoolean getNoSyncDeadlock() {
return no_sync_deadlock;
}
public boolean revert(DatFile df) {
if (df.isReadOnly() || !Project.getUnsavedFiles().contains(df) || df.isVirtual() && df.getText().trim().isEmpty()) {
regainFocus();
return false;
}
df.getVertexManager().addSnapshot();
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox.setText(I18n.DIALOG_RevertTitle);
Object[] messageArguments = {df.getShortName(), df.getLastSavedOpened()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_Revert);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.NO) {
regainFocus();
return false;
}
boolean canUpdate = false;
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(df)) {
canUpdate = true;
break;
}
}
EditorTextWindow tmpW = null;
CTabItem tmpT = null;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
canUpdate = true;
tmpW = w;
tmpT = t;
break;
}
}
}
df.setText(df.getOriginalText());
df.setOldName(df.getNewName());
if (!df.isVirtual()) {
Project.removeUnsavedFile(df);
updateTree_unsavedEntries();
}
if (canUpdate) {
df.parseForData(true);
df.getVertexManager().setModified(true, true);
if (tmpW != null) {
tmpW.getTabFolder().setSelection(tmpT);
((CompositeTab) tmpT).getControl().getShell().forceActive();
if (tmpW.isSeperateWindow()) {
tmpW.open();
}
((CompositeTab) tmpT).getTextComposite().forceFocus();
}
}
return true;
}
public void saveState(final DatFile df, final Composite3D c3d) {
if (df == null || c3d == null) {
return;
}
{
HashMap<Composite3D, org.nschmidt.ldparteditor.composites.Composite3DViewState> states = new HashMap<>();
if (c3dStates.containsKey(df)) {
states = c3dStates.get(df);
} else {
c3dStates.put(df, states);
}
states.remove(c3d);
states.put(c3d, c3d.exportState());
}
// Cleanup old states
{
HashSet<DatFile> allFiles = new HashSet<DatFile>();
for (CTabItem ci : tabFolder_OpenDatFiles[0].getItems()) {
allFiles.add((DatFile) ci.getData());
}
HashSet<DatFile> cachedStates = new HashSet<DatFile>();
cachedStates.addAll(c3dStates.keySet());
for (DatFile d : cachedStates) {
if (!allFiles.contains(d)) {
c3dStates.remove(d);
}
}
}
}
public void loadState(final DatFile df, final Composite3D c3d) {
if (df == null || c3d == null) {
return;
}
if (c3dStates.containsKey(df)) {
HashMap<Composite3D, org.nschmidt.ldparteditor.composites.Composite3DViewState> states = c3dStates.get(df);
if (states.containsKey(c3d)) {
c3d.importState(states.get(c3d));
}
}
}
public boolean hasState(final DatFile df, final Composite3D c3d) {
return c3dStates.containsKey(df) && c3dStates.get(df).containsKey(c3d);
}
}
| src/org/nschmidt/ldparteditor/shells/editor3d/Editor3DWindow.java | /* MIT - License
Copyright (c) 2012 - this year, Nils Schmidt
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 org.nschmidt.ldparteditor.shells.editor3d;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.custom.CTabFolder2Listener;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.opengl.GLCanvas;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.SWTResourceManager;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;
import org.nschmidt.ldparteditor.composites.Composite3D;
import org.nschmidt.ldparteditor.composites.CompositeContainer;
import org.nschmidt.ldparteditor.composites.CompositeScale;
import org.nschmidt.ldparteditor.composites.ToolItem;
import org.nschmidt.ldparteditor.composites.compositetab.CompositeTab;
import org.nschmidt.ldparteditor.composites.compositetab.CompositeTabFolder;
import org.nschmidt.ldparteditor.composites.primitive.CompositePrimitive;
import org.nschmidt.ldparteditor.data.BFC;
import org.nschmidt.ldparteditor.data.DatFile;
import org.nschmidt.ldparteditor.data.DatType;
import org.nschmidt.ldparteditor.data.GColour;
import org.nschmidt.ldparteditor.data.GData;
import org.nschmidt.ldparteditor.data.GData0;
import org.nschmidt.ldparteditor.data.GData1;
import org.nschmidt.ldparteditor.data.GDataBFC;
import org.nschmidt.ldparteditor.data.GDataCSG;
import org.nschmidt.ldparteditor.data.GDataPNG;
import org.nschmidt.ldparteditor.data.GraphicalDataTools;
import org.nschmidt.ldparteditor.data.LibraryManager;
import org.nschmidt.ldparteditor.data.Matrix;
import org.nschmidt.ldparteditor.data.ParsingResult;
import org.nschmidt.ldparteditor.data.Primitive;
import org.nschmidt.ldparteditor.data.ReferenceParser;
import org.nschmidt.ldparteditor.data.RingsAndCones;
import org.nschmidt.ldparteditor.data.Vertex;
import org.nschmidt.ldparteditor.data.VertexManager;
import org.nschmidt.ldparteditor.dialogs.colour.ColourDialog;
import org.nschmidt.ldparteditor.dialogs.copy.CopyDialog;
import org.nschmidt.ldparteditor.dialogs.edger2.EdgerDialog;
import org.nschmidt.ldparteditor.dialogs.intersector.IntersectorDialog;
import org.nschmidt.ldparteditor.dialogs.isecalc.IsecalcDialog;
import org.nschmidt.ldparteditor.dialogs.lines2pattern.Lines2PatternDialog;
import org.nschmidt.ldparteditor.dialogs.logupload.LogUploadDialog;
import org.nschmidt.ldparteditor.dialogs.newproject.NewProjectDialog;
import org.nschmidt.ldparteditor.dialogs.options.OptionsDialog;
import org.nschmidt.ldparteditor.dialogs.partreview.PartReviewDialog;
import org.nschmidt.ldparteditor.dialogs.pathtruder.PathTruderDialog;
import org.nschmidt.ldparteditor.dialogs.rectifier.RectifierDialog;
import org.nschmidt.ldparteditor.dialogs.ringsandcones.RingsAndConesDialog;
import org.nschmidt.ldparteditor.dialogs.rotate.RotateDialog;
import org.nschmidt.ldparteditor.dialogs.round.RoundDialog;
import org.nschmidt.ldparteditor.dialogs.scale.ScaleDialog;
import org.nschmidt.ldparteditor.dialogs.selectvertex.VertexDialog;
import org.nschmidt.ldparteditor.dialogs.setcoordinates.CoordinatesDialog;
import org.nschmidt.ldparteditor.dialogs.slicerpro.SlicerProDialog;
import org.nschmidt.ldparteditor.dialogs.smooth.SmoothDialog;
import org.nschmidt.ldparteditor.dialogs.symsplitter.SymSplitterDialog;
import org.nschmidt.ldparteditor.dialogs.tjunction.TJunctionDialog;
import org.nschmidt.ldparteditor.dialogs.translate.TranslateDialog;
import org.nschmidt.ldparteditor.dialogs.txt2dat.Txt2DatDialog;
import org.nschmidt.ldparteditor.dialogs.unificator.UnificatorDialog;
import org.nschmidt.ldparteditor.dialogs.value.ValueDialog;
import org.nschmidt.ldparteditor.dialogs.value.ValueDialogInt;
import org.nschmidt.ldparteditor.enums.GLPrimitives;
import org.nschmidt.ldparteditor.enums.ManipulatorScope;
import org.nschmidt.ldparteditor.enums.MergeTo;
import org.nschmidt.ldparteditor.enums.MouseButton;
import org.nschmidt.ldparteditor.enums.MyLanguage;
import org.nschmidt.ldparteditor.enums.ObjectMode;
import org.nschmidt.ldparteditor.enums.OpenInWhat;
import org.nschmidt.ldparteditor.enums.Perspective;
import org.nschmidt.ldparteditor.enums.Threshold;
import org.nschmidt.ldparteditor.enums.TransformationMode;
import org.nschmidt.ldparteditor.enums.View;
import org.nschmidt.ldparteditor.enums.WorkingMode;
import org.nschmidt.ldparteditor.helpers.FileHelper;
import org.nschmidt.ldparteditor.helpers.Manipulator;
import org.nschmidt.ldparteditor.helpers.ShellHelper;
import org.nschmidt.ldparteditor.helpers.Sphere;
import org.nschmidt.ldparteditor.helpers.Version;
import org.nschmidt.ldparteditor.helpers.WidgetSelectionHelper;
import org.nschmidt.ldparteditor.helpers.composite3d.Edger2Settings;
import org.nschmidt.ldparteditor.helpers.composite3d.GuiManager;
import org.nschmidt.ldparteditor.helpers.composite3d.IntersectorSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.IsecalcSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.PathTruderSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.RectifierSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.RingsAndConesSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.SelectorSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.SlicerProSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.SymSplitterSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.TJunctionSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.TreeData;
import org.nschmidt.ldparteditor.helpers.composite3d.Txt2DatSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.UnificatorSettings;
import org.nschmidt.ldparteditor.helpers.composite3d.ViewIdleManager;
import org.nschmidt.ldparteditor.helpers.compositetext.ProjectActions;
import org.nschmidt.ldparteditor.helpers.compositetext.SubfileCompiler;
import org.nschmidt.ldparteditor.helpers.math.MathHelper;
import org.nschmidt.ldparteditor.helpers.math.Vector3d;
import org.nschmidt.ldparteditor.i18n.I18n;
import org.nschmidt.ldparteditor.logger.NLogger;
import org.nschmidt.ldparteditor.opengl.OpenGLRenderer;
import org.nschmidt.ldparteditor.project.Project;
import org.nschmidt.ldparteditor.resources.ResourceManager;
import org.nschmidt.ldparteditor.shells.editormeta.EditorMetaWindow;
import org.nschmidt.ldparteditor.shells.editortext.EditorTextWindow;
import org.nschmidt.ldparteditor.shells.searchnreplace.SearchWindow;
import org.nschmidt.ldparteditor.text.DatParser;
import org.nschmidt.ldparteditor.text.LDParsingException;
import org.nschmidt.ldparteditor.text.References;
import org.nschmidt.ldparteditor.text.StringHelper;
import org.nschmidt.ldparteditor.text.TextTriangulator;
import org.nschmidt.ldparteditor.text.UTF8BufferedReader;
import org.nschmidt.ldparteditor.text.UTF8PrintWriter;
import org.nschmidt.ldparteditor.widgets.BigDecimalSpinner;
import org.nschmidt.ldparteditor.widgets.TreeItem;
import org.nschmidt.ldparteditor.widgets.ValueChangeAdapter;
import org.nschmidt.ldparteditor.workbench.Composite3DState;
import org.nschmidt.ldparteditor.workbench.Editor3DWindowState;
import org.nschmidt.ldparteditor.workbench.WorkbenchManager;
/**
* The 3D editor window
* <p>
* Note: This class should be instantiated once, it defines all listeners and
* part of the business logic.
*
* @author nils
*
*/
public class Editor3DWindow extends Editor3DDesign {
/** The window state of this window */
private Editor3DWindowState editor3DWindowState;
/** The reference to this window */
private static Editor3DWindow window;
/** The window state of this window */
private SearchWindow searchWindow;
public static final ArrayList<GLCanvas> canvasList = new ArrayList<GLCanvas>();
public static final ArrayList<OpenGLRenderer> renders = new ArrayList<OpenGLRenderer>();
final private static AtomicBoolean alive = new AtomicBoolean(true);
final private static AtomicBoolean no_sync_deadlock = new AtomicBoolean(false);
private boolean addingSomething = false;
private boolean addingVertices = false;
private boolean addingLines = false;
private boolean addingTriangles = false;
private boolean addingQuads = false;
private boolean addingCondlines = false;
private boolean addingDistance = false;
private boolean addingProtractor = false;
private boolean addingSubfiles = false;
private boolean movingAdjacentData = false;
private boolean noTransparentSelection = false;
private boolean bfcToggle = false;
private boolean insertingAtCursorPosition = false;
private ObjectMode workingType = ObjectMode.VERTICES;
private WorkingMode workingAction = WorkingMode.SELECT;
private GColour lastUsedColour = new GColour(16, .5f, .5f, .5f, 1f);
private ManipulatorScope transformationMode = ManipulatorScope.LOCAL;
private int snapSize = 1;
private Txt2DatSettings ts = new Txt2DatSettings();
private Edger2Settings es = new Edger2Settings();
private RectifierSettings rs = new RectifierSettings();
private IsecalcSettings is = new IsecalcSettings();
private SlicerProSettings ss = new SlicerProSettings();
private IntersectorSettings ins = new IntersectorSettings();
private PathTruderSettings ps = new PathTruderSettings();
private SymSplitterSettings sims = new SymSplitterSettings();
private UnificatorSettings us = new UnificatorSettings();
private RingsAndConesSettings ris = new RingsAndConesSettings();
private SelectorSettings sels = new SelectorSettings();
private TJunctionSettings tjs = new TJunctionSettings();
private boolean updatingPngPictureTab;
private int pngPictureUpdateCounter = 0;
private final EditorMetaWindow metaWindow = new EditorMetaWindow();
private boolean updatingSelectionTab = true;
private ArrayList<String> recentItems = new ArrayList<String>();
private HashMap<DatFile, HashMap<Composite3D, org.nschmidt.ldparteditor.composites.Composite3DViewState>> c3dStates = new HashMap<>();
/**
* Create the application window.
*/
public Editor3DWindow() {
super();
final int[] i = new int[1];
final int[] j = new int[1];
final GLCanvas[] first1 = ViewIdleManager.firstCanvas;
final OpenGLRenderer[] first2 = ViewIdleManager.firstRender;
final int[] intervall = new int[] { 10 };
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
if (ViewIdleManager.pause[0].get()) {
ViewIdleManager.pause[0].set(false);
intervall[0] = 500;
} else {
final int cs = canvasList.size();
if (i[0] < cs && cs > 0) {
GLCanvas canvas;
if (!canvasList.get(i[0]).equals(first1[0])) {
canvas = first1[0];
if (canvas != null && !canvas.isDisposed()) {
first2[0].drawScene();
first1[0] = null;
first2[0] = null;
}
}
canvas = canvasList.get(i[0]);
if (!canvas.isDisposed()) {
boolean stdMode = ViewIdleManager.renderLDrawStandard[0].get();
// FIXME Needs workaround since SWT upgrade to 4.5!
if (renders.get(i[0]).getC3D().getRenderMode() != 5 || cs == 1 || stdMode) {
renders.get(i[0]).drawScene();
if (stdMode) {
j[0]++;
}
}
} else {
canvasList.remove(i[0]);
renders.remove(i[0]);
}
i[0]++;
} else {
i[0] = 0;
if (j[0] > cs) {
j[0] = 0;
ViewIdleManager.renderLDrawStandard[0].set(false);
}
}
}
Display.getCurrent().timerExec(intervall[0], this);
intervall[0] = 10;
}
});
}
/**
* Run a fresh instance of this window
*/
public void run() {
window = this;
// Load colours
WorkbenchManager.getUserSettingState().loadColours();
// Load recent files
recentItems = WorkbenchManager.getUserSettingState().getRecentItems();
if (recentItems == null) recentItems = new ArrayList<String>();
// Adjust the last visited path according to what was last opened (and exists on the harddrive)
{
final int rc = recentItems.size() - 1;
boolean foundPath = false;
for (int i = rc; i > -1; i--) {
final String path = recentItems.get(i);
final File f = new File(path);
if (f.exists()) {
if (f.isFile() && f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
foundPath = true;
break;
} else if (f.isDirectory()) {
Project.setLastVisitedPath(path);
foundPath = true;
break;
}
}
}
if (!foundPath) {
final File f = new File(WorkbenchManager.getUserSettingState().getAuthoringFolderPath());
if (f.exists() && f.isDirectory()) {
Project.setLastVisitedPath(WorkbenchManager.getUserSettingState().getAuthoringFolderPath());
}
}
}
// Load the window state data
editor3DWindowState = WorkbenchManager.getEditor3DWindowState();
WorkbenchManager.setEditor3DWindow(this);
// Closing this window causes the whole application to quit
this.setBlockOnOpen(true);
// Creating the window to get the shell
this.create();
final Shell sh = this.getShell();
sh.setText(Version.getApplicationName() + " " + Version.getVersion()); //$NON-NLS-1$
sh.setImage(ResourceManager.getImage("imgDuke2.png")); //$NON-NLS-1$
sh.setMinimumSize(640, 480);
sh.setBounds(this.editor3DWindowState.getWindowState().getSizeAndPosition());
if (this.editor3DWindowState.getWindowState().isCentered()) {
ShellHelper.centerShellOnPrimaryScreen(sh);
}
// Maximize / tab creation on text editor has to be called asynchronously
sh.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
sh.setMaximized(editor3DWindowState.getWindowState().isMaximized());
if ((WorkbenchManager.getUserSettingState().getTextWinArr() != TEXT_3D_SEPARATE)) {
for (EditorTextWindow w : Project.getOpenTextWindows()) {
if (!w.isSeperateWindow()) {
Project.getParsedFiles().add(Project.getFileToEdit());
Project.addOpenedFile(Project.getFileToEdit());
{
CompositeTab tbtmnewItem = new CompositeTab(w.getTabFolder(), SWT.CLOSE);
tbtmnewItem.setFolderAndWindow(w.getTabFolder(), Editor3DWindow.getWindow());
tbtmnewItem.getState().setFileNameObj(Project.getFileToEdit());
w.getTabFolder().setSelection(tbtmnewItem);
tbtmnewItem.parseForErrorAndHints();
tbtmnewItem.getTextComposite().redraw();
}
break;
}
}
}
}
});
// Set the snapping
Manipulator.setSnap(
WorkbenchManager.getUserSettingState().getMedium_move_snap(),
WorkbenchManager.getUserSettingState().getMedium_rotate_snap(),
WorkbenchManager.getUserSettingState().getMedium_scale_snap()
);
// MARK All final listeners will be configured here..
NLogger.writeVersion();
sh.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent consumed) {}
@Override
public void focusGained(FocusEvent e) {
regainFocus();
}
});
tabFolder_Settings[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
regainFocus();
}
});
btn_Sync[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetSearch();
int[][] stats = new int[15][3];
stats[0] = LibraryManager.syncProjectElements(treeItem_Project[0]);
stats[5] = LibraryManager.syncUnofficialParts(treeItem_UnofficialParts[0]);
stats[6] = LibraryManager.syncUnofficialSubparts(treeItem_UnofficialSubparts[0]);
stats[7] = LibraryManager.syncUnofficialPrimitives(treeItem_UnofficialPrimitives[0]);
stats[8] = LibraryManager.syncUnofficialHiResPrimitives(treeItem_UnofficialPrimitives48[0]);
stats[9] = LibraryManager.syncUnofficialLowResPrimitives(treeItem_UnofficialPrimitives8[0]);
stats[10] = LibraryManager.syncOfficialParts(treeItem_OfficialParts[0]);
stats[11] = LibraryManager.syncOfficialSubparts(treeItem_OfficialSubparts[0]);
stats[12] = LibraryManager.syncOfficialPrimitives(treeItem_OfficialPrimitives[0]);
stats[13] = LibraryManager.syncOfficialHiResPrimitives(treeItem_OfficialPrimitives48[0]);
stats[14] = LibraryManager.syncOfficialLowResPrimitives(treeItem_OfficialPrimitives8[0]);
int additions = 0;
int deletions = 0;
int conflicts = 0;
for (int[] is : stats) {
additions += is[0];
deletions += is[1];
conflicts += is[2];
}
txt_Search[0].setText(" "); //$NON-NLS-1$
txt_Search[0].setText(""); //$NON-NLS-1$
Set<DatFile> dfs = new HashSet<DatFile>();
for (OpenGLRenderer renderer : renders) {
dfs.add(renderer.getC3D().getLockableDatFileReference());
}
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj();
if (txtDat != null) {
dfs.add(txtDat);
}
}
}
for (DatFile df : dfs) {
SubfileCompiler.compile(df, false, false);
}
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
DatFile txtDat = ((CompositeTab) t).getState().getFileNameObj();
if (txtDat != null) {
((CompositeTab) t).parseForErrorAndHints();
((CompositeTab) t).getTextComposite().redraw();
((CompositeTab) t).getState().getTab().setText(((CompositeTab) t).getState().getFilenameWithStar());
}
}
}
updateTree_unsavedEntries();
treeParts[0].getTree().showItem(treeParts[0].getTree().getItem(0));
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_SyncTitle);
Object[] messageArguments = {additions, deletions, conflicts};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_Sync);
messageBox.setMessage(formatter.format(messageArguments));
messageBox.open();
regainFocus();
}
});
btn_LastOpen[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Menu lastOpenedMenu = new Menu(treeParts[0].getTree());
btn_LastOpen[0].setMenu(lastOpenedMenu);
final int size = recentItems.size() - 1;
for (int i = size; i > -1; i--) {
final String path = recentItems.get(i);
File f = new File(path);
if (f.exists() && f.canRead()) {
if (f.isFile()) {
MenuItem mntmItem = new MenuItem(lastOpenedMenu, I18n.I18N_NON_BIDIRECT());
mntmItem.setEnabled(true);
mntmItem.setText(path);
mntmItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
File f = new File(path);
if (f.exists() && f.isFile() && f.canRead()) {
DatFile df = openDatFile(getShell(), OpenInWhat.EDITOR_3D, path, false);
if (df != null && !df.equals(View.DUMMY_DATFILE) && WorkbenchManager.getUserSettingState().isSyncingTabs()) {
boolean fileIsOpenInTextEditor = false;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
fileIsOpenInTextEditor = true;
}
if (fileIsOpenInTextEditor) break;
}
if (fileIsOpenInTextEditor) break;
}
if (Project.getOpenTextWindows().isEmpty() || fileIsOpenInTextEditor) {
openDatFile(df, OpenInWhat.EDITOR_TEXT, null);
} else {
Project.getOpenTextWindows().iterator().next().openNewDatFileTab(df, true);
}
}
cleanupClosedData();
regainFocus();
}
}
});
} else if (f.isDirectory()) {
MenuItem mntmItem = new MenuItem(lastOpenedMenu, I18n.I18N_NON_BIDIRECT());
mntmItem.setEnabled(true);
Object[] messageArguments = {path};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.E3D_LastProject);
mntmItem.setText(formatter.format(messageArguments));
mntmItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
File f = new File(path);
if (f.exists() && f.isDirectory() && f.canRead() && ProjectActions.openProject(path)) {
Project.create(false);
treeItem_Project[0].setData(Project.getProjectPath());
resetSearch();
LibraryManager.readProjectPartsParent(treeItem_ProjectParts[0]);
LibraryManager.readProjectParts(treeItem_ProjectParts[0]);
LibraryManager.readProjectSubparts(treeItem_ProjectSubparts[0]);
LibraryManager.readProjectPrimitives(treeItem_ProjectPrimitives[0]);
LibraryManager.readProjectHiResPrimitives(treeItem_ProjectPrimitives48[0]);
LibraryManager.readProjectLowResPrimitives(treeItem_ProjectPrimitives8[0]);
treeItem_OfficialParts[0].setData(null);
txt_Search[0].setText(" "); //$NON-NLS-1$
txt_Search[0].setText(""); //$NON-NLS-1$
updateTree_unsavedEntries();
}
regainFocus();
}
});
}
}
}
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
lastOpenedMenu.setLocation(x, y);
lastOpenedMenu.setVisible(true);
regainFocus();
}
});
btn_New[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (ProjectActions.createNewProject(Editor3DWindow.getWindow(), false)) {
addRecentFile(Project.getProjectPath());
}
regainFocus();
}
});
btn_Open[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (ProjectActions.openProject(null)) {
addRecentFile(Project.getProjectPath());
Project.setLastVisitedPath(Project.getProjectPath());
Project.create(false);
treeItem_Project[0].setData(Project.getProjectPath());
resetSearch();
LibraryManager.readProjectPartsParent(treeItem_ProjectParts[0]);
LibraryManager.readProjectParts(treeItem_ProjectParts[0]);
LibraryManager.readProjectSubparts(treeItem_ProjectSubparts[0]);
LibraryManager.readProjectPrimitives(treeItem_ProjectPrimitives[0]);
LibraryManager.readProjectHiResPrimitives(treeItem_ProjectPrimitives48[0]);
LibraryManager.readProjectLowResPrimitives(treeItem_ProjectPrimitives8[0]);
treeItem_OfficialParts[0].setData(null);
txt_Search[0].setText(" "); //$NON-NLS-1$
txt_Search[0].setText(""); //$NON-NLS-1$
updateTree_unsavedEntries();
}
regainFocus();
}
});
btn_Save[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1) {
if (treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
Editor3DWindow.getWindow().updateTree_unsavedEntries();
}
}
} else if (treeParts[0].getSelection()[0].getData() instanceof ArrayList<?>) {
NLogger.debug(getClass(), "Saving all files from this group"); //$NON-NLS-1$
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> dfs = (ArrayList<DatFile>) treeParts[0].getSelection()[0].getData();
for (DatFile df : dfs) {
if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Project.removeUnsavedFile(df);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
Editor3DWindow.getWindow().updateTree_unsavedEntries();
}
}
}
}
} else if (treeParts[0].getSelection()[0].getData() instanceof String) {
if (treeParts[0].getSelection()[0].equals(treeItem_Project[0])) {
NLogger.debug(getClass(), "Save the project..."); //$NON-NLS-1$
if (Project.isDefaultProject()) {
if (ProjectActions.createNewProject(Editor3DWindow.getWindow(), true)) {
Project.setLastVisitedPath(Project.getProjectPath());
}
}
iterateOverItems(treeItem_ProjectParts[0]);
iterateOverItems(treeItem_ProjectSubparts[0]);
iterateOverItems(treeItem_ProjectPrimitives[0]);
iterateOverItems(treeItem_ProjectPrimitives48[0]);
iterateOverItems(treeItem_ProjectPrimitives8[0]);
} else if (treeParts[0].getSelection()[0].equals(treeItem_Unofficial[0])) {
iterateOverItems(treeItem_UnofficialParts[0]);
iterateOverItems(treeItem_UnofficialSubparts[0]);
iterateOverItems(treeItem_UnofficialPrimitives[0]);
iterateOverItems(treeItem_UnofficialPrimitives48[0]);
iterateOverItems(treeItem_UnofficialPrimitives8[0]);
}
NLogger.debug(getClass(), "Saving all files from this group to {0}", treeParts[0].getSelection()[0].getData()); //$NON-NLS-1$
}
} else {
NLogger.debug(getClass(), "Save the project..."); //$NON-NLS-1$
if (Project.isDefaultProject()) {
if (ProjectActions.createNewProject(Editor3DWindow.getWindow(), true)) {
Project.setLastVisitedPath(Project.getProjectPath());
}
}
}
regainFocus();
}
private void iterateOverItems(TreeItem ti) {
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> dfs = (ArrayList<DatFile>) ti.getData();
for (DatFile df : dfs) {
if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Project.removeUnsavedFile(df);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
Editor3DWindow.getWindow().updateTree_unsavedEntries();
}
}
}
}
}
});
btn_SaveAll[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
HashSet<DatFile> dfs = new HashSet<DatFile>(Project.getUnsavedFiles());
for (DatFile df : dfs) {
if (!df.isReadOnly()) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Project.removeUnsavedFile(df);
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
}
}
}
if (Project.isDefaultProject()) {
if (ProjectActions.createNewProject(getWindow(), true)) {
addRecentFile(Project.getProjectPath());
}
}
Editor3DWindow.getWindow().updateTree_unsavedEntries();
regainFocus();
}
});
btn_NewDat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
DatFile dat = createNewDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D);
if (dat != null) {
addRecentFile(dat);
final File f = new File(dat.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
}
regainFocus();
}
});
btn_OpenDat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean tabSync = WorkbenchManager.getUserSettingState().isSyncingTabs();
WorkbenchManager.getUserSettingState().setSyncingTabs(false);
DatFile dat = openDatFile(getShell(), OpenInWhat.EDITOR_3D, null, true);
if (dat != null) {
addRecentFile(dat);
final File f = new File(dat.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
boolean fileIsOpenInTextEditor = false;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (dat.equals(((CompositeTab) t).getState().getFileNameObj())) {
fileIsOpenInTextEditor = true;
}
if (fileIsOpenInTextEditor) break;
}
if (fileIsOpenInTextEditor) break;
}
if (Project.getOpenTextWindows().isEmpty() || fileIsOpenInTextEditor) {
openDatFile(dat, OpenInWhat.EDITOR_TEXT, null);
} else {
Project.getOpenTextWindows().iterator().next().openNewDatFileTab(dat, true);
}
Project.setFileToEdit(dat);
updateTabs();
}
WorkbenchManager.getUserSettingState().setSyncingTabs(tabSync);
regainFocus();
}
});
btn_SaveDat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().equals(View.DUMMY_DATFILE)) {
final DatFile df = Project.getFileToEdit();
Editor3DWindow.getWindow().addRecentFile(df);
if (!df.isReadOnly() && Project.getUnsavedFiles().contains(df)) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
Editor3DWindow.getWindow().updateTree_unsavedEntries();
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
}
}
}
regainFocus();
}
});
btn_SaveAsDat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().equals(View.DUMMY_DATFILE)) {
final DatFile df2 = Project.getFileToEdit();
FileDialog fd = new FileDialog(sh, SWT.SAVE);
fd.setText(I18n.E3D_SaveDatFileAs);
{
File f = new File(df2.getNewName()).getParentFile();
if (f.exists()) {
fd.setFilterPath(f.getAbsolutePath());
} else {
fd.setFilterPath(Project.getLastVisitedPath());
}
}
String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = {I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles};
fd.setFilterNames(filterNames);
while (true) {
try {
String selected = fd.open();
if (selected != null) {
if (Editor3DWindow.getWindow().isFileNameAllocated(selected, new DatFile(selected), true)) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
int result = messageBox.open();
if (result == SWT.CANCEL) {
break;
} else if (result == SWT.RETRY) {
continue;
}
}
df2.saveAs(selected);
DatFile df = Editor3DWindow.getWindow().openDatFile(getShell(), OpenInWhat.EDITOR_3D, selected, false);
if (df != null) {
Editor3DWindow.getWindow().addRecentFile(df);
final File f = new File(df.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
}
}
} catch (Exception ex) {
NLogger.error(getClass(), ex);
}
break;
}
}
regainFocus();
}
});
btn_Undo[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().undo(null);
}
regainFocus();
}
});
btn_Redo[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().redo(null);
}
regainFocus();
}
});
if (NLogger.DEBUG) {
btn_AddHistory[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().addHistory();
}
}
});
}
btn_Select[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Select[0]);
workingAction = WorkingMode.SELECT;
disableAddAction();
regainFocus();
}
});
btn_Move[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Move[0]);
workingAction = WorkingMode.MOVE;
disableAddAction();
regainFocus();
}
});
btn_Rotate[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Rotate[0]);
workingAction = WorkingMode.ROTATE;
disableAddAction();
regainFocus();
}
});
btn_Scale[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Scale[0]);
workingAction = WorkingMode.SCALE;
disableAddAction();
regainFocus();
}
});
btn_Combined[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Combined[0]);
workingAction = WorkingMode.COMBINED;
disableAddAction();
regainFocus();
}
});
btn_Local[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Local[0]);
transformationMode = ManipulatorScope.LOCAL;
regainFocus();
}
});
btn_Global[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Global[0]);
transformationMode = ManipulatorScope.GLOBAL;
regainFocus();
}
});
btn_Vertices[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Vertices[0]);
setWorkingType(ObjectMode.VERTICES);
if ((e.stateMask & SWT.ALT) == SWT.ALT && Project.getFileToEdit() != null && !Project.getFileToEdit().getVertexManager().getSelectedVertices().isEmpty()) {
final VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.getSelectedVertices().clear();
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
vm.reSelectSubFiles();
} else {
vm.getSelectedData().removeAll(vm.getSelectedSubfiles());
vm.getSelectedSubfiles().clear();
}
vm.setModified(true, true);
}
regainFocus();
}
});
btn_TrisNQuads[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_TrisNQuads[0]);
setWorkingType(ObjectMode.FACES);
if ((e.stateMask & SWT.ALT) == SWT.ALT && Project.getFileToEdit() != null && (!Project.getFileToEdit().getVertexManager().getSelectedQuads().isEmpty() || !Project.getFileToEdit().getVertexManager().getSelectedTriangles().isEmpty())) {
final VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.getSelectedData().removeAll(vm.getSelectedTriangles());
vm.getSelectedData().removeAll(vm.getSelectedQuads());
vm.getSelectedTriangles().clear();
vm.getSelectedQuads().clear();
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
vm.reSelectSubFiles();
} else {
vm.getSelectedData().removeAll(vm.getSelectedSubfiles());
vm.getSelectedSubfiles().clear();
}
vm.setModified(true, true);
}
regainFocus();
}
});
btn_Lines[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Lines[0]);
setWorkingType(ObjectMode.LINES);
if ((e.stateMask & SWT.ALT) == SWT.ALT && Project.getFileToEdit() != null && (!Project.getFileToEdit().getVertexManager().getSelectedLines().isEmpty() || !Project.getFileToEdit().getVertexManager().getSelectedCondlines().isEmpty())) {
final VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.getSelectedData().removeAll(vm.getSelectedCondlines());
vm.getSelectedData().removeAll(vm.getSelectedLines());
vm.getSelectedCondlines().clear();
vm.getSelectedLines().clear();
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
vm.reSelectSubFiles();
} else {
vm.getSelectedData().removeAll(vm.getSelectedSubfiles());
vm.getSelectedSubfiles().clear();
}
vm.setModified(true, true);
}
regainFocus();
}
});
btn_Subfiles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickBtnTest(btn_Subfiles[0]);
setWorkingType(ObjectMode.SUBFILES);
if ((e.stateMask & SWT.ALT) == SWT.ALT && (e.stateMask & SWT.CTRL) != SWT.CTRL && Project.getFileToEdit() != null && !Project.getFileToEdit().getVertexManager().getSelectedSubfiles().isEmpty()) {
final VertexManager vm = Project.getFileToEdit().getVertexManager();
final ArrayList<GData1> subfiles = new ArrayList<GData1>();
subfiles.addAll(vm.getSelectedSubfiles());
for (GData1 g1 : subfiles) {
vm.removeSubfileFromSelection(g1);
}
vm.getSelectedSubfiles().clear();
vm.setModified(true, true);
}
regainFocus();
}
});
btn_AddComment[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!metaWindow.isOpened()) {
metaWindow.run();
} else {
metaWindow.open();
}
}
});
btn_AddVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
clickSingleBtn(btn_AddVertex[0]);
setAddingVertices(btn_AddVertex[0].getSelection());
setAddingSomething(isAddingVertices());
regainFocus();
}
});
btn_AddPrimitive[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingSubfiles(btn_AddPrimitive[0].getSelection());
clickSingleBtn(btn_AddPrimitive[0]);
if (Project.getFileToEdit() != null) {
final boolean readOnly = Project.getFileToEdit().isReadOnly();
final VertexManager vm = Project.getFileToEdit().getVertexManager();
if (vm.getSelectedData().size() > 0 || vm.getSelectedVertices().size() > 0) {
final boolean insertSubfileFromSelection;
final boolean cutTheSelection;
{
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox.setText(I18n.E3D_SubfileFromSelection);
messageBox.setMessage(I18n.E3D_SubfileFromSelectionQuestion);
int result = messageBox.open();
insertSubfileFromSelection = result == SWT.YES;
if (result != SWT.NO && result != SWT.YES) {
resetAddState();
btn_AddPrimitive[0].setSelection(false);
setAddingSubfiles(false);
addingSomething = false;
regainFocus();
return;
}
}
if (insertSubfileFromSelection) {
if (!readOnly) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox.setText(I18n.E3D_SubfileFromSelection);
messageBox.setMessage(I18n.E3D_SubfileFromSelectionQuestionCut);
int result = messageBox.open();
cutTheSelection = result == SWT.YES;
if (result != SWT.NO && result != SWT.YES) {
resetAddState();
btn_AddPrimitive[0].setSelection(false);
setAddingSubfiles(false);
addingSomething = false;
regainFocus();
return;
}
} else {
cutTheSelection = false;
}
vm.addSnapshot();
vm.copy();
vm.extendClipboardContent(cutTheSelection);
FileDialog fd = new FileDialog(sh, SWT.SAVE);
fd.setText(I18n.E3D_SaveDatFileAs);
{
File f = new File(Project.getFileToEdit().getNewName()).getParentFile();
if (f.exists()) {
fd.setFilterPath(f.getAbsolutePath());
} else {
fd.setFilterPath(Project.getLastVisitedPath());
}
}
String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = {I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles};
fd.setFilterNames(filterNames);
while (true) {
try {
String selected = fd.open();
if (selected != null) {
if (Editor3DWindow.getWindow().isFileNameAllocated(selected, new DatFile(selected), true)) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
int result = messageBox.open();
if (result == SWT.CANCEL) {
break;
} else if (result == SWT.RETRY) {
continue;
}
}
SearchWindow sw = Editor3DWindow.getWindow().getSearchWindow();
if (sw != null) {
sw.setTextComposite(null);
sw.setScopeToAll();
}
boolean hasIOerror = false;
UTF8PrintWriter r = null;
try {
String typeSuffix = ""; //$NON-NLS-1$
String folderPrefix = ""; //$NON-NLS-1$
String subfilePrefix = ""; //$NON-NLS-1$
String path = new File(selected).getParent();
if (path.endsWith(File.separator + "S") || path.endsWith(File.separator + "s")) { //$NON-NLS-1$ //$NON-NLS-2$
typeSuffix = "Unofficial_Subpart"; //$NON-NLS-1$
folderPrefix = "s\\"; //$NON-NLS-1$
subfilePrefix = "~"; //$NON-NLS-1$
} else if (path.endsWith(File.separator + "P" + File.separator + "48") || path.endsWith(File.separator + "p" + File.separator + "48")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
typeSuffix = "Unofficial_48_Primitive"; //$NON-NLS-1$
folderPrefix = "48\\"; //$NON-NLS-1$
} else if (path.endsWith(File.separator + "P" + File.separator + "8") || path.endsWith(File.separator + "p" + File.separator + "8")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
typeSuffix = "Unofficial_8_Primitive"; //$NON-NLS-1$
folderPrefix = "8\\"; //$NON-NLS-1$
} else if (path.endsWith(File.separator + "P") || path.endsWith(File.separator + "p")) { //$NON-NLS-1$ //$NON-NLS-2$
typeSuffix = "Unofficial_Primitive"; //$NON-NLS-1$
}
r = new UTF8PrintWriter(selected);
r.println("0 " + subfilePrefix); //$NON-NLS-1$
r.println("0 Name: " + folderPrefix + new File(selected).getName()); //$NON-NLS-1$
String ldrawName = WorkbenchManager.getUserSettingState().getLdrawUserName();
if (ldrawName == null || ldrawName.isEmpty()) {
r.println("0 Author: " + WorkbenchManager.getUserSettingState().getRealUserName()); //$NON-NLS-1$
} else {
r.println("0 Author: " + WorkbenchManager.getUserSettingState().getRealUserName() + " [" + WorkbenchManager.getUserSettingState().getLdrawUserName() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
r.println("0 !LDRAW_ORG " + typeSuffix); //$NON-NLS-1$
String license = WorkbenchManager.getUserSettingState().getLicense();
if (license == null || license.isEmpty()) {
r.println("0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt"); //$NON-NLS-1$
} else {
r.println(license);
}
r.println(""); //$NON-NLS-1$
{
byte bfc_type = BFC.NOCERTIFY;
GData g = Project.getFileToEdit().getDrawChainStart();
while ((g = g.getNext()) != null) {
if (g.type() == 6) {
byte bfc = ((GDataBFC) g).getType();
switch (bfc) {
case BFC.CCW_CLIP:
bfc_type = bfc;
r.println("0 BFC CERTIFY CCW"); //$NON-NLS-1$
break;
case BFC.CW_CLIP:
bfc_type = bfc;
r.println("0 BFC CERTIFY CW"); //$NON-NLS-1$
break;
}
if (bfc_type != BFC.NOCERTIFY) break;
}
}
if (bfc_type == BFC.NOCERTIFY) {
r.println("0 BFC NOCERTIFY"); //$NON-NLS-1$
}
}
r.println(""); //$NON-NLS-1$
r.println(vm.getClipboardText());
r.flush();
r.close();
} catch (Exception ex) {
hasIOerror = true;
} finally {
if (r != null) {
r.close();
}
}
if (hasIOerror) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
} else {
if (cutTheSelection) {
// Insert a reference to the subfile in the old file
Set<String> alreadyParsed = new HashSet<String>();
alreadyParsed.add(Project.getFileToEdit().getShortName());
ArrayList<ParsingResult> subfileLine = DatParser
.parseLine(
"1 16 0 0 0 1 0 0 0 1 0 0 0 1 s\\" + new File(selected).getName(), -1, 0, 0.5f, 0.5f, 0.5f, 1.1f, View.DUMMY_REFERENCE, View.ID, View.ACCURATE_ID, Project.getFileToEdit(), false, alreadyParsed, false); //$NON-NLS-1$
GData1 gd1 = (GData1) subfileLine.get(0).getGraphicalData();
if (gd1 != null) {
if (isInsertingAtCursorPosition()) {
Project.getFileToEdit().insertAfterCursor(gd1);
} else {
Set<GData> sd = vm.getSelectedData();
GData g = Project.getFileToEdit().getDrawChainStart();
GData whereToInsert = null;
while ((g = g.getNext()) != null) {
if (sd.contains(g)) {
whereToInsert = g.getBefore();
break;
}
}
if (whereToInsert == null) {
whereToInsert = Project.getFileToEdit().getDrawChainTail();
}
Project.getFileToEdit().insertAfter(whereToInsert, gd1);
}
}
vm.delete(false, true);
}
DatFile df = Editor3DWindow.getWindow().openDatFile(getShell(), OpenInWhat.EDITOR_TEXT_AND_3D, selected, false);
if (df != null) {
addRecentFile(df);
final File f = new File(df.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
}
}
updateTree_unsavedEntries();
}
} catch (Exception ex) {
NLogger.error(getClass(), ex);
}
break;
}
resetAddState();
btn_AddPrimitive[0].setSelection(false);
setAddingSubfiles(false);
addingSomething = false;
regainFocus();
return;
}
}
}
setAddingSomething(isAddingSubfiles());
regainFocus();
}
});
btn_AddLine[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingLines(btn_AddLine[0].getSelection());
setAddingSomething(isAddingLines());
clickSingleBtn(btn_AddLine[0]);
regainFocus();
}
});
btn_AddTriangle[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingTriangles(btn_AddTriangle[0].getSelection());
setAddingSomething(isAddingTriangles());
clickSingleBtn(btn_AddTriangle[0]);
regainFocus();
}
});
btn_AddQuad[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingQuads(btn_AddQuad[0].getSelection());
setAddingSomething(isAddingQuads());
clickSingleBtn(btn_AddQuad[0]);
regainFocus();
}
});
btn_AddCondline[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingCondlines(btn_AddCondline[0].getSelection());
setAddingSomething(isAddingCondlines());
clickSingleBtn(btn_AddCondline[0]);
regainFocus();
}
});
btn_AddDistance[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingDistance(btn_AddDistance[0].getSelection());
setAddingSomething(isAddingDistance());
clickSingleBtn(btn_AddDistance[0]);
regainFocus();
}
});
btn_AddProtractor[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
resetAddState();
setAddingProtractor(btn_AddProtractor[0].getSelection());
setAddingSomething(isAddingProtractor());
clickSingleBtn(btn_AddProtractor[0]);
regainFocus();
}
});
btn_MoveAdjacentData[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clickSingleBtn(btn_MoveAdjacentData[0]);
setMovingAdjacentData(btn_MoveAdjacentData[0].getSelection());
GuiManager.updateStatus();
regainFocus();
}
});
btn_CompileSubfile[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
SubfileCompiler.compile(Project.getFileToEdit(), false, false);
}
regainFocus();
}
});
btn_ToggleLinesOpenGL[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (btn_ToggleLinesOpenGL[0].getSelection()) {
View.edge_threshold = 5e6f;
} else {
View.edge_threshold = 5e-6f;
}
regainFocus();
}
});
btn_lineSize1[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setLineSize(GLPrimitives.SPHERE1, GLPrimitives.SPHERE_INV1, 25f, .025f, .375f, btn_lineSize1[0]);
regainFocus();
}
});
btn_lineSize2[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setLineSize(GLPrimitives.SPHERE2, GLPrimitives.SPHERE_INV2, 50f, .050f, .75f, btn_lineSize2[0]);
regainFocus();
}
});
btn_lineSize3[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setLineSize(GLPrimitives.SPHERE3, GLPrimitives.SPHERE_INV3, 100f, .100f, 1.5f, btn_lineSize3[0]);
regainFocus();
}
});
btn_lineSize4[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setLineSize(GLPrimitives.SPHERE4, GLPrimitives.SPHERE_INV4, 200f, .200f, 3f, btn_lineSize4[0]);
regainFocus();
}
});
btn_ShowSelectionInTextEditor[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Composite3D.showSelectionInTextEditor(Project.getFileToEdit(), true);
}
regainFocus();
}
});
btn_BFCswap[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().backupHideShowState();
Project.getFileToEdit().getVertexManager().windingChangeSelection(true);
}
regainFocus();
}
});
btn_RoundSelection[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
if ((e.stateMask & SWT.CTRL) == SWT.CTRL) {
if (new RoundDialog(getShell()).open() == IDialogConstants.CANCEL_ID) return;
}
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().backupHideShowState();
Project.getFileToEdit().getVertexManager()
.roundSelection(WorkbenchManager.getUserSettingState().getCoordsPrecision(), WorkbenchManager.getUserSettingState().getTransMatrixPrecision(), isMovingAdjacentData(), true);
}
regainFocus();
}
});
btn_Pipette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.addSnapshot();
final GColour gColour2;
{
GColour gColour3 = vm.getRandomSelectedColour(lastUsedColour);
if (gColour3.getColourNumber() == 16) {
gColour2 = View.getLDConfigColour(16);
} else {
gColour2 = gColour3;
}
lastUsedColour = gColour2;
}
setLastUsedColour(gColour2);
btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]);
btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]);
final Color col = SWTResourceManager.getColor((int) (gColour2.getR() * 255f), (int) (gColour2.getG() * 255f), (int) (gColour2.getB() * 255f));
final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT);
final int x = Math.round(size.x / 5f);
final int y = Math.round(size.y / 5f);
final int w = Math.round(size.x * (3f / 5f));
final int h = Math.round(size.y * (3f / 5f));
int num = gColour2.getColourNumber();
btn_LastUsedColour[0].addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.setBackground(col);
e.gc.fillRectangle(x, y, w, h);
if (gColour2.getA() == 1f) {
e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
} else {
e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
}
}
});
btn_LastUsedColour[0].addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
int num = gColour2.getColourNumber();
if (!View.hasLDConfigColour(num)) {
num = -1;
}
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2.getR(), gColour2.getG(), gColour2.getB(), gColour2.getA(), true);
}
regainFocus();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
if (num != -1) {
Object[] messageArguments = {num, View.getLDConfigColourName(num)};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour1);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
} else {
StringBuilder colourBuilder = new StringBuilder();
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2.getB())).toUpperCase());
Object[] messageArguments = {colourBuilder.toString()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour2);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
}
btn_LastUsedColour[0].redraw();
}
regainFocus();
}
});
btn_Decolour[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = Project.getFileToEdit().getVertexManager();
vm.addSnapshot();
vm.selectAll(new SelectorSettings(), true);
GDataCSG.clearSelection(Project.getFileToEdit());
GColour c = View.getLDConfigColour(16);
vm.colourChangeSelection(c.getColourNumber(), c.getR(), c.getG(), c.getB(), c.getA(), false);
vm.getSelectedData().removeAll(vm.getTriangles().keySet());
vm.getSelectedData().removeAll(vm.getQuads().keySet());
vm.getSelectedData().removeAll(vm.getSelectedSubfiles());
vm.getSelectedSubfiles().clear();
vm.getSelectedTriangles().removeAll(vm.getTriangles().keySet());
vm.getSelectedQuads().removeAll(vm.getQuads().keySet());
c = View.getLDConfigColour(24);
vm.colourChangeSelection(c.getColourNumber(), c.getR(), c.getG(), c.getB(), c.getA(), true);
}
}
});
btn_Palette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
final GColour[] gColour2 = new GColour[1];
new ColourDialog(getShell(), gColour2, true).open();
if (gColour2[0] != null) {
setLastUsedColour(gColour2[0]);
int num = gColour2[0].getColourNumber();
if (!View.hasLDConfigColour(num)) {
num = -1;
}
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA(), true);
btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]);
btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]);
final Color col = SWTResourceManager.getColor((int) (gColour2[0].getR() * 255f), (int) (gColour2[0].getG() * 255f), (int) (gColour2[0].getB() * 255f));
final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT);
final int x = Math.round(size.x / 5f);
final int y = Math.round(size.y / 5f);
final int w = Math.round(size.x * (3f / 5f));
final int h = Math.round(size.y * (3f / 5f));
btn_LastUsedColour[0].addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.setBackground(col);
e.gc.fillRectangle(x, y, w, h);
if (gColour2[0].getA() == 1f) {
e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
} else if (gColour2[0].getA() == 0f) {
e.gc.drawImage(ResourceManager.getImage("icon16_randomColours.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
} else {
e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
}
}
});
btn_LastUsedColour[0].addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
int num = gColour2[0].getColourNumber();
if (!View.hasLDConfigColour(num)) {
num = -1;
}
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA(), true);
}
regainFocus();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
if (num != -1) {
Object[] messageArguments = {num, View.getLDConfigColourName(num)};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour1);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
} else {
StringBuilder colourBuilder = new StringBuilder();
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getB())).toUpperCase());
Object[] messageArguments = {colourBuilder.toString()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour2);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
if (gColour2[0].getA() == 0f) btn_LastUsedColour[0].setToolTipText(I18n.COLOURDIALOG_RandomColours);
}
btn_LastUsedColour[0].redraw();
}
}
regainFocus();
}
});
btn_Coarse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
BigDecimal m = WorkbenchManager.getUserSettingState().getCoarse_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap();
snapSize = 2;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
regainFocus();
}
});
btn_Medium[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
BigDecimal m = WorkbenchManager.getUserSettingState().getMedium_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getMedium_scale_snap();
snapSize = 1;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
regainFocus();
}
});
btn_Fine[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
BigDecimal m = WorkbenchManager.getUserSettingState().getFine_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getFine_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getFine_scale_snap();
snapSize = 0;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
regainFocus();
}
});
btn_Coarse[0].addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == MouseButton.RIGHT) {
try {
if (btn_Coarse[0].getMenu() != null) {
btn_Coarse[0].getMenu().dispose();
}
} catch (Exception ex) {}
Menu gridMenu = new Menu(btn_Coarse[0]);
btn_Coarse[0].setMenu(gridMenu);
mnu_coarseMenu[0] = gridMenu;
MenuItem mntmGridCoarseDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT());
mntm_gridCoarseDefault[0] = mntmGridCoarseDefault;
mntmGridCoarseDefault.setEnabled(true);
mntmGridCoarseDefault.setText(I18n.E3D_GridCoarseDefault);
mntm_gridCoarseDefault[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setCoarse_move_snap(new BigDecimal("1")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setCoarse_rotate_snap(new BigDecimal("90")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setCoarse_scale_snap(new BigDecimal("2")); //$NON-NLS-1$
BigDecimal m = WorkbenchManager.getUserSettingState().getCoarse_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap();
snapSize = 2;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
btn_Coarse[0].setSelection(true);
btn_Medium[0].setSelection(false);
btn_Fine[0].setSelection(false);
regainFocus();
}
});
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
Menu menu = mnu_coarseMenu[0];
menu.setLocation(x, y);
menu.setVisible(true);
regainFocus();
}
}
});
btn_Medium[0].addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == MouseButton.RIGHT) {
try {
if (btn_Medium[0].getMenu() != null) {
btn_Medium[0].getMenu().dispose();
}
} catch (Exception ex) {}
Menu gridMenu = new Menu(btn_Medium[0]);
btn_Medium[0].setMenu(gridMenu);
mnu_mediumMenu[0] = gridMenu;
MenuItem mntmGridMediumDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT());
mntm_gridMediumDefault[0] = mntmGridMediumDefault;
mntmGridMediumDefault.setEnabled(true);
mntmGridMediumDefault.setText(I18n.E3D_GridMediumDefault);
mntm_gridMediumDefault[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setMedium_move_snap(new BigDecimal("0.01")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setMedium_rotate_snap(new BigDecimal("11.25")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setMedium_scale_snap(new BigDecimal("1.1")); //$NON-NLS-1$
BigDecimal m = WorkbenchManager.getUserSettingState().getMedium_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getMedium_scale_snap();
snapSize = 1;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
btn_Coarse[0].setSelection(false);
btn_Medium[0].setSelection(true);
btn_Fine[0].setSelection(false);
regainFocus();
}
});
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
Menu menu = mnu_mediumMenu[0];
menu.setLocation(x, y);
menu.setVisible(true);
regainFocus();
}
}
});
btn_Fine[0].addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == MouseButton.RIGHT) {
try {
if (btn_Fine[0].getMenu() != null) {
btn_Fine[0].getMenu().dispose();
}
} catch (Exception ex) {}
Menu gridMenu = new Menu(btn_Fine[0]);
btn_Fine[0].setMenu(gridMenu);
mnu_fineMenu[0] = gridMenu;
MenuItem mntmGridFineDefault = new MenuItem(gridMenu, I18n.I18N_NON_BIDIRECT());
mntm_gridFineDefault[0] = mntmGridFineDefault;
mntmGridFineDefault.setEnabled(true);
mntmGridFineDefault.setText(I18n.E3D_GridFineDefault);
mntm_gridFineDefault[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setFine_move_snap(new BigDecimal("0.0001")); //$NON-NLS-1$
WorkbenchManager.getUserSettingState().setFine_rotate_snap(BigDecimal.ONE);
WorkbenchManager.getUserSettingState().setFine_scale_snap(new BigDecimal("1.001")); //$NON-NLS-1$
BigDecimal m = WorkbenchManager.getUserSettingState().getFine_move_snap();
BigDecimal r = WorkbenchManager.getUserSettingState().getFine_rotate_snap();
BigDecimal s = WorkbenchManager.getUserSettingState().getFine_scale_snap();
snapSize = 0;
spn_Move[0].setValue(m);
spn_Rotate[0].setValue(r);
spn_Scale[0].setValue(s);
Manipulator.setSnap(m, r, s);
btn_Coarse[0].setSelection(false);
btn_Medium[0].setSelection(false);
btn_Fine[0].setSelection(true);
regainFocus();
}
});
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
Menu menu = mnu_fineMenu[0];
menu.setLocation(x, y);
menu.setVisible(true);
regainFocus();
}
}
});
btn_SplitQuad[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().splitQuads(true);
}
regainFocus();
}
});
btn_MergeQuad[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
RectifierSettings rs = new RectifierSettings();
rs.setScope(1);
rs.setNoBorderedQuadToRectConversation(true);
Project.getFileToEdit().getVertexManager().rectify(rs, true, true);
}
regainFocus();
}
});
btn_CondlineToLine[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().condlineToLine();
}
regainFocus();
}
});
btn_LineToCondline[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().lineToCondline();
}
regainFocus();
}
});
btn_MoveOnLine[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null && !Project.getFileToEdit().isReadOnly()) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Set<Vertex> verts = Project.getFileToEdit().getVertexManager().getSelectedVertices();
CoordinatesDialog.setStart(null);
CoordinatesDialog.setEnd(null);
if (verts.size() == 2) {
Iterator<Vertex> it = verts.iterator();
CoordinatesDialog.setStart(new Vector3d(it.next()));
CoordinatesDialog.setEnd(new Vector3d(it.next()));
}
}
regainFocus();
}
});
spn_Move[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
BigDecimal m, r, s;
m = spn.getValue();
switch (snapSize) {
case 0:
WorkbenchManager.getUserSettingState().setFine_move_snap(m);
r = WorkbenchManager.getUserSettingState().getFine_rotate_snap();
s = WorkbenchManager.getUserSettingState().getFine_scale_snap();
break;
case 2:
WorkbenchManager.getUserSettingState().setCoarse_move_snap(m);
r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap();
s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap();
break;
default:
WorkbenchManager.getUserSettingState().setMedium_move_snap(m);
r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap();
s = WorkbenchManager.getUserSettingState().getMedium_scale_snap();
break;
}
Manipulator.setSnap(m, r, s);
}
});
spn_Rotate[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
BigDecimal m, r, s;
r = spn.getValue();
switch (snapSize) {
case 0:
m = WorkbenchManager.getUserSettingState().getFine_move_snap();
WorkbenchManager.getUserSettingState().setFine_rotate_snap(r);
s = WorkbenchManager.getUserSettingState().getFine_scale_snap();
break;
case 2:
m = WorkbenchManager.getUserSettingState().getCoarse_move_snap();
WorkbenchManager.getUserSettingState().setCoarse_rotate_snap(r);
s = WorkbenchManager.getUserSettingState().getCoarse_scale_snap();
break;
default:
m = WorkbenchManager.getUserSettingState().getMedium_move_snap();
WorkbenchManager.getUserSettingState().setMedium_rotate_snap(r);
s = WorkbenchManager.getUserSettingState().getMedium_scale_snap();
break;
}
Manipulator.setSnap(m, r, s);
}
});
spn_Scale[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
BigDecimal m, r, s;
s = spn.getValue();
switch (snapSize) {
case 0:
m = WorkbenchManager.getUserSettingState().getFine_move_snap();
r = WorkbenchManager.getUserSettingState().getFine_rotate_snap();
WorkbenchManager.getUserSettingState().setFine_scale_snap(s);
break;
case 2:
m = WorkbenchManager.getUserSettingState().getCoarse_move_snap();
r = WorkbenchManager.getUserSettingState().getCoarse_rotate_snap();
WorkbenchManager.getUserSettingState().setCoarse_scale_snap(s);
break;
default:
m = WorkbenchManager.getUserSettingState().getMedium_move_snap();
r = WorkbenchManager.getUserSettingState().getMedium_rotate_snap();
WorkbenchManager.getUserSettingState().setMedium_scale_snap(s);
break;
}
Manipulator.setSnap(m, r, s);
}
});
btn_PreviousSelection[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updatingSelectionTab = true;
NLogger.debug(getClass(), "Previous Selection..."); //$NON-NLS-1$
final DatFile df = Project.getFileToEdit();
if (df != null && !df.isReadOnly()) {
final VertexManager vm = df.getVertexManager();
vm.addSnapshot();
final int count = vm.getSelectedData().size();
if (count > 0) {
boolean breakIt = false;
boolean firstRun = true;
while (true) {
int index = vm.getSelectedItemIndex();
index--;
if (index < 0) {
index = count - 1;
if (!firstRun) breakIt = true;
}
if (index > count - 1) index = count - 1;
firstRun = false;
vm.setSelectedItemIndex(index);
final GData gdata = (GData) vm.getSelectedData().toArray()[index];
if (vm.isNotInSubfileAndLinetype1to5(gdata)) {
vm.setSelectedLine(gdata);
disableSelectionTab();
updatingSelectionTab = true;
switch (gdata.type()) {
case 1:
case 5:
case 4:
spn_SelectionX4[0].setEnabled(true);
spn_SelectionY4[0].setEnabled(true);
spn_SelectionZ4[0].setEnabled(true);
case 3:
spn_SelectionX3[0].setEnabled(true);
spn_SelectionY3[0].setEnabled(true);
spn_SelectionZ3[0].setEnabled(true);
case 2:
spn_SelectionX1[0].setEnabled(true);
spn_SelectionY1[0].setEnabled(true);
spn_SelectionZ1[0].setEnabled(true);
spn_SelectionX2[0].setEnabled(true);
spn_SelectionY2[0].setEnabled(true);
spn_SelectionZ2[0].setEnabled(true);
txt_Line[0].setText(gdata.toString());
breakIt = true;
btn_MoveAdjacentData2[0].setEnabled(true);
switch (gdata.type()) {
case 5:
BigDecimal[] g5 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g5[0]);
spn_SelectionY1[0].setValue(g5[1]);
spn_SelectionZ1[0].setValue(g5[2]);
spn_SelectionX2[0].setValue(g5[3]);
spn_SelectionY2[0].setValue(g5[4]);
spn_SelectionZ2[0].setValue(g5[5]);
spn_SelectionX3[0].setValue(g5[6]);
spn_SelectionY3[0].setValue(g5[7]);
spn_SelectionZ3[0].setValue(g5[8]);
spn_SelectionX4[0].setValue(g5[9]);
spn_SelectionY4[0].setValue(g5[10]);
spn_SelectionZ4[0].setValue(g5[11]);
break;
case 4:
BigDecimal[] g4 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g4[0]);
spn_SelectionY1[0].setValue(g4[1]);
spn_SelectionZ1[0].setValue(g4[2]);
spn_SelectionX2[0].setValue(g4[3]);
spn_SelectionY2[0].setValue(g4[4]);
spn_SelectionZ2[0].setValue(g4[5]);
spn_SelectionX3[0].setValue(g4[6]);
spn_SelectionY3[0].setValue(g4[7]);
spn_SelectionZ3[0].setValue(g4[8]);
spn_SelectionX4[0].setValue(g4[9]);
spn_SelectionY4[0].setValue(g4[10]);
spn_SelectionZ4[0].setValue(g4[11]);
break;
case 3:
BigDecimal[] g3 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g3[0]);
spn_SelectionY1[0].setValue(g3[1]);
spn_SelectionZ1[0].setValue(g3[2]);
spn_SelectionX2[0].setValue(g3[3]);
spn_SelectionY2[0].setValue(g3[4]);
spn_SelectionZ2[0].setValue(g3[5]);
spn_SelectionX3[0].setValue(g3[6]);
spn_SelectionY3[0].setValue(g3[7]);
spn_SelectionZ3[0].setValue(g3[8]);
break;
case 2:
BigDecimal[] g2 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g2[0]);
spn_SelectionY1[0].setValue(g2[1]);
spn_SelectionZ1[0].setValue(g2[2]);
spn_SelectionX2[0].setValue(g2[3]);
spn_SelectionY2[0].setValue(g2[4]);
spn_SelectionZ2[0].setValue(g2[5]);
break;
case 1:
vm.getSelectedVertices().clear();
btn_MoveAdjacentData2[0].setEnabled(false);
GData1 g1 = (GData1) gdata;
spn_SelectionX1[0].setValue(g1.getAccurateProductMatrix().M30);
spn_SelectionY1[0].setValue(g1.getAccurateProductMatrix().M31);
spn_SelectionZ1[0].setValue(g1.getAccurateProductMatrix().M32);
spn_SelectionX2[0].setValue(g1.getAccurateProductMatrix().M00);
spn_SelectionY2[0].setValue(g1.getAccurateProductMatrix().M01);
spn_SelectionZ2[0].setValue(g1.getAccurateProductMatrix().M02);
spn_SelectionX3[0].setValue(g1.getAccurateProductMatrix().M10);
spn_SelectionY3[0].setValue(g1.getAccurateProductMatrix().M11);
spn_SelectionZ3[0].setValue(g1.getAccurateProductMatrix().M12);
spn_SelectionX4[0].setValue(g1.getAccurateProductMatrix().M20);
spn_SelectionY4[0].setValue(g1.getAccurateProductMatrix().M21);
spn_SelectionZ4[0].setValue(g1.getAccurateProductMatrix().M22);
break;
default:
disableSelectionTab();
updatingSelectionTab = true;
break;
}
lbl_SelectionX1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX1 : "") + " {" + spn_SelectionX1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY1 : "") + " {" + spn_SelectionY1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ1 : "") + " {" + spn_SelectionZ1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX2 : "") + " {" + spn_SelectionX2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY2 : "") + " {" + spn_SelectionY2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ2 : "") + " {" + spn_SelectionZ2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX3 : "") + " {" + spn_SelectionX3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY3 : "") + " {" + spn_SelectionY3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ3 : "") + " {" + spn_SelectionZ3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX4 : "") + " {" + spn_SelectionX4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY4 : "") + " {" + spn_SelectionY4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ4 : "") + " {" + spn_SelectionZ4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX1[0].getParent().layout();
updatingSelectionTab = false;
break;
default:
disableSelectionTab();
break;
}
} else {
disableSelectionTab();
}
if (breakIt) break;
}
} else {
disableSelectionTab();
}
} else {
disableSelectionTab();
}
updatingSelectionTab = false;
regainFocus();
}
});
btn_NextSelection[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updatingSelectionTab = true;
NLogger.debug(getClass(), "Next Selection..."); //$NON-NLS-1$
final DatFile df = Project.getFileToEdit();
if (df != null && !df.isReadOnly()) {
final VertexManager vm = df.getVertexManager();
vm.addSnapshot();
final int count = vm.getSelectedData().size();
if (count > 0) {
boolean breakIt = false;
boolean firstRun = true;
while (true) {
int index = vm.getSelectedItemIndex();
index++;
if (index >= count) {
index = 0;
if (!firstRun) breakIt = true;
}
firstRun = false;
vm.setSelectedItemIndex(index);
final GData gdata = (GData) vm.getSelectedData().toArray()[index];
if (vm.isNotInSubfileAndLinetype1to5(gdata)) {
vm.setSelectedLine(gdata);
disableSelectionTab();
updatingSelectionTab = true;
switch (gdata.type()) {
case 1:
case 5:
case 4:
spn_SelectionX4[0].setEnabled(true);
spn_SelectionY4[0].setEnabled(true);
spn_SelectionZ4[0].setEnabled(true);
case 3:
spn_SelectionX3[0].setEnabled(true);
spn_SelectionY3[0].setEnabled(true);
spn_SelectionZ3[0].setEnabled(true);
case 2:
spn_SelectionX1[0].setEnabled(true);
spn_SelectionY1[0].setEnabled(true);
spn_SelectionZ1[0].setEnabled(true);
spn_SelectionX2[0].setEnabled(true);
spn_SelectionY2[0].setEnabled(true);
spn_SelectionZ2[0].setEnabled(true);
txt_Line[0].setText(gdata.toString());
breakIt = true;
btn_MoveAdjacentData2[0].setEnabled(true);
switch (gdata.type()) {
case 5:
BigDecimal[] g5 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g5[0]);
spn_SelectionY1[0].setValue(g5[1]);
spn_SelectionZ1[0].setValue(g5[2]);
spn_SelectionX2[0].setValue(g5[3]);
spn_SelectionY2[0].setValue(g5[4]);
spn_SelectionZ2[0].setValue(g5[5]);
spn_SelectionX3[0].setValue(g5[6]);
spn_SelectionY3[0].setValue(g5[7]);
spn_SelectionZ3[0].setValue(g5[8]);
spn_SelectionX4[0].setValue(g5[9]);
spn_SelectionY4[0].setValue(g5[10]);
spn_SelectionZ4[0].setValue(g5[11]);
break;
case 4:
BigDecimal[] g4 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g4[0]);
spn_SelectionY1[0].setValue(g4[1]);
spn_SelectionZ1[0].setValue(g4[2]);
spn_SelectionX2[0].setValue(g4[3]);
spn_SelectionY2[0].setValue(g4[4]);
spn_SelectionZ2[0].setValue(g4[5]);
spn_SelectionX3[0].setValue(g4[6]);
spn_SelectionY3[0].setValue(g4[7]);
spn_SelectionZ3[0].setValue(g4[8]);
spn_SelectionX4[0].setValue(g4[9]);
spn_SelectionY4[0].setValue(g4[10]);
spn_SelectionZ4[0].setValue(g4[11]);
break;
case 3:
BigDecimal[] g3 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g3[0]);
spn_SelectionY1[0].setValue(g3[1]);
spn_SelectionZ1[0].setValue(g3[2]);
spn_SelectionX2[0].setValue(g3[3]);
spn_SelectionY2[0].setValue(g3[4]);
spn_SelectionZ2[0].setValue(g3[5]);
spn_SelectionX3[0].setValue(g3[6]);
spn_SelectionY3[0].setValue(g3[7]);
spn_SelectionZ3[0].setValue(g3[8]);
break;
case 2:
BigDecimal[] g2 = GraphicalDataTools.getPreciseCoordinates(gdata);
spn_SelectionX1[0].setValue(g2[0]);
spn_SelectionY1[0].setValue(g2[1]);
spn_SelectionZ1[0].setValue(g2[2]);
spn_SelectionX2[0].setValue(g2[3]);
spn_SelectionY2[0].setValue(g2[4]);
spn_SelectionZ2[0].setValue(g2[5]);
break;
case 1:
vm.getSelectedVertices().clear();
btn_MoveAdjacentData2[0].setEnabled(false);
GData1 g1 = (GData1) gdata;
spn_SelectionX1[0].setValue(g1.getAccurateProductMatrix().M30);
spn_SelectionY1[0].setValue(g1.getAccurateProductMatrix().M31);
spn_SelectionZ1[0].setValue(g1.getAccurateProductMatrix().M32);
spn_SelectionX2[0].setValue(g1.getAccurateProductMatrix().M00);
spn_SelectionY2[0].setValue(g1.getAccurateProductMatrix().M01);
spn_SelectionZ2[0].setValue(g1.getAccurateProductMatrix().M02);
spn_SelectionX3[0].setValue(g1.getAccurateProductMatrix().M10);
spn_SelectionY3[0].setValue(g1.getAccurateProductMatrix().M11);
spn_SelectionZ3[0].setValue(g1.getAccurateProductMatrix().M12);
spn_SelectionX4[0].setValue(g1.getAccurateProductMatrix().M20);
spn_SelectionY4[0].setValue(g1.getAccurateProductMatrix().M21);
spn_SelectionZ4[0].setValue(g1.getAccurateProductMatrix().M22);
break;
default:
disableSelectionTab();
updatingSelectionTab = true;
break;
}
lbl_SelectionX1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX1 : "X :") + " {" + spn_SelectionX1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY1 : "Y :") + " {" + spn_SelectionY1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ1[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ1 : "Z :") + " {" + spn_SelectionZ1[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX2 : "M00:") + " {" + spn_SelectionX2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY2 : "M01:") + " {" + spn_SelectionY2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ2[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ2 : "M02:") + " {" + spn_SelectionZ2[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX3 : "M10:") + " {" + spn_SelectionX3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY3 : "M11:") + " {" + spn_SelectionY3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ3[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ3 : "M12:") + " {" + spn_SelectionZ3[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionX4 : "M20:") + " {" + spn_SelectionX4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionY4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionY4 : "M21:") + " {" + spn_SelectionY4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionZ4[0].setText((gdata.type() != 1 ? I18n.E3D_PositionZ4 : "M22:") + " {" + spn_SelectionZ4[0].getStringValue() + "}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
lbl_SelectionX1[0].getParent().layout();
break;
default:
disableSelectionTab();
break;
}
} else {
disableSelectionTab();
}
if (breakIt) break;
}
} else {
disableSelectionTab();
}
} else {
disableSelectionTab();
}
updatingSelectionTab = false;
regainFocus();
}
});
final ValueChangeAdapter va = new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
if (updatingSelectionTab || Project.getFileToEdit() == null) return;
Project.getFileToEdit().getVertexManager().addSnapshot();
final GData newLine = Project.getFileToEdit().getVertexManager().updateSelectedLine(
spn_SelectionX1[0].getValue(), spn_SelectionY1[0].getValue(), spn_SelectionZ1[0].getValue(),
spn_SelectionX2[0].getValue(), spn_SelectionY2[0].getValue(), spn_SelectionZ2[0].getValue(),
spn_SelectionX3[0].getValue(), spn_SelectionY3[0].getValue(), spn_SelectionZ3[0].getValue(),
spn_SelectionX4[0].getValue(), spn_SelectionY4[0].getValue(), spn_SelectionZ4[0].getValue(),
btn_MoveAdjacentData2[0].getSelection()
);
if (newLine == null) {
disableSelectionTab();
} else {
txt_Line[0].setText(newLine.toString());
}
}
};
spn_SelectionX1[0].addValueChangeListener(va);
spn_SelectionY1[0].addValueChangeListener(va);
spn_SelectionZ1[0].addValueChangeListener(va);
spn_SelectionX2[0].addValueChangeListener(va);
spn_SelectionY2[0].addValueChangeListener(va);
spn_SelectionZ2[0].addValueChangeListener(va);
spn_SelectionX3[0].addValueChangeListener(va);
spn_SelectionY3[0].addValueChangeListener(va);
spn_SelectionZ3[0].addValueChangeListener(va);
spn_SelectionX4[0].addValueChangeListener(va);
spn_SelectionY4[0].addValueChangeListener(va);
spn_SelectionZ4[0].addValueChangeListener(va);
btn_MoveAdjacentData2[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
regainFocus();
}
});
treeParts[0].addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (event.button == MouseButton.RIGHT) {
NLogger.debug(getClass(), "Showing context menu."); //$NON-NLS-1$
try {
if (treeParts[0].getTree().getMenu() != null) {
treeParts[0].getTree().getMenu().dispose();
}
} catch (Exception ex) {}
Menu treeMenu = new Menu(treeParts[0].getTree());
treeParts[0].getTree().setMenu(treeMenu);
mnu_treeMenu[0] = treeMenu;
MenuItem mntmOpenIn3DEditor = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_OpenIn3DEditor[0] = mntmOpenIn3DEditor;
mntmOpenIn3DEditor.setEnabled(true);
mntmOpenIn3DEditor.setText(I18n.E3D_OpenIn3DEditor);
MenuItem mntmOpenInTextEditor = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_OpenInTextEditor[0] = mntmOpenInTextEditor;
mntmOpenInTextEditor.setEnabled(true);
mntmOpenInTextEditor.setText(I18n.E3D_OpenInTextEditor);
@SuppressWarnings("unused")
MenuItem mntm_Separator = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR);
MenuItem mntmClose = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_Close[0] = mntmClose;
mntmClose.setEnabled(true);
mntmClose.setText(I18n.E3D_Close);
@SuppressWarnings("unused")
MenuItem mntm_Separator2 = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR);
MenuItem mntmRename = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_Rename[0] = mntmRename;
mntmRename.setEnabled(true);
mntmRename.setText(I18n.E3D_RenameMove);
MenuItem mntmRevert = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_Revert[0] = mntmRevert;
mntmRevert.setEnabled(true);
mntmRevert.setText(I18n.E3D_RevertAllChanges);
@SuppressWarnings("unused")
MenuItem mntm_Separator3 = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT() | SWT.SEPARATOR);
MenuItem mntmCopyToUnofficial = new MenuItem(treeMenu, I18n.I18N_NON_BIDIRECT());
mntm_CopyToUnofficial[0] = mntmCopyToUnofficial;
mntmCopyToUnofficial.setEnabled(true);
mntmCopyToUnofficial.setText(I18n.E3D_CopyToUnofficialLibrary);
mntm_OpenInTextEditor[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
w.getTabFolder().setSelection(t);
((CompositeTab) t).getControl().getShell().forceActive();
if (w.isSeperateWindow()) {
w.open();
}
df.getVertexManager().setUpdated(true);
return;
}
}
}
EditorTextWindow w = null;
for (EditorTextWindow w2 : Project.getOpenTextWindows()) {
if (w2.getTabFolder().getItems().length == 0) {
w = w2;
break;
}
}
// Project.getParsedFiles().add(df); IS NECESSARY HERE
Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
if (!Project.getOpenTextWindows().isEmpty() && w != null || !(w = Project.getOpenTextWindows().iterator().next()).isSeperateWindow()) {
w.openNewDatFileTab(df, true);
} else {
new EditorTextWindow().run(df, false);
}
df.getVertexManager().addSnapshot();
}
cleanupClosedData();
updateTabs();
}
});
mntm_OpenIn3DEditor[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
openFileIn3DEditor(df);
updateTree_unsavedEntries();
cleanupClosedData();
regainFocus();
}
}
});
mntm_Revert[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
revert(df);
}
regainFocus();
}
});
mntm_Close[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
Project.removeOpenedFile(df);
if (!closeDatfile(df)) {
Project.addOpenedFile(df);
updateTabs();
}
}
}
});
mntm_Rename[0].addSelectionListener(new SelectionAdapter() {
@SuppressWarnings("unchecked")
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
if (df.isReadOnly()) {
regainFocus();
return;
}
df.getVertexManager().addSnapshot();
FileDialog dlg = new FileDialog(Editor3DWindow.getWindow().getShell(), SWT.SAVE);
File tmp = new File(df.getNewName());
dlg.setFilterPath(tmp.getAbsolutePath().substring(0, tmp.getAbsolutePath().length() - tmp.getName().length()));
dlg.setFileName(tmp.getName());
dlg.setFilterExtensions(new String[]{"*.dat"}); //$NON-NLS-1$
dlg.setOverwrite(true);
// Change the title bar text
dlg.setText(I18n.DIALOG_RenameOrMove);
// Calling open() will open and run the dialog.
// It will return the selected file, or
// null if user cancels
String newPath = dlg.open();
if (newPath != null) {
while (isFileNameAllocated(newPath, df, false)) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
int result = messageBox.open();
if (result == SWT.CANCEL) {
regainFocus();
return;
}
newPath = dlg.open();
if (newPath == null) {
regainFocus();
return;
}
}
if (df.isProjectFile() && !newPath.startsWith(Project.getProjectPath())) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.YES | SWT.NO);
messageBox.setText(I18n.DIALOG_NoProjectLocationTitle);
Object[] messageArguments = {new File(newPath).getName()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_NoProjectLocation);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.NO) {
regainFocus();
return;
}
}
df.setNewName(newPath);
if (!df.getOldName().equals(df.getNewName())) {
if (!Project.getUnsavedFiles().contains(df)) {
df.parseForData(true);
df.getVertexManager().setModified(true, true);
Project.getUnsavedFiles().add(df);
}
} else {
if (df.getText().equals(df.getOriginalText()) && df.getOldName().equals(df.getNewName())) {
Project.removeUnsavedFile(df);
}
}
df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath()));
final File f = new File(df.getNewName());
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
HashSet<EditorTextWindow> windows = new HashSet<EditorTextWindow>(Project.getOpenTextWindows());
for (EditorTextWindow win : windows) {
win.updateTabWithDatfile(df);
}
updateTree_renamedEntries();
updateTree_unsavedEntries();
}
} else if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].equals(treeItem_Project[0])) {
if (Project.isDefaultProject()) {
if (ProjectActions.createNewProject(Editor3DWindow.getWindow(), true)) {
Project.setLastVisitedPath(Project.getProjectPath());
}
} else {
int result = new NewProjectDialog(true).open();
if (result == IDialogConstants.OK_ID && !Project.getTempProjectPath().equals(Project.getProjectPath())) {
try {
while (new File(Project.getTempProjectPath()).isDirectory()) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.YES | SWT.CANCEL | SWT.NO);
messageBoxError.setText(I18n.PROJECT_ProjectOverwriteTitle);
messageBoxError.setMessage(I18n.PROJECT_ProjectOverwrite);
int result2 = messageBoxError.open();
if (result2 == SWT.CANCEL) {
regainFocus();
return;
} else if (result2 == SWT.YES) {
break;
} else {
result = new NewProjectDialog(true).open();
if (result == IDialogConstants.CANCEL_ID) {
regainFocus();
return;
}
}
}
Project.copyFolder(new File(Project.getProjectPath()), new File(Project.getTempProjectPath()));
Project.deleteFolder(new File(Project.getProjectPath()));
// Linked project parts need a new path, because they were copied to a new directory
String defaultPrefix = new File(Project.getProjectPath()).getAbsolutePath() + File.separator;
String projectPrefix = new File(Project.getTempProjectPath()).getAbsolutePath() + File.separator;
Editor3DWindow.getWindow().getProjectParts().getParentItem().setData(Project.getTempProjectPath());
HashSet<DatFile> projectFiles = new HashSet<DatFile>();
projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectParts().getData());
projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectSubparts().getData());
projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives().getData());
projectFiles.addAll((ArrayList<DatFile>) Editor3DWindow.getWindow().getProjectPrimitives48().getData());
for (DatFile df : projectFiles) {
df.getVertexManager().addSnapshot();
boolean isUnsaved = Project.getUnsavedFiles().contains(df);
boolean isParsed = Project.getParsedFiles().contains(df);
Project.getParsedFiles().remove(df);
Project.getUnsavedFiles().remove(df);
String newName = df.getNewName();
String oldName = df.getOldName();
df.updateLastModified();
if (!newName.startsWith(projectPrefix) && newName.startsWith(defaultPrefix)) {
df.setNewName(projectPrefix + newName.substring(defaultPrefix.length()));
}
if (!oldName.startsWith(projectPrefix) && oldName.startsWith(defaultPrefix)) {
df.setOldName(projectPrefix + oldName.substring(defaultPrefix.length()));
}
df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath()));
if (isUnsaved) Project.addUnsavedFile(df);
if (isParsed) Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
}
Project.setProjectName(Project.getTempProjectName());
Project.setProjectPath(Project.getTempProjectPath());
Editor3DWindow.getWindow().getProjectParts().getParentItem().setText(Project.getProjectName());
updateTree_unsavedEntries();
Project.updateEditor();
Editor3DWindow.getWindow().getShell().update();
Project.setLastVisitedPath(Project.getProjectPath());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
} else {
// MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
// messageBoxError.setText(I18n.DIALOG_UnavailableTitle);
// messageBoxError.setMessage(I18n.DIALOG_Unavailable);
// messageBoxError.open();
}
regainFocus();
}
});
mntm_CopyToUnofficial[0] .addSelectionListener(new SelectionAdapter() {
@SuppressWarnings("unchecked")
@Override
public void widgetSelected(SelectionEvent e) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null && treeParts[0].getSelection()[0].getData() instanceof DatFile) {
DatFile df = (DatFile) treeParts[0].getSelection()[0].getData();
TreeItem p = treeParts[0].getSelection()[0].getParentItem();
String targetPath_u;
String targetPath_l;
String targetPathDir_u;
String targetPathDir_l;
TreeItem targetTreeItem;
boolean projectIsFileOrigin = false;
if (treeItem_ProjectParts[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"; //$NON-NLS-1$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"; //$NON-NLS-1$
targetTreeItem = treeItem_UnofficialParts[0];
projectIsFileOrigin = true;
} else if (treeItem_ProjectPrimitives[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P"; //$NON-NLS-1$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p"; //$NON-NLS-1$
targetTreeItem = treeItem_UnofficialPrimitives[0];
projectIsFileOrigin = true;
} else if (treeItem_ProjectPrimitives48[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialPrimitives48[0];
projectIsFileOrigin = true;
} else if (treeItem_ProjectPrimitives8[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialPrimitives8[0];
projectIsFileOrigin = true;
} else if (treeItem_ProjectSubparts[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"+ File.separator + "S"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"+ File.separator + "s"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialSubparts[0];
projectIsFileOrigin = true;
} else if (treeItem_OfficialParts[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"; //$NON-NLS-1$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"; //$NON-NLS-1$
targetTreeItem = treeItem_UnofficialParts[0];
} else if (treeItem_OfficialPrimitives[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P"; //$NON-NLS-1$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p"; //$NON-NLS-1$
targetTreeItem = treeItem_UnofficialPrimitives[0];
} else if (treeItem_OfficialPrimitives48[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialPrimitives48[0];
} else if (treeItem_OfficialPrimitives8[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialPrimitives8[0];
} else if (treeItem_OfficialSubparts[0].equals(p)) {
targetPath_u = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS"+ File.separator + "S"; //$NON-NLS-1$ //$NON-NLS-2$
targetPath_l = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts"+ File.separator + "s"; //$NON-NLS-1$ //$NON-NLS-2$
targetTreeItem = treeItem_UnofficialSubparts[0];
} else {
// MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
// messageBoxError.setText(I18n.DIALOG_UnavailableTitle);
// messageBoxError.setMessage(I18n.DIALOG_Unavailable);
// messageBoxError.open();
regainFocus();
return;
}
targetPathDir_l = targetPath_l;
targetPathDir_u = targetPath_u;
final String newName = new File(df.getNewName()).getName();
targetPath_u = targetPath_u + File.separator + newName;
targetPath_l = targetPath_l + File.separator + newName;
DatFile fileToOverwrite_u = new DatFile(targetPath_u);
DatFile fileToOverwrite_l = new DatFile(targetPath_l);
DatFile targetFile = null;
TreeItem[] folders = new TreeItem[5];
folders[0] = treeItem_UnofficialParts[0];
folders[1] = treeItem_UnofficialPrimitives[0];
folders[2] = treeItem_UnofficialPrimitives48[0];
folders[3] = treeItem_UnofficialPrimitives8[0];
folders[4] = treeItem_UnofficialSubparts[0];
for (TreeItem folder : folders) {
ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData();
for (DatFile d : cachedReferences) {
if (fileToOverwrite_u.equals(d) || fileToOverwrite_l.equals(d)) {
targetFile = d;
break;
}
}
}
if (new File(targetPath_u).exists() || new File(targetPath_l).exists() || targetFile != null) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_ReplaceTitle);
Object[] messageArguments = {newName};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_Replace);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.CANCEL) {
regainFocus();
return;
}
}
ArrayList<ArrayList<DatFile>> refResult = null;
if (new File(targetPathDir_l).exists() || new File(targetPathDir_u).exists()) {
if (targetFile == null) {
int result = new CopyDialog(getShell(), new File(df.getNewName()).getName()).open();
switch (result) {
case IDialogConstants.OK_ID:
// Copy File Only
break;
case IDialogConstants.NO_ID:
// Copy File and required and related
if (projectIsFileOrigin) {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]);
} else {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]);
}
break;
case IDialogConstants.YES_ID:
// Copy File and required
if (projectIsFileOrigin) {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]);
} else {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]);
}
break;
default:
regainFocus();
return;
}
DatFile newDatFile = new DatFile(new File(targetPathDir_l).exists() ? targetPath_l : targetPath_u);
// Text exchange includes description exchange
newDatFile.setText(df.getText());
newDatFile.saveForced();
newDatFile.setType(df.getType());
((ArrayList<DatFile>) targetTreeItem.getData()).add(newDatFile);
TreeItem ti = new TreeItem(targetTreeItem, SWT.NONE);
ti.setText(new File(df.getNewName()).getName());
ti.setData(newDatFile);
} else if (targetFile.equals(df)) { // This can only happen if the user opens the unofficial parts folder as a project
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
messageBox.open();
regainFocus();
return;
} else {
int result = new CopyDialog(getShell(), new File(df.getNewName()).getName()).open();
switch (result) {
case IDialogConstants.OK_ID:
// Copy File Only
break;
case IDialogConstants.NO_ID:
// Copy File and required and related
if (projectIsFileOrigin) {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]);
} else {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED_AND_RELATED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]);
}
break;
case IDialogConstants.YES_ID:
// Copy File and required
if (projectIsFileOrigin) {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Project[0], treeItem_Unofficial[0], treeItem_Official[0]);
} else {
refResult = ReferenceParser.checkForReferences(df, References.REQUIRED, treeItem_Official[0], treeItem_Unofficial[0], treeItem_Project[0]);
}
break;
default:
regainFocus();
return;
}
targetFile.disposeData();
updateTree_removeEntry(targetFile);
DatFile newDatFile = new DatFile(new File(targetPathDir_l).exists() ? targetPath_l : targetPath_u);
newDatFile.setText(df.getText());
newDatFile.saveForced();
((ArrayList<DatFile>) targetTreeItem.getData()).add(newDatFile);
TreeItem ti = new TreeItem(targetTreeItem, SWT.NONE);
ti.setText(new File(df.getNewName()).getName());
ti.setData(newDatFile);
}
if (refResult != null) {
// Remove old data
for(int i = 0; i < 5; i++) {
ArrayList<DatFile> toRemove = refResult.get(i);
for (DatFile datToRemove : toRemove) {
datToRemove.disposeData();
updateTree_removeEntry(datToRemove);
}
}
// Create new data
TreeItem[] targetTrees = new TreeItem[]{treeItem_UnofficialParts[0], treeItem_UnofficialSubparts[0], treeItem_UnofficialPrimitives[0], treeItem_UnofficialPrimitives48[0], treeItem_UnofficialPrimitives8[0]};
for(int i = 5; i < 10; i++) {
ArrayList<DatFile> toCreate = refResult.get(i);
for (DatFile datToCreate : toCreate) {
DatFile newDatFile = new DatFile(datToCreate.getOldName());
String source = datToCreate.getTextDirect();
newDatFile.setText(source);
newDatFile.setOriginalText(source);
newDatFile.saveForced();
newDatFile.setType(datToCreate.getType());
((ArrayList<DatFile>) targetTrees[i - 5].getData()).add(newDatFile);
TreeItem ti = new TreeItem(targetTrees[i - 5], SWT.NONE);
ti.setText(new File(datToCreate.getOldName()).getName());
ti.setData(newDatFile);
}
}
}
updateTree_unsavedEntries();
}
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBoxError.setText(I18n.DIALOG_UnavailableTitle);
messageBoxError.setMessage(I18n.DIALOG_Unavailable);
messageBoxError.open();
}
regainFocus();
}
});
java.awt.Point b = java.awt.MouseInfo.getPointerInfo().getLocation();
final int x = (int) b.getX();
final int y = (int) b.getY();
Menu menu = mnu_treeMenu[0];
menu.setLocation(x, y);
menu.setVisible(true);
}
regainFocus();
}
});
treeParts[0].addListener(SWT.MouseDoubleClick, new Listener() {
@Override
public void handleEvent(Event event) {
if (treeParts[0].getSelectionCount() == 1 && treeParts[0].getSelection()[0] != null) {
treeParts[0].getSelection()[0].setVisible(!treeParts[0].getSelection()[0].isVisible());
TreeItem sel = treeParts[0].getSelection()[0];
sh.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
treeParts[0].build();
}
});
treeParts[0].redraw();
treeParts[0].update();
treeParts[0].getTree().select(treeParts[0].getMapInv().get(sel));
}
regainFocus();
}
});
txt_Search[0].addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
search(txt_Search[0].getText());
}
});
btn_ResetSearch[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
txt_Search[0].setText(""); //$NON-NLS-1$
txt_Search[0].setFocus();
}
});
txt_primitiveSearch[0].addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
getCompositePrimitive().collapseAll();
ArrayList<Primitive> prims = getCompositePrimitive().getPrimitives();
final String crit = txt_primitiveSearch[0].getText();
if (crit.trim().isEmpty()) {
getCompositePrimitive().setSearchResults(new ArrayList<Primitive>());
Matrix4f.setIdentity(getCompositePrimitive().getTranslation());
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
return;
}
String criteria = ".*" + crit + ".*"; //$NON-NLS-1$ //$NON-NLS-2$
try {
"DUMMY".matches(criteria); //$NON-NLS-1$
} catch (PatternSyntaxException pe) {
getCompositePrimitive().setSearchResults(new ArrayList<Primitive>());
Matrix4f.setIdentity(getCompositePrimitive().getTranslation());
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
return;
}
final Pattern pattern = Pattern.compile(criteria);
ArrayList<Primitive> results = new ArrayList<Primitive>();
for (Primitive p : prims) {
p.search(pattern, results);
}
if (results.isEmpty()) {
results.add(null);
}
getCompositePrimitive().setSearchResults(results);
Matrix4f.setIdentity(getCompositePrimitive().getTranslation());
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
}
});
btn_resetPrimitiveSearch[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
txt_primitiveSearch[0].setText(""); //$NON-NLS-1$
txt_primitiveSearch[0].setFocus();
}
});
btn_zoomInPrimitives[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getCompositePrimitive().zoomIn();
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
}
});
btn_zoomOutPrimitives[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getCompositePrimitive().zoomOut();
getCompositePrimitive().getOpenGL().drawScene(-1, -1);
}
});
btn_Hide[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
if (Project.getFileToEdit().getVertexManager().getSelectedData().size() > 0) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().hideSelection();
Project.getFileToEdit().addHistory();
}
}
regainFocus();
}
});
btn_ShowAll[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().showAll();
Project.getFileToEdit().addHistory();
}
regainFocus();
}
});
btn_NoTransparentSelection[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setNoTransparentSelection(btn_NoTransparentSelection[0].getSelection());
regainFocus();
}
});
btn_BFCToggle[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setBfcToggle(btn_BFCToggle[0].getSelection());
regainFocus();
}
});
btn_InsertAtCursorPosition[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setInsertingAtCursorPosition(btn_InsertAtCursorPosition[0].getSelection());
regainFocus();
}
});
btn_Delete[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().delete(Editor3DWindow.getWindow().isMovingAdjacentData(), true);
}
regainFocus();
}
});
btn_Copy[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().copy();
}
regainFocus();
}
});
btn_Cut[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().copy();
Project.getFileToEdit().getVertexManager().delete(false, true);
}
regainFocus();
}
});
btn_Paste[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Project.getFileToEdit().getVertexManager().addSnapshot();
Project.getFileToEdit().getVertexManager().paste();
if (WorkbenchManager.getUserSettingState().isDisableMAD3D()) {
setMovingAdjacentData(false);
GuiManager.updateStatus();
}
}
regainFocus();
}
});
if (btn_Manipulator_0_toOrigin[0] != null) btn_Manipulator_0_toOrigin[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_0();
}
});
if (btn_Manipulator_XIII_toWorld[0] != null) btn_Manipulator_XIII_toWorld[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XIII();
}
});
if (btn_Manipulator_X_XReverse[0] != null) btn_Manipulator_X_XReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_X();
}
});
if (btn_Manipulator_XI_YReverse[0] != null) btn_Manipulator_XI_YReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XI();
}
});
if (btn_Manipulator_XII_ZReverse[0] != null) btn_Manipulator_XII_ZReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XII();
}
});
if (btn_Manipulator_SwitchXY[0] != null) btn_Manipulator_SwitchXY[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XY();
}
});
if (btn_Manipulator_SwitchXZ[0] != null) btn_Manipulator_SwitchXZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XZ();
}
});
if (btn_Manipulator_SwitchYZ[0] != null) btn_Manipulator_SwitchYZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_YZ();
}
});
if (btn_Manipulator_1_cameraToPos[0] != null) btn_Manipulator_1_cameraToPos[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_1();
}
});
if (btn_Manipulator_2_toAverage[0] != null) btn_Manipulator_2_toAverage[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_2();
}
});
if (btn_Manipulator_3_toSubfile[0] != null) btn_Manipulator_3_toSubfile[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_3();
}
});
if (btn_Manipulator_32_subfileTo[0] != null) btn_Manipulator_32_subfileTo[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_32();
}
});
if (btn_Manipulator_4_toVertex[0] != null) btn_Manipulator_4_toVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_4();
}
});
if (btn_Manipulator_5_toEdge[0] != null) btn_Manipulator_5_toEdge[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_5();
}
});
if (btn_Manipulator_6_toSurface[0] != null) btn_Manipulator_6_toSurface[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_6();
}
});
if (btn_Manipulator_7_toVertexNormal[0] != null) btn_Manipulator_7_toVertexNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_7();
}
});
if (btn_Manipulator_8_toEdgeNormal[0] != null) btn_Manipulator_8_toEdgeNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_8();
}
});
if (btn_Manipulator_9_toSurfaceNormal[0] != null) btn_Manipulator_9_toSurfaceNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_9();
}
});
if (btn_Manipulator_XIV_adjustRotationCenter[0] != null) btn_Manipulator_XIV_adjustRotationCenter[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XIV();
}
});
if (btn_Manipulator_XV_toVertexPosition[0] != null) btn_Manipulator_XV_toVertexPosition[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XV();
}
});
if (mntm_Manipulator_0_toOrigin[0] != null) mntm_Manipulator_0_toOrigin[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_0();
}
});
if (mntm_Manipulator_XIII_toWorld[0] != null) mntm_Manipulator_XIII_toWorld[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XIII();
}
});
if (mntm_Manipulator_X_XReverse[0] != null) mntm_Manipulator_X_XReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_X();
}
});
if (mntm_Manipulator_XI_YReverse[0] != null) mntm_Manipulator_XI_YReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XI();
}
});
if (mntm_Manipulator_XII_ZReverse[0] != null) mntm_Manipulator_XII_ZReverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XII();
}
});
if (mntm_Manipulator_SwitchXY[0] != null) mntm_Manipulator_SwitchXY[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XY();
}
});
if (mntm_Manipulator_SwitchXZ[0] != null) mntm_Manipulator_SwitchXZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XZ();
}
});
if (mntm_Manipulator_SwitchYZ[0] != null) mntm_Manipulator_SwitchYZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_YZ();
}
});
if (mntm_Manipulator_1_cameraToPos[0] != null) mntm_Manipulator_1_cameraToPos[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_1();
}
});
if (mntm_Manipulator_2_toAverage[0] != null) mntm_Manipulator_2_toAverage[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_2();
}
});
if (mntm_Manipulator_3_toSubfile[0] != null) mntm_Manipulator_3_toSubfile[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_3();
}
});
if (mntm_Manipulator_32_subfileTo[0] != null) mntm_Manipulator_32_subfileTo[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_32();
}
});
if (mntm_Manipulator_4_toVertex[0] != null) mntm_Manipulator_4_toVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_4();
}
});
if (mntm_Manipulator_5_toEdge[0] != null) mntm_Manipulator_5_toEdge[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_5();
}
});
if (mntm_Manipulator_6_toSurface[0] != null) mntm_Manipulator_6_toSurface[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_6();
}
});
if (mntm_Manipulator_7_toVertexNormal[0] != null) mntm_Manipulator_7_toVertexNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_7();
}
});
if (mntm_Manipulator_8_toEdgeNormal[0] != null) mntm_Manipulator_8_toEdgeNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_8();
}
});
if (mntm_Manipulator_9_toSurfaceNormal[0] != null) mntm_Manipulator_9_toSurfaceNormal[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_9();
}
});
if (mntm_Manipulator_XIV_adjustRotationCenter[0] != null) mntm_Manipulator_XIV_adjustRotationCenter[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XIV();
}
});
if (mntm_Manipulator_XV_toVertexPosition[0] != null) mntm_Manipulator_XV_toVertexPosition[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
mntm_Manipulator_XV();
}
});
mntm_SelectAll[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectAll(sels, true);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectAllVisible[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectAll(sels, false);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectAllWithColours[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectAllWithSameColours(sels, true);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectAllVisibleWithColours[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectAllWithSameColours(sels, false);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectNone[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.clearSelection();
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectInverse[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
loadSelectorSettings();
vm.selectInverse(sels);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_WithSameColour[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithSameOrientation[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
if (mntm_WithSameOrientation[0].getSelection()) {
new ValueDialog(getShell(), I18n.E3D_AngleDiff, I18n.E3D_ThreshInDeg) {
@Override
public void initializeSpinner() {
this.spn_Value[0].setMinimum(new BigDecimal("-90")); //$NON-NLS-1$
this.spn_Value[0].setMaximum(new BigDecimal("180")); //$NON-NLS-1$
this.spn_Value[0].setValue(sels.getAngle());
}
@Override
public void applyValue() {
sels.setAngle(this.spn_Value[0].getValue());
}
}.open();
}
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithAccuracy[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
if (mntm_WithAccuracy[0].getSelection()) {
new ValueDialog(getShell(), I18n.E3D_SetAccuracy, I18n.E3D_ThreshInLdu) {
@Override
public void initializeSpinner() {
this.spn_Value[0].setMinimum(new BigDecimal("0")); //$NON-NLS-1$
this.spn_Value[0].setMaximum(new BigDecimal("1000")); //$NON-NLS-1$
this.spn_Value[0].setValue(sels.getEqualDistance());
}
@Override
public void applyValue() {
sels.setEqualDistance(this.spn_Value[0].getValue());
}
}.open();
}
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithHiddenData[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithWholeSubfiles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_WithAdjacency[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_ExceptSubfiles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
mntm_SelectEverything[0].setEnabled(
mntm_WithHiddenData[0].getSelection() ||
mntm_WithSameColour[0].getSelection() ||
mntm_WithSameOrientation[0].getSelection() ||
mntm_ExceptSubfiles[0].getSelection()
);
mntm_WithWholeSubfiles[0].setEnabled(!mntm_ExceptSubfiles[0].getSelection());
showSelectMenu();
}
});
regainFocus();
}
});
mntm_StopAtEdges[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_STriangles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SQuads[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SCLines[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SVertices[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SLines[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
showSelectMenu();
}
});
regainFocus();
}
});
mntm_SelectEverything[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
sels.setScope(SelectorSettings.EVERYTHING);
loadSelectorSettings();
vm.selector(sels);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectConnected[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
sels.setScope(SelectorSettings.CONNECTED);
loadSelectorSettings();
vm.selector(sels);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectTouching[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
sels.setScope(SelectorSettings.TOUCHING);
loadSelectorSettings();
vm.selector(sels);
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectIsolatedVertices[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.selectIsolatedVertices();
vm.syncWithTextEditors(true);
regainFocus();
return;
}
}
}
});
regainFocus();
}
});
mntm_Split[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.split(2);
regainFocus();
return;
}
}
}
});
regainFocus();
}
});
mntm_SplitNTimes[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
final int[] frac = new int[]{2};
if (new ValueDialogInt(getShell(), I18n.E3D_SplitEdges, I18n.E3D_NumberOfFractions) {
@Override
public void initializeSpinner() {
this.spn_Value[0].setMinimum(2);
this.spn_Value[0].setMaximum(1000);
this.spn_Value[0].setValue(2);
}
@Override
public void applyValue() {
frac[0] = this.spn_Value[0].getValue();
}
}.open() == OK) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.split(frac[0]);
regainFocus();
return;
}
}
}
}
});
regainFocus();
}
});
mntm_Smooth[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Display.getCurrent().asyncExec(new Runnable() {
@Override
public void run() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
OpenGLRenderer.getSmoothing().set(true);
if (new SmoothDialog(getShell()).open() == OK) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.smooth(SmoothDialog.isX(), SmoothDialog.isY(), SmoothDialog.isZ(), SmoothDialog.getFactor(), SmoothDialog.getIterations());
regainFocus();
}
OpenGLRenderer.getSmoothing().set(false);
return;
}
}
}
});
regainFocus();
}
});
mntm_MergeToAverage[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.AVERAGE, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MergeToLastSelected[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.LAST_SELECTED, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MergeToNearestVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.NEAREST_VERTEX, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MergeToNearestEdge[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.NEAREST_EDGE, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MergeToNearestFace[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.merge(MergeTo.NEAREST_FACE, true);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SelectSingleVertex[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
final VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
final Set<Vertex> sv = vm.getSelectedVertices();
if (new VertexDialog(getShell()).open() == IDialogConstants.OK_ID) {
Vertex v = VertexDialog.getVertex();
if (vm.getVertices().contains(v)) {
sv.add(v);
vm.syncWithTextEditors(true);
}
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_setXYZ[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final boolean noReset = (e.stateMask & SWT.CTRL) != SWT.CTRL;
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
Vertex v = null;
final VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
final Set<Vertex> sv = vm.getSelectedVertices();
if (VertexManager.getClipboard().size() == 1) {
GData vertex = VertexManager.getClipboard().get(0);
if (vertex.type() == 0) {
String line = vertex.toString();
line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$
String[] data_segments = line.split("\\s+"); //$NON-NLS-1$
if (line.startsWith("0 !LPE")) { //$NON-NLS-1$
if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$
Vector3d start = new Vector3d();
boolean numberError = false;
if (data_segments.length == 6) {
try {
start.setX(new BigDecimal(data_segments[3], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setY(new BigDecimal(data_segments[4], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setZ(new BigDecimal(data_segments[5], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
} else {
numberError = true;
}
if (!numberError) {
v = new Vertex(start);
}
}
}
}
} else if (sv.size() == 1) {
v = sv.iterator().next();
}
final Vertex mani = new Vertex(c3d.getManipulator().getAccuratePosition());
if (new CoordinatesDialog(getShell(), v, mani).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
int coordCount = 0;
coordCount += CoordinatesDialog.isX() ? 1 : 0;
coordCount += CoordinatesDialog.isY() ? 1 : 0;
coordCount += CoordinatesDialog.isZ() ? 1 : 0;
if (coordCount == 1 && CoordinatesDialog.getStart() != null) {
TreeSet<Vertex> verts = new TreeSet<Vertex>();
verts.addAll(vm.getSelectedVertices());
vm.clearSelection();
for (Vertex v2 : verts) {
final boolean a = CoordinatesDialog.isX();
final boolean b = CoordinatesDialog.isY();
final boolean c = CoordinatesDialog.isZ();
vm.getSelectedVertices().add(v2);
Vector3d delta = Vector3d.sub(CoordinatesDialog.getEnd(), CoordinatesDialog.getStart());
boolean doMoveOnLine = false;
BigDecimal s = BigDecimal.ZERO;
Vector3d v1 = CoordinatesDialog.getStart();
if (CoordinatesDialog.isX() && delta.X.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.X.subtract(CoordinatesDialog.getStart().X).divide(delta.X, Threshold.mc);
} else if (CoordinatesDialog.isY() && delta.Y.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.Y.subtract(CoordinatesDialog.getStart().Y).divide(delta.Y, Threshold.mc);
} else if (CoordinatesDialog.isZ() && delta.Z.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.Z.subtract(CoordinatesDialog.getStart().Z).divide(delta.Z, Threshold.mc);
}
if (doMoveOnLine) {
CoordinatesDialog.setVertex(new Vertex(v1.X.add(delta.X.multiply(s)), v1.Y.add(delta.Y.multiply(s)), v1.Z.add(delta.Z.multiply(s))));
CoordinatesDialog.setX(true);
CoordinatesDialog.setY(true);
CoordinatesDialog.setZ(true);
}
vm.setXyzOrTranslateOrTransform(CoordinatesDialog.getVertex(), null, TransformationMode.SET, CoordinatesDialog.isX(), CoordinatesDialog.isY(), CoordinatesDialog.isZ(), isMovingAdjacentData() || vm.getSelectedVertices().size() == 1, true);
vm.clearSelection();
CoordinatesDialog.setX(a);
CoordinatesDialog.setY(b);
CoordinatesDialog.setZ(c);
}
}else if (coordCount == 2 && CoordinatesDialog.getStart() != null) {
TreeSet<Vertex> verts = new TreeSet<Vertex>();
verts.addAll(vm.getSelectedVertices());
vm.clearSelection();
for (Vertex v2 : verts) {
final boolean a = CoordinatesDialog.isX();
final boolean b = CoordinatesDialog.isY();
final boolean c = CoordinatesDialog.isZ();
vm.getSelectedVertices().add(v2);
Vector3d delta = Vector3d.sub(CoordinatesDialog.getEnd(), CoordinatesDialog.getStart());
boolean doMoveOnLine = false;
BigDecimal s = BigDecimal.ZERO;
Vector3d v1 = CoordinatesDialog.getStart();
if (CoordinatesDialog.isX() && delta.X.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.X.subtract(CoordinatesDialog.getStart().X).divide(delta.X, Threshold.mc);
} else if (CoordinatesDialog.isY() && delta.Y.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.Y.subtract(CoordinatesDialog.getStart().Y).divide(delta.Y, Threshold.mc);
} else if (CoordinatesDialog.isZ() && delta.Z.compareTo(BigDecimal.ZERO) != 0) {
doMoveOnLine = true;
s = v2.Z.subtract(CoordinatesDialog.getStart().Z).divide(delta.Z, Threshold.mc);
}
BigDecimal X = !CoordinatesDialog.isX() ? v1.X.add(delta.X.multiply(s)) : v2.X;
BigDecimal Y = !CoordinatesDialog.isY() ? v1.Y.add(delta.Y.multiply(s)) : v2.Y;
BigDecimal Z = !CoordinatesDialog.isZ() ? v1.Z.add(delta.Z.multiply(s)) : v2.Z;
if (doMoveOnLine) {
CoordinatesDialog.setVertex(new Vertex(X, Y, Z));
CoordinatesDialog.setX(true);
CoordinatesDialog.setY(true);
CoordinatesDialog.setZ(true);
}
vm.setXyzOrTranslateOrTransform(CoordinatesDialog.getVertex(), null, TransformationMode.SET, CoordinatesDialog.isX(), CoordinatesDialog.isY(), CoordinatesDialog.isZ(), isMovingAdjacentData() || vm.getSelectedVertices().size() == 1, true);
vm.clearSelection();
CoordinatesDialog.setX(a);
CoordinatesDialog.setY(b);
CoordinatesDialog.setZ(c);
}
} else {
vm.setXyzOrTranslateOrTransform(CoordinatesDialog.getVertex(), null, TransformationMode.SET, CoordinatesDialog.isX(), CoordinatesDialog.isY(), CoordinatesDialog.isZ(), isMovingAdjacentData() || vm.getSelectedVertices().size() == 1, true);
}
if (noReset) {
CoordinatesDialog.setStart(null);
CoordinatesDialog.setEnd(null);
}
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Translate[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
if (new TranslateDialog(getShell(), null).open() == IDialogConstants.OK_ID) {
c3d.getLockableDatFileReference().getVertexManager().addSnapshot();
c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(TranslateDialog.getOffset(), null, TransformationMode.TRANSLATE, TranslateDialog.isX(), TranslateDialog.isY(), TranslateDialog.isZ(), isMovingAdjacentData(), true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Rotate[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
TreeSet<Vertex> clipboard = new TreeSet<Vertex>();
if (VertexManager.getClipboard().size() == 1) {
GData vertex = VertexManager.getClipboard().get(0);
if (vertex.type() == 0) {
String line = vertex.toString();
line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$
String[] data_segments = line.split("\\s+"); //$NON-NLS-1$
if (line.startsWith("0 !LPE")) { //$NON-NLS-1$
if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$
Vector3d start = new Vector3d();
boolean numberError = false;
if (data_segments.length == 6) {
try {
start.setX(new BigDecimal(data_segments[3], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setY(new BigDecimal(data_segments[4], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setZ(new BigDecimal(data_segments[5], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
} else {
numberError = true;
}
if (!numberError) {
clipboard.add(new Vertex(start));
}
}
}
}
}
final Vertex mani = new Vertex(c3d.getManipulator().getAccuratePosition());
if (new RotateDialog(getShell(), null, clipboard, mani).open() == IDialogConstants.OK_ID) {
c3d.getLockableDatFileReference().getVertexManager().addSnapshot();
c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(RotateDialog.getAngles(), RotateDialog.getPivot(), TransformationMode.ROTATE, RotateDialog.isX(), RotateDialog.isY(), RotateDialog.isZ(), isMovingAdjacentData(), true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Scale[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
TreeSet<Vertex> clipboard = new TreeSet<Vertex>();
if (VertexManager.getClipboard().size() == 1) {
GData vertex = VertexManager.getClipboard().get(0);
if (vertex.type() == 0) {
String line = vertex.toString();
line = line.replaceAll("\\s+", " ").trim(); //$NON-NLS-1$ //$NON-NLS-2$
String[] data_segments = line.split("\\s+"); //$NON-NLS-1$
if (line.startsWith("0 !LPE")) { //$NON-NLS-1$
if (line.startsWith("VERTEX ", 7)) { //$NON-NLS-1$
Vector3d start = new Vector3d();
boolean numberError = false;
if (data_segments.length == 6) {
try {
start.setX(new BigDecimal(data_segments[3], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setY(new BigDecimal(data_segments[4], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
try {
start.setZ(new BigDecimal(data_segments[5], Threshold.mc));
} catch (NumberFormatException nfe) {
numberError = true;
}
} else {
numberError = true;
}
if (!numberError) {
clipboard.add(new Vertex(start));
}
}
}
}
}
final Vertex mani = new Vertex(c3d.getManipulator().getAccuratePosition());
if (new ScaleDialog(getShell(), null, clipboard, mani).open() == IDialogConstants.OK_ID) {
c3d.getLockableDatFileReference().getVertexManager().addSnapshot();
c3d.getLockableDatFileReference().getVertexManager().setXyzOrTranslateOrTransform(ScaleDialog.getScaleFactors(), ScaleDialog.getPivot(), TransformationMode.SCALE, ScaleDialog.isX(), ScaleDialog.isY(), ScaleDialog.isZ(), isMovingAdjacentData(), true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_PartReview[0].addSelectionListener(new SelectionAdapter() {
final Pattern WHITESPACE = Pattern.compile("\\s+"); //$NON-NLS-1$
final Pattern pattern = Pattern.compile("\r?\n|\r"); //$NON-NLS-1$
@Override
public void widgetSelected(SelectionEvent e) {
if (new PartReviewDialog(getShell()).open() == IDialogConstants.OK_ID) {
try {
new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(false, false, new IRunnableWithProgress() {
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask(I18n.E3D_PartReview, IProgressMonitor.UNKNOWN);
String fileName = PartReviewDialog.getFileName().toLowerCase(Locale.ENGLISH);
if (!fileName.endsWith(".dat")) fileName = fileName + ".dat"; //$NON-NLS-1$ //$NON-NLS-2$
String oldFileName = fileName;
try {
oldFileName = oldFileName.replaceAll("\\\\", File.separator); //$NON-NLS-1$
} catch (Exception ex) {
// Workaround for windows OS / JVM BUG
oldFileName = oldFileName.replace("\\", File.separator); //$NON-NLS-1$
}
try {
fileName = fileName.replaceAll("\\\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (Exception ex) {
// Workaround for windows OS / JVM BUG
fileName = fileName.replace("\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
}
// Download first, then build the views
// http://www.ldraw.org/library/unofficial
monitor.subTask(fileName);
String source = FileHelper.downloadPartFile("parts/" + fileName); //$NON-NLS-1$
if (source == null) source = FileHelper.downloadPartFile("parts/s/" + fileName); //$NON-NLS-1$
if (source == null) source = FileHelper.downloadPartFile("p/" + fileName); //$NON-NLS-1$
if (source == null) source = FileHelper.downloadPartFile("p/8/" + fileName); //$NON-NLS-1$
if (source == null) source = FileHelper.downloadPartFile("p/48/" + fileName); //$NON-NLS-1$
if (source == null) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setText(I18n.DIALOG_Error);
messageBox.setMessage(I18n.E3D_PartReviewError);
messageBox.open();
return;
}
HashSet<String> files = new HashSet<String>();
files.add(fileName);
ArrayList<String> list = buildFileList(source, new ArrayList<String>(), files, monitor);
final String fileName2 = fileName;
final String source2 = source;
final String oldFileName2 = oldFileName;
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
String fileName = fileName2;
String source = source2;
closeAllComposite3D();
for (EditorTextWindow txtwin : Project.getOpenTextWindows()) {
if (txtwin.isSeperateWindow()) {
txtwin.getShell().close();
} else {
txtwin.closeAllTabs();
}
}
Project.setDefaultProject(true);
Project.setProjectPath(new File("project").getAbsolutePath()); //$NON-NLS-1$
getShell().setText(Version.getApplicationName() + " " + Version.getVersion()); //$NON-NLS-1$
getShell().update();
treeItem_Project[0].setText(fileName);
treeItem_Project[0].setData(Project.getProjectPath());
treeItem_ProjectParts[0].getItems().clear();
treeItem_ProjectSubparts[0].getItems().clear();
treeItem_ProjectPrimitives[0].getItems().clear();
treeItem_OfficialParts[0].setData(null);
list.add(0, new File("project").getAbsolutePath() + File.separator + oldFileName2); //$NON-NLS-1$
list.add(1, source);
DatFile main = View.DUMMY_DATFILE;
HashSet<DatFile> dfsToOpen = new HashSet<DatFile>();
for (int i = list.size() - 2; i >= 0; i -= 2) {
DatFile df;
TreeItem n;
fileName = list.get(i);
source = list.get(i + 1);
df = new DatFile(fileName);
monitor.beginTask(fileName, IProgressMonitor.UNKNOWN);
Display.getCurrent().readAndDispatch();
dfsToOpen.add(df);
df.setText(source);
// Add / remove from unsaved files is mandatory!
Project.addUnsavedFile(df);
df.parseForData(true);
Project.removeUnsavedFile(df);
Project.getParsedFiles().remove(df);
if (source.contains("0 !LDRAW_ORG Unofficial_Subpart")) { //$NON-NLS-1$
int ind = fileName.lastIndexOf(File.separator + "s" + File.separator); //$NON-NLS-1$
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length() * 2 + 1, File.separator + "parts" + File.separator + "s" + File.separator).toString(); //$NON-NLS-1$ //$NON-NLS-2$
}
n = new TreeItem(treeItem_ProjectSubparts[0], SWT.NONE);
df.setType(DatType.SUBPART);
} else if (source.contains("0 !LDRAW_ORG Unofficial_Primitive")) { //$NON-NLS-1$
int ind = fileName.lastIndexOf(File.separator);
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length(), File.separator + "p" + File.separator).toString(); //$NON-NLS-1$
}
n = new TreeItem(treeItem_ProjectPrimitives[0], SWT.NONE);
df.setType(DatType.PRIMITIVE);
} else if (source.contains("0 !LDRAW_ORG Unofficial_48_Primitive")) { //$NON-NLS-1$
int ind = fileName.lastIndexOf(File.separator + "48" + File.separator); //$NON-NLS-1$
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length() * 2 + 2, File.separator + "p" + File.separator + "48" + File.separator).toString(); //$NON-NLS-1$ //$NON-NLS-2$
}
n = new TreeItem(treeItem_ProjectPrimitives48[0], SWT.NONE);
df.setType(DatType.PRIMITIVE48);
} else if (source.contains("0 !LDRAW_ORG Unofficial_8_Primitive")) { //$NON-NLS-1$
int ind = fileName.lastIndexOf(File.separator + "8" + File.separator); //$NON-NLS-1$
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length() * 2 + 1, File.separator + "p" + File.separator + "8" + File.separator).toString(); //$NON-NLS-1$ //$NON-NLS-2$
}
n = new TreeItem(treeItem_ProjectPrimitives8[0], SWT.NONE);
df.setType(DatType.PRIMITIVE8);
} else {
int ind = fileName.lastIndexOf(File.separator);
if (ind >= 0) {
fileName = new StringBuilder(fileName).replace(ind, ind + File.separator.length(), File.separator + "parts" + File.separator).toString(); //$NON-NLS-1$
}
n = new TreeItem(treeItem_ProjectParts[0], SWT.NONE);
df.setType(DatType.PART);
}
df.setNewName(fileName);
df.setOldName(fileName);
Project.addUnsavedFile(df);
Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
n.setText(fileName2);
n.setData(df);
if (i == 0) {
main = df;
}
}
dfsToOpen.remove(main);
resetSearch();
treeItem_Project[0].getParent().build();
treeItem_Project[0].getParent().redraw();
treeItem_Project[0].getParent().update();
{
int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights();
Editor3DWindow.getSashForm().getChildren()[1].dispose();
CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false, true, true, true);
cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]);
DatFile df = main;
Project.setFileToEdit(df);
cmp_Container.getComposite3D().setLockableDatFileReference(df);
Editor3DWindow.getSashForm().getParent().layout();
Editor3DWindow.getSashForm().setWeights(mainSashWeights);
SashForm s = cmp_Container.getComposite3D().getModifier().splitViewHorizontally();
((CompositeContainer) s.getChildren()[0]).getComposite3D().getModifier().splitViewVertically();
((CompositeContainer) s.getChildren()[1]).getComposite3D().getModifier().splitViewVertically();
}
int state = 0;
for (OpenGLRenderer renderer : getRenders()) {
Composite3D c3d = renderer.getC3D();
WidgetSelectionHelper.unselectAllChildButtons(c3d.mnu_renderMode);
if (state == 0) {
c3d.mntmNoBFC[0].setSelection(true);
c3d.getModifier().setRenderMode(0);
}
if (state == 1) {
c3d.mntmRandomColours[0].setSelection(true);
c3d.getModifier().setRenderMode(1);
}
if (state == 2) {
c3d.mntmCondlineMode[0].setSelection(true);
c3d.getModifier().setRenderMode(6);
}
if (state == 3) {
c3d.mntmWireframeMode[0].setSelection(true);
c3d.getModifier().setRenderMode(-1);
}
state++;
}
updateTree_unsavedEntries();
EditorTextWindow txt;
if (Project.getOpenTextWindows().isEmpty()) {
txt = new EditorTextWindow();
txt.run(main, false);
} else {
txt = Project.getOpenTextWindows().iterator().next();
}
for (DatFile df : dfsToOpen) {
txt.openNewDatFileTab(df, false);
}
regainFocus();
}
});
}
});
} catch (InvocationTargetException consumed) {
} catch (InterruptedException consumed) {
}
}
}
private ArrayList<String> buildFileList(String source, ArrayList<String> result, HashSet<String> files, final IProgressMonitor monitor) {
String[] lines;
lines = pattern.split(source, -1);
for (String line : lines) {
line = line.trim();
if (line.startsWith("1 ")) { //$NON-NLS-1$
final String[] data_segments = WHITESPACE.split(line.trim());
if (data_segments.length > 14) {
StringBuilder sb = new StringBuilder();
for (int s = 14; s < data_segments.length - 1; s++) {
sb.append(data_segments[s]);
sb.append(" "); //$NON-NLS-1$
}
sb.append(data_segments[data_segments.length - 1]);
String fileName = sb.toString();
fileName = fileName.toLowerCase(Locale.ENGLISH);
try {
fileName = fileName.replaceAll("\\\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (Exception e) {
// Workaround for windows OS / JVM BUG
fileName = fileName.replace("\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
}
if (files.contains(fileName)) continue;
files.add(fileName);
monitor.subTask(fileName);
String source2 = FileHelper.downloadPartFile("parts/" + fileName); //$NON-NLS-1$
if (source2 == null) source2 = FileHelper.downloadPartFile("parts/s/" + fileName); //$NON-NLS-1$
if (source2 == null) source2 = FileHelper.downloadPartFile("p/" + fileName); //$NON-NLS-1$
if (source2 != null) {
try {
fileName = fileName.replaceAll("/", File.separator); //$NON-NLS-1$
} catch (Exception ex) {
// Workaround for windows OS / JVM BUG
fileName = fileName.replace("/", File.separator); //$NON-NLS-1$
}
try {
fileName = fileName.replaceAll("\\\\", File.separator); //$NON-NLS-1$
} catch (Exception ex) {
// Workaround for windows OS / JVM BUG
fileName = fileName.replace("\\", File.separator); //$NON-NLS-1$
}
result.add(new File("project").getAbsolutePath() + File.separator + fileName); //$NON-NLS-1$
result.add(source2);
buildFileList(source2, result, files, monitor);
}
}
}
}
return result;
}
});
mntm_Edger2[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new EdgerDialog(getShell(), es).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.addEdges(es);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Rectifier[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new RectifierDialog(getShell(), rs).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.rectify(rs, true, true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Isecalc[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new IsecalcDialog(getShell(), is).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.isecalc(is);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SlicerPro[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new SlicerProDialog(getShell(), ss).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.slicerpro(ss);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Intersector[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new IntersectorDialog(getShell(), ins).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.intersector(ins, true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Lines2Pattern[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new Lines2PatternDialog(getShell()).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.lines2pattern();
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_PathTruder[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new PathTruderDialog(getShell(), ps).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.pathTruder(ps, true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SymSplitter[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new SymSplitterDialog(getShell(), sims).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.symSplitter(sims);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Unificator[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
if (new UnificatorDialog(getShell(), us).open() == IDialogConstants.OK_ID) {
vm.addSnapshot();
vm.unificator(us);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_RingsAndCones[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !c3d.getLockableDatFileReference().isReadOnly()) {
if (new RingsAndConesDialog(getShell(), ris).open() == IDialogConstants.OK_ID) {
c3d.getLockableDatFileReference().getVertexManager().addSnapshot();
RingsAndCones.solve(Editor3DWindow.getWindow().getShell(), c3d.getLockableDatFileReference(), cmp_Primitives[0].getPrimitives(), ris, true);
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_TJunctionFinder[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
if (df.equals(Project.getFileToEdit()) && !df.isReadOnly()) {
if (new TJunctionDialog(getShell(), tjs).open() == IDialogConstants.OK_ID) {
VertexManager vm = df.getVertexManager();
vm.addSnapshot();
vm.fixTjunctions(tjs.getMode());
}
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_MeshReducer[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
if (df.equals(Project.getFileToEdit()) && !df.isReadOnly()) {
VertexManager vm = df.getVertexManager();
vm.addSnapshot();
vm.meshReduce(0);
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_Txt2Dat[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
DatFile df = c3d.getLockableDatFileReference();
if (df.isReadOnly()) {
regainFocus();
return;
}
VertexManager vm = df.getVertexManager();
vm.addSnapshot();
if (new Txt2DatDialog(getShell(), ts).open() == IDialogConstants.OK_ID && !ts.getText().trim().isEmpty()) {
java.awt.Font myFont;
if (ts.getFontData() == null) {
myFont = new java.awt.Font(org.nschmidt.ldparteditor.enums.Font.MONOSPACE.getFontData()[0].getName(), java.awt.Font.PLAIN, 32);
} else {
FontData fd = ts.getFontData();
int style = 0;
final int c2 = SWT.BOLD | SWT.ITALIC;
switch (fd.getStyle()) {
case c2:
style = java.awt.Font.BOLD | java.awt.Font.ITALIC;
break;
case SWT.BOLD:
style = java.awt.Font.BOLD;
break;
case SWT.ITALIC:
style = java.awt.Font.ITALIC;
break;
case SWT.NORMAL:
style = java.awt.Font.PLAIN;
break;
}
myFont = new java.awt.Font(fd.getName(), style, fd.getHeight());
}
GData anchorData = df.getDrawChainTail();
int lineNumber = df.getDrawPerLine_NOCLONE().getKey(anchorData);
Set<GData> triangleSet = TextTriangulator.triangulateText(myFont, ts.getText().trim(), ts.getFlatness().doubleValue(), ts.getInterpolateFlatness().doubleValue(), View.DUMMY_REFERENCE, df, ts.getFontHeight().intValue(), ts.getDeltaAngle().doubleValue());
for (GData gda3 : triangleSet) {
lineNumber++;
df.getDrawPerLine_NOCLONE().put(lineNumber, gda3);
GData gdata = gda3;
anchorData.setNext(gda3);
anchorData = gdata;
}
anchorData.setNext(null);
df.setDrawChainTail(anchorData);
vm.setModified(true, true);
regainFocus();
return;
}
}
}
regainFocus();
}
});
// MARK Options
mntm_ResetSettingsOnRestart[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_Warning);
messageBox.setMessage(I18n.E3D_DeleteConfig);
int result = messageBox.open();
if (result == SWT.CANCEL) {
regainFocus();
return;
}
WorkbenchManager.getUserSettingState().setResetOnStart(true);
regainFocus();
}
});
mntm_Options[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
OptionsDialog dialog = new OptionsDialog(getShell());
dialog.run();
// KeyTableDialog dialog = new KeyTableDialog(getShell());
// if (dialog.open() == IDialogConstants.OK_ID) {
//
// }
regainFocus();
}
});
mntm_SelectAnotherLDConfig[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fd = new FileDialog(sh, SWT.OPEN);
fd.setText(I18n.E3D_OpenLDConfig);
fd.setFilterPath(WorkbenchManager.getUserSettingState().getLdrawFolderPath());
String[] filterExt = { "*.ldr", "LDConfig.ldr", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
fd.setFilterExtensions(filterExt);
String[] filterNames = { I18n.E3D_LDrawConfigurationFile1, I18n.E3D_LDrawConfigurationFile2, I18n.E3D_AllFiles };
fd.setFilterNames(filterNames);
String selected = fd.open();
System.out.println(selected);
if (selected != null && View.loadLDConfig(selected)) {
GData.CACHE_warningsAndErrors.clear();
WorkbenchManager.getUserSettingState().setLdConfigPath(selected);
Set<DatFile> dfs = new HashSet<DatFile>();
for (OpenGLRenderer renderer : renders) {
dfs.add(renderer.getC3D().getLockableDatFileReference());
}
for (DatFile df : dfs) {
df.getVertexManager().addSnapshot();
SubfileCompiler.compile(df, false, false);
}
}
regainFocus();
}
});
mntm_SavePalette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog dlg = new FileDialog(Editor3DWindow.getWindow().getShell(), SWT.SAVE);
dlg.setFilterPath(Project.getLastVisitedPath());
dlg.setFilterExtensions(new String[]{"*_pal.dat"}); //$NON-NLS-1$
dlg.setOverwrite(true);
// Change the title bar text
dlg.setText(I18n.E3D_PaletteSave);
// Calling open() will open and run the dialog.
// It will return the selected file, or
// null if user cancels
String newPath = dlg.open();
if (newPath != null) {
final File f = new File(newPath);
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
UTF8PrintWriter r = null;
try {
r = new UTF8PrintWriter(newPath);
int x = 0;
for (GColour col : WorkbenchManager.getUserSettingState().getUserPalette()) {
r.println("1 " + col + " " + x + " 0 0 1 0 0 0 1 0 0 0 1 rect.dat"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
x += 2;
}
r.flush();
r.close();
} catch (Exception ex) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
} finally {
if (r != null) {
r.close();
}
}
}
regainFocus();
}
});
mntm_LoadPalette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog dlg = new FileDialog(Editor3DWindow.getWindow().getShell(), SWT.OPEN);
dlg.setFilterPath(Project.getLastVisitedPath());
dlg.setFilterExtensions(new String[]{"*_pal.dat"}); //$NON-NLS-1$
dlg.setOverwrite(true);
// Change the title bar text
dlg.setText(I18n.E3D_PaletteLoad);
// Calling open() will open and run the dialog.
// It will return the selected file, or
// null if user cancels
String newPath = dlg.open();
if (newPath != null) {
final File f = new File(newPath);
if (f.getParentFile() != null) {
Project.setLastVisitedPath(f.getParentFile().getAbsolutePath());
}
final Pattern WHITESPACE = Pattern.compile("\\s+"); //$NON-NLS-1$
ArrayList<GColour> pal = WorkbenchManager.getUserSettingState().getUserPalette();
ArrayList<GColour> newPal = new ArrayList<GColour>();
UTF8BufferedReader reader = null;
try {
reader = new UTF8BufferedReader(newPath);
String line;
while ((line = reader.readLine()) != null) {
final String[] data_segments = WHITESPACE.split(line.trim());
if (data_segments.length > 1) {
GColour c = DatParser.validateColour(data_segments[1], 0f, 0f, 0f, 1f);
if (c != null) {
newPal.add(c.clone());
}
}
}
pal.clear();
pal.addAll(newPal);
} catch (LDParsingException ex) {
} catch (FileNotFoundException ex) {
} catch (UnsupportedEncodingException ex) {
} finally {
try {
if (reader != null)
reader.close();
} catch (LDParsingException ex2) {
}
}
reloadAllColours();
}
regainFocus();
}
});
mntm_SetPaletteSize[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final List<GColour> colours = WorkbenchManager.getUserSettingState().getUserPalette();
final int[] frac = new int[]{2};
if (new ValueDialogInt(getShell(), I18n.E3D_PaletteSetSize, "") { //$NON-NLS-1$
@Override
public void initializeSpinner() {
this.spn_Value[0].setMinimum(1);
this.spn_Value[0].setMaximum(100);
this.spn_Value[0].setValue(colours.size());
}
@Override
public void applyValue() {
frac[0] = this.spn_Value[0].getValue();
}
}.open() == OK) {
final boolean reBuild = frac[0] != colours.size();
if (frac[0] > colours.size()) {
while (frac[0] > colours.size()) {
if (colours.size() < 17) {
if (colours.size() == 8) {
colours.add(View.getLDConfigColour(72));
} else {
colours.add(View.getLDConfigColour(colours.size()));
}
} else {
colours.add(View.getLDConfigColour(16));
}
}
} else {
while (frac[0] < colours.size()) {
colours.remove(colours.size() - 1);
}
}
if (reBuild) {
reloadAllColours();
}
}
regainFocus();
}
});
mntm_ResetPalette[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final List<GColour> colours = WorkbenchManager.getUserSettingState().getUserPalette();
colours.clear();
while (colours.size() < 17) {
if (colours.size() == 8) {
colours.add(View.getLDConfigColour(72));
} else {
colours.add(View.getLDConfigColour(colours.size()));
}
}
reloadAllColours();
regainFocus();
}
});
mntm_UploadLogs[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String source = ""; //$NON-NLS-1$
{
UTF8BufferedReader b1 = null, b2 = null;
StringBuilder code = new StringBuilder();
File l1 = new File("error_log.txt");//$NON-NLS-1$
File l2 = new File("error_log2.txt");//$NON-NLS-1$
if (l1.exists() || l2.exists()) {
try {
if (l1.exists()) {
b1 = new UTF8BufferedReader("error_log.txt"); //$NON-NLS-1$
String line;
while ((line = b1.readLine()) != null) {
code.append(line);
code.append(StringHelper.getLineDelimiter());
}
}
if (l2.exists()) {
b2 = new UTF8BufferedReader("error_log2.txt"); //$NON-NLS-1$
String line;
while ((line = b2.readLine()) != null) {
code.append(line);
code.append(StringHelper.getLineDelimiter());
}
}
source = code.toString();
} catch (Exception e1) {
if (b1 != null) {
try {
b1.close();
} catch (Exception consumend) {}
}
if (b2 != null) {
try {
b2.close();
} catch (Exception consumend) {}
}
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setText(I18n.DIALOG_Error);
messageBox.setMessage(I18n.E3D_LogUploadUnexpectedException);
messageBox.open();
regainFocus();
return;
} finally {
if (b1 != null) {
try {
b1.close();
} catch (Exception consumend) {}
}
if (b2 != null) {
try {
b2.close();
} catch (Exception consumend) {}
}
}
} else {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_Info);
messageBox.setMessage(I18n.E3D_LogUploadNoLogFiles);
messageBox.open();
regainFocus();
return;
}
}
LogUploadDialog dialog = new LogUploadDialog(getShell(), source);
if (dialog.open() == IDialogConstants.OK_ID) {
UTF8BufferedReader b1 = null, b2 = null;
if (mntm_UploadLogs[0].getData() == null) {
mntm_UploadLogs[0].setData(0);
} else {
int uploadCount = (int) mntm_UploadLogs[0].getData();
uploadCount++;
if (uploadCount > 16) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_Warning);
messageBox.setMessage(I18n.E3D_LogUploadLimit);
messageBox.open();
regainFocus();
return;
}
mntm_UploadLogs[0].setData(uploadCount);
}
try {
Thread.sleep(2000);
String url = "http://pastebin.com/api/api_post.php"; //$NON-NLS-1$
String charset = StandardCharsets.UTF_8.name(); // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String title = "[LDPartEditor " + I18n.VERSION_Version + "]"; //$NON-NLS-1$ //$NON-NLS-2$
String devKey = "79cf77977cd2d798dd02f07d93b01ddb"; //$NON-NLS-1$
StringBuilder code = new StringBuilder();
File l1 = new File("error_log.txt");//$NON-NLS-1$
File l2 = new File("error_log2.txt");//$NON-NLS-1$
if (l1.exists() || l2.exists()) {
if (l1.exists()) {
b1 = new UTF8BufferedReader("error_log.txt"); //$NON-NLS-1$
String line;
while ((line = b1.readLine()) != null) {
code.append(line);
code.append(StringHelper.getLineDelimiter());
}
}
if (l2.exists()) {
b2 = new UTF8BufferedReader("error_log2.txt"); //$NON-NLS-1$
String line;
while ((line = b2.readLine()) != null) {
code.append(line);
code.append(StringHelper.getLineDelimiter());
}
}
String query = String.format("api_option=paste&api_user_key=%s&api_paste_private=%s&api_paste_name=%s&api_dev_key=%s&api_paste_code=%s", //$NON-NLS-1$
URLEncoder.encode("4cc892c8052bd17d805a1a2907ee8014", charset), //$NON-NLS-1$
URLEncoder.encode("0", charset),//$NON-NLS-1$
URLEncoder.encode(title, charset),
URLEncoder.encode(devKey, charset),
URLEncoder.encode(code.toString(), charset)
);
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset); //$NON-NLS-1$
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); //$NON-NLS-1$ //$NON-NLS-2$
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
BufferedReader response =new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); //$NON-NLS-1$
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_Info);
Object[] messageArguments = {response.readLine()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.E3D_LogUploadSuccess);
messageBox.setMessage(formatter.format(messageArguments));
messageBox.open();
} else {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setText(I18n.DIALOG_Info);
messageBox.setMessage(I18n.E3D_LogUploadNoLogFiles);
messageBox.open();
}
} catch (Exception e1) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setText(I18n.DIALOG_Info);
messageBox.setMessage(I18n.E3D_LogUploadUnexpectedException);
messageBox.open();
} finally {
if (b1 != null) {
try {
b1.close();
} catch (Exception consumend) {}
}
if (b2 != null) {
try {
b2.close();
} catch (Exception consumend) {}
}
}
}
regainFocus();
}
});
mntm_AntiAliasing[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setAntiAliasing(mntm_AntiAliasing[0].getSelection());
regainFocus();
}
});
// mntm_SyncWithTextEditor[0].addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent e) {
// WorkbenchManager.getUserSettingState().getSyncWithTextEditor().set(mntm_SyncWithTextEditor[0].getSelection());
// mntm_SyncLpeInline[0].setEnabled(mntm_SyncWithTextEditor[0].getSelection());
// regainFocus();
// }
// });
mntm_SyncLpeInline[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().getSyncWithLpeInline().set(mntm_SyncLpeInline[0].getSelection());
regainFocus();
}
});
// MARK Merge, split...
mntm_Flip[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.flipSelection();
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SubdivideCatmullClark[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.subdivideCatmullClark();
regainFocus();
return;
}
}
regainFocus();
}
});
mntm_SubdivideLoop[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.addSnapshot();
vm.subdivideLoop();
regainFocus();
return;
}
}
regainFocus();
}
});
// MARK Background PNG
btn_PngFocus[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Composite3D c3d = null;
for (OpenGLRenderer renderer : renders) {
c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d = c3d.getLockableDatFileReference().getLastSelectedComposite();
if (c3d == null) {
c3d = renderer.getC3D();
}
break;
}
}
if (c3d == null) {
regainFocus();
return;
}
c3d.setClassicPerspective(false);
WidgetSelectionHelper.unselectAllChildButtons(c3d.getViewAnglesMenu());
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Matrix4f tMatrix = new Matrix4f();
tMatrix.setIdentity();
tMatrix = tMatrix.scale(new Vector3f(png.scale.x, png.scale.y, png.scale.z));
Matrix4f dMatrix = new Matrix4f();
dMatrix.setIdentity();
Matrix4f.rotate((float) (png.angleB.doubleValue() / 180.0 * Math.PI), new Vector3f(1f, 0f, 0f), dMatrix, dMatrix);
Matrix4f.rotate((float) (png.angleA.doubleValue() / 180.0 * Math.PI), new Vector3f(0f, 1f, 0f), dMatrix, dMatrix);
Matrix4f.mul(dMatrix, tMatrix, tMatrix);
Vector4f vx = Matrix4f.transform(dMatrix, new Vector4f(png.offset.x, 0f, 0f, 1f), null);
Vector4f vy = Matrix4f.transform(dMatrix, new Vector4f(0f, png.offset.y, 0f, 1f), null);
Vector4f vz = Matrix4f.transform(dMatrix, new Vector4f(0f, 0f, png.offset.z, 1f), null);
Matrix4f transMatrix = new Matrix4f();
transMatrix.setIdentity();
transMatrix.m30 = -vx.x;
transMatrix.m31 = -vx.y;
transMatrix.m32 = -vx.z;
transMatrix.m30 -= vy.x;
transMatrix.m31 -= vy.y;
transMatrix.m32 -= vy.z;
transMatrix.m30 -= vz.x;
transMatrix.m31 -= vz.y;
transMatrix.m32 -= vz.z;
Matrix4f rotMatrixD = new Matrix4f();
rotMatrixD.setIdentity();
Matrix4f.rotate((float) (png.angleB.doubleValue() / 180.0 * Math.PI), new Vector3f(1f, 0f, 0f), rotMatrixD, rotMatrixD);
Matrix4f.rotate((float) (png.angleA.doubleValue() / 180.0 * Math.PI), new Vector3f(0f, 1f, 0f), rotMatrixD, rotMatrixD);
rotMatrixD = rotMatrixD.scale(new Vector3f(-1f, 1f, -1f));
rotMatrixD.invert();
c3d.getRotation().load(rotMatrixD);
c3d.getTranslation().load(transMatrix);
c3d.getPerspectiveCalculator().calculateOriginData();
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
regainFocus();
}
});
btn_PngImage[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
FileDialog fd = new FileDialog(getShell(), SWT.SAVE);
fd.setText(I18n.E3D_OpenPngImage);
try {
File f = new File(png.texturePath);
fd.setFilterPath(f.getParent());
fd.setFileName(f.getName());
} catch (Exception ex) {
}
String[] filterExt = { "*.png", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = { I18n.E3D_PortableNetworkGraphics, I18n.E3D_AllFiles};
fd.setFilterNames(filterNames);
String texturePath = fd.open();
if (texturePath != null) {
String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, png.scale, texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, png.scale, texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
}
return;
}
}
}
});
btn_PngNext[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
if (df.equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = df.getVertexManager();
GDataPNG sp = vm.getSelectedBgPicture();
boolean noBgPictures = df.hasNoBackgroundPictures();
vm.setSelectedBgPictureIndex(vm.getSelectedBgPictureIndex() + 1);
boolean indexOutOfBounds = vm.getSelectedBgPictureIndex() >= df.getBackgroundPictureCount();
boolean noRealData = df.getDrawPerLine_NOCLONE().getKey(sp) == null;
if (noBgPictures) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
} else {
if (indexOutOfBounds) vm.setSelectedBgPictureIndex(0);
if (noRealData) {
vm.setSelectedBgPictureIndex(0);
vm.setSelectedBgPicture(df.getBackgroundPicture(0));
} else {
vm.setSelectedBgPicture(df.getBackgroundPicture(vm.getSelectedBgPictureIndex()));
}
}
updateBgPictureTab();
}
}
regainFocus();
}
});
btn_PngPrevious[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
if (df.equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = df.getVertexManager();
GDataPNG sp = vm.getSelectedBgPicture();
boolean noBgPictures = df.hasNoBackgroundPictures();
vm.setSelectedBgPictureIndex(vm.getSelectedBgPictureIndex() - 1);
boolean indexOutOfBounds = vm.getSelectedBgPictureIndex() < 0;
boolean noRealData = df.getDrawPerLine_NOCLONE().getKey(sp) == null;
if (noBgPictures) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
} else {
if (indexOutOfBounds) vm.setSelectedBgPictureIndex(df.getBackgroundPictureCount() - 1);
if (noRealData) {
vm.setSelectedBgPictureIndex(0);
vm.setSelectedBgPicture(df.getBackgroundPicture(0));
} else {
vm.setSelectedBgPicture(df.getBackgroundPicture(vm.getSelectedBgPictureIndex()));
}
}
updateBgPictureTab();
}
}
regainFocus();
}
});
spn_PngA1[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
String newText = png.getString(png.offset, spn.getValue(), png.angleB, png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, spn.getValue(), png.angleB, png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngA2[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
String newText = png.getString(png.offset, png.angleA, spn.getValue(), png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, spn.getValue(), png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngA3[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
String newText = png.getString(png.offset, png.angleA, png.angleB, spn.getValue(), png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, spn.getValue(), png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngSX[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newScale = new Vertex(spn.getValue(), png.scale.Y, png.scale.Z);
String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngSY[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newScale = new Vertex(png.scale.X, spn.getValue(), png.scale.Z);
String newText = png.getString(png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, png.offset, png.angleA, png.angleB, png.angleC, newScale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngX[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newOffset = new Vertex(spn.getValue(), png.offset.Y, png.offset.Z);
String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngY[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newOffset = new Vertex(png.offset.X, spn.getValue(), png.offset.Z);
String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
spn_PngZ[0].addValueChangeListener(new ValueChangeAdapter() {
@Override
public void valueChanged(BigDecimalSpinner spn) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit()) && !Project.getFileToEdit().isReadOnly()) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (updatingPngPictureTab) return;
if (png == null) {
if (c3d.getLockableDatFileReference().hasNoBackgroundPictures()) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeAllTextures();
}
vm.addBackgroundPicture("", new Vertex(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO), BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new Vertex(BigDecimal.ONE, BigDecimal.ONE, BigDecimal.ONE), Project.getProjectPath() + File.separator + ".png"); //$NON-NLS-1$ //$NON-NLS-2$
vm.setModified(true, true);
}
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(0));
png = vm.getSelectedBgPicture();
updateBgPictureTab();
}
Vertex newOffset = new Vertex(png.offset.X, png.offset.Y, spn.getValue());
String newText = png.getString(newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
GDataPNG newPngPicture = new GDataPNG(newText, newOffset, png.angleA, png.angleB, png.angleC, png.scale, png.texturePath);
replaceBgPicture(png, newPngPicture, c3d.getLockableDatFileReference());
pngPictureUpdateCounter++;
if (pngPictureUpdateCounter > 3) {
for (OpenGLRenderer renderer2 : renders) {
renderer2.disposeOldTextures();
}
pngPictureUpdateCounter = 0;
}
vm.setModified(true, true);
vm.setSelectedBgPicture(c3d.getLockableDatFileReference().getBackgroundPicture(vm.getSelectedBgPictureIndex()));
return;
}
}
}
});
mntm_IconSize1[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(0);
regainFocus();
}
});
mntm_IconSize2[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(1);
regainFocus();
}
});
mntm_IconSize3[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(2);
regainFocus();
}
});
mntm_IconSize4[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(3);
regainFocus();
}
});
mntm_IconSize5[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(4);
regainFocus();
}
});
mntm_IconSize6[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setIconSize(5);
regainFocus();
}
});
Project.createDefault();
treeItem_Project[0].setData(Project.getProjectPath());
treeItem_Official[0].setData(WorkbenchManager.getUserSettingState().getLdrawFolderPath());
treeItem_Unofficial[0].setData(WorkbenchManager.getUserSettingState().getUnofficialFolderPath());
try {
new ProgressMonitorDialog(Editor3DWindow.getWindow().getShell()).run(true, false, new IRunnableWithProgress() {
@Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask(I18n.E3D_LoadingLibrary, IProgressMonitor.UNKNOWN);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
LibraryManager.readUnofficialParts(treeItem_UnofficialParts[0]);
LibraryManager.readUnofficialSubparts(treeItem_UnofficialSubparts[0]);
LibraryManager.readUnofficialPrimitives(treeItem_UnofficialPrimitives[0]);
LibraryManager.readUnofficialHiResPrimitives(treeItem_UnofficialPrimitives48[0]);
LibraryManager.readUnofficialLowResPrimitives(treeItem_UnofficialPrimitives8[0]);
LibraryManager.readOfficialParts(treeItem_OfficialParts[0]);
LibraryManager.readOfficialSubparts(treeItem_OfficialSubparts[0]);
LibraryManager.readOfficialPrimitives(treeItem_OfficialPrimitives[0]);
LibraryManager.readOfficialHiResPrimitives(treeItem_OfficialPrimitives48[0]);
LibraryManager.readOfficialLowResPrimitives(treeItem_OfficialPrimitives8[0]);
}
});
Thread.sleep(1500);
}
});
} catch (InvocationTargetException consumed) {
} catch (InterruptedException consumed) {
}
tabFolder_OpenDatFiles[0].getItem(0).setData(View.DUMMY_DATFILE);
tabFolder_OpenDatFiles[0].getItem(1).setData(Project.getFileToEdit());
Project.addOpenedFile(Project.getFileToEdit());
tabFolder_OpenDatFiles[0].addCTabFolder2Listener(new CTabFolder2Listener() {
@Override
public void showList(CTabFolderEvent event) {}
@Override
public void restore(CTabFolderEvent event) {}
@Override
public void minimize(CTabFolderEvent event) {}
@Override
public void maximize(CTabFolderEvent event) {
// TODO Auto-generated method stub
}
@Override
public void close(CTabFolderEvent event) {
DatFile df = null;
if (tabFolder_OpenDatFiles[0].getSelection() != null && (df = (DatFile) tabFolder_OpenDatFiles[0].getSelection().getData()) != null) {
if (df.equals(View.DUMMY_DATFILE)) {
event.doit = false;
} else {
Project.removeOpenedFile(df);
if (!closeDatfile(df)) {
Project.addOpenedFile(df);
updateTabs();
}
Editor3DWindow.getWindow().getShell().forceFocus();
regainFocus();
}
}
}
});
tabFolder_OpenDatFiles[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Editor3DWindow.getNoSyncDeadlock().compareAndSet(false, true)) {
if (tabFolder_OpenDatFiles[0].getData() != null) {
Editor3DWindow.getNoSyncDeadlock().set(false);
return;
}
DatFile df = null;
if (tabFolder_OpenDatFiles[0].getSelection() != null && (df = (DatFile) tabFolder_OpenDatFiles[0].getSelection().getData()) != null) {
openFileIn3DEditor(df);
if (!df.equals(View.DUMMY_DATFILE) && WorkbenchManager.getUserSettingState().isSyncingTabs()) {
boolean fileIsOpenInTextEditor = false;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
fileIsOpenInTextEditor = true;
}
if (fileIsOpenInTextEditor) break;
}
if (fileIsOpenInTextEditor) break;
}
if (fileIsOpenInTextEditor) {
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (final CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
w.getTabFolder().setSelection(t);
((CompositeTab) t).getControl().getShell().forceActive();
if (w.isSeperateWindow()) {
w.open();
}
}
}
}
} else if (Project.getOpenTextWindows().isEmpty()) {
openDatFile(df, OpenInWhat.EDITOR_TEXT, null);
} else {
Project.getOpenTextWindows().iterator().next().openNewDatFileTab(df, false);
}
}
cleanupClosedData();
regainFocus();
}
Editor3DWindow.getNoSyncDeadlock().set(false);
}
}
});
btn_SyncTabs[0].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
WorkbenchManager.getUserSettingState().setSyncingTabs(btn_SyncTabs[0].getSelection());
}
});
txt_Search[0].setText(" "); //$NON-NLS-1$
txt_Search[0].setText(""); //$NON-NLS-1$
Project.getFileToEdit().setLastSelectedComposite(Editor3DWindow.renders.get(0).getC3D());
new EditorTextWindow().run(Project.getFileToEdit(), true);
updateBgPictureTab();
Project.getFileToEdit().addHistory();
this.open();
// Dispose all resources (never delete this!)
ResourceManager.dispose();
SWTResourceManager.dispose();
// Dispose the display (never delete this, too!)
Display.getCurrent().dispose();
}
protected void addRecentFile(String projectPath) {
final int index = recentItems.indexOf(projectPath);
if (index > -1) {
recentItems.remove(index);
} else if (recentItems.size() > 20) {
recentItems.remove(0);
}
recentItems.add(projectPath);
}
public void addRecentFile(DatFile dat) {
addRecentFile(dat.getNewName());
}
private void replaceBgPicture(GDataPNG selectedBgPicture, GDataPNG newBgPicture, DatFile linkedDatFile) {
if (linkedDatFile.getDrawPerLine_NOCLONE().getKey(selectedBgPicture) == null) return;
GData before = selectedBgPicture.getBefore();
GData next = selectedBgPicture.getNext();
int index = linkedDatFile.getDrawPerLine_NOCLONE().getKey(selectedBgPicture);
selectedBgPicture.setGoingToBeReplaced(true);
linkedDatFile.getVertexManager().remove(selectedBgPicture);
linkedDatFile.getDrawPerLine_NOCLONE().put(index, newBgPicture);
before.setNext(newBgPicture);
newBgPicture.setNext(next);
linkedDatFile.getVertexManager().setSelectedBgPicture(newBgPicture);
updateBgPictureTab();
return;
}
private void resetAddState() {
setAddingSubfiles(false);
setAddingVertices(false);
setAddingLines(false);
setAddingTriangles(false);
setAddingQuads(false);
setAddingCondlines(false);
setAddingDistance(false);
setAddingProtractor(false);
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
DatFile df = c3d.getLockableDatFileReference();
df.setObjVertex1(null);
df.setObjVertex2(null);
df.setObjVertex3(null);
df.setObjVertex4(null);
df.setNearestObjVertex1(null);
df.setNearestObjVertex2(null);
}
}
public void setAddState(int type) {
if (isAddingSomething()) {
resetAddState();
btn_AddVertex[0].setSelection(false);
btn_AddLine[0].setSelection(false);
btn_AddTriangle[0].setSelection(false);
btn_AddQuad[0].setSelection(false);
btn_AddCondline[0].setSelection(false);
btn_AddDistance[0].setSelection(false);
btn_AddProtractor[0].setSelection(false);
btn_AddPrimitive[0].setSelection(false);
setAddingSomething(false);
}
switch (type) {
case 0:
btn_AddComment[0].notifyListeners(SWT.Selection, new Event());
break;
case 1:
setAddingVertices(!isAddingVertices());
btn_AddVertex[0].setSelection(isAddingVertices());
setAddingSomething(isAddingVertices());
clickSingleBtn(btn_AddVertex[0]);
break;
case 2:
setAddingLines(!isAddingLines());
btn_AddLine[0].setSelection(isAddingLines());
setAddingSomething(isAddingLines());
clickSingleBtn(btn_AddLine[0]);
break;
case 3:
setAddingTriangles(!isAddingTriangles());
btn_AddTriangle[0].setSelection(isAddingTriangles());
setAddingSomething(isAddingTriangles());
clickSingleBtn(btn_AddTriangle[0]);
break;
case 4:
setAddingQuads(!isAddingQuads());
btn_AddQuad[0].setSelection(isAddingQuads());
setAddingSomething(isAddingQuads());
clickSingleBtn(btn_AddQuad[0]);
break;
case 5:
setAddingCondlines(!isAddingCondlines());
btn_AddCondline[0].setSelection(isAddingCondlines());
setAddingSomething(isAddingCondlines());
clickSingleBtn(btn_AddCondline[0]);
case 6:
setAddingDistance(!isAddingDistance());
btn_AddDistance[0].setSelection(isAddingDistance());
setAddingSomething(isAddingDistance());
clickSingleBtn(btn_AddDistance[0]);
break;
case 7:
setAddingProtractor(!isAddingProtractor());
btn_AddProtractor[0].setSelection(isAddingProtractor());
setAddingSomething(isAddingProtractor());
clickSingleBtn(btn_AddProtractor[0]);
break;
}
}
public void toggleInsertAtCursor() {
setInsertingAtCursorPosition(!isInsertingAtCursorPosition());
btn_InsertAtCursorPosition[0].setSelection(isInsertingAtCursorPosition());
clickSingleBtn(btn_InsertAtCursorPosition[0]);
}
public void setObjMode(int type) {
switch (type) {
case 0:
btn_Vertices[0].setSelection(true);
setWorkingType(ObjectMode.VERTICES);
clickSingleBtn(btn_Vertices[0]);
break;
case 1:
btn_TrisNQuads[0].setSelection(true);
setWorkingType(ObjectMode.FACES);
clickSingleBtn(btn_TrisNQuads[0]);
break;
case 2:
btn_Lines[0].setSelection(true);
setWorkingType(ObjectMode.LINES);
clickSingleBtn(btn_Lines[0]);
break;
case 3:
btn_Subfiles[0].setSelection(true);
setWorkingType(ObjectMode.SUBFILES);
clickSingleBtn(btn_Subfiles[0]);
break;
}
}
/**
* The Shell-Close-Event
*/
@Override
protected void handleShellCloseEvent() {
boolean unsavedProjectFiles = false;
Set<DatFile> unsavedFiles = new HashSet<DatFile>(Project.getUnsavedFiles());
for (DatFile df : unsavedFiles) {
final String text = df.getText();
if ((!text.equals(df.getOriginalText()) || df.isVirtual() && !text.trim().isEmpty()) && !text.equals(WorkbenchManager.getDefaultFileHeader())) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO);
messageBox.setText(I18n.DIALOG_UnsavedChangesTitle);
Object[] messageArguments = {df.getShortName()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_UnsavedChanges);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.NO) {
// Remove file from tree
updateTree_removeEntry(df);
} else if (result == SWT.YES) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
cleanupClosedData();
updateTree_unsavedEntries();
return;
}
} else {
cleanupClosedData();
updateTree_unsavedEntries();
return;
}
}
}
Set<EditorTextWindow> ow = new HashSet<EditorTextWindow>(Project.getOpenTextWindows());
for (EditorTextWindow w : ow) {
if (w.isSeperateWindow()) {
w.getShell().close();
} else {
w.closeAllTabs();
}
}
{
ArrayList<TreeItem> ta = getProjectParts().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); //$NON-NLS-1$
}
}
{
ArrayList<TreeItem> ta = getProjectSubparts().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$
}
}
{
ArrayList<TreeItem> ta = getProjectPrimitives().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$
}
}
{
ArrayList<TreeItem> ta = getProjectPrimitives48().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$
}
}
{
ArrayList<TreeItem> ta = getProjectPrimitives8().getItems();
for (TreeItem ti : ta) {
unsavedProjectFiles = unsavedProjectFiles || !((DatFile) ti.getData()).getText().trim().equals("") || !Project.getUnsavedFiles().contains(ti.getData()); ; //$NON-NLS-1$
}
}
final boolean ENABLE_DEFAULT_PROJECT_SAVE = !(Math.random() + 1 > 0);
if (unsavedProjectFiles && Project.isDefaultProject() && ENABLE_DEFAULT_PROJECT_SAVE) {
// Save new project here, if the project contains at least one non-empty file
boolean cancelIt = false;
boolean secondRun = false;
while (true) {
int result = IDialogConstants.CANCEL_ID;
if (secondRun) result = new NewProjectDialog(true).open();
if (result == IDialogConstants.OK_ID) {
while (new File(Project.getTempProjectPath()).isDirectory()) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.YES | SWT.CANCEL | SWT.NO);
messageBoxError.setText(I18n.PROJECT_ProjectOverwriteTitle);
messageBoxError.setMessage(I18n.PROJECT_ProjectOverwrite);
int result2 = messageBoxError.open();
if (result2 == SWT.NO) {
result = new NewProjectDialog(true).open();
} else if (result2 == SWT.YES) {
break;
} else {
cancelIt = true;
break;
}
}
if (!cancelIt) {
Project.setProjectName(Project.getTempProjectName());
Project.setProjectPath(Project.getTempProjectPath());
NLogger.debug(getClass(), "Saving new project..."); //$NON-NLS-1$
if (!Project.save()) {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveProject);
}
}
break;
} else {
secondRun = true;
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO);
messageBox.setText(I18n.DIALOG_UnsavedChangesTitle);
Object[] messageArguments = {I18n.DIALOG_TheNewProject};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_UnsavedChanges);
messageBox.setMessage(formatter.format(messageArguments));
int result2 = messageBox.open();
if (result2 == SWT.CANCEL) {
cancelIt = true;
break;
} else if (result2 == SWT.NO) {
break;
}
}
}
if (cancelIt) {
cleanupClosedData();
updateTree_unsavedEntries();
return;
}
}
// NEVER DELETE THIS!
final int s = renders.size();
for (int i = 0; i < s; i++) {
try {
GLCanvas canvas = canvasList.get(i);
OpenGLRenderer renderer = renders.get(i);
if (!canvas.isCurrent()) {
canvas.setCurrent();
try {
GLContext.useContext(canvas);
} catch (LWJGLException e) {
NLogger.error(Editor3DWindow.class, e);
}
}
renderer.dispose();
} catch (SWTException swtEx) {
NLogger.error(Editor3DWindow.class, swtEx);
}
}
// All "history threads" needs to know that the main window was closed
alive.set(false);
final Editor3DWindowState winState = WorkbenchManager.getEditor3DWindowState();
// Traverse the sash forms to store the 3D configuration
final ArrayList<Composite3DState> c3dStates = new ArrayList<Composite3DState>();
Control c = Editor3DDesign.getSashForm().getChildren()[1];
if (c != null) {
if (c instanceof SashForm|| c instanceof CompositeContainer) {
// c instanceof CompositeContainer: Simple case, since its only one 3D view open -> No recursion!
saveComposite3DStates(c, c3dStates, "", "|"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
// There is no 3D window open at the moment
}
} else {
// There is no 3D window open at the moment
}
winState.setThreeDwindowConfig(c3dStates);
winState.setLeftSashWeights(((SashForm) Editor3DDesign.getSashForm().getChildren()[0]).getWeights());
winState.setLeftSashWidth(Editor3DDesign.getSashForm().getWeights());
winState.setPrimitiveZoom(cmp_Primitives[0].getZoom());
winState.setPrimitiveZoomExponent(cmp_Primitives[0].getZoom_exponent());
winState.setPrimitiveViewport(cmp_Primitives[0].getViewport2());
WorkbenchManager.getPrimitiveCache().setPrimitiveCache(CompositePrimitive.getCache());
WorkbenchManager.getPrimitiveCache().setPrimitiveFileCache(CompositePrimitive.getFileCache());
WorkbenchManager.getUserSettingState().setRecentItems(getRecentItems());
// Save the workbench
WorkbenchManager.saveWorkbench();
setReturnCode(CANCEL);
close();
}
private void saveComposite3DStates(Control c, ArrayList<Composite3DState> c3dStates, String parentPath, String path) {
Composite3DState st = new Composite3DState();
st.setParentPath(parentPath);
st.setPath(path);
if (c instanceof CompositeContainer) {
NLogger.debug(getClass(), "{0}C", path); //$NON-NLS-1$
final Composite3D c3d = ((CompositeContainer) c).getComposite3D();
st.setSash(false);
st.setScales(c3d.getParent() instanceof CompositeScale);
st.setVertical(false);
st.setWeights(null);
fillC3DState(st, c3d);
} else if (c instanceof SashForm) {
NLogger.debug(getClass(), path);
SashForm s = (SashForm) c;
st.setSash(true);
st.setVertical((s.getStyle() & SWT.VERTICAL) != 0);
st.setWeights(s.getWeights());
Control c1 = s.getChildren()[0];
Control c2 = s.getChildren()[1];
saveComposite3DStates(c1, c3dStates, path, path + "s1|"); //$NON-NLS-1$
saveComposite3DStates(c2, c3dStates, path, path + "s2|"); //$NON-NLS-1$
} else {
return;
}
c3dStates.add(st);
}
public void fillC3DState(Composite3DState st, Composite3D c3d) {
st.setPerspective(c3d.isClassicPerspective() ? c3d.getPerspectiveIndex() : Perspective.TWO_THIRDS);
st.setRenderMode(c3d.getRenderMode());
st.setShowLabel(c3d.isShowingLabels());
st.setShowAxis(c3d.isShowingAxis());
st.setShowGrid(c3d.isGridShown());
st.setShowOrigin(c3d.isOriginShown());
st.setLights(c3d.isLightOn());
st.setMeshlines(c3d.isMeshLines());
st.setSubfileMeshlines(c3d.isSubMeshLines());
st.setVertices(c3d.isShowingVertices());
st.setCondlineControlPoints(c3d.isShowingCondlineControlPoints());
st.setHiddenVertices(c3d.isShowingHiddenVertices());
st.setStudLogo(c3d.isShowingLogo());
st.setLineMode(c3d.getLineMode());
st.setAlwaysBlackLines(c3d.isBlackEdges());
st.setAnaglyph3d(c3d.isAnaglyph3d());
st.setGridScale(c3d.getGrid_scale());
st.setSyncManipulator(c3d.isSyncManipulator());
st.setSyncTranslation(c3d.isSyncTranslation());
st.setSyncZoom(c3d.isSyncZoom());
}
/**
* @return The serializable window state of the Editor3DWindow
*/
public Editor3DWindowState getEditor3DWindowState() {
return this.editor3DWindowState;
}
/**
* @param editor3DWindowState
* The serializable window state of the Editor3DWindow
*/
public void setEditor3DWindowState(Editor3DWindowState editor3DWindowState) {
this.editor3DWindowState = editor3DWindowState;
}
/**
* @return The current Editor3DWindow instance
*/
public static Editor3DWindow getWindow() {
return Editor3DWindow.window;
}
/**
* Updates the tree for new unsaved entries
*/
public void updateTree_unsavedEntries() {
ArrayList<TreeItem> categories = new ArrayList<TreeItem>();
categories.add(this.treeItem_ProjectParts[0]);
categories.add(this.treeItem_ProjectSubparts[0]);
categories.add(this.treeItem_ProjectPrimitives[0]);
categories.add(this.treeItem_ProjectPrimitives48[0]);
categories.add(this.treeItem_ProjectPrimitives8[0]);
categories.add(this.treeItem_UnofficialParts[0]);
categories.add(this.treeItem_UnofficialSubparts[0]);
categories.add(this.treeItem_UnofficialPrimitives[0]);
categories.add(this.treeItem_UnofficialPrimitives48[0]);
categories.add(this.treeItem_UnofficialPrimitives8[0]);
int counter = 0;
for (TreeItem item : categories) {
counter++;
ArrayList<TreeItem> datFileTreeItems = item.getItems();
for (TreeItem df : datFileTreeItems) {
DatFile d = (DatFile) df.getData();
StringBuilder nameSb = new StringBuilder(new File(d.getNewName()).getName());
final String d2 = d.getDescription();
if (counter < 6 && (!d.getNewName().startsWith(Project.getProjectPath()) || !d.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$
nameSb.insert(0, "(!) "); //$NON-NLS-1$
}
// MARK For Debug Only!
// DatType t = d.getType();
// if (t == DatType.PART) {
// nameSb.append(" PART"); //$NON-NLS-1$
// } else if (t == DatType.SUBPART) {
// nameSb.append(" SUBPART"); //$NON-NLS-1$
// } else if (t == DatType.PRIMITIVE) {
// nameSb.append(" PRIMITIVE"); //$NON-NLS-1$
// } else if (t == DatType.PRIMITIVE48) {
// nameSb.append(" PRIMITIVE48"); //$NON-NLS-1$
// } else if (t == DatType.PRIMITIVE8) {
// nameSb.append(" PRIMITIVE8"); //$NON-NLS-1$
// }
if (d2 != null)
nameSb.append(d2);
if (Project.getUnsavedFiles().contains(d)) {
df.setText("* " + nameSb.toString()); //$NON-NLS-1$
} else {
df.setText(nameSb.toString());
}
}
}
this.treeItem_Unsaved[0].removeAll();
Set<DatFile> unsaved = Project.getUnsavedFiles();
for (DatFile df : unsaved) {
TreeItem ti = new TreeItem(this.treeItem_Unsaved[0], SWT.NONE);
StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName());
final String d = df.getDescription();
if (d != null)
nameSb.append(d);
ti.setText(nameSb.toString());
ti.setData(df);
}
this.treeParts[0].build();
this.treeParts[0].redraw();
updateTabs();
}
/**
* Updates the tree for new unsaved entries
*/
public void updateTree_selectedDatFile(DatFile sdf) {
ArrayList<TreeItem> categories = new ArrayList<TreeItem>();
categories.add(this.treeItem_ProjectParts[0]);
categories.add(this.treeItem_ProjectSubparts[0]);
categories.add(this.treeItem_ProjectPrimitives[0]);
categories.add(this.treeItem_ProjectPrimitives48[0]);
categories.add(this.treeItem_ProjectPrimitives8[0]);
categories.add(this.treeItem_UnofficialParts[0]);
categories.add(this.treeItem_UnofficialSubparts[0]);
categories.add(this.treeItem_UnofficialPrimitives[0]);
categories.add(this.treeItem_UnofficialPrimitives48[0]);
categories.add(this.treeItem_UnofficialPrimitives8[0]);
categories.add(this.treeItem_OfficialParts[0]);
categories.add(this.treeItem_OfficialSubparts[0]);
categories.add(this.treeItem_OfficialPrimitives[0]);
categories.add(this.treeItem_OfficialPrimitives48[0]);
categories.add(this.treeItem_OfficialPrimitives8[0]);
for (TreeItem item : categories) {
ArrayList<TreeItem> datFileTreeItems = item.getItems();
for (TreeItem df : datFileTreeItems) {
DatFile d = (DatFile) df.getData();
if (d.equals(sdf)) {
item.setVisible(true);
item.getParentItem().setVisible(true);
this.treeParts[0].build();
this.treeParts[0].setSelection(df);
this.treeParts[0].redraw();
updateTabs();
return;
}
}
}
updateTabs();
}
/**
* Updates the tree for renamed entries
*/
@SuppressWarnings("unchecked")
public void updateTree_renamedEntries() {
HashMap<String, TreeItem> categories = new HashMap<String, TreeItem>();
HashMap<String, DatType> types = new HashMap<String, DatType>();
ArrayList<String> validPrefixes = new ArrayList<String>();
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS" + File.separator + "S" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialSubparts[0]);
types.put(s, DatType.SUBPART);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts" + File.separator + "s" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialSubparts[0]);
types.put(s, DatType.SUBPART);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "PARTS" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialParts[0]);
types.put(s, DatType.PART);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "parts" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s,this.treeItem_UnofficialParts[0]);
types.put(s, DatType.PART);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives48[0]);
types.put(s, DatType.PRIMITIVE48);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives48[0]);
types.put(s, DatType.PRIMITIVE48);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives8[0]);
types.put(s, DatType.PRIMITIVE8);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives8[0]);
types.put(s, DatType.PRIMITIVE8);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "P" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives[0]);
types.put(s, DatType.PRIMITIVE);
}
{
String s = WorkbenchManager.getUserSettingState().getUnofficialFolderPath() + File.separator + "p" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_UnofficialPrimitives[0]);
types.put(s, DatType.PRIMITIVE);
}
{
String s = Project.getProjectPath() + File.separator + "PARTS" + File.separator + "S" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectSubparts[0]);
types.put(s, DatType.SUBPART);
}
{
String s = Project.getProjectPath() + File.separator + "parts" + File.separator + "s" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectSubparts[0]);
types.put(s, DatType.SUBPART);
}
{
String s = Project.getProjectPath() + File.separator + "PARTS" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectParts[0]);
types.put(s, DatType.PART);
}
{
String s = Project.getProjectPath() + File.separator + "parts" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectParts[0]);
types.put(s, DatType.PART);
}
{
String s = Project.getProjectPath() + File.separator + "P" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives48[0]);
types.put(s, DatType.PRIMITIVE48);
}
{
String s = Project.getProjectPath() + File.separator + "p" + File.separator + "48" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives48[0]);
types.put(s, DatType.PRIMITIVE48);
}
{
String s = Project.getProjectPath() + File.separator + "P" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives8[0]);
types.put(s, DatType.PRIMITIVE8);
}
{
String s = Project.getProjectPath() + File.separator + "p" + File.separator + "8" + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives8[0]);
types.put(s, DatType.PRIMITIVE8);
}
{
String s = Project.getProjectPath() + File.separator + "P" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives[0]);
types.put(s, DatType.PRIMITIVE);
}
{
String s = Project.getProjectPath() + File.separator + "p" + File.separator; //$NON-NLS-1$
validPrefixes.add(s);
categories.put(s, this.treeItem_ProjectPrimitives[0]);
types.put(s, DatType.PRIMITIVE);
}
Collections.sort(validPrefixes, new Comp());
for (String prefix : validPrefixes) {
TreeItem item = categories.get(prefix);
ArrayList<DatFile> dats = (ArrayList<DatFile>) item.getData();
ArrayList<TreeItem> datFileTreeItems = item.getItems();
Set<TreeItem> itemsToRemove = new HashSet<TreeItem>();
for (TreeItem df : datFileTreeItems) {
DatFile d = (DatFile) df.getData();
String newName = d.getNewName();
String validPrefix = null;
for (String p2 : validPrefixes) {
if (newName.startsWith(p2)) {
validPrefix = p2;
break;
}
}
if (validPrefix != null) {
TreeItem item2 = categories.get(validPrefix);
if (!item2.equals(item)) {
itemsToRemove.add(df);
dats.remove(d);
((ArrayList<DatFile>) item2.getData()).add(d);
TreeItem nt = new TreeItem(item2, SWT.NONE);
nt.setText(df.getText());
d.setType(types.get(validPrefix));
nt.setData(d);
}
}
}
datFileTreeItems.removeAll(itemsToRemove);
}
this.treeParts[0].build();
this.treeParts[0].redraw();
updateTabs();
}
private class Comp implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if (o1.length() < o2.length()) {
return 1;
} else if (o1.length() > o2.length()) {
return -1;
} else {
return 0;
}
}
}
/**
* Removes an item from the tree,<br><br>
* If it is open in a {@linkplain Composite3D}, this composite will be linked with a dummy file
* If it is open in a {@linkplain CompositeTab}, this composite will be closed
*
*/
public void updateTree_removeEntry(DatFile e) {
ArrayList<TreeItem> categories = new ArrayList<TreeItem>();
categories.add(this.treeItem_ProjectParts[0]);
categories.add(this.treeItem_ProjectSubparts[0]);
categories.add(this.treeItem_ProjectPrimitives[0]);
categories.add(this.treeItem_ProjectPrimitives8[0]);
categories.add(this.treeItem_ProjectPrimitives48[0]);
categories.add(this.treeItem_UnofficialParts[0]);
categories.add(this.treeItem_UnofficialSubparts[0]);
categories.add(this.treeItem_UnofficialPrimitives[0]);
categories.add(this.treeItem_UnofficialPrimitives8[0]);
categories.add(this.treeItem_UnofficialPrimitives48[0]);
int counter = 0;
for (TreeItem item : categories) {
counter++;
ArrayList<TreeItem> datFileTreeItems = new ArrayList<TreeItem>(item.getItems());
for (TreeItem df : datFileTreeItems) {
DatFile d = (DatFile) df.getData();
if (e.equals(d)) {
item.getItems().remove(df);
} else {
StringBuilder nameSb = new StringBuilder(new File(d.getNewName()).getName());
final String d2 = d.getDescription();
if (counter < 6 && (!d.getNewName().startsWith(Project.getProjectPath()) || !d.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$
nameSb.insert(0, "(!) "); //$NON-NLS-1$
}
if (d2 != null)
nameSb.append(d2);
if (Project.getUnsavedFiles().contains(d)) {
df.setText("* " + nameSb.toString()); //$NON-NLS-1$
} else {
df.setText(nameSb.toString());
}
}
}
}
this.treeItem_Unsaved[0].removeAll();
Project.removeUnsavedFile(e);
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(e)) {
c3d.unlinkData();
}
}
HashSet<EditorTextWindow> windows = new HashSet<EditorTextWindow>(Project.getOpenTextWindows());
for (EditorTextWindow win : windows) {
win.closeTabWithDatfile(e);
}
Set<DatFile> unsaved = Project.getUnsavedFiles();
for (DatFile df : unsaved) {
TreeItem ti = new TreeItem(this.treeItem_Unsaved[0], SWT.NONE);
StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName());
final String d = df.getDescription();
if (d != null)
nameSb.append(d);
ti.setText(nameSb.toString());
ti.setData(df);
}
TreeItem[] folders = new TreeItem[10];
folders[0] = treeItem_ProjectParts[0];
folders[1] = treeItem_ProjectPrimitives[0];
folders[2] = treeItem_ProjectPrimitives8[0];
folders[3] = treeItem_ProjectPrimitives48[0];
folders[4] = treeItem_ProjectSubparts[0];
folders[5] = treeItem_UnofficialParts[0];
folders[6] = treeItem_UnofficialPrimitives[0];
folders[7] = treeItem_UnofficialPrimitives8[0];
folders[8] = treeItem_UnofficialPrimitives48[0];
folders[9] = treeItem_UnofficialSubparts[0];
for (TreeItem folder : folders) {
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData();
cachedReferences.remove(e);
}
this.treeParts[0].build();
this.treeParts[0].redraw();
updateTabs();
}
private synchronized void updateTabs() {
boolean isSelected = false;
if (tabFolder_OpenDatFiles[0].getData() != null) {
return;
}
tabFolder_OpenDatFiles[0].setData(true);
for (CTabItem c : tabFolder_OpenDatFiles[0].getItems()) {
c.dispose();
}
{
CTabItem tItem = new CTabItem(tabFolder_OpenDatFiles[0], SWT.NONE);
tItem.setText(I18n.E3D_NoFileSelected);
tItem.setData(View.DUMMY_DATFILE);
}
for (Iterator<DatFile> iterator = Project.getOpenedFiles().iterator(); iterator.hasNext();) {
DatFile df3 = iterator.next();
if (View.DUMMY_DATFILE.equals(df3)) {
iterator.remove();
}
}
for (DatFile df2 : Project.getOpenedFiles()) {
CTabItem tItem = new CTabItem(tabFolder_OpenDatFiles[0], SWT.NONE);
tItem.setText(df2.getShortName() + (Project.getUnsavedFiles().contains(df2) ? "*" : "")); //$NON-NLS-1$ //$NON-NLS-2$
tItem.setData(df2);
if (df2.equals(Project.getFileToEdit())) {
tabFolder_OpenDatFiles[0].setSelection(tItem);
isSelected = true;
}
}
if (!isSelected) {
tabFolder_OpenDatFiles[0].setSelection(0);
Project.setFileToEdit(View.DUMMY_DATFILE);
}
tabFolder_OpenDatFiles[0].setData(null);
tabFolder_OpenDatFiles[0].layout();
tabFolder_OpenDatFiles[0].redraw();
}
// Helper functions
private void clickBtnTest(Button btn) {
WidgetSelectionHelper.unselectAllChildButtons((ToolItem) btn.getParent());
btn.setSelection(true);
}
private void clickSingleBtn(Button btn) {
boolean state = btn.getSelection();
WidgetSelectionHelper.unselectAllChildButtons((ToolItem) btn.getParent());
btn.setSelection(state);
}
public boolean isAddingSomething() {
return addingSomething;
}
public void setAddingSomething(boolean addingSomething) {
this.addingSomething = addingSomething;
for (OpenGLRenderer renderer : renders) {
renderer.getC3D().getLockableDatFileReference().getVertexManager().clearSelection();
}
}
public boolean isAddingVertices() {
return addingVertices;
}
public void setAddingVertices(boolean addingVertices) {
this.addingVertices = addingVertices;
}
public boolean isAddingLines() {
return addingLines;
}
public void setAddingLines(boolean addingLines) {
this.addingLines = addingLines;
}
public boolean isAddingTriangles() {
return addingTriangles;
}
public void setAddingTriangles(boolean addingTriangles) {
this.addingTriangles = addingTriangles;
}
public boolean isAddingQuads() {
return addingQuads;
}
public void setAddingQuads(boolean addingQuads) {
this.addingQuads = addingQuads;
}
public boolean isAddingCondlines() {
return addingCondlines;
}
public void setAddingCondlines(boolean addingCondlines) {
this.addingCondlines = addingCondlines;
}
public boolean isAddingSubfiles() {
return addingSubfiles;
}
public void setAddingSubfiles(boolean addingSubfiles) {
this.addingSubfiles = addingSubfiles;
}
public boolean isAddingDistance() {
return addingDistance;
}
public void setAddingDistance(boolean addingDistance) {
this.addingDistance = addingDistance;
}
public boolean isAddingProtractor() {
return addingProtractor;
}
public void setAddingProtractor(boolean addingProtractor) {
this.addingProtractor = addingProtractor;
}
public void disableAddAction() {
addingSomething = false;
addingVertices = false;
addingLines = false;
addingTriangles = false;
addingQuads = false;
addingCondlines = false;
addingSubfiles = false;
addingDistance = false;
addingProtractor = false;
btn_AddVertex[0].setSelection(false);
btn_AddLine[0].setSelection(false);
btn_AddTriangle[0].setSelection(false);
btn_AddQuad[0].setSelection(false);
btn_AddCondline[0].setSelection(false);
btn_AddDistance[0].setSelection(false);
btn_AddProtractor[0].setSelection(false);
btn_AddPrimitive[0].setSelection(false);
}
public TreeItem getProjectParts() {
return treeItem_ProjectParts[0];
}
public TreeItem getProjectPrimitives() {
return treeItem_ProjectPrimitives[0];
}
public TreeItem getProjectPrimitives48() {
return treeItem_ProjectPrimitives48[0];
}
public TreeItem getProjectPrimitives8() {
return treeItem_ProjectPrimitives8[0];
}
public TreeItem getProjectSubparts() {
return treeItem_ProjectSubparts[0];
}
public TreeItem getUnofficialParts() {
return treeItem_UnofficialParts[0];
}
public TreeItem getUnofficialPrimitives() {
return treeItem_UnofficialPrimitives[0];
}
public TreeItem getUnofficialPrimitives48() {
return treeItem_UnofficialPrimitives48[0];
}
public TreeItem getUnofficialPrimitives8() {
return treeItem_UnofficialPrimitives8[0];
}
public TreeItem getUnofficialSubparts() {
return treeItem_UnofficialSubparts[0];
}
public TreeItem getOfficialParts() {
return treeItem_OfficialParts[0];
}
public TreeItem getOfficialPrimitives() {
return treeItem_OfficialPrimitives[0];
}
public TreeItem getOfficialPrimitives48() {
return treeItem_OfficialPrimitives48[0];
}
public TreeItem getOfficialPrimitives8() {
return treeItem_OfficialPrimitives8[0];
}
public TreeItem getOfficialSubparts() {
return treeItem_OfficialSubparts[0];
}
public TreeItem getUnsaved() {
return treeItem_Unsaved[0];
}
public ObjectMode getWorkingType() {
return workingType;
}
public void setWorkingType(ObjectMode workingMode) {
this.workingType = workingMode;
}
public boolean isMovingAdjacentData() {
return movingAdjacentData;
}
public void setMovingAdjacentData(boolean movingAdjacentData) {
btn_MoveAdjacentData[0].setSelection(movingAdjacentData);
this.movingAdjacentData = movingAdjacentData;
}
public WorkingMode getWorkingAction() {
return workingAction;
}
public void setWorkingAction(WorkingMode workingAction) {
this.workingAction = workingAction;
switch (workingAction) {
case COMBINED:
clickBtnTest(btn_Combined[0]);
workingAction = WorkingMode.COMBINED;
break;
case MOVE:
clickBtnTest(btn_Move[0]);
workingAction = WorkingMode.MOVE;
break;
case ROTATE:
clickBtnTest(btn_Rotate[0]);
workingAction = WorkingMode.ROTATE;
break;
case SCALE:
clickBtnTest(btn_Scale[0]);
workingAction = WorkingMode.SCALE;
break;
case SELECT:
clickBtnTest(btn_Select[0]);
workingAction = WorkingMode.SELECT;
break;
default:
break;
}
}
public ManipulatorScope getTransformationMode() {
return transformationMode;
}
public boolean hasNoTransparentSelection() {
return noTransparentSelection;
}
public void setNoTransparentSelection(boolean noTransparentSelection) {
this.noTransparentSelection = noTransparentSelection;
}
public boolean hasBfcToggle() {
return bfcToggle;
}
public void setBfcToggle(boolean bfcToggle) {
this.bfcToggle = bfcToggle;
}
public boolean isInsertingAtCursorPosition() {
return insertingAtCursorPosition;
}
public void setInsertingAtCursorPosition(boolean insertAtCursor) {
this.insertingAtCursorPosition = insertAtCursor;
}
public GColour getLastUsedColour() {
return lastUsedColour;
}
public void setLastUsedColour(GColour lastUsedColour) {
this.lastUsedColour = lastUsedColour;
}
public void setLastUsedColour2(GColour lastUsedColour) {
final int imgSize;
switch (Editor3DWindow.getIconsize()) {
case 0:
imgSize = 16;
break;
case 1:
imgSize = 24;
break;
case 2:
imgSize = 32;
break;
case 3:
imgSize = 48;
break;
case 4:
imgSize = 64;
break;
case 5:
imgSize = 72;
break;
default:
imgSize = 16;
break;
}
final GColour[] gColour2 = new GColour[] { lastUsedColour };
int num = gColour2[0].getColourNumber();
if (View.hasLDConfigColour(num)) {
gColour2[0] = View.getLDConfigColour(num);
} else {
num = -1;
}
Editor3DWindow.getWindow().setLastUsedColour(gColour2[0]);
btn_LastUsedColour[0].removeListener(SWT.Paint, btn_LastUsedColour[0].getListeners(SWT.Paint)[0]);
btn_LastUsedColour[0].removeListener(SWT.Selection, btn_LastUsedColour[0].getListeners(SWT.Selection)[0]);
final Color col = SWTResourceManager.getColor((int) (gColour2[0].getR() * 255f), (int) (gColour2[0].getG() * 255f), (int) (gColour2[0].getB() * 255f));
final Point size = btn_LastUsedColour[0].computeSize(SWT.DEFAULT, SWT.DEFAULT);
final int x = size.x / 4;
final int y = size.y / 4;
final int w = size.x / 2;
final int h = size.y / 2;
btn_LastUsedColour[0].addPaintListener(new PaintListener() {
@Override
public void paintControl(PaintEvent e) {
e.gc.setBackground(col);
e.gc.fillRectangle(x, y, w, h);
if (gColour2[0].getA() == 1f) {
e.gc.drawImage(ResourceManager.getImage("icon16_transparent.png"), 0, 0, imgSize, imgSize, x, y, w, h); //$NON-NLS-1$
} else if (gColour2[0].getA() == 0f) {
e.gc.drawImage(ResourceManager.getImage("icon16_randomColours.png"), 0, 0, 16, 16, x, y, w, h); //$NON-NLS-1$
} else {
e.gc.drawImage(ResourceManager.getImage("icon16_halftrans.png"), 0, 0, imgSize, imgSize, x, y, w, h); //$NON-NLS-1$
}
}
});
btn_LastUsedColour[0].addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (Project.getFileToEdit() != null) {
Editor3DWindow.getWindow().setLastUsedColour(gColour2[0]);
int num = gColour2[0].getColourNumber();
if (!View.hasLDConfigColour(num)) {
num = -1;
}
Project.getFileToEdit().getVertexManager().colourChangeSelection(num, gColour2[0].getR(), gColour2[0].getG(), gColour2[0].getB(), gColour2[0].getA(), true);
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
if (num != -1) {
Object[] messageArguments = {num, View.getLDConfigColourName(num)};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour1);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
} else {
StringBuilder colourBuilder = new StringBuilder();
colourBuilder.append("0x2"); //$NON-NLS-1$
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getR())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getG())).toUpperCase());
colourBuilder.append(MathHelper.toHex((int) (255f * gColour2[0].getB())).toUpperCase());
Object[] messageArguments = {colourBuilder.toString()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.EDITORTEXT_Colour2);
btn_LastUsedColour[0].setToolTipText(formatter.format(messageArguments));
if (gColour2[0].getA() == 0f) btn_LastUsedColour[0].setToolTipText(I18n.COLOURDIALOG_RandomColours);
}
btn_LastUsedColour[0].redraw();
}
public void cleanupClosedData() {
Set<DatFile> openFiles = new HashSet<DatFile>(Project.getUnsavedFiles());
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
openFiles.add(c3d.getLockableDatFileReference());
}
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
openFiles.add(((CompositeTab) t).getState().getFileNameObj());
}
}
Set<DatFile> deadFiles = new HashSet<DatFile>(Project.getParsedFiles());
deadFiles.removeAll(openFiles);
if (!deadFiles.isEmpty()) {
GData.CACHE_viewByProjection.clear();
GData.parsedLines.clear();
GData.CACHE_parsedFilesSource.clear();
}
for (DatFile datFile : deadFiles) {
datFile.disposeData();
}
if (!deadFiles.isEmpty()) {
// TODO Debug only System.gc();
}
}
public String getSearchCriteria() {
return txt_Search[0].getText();
}
public void resetSearch() {
search(""); //$NON-NLS-1$
}
public void search(final String word) {
this.getShell().getDisplay().asyncExec(new Runnable() {
@SuppressWarnings("unchecked")
@Override
public void run() {
String criteria = ".*" + word + ".*"; //$NON-NLS-1$ //$NON-NLS-2$
TreeItem[] folders = new TreeItem[15];
folders[0] = treeItem_OfficialParts[0];
folders[1] = treeItem_OfficialPrimitives[0];
folders[2] = treeItem_OfficialPrimitives8[0];
folders[3] = treeItem_OfficialPrimitives48[0];
folders[4] = treeItem_OfficialSubparts[0];
folders[5] = treeItem_UnofficialParts[0];
folders[6] = treeItem_UnofficialPrimitives[0];
folders[7] = treeItem_UnofficialPrimitives8[0];
folders[8] = treeItem_UnofficialPrimitives48[0];
folders[9] = treeItem_UnofficialSubparts[0];
folders[10] = treeItem_ProjectParts[0];
folders[11] = treeItem_ProjectPrimitives[0];
folders[12] = treeItem_ProjectPrimitives8[0];
folders[13] = treeItem_ProjectPrimitives48[0];
folders[14] = treeItem_ProjectSubparts[0];
if (folders[0].getData() == null) {
for (TreeItem folder : folders) {
folder.setData(new ArrayList<DatFile>());
for (TreeItem part : folder.getItems()) {
((ArrayList<DatFile>) folder.getData()).add((DatFile) part.getData());
}
}
}
try {
"42".matches(criteria); //$NON-NLS-1$
} catch (Exception ex) {
criteria = ".*"; //$NON-NLS-1$
}
final Pattern pattern = Pattern.compile(criteria);
for (int i = 0; i < 15; i++) {
TreeItem folder = folders[i];
folder.removeAll();
for (DatFile part : (ArrayList<DatFile>) folder.getData()) {
StringBuilder nameSb = new StringBuilder(new File(part.getNewName()).getName());
if (i > 9 && (!part.getNewName().startsWith(Project.getProjectPath()) || !part.getNewName().replace(Project.getProjectPath() + File.separator, "").contains(File.separator))) { //$NON-NLS-1$
nameSb.insert(0, "(!) "); //$NON-NLS-1$
}
final String d = part.getDescription();
if (d != null)
nameSb.append(d);
String name = nameSb.toString();
TreeItem finding = new TreeItem(folder, SWT.NONE);
// Save the path
finding.setData(part);
// Set the filename
if (Project.getUnsavedFiles().contains(part) || !part.getOldName().equals(part.getNewName())) {
// Insert asterisk if the file was
// modified
finding.setText("* " + name); //$NON-NLS-1$
} else {
finding.setText(name);
}
finding.setShown(!(d != null && d.startsWith(" - ~Moved to")) && pattern.matcher(name).matches()); //$NON-NLS-1$
}
}
folders[0].getParent().build();
folders[0].getParent().redraw();
folders[0].getParent().update();
}
});
}
public void closeAllComposite3D() {
canvasList.clear();
ArrayList<OpenGLRenderer> renders2 = new ArrayList<OpenGLRenderer>(renders);
for (OpenGLRenderer renderer : renders2) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().closeView();
}
renders.clear();
}
public TreeData getDatFileTreeData(DatFile df) {
TreeData result = new TreeData();
ArrayList<TreeItem> categories = new ArrayList<TreeItem>();
categories.add(this.treeItem_ProjectParts[0]);
categories.add(this.treeItem_ProjectSubparts[0]);
categories.add(this.treeItem_ProjectPrimitives[0]);
categories.add(this.treeItem_ProjectPrimitives48[0]);
categories.add(this.treeItem_ProjectPrimitives8[0]);
categories.add(this.treeItem_UnofficialParts[0]);
categories.add(this.treeItem_UnofficialSubparts[0]);
categories.add(this.treeItem_UnofficialPrimitives[0]);
categories.add(this.treeItem_UnofficialPrimitives48[0]);
categories.add(this.treeItem_UnofficialPrimitives8[0]);
categories.add(this.treeItem_OfficialParts[0]);
categories.add(this.treeItem_OfficialSubparts[0]);
categories.add(this.treeItem_OfficialPrimitives[0]);
categories.add(this.treeItem_OfficialPrimitives48[0]);
categories.add(this.treeItem_OfficialPrimitives8[0]);
categories.add(this.treeItem_Unsaved[0]);
for (TreeItem item : categories) {
ArrayList<TreeItem> datFileTreeItems = item.getItems();
for (TreeItem ti : datFileTreeItems) {
DatFile d = (DatFile) ti.getData();
if (df.equals(d)) {
result.setLocation(ti);
} else if (d.getShortName().equals(df.getShortName())) {
result.getLocationsWithSameShortFilenames().add(ti);
}
}
}
return result;
}
/**
* Updates the background picture tab
*/
public void updateBgPictureTab() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
GDataPNG png = vm.getSelectedBgPicture();
if (png == null) {
updatingPngPictureTab = true;
txt_PngPath[0].setText("---"); //$NON-NLS-1$
txt_PngPath[0].setToolTipText("---"); //$NON-NLS-1$
spn_PngX[0].setValue(BigDecimal.ZERO);
spn_PngY[0].setValue(BigDecimal.ZERO);
spn_PngZ[0].setValue(BigDecimal.ZERO);
spn_PngA1[0].setValue(BigDecimal.ZERO);
spn_PngA2[0].setValue(BigDecimal.ZERO);
spn_PngA3[0].setValue(BigDecimal.ZERO);
spn_PngSX[0].setValue(BigDecimal.ONE);
spn_PngSY[0].setValue(BigDecimal.ONE);
txt_PngPath[0].setEnabled(false);
btn_PngFocus[0].setEnabled(false);
btn_PngImage[0].setEnabled(false);
spn_PngX[0].setEnabled(false);
spn_PngY[0].setEnabled(false);
spn_PngZ[0].setEnabled(false);
spn_PngA1[0].setEnabled(false);
spn_PngA2[0].setEnabled(false);
spn_PngA3[0].setEnabled(false);
spn_PngSX[0].setEnabled(false);
spn_PngSY[0].setEnabled(false);
spn_PngA1[0].getParent().update();
updatingPngPictureTab = false;
return;
}
updatingPngPictureTab = true;
txt_PngPath[0].setEnabled(true);
btn_PngFocus[0].setEnabled(true);
btn_PngImage[0].setEnabled(true);
spn_PngX[0].setEnabled(true);
spn_PngY[0].setEnabled(true);
spn_PngZ[0].setEnabled(true);
spn_PngA1[0].setEnabled(true);
spn_PngA2[0].setEnabled(true);
spn_PngA3[0].setEnabled(true);
spn_PngSX[0].setEnabled(true);
spn_PngSY[0].setEnabled(true);
txt_PngPath[0].setText(png.texturePath);
txt_PngPath[0].setToolTipText(png.texturePath);
spn_PngX[0].setValue(png.offset.X);
spn_PngY[0].setValue(png.offset.Y);
spn_PngZ[0].setValue(png.offset.Z);
spn_PngA1[0].setValue(png.angleA);
spn_PngA2[0].setValue(png.angleB);
spn_PngA3[0].setValue(png.angleC);
spn_PngSX[0].setValue(png.scale.X);
spn_PngSY[0].setValue(png.scale.Y);
spn_PngA1[0].getParent().update();
updatingPngPictureTab = false;
return;
}
}
}
public void unselectAddSubfile() {
resetAddState();
btn_AddPrimitive[0].setSelection(false);
setAddingSubfiles(false);
setAddingSomething(false);
}
public DatFile createNewDatFile(Shell sh, OpenInWhat where) {
FileDialog fd = new FileDialog(sh, SWT.SAVE);
fd.setText(I18n.E3D_CreateNewDat);
fd.setFilterPath(Project.getLastVisitedPath());
String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = { I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles };
fd.setFilterNames(filterNames);
while (true) {
String selected = fd.open();
System.out.println(selected);
if (selected != null) {
// Check if its already created
DatFile df = new DatFile(selected);
if (isFileNameAllocated(selected, df, true)) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
messageBox.setText(I18n.DIALOG_AlreadyAllocatedNameTitle);
messageBox.setMessage(I18n.DIALOG_AlreadyAllocatedName);
int result = messageBox.open();
if (result == SWT.CANCEL) {
break;
}
} else {
String typeSuffix = ""; //$NON-NLS-1$
String folderPrefix = ""; //$NON-NLS-1$
String subfilePrefix = ""; //$NON-NLS-1$
String path = new File(selected).getParent();
TreeItem parent = this.treeItem_ProjectParts[0];
if (path.endsWith(File.separator + "S") || path.endsWith(File.separator + "s")) { //$NON-NLS-1$ //$NON-NLS-2$
typeSuffix = "Unofficial_Subpart"; //$NON-NLS-1$
folderPrefix = "s\\"; //$NON-NLS-1$
subfilePrefix = "~"; //$NON-NLS-1$
parent = this.treeItem_ProjectSubparts[0];
} else if (path.endsWith(File.separator + "P" + File.separator + "48") || path.endsWith(File.separator + "p" + File.separator + "48")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
typeSuffix = "Unofficial_48_Primitive"; //$NON-NLS-1$
folderPrefix = "48\\"; //$NON-NLS-1$
parent = this.treeItem_ProjectPrimitives48[0];
} else if (path.endsWith(File.separator + "P" + File.separator + "8") || path.endsWith(File.separator + "p" + File.separator + "8")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
typeSuffix = "Unofficial_8_Primitive"; //$NON-NLS-1$
folderPrefix = "8\\"; //$NON-NLS-1$
parent = this.treeItem_ProjectPrimitives8[0];
} else if (path.endsWith(File.separator + "P") || path.endsWith(File.separator + "p")) { //$NON-NLS-1$ //$NON-NLS-2$
typeSuffix = "Unofficial_Primitive"; //$NON-NLS-1$
parent = this.treeItem_ProjectPrimitives[0];
}
df.addToTail(new GData0("0 " + subfilePrefix)); //$NON-NLS-1$
df.addToTail(new GData0("0 Name: " + folderPrefix + new File(selected).getName())); //$NON-NLS-1$
String ldrawName = WorkbenchManager.getUserSettingState().getLdrawUserName();
if (ldrawName == null || ldrawName.isEmpty()) {
df.addToTail(new GData0("0 Author: " + WorkbenchManager.getUserSettingState().getRealUserName())); //$NON-NLS-1$
} else {
df.addToTail(new GData0("0 Author: " + WorkbenchManager.getUserSettingState().getRealUserName() + " [" + WorkbenchManager.getUserSettingState().getLdrawUserName() + "]")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
df.addToTail(new GData0("0 !LDRAW_ORG " + typeSuffix)); //$NON-NLS-1$
String license = WorkbenchManager.getUserSettingState().getLicense();
if (license == null || license.isEmpty()) {
df.addToTail(new GData0("0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt")); //$NON-NLS-1$
} else {
df.addToTail(new GData0(license));
}
df.addToTail(new GData0("")); //$NON-NLS-1$
df.addToTail(new GDataBFC(BFC.CCW_CLIP));
df.addToTail(new GData0("")); //$NON-NLS-1$
df.addToTail(new GData0("")); //$NON-NLS-1$
df.getVertexManager().setModified(true, true);
TreeItem ti = new TreeItem(parent, SWT.NONE);
StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName());
nameSb.append(I18n.E3D_NewFile);
ti.setText(nameSb.toString());
ti.setData(df);
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData();
cachedReferences.add(df);
Project.addUnsavedFile(df);
updateTree_renamedEntries();
updateTree_unsavedEntries();
updateTree_selectedDatFile(df);
openDatFile(df, where, null);
return df;
}
} else {
break;
}
}
return null;
}
public DatFile openDatFile(Shell sh, OpenInWhat where, String filePath, boolean canRevert) {
FileDialog fd = new FileDialog(sh, SWT.OPEN);
fd.setText(I18n.E3D_OpenDatFile);
fd.setFilterPath(Project.getLastVisitedPath());
String[] filterExt = { "*.dat", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$
fd.setFilterExtensions(filterExt);
String[] filterNames = {I18n.E3D_LDrawSourceFile, I18n.E3D_AllFiles};
fd.setFilterNames(filterNames);
String selected = filePath == null ? fd.open() : filePath;
System.out.println(selected);
if (selected != null) {
// Check if its already created
DatType type = DatType.PART;
DatFile df = new DatFile(selected);
DatFile original = isFileNameAllocated2(selected, df);
if (original == null) {
// Type Check and Description Parsing!!
StringBuilder titleSb = new StringBuilder();
UTF8BufferedReader reader = null;
File f = new File(selected);
try {
reader = new UTF8BufferedReader(f.getAbsolutePath());
String title = reader.readLine();
if (title != null) {
title = title.trim();
if (title.length() > 0) {
titleSb.append(" -"); //$NON-NLS-1$
titleSb.append(title.substring(1));
}
}
while (true) {
String typ = reader.readLine();
if (typ != null) {
typ = typ.trim();
if (!typ.startsWith("0")) { //$NON-NLS-1$
break;
} else {
int i1 = typ.indexOf("!LDRAW_ORG"); //$NON-NLS-1$
if (i1 > -1) {
int i2;
i2 = typ.indexOf("Subpart"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.SUBPART;
break;
}
i2 = typ.indexOf("Part"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.PART;
break;
}
i2 = typ.indexOf("48_Primitive"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.PRIMITIVE48;
break;
}
i2 = typ.indexOf("8_Primitive"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.PRIMITIVE8;
break;
}
i2 = typ.indexOf("Primitive"); //$NON-NLS-1$
if (i2 > -1 && i1 < i2) {
type = DatType.PRIMITIVE;
break;
}
}
}
} else {
break;
}
}
} catch (LDParsingException e) {
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {
} finally {
try {
if (reader != null)
reader.close();
} catch (LDParsingException e1) {
}
}
df = new DatFile(selected, titleSb.toString(), false, type);
df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath()));
} else {
// FIXME Needs code cleanup!!
df = original;
if (canRevert && Project.getUnsavedFiles().contains(df)) {
if (Editor3DWindow.getWindow().revert(df)) {
updateTree_unsavedEntries();
boolean foundTab = false;
for (EditorTextWindow win : Project.getOpenTextWindows()) {
for (CTabItem ci : win.getTabFolder().getItems()) {
CompositeTab ct = (CompositeTab) ci;
if (df.equals(ct.getState().getFileNameObj())) {
foundTab = true;
break;
}
}
if (foundTab) {
break;
}
}
if (foundTab && OpenInWhat.EDITOR_3D != where) {
return null;
}
}
}
df.setProjectFile(df.getNewName().startsWith(Project.getProjectPath()));
if (original.isProjectFile()) {
openDatFile(df, where, null);
return df;
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectSubparts[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives48[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives8[0].getData();
if (cachedReferences.contains(df)) {
openDatFile(df, where, null);
return df;
}
}
type = original.getType();
df = original;
}
TreeItem ti;
switch (type) {
case PART:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE);
break;
case SUBPART:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectSubparts[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectSubparts[0], SWT.NONE);
break;
case PRIMITIVE:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectPrimitives[0], SWT.NONE);
break;
case PRIMITIVE48:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives48[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectPrimitives48[0], SWT.NONE);
break;
case PRIMITIVE8:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectPrimitives8[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectPrimitives8[0], SWT.NONE);
break;
default:
{
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences = (ArrayList<DatFile>) this.treeItem_ProjectParts[0].getData();
cachedReferences.add(df);
}
ti = new TreeItem(this.treeItem_ProjectParts[0], SWT.NONE);
break;
}
StringBuilder nameSb = new StringBuilder(new File(df.getNewName()).getName());
nameSb.append(I18n.E3D_NewFile);
ti.setText(nameSb.toString());
ti.setData(df);
if (canRevert && Project.getUnsavedFiles().contains(df)) {
if (Editor3DWindow.getWindow().revert(df)) {
boolean foundTab = false;
for (EditorTextWindow win : Project.getOpenTextWindows()) {
for (CTabItem ci : win.getTabFolder().getItems()) {
CompositeTab ct = (CompositeTab) ci;
if (df.equals(ct.getState().getFileNameObj())) {
foundTab = true;
break;
}
}
if (foundTab) {
break;
}
}
if (foundTab && OpenInWhat.EDITOR_3D != where) {
updateTree_unsavedEntries();
return null;
}
}
}
updateTree_unsavedEntries();
openDatFile(df, where, null);
return df;
}
return null;
}
public boolean openDatFile(DatFile df, OpenInWhat where, ApplicationWindow tWin) {
if (where == OpenInWhat.EDITOR_3D || where == OpenInWhat.EDITOR_TEXT_AND_3D) {
if (renders.isEmpty()) {
if ("%EMPTY%".equals(Editor3DWindow.getSashForm().getChildren()[1].getData())) { //$NON-NLS-1$
int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights();
Editor3DWindow.getSashForm().getChildren()[1].dispose();
CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false);
cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]);
df.parseForData(true);
Project.setFileToEdit(df);
boolean hasState = hasState(df, cmp_Container.getComposite3D());
cmp_Container.getComposite3D().setLockableDatFileReference(df);
if (!hasState) cmp_Container.getComposite3D().getModifier().zoomToFit();
Editor3DWindow.getSashForm().getParent().layout();
Editor3DWindow.getSashForm().setWeights(mainSashWeights);
}
} else {
boolean canUpdate = false;
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (!c3d.isDatFileLockedOnDisplay()) {
canUpdate = true;
break;
}
}
if (!canUpdate) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().switchLockedDat(false);
}
}
final VertexManager vm = df.getVertexManager();
if (vm.isModified()) {
df.setText(df.getText());
}
df.parseForData(true);
Project.setFileToEdit(df);
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (!c3d.isDatFileLockedOnDisplay()) {
boolean hasState = hasState(df, c3d);
c3d.setLockableDatFileReference(df);
if (!hasState) c3d.getModifier().zoomToFit();
}
}
if (!canUpdate) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().switchLockedDat(true);
}
}
}
updateTree_selectedDatFile(df);
}
if (where == OpenInWhat.EDITOR_TEXT || where == OpenInWhat.EDITOR_TEXT_AND_3D) {
for (EditorTextWindow w : Project.getOpenTextWindows()) {
final CompositeTabFolder cTabFolder = w.getTabFolder();
for (CTabItem t : cTabFolder.getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
if (Project.getUnsavedFiles().contains(df)) {
cTabFolder.setSelection(t);
((CompositeTab) t).getControl().getShell().forceActive();
} else {
CompositeTab tbtmnewItem = new CompositeTab(cTabFolder, SWT.CLOSE);
tbtmnewItem.setFolderAndWindow(cTabFolder, w);
tbtmnewItem.getState().setFileNameObj(View.DUMMY_DATFILE);
w.closeTabWithDatfile(df);
tbtmnewItem.getState().setFileNameObj(df);
cTabFolder.setSelection(tbtmnewItem);
tbtmnewItem.getControl().getShell().forceActive();
if (w.isSeperateWindow()) {
w.open();
}
Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
tbtmnewItem.parseForErrorAndHints();
tbtmnewItem.getTextComposite().redraw();
return true;
}
if (w.isSeperateWindow()) {
w.open();
}
return w == tWin;
}
}
}
if (tWin == null) {
EditorTextWindow w;
// Project.getParsedFiles().add(df); IS NECESSARY HERE
Project.getParsedFiles().add(df);
Project.addOpenedFile(df);
if (!Project.getOpenTextWindows().isEmpty() && !(w = Project.getOpenTextWindows().iterator().next()).isSeperateWindow()) {
w.openNewDatFileTab(df, true);
} else {
new EditorTextWindow().run(df, false);
}
}
}
return false;
}
public void disableSelectionTab() {
if (Thread.currentThread() == Display.getDefault().getThread()) {
updatingSelectionTab = true;
txt_Line[0].setText(""); //$NON-NLS-1$
spn_SelectionX1[0].setEnabled(false);
spn_SelectionY1[0].setEnabled(false);
spn_SelectionZ1[0].setEnabled(false);
spn_SelectionX2[0].setEnabled(false);
spn_SelectionY2[0].setEnabled(false);
spn_SelectionZ2[0].setEnabled(false);
spn_SelectionX3[0].setEnabled(false);
spn_SelectionY3[0].setEnabled(false);
spn_SelectionZ3[0].setEnabled(false);
spn_SelectionX4[0].setEnabled(false);
spn_SelectionY4[0].setEnabled(false);
spn_SelectionZ4[0].setEnabled(false);
spn_SelectionX1[0].setValue(BigDecimal.ZERO);
spn_SelectionY1[0].setValue(BigDecimal.ZERO);
spn_SelectionZ1[0].setValue(BigDecimal.ZERO);
spn_SelectionX2[0].setValue(BigDecimal.ZERO);
spn_SelectionY2[0].setValue(BigDecimal.ZERO);
spn_SelectionZ2[0].setValue(BigDecimal.ZERO);
spn_SelectionX3[0].setValue(BigDecimal.ZERO);
spn_SelectionY3[0].setValue(BigDecimal.ZERO);
spn_SelectionZ3[0].setValue(BigDecimal.ZERO);
spn_SelectionX4[0].setValue(BigDecimal.ZERO);
spn_SelectionY4[0].setValue(BigDecimal.ZERO);
spn_SelectionZ4[0].setValue(BigDecimal.ZERO);
lbl_SelectionX1[0].setText(I18n.E3D_PositionX1);
lbl_SelectionY1[0].setText(I18n.E3D_PositionY1);
lbl_SelectionZ1[0].setText(I18n.E3D_PositionZ1);
lbl_SelectionX2[0].setText(I18n.E3D_PositionX2);
lbl_SelectionY2[0].setText(I18n.E3D_PositionY2);
lbl_SelectionZ2[0].setText(I18n.E3D_PositionZ2);
lbl_SelectionX3[0].setText(I18n.E3D_PositionX3);
lbl_SelectionY3[0].setText(I18n.E3D_PositionY3);
lbl_SelectionZ3[0].setText(I18n.E3D_PositionZ3);
lbl_SelectionX4[0].setText(I18n.E3D_PositionX4);
lbl_SelectionY4[0].setText(I18n.E3D_PositionY4);
lbl_SelectionZ4[0].setText(I18n.E3D_PositionZ4);
updatingSelectionTab = false;
} else {
NLogger.error(getClass(), new SWTException(SWT.ERROR_THREAD_INVALID_ACCESS, "A wrong thread tries to access the GUI!")); //$NON-NLS-1$
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
updatingSelectionTab = true;
txt_Line[0].setText(""); //$NON-NLS-1$
spn_SelectionX1[0].setEnabled(false);
spn_SelectionY1[0].setEnabled(false);
spn_SelectionZ1[0].setEnabled(false);
spn_SelectionX2[0].setEnabled(false);
spn_SelectionY2[0].setEnabled(false);
spn_SelectionZ2[0].setEnabled(false);
spn_SelectionX3[0].setEnabled(false);
spn_SelectionY3[0].setEnabled(false);
spn_SelectionZ3[0].setEnabled(false);
spn_SelectionX4[0].setEnabled(false);
spn_SelectionY4[0].setEnabled(false);
spn_SelectionZ4[0].setEnabled(false);
spn_SelectionX1[0].setValue(BigDecimal.ZERO);
spn_SelectionY1[0].setValue(BigDecimal.ZERO);
spn_SelectionZ1[0].setValue(BigDecimal.ZERO);
spn_SelectionX2[0].setValue(BigDecimal.ZERO);
spn_SelectionY2[0].setValue(BigDecimal.ZERO);
spn_SelectionZ2[0].setValue(BigDecimal.ZERO);
spn_SelectionX3[0].setValue(BigDecimal.ZERO);
spn_SelectionY3[0].setValue(BigDecimal.ZERO);
spn_SelectionZ3[0].setValue(BigDecimal.ZERO);
spn_SelectionX4[0].setValue(BigDecimal.ZERO);
spn_SelectionY4[0].setValue(BigDecimal.ZERO);
spn_SelectionZ4[0].setValue(BigDecimal.ZERO);
lbl_SelectionX1[0].setText(I18n.E3D_PositionX1);
lbl_SelectionY1[0].setText(I18n.E3D_PositionY1);
lbl_SelectionZ1[0].setText(I18n.E3D_PositionZ1);
lbl_SelectionX2[0].setText(I18n.E3D_PositionX2);
lbl_SelectionY2[0].setText(I18n.E3D_PositionY2);
lbl_SelectionZ2[0].setText(I18n.E3D_PositionZ2);
lbl_SelectionX3[0].setText(I18n.E3D_PositionX3);
lbl_SelectionY3[0].setText(I18n.E3D_PositionY3);
lbl_SelectionZ3[0].setText(I18n.E3D_PositionZ3);
lbl_SelectionX4[0].setText(I18n.E3D_PositionX4);
lbl_SelectionY4[0].setText(I18n.E3D_PositionY4);
lbl_SelectionZ4[0].setText(I18n.E3D_PositionZ4);
updatingSelectionTab = false;
} catch (Exception ex) {
NLogger.error(getClass(), ex);
}
}
});
}
}
public static ArrayList<OpenGLRenderer> getRenders() {
return renders;
}
public SearchWindow getSearchWindow() {
return searchWindow;
}
public void setSearchWindow(SearchWindow searchWindow) {
this.searchWindow = searchWindow;
}
public SelectorSettings loadSelectorSettings() {
sels.setColour(mntm_WithSameColour[0].getSelection());
sels.setEdgeAdjacency(mntm_WithAdjacency[0].getSelection());
sels.setEdgeStop(mntm_StopAtEdges[0].getSelection());
sels.setHidden(mntm_WithHiddenData[0].getSelection());
sels.setNoSubfiles(mntm_ExceptSubfiles[0].getSelection());
sels.setOrientation(mntm_WithSameOrientation[0].getSelection());
sels.setDistance(mntm_WithAccuracy[0].getSelection());
sels.setWholeSubfiles(mntm_WithWholeSubfiles[0].getSelection());
sels.setVertices(mntm_SVertices[0].getSelection());
sels.setLines(mntm_SLines[0].getSelection());
sels.setTriangles(mntm_STriangles[0].getSelection());
sels.setQuads(mntm_SQuads[0].getSelection());
sels.setCondlines(mntm_SCLines[0].getSelection());
return sels;
}
public boolean isFileNameAllocated(String dir, DatFile df, boolean createNew) {
TreeItem[] folders = new TreeItem[15];
folders[0] = treeItem_OfficialParts[0];
folders[1] = treeItem_OfficialPrimitives[0];
folders[2] = treeItem_OfficialPrimitives8[0];
folders[3] = treeItem_OfficialPrimitives48[0];
folders[4] = treeItem_OfficialSubparts[0];
folders[5] = treeItem_UnofficialParts[0];
folders[6] = treeItem_UnofficialPrimitives[0];
folders[7] = treeItem_UnofficialPrimitives8[0];
folders[8] = treeItem_UnofficialPrimitives48[0];
folders[9] = treeItem_UnofficialSubparts[0];
folders[10] = treeItem_ProjectParts[0];
folders[11] = treeItem_ProjectPrimitives[0];
folders[12] = treeItem_ProjectPrimitives8[0];
folders[13] = treeItem_ProjectPrimitives48[0];
folders[14] = treeItem_ProjectSubparts[0];
for (TreeItem folder : folders) {
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData();
for (DatFile d : cachedReferences) {
if (createNew || !df.equals(d)) {
if (dir.equals(d.getOldName()) || dir.equals(d.getNewName())) {
return true;
}
}
}
}
return false;
}
/**
* @return null if the file is not allocated
*/
private DatFile isFileNameAllocated2(String dir, DatFile df) {
TreeItem[] folders = new TreeItem[15];
folders[0] = treeItem_OfficialParts[0];
folders[1] = treeItem_OfficialPrimitives[0];
folders[2] = treeItem_OfficialPrimitives8[0];
folders[3] = treeItem_OfficialPrimitives48[0];
folders[4] = treeItem_OfficialSubparts[0];
folders[5] = treeItem_UnofficialParts[0];
folders[6] = treeItem_UnofficialPrimitives[0];
folders[7] = treeItem_UnofficialPrimitives8[0];
folders[8] = treeItem_UnofficialPrimitives48[0];
folders[9] = treeItem_UnofficialSubparts[0];
folders[10] = treeItem_ProjectParts[0];
folders[11] = treeItem_ProjectPrimitives[0];
folders[12] = treeItem_ProjectPrimitives8[0];
folders[13] = treeItem_ProjectPrimitives48[0];
folders[14] = treeItem_ProjectSubparts[0];
for (TreeItem folder : folders) {
@SuppressWarnings("unchecked")
ArrayList<DatFile> cachedReferences =(ArrayList<DatFile>) folder.getData();
for (DatFile d : cachedReferences) {
if (dir.equals(d.getOldName()) || dir.equals(d.getNewName())) {
return d;
}
}
}
return null;
}
public void updatePrimitiveLabel(Primitive p) {
if (lbl_selectedPrimitiveItem[0] == null) return;
if (p == null) {
lbl_selectedPrimitiveItem[0].setText(I18n.E3D_NoPrimitiveSelected);
} else {
lbl_selectedPrimitiveItem[0].setText(p.toString());
}
lbl_selectedPrimitiveItem[0].getParent().layout();
}
public CompositePrimitive getCompositePrimitive() {
return cmp_Primitives[0];
}
public static AtomicBoolean getAlive() {
return alive;
}
public MenuItem getMntmWithSameColour() {
return mntm_WithSameColour[0];
}
public ArrayList<String> getRecentItems() {
return recentItems;
}
private void setLineSize(Sphere sp, Sphere sp_inv, float line_width1000, float line_width, float line_width_gl, Button btn) {
GLPrimitives.SPHERE = sp;
GLPrimitives.SPHERE_INV = sp_inv;
View.lineWidth1000[0] = line_width1000;
View.lineWidth[0] = line_width;
View.lineWidthGL[0] = line_width_gl;
compileAll();
clickSingleBtn(btn);
}
public void compileAll() {
Set<DatFile> dfs = new HashSet<DatFile>();
for (OpenGLRenderer renderer : renders) {
dfs.add(renderer.getC3D().getLockableDatFileReference());
}
for (DatFile df : dfs) {
df.getVertexManager().addSnapshot();
SubfileCompiler.compile(df, false, false);
}
}
public void initAllRenderers() {
for (OpenGLRenderer renderer : renders) {
final GLCanvas canvas = renderer.getC3D().getCanvas();
if (!canvas.isCurrent()) {
canvas.setCurrent();
try {
GLContext.useContext(canvas);
} catch (LWJGLException e) {
NLogger.error(OpenGLRenderer.class, e);
}
}
renderer.init();
}
final GLCanvas canvas = getCompositePrimitive().getCanvas();
if (!canvas.isCurrent()) {
canvas.setCurrent();
try {
GLContext.useContext(canvas);
} catch (LWJGLException e) {
NLogger.error(OpenGLRenderer.class, e);
}
}
getCompositePrimitive().getOpenGL().init();
}
public void regainFocus() {
for (OpenGLRenderer r : renders) {
if (r.getC3D().getLockableDatFileReference().equals(Project.getFileToEdit())) {
r.getC3D().getCanvas().setFocus();
return;
}
}
}
private void mntm_Manipulator_0() {
if (Project.getFileToEdit() != null) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d.getManipulator().reset();
}
}
}
regainFocus();
}
private void mntm_Manipulator_XIII() {
if (Project.getFileToEdit() != null) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f t = new Vector4f(c3d.getManipulator().getPosition());
BigDecimal[] T = c3d.getManipulator().getAccuratePosition();
c3d.getManipulator().reset();
c3d.getManipulator().getPosition().set(t);
c3d.getManipulator().setAccuratePosition(T[0], T[1], T[2]);
;
}
}
}
regainFocus();
}
private void mntm_Manipulator_X() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getXaxis(), c3d.getManipulator().getXaxis());
BigDecimal[] a = c3d.getManipulator().getAccurateXaxis();
c3d.getManipulator().setAccurateXaxis(a[0].negate(), a[1].negate(), a[2].negate());
}
}
regainFocus();
}
private void mntm_Manipulator_XI() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getYaxis(), c3d.getManipulator().getYaxis());
BigDecimal[] a = c3d.getManipulator().getAccurateYaxis();
c3d.getManipulator().setAccurateYaxis(a[0].negate(), a[1].negate(), a[2].negate());
}
}
regainFocus();
}
private void mntm_Manipulator_XII() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f.sub(new Vector4f(0f, 0f, 0f, 2f), c3d.getManipulator().getZaxis(), c3d.getManipulator().getZaxis());
BigDecimal[] a = c3d.getManipulator().getAccurateZaxis();
c3d.getManipulator().setAccurateZaxis(a[0].negate(), a[1].negate(), a[2].negate());
}
}
regainFocus();
}
private void mntm_Manipulator_1() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
Vector4f pos = c3d.getManipulator().getPosition();
Vector4f a1 = c3d.getManipulator().getXaxis();
Vector4f a2 = c3d.getManipulator().getYaxis();
Vector4f a3 = c3d.getManipulator().getZaxis();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d.setClassicPerspective(false);
WidgetSelectionHelper.unselectAllChildButtons(c3d.getViewAnglesMenu());
Matrix4f rot = new Matrix4f();
Matrix4f.setIdentity(rot);
rot.m00 = a1.x;
rot.m10 = a1.y;
rot.m20 = a1.z;
rot.m01 = a2.x;
rot.m11 = a2.y;
rot.m21 = a2.z;
rot.m02 = a3.x;
rot.m12 = a3.y;
rot.m22 = a3.z;
c3d.getRotation().load(rot);
Matrix4f trans = new Matrix4f();
Matrix4f.setIdentity(trans);
trans.translate(new Vector3f(-pos.x, -pos.y, -pos.z));
c3d.getTranslation().load(trans);
c3d.getPerspectiveCalculator().calculateOriginData();
}
}
regainFocus();
}
public void mntm_Manipulator_2() {
if (Project.getFileToEdit() != null) {
Vector4f avg = Project.getFileToEdit().getVertexManager().getSelectionCenter();
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d.getManipulator().getPosition().set(avg.x, avg.y, avg.z, 1f);
c3d.getManipulator().setAccuratePosition(new BigDecimal(avg.x / 1000f), new BigDecimal(avg.y / 1000f), new BigDecimal(avg.z / 1000f));
}
}
}
regainFocus();
}
private void mntm_Manipulator_3() {
if (Project.getFileToEdit() != null) {
Set<GData1> subfiles = Project.getFileToEdit().getVertexManager().getSelectedSubfiles();
if (!subfiles.isEmpty()) {
GData1 subfile = null;
for (GData1 g1 : subfiles) {
subfile = g1;
break;
}
Matrix4f m = subfile.getProductMatrix();
Matrix M = subfile.getAccurateProductMatrix();
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
c3d.getManipulator().getPosition().set(m.m30, m.m31, m.m32, 1f);
c3d.getManipulator().setAccuratePosition(M.M30, M.M31, M.M32);
Vector3f x = new Vector3f(m.m00, m.m01, m.m02);
x.normalise();
Vector3f y = new Vector3f(m.m10, m.m11, m.m12);
y.normalise();
Vector3f z = new Vector3f(m.m20, m.m21, m.m22);
z.normalise();
c3d.getManipulator().getXaxis().set(x.x, x.y, x.z, 1f);
c3d.getManipulator().getYaxis().set(y.x, y.y, y.z, 1f);
c3d.getManipulator().getZaxis().set(z.x, z.y, z.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
}
}
regainFocus();
}
private void mntm_Manipulator_32() {
if (Project.getFileToEdit() != null) {
VertexManager vm = Project.getFileToEdit().getVertexManager();
Set<GData1> subfiles = vm.getSelectedSubfiles();
if (!subfiles.isEmpty()) {
GData1 subfile = null;
for (GData1 g1 : subfiles) {
if (vm.getLineLinkedToVertices().containsKey(g1)) {
subfile = g1;
break;
}
}
if (subfile == null) {
return;
}
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
vm.addSnapshot();
vm.backupHideShowState();
Manipulator ma = c3d.getManipulator();
vm.transformSubfile(subfile, ma.getAccurateMatrix(), true, true);
break;
}
}
}
}
regainFocus();
}
private void mntm_Manipulator_4() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
float minDist = Float.MAX_VALUE;
Vector4f next = new Vector4f(c3d.getManipulator().getPosition());
Vector4f min = new Vector4f(c3d.getManipulator().getPosition());
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Set<Vertex> vertices;
if (vm.getSelectedVertices().isEmpty()) {
vertices = vm.getVertices();
} else {
vertices = vm.getSelectedVertices();
}
Vertex minVertex = new Vertex(0f, 0f, 0f);
for (Vertex vertex : vertices) {
Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null);
float d2 = sub.lengthSquared();
if (d2 < minDist) {
minVertex = vertex;
minDist = d2;
min = vertex.toVector4f();
}
}
c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f);
c3d.getManipulator().setAccuratePosition(minVertex.X, minVertex.Y, minVertex.Z);
}
}
regainFocus();
}
private void mntm_Manipulator_5() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f min = new Vector4f(c3d.getManipulator().getPosition());
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
min = vm.getMinimalDistanceVertexToLines(new Vertex(c3d.getManipulator().getPosition())).toVector4f();
c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f);
c3d.getManipulator().setAccuratePosition(new BigDecimal(min.x / 1000f), new BigDecimal(min.y / 1000f), new BigDecimal(min.z / 1000f));
}
}
regainFocus();
}
private void mntm_Manipulator_6() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f min = new Vector4f(c3d.getManipulator().getPosition());
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
min = vm.getMinimalDistanceVertexToSurfaces(new Vertex(c3d.getManipulator().getPosition())).toVector4f();
c3d.getManipulator().getPosition().set(min.x, min.y, min.z, 1f);
c3d.getManipulator().setAccuratePosition(new BigDecimal(min.x / 1000f), new BigDecimal(min.y / 1000f), new BigDecimal(min.z / 1000f));
}
}
regainFocus();
}
private void mntm_Manipulator_7() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
float minDist = Float.MAX_VALUE;
Vector4f next = new Vector4f(c3d.getManipulator().getPosition());
Vertex min = null;
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Set<Vertex> vertices;
if (vm.getSelectedVertices().isEmpty()) {
vertices = vm.getVertices();
} else {
vertices = vm.getSelectedVertices();
}
for (Vertex vertex : vertices) {
Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null);
float d2 = sub.lengthSquared();
if (d2 < minDist) {
minDist = d2;
min = vertex;
}
}
vm = c3d.getLockableDatFileReference().getVertexManager();
Vector4f n = vm.getVertexNormal(min);
float tx = 1f;
float ty = 0f;
float tz = 0f;
if (n.x <= 0f) {
tx = -1;
}
if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
tz = tx;
tx = 0f;
ty = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) {
// ty = 0f;
// tz = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
ty = tx;
tx = 0f;
tz = 0f;
} else {
regainFocus();
return;
}
Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise();
c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f);
c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f);
Vector4f zaxis = c3d.getManipulator().getZaxis();
Vector4f xaxis = c3d.getManipulator().getXaxis();
cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null);
c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
regainFocus();
}
private void mntm_Manipulator_8() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Vector4f n = vm.getMinimalDistanceEdgeNormal(new Vertex(c3d.getManipulator().getPosition()));
float tx = 1f;
float ty = 0f;
float tz = 0f;
if (n.x <= 0f) {
tx = -1;
}
if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
tz = tx;
tx = 0f;
ty = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) {
// ty = 0f;
// tz = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
ty = tx;
tx = 0f;
tz = 0f;
} else {
regainFocus();
return;
}
Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise();
c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f);
c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f);
Vector4f zaxis = c3d.getManipulator().getZaxis();
Vector4f xaxis = c3d.getManipulator().getXaxis();
cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null);
c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
regainFocus();
}
private void mntm_Manipulator_9() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Vector4f n = vm.getMinimalDistanceSurfaceNormal(new Vertex(c3d.getManipulator().getPosition()));
float tx = 1f;
float ty = 0f;
float tz = 0f;
if (n.x <= 0f) {
tx = -1;
}
if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
tz = tx;
tx = 0f;
ty = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) {
// ty = 0f;
// tz = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
ty = tx;
tx = 0f;
tz = 0f;
} else {
regainFocus();
return;
}
Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise();
c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f);
c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f);
Vector4f zaxis = c3d.getManipulator().getZaxis();
Vector4f xaxis = c3d.getManipulator().getXaxis();
cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null);
c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
regainFocus();
}
private void mntm_Manipulator_XIV() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
vm.adjustRotationCenter(c3d, null);
}
}
regainFocus();
}
private void mntm_Manipulator_XV() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
float minDist = Float.MAX_VALUE;
Vector4f next = new Vector4f(c3d.getManipulator().getPosition());
Vertex min = null;
VertexManager vm = c3d.getLockableDatFileReference().getVertexManager();
Set<Vertex> vertices;
if (vm.getSelectedVertices().isEmpty()) {
vertices = vm.getVertices();
} else {
vertices = vm.getSelectedVertices();
}
for (Vertex vertex : vertices) {
Vector4f sub = Vector4f.sub(next, vertex.toVector4f(), null);
float d2 = sub.lengthSquared();
if (d2 < minDist) {
minDist = d2;
min = vertex;
}
}
vm = c3d.getLockableDatFileReference().getVertexManager();
Vector4f n = new Vector4f(min.x, min.y, min.z, 0f);
if (min.x == 0f && min.y == 0f && min.z == 0f) {
n = new Vector4f(0f, 0f, 1f, 0f);
}
n.normalise();
n.setW(1f);
float tx = 1f;
float ty = 0f;
float tz = 0f;
if (n.x <= 0f) {
tx = -1;
}
if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
tz = tx;
tx = 0f;
ty = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, 0f, 0f), null).length()) > .00001f) {
// ty = 0f;
// tz = 0f;
} else if (Math.abs(Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(0f, 0f, tx), null).length()) > .00001f) {
ty = tx;
tx = 0f;
tz = 0f;
} else {
regainFocus();
return;
}
Vector3f cross = (Vector3f) Vector3f.cross(new Vector3f(n.x, n.y, n.z), new Vector3f(tx, ty, tz), null).normalise();
c3d.getManipulator().getZaxis().set(n.x, n.y, n.z, 1f);
c3d.getManipulator().getXaxis().set(cross.x, cross.y, cross.z, 1f);
Vector4f zaxis = c3d.getManipulator().getZaxis();
Vector4f xaxis = c3d.getManipulator().getXaxis();
cross = Vector3f.cross(new Vector3f(xaxis.x, xaxis.y, xaxis.z), new Vector3f(zaxis.x, zaxis.y, zaxis.z), null);
c3d.getManipulator().getYaxis().set(cross.x, cross.y, cross.z, 1f);
c3d.getManipulator().setAccurateXaxis(new BigDecimal(c3d.getManipulator().getXaxis().x), new BigDecimal(c3d.getManipulator().getXaxis().y),
new BigDecimal(c3d.getManipulator().getXaxis().z));
c3d.getManipulator().setAccurateYaxis(new BigDecimal(c3d.getManipulator().getYaxis().x), new BigDecimal(c3d.getManipulator().getYaxis().y),
new BigDecimal(c3d.getManipulator().getYaxis().z));
c3d.getManipulator().setAccurateZaxis(new BigDecimal(c3d.getManipulator().getZaxis().x), new BigDecimal(c3d.getManipulator().getZaxis().y),
new BigDecimal(c3d.getManipulator().getZaxis().z));
}
}
regainFocus();
}
private void mntm_Manipulator_YZ() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f temp = new Vector4f(c3d.getManipulator().getZaxis());
c3d.getManipulator().getZaxis().set(c3d.getManipulator().getYaxis());
c3d.getManipulator().getYaxis().set(temp);
BigDecimal[] a = c3d.getManipulator().getAccurateYaxis().clone();
BigDecimal[] b = c3d.getManipulator().getAccurateZaxis().clone();
c3d.getManipulator().setAccurateYaxis(b[0], b[1], b[2]);
c3d.getManipulator().setAccurateZaxis(a[0], a[1], a[2]);
}
}
regainFocus();
}
private void mntm_Manipulator_XZ() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f temp = new Vector4f(c3d.getManipulator().getXaxis());
c3d.getManipulator().getXaxis().set(c3d.getManipulator().getZaxis());
c3d.getManipulator().getZaxis().set(temp);
BigDecimal[] a = c3d.getManipulator().getAccurateXaxis().clone();
BigDecimal[] b = c3d.getManipulator().getAccurateZaxis().clone();
c3d.getManipulator().setAccurateXaxis(b[0], b[1], b[2]);
c3d.getManipulator().setAccurateZaxis(a[0], a[1], a[2]);
}
}
regainFocus();
}
private void mntm_Manipulator_XY() {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(Project.getFileToEdit())) {
Vector4f temp = new Vector4f(c3d.getManipulator().getXaxis());
c3d.getManipulator().getXaxis().set(c3d.getManipulator().getYaxis());
c3d.getManipulator().getYaxis().set(temp);
BigDecimal[] a = c3d.getManipulator().getAccurateXaxis().clone();
BigDecimal[] b = c3d.getManipulator().getAccurateYaxis().clone();
c3d.getManipulator().setAccurateXaxis(b[0], b[1], b[2]);
c3d.getManipulator().setAccurateYaxis(a[0], a[1], a[2]);
}
}
regainFocus();
}
public boolean closeDatfile(DatFile df) {
boolean result2 = false;
if (Project.getUnsavedFiles().contains(df) && !df.isReadOnly()) {
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.CANCEL | SWT.NO);
messageBox.setText(I18n.DIALOG_UnsavedChangesTitle);
Object[] messageArguments = {df.getShortName()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_UnsavedChanges);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.NO) {
result2 = true;
} else if (result == SWT.YES) {
if (df.save()) {
Editor3DWindow.getWindow().addRecentFile(df);
result2 = true;
} else {
MessageBox messageBoxError = new MessageBox(getShell(), SWT.ICON_ERROR | SWT.OK);
messageBoxError.setText(I18n.DIALOG_Error);
messageBoxError.setMessage(I18n.DIALOG_CantSaveFile);
messageBoxError.open();
cleanupClosedData();
updateTree_unsavedEntries();
regainFocus();
return false;
}
} else {
cleanupClosedData();
updateTree_unsavedEntries();
regainFocus();
return false;
}
} else {
result2 = true;
}
updateTree_removeEntry(df);
cleanupClosedData();
regainFocus();
return result2;
}
private void openFileIn3DEditor(final DatFile df) {
if (renders.isEmpty()) {
if ("%EMPTY%".equals(Editor3DWindow.getSashForm().getChildren()[1].getData())) { //$NON-NLS-1$
int[] mainSashWeights = Editor3DWindow.getSashForm().getWeights();
Editor3DWindow.getSashForm().getChildren()[1].dispose();
CompositeContainer cmp_Container = new CompositeContainer(Editor3DWindow.getSashForm(), false);
cmp_Container.moveBelow(Editor3DWindow.getSashForm().getChildren()[0]);
df.parseForData(true);
Project.setFileToEdit(df);
cmp_Container.getComposite3D().setLockableDatFileReference(df);
df.getVertexManager().addSnapshot();
Editor3DWindow.getSashForm().getParent().layout();
Editor3DWindow.getSashForm().setWeights(mainSashWeights);
}
} else {
boolean canUpdate = false;
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (!c3d.isDatFileLockedOnDisplay()) {
canUpdate = true;
break;
}
}
if (!canUpdate) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().switchLockedDat(false);
}
}
final VertexManager vm = df.getVertexManager();
if (vm.isModified()) {
df.setText(df.getText());
}
df.parseForData(true);
Project.setFileToEdit(df);
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (!c3d.isDatFileLockedOnDisplay()) {
boolean hasState = hasState(df, c3d);
c3d.setLockableDatFileReference(df);
if (!hasState) c3d.getModifier().zoomToFit();
}
}
df.getVertexManager().addSnapshot();
if (!canUpdate) {
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
c3d.getModifier().switchLockedDat(true);
}
}
}
}
public void selectTabWithDatFile(DatFile df) {
for (CTabItem ti : tabFolder_OpenDatFiles[0].getItems()) {
if (df.equals(ti.getData())) {
tabFolder_OpenDatFiles[0].setSelection(ti);
openFileIn3DEditor(df);
cleanupClosedData();
regainFocus();
break;
}
}
}
public static AtomicBoolean getNoSyncDeadlock() {
return no_sync_deadlock;
}
public boolean revert(DatFile df) {
if (df.isReadOnly() || !Project.getUnsavedFiles().contains(df) || df.isVirtual() && df.getText().trim().isEmpty()) {
regainFocus();
return false;
}
df.getVertexManager().addSnapshot();
MessageBox messageBox = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox.setText(I18n.DIALOG_RevertTitle);
Object[] messageArguments = {df.getShortName(), df.getLastSavedOpened()};
MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$
formatter.setLocale(MyLanguage.LOCALE);
formatter.applyPattern(I18n.DIALOG_Revert);
messageBox.setMessage(formatter.format(messageArguments));
int result = messageBox.open();
if (result == SWT.NO) {
regainFocus();
return false;
}
boolean canUpdate = false;
for (OpenGLRenderer renderer : renders) {
Composite3D c3d = renderer.getC3D();
if (c3d.getLockableDatFileReference().equals(df)) {
canUpdate = true;
break;
}
}
EditorTextWindow tmpW = null;
CTabItem tmpT = null;
for (EditorTextWindow w : Project.getOpenTextWindows()) {
for (CTabItem t : w.getTabFolder().getItems()) {
if (df.equals(((CompositeTab) t).getState().getFileNameObj())) {
canUpdate = true;
tmpW = w;
tmpT = t;
break;
}
}
}
df.setText(df.getOriginalText());
df.setOldName(df.getNewName());
if (!df.isVirtual()) {
Project.removeUnsavedFile(df);
updateTree_unsavedEntries();
}
if (canUpdate) {
df.parseForData(true);
df.getVertexManager().setModified(true, true);
if (tmpW != null) {
tmpW.getTabFolder().setSelection(tmpT);
((CompositeTab) tmpT).getControl().getShell().forceActive();
if (tmpW.isSeperateWindow()) {
tmpW.open();
}
((CompositeTab) tmpT).getTextComposite().forceFocus();
}
}
return true;
}
public void saveState(final DatFile df, final Composite3D c3d) {
if (df == null || c3d == null) {
return;
}
{
HashMap<Composite3D, org.nschmidt.ldparteditor.composites.Composite3DViewState> states = new HashMap<>();
if (c3dStates.containsKey(df)) {
states = c3dStates.get(df);
} else {
c3dStates.put(df, states);
}
states.remove(c3d);
states.put(c3d, c3d.exportState());
}
// Cleanup old states
{
HashSet<DatFile> allFiles = new HashSet<DatFile>();
for (CTabItem ci : tabFolder_OpenDatFiles[0].getItems()) {
allFiles.add((DatFile) ci.getData());
}
HashSet<DatFile> cachedStates = new HashSet<DatFile>();
cachedStates.addAll(c3dStates.keySet());
for (DatFile d : cachedStates) {
if (!allFiles.contains(d)) {
c3dStates.remove(d);
}
}
}
}
public void loadState(final DatFile df, final Composite3D c3d) {
if (df == null || c3d == null) {
return;
}
if (c3dStates.containsKey(df)) {
HashMap<Composite3D, org.nschmidt.ldparteditor.composites.Composite3DViewState> states = c3dStates.get(df);
if (states.containsKey(c3d)) {
c3d.importState(states.get(c3d));
}
}
}
public boolean hasState(final DatFile df, final Composite3D c3d) {
return c3dStates.containsKey(df) && c3dStates.get(df).containsKey(c3d);
}
}
| Fixed issue #395. | src/org/nschmidt/ldparteditor/shells/editor3d/Editor3DWindow.java | Fixed issue #395. |
|
Java | mit | 31fafa71f77ac371854dbdae60aa199f483a1c94 | 0 | curioswitch/curiostack,curioswitch/curiostack,curioswitch/curiostack,curioswitch/curiostack,curioswitch/curiostack,curioswitch/curiostack,curioswitch/curiostack,curioswitch/curiostack,curioswitch/curiostack,curioswitch/curiostack | /*
* MIT License
*
* Copyright (c) 2019 Choko ([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 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.curioswitch.common.protobuf.json;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.CharMatcher;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.JavaType;
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.Message;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import javax.annotation.Nullable;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
/**
* A wrapper of a {@link FieldDescriptor} to provide additional information like protobuf generated
* code naming conventions and value type information.
*/
class ProtoFieldInfo {
private static final CharMatcher DIGITS_ASCII = CharMatcher.inRange('0', '9');
private static final CharMatcher LOWERCASE_ASCII = CharMatcher.inRange('a', 'z');
private static final CharMatcher UPPERCASE_ASCII = CharMatcher.inRange('A', 'Z');
private final FieldDescriptor field;
private final Message containingPrototype;
private final Class<? extends Message.Builder> builderClass;
private final String camelCaseName;
@Nullable private final ProtoFieldInfo mapKeyField;
@Nullable private final ProtoFieldInfo mapValueField;
ProtoFieldInfo(FieldDescriptor field, Message containingPrototype) {
this.field = checkNotNull(field, "field");
this.containingPrototype = checkNotNull(containingPrototype, "containingPrototype");
builderClass = containingPrototype.newBuilderForType().getClass();
camelCaseName = underscoresToUpperCamelCase(field.getName());
if (field.isMapField()) {
Descriptor mapType = field.getMessageType();
mapKeyField = new ProtoFieldInfo(mapType.findFieldByName("key"), containingPrototype);
mapValueField = new ProtoFieldInfo(mapType.findFieldByName("value"), containingPrototype);
} else {
mapKeyField = null;
mapValueField = null;
}
}
/** Returns the raw {@link FieldDescriptor} for this field. */
FieldDescriptor descriptor() {
return field;
}
/** Returns whether this is a map field. */
@EnsuresNonNullIf(
expression = {"mapKeyField", "mapValueField"},
result = true)
boolean isMapField() {
return field.isMapField();
}
/**
* Returns whether this is a repeated field. Note, map fields are also considered repeated fields.
*/
boolean isRepeated() {
return field.isRepeated();
}
/** Returns the {@link ProtoFieldInfo} of the key for this map field. */
@Nullable
ProtoFieldInfo mapKeyField() {
checkState(isMapField(), "Not a map field: %s", field);
return mapKeyField;
}
/**
* Returns the {@link ProtoFieldInfo} describing the actual value of this field, which for map
* fields is the map's value.
*/
ProtoFieldInfo valueField() {
return mapValueField != null ? mapValueField : this;
}
/**
* Returns the {@link Type} of the actual value of this field, which for map fields is the type of
* the map's value.
*/
FieldDescriptor.Type valueType() {
return valueField().descriptor().getType();
}
/**
* Returns the {@link JavaType} of the actual value of this field, which for map fields is the
* type of the map's value.
*/
FieldDescriptor.JavaType valueJavaType() {
return valueField().descriptor().getJavaType();
}
/**
* Returns a prototype {@link Message} for the value of this field. For maps, it will be for the
* value field of the map, otherwise it is for the field itself.
*/
Message valuePrototype() {
Message nestedPrototype =
containingPrototype.newBuilderForType().newBuilderForField(field).buildPartial();
if (isMapField()) {
// newBuilderForField will give us the Message corresponding to the map with key and value,
// but we want the marshaller for the value itself.
nestedPrototype = (Message) nestedPrototype.getField(mapValueField.descriptor());
}
return nestedPrototype;
}
/**
* Returns the method to get the value for the field within its message. The message must already
* be on the execution stack. For map fields, this will be the method that returns a {@link
* java.util.Map} and for repeated fields it will be the method that returns a {@link List}.
*/
Method getValueMethod() {
StringBuilder methodName = new StringBuilder().append("get").append(camelCaseName);
if (valueJavaType() == JavaType.ENUM) {
methodName.append("Value");
}
if (isMapField()) {
methodName.append("Map");
} else if (field.isRepeated()) {
methodName.append("List");
}
try {
return containingPrototype.getClass().getDeclaredMethod(methodName.toString());
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find generated getter method.", e);
}
}
/**
* Returns the getter for the currently set value of this field's oneof. Must only be called for
* oneof fields, which can be checked using {@link #isInOneof()}.
*/
Method oneOfCaseMethod() {
checkState(isInOneof(), "field is not in a oneof");
String methodName =
"get" + underscoresToUpperCamelCase(field.getContainingOneof().getName()) + "Case";
try {
return containingPrototype.getClass().getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find generated oneof case method.", e);
}
}
/**
* Returns the method to determine whether the message has a value for this field. Only valid for
* message types for proto3 messages, valid for all fields otherwise.
*/
Method hasValueMethod() {
String methodName = "has" + camelCaseName;
try {
return containingPrototype.getClass().getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find generated has method.", e);
}
}
/**
* Returns the {@link Method} that returns the current count of a repeated field. Must only be
* called for repeated fields, which can be checked with {@link #isRepeated()}.
*/
Method repeatedValueCountMethod() {
String methodName = "get" + camelCaseName + "Count";
try {
return containingPrototype.getClass().getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find repeated field count method.", e);
}
}
/**
* Returns the {@link Method} that sets a single value of the field. For repeated and map fields,
* this is the add or put method that only take an individual element;
*/
Method setValueMethod() {
StringBuilder setter = new StringBuilder();
final Class<?>[] args;
if (isMapField()) {
setter.append("put");
args = new Class<?>[] {mapKeyField.javaClass(), javaClass()};
} else {
args = new Class<?>[] {javaClass()};
if (field.isRepeated()) {
setter.append("add");
} else {
setter.append("set");
}
}
setter.append(camelCaseName);
if (valueType() == Type.ENUM) {
setter.append("Value");
}
try {
return builderClass.getDeclaredMethod(setter.toString(), args);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find setter.", e);
}
}
/** Returns whether this field is in a oneof. */
boolean isInOneof() {
return field.getContainingOneof() != null;
}
/**
* Returns the getter for the currently set value of this field's oneof. Must only be called for
* oneof fields, which can be checked using {@link #isInOneof()}.
*/
String getOneOfCaseMethodName() {
checkState(isInOneof(), "field is not in a oneof");
return "get" + underscoresToUpperCamelCase(field.getContainingOneof().getName()) + "Case";
}
/**
* Determine the {@link Enum} class corresponding to this field's value. Because {@link Enum}
* classes themselves are generated, we must introspect the prototype for determining the concrete
* class. Due to type erasure, for repeated types we actually use protobuf reflection to add a
* value to the container and retrieve it to determine the concrete type at runtime.
*/
Class<?> enumClass() {
Class<? extends Message> messageClass = containingPrototype.getClass();
if (!field.isRepeated()) {
return getEnumAsClassMethod().getReturnType();
}
if (isMapField()) {
checkArgument(
valueJavaType() == JavaType.ENUM,
"Trying to determine enum class of non-enum type: %s",
field);
Message msgWithEnumValue =
containingPrototype
.newBuilderForType()
.addRepeatedField(
field,
containingPrototype
.newBuilderForType()
.newBuilderForField(field)
.setField(
mapKeyField.descriptor(), mapKeyField.descriptor().getDefaultValue())
.setField(
mapValueField.descriptor(), mapValueField.descriptor().getDefaultValue())
.build())
.build();
try {
return messageClass
.getDeclaredMethod(
getMapValueOrThrowMethodName(),
new ProtoFieldInfo(mapKeyField.descriptor(), containingPrototype).javaClass())
.invoke(msgWithEnumValue, mapKeyField.descriptor().getDefaultValue())
.getClass();
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalStateException("Could not find or invoke map item getter.", e);
}
}
// Repeated field.
// Enums always have at least one value, so we can call getValues().get(0) without checking.
Message msgWithEnumValue =
containingPrototype
.newBuilderForType()
.addRepeatedField(
valueField().descriptor(),
valueField().descriptor().getEnumType().getValues().get(0))
.build();
try {
return ((List<?>) getEnumAsClassMethod().invoke(msgWithEnumValue)).get(0).getClass();
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException("Could not invoke enum getter for determining type.", e);
}
}
/**
* Return the Java {@link Class} that corresponds to the value of this field. Generally used for
* method resolution and casting generics.
*/
Class<?> javaClass() {
if (isMapField() && valueJavaType() == JavaType.MESSAGE) {
Message mapEntry = containingPrototype.newBuilderForType().newBuilderForField(field).build();
return mapEntry.getField(mapEntry.getDescriptorForType().findFieldByName("value")).getClass();
}
switch (valueJavaType()) {
case INT:
return int.class;
case LONG:
return long.class;
case FLOAT:
return float.class;
case DOUBLE:
return double.class;
case BOOLEAN:
return boolean.class;
case STRING:
return String.class;
case BYTE_STRING:
return ByteString.class;
case ENUM:
return int.class;
case MESSAGE:
return containingPrototype
.newBuilderForType()
.newBuilderForField(valueField().descriptor())
.buildPartial()
.getClass();
default:
throw new IllegalArgumentException("Unknown field type: " + valueJavaType());
}
}
/**
* Returns the name of the method that returns the value of a map field. Must only be called for
* map fields, which can be checked using {@link #isMapField()}.
*/
private String getMapValueOrThrowMethodName() {
checkState(isMapField(), "field is not a map");
return "get" + camelCaseName + "OrThrow";
}
/**
* Returns the {@link Method} that returns the value for this enum field within the message. Used
* for introspection of the concrete Java type of an enum.
*/
private Method getEnumAsClassMethod() {
String getter = "get" + camelCaseName;
if (field.isMapField()) {
getter += "Map";
} else if (field.isRepeated()) {
getter += "List";
}
try {
return containingPrototype.getClass().getDeclaredMethod(getter);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find getter for enum field.", e);
}
}
// Guava's CaseFormat does not handle non-snake-case field names the same as protobuf compiler,
// so we just directly port the compiler's code from here:
// https://github.com/google/protobuf/blob/2f4489a3e504e0a4aaffee69b551c6acc9e08374/src/google/protobuf/compiler/cpp/cpp_helpers.cc#L108
private static String underscoresToUpperCamelCase(String input) {
boolean capitalizeNextLetter = true;
StringBuilder result = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (LOWERCASE_ASCII.matches(c)) {
if (capitalizeNextLetter) {
result.append((char) (c + ('A' - 'a')));
} else {
result.append(c);
}
capitalizeNextLetter = false;
} else if (UPPERCASE_ASCII.matches(c)) {
// Capital letters are left as-is.
result.append(c);
capitalizeNextLetter = false;
} else if (DIGITS_ASCII.matches(c)) {
result.append(c);
capitalizeNextLetter = true;
} else {
capitalizeNextLetter = true;
}
}
return result.toString();
}
}
| common/grpc/protobuf-jackson/src/main/java/org/curioswitch/common/protobuf/json/ProtoFieldInfo.java | /*
* MIT License
*
* Copyright (c) 2019 Choko ([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 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.curioswitch.common.protobuf.json;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.CharMatcher;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.JavaType;
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.Message;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import javax.annotation.Nullable;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
/**
* A wrapper of a {@link FieldDescriptor} to provide additional information like protobuf generated
* code naming conventions and value type information.
*/
class ProtoFieldInfo {
private static final CharMatcher DIGITS_ASCII = CharMatcher.inRange('0', '9');
private static final CharMatcher LOWERCASE_ASCII = CharMatcher.inRange('a', 'z');
private static final CharMatcher UPPERCASE_ASCII = CharMatcher.inRange('A', 'Z');
private final FieldDescriptor field;
private final Message containingPrototype;
private final Class<? extends Message.Builder> builderClass;
private final String camelCaseName;
@Nullable private final ProtoFieldInfo mapKeyField;
@Nullable private final ProtoFieldInfo mapValueField;
ProtoFieldInfo(FieldDescriptor field, Message containingPrototype) {
this.field = checkNotNull(field, "field");
this.containingPrototype = checkNotNull(containingPrototype, "containingPrototype");
builderClass = containingPrototype.newBuilderForType().getClass();
camelCaseName = underscoresToUpperCamelCase(field.getName());
if (field.isMapField()) {
Descriptor mapType = field.getMessageType();
mapKeyField = new ProtoFieldInfo(mapType.findFieldByName("key"), containingPrototype);
mapValueField = new ProtoFieldInfo(mapType.findFieldByName("value"), containingPrototype);
} else {
mapKeyField = null;
mapValueField = null;
}
}
/** Returns the raw {@link FieldDescriptor} for this field. */
FieldDescriptor descriptor() {
return field;
}
/** Returns whether this is a map field. */
@EnsuresNonNullIf(
expression = {"mapKeyField", "mapValueField"},
result = true)
boolean isMapField() {
return field.isMapField();
}
/**
* Returns whether this is a repeated field. Note, map fields are also considered repeated fields.
*/
boolean isRepeated() {
return field.isRepeated();
}
/** Returns the {@link ProtoFieldInfo} of the key for this map field. */
@Nullable
ProtoFieldInfo mapKeyField() {
checkState(isMapField(), "Not a map field: %s", field);
return mapKeyField;
}
/**
* Returns the {@link ProtoFieldInfo} describing the actual value of this field, which for map
* fields is the map's value.
*/
ProtoFieldInfo valueField() {
return mapValueField != null ? mapValueField : this;
}
/**
* Returns the {@link Type} of the actual value of this field, which for map fields is the type of
* the map's value.
*/
FieldDescriptor.Type valueType() {
return valueField().descriptor().getType();
}
/**
* Returns the {@link JavaType} of the actual value of this field, which for map fields is the
* type of the map's value.
*/
FieldDescriptor.JavaType valueJavaType() {
return valueField().descriptor().getJavaType();
}
/**
* Returns a prototype {@link Message} for the value of this field. For maps, it will be for the
* value field of the map, otherwise it is for the field itself.
*/
Message valuePrototype() {
Message nestedPrototype =
containingPrototype.newBuilderForType().newBuilderForField(field).build();
if (isMapField()) {
// newBuilderForField will give us the Message corresponding to the map with key and value,
// but we want the marshaller for the value itself.
nestedPrototype = (Message) nestedPrototype.getField(mapValueField.descriptor());
}
return nestedPrototype;
}
/**
* Returns the method to get the value for the field within its message. The message must already
* be on the execution stack. For map fields, this will be the method that returns a {@link
* java.util.Map} and for repeated fields it will be the method that returns a {@link List}.
*/
Method getValueMethod() {
StringBuilder methodName = new StringBuilder().append("get").append(camelCaseName);
if (valueJavaType() == JavaType.ENUM) {
methodName.append("Value");
}
if (isMapField()) {
methodName.append("Map");
} else if (field.isRepeated()) {
methodName.append("List");
}
try {
return containingPrototype.getClass().getDeclaredMethod(methodName.toString());
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find generated getter method.", e);
}
}
/**
* Returns the getter for the currently set value of this field's oneof. Must only be called for
* oneof fields, which can be checked using {@link #isInOneof()}.
*/
Method oneOfCaseMethod() {
checkState(isInOneof(), "field is not in a oneof");
String methodName =
"get" + underscoresToUpperCamelCase(field.getContainingOneof().getName()) + "Case";
try {
return containingPrototype.getClass().getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find generated oneof case method.", e);
}
}
/**
* Returns the method to determine whether the message has a value for this field. Only valid for
* message types for proto3 messages, valid for all fields otherwise.
*/
Method hasValueMethod() {
String methodName = "has" + camelCaseName;
try {
return containingPrototype.getClass().getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find generated has method.", e);
}
}
/**
* Returns the {@link Method} that returns the current count of a repeated field. Must only be
* called for repeated fields, which can be checked with {@link #isRepeated()}.
*/
Method repeatedValueCountMethod() {
String methodName = "get" + camelCaseName + "Count";
try {
return containingPrototype.getClass().getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find repeated field count method.", e);
}
}
/**
* Returns the {@link Method} that sets a single value of the field. For repeated and map fields,
* this is the add or put method that only take an individual element;
*/
Method setValueMethod() {
StringBuilder setter = new StringBuilder();
final Class<?>[] args;
if (isMapField()) {
setter.append("put");
args = new Class<?>[] {mapKeyField.javaClass(), javaClass()};
} else {
args = new Class<?>[] {javaClass()};
if (field.isRepeated()) {
setter.append("add");
} else {
setter.append("set");
}
}
setter.append(camelCaseName);
if (valueType() == Type.ENUM) {
setter.append("Value");
}
try {
return builderClass.getDeclaredMethod(setter.toString(), args);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find setter.", e);
}
}
/** Returns whether this field is in a oneof. */
boolean isInOneof() {
return field.getContainingOneof() != null;
}
/**
* Returns the getter for the currently set value of this field's oneof. Must only be called for
* oneof fields, which can be checked using {@link #isInOneof()}.
*/
String getOneOfCaseMethodName() {
checkState(isInOneof(), "field is not in a oneof");
return "get" + underscoresToUpperCamelCase(field.getContainingOneof().getName()) + "Case";
}
/**
* Determine the {@link Enum} class corresponding to this field's value. Because {@link Enum}
* classes themselves are generated, we must introspect the prototype for determining the concrete
* class. Due to type erasure, for repeated types we actually use protobuf reflection to add a
* value to the container and retrieve it to determine the concrete type at runtime.
*/
Class<?> enumClass() {
Class<? extends Message> messageClass = containingPrototype.getClass();
if (!field.isRepeated()) {
return getEnumAsClassMethod().getReturnType();
}
if (isMapField()) {
checkArgument(
valueJavaType() == JavaType.ENUM,
"Trying to determine enum class of non-enum type: %s",
field);
Message msgWithEnumValue =
containingPrototype
.newBuilderForType()
.addRepeatedField(
field,
containingPrototype
.newBuilderForType()
.newBuilderForField(field)
.setField(
mapKeyField.descriptor(), mapKeyField.descriptor().getDefaultValue())
.setField(
mapValueField.descriptor(), mapValueField.descriptor().getDefaultValue())
.build())
.build();
try {
return messageClass
.getDeclaredMethod(
getMapValueOrThrowMethodName(),
new ProtoFieldInfo(mapKeyField.descriptor(), containingPrototype).javaClass())
.invoke(msgWithEnumValue, mapKeyField.descriptor().getDefaultValue())
.getClass();
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new IllegalStateException("Could not find or invoke map item getter.", e);
}
}
// Repeated field.
// Enums always have at least one value, so we can call getValues().get(0) without checking.
Message msgWithEnumValue =
containingPrototype
.newBuilderForType()
.addRepeatedField(
valueField().descriptor(),
valueField().descriptor().getEnumType().getValues().get(0))
.build();
try {
return ((List<?>) getEnumAsClassMethod().invoke(msgWithEnumValue)).get(0).getClass();
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException("Could not invoke enum getter for determining type.", e);
}
}
/**
* Return the Java {@link Class} that corresponds to the value of this field. Generally used for
* method resolution and casting generics.
*/
Class<?> javaClass() {
if (isMapField() && valueJavaType() == JavaType.MESSAGE) {
Message mapEntry = containingPrototype.newBuilderForType().newBuilderForField(field).build();
return mapEntry.getField(mapEntry.getDescriptorForType().findFieldByName("value")).getClass();
}
switch (valueJavaType()) {
case INT:
return int.class;
case LONG:
return long.class;
case FLOAT:
return float.class;
case DOUBLE:
return double.class;
case BOOLEAN:
return boolean.class;
case STRING:
return String.class;
case BYTE_STRING:
return ByteString.class;
case ENUM:
return int.class;
case MESSAGE:
return containingPrototype
.newBuilderForType()
.newBuilderForField(valueField().descriptor())
.build()
.getClass();
default:
throw new IllegalArgumentException("Unknown field type: " + valueJavaType());
}
}
/**
* Returns the name of the method that returns the value of a map field. Must only be called for
* map fields, which can be checked using {@link #isMapField()}.
*/
private String getMapValueOrThrowMethodName() {
checkState(isMapField(), "field is not a map");
return "get" + camelCaseName + "OrThrow";
}
/**
* Returns the {@link Method} that returns the value for this enum field within the message. Used
* for introspection of the concrete Java type of an enum.
*/
private Method getEnumAsClassMethod() {
String getter = "get" + camelCaseName;
if (field.isMapField()) {
getter += "Map";
} else if (field.isRepeated()) {
getter += "List";
}
try {
return containingPrototype.getClass().getDeclaredMethod(getter);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find getter for enum field.", e);
}
}
// Guava's CaseFormat does not handle non-snake-case field names the same as protobuf compiler,
// so we just directly port the compiler's code from here:
// https://github.com/google/protobuf/blob/2f4489a3e504e0a4aaffee69b551c6acc9e08374/src/google/protobuf/compiler/cpp/cpp_helpers.cc#L108
private static String underscoresToUpperCamelCase(String input) {
boolean capitalizeNextLetter = true;
StringBuilder result = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (LOWERCASE_ASCII.matches(c)) {
if (capitalizeNextLetter) {
result.append((char) (c + ('A' - 'a')));
} else {
result.append(c);
}
capitalizeNextLetter = false;
} else if (UPPERCASE_ASCII.matches(c)) {
// Capital letters are left as-is.
result.append(c);
capitalizeNextLetter = false;
} else if (DIGITS_ASCII.matches(c)) {
result.append(c);
capitalizeNextLetter = true;
} else {
capitalizeNextLetter = true;
}
}
return result.toString();
}
}
| support proto version 2 for armeria (#604)
| common/grpc/protobuf-jackson/src/main/java/org/curioswitch/common/protobuf/json/ProtoFieldInfo.java | support proto version 2 for armeria (#604) |
|
Java | mit | 820b3cf736b42085096c4dc8d1fe1720092e589e | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.assessment.controller;
import org.innovateuk.ifs.BaseControllerIntegrationTest;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.assessment.panel.domain.AssessmentReview;
import org.innovateuk.ifs.assessment.panel.repository.AssessmentReviewRepository;
import org.innovateuk.ifs.assessment.panel.resource.AssessmentReviewRejectOutcomeResource;
import org.innovateuk.ifs.assessment.panel.resource.AssessmentReviewState;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.domain.Milestone;
import org.innovateuk.ifs.competition.repository.CompetitionRepository;
import org.innovateuk.ifs.competition.repository.MilestoneRepository;
import org.innovateuk.ifs.competition.resource.MilestoneType;
import org.innovateuk.ifs.invite.constant.InviteStatus;
import org.innovateuk.ifs.invite.domain.competition.AssessmentPanelInvite;
import org.innovateuk.ifs.invite.domain.competition.AssessmentPanelParticipant;
import org.innovateuk.ifs.invite.repository.AssessmentPanelInviteRepository;
import org.innovateuk.ifs.invite.repository.AssessmentPanelParticipantRepository;
import org.innovateuk.ifs.user.domain.ProcessRole;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.repository.ProcessRoleRepository;
import org.innovateuk.ifs.user.repository.UserRepository;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.innovateuk.ifs.workflow.domain.ActivityType;
import org.innovateuk.ifs.workflow.repository.ActivityStateRepository;
import org.innovateuk.ifs.workflow.resource.State;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.ZonedDateTime;
import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication;
import static org.innovateuk.ifs.assessment.builder.AssessmentReviewRejectOutcomeResourceBuilder.newAssessmentReviewRejectOutcomeResource;
import static org.innovateuk.ifs.assessment.panel.builder.AssessmentPanelInviteBuilder.newAssessmentPanelInvite;
import static org.innovateuk.ifs.assessment.panel.builder.AssessmentReviewBuilder.newAssessmentReview;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.id;
import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition;
import static org.innovateuk.ifs.competition.builder.MilestoneBuilder.newMilestone;
import static org.innovateuk.ifs.user.builder.ProcessRoleBuilder.newProcessRole;
import static org.innovateuk.ifs.user.builder.UserBuilder.newUser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class AssessmentPanelControllerIntegrationTest extends BaseControllerIntegrationTest<AssessmentPanelController> {
private static final long applicationId = 2L;
private static final long competitionId = 3L;
private Application application;
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private CompetitionRepository competitionRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private AssessmentPanelInviteRepository assessmentPanelInviteRepository;
@Autowired
private ProcessRoleRepository processRoleRepository;
@Autowired
private AssessmentPanelParticipantRepository assessmentPanelParticipantRepository;
@Autowired
private ActivityStateRepository activityStateRepository;
@Autowired
private AssessmentReviewRepository assessmentReviewRepository;
@Autowired
private MilestoneRepository milestoneRepository;
@Autowired
@Override
public void setControllerUnderTest(AssessmentPanelController controller) {
this.controller = controller;
}
@Before
public void setUp() {
loginCompAdmin();
}
@After
public void clearDown() {
flushAndClearSession();
}
@Test
public void assignApplication() throws Exception {
application = newApplication()
.withId(applicationId)
.withAssessmentPanelStatus(false)
.build();
applicationRepository.save(application);
RestResult<Void> result = controller.assignApplication(application.getId());
assertTrue(result.isSuccess());
application = applicationRepository.findOne(applicationId);
assertTrue(application.isInAssessmentPanel());
}
@Test
public void unAssignApplication() throws Exception {
application = newApplication()
.withId(applicationId)
.withAssessmentPanelStatus(true)
.build();
applicationRepository.save(application);
RestResult<Void> result = controller.unAssignApplication(application.getId());
assertTrue(result.isSuccess());
application = applicationRepository.findOne(applicationId);
assertFalse(application.isInAssessmentPanel());
}
@Test
public void notifyAssessors() {
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Milestone milestone = newMilestone()
.with(id(null))
.withCompetition(competition)
.withType(MilestoneType.ASSESSMENT_PANEL)
.withDate(ZonedDateTime.parse("2017-12-18T12:00:00+00:00"))
.build();
milestoneRepository.save(milestone);
User user = newUser()
.with(id(null))
.withEmailAddress("[email protected]")
.withUid("foo")
.build();
userRepository.save(user);
AssessmentPanelInvite assessmentPanelInvite = newAssessmentPanelInvite()
.with(id(null))
.withCompetition(competition)
.withUser(user)
.withEmail("[email protected]")
.withStatus(InviteStatus.SENT)
.withName("tom baldwin")
.build();
assessmentPanelInviteRepository.save(assessmentPanelInvite);
AssessmentPanelParticipant assessmentPanelParticipant = new AssessmentPanelParticipant(assessmentPanelInvite);
assessmentPanelParticipant.getInvite().open();
assessmentPanelParticipant.acceptAndAssignUser(user);
assessmentPanelParticipantRepository.save(assessmentPanelParticipant);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
flushAndClearSession();
controller.notifyAssessors(competition.getId()).getSuccessObjectOrThrowException();
assertTrue(assessmentReviewRepository.existsByTargetCompetitionIdAndActivityStateState(competition.getId(), State.PENDING));
}
@Test
public void isPendingReviewNotifications() {
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Milestone milestone = newMilestone()
.with(id(null))
.withCompetition(competition)
.withType(MilestoneType.ASSESSMENT_PANEL)
.withDate(ZonedDateTime.parse("2017-12-18T12:00:00+00:00"))
.build();
milestoneRepository.save(milestone);
User user = newUser()
.with(id(null))
.withEmailAddress("[email protected]")
.withUid("foo")
.build();
userRepository.save(user);
AssessmentPanelInvite assessmentPanelInvite = newAssessmentPanelInvite()
.with(id(null))
.withCompetition(competition)
.withUser(user)
.withEmail("[email protected]")
.withStatus(InviteStatus.SENT)
.withName("tom baldwin")
.build();
assessmentPanelInviteRepository.save(assessmentPanelInvite);
AssessmentPanelParticipant assessmentPanelParticipant = new AssessmentPanelParticipant(assessmentPanelInvite);
assessmentPanelParticipant.getInvite().open();
assessmentPanelParticipant.acceptAndAssignUser(user);
assessmentPanelParticipantRepository.save(assessmentPanelParticipant);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
flushAndClearSession();
assertTrue(controller.isPendingReviewNotifications(competition.getId()).getSuccessObjectOrThrowException());
}
@Test
public void isPendingReviewNotifications_reviewExists() {
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Milestone milestone = newMilestone()
.with(id(null))
.withCompetition(competition)
.withType(MilestoneType.ASSESSMENT_PANEL)
.withDate(ZonedDateTime.parse("2017-12-18T12:00:00+00:00"))
.build();
milestoneRepository.save(milestone);
User user = newUser()
.with(id(null))
.withEmailAddress("[email protected]")
.withUid("foo")
.build();
userRepository.save(user);
AssessmentPanelInvite assessmentPanelInvite = newAssessmentPanelInvite()
.with(id(null))
.withCompetition(competition)
.withUser(user)
.withEmail("[email protected]")
.withStatus(InviteStatus.SENT)
.withName("tom baldwin")
.build();
assessmentPanelInviteRepository.save(assessmentPanelInvite);
AssessmentPanelParticipant assessmentPanelParticipant = new AssessmentPanelParticipant(assessmentPanelInvite);
assessmentPanelParticipant.getInvite().open();
assessmentPanelParticipant.acceptAndAssignUser(user);
assessmentPanelParticipantRepository.save(assessmentPanelParticipant);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
ProcessRole processRole = newProcessRole()
.with(id(null))
.withUser(user)
.withApplication(application)
.withRole(UserRoleType.PANEL_ASSESSOR)
.build();
processRoleRepository.save(processRole);
AssessmentReview assessmentReview =
newAssessmentReview()
.with(id(null))
.withParticipant(processRole)
.withTarget(application)
.build();
assessmentReview.setActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_PANEL_APPLICATION_INVITE, State.CREATED));
assessmentReviewRepository.save(assessmentReview);
flushAndClearSession();
assertFalse(controller.isPendingReviewNotifications(competition.getId()).getSuccessObjectOrThrowException());
}
@Test
public void isPendingReviewNotifications_withdrawnReviewExists() {
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Milestone milestone = newMilestone()
.with(id(null))
.withCompetition(competition)
.withType(MilestoneType.ASSESSMENT_PANEL)
.withDate(ZonedDateTime.parse("2017-12-18T12:00:00+00:00"))
.build();
milestoneRepository.save(milestone);
User user = newUser()
.with(id(null))
.withEmailAddress("[email protected]")
.withUid("foo")
.build();
userRepository.save(user);
AssessmentPanelInvite competitionAssessmentInvite = newAssessmentPanelInvite()
.with(id(null))
.withCompetition(competition)
.withUser(user)
.withEmail("[email protected]")
.withStatus(InviteStatus.SENT)
.withName("tom baldwin")
.build();
assessmentPanelInviteRepository.save(competitionAssessmentInvite);
AssessmentPanelParticipant assessmentPanelParticipant = new AssessmentPanelParticipant(competitionAssessmentInvite);
assessmentPanelParticipant.getInvite().open();
assessmentPanelParticipant.acceptAndAssignUser(user);
assessmentPanelParticipantRepository.save(assessmentPanelParticipant);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
ProcessRole processRole = newProcessRole()
.with(id(null))
.withUser(user)
.withApplication(application)
.withRole(UserRoleType.PANEL_ASSESSOR)
.build();
processRoleRepository.save(processRole);
AssessmentReview assessmentReview =
newAssessmentReview()
.with(id(null))
.withParticipant(processRole)
.withTarget(application)
.build();
assessmentReview.setActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_PANEL_APPLICATION_INVITE, State.WITHDRAWN));
assessmentReviewRepository.save(assessmentReview);
flushAndClearSession();
assertTrue(controller.isPendingReviewNotifications(competition.getId()).getSuccessObjectOrThrowException());
}
@Test
public void isPendingReviewNotifications_noneExist() {
assertFalse(controller.isPendingReviewNotifications(competitionId).getSuccessObjectOrThrowException());
}
@Test
public void acceptInvitation() {
loginPaulPlum();
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
ProcessRole processRole = newProcessRole()
.with(id(null))
.withUser(userRepository.findByEmail(getPaulPlum().getEmail()).get())
.withApplication(application)
.withRole(UserRoleType.PANEL_ASSESSOR)
.build();
processRoleRepository.save(processRole);
AssessmentReview assessmentReview = newAssessmentReview()
.with(id(null))
.withTarget(application)
.withParticipant(processRole)
.build();
assessmentReview.setActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_PANEL_APPLICATION_INVITE, State.PENDING));
assessmentReviewRepository.save(assessmentReview);
flushAndClearSession();
controller.acceptInvitation(assessmentReview.getId()).getSuccessObjectOrThrowException();
assertEquals(AssessmentReviewState.ACCEPTED, assessmentReviewRepository.findOne(assessmentReview.getId()).getActivityState());
}
@Test
public void acceptInvitation_rejected() {
loginPaulPlum();
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
ProcessRole processRole = newProcessRole()
.with(id(null))
.withUser(userRepository.findByEmail(getPaulPlum().getEmail()).get())
.withApplication(application)
.withRole(UserRoleType.PANEL_ASSESSOR)
.build();
processRoleRepository.save(processRole);
AssessmentReview assessmentReview = newAssessmentReview()
.with(id(null))
.withTarget(application)
.withParticipant(processRole)
.build();
assessmentReview.setActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_PANEL_APPLICATION_INVITE, State.REJECTED));
assessmentReviewRepository.save(assessmentReview);
flushAndClearSession();
controller.acceptInvitation(assessmentReview.getId()).getSuccessObjectOrThrowException();
assertEquals(AssessmentReviewState.ACCEPTED, assessmentReviewRepository.findOne(assessmentReview.getId()).getActivityState());
}
@Test
public void rejectInvitation() {
loginPaulPlum();
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
ProcessRole processRole = newProcessRole()
.with(id(null))
.withUser(userRepository.findByEmail(getPaulPlum().getEmail()).get())
.withApplication(application)
.withRole(UserRoleType.PANEL_ASSESSOR)
.build();
processRoleRepository.save(processRole);
AssessmentReview assessmentReview = newAssessmentReview()
.with(id(null))
.withTarget(application)
.withParticipant(processRole)
.build();
assessmentReview.setActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_PANEL_APPLICATION_INVITE, State.PENDING));
assessmentReviewRepository.save(assessmentReview);
flushAndClearSession();
AssessmentReviewRejectOutcomeResource rejectOutcomeResource = newAssessmentReviewRejectOutcomeResource()
.withRejectComment("comment")
.build();
controller.rejectInvitation(assessmentReview.getId(), rejectOutcomeResource).getSuccessObjectOrThrowException();
assertEquals(AssessmentReviewState.REJECTED, assessmentReviewRepository.findOne(assessmentReview.getId()).getActivityState());
}
} | ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/assessment/controller/AssessmentPanelControllerIntegrationTest.java | package org.innovateuk.ifs.assessment.controller;
import org.innovateuk.ifs.BaseControllerIntegrationTest;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.assessment.panel.domain.AssessmentReview;
import org.innovateuk.ifs.assessment.panel.repository.AssessmentReviewRepository;
import org.innovateuk.ifs.commons.rest.RestResult;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.domain.Milestone;
import org.innovateuk.ifs.competition.repository.CompetitionRepository;
import org.innovateuk.ifs.competition.repository.MilestoneRepository;
import org.innovateuk.ifs.competition.resource.MilestoneType;
import org.innovateuk.ifs.invite.constant.InviteStatus;
import org.innovateuk.ifs.invite.domain.competition.AssessmentPanelInvite;
import org.innovateuk.ifs.invite.domain.competition.AssessmentPanelParticipant;
import org.innovateuk.ifs.invite.repository.AssessmentPanelInviteRepository;
import org.innovateuk.ifs.invite.repository.AssessmentPanelParticipantRepository;
import org.innovateuk.ifs.user.domain.ProcessRole;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.repository.ProcessRoleRepository;
import org.innovateuk.ifs.user.repository.UserRepository;
import org.innovateuk.ifs.user.resource.UserRoleType;
import org.innovateuk.ifs.workflow.domain.ActivityType;
import org.innovateuk.ifs.workflow.repository.ActivityStateRepository;
import org.innovateuk.ifs.workflow.resource.State;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.ZonedDateTime;
import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication;
import static org.innovateuk.ifs.assessment.panel.builder.AssessmentPanelInviteBuilder.newAssessmentPanelInvite;
import static org.innovateuk.ifs.assessment.panel.builder.AssessmentReviewBuilder.newAssessmentReview;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.id;
import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition;
import static org.innovateuk.ifs.competition.builder.MilestoneBuilder.newMilestone;
import static org.innovateuk.ifs.user.builder.ProcessRoleBuilder.newProcessRole;
import static org.innovateuk.ifs.user.builder.UserBuilder.newUser;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class AssessmentPanelControllerIntegrationTest extends BaseControllerIntegrationTest<AssessmentPanelController> {
private static final long applicationId = 2L;
private static final long competitionId = 3L;
private Application application;
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private CompetitionRepository competitionRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private AssessmentPanelInviteRepository assessmentPanelInviteRepository;
@Autowired
private ProcessRoleRepository processRoleRepository;
@Autowired
private AssessmentPanelParticipantRepository assessmentPanelParticipantRepository;
@Autowired
private ActivityStateRepository activityStateRepository;
@Autowired
private AssessmentReviewRepository assessmentReviewRepository;
@Autowired
private MilestoneRepository milestoneRepository;
@Autowired
@Override
public void setControllerUnderTest(AssessmentPanelController controller) {
this.controller = controller;
}
@Before
public void setUp() {
loginCompAdmin();
}
@After
public void clearDown() {
flushAndClearSession();
}
@Test
public void assignApplication() throws Exception {
application = newApplication()
.withId(applicationId)
.withAssessmentPanelStatus(false)
.build();
applicationRepository.save(application);
RestResult<Void> result = controller.assignApplication(application.getId());
assertTrue(result.isSuccess());
application = applicationRepository.findOne(applicationId);
assertTrue(application.isInAssessmentPanel());
}
@Test
public void unAssignApplication() throws Exception {
application = newApplication()
.withId(applicationId)
.withAssessmentPanelStatus(true)
.build();
applicationRepository.save(application);
RestResult<Void> result = controller.unAssignApplication(application.getId());
assertTrue(result.isSuccess());
application = applicationRepository.findOne(applicationId);
assertFalse(application.isInAssessmentPanel());
}
@Test
public void notifyAssessors() {
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Milestone milestone = newMilestone()
.with(id(null))
.withCompetition(competition)
.withType(MilestoneType.ASSESSMENT_PANEL)
.withDate(ZonedDateTime.parse("2017-12-18T12:00:00+00:00"))
.build();
milestoneRepository.save(milestone);
User user = newUser()
.with(id(null))
.withEmailAddress("[email protected]")
.withUid("foo")
.build();
userRepository.save(user);
AssessmentPanelInvite assessmentPanelInvite = newAssessmentPanelInvite()
.with(id(null))
.withCompetition(competition)
.withUser(user)
.withEmail("[email protected]")
.withStatus(InviteStatus.SENT)
.withName("tom baldwin")
.build();
assessmentPanelInviteRepository.save(assessmentPanelInvite);
AssessmentPanelParticipant assessmentPanelParticipant = new AssessmentPanelParticipant(assessmentPanelInvite);
assessmentPanelParticipant.getInvite().open();
assessmentPanelParticipant.acceptAndAssignUser(user);
assessmentPanelParticipantRepository.save(assessmentPanelParticipant);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
flushAndClearSession();
controller.notifyAssessors(competition.getId()).getSuccessObjectOrThrowException();
assertTrue(assessmentReviewRepository.existsByTargetCompetitionIdAndActivityStateState(competition.getId(), State.PENDING));
}
@Test
public void isPendingReviewNotifications() {
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Milestone milestone = newMilestone()
.with(id(null))
.withCompetition(competition)
.withType(MilestoneType.ASSESSMENT_PANEL)
.withDate(ZonedDateTime.parse("2017-12-18T12:00:00+00:00"))
.build();
milestoneRepository.save(milestone);
User user = newUser()
.with(id(null))
.withEmailAddress("[email protected]")
.withUid("foo")
.build();
userRepository.save(user);
AssessmentPanelInvite assessmentPanelInvite = newAssessmentPanelInvite()
.with(id(null))
.withCompetition(competition)
.withUser(user)
.withEmail("[email protected]")
.withStatus(InviteStatus.SENT)
.withName("tom baldwin")
.build();
assessmentPanelInviteRepository.save(assessmentPanelInvite);
AssessmentPanelParticipant assessmentPanelParticipant = new AssessmentPanelParticipant(assessmentPanelInvite);
assessmentPanelParticipant.getInvite().open();
assessmentPanelParticipant.acceptAndAssignUser(user);
assessmentPanelParticipantRepository.save(assessmentPanelParticipant);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
flushAndClearSession();
assertTrue(controller.isPendingReviewNotifications(competition.getId()).getSuccessObjectOrThrowException());
}
@Test
public void isPendingReviewNotifications_reviewExists() {
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Milestone milestone = newMilestone()
.with(id(null))
.withCompetition(competition)
.withType(MilestoneType.ASSESSMENT_PANEL)
.withDate(ZonedDateTime.parse("2017-12-18T12:00:00+00:00"))
.build();
milestoneRepository.save(milestone);
User user = newUser()
.with(id(null))
.withEmailAddress("[email protected]")
.withUid("foo")
.build();
userRepository.save(user);
AssessmentPanelInvite assessmentPanelInvite = newAssessmentPanelInvite()
.with(id(null))
.withCompetition(competition)
.withUser(user)
.withEmail("[email protected]")
.withStatus(InviteStatus.SENT)
.withName("tom baldwin")
.build();
assessmentPanelInviteRepository.save(assessmentPanelInvite);
AssessmentPanelParticipant assessmentPanelParticipant = new AssessmentPanelParticipant(assessmentPanelInvite);
assessmentPanelParticipant.getInvite().open();
assessmentPanelParticipant.acceptAndAssignUser(user);
assessmentPanelParticipantRepository.save(assessmentPanelParticipant);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
ProcessRole processRole = newProcessRole()
.with(id(null))
.withUser(user)
.withApplication(application)
.withRole(UserRoleType.PANEL_ASSESSOR)
.build();
processRoleRepository.save(processRole);
AssessmentReview assessmentReview =
newAssessmentReview()
.with(id(null))
.withParticipant(processRole)
.withTarget(application)
.build();
assessmentReview.setActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_PANEL_APPLICATION_INVITE, State.CREATED));
assessmentReviewRepository.save(assessmentReview);
flushAndClearSession();
assertFalse(controller.isPendingReviewNotifications(competition.getId()).getSuccessObjectOrThrowException());
}
@Test
public void isPendingReviewNotifications_withdrawnReviewExists() {
Competition competition = newCompetition()
.with(id(null))
.build();
competitionRepository.save(competition);
Milestone milestone = newMilestone()
.with(id(null))
.withCompetition(competition)
.withType(MilestoneType.ASSESSMENT_PANEL)
.withDate(ZonedDateTime.parse("2017-12-18T12:00:00+00:00"))
.build();
milestoneRepository.save(milestone);
User user = newUser()
.with(id(null))
.withEmailAddress("[email protected]")
.withUid("foo")
.build();
userRepository.save(user);
AssessmentPanelInvite competitionAssessmentInvite = newAssessmentPanelInvite()
.with(id(null))
.withCompetition(competition)
.withUser(user)
.withEmail("[email protected]")
.withStatus(InviteStatus.SENT)
.withName("tom baldwin")
.build();
assessmentPanelInviteRepository.save(competitionAssessmentInvite);
AssessmentPanelParticipant assessmentPanelParticipant = new AssessmentPanelParticipant(competitionAssessmentInvite);
assessmentPanelParticipant.getInvite().open();
assessmentPanelParticipant.acceptAndAssignUser(user);
assessmentPanelParticipantRepository.save(assessmentPanelParticipant);
Application application = newApplication()
.with(id(null))
.withCompetition(competition)
.withInAssessmentPanel(true)
.withActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.APPLICATION, State.SUBMITTED))
.build();
applicationRepository.save(application);
ProcessRole processRole = newProcessRole()
.with(id(null))
.withUser(user)
.withApplication(application)
.withRole(UserRoleType.PANEL_ASSESSOR)
.build();
processRoleRepository.save(processRole);
AssessmentReview assessmentReview =
newAssessmentReview()
.with(id(null))
.withParticipant(processRole)
.withTarget(application)
.build();
assessmentReview.setActivityState(activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_PANEL_APPLICATION_INVITE, State.WITHDRAWN));
assessmentReviewRepository.save(assessmentReview);
flushAndClearSession();
assertTrue(controller.isPendingReviewNotifications(competition.getId()).getSuccessObjectOrThrowException());
}
@Test
public void isPendingReviewNotifications_noneExist() {
assertFalse(controller.isPendingReviewNotifications(competitionId).getSuccessObjectOrThrowException());
}
} | IFS-388 - Adds AssessmentPanelController integration tests.
| ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/assessment/controller/AssessmentPanelControllerIntegrationTest.java | IFS-388 - Adds AssessmentPanelController integration tests. |
|
Java | epl-1.0 | 9e82170d0395c7e721ffc317c0a59291cea2b642 | 0 | debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief | package org.mwc.debrief.lite.menu;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.mwc.debrief.lite.gui.LiteStepControl;
import org.mwc.debrief.lite.gui.LiteStepControl.SliderControls;
import org.mwc.debrief.lite.gui.LiteStepControl.TimeLabel;
import org.mwc.debrief.lite.gui.custom.RangeSlider;
import org.mwc.debrief.lite.map.GeoToolMapRenderer;
import org.mwc.debrief.lite.properties.PropertiesDialog;
import org.pushingpixels.flamingo.api.common.CommandButtonDisplayState;
import org.pushingpixels.flamingo.api.common.FlamingoCommand.FlamingoCommandToggleGroup;
import org.pushingpixels.flamingo.api.common.RichTooltip.RichTooltipBuilder;
import org.pushingpixels.flamingo.api.common.JCommandButton;
import org.pushingpixels.flamingo.api.common.RichTooltip;
import org.pushingpixels.flamingo.api.common.icon.ImageWrapperResizableIcon;
import org.pushingpixels.flamingo.api.ribbon.JRibbon;
import org.pushingpixels.flamingo.api.ribbon.JRibbonBand;
import org.pushingpixels.flamingo.api.ribbon.JRibbonComponent;
import org.pushingpixels.flamingo.api.ribbon.RibbonElementPriority;
import org.pushingpixels.flamingo.api.ribbon.RibbonTask;
import MWC.GUI.CanvasType;
import MWC.GUI.Layers;
import MWC.GUI.StepperListener;
import MWC.GUI.ToolParent;
import MWC.GUI.Tools.Swing.MyMetalToolBarUI.ToolbarOwner;
import MWC.GUI.Undo.UndoBuffer;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.TacticalData.temporal.ControllablePeriod;
import MWC.TacticalData.temporal.PlotOperations;
import MWC.TacticalData.temporal.TimeManager;
public class DebriefRibbonTimeController
{
private static final String START_TEXT = "Start playing";
private static final String STOP_TEXT = "Stop playing";
private static final String STOP_IMAGE = "icons/24/media_stop.png";
private static final String PLAY_IMAGE = "icons/24/media_play.png";
/**
* Class that binds the Time Filter and Time Label.
* It is used to update the date formatting.
*
*/
protected static class DateFormatBinder
{
protected LiteStepControl stepControl;
protected JLabel minimumValue;
protected JLabel maximumValue;
protected RangeSlider slider;
protected TimeManager timeManager;
public void updateTimeDateFormat(final String format)
{
stepControl.setDateFormat(format);
timeManager.fireTimePropertyChange();
updateFilterDateFormat();
}
public String getDateFormat()
{
return stepControl.getDateFormat();
}
public void updateFilterDateFormat()
{
Date low = RangeSlider.toDate(slider.getValue()).getTime();
Date high = RangeSlider.toDate(slider.getUpperValue()).getTime();
final SimpleDateFormat formatter = new SimpleDateFormat(stepControl
.getDateFormat());
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
minimumValue.setText(formatter.format(low));
maximumValue.setText(formatter.format(high));
}
}
protected static class ShowFormatAction extends AbstractAction
{
/**
*
*/
private static final long serialVersionUID = 1L;
private final JPopupMenu menu;
private ShowFormatAction(final JPopupMenu theMenu)
{
this.menu = theMenu;
}
@Override
public void actionPerformed(final ActionEvent e)
{
// Get the event source
final Component component = (Component) e.getSource();
menu.show(component, 0, 0);
// Get the location of the point 'on the screen'
final Point p = component.getLocationOnScreen();
menu.setLocation(p.x, p.y + component.getHeight());
}
}
/**
* utility class to handle converting between slider range and time values
*
* @author ian
*
*/
private static class SliderConverter
{
private int range;
private long origin;
// have one minute steps
private final int step = 1000;
public int getCurrentAt(final long now)
{
return (int) ((now - origin) / step);
}
public int getEnd()
{
return range;
}
public int getStart()
{
return 0;
}
public long getTimeAt(final int position)
{
return origin + (position * step);
}
public void init(final long start, final long end)
{
origin = start;
range = (int) ((end - start) / step);
}
}
private static final String[] timeFormats = new String[]
{"mm:ss.SSS", "HHmm.ss", "HHmm",
"ddHHmm", "ddHHmm:ss", "yy/MM/dd HH:mm",
"yy/MM/dd hh:mm:ss"};
private static SliderConverter converter = new SliderConverter();
private static DateFormatBinder formatBinder = new DateFormatBinder();
private static TimeLabel label;
private static JCheckBoxMenuItem[] _menuItem;
public static void assignThisTimeFormat(String format, boolean fireUpdate)
{
if ( _menuItem != null && format != null )
{
for ( int i = 0 ; i < _menuItem.length ; i++ )
{
_menuItem[i].setSelected(format.equals(_menuItem[i].getText()));
}
final int completeSize = 17;
final int diff = completeSize - format.length();
String newFormat = format;
for (int i = 0 ; i < diff / 2 ; i++)
{
newFormat = " " + newFormat + " ";
}
if ( newFormat.length() < completeSize ) {
newFormat = newFormat + " ";
}
if ( fireUpdate && formatBinder != null )
{
formatBinder.updateTimeDateFormat(newFormat);
}
}
}
protected static void addTimeControllerTab(final JRibbon ribbon,
final GeoToolMapRenderer _geoMapRenderer,
final LiteStepControl stepControl, final TimeManager timeManager,
final PlotOperations operations, final Layers layers,
final UndoBuffer undoBuffer, final Runnable normalPainter,
final Runnable snailPainter)
{
final JRibbonBand displayMode = createDisplayMode(normalPainter, snailPainter);
final JRibbonBand filterToTime = createFilterToTime(stepControl, operations,
timeManager);
final JRibbonBand control = createControl(stepControl, timeManager, layers,
undoBuffer);
final RibbonTask timeTask = new RibbonTask("Time", displayMode, control,
filterToTime);
ribbon.addTask(timeTask);
}
private static JRibbonBand createControl(final LiteStepControl stepControl,
final TimeManager timeManager, final Layers layers,
final UndoBuffer undoBuffer)
{
final JRibbonBand control = new JRibbonBand("Control", null);
final JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
controlPanel.setPreferredSize(new Dimension(500, 80));
final JPanel topButtonsPanel = new JPanel();
topButtonsPanel.setLayout(new BoxLayout(topButtonsPanel, BoxLayout.X_AXIS));
final JCommandButton behindCommandButton = MenuUtils.addCommandButton(
"Behind", "icons/24/media_beginning.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
timeManager.setTime(control, timeManager.getPeriod().getStartDTG(),
true);
}
}, CommandButtonDisplayState.SMALL, "Move to start time");
final JCommandButton rewindCommandButton = MenuUtils.addCommandButton(
"Rewind", "icons/24/media_rewind.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(false, true);
}
}, CommandButtonDisplayState.SMALL, "Large step backwards");
final JCommandButton backCommandButton = MenuUtils.addCommandButton("Back",
"icons/24/media_back.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(false, false);
}
}, CommandButtonDisplayState.SMALL, "Small step backwards");
final JCommandButton playCommandButton = MenuUtils.addCommandButton("Play",
PLAY_IMAGE, new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
// ignore, we define the action once we've finished creating the button
}
}, CommandButtonDisplayState.SMALL, START_TEXT);
playCommandButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e)
{
// what state are we in?
final boolean isPlaying = stepControl.isPlaying();
stepControl.startStepping(!isPlaying);
// now update the play button UI
updatePlayBtnUI(playCommandButton, isPlaying);
}
});
final JCommandButton recordCommandButton = MenuUtils.addCommandButton(
"Record", "icons/24/media_record.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
JOptionPane.showMessageDialog(null,
"Record to PPT not yet implemented.");
}
}, CommandButtonDisplayState.SMALL, "Start recording");
final JCommandButton forwardCommandButton = MenuUtils.addCommandButton(
"Forward", "icons/24/media_forward.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(true, false);
}
}, CommandButtonDisplayState.SMALL, "Small step forwards");
final JCommandButton fastForwardCommandButton = MenuUtils.addCommandButton(
"Fast Forward", "icons/24/media_fast_forward.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(true, true);
}
}, CommandButtonDisplayState.SMALL, "Large step forwards");
final JCommandButton endCommandButton = MenuUtils.addCommandButton("End",
"icons/24/media_end.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
timeManager.setTime(control, timeManager.getPeriod().getEndDTG(),
true);
}
}, CommandButtonDisplayState.SMALL, "Move to end time");
final JCommandButton propertiesCommandButton = MenuUtils.addCommandButton(
"Properties", "icons/16/properties.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1973993003498667463L;
@Override
public void actionPerformed(ActionEvent arg0)
{
ToolbarOwner owner = null;
ToolParent parent = stepControl.getParent();
if (parent instanceof ToolbarOwner)
{
owner = (ToolbarOwner) parent;
}
PropertiesDialog dialog = new PropertiesDialog(stepControl, layers,
undoBuffer, parent, owner);
dialog.setSize(400, 500);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}, CommandButtonDisplayState.SMALL, "Edit time-step properties");
// we need to give the menu to the command popup
final JPopupMenu menu = new JPopupMenu();
final JCommandButton formatCommandButton = MenuUtils.addCommandButton(
"Format", "icons/24/gears_view.png", new ShowFormatAction(menu),
CommandButtonDisplayState.SMALL, "Format time control");
final JLabel timeLabel = new JLabel("YY/MM/dd hh:mm:ss")
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(final Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
timeLabel.setSize(200, 60);
timeLabel.setPreferredSize(new Dimension(200, 60));
timeLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
timeLabel.setForeground(new Color(0, 255, 0));
_menuItem = new JCheckBoxMenuItem[timeFormats.length];
for (int i = 0 ; i < timeFormats.length; i++)
{
_menuItem[i] = new JCheckBoxMenuItem(timeFormats[i]);
}
resetDateFormat();
final ActionListener selfAssignFormat = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String format = e.getActionCommand();
assignThisTimeFormat(format, true);
}
};
for(int i = 0 ; i < timeFormats.length; i++)
{
_menuItem[i].addActionListener(selfAssignFormat);
menu.add(_menuItem[i]);
}
topButtonsPanel.add(behindCommandButton);
topButtonsPanel.add(rewindCommandButton);
topButtonsPanel.add(backCommandButton);
topButtonsPanel.add(playCommandButton);
topButtonsPanel.add(recordCommandButton);
topButtonsPanel.add(forwardCommandButton);
topButtonsPanel.add(fastForwardCommandButton);
topButtonsPanel.add(endCommandButton);
topButtonsPanel.add(new JLabel(" | "));
topButtonsPanel.add(propertiesCommandButton);
topButtonsPanel.add(timeLabel);
topButtonsPanel.add(formatCommandButton);
controlPanel.add(topButtonsPanel);
final JSlider timeSlider = new JSlider();
timeSlider.setPreferredSize(new Dimension(420, 30));
timeSlider.setEnabled(false);
label = new TimeLabel()
{
@Override
public void setRange(final long start, final long end)
{
// ok, we can use time slider
timeSlider.setEnabled(true);
// and we can use the buttons
setButtonsEnabled(topButtonsPanel, true);
converter.init(start, end);
timeSlider.setMinimum(converter.getStart());
timeSlider.setMaximum(converter.getEnd());
}
@Override
public void setValue(final long time)
{
// find the value
final int value = converter.getCurrentAt(time);
timeSlider.setValue(value);
}
@Override
public void setValue(final String text)
{
timeLabel.setText(text);
}
};
stepControl.setTimeLabel(label);
// we also need to listen to the slider
timeSlider.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(final ChangeEvent e)
{
final int pos = timeSlider.getValue();
final long time = converter.getTimeAt(pos);
if(timeManager.getTime() == null || timeManager.getTime().getDate().getTime() != time)
{
timeManager.setTime(timeSlider, new HiResDate(time), true);
}
}
});
// ok, start off with the buttons disabled
setButtonsEnabled(topButtonsPanel, false);
// we also need to listen out for the stepper control mode changing
stepControl.addStepperListener(new LiteStepperListener(playCommandButton) {
@Override
public void reset()
{
// move the slider to the start
timeSlider.setValue(0);
label.setValue(LiteStepControl.timeFormat);
// ok, do some disabling
setButtonsEnabled(topButtonsPanel, false);
timeSlider.setEnabled(false);
}});
control.addRibbonComponent(new JRibbonComponent(topButtonsPanel));
control.addRibbonComponent(new JRibbonComponent(timeSlider));
control.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
control));
return control;
}
public static void resetDateFormat()
{
final String defaultFormat = LiteStepControl.timeFormat;
if ( defaultFormat != null )
{
DebriefRibbonTimeController.assignThisTimeFormat(defaultFormat, false);
formatBinder.stepControl.setDateFormat(defaultFormat);
formatBinder.updateFilterDateFormat();
}
if(label != null)
{
label.setValue(defaultFormat);
}
}
public static void updatePlayBtnUI(final JCommandButton playCommandButton,
final boolean isPlaying)
{
final String image;
if (isPlaying)
image = PLAY_IMAGE;
else
image = STOP_IMAGE;
final String tooltip = isPlaying ? STOP_TEXT : START_TEXT;
RichTooltipBuilder builder = new RichTooltipBuilder();
RichTooltip richTooltip = builder.setTitle("Timer")
.addDescriptionSection(tooltip).build();
playCommandButton.setActionRichTooltip(richTooltip);
// switch the icon
final Image playStopinImage = MenuUtils.createImage(image);
final ImageWrapperResizableIcon imageIcon = ImageWrapperResizableIcon
.getIcon(playStopinImage, MenuUtils.ICON_SIZE_16);
playCommandButton.setExtraText(tooltip);
playCommandButton.setIcon(imageIcon);
}
private static abstract class LiteStepperListener implements StepperListener
{
private JCommandButton _playBtn;
private LiteStepperListener(JCommandButton playCommandButton)
{
_playBtn = playCommandButton;
}
@Override
public void steppingModeChanged(boolean on)
{
if (_playBtn != null)
{
updatePlayBtnUI(_playBtn, !on);
}
}
@Override
public void newTime(HiResDate oldDTG, HiResDate newDTG, CanvasType canvas)
{
// ignore
}
}
private static JRibbonBand createDisplayMode(final Runnable normalPainter,
final Runnable snailPainter)
{
final JRibbonBand displayMode = new JRibbonBand("Display Mode", null);
final FlamingoCommandToggleGroup displayModeGroup =
new FlamingoCommandToggleGroup();
MenuUtils.addCommandToggleButton("Normal", "icons/48/normal.png",
new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
normalPainter.run();
}}, displayMode, RibbonElementPriority.TOP,
true, displayModeGroup, true);
MenuUtils.addCommandToggleButton("Snail", "icons/48/snail.png",
new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
snailPainter.run();
}}, displayMode, RibbonElementPriority.TOP,
true, displayModeGroup, false);
displayMode.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
displayMode));
return displayMode;
}
private static class SliderListener implements ChangeListener
{
final private PlotOperations operations;
final private TimeManager timeManager;
private SliderListener(final PlotOperations operations,
final TimeManager time)
{
this.operations = operations;
timeManager = time;
}
@Override
public void stateChanged(final ChangeEvent e)
{
final RangeSlider slider = (RangeSlider) e.getSource();
Date low = RangeSlider.toDate(slider.getValue()).getTime();
Date high = RangeSlider.toDate(slider.getUpperValue()).getTime();
formatBinder.updateFilterDateFormat();
operations.setPeriod(new TimePeriod.BaseTimePeriod(new HiResDate(low),
new HiResDate(high)));
HiResDate currentTime = timeManager.getTime();
if ( currentTime != null )
{
Date oldTime = currentTime.getDate();
if ( oldTime.before(low) ) {
oldTime = low;
}
if ( oldTime.after(high) ) {
oldTime = high;
}
label.setRange(low.getTime(), high.getTime());
label.setValue(oldTime.getTime());
// and enable those buttons
}
operations.performOperation(ControllablePeriod.FILTER_TO_TIME_PERIOD);
}
}
private static class LiteSliderControls implements SliderControls
{
private final RangeSlider slider;
private LiteSliderControls(RangeSlider slider)
{
this.slider = slider;
}
@Override
public HiResDate getToolboxEndTime()
{
final long val = slider.getUpperDate().getTimeInMillis();
return new HiResDate(val);
}
@Override
public HiResDate getToolboxStartTime()
{
final long val = slider.getLowerDate().getTimeInMillis();
return new HiResDate(val);
}
@Override
public void setToolboxEndTime(final HiResDate val)
{
final GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(val.getDate().getTime());
slider.setMaximum(cal);
slider.setUpperDate(cal);
}
@Override
public void setToolboxStartTime(final HiResDate val)
{
final GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(val.getDate().getTime());
slider.setMinimum(cal);
slider.setLowerDate(cal);
}
@Override
public void setEnabled(boolean enabled)
{
slider.setEnabled(enabled);
}
}
private static JRibbonBand createFilterToTime(
final LiteStepControl stepControl, final PlotOperations operations,
final TimeManager timeManager)
{
final JRibbonBand timePeriod = new JRibbonBand("Filter to time", null);
final Calendar start = new GregorianCalendar(1995, 11, 12);
final Calendar end = new GregorianCalendar(1995, 11, 12);
// Now we create the components for the sliders
final JLabel minimumValue = new JLabel();
final JLabel maximumValue = new JLabel();
final RangeSlider slider = new RangeSlider(start, end);
formatBinder.stepControl = stepControl;
formatBinder.maximumValue = maximumValue;
formatBinder.minimumValue = minimumValue;
formatBinder.slider = slider;
formatBinder.timeManager = timeManager;
formatBinder.updateFilterDateFormat();
slider.addChangeListener(new SliderListener(operations, timeManager));
slider.setEnabled(false);
slider.setPreferredSize(new Dimension(250, 200));
final JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new BoxLayout(sliderPanel, BoxLayout.Y_AXIS));
sliderPanel.setPreferredSize(new Dimension(250, 200));
// Label's panel
final JPanel valuePanel = new JPanel();
valuePanel.setLayout(new BoxLayout(valuePanel, BoxLayout.X_AXIS));
valuePanel.add(minimumValue);
valuePanel.add(Box.createGlue());
valuePanel.add(maximumValue);
valuePanel.setPreferredSize(new Dimension(250, 200));
timePeriod.addRibbonComponent(new JRibbonComponent(slider));
timePeriod.addRibbonComponent(new JRibbonComponent(valuePanel));
// tie in to the stepper
final SliderControls iSlider = new LiteSliderControls(slider);
stepControl.setSliderControls(iSlider);
// listen out for time being reset
// we also need to listen out for the stepper control mode changing
stepControl.addStepperListener(new LiteStepperListener(null) {
@Override
public void reset()
{
minimumValue.setText(" ");
maximumValue.setText(" ");
}});
return timePeriod;
}
/**
* convenience class to bulk enable/disable controls in a panel
*
* @param panel
* @param enabled
*/
private static void setButtonsEnabled(final JPanel panel,
final boolean enabled)
{
final Component[] items = panel.getComponents();
for (final Component item : items)
{
final boolean state = item.isEnabled();
if (state != enabled)
{
item.setEnabled(enabled);
}
}
}
}
| org.mwc.debrief.lite/src/main/java/org/mwc/debrief/lite/menu/DebriefRibbonTimeController.java | package org.mwc.debrief.lite.menu;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.mwc.debrief.lite.gui.LiteStepControl;
import org.mwc.debrief.lite.gui.LiteStepControl.SliderControls;
import org.mwc.debrief.lite.gui.LiteStepControl.TimeLabel;
import org.mwc.debrief.lite.gui.custom.RangeSlider;
import org.mwc.debrief.lite.map.GeoToolMapRenderer;
import org.mwc.debrief.lite.properties.PropertiesDialog;
import org.pushingpixels.flamingo.api.common.CommandButtonDisplayState;
import org.pushingpixels.flamingo.api.common.FlamingoCommand.FlamingoCommandToggleGroup;
import org.pushingpixels.flamingo.api.common.RichTooltip.RichTooltipBuilder;
import org.pushingpixels.flamingo.api.common.JCommandButton;
import org.pushingpixels.flamingo.api.common.RichTooltip;
import org.pushingpixels.flamingo.api.common.icon.ImageWrapperResizableIcon;
import org.pushingpixels.flamingo.api.ribbon.JRibbon;
import org.pushingpixels.flamingo.api.ribbon.JRibbonBand;
import org.pushingpixels.flamingo.api.ribbon.JRibbonComponent;
import org.pushingpixels.flamingo.api.ribbon.RibbonElementPriority;
import org.pushingpixels.flamingo.api.ribbon.RibbonTask;
import MWC.GUI.CanvasType;
import MWC.GUI.Layers;
import MWC.GUI.StepperListener;
import MWC.GUI.ToolParent;
import MWC.GUI.Tools.Swing.MyMetalToolBarUI.ToolbarOwner;
import MWC.GUI.Undo.UndoBuffer;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.TacticalData.temporal.ControllablePeriod;
import MWC.TacticalData.temporal.PlotOperations;
import MWC.TacticalData.temporal.TimeManager;
public class DebriefRibbonTimeController
{
private static final String START_TEXT = "Start playing";
private static final String STOP_TEXT = "Stop playing";
private static final String STOP_IMAGE = "icons/24/media_stop.png";
private static final String PLAY_IMAGE = "icons/24/media_play.png";
/**
* Class that binds the Time Filter and Time Label.
* It is used to update the date formatting.
*
*/
protected static class DateFormatBinder
{
protected LiteStepControl stepControl;
protected JLabel minimumValue;
protected JLabel maximumValue;
protected RangeSlider slider;
protected TimeManager timeManager;
public void updateTimeDateFormat(final String format)
{
stepControl.setDateFormat(format);
timeManager.fireTimePropertyChange();
updateFilterDateFormat();
}
public String getDateFormat()
{
return stepControl.getDateFormat();
}
public void updateFilterDateFormat()
{
Date low = RangeSlider.toDate(slider.getValue()).getTime();
Date high = RangeSlider.toDate(slider.getUpperValue()).getTime();
final SimpleDateFormat formatter = new SimpleDateFormat(stepControl
.getDateFormat());
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
minimumValue.setText(formatter.format(low));
maximumValue.setText(formatter.format(high));
}
}
protected static class ShowFormatAction extends AbstractAction
{
/**
*
*/
private static final long serialVersionUID = 1L;
private final JPopupMenu menu;
private ShowFormatAction(final JPopupMenu theMenu)
{
this.menu = theMenu;
}
@Override
public void actionPerformed(final ActionEvent e)
{
// Get the event source
final Component component = (Component) e.getSource();
menu.show(component, 0, 0);
// Get the location of the point 'on the screen'
final Point p = component.getLocationOnScreen();
menu.setLocation(p.x, p.y + component.getHeight());
}
}
/**
* utility class to handle converting between slider range and time values
*
* @author ian
*
*/
private static class SliderConverter
{
private int range;
private long origin;
// have one minute steps
private final int step = 1000;
public int getCurrentAt(final long now)
{
return (int) ((now - origin) / step);
}
public int getEnd()
{
return range;
}
public int getStart()
{
return 0;
}
public long getTimeAt(final int position)
{
return origin + (position * step);
}
public void init(final long start, final long end)
{
origin = start;
range = (int) ((end - start) / step);
}
}
private static final String[] timeFormats = new String[]
{"mm:ss.SSS", "HHmm.ss", "HHmm",
"ddHHmm", "ddHHmm:ss", "yy/MM/dd HH:mm",
"yy/MM/dd hh:mm:ss"};
private static SliderConverter converter = new SliderConverter();
private static DateFormatBinder formatBinder = new DateFormatBinder();
private static TimeLabel label;
private static JCheckBoxMenuItem[] _menuItem;
public static void assignThisTimeFormat(String format, boolean fireUpdate)
{
if ( _menuItem != null && format != null )
{
for ( int i = 0 ; i < _menuItem.length ; i++ )
{
_menuItem[i].setSelected(format.equals(_menuItem[i].getText()));
}
final int completeSize = 17;
final int diff = completeSize - format.length();
String newFormat = format;
for (int i = 0 ; i < diff / 2 ; i++)
{
newFormat = " " + newFormat + " ";
}
if ( newFormat.length() < completeSize ) {
newFormat = newFormat + " ";
}
if ( fireUpdate && formatBinder != null )
{
formatBinder.updateTimeDateFormat(newFormat);
}
}
}
protected static void addTimeControllerTab(final JRibbon ribbon,
final GeoToolMapRenderer _geoMapRenderer,
final LiteStepControl stepControl, final TimeManager timeManager,
final PlotOperations operations, final Layers layers,
final UndoBuffer undoBuffer, final Runnable normalPainter,
final Runnable snailPainter)
{
final JRibbonBand displayMode = createDisplayMode(normalPainter, snailPainter);
final JRibbonBand filterToTime = createFilterToTime(stepControl, operations,
timeManager);
final JRibbonBand control = createControl(stepControl, timeManager, layers,
undoBuffer);
final RibbonTask timeTask = new RibbonTask("Time", displayMode, control,
filterToTime);
ribbon.addTask(timeTask);
}
private static JRibbonBand createControl(final LiteStepControl stepControl,
final TimeManager timeManager, final Layers layers,
final UndoBuffer undoBuffer)
{
final JRibbonBand control = new JRibbonBand("Control", null);
final JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
controlPanel.setPreferredSize(new Dimension(500, 80));
final JPanel topButtonsPanel = new JPanel();
topButtonsPanel.setLayout(new BoxLayout(topButtonsPanel, BoxLayout.X_AXIS));
final JCommandButton behindCommandButton = MenuUtils.addCommandButton(
"Behind", "icons/24/media_beginning.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
timeManager.setTime(control, timeManager.getPeriod().getStartDTG(),
true);
}
}, CommandButtonDisplayState.SMALL, "Move to start time");
final JCommandButton rewindCommandButton = MenuUtils.addCommandButton(
"Rewind", "icons/24/media_rewind.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(false, true);
}
}, CommandButtonDisplayState.SMALL, "Large step backwards");
final JCommandButton backCommandButton = MenuUtils.addCommandButton("Back",
"icons/24/media_back.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(false, false);
}
}, CommandButtonDisplayState.SMALL, "Small step backwards");
final JCommandButton playCommandButton = MenuUtils.addCommandButton("Play",
PLAY_IMAGE, new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
// ignore, we define the action once we've finished creating the button
}
}, CommandButtonDisplayState.SMALL, START_TEXT);
playCommandButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(final ActionEvent e)
{
// what state are we in?
final boolean isPlaying = stepControl.isPlaying();
stepControl.startStepping(!isPlaying);
// now update the play button UI
updatePlayBtnUI(playCommandButton, isPlaying);
}
});
final JCommandButton recordCommandButton = MenuUtils.addCommandButton(
"Record", "icons/24/media_record.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
JOptionPane.showMessageDialog(null,
"Record to PPT not yet implemented.");
}
}, CommandButtonDisplayState.SMALL, "Start recording");
final JCommandButton forwardCommandButton = MenuUtils.addCommandButton(
"Forward", "icons/24/media_forward.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(true, false);
}
}, CommandButtonDisplayState.SMALL, "Small step forwards");
final JCommandButton fastForwardCommandButton = MenuUtils.addCommandButton(
"Fast Forward", "icons/24/media_fast_forward.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
stepControl.doStep(true, true);
}
}, CommandButtonDisplayState.SMALL, "Large step forwards");
final JCommandButton endCommandButton = MenuUtils.addCommandButton("End",
"icons/24/media_end.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(final ActionEvent e)
{
timeManager.setTime(control, timeManager.getPeriod().getEndDTG(),
true);
}
}, CommandButtonDisplayState.SMALL, "Move to end time");
final JCommandButton propertiesCommandButton = MenuUtils.addCommandButton(
"Properties", "icons/16/properties.png", new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 1973993003498667463L;
@Override
public void actionPerformed(ActionEvent arg0)
{
ToolbarOwner owner = null;
ToolParent parent = stepControl.getParent();
if (parent instanceof ToolbarOwner)
{
owner = (ToolbarOwner) parent;
}
PropertiesDialog dialog = new PropertiesDialog(stepControl, layers,
undoBuffer, parent, owner);
dialog.setSize(400, 500);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}, CommandButtonDisplayState.SMALL, "Edit time-step properties");
// we need to give the menu to the command popup
final JPopupMenu menu = new JPopupMenu();
final JCommandButton formatCommandButton = MenuUtils.addCommandButton(
"Format", "icons/24/gears_view.png", new ShowFormatAction(menu),
CommandButtonDisplayState.SMALL, "Format time control");
final JLabel timeLabel = new JLabel("YY/MM/dd hh:mm:ss")
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(final Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
};
timeLabel.setSize(200, 60);
timeLabel.setPreferredSize(new Dimension(200, 60));
timeLabel.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 16));
timeLabel.setForeground(new Color(0, 255, 0));
_menuItem = new JCheckBoxMenuItem[timeFormats.length];
for (int i = 0 ; i < timeFormats.length; i++)
{
_menuItem[i] = new JCheckBoxMenuItem(timeFormats[i]);
}
resetDateFormat();
final ActionListener selfAssignFormat = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String format = e.getActionCommand();
assignThisTimeFormat(format, true);
}
};
for(int i = 0 ; i < timeFormats.length; i++)
{
_menuItem[i].addActionListener(selfAssignFormat);
menu.add(_menuItem[i]);
}
topButtonsPanel.add(behindCommandButton);
topButtonsPanel.add(rewindCommandButton);
topButtonsPanel.add(backCommandButton);
topButtonsPanel.add(playCommandButton);
topButtonsPanel.add(recordCommandButton);
topButtonsPanel.add(forwardCommandButton);
topButtonsPanel.add(fastForwardCommandButton);
topButtonsPanel.add(endCommandButton);
topButtonsPanel.add(new JLabel(" | "));
topButtonsPanel.add(propertiesCommandButton);
topButtonsPanel.add(timeLabel);
topButtonsPanel.add(formatCommandButton);
controlPanel.add(topButtonsPanel);
final JSlider timeSlider = new JSlider();
timeSlider.setPreferredSize(new Dimension(420, 30));
timeSlider.setEnabled(false);
label = new TimeLabel()
{
@Override
public void setRange(final long start, final long end)
{
// ok, we can use time slider
timeSlider.setEnabled(true);
// and we can use the buttons
setButtonsEnabled(topButtonsPanel, true);
converter.init(start, end);
timeSlider.setMinimum(converter.getStart());
timeSlider.setMaximum(converter.getEnd());
}
@Override
public void setValue(final long time)
{
// find the value
final int value = converter.getCurrentAt(time);
timeSlider.setValue(value);
}
@Override
public void setValue(final String text)
{
timeLabel.setText(text);
}
};
stepControl.setTimeLabel(label);
// we also need to listen to the slider
timeSlider.addChangeListener(new ChangeListener()
{
@Override
public void stateChanged(final ChangeEvent e)
{
final int pos = timeSlider.getValue();
final long time = converter.getTimeAt(pos);
if(timeManager.getTime() == null || timeManager.getTime().getDate().getTime() != time)
{
timeManager.setTime(timeSlider, new HiResDate(time), true);
}
}
});
// ok, start off with the buttons disabled
setButtonsEnabled(topButtonsPanel, false);
// we also need to listen out for the stepper control mode changing
stepControl.addStepperListener(new LiteStepperListener(playCommandButton) {
@Override
public void reset()
{
// move the slider to the start
timeSlider.setValue(0);
label.setValue(LiteStepControl.timeFormat);
// ok, do some disabling
setButtonsEnabled(topButtonsPanel, false);
timeSlider.setEnabled(false);
}});
control.addRibbonComponent(new JRibbonComponent(topButtonsPanel));
control.addRibbonComponent(new JRibbonComponent(timeSlider));
control.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
control));
return control;
}
public static void resetDateFormat()
{
final String defaultFormat = LiteStepControl.timeFormat;
for (int i = 0 ; i < timeFormats.length; i++)
{
// is this the default format
final boolean isGood = defaultFormat != null && defaultFormat.equals(timeFormats[i]);
_menuItem[i].setSelected(isGood);
}
if(label != null)
{
label.setValue(defaultFormat);
}
}
public static void updatePlayBtnUI(final JCommandButton playCommandButton,
final boolean isPlaying)
{
final String image;
if (isPlaying)
image = PLAY_IMAGE;
else
image = STOP_IMAGE;
final String tooltip = isPlaying ? STOP_TEXT : START_TEXT;
RichTooltipBuilder builder = new RichTooltipBuilder();
RichTooltip richTooltip = builder.setTitle("Timer")
.addDescriptionSection(tooltip).build();
playCommandButton.setActionRichTooltip(richTooltip);
// switch the icon
final Image playStopinImage = MenuUtils.createImage(image);
final ImageWrapperResizableIcon imageIcon = ImageWrapperResizableIcon
.getIcon(playStopinImage, MenuUtils.ICON_SIZE_16);
playCommandButton.setExtraText(tooltip);
playCommandButton.setIcon(imageIcon);
}
private static abstract class LiteStepperListener implements StepperListener
{
private JCommandButton _playBtn;
private LiteStepperListener(JCommandButton playCommandButton)
{
_playBtn = playCommandButton;
}
@Override
public void steppingModeChanged(boolean on)
{
if (_playBtn != null)
{
updatePlayBtnUI(_playBtn, !on);
}
}
@Override
public void newTime(HiResDate oldDTG, HiResDate newDTG, CanvasType canvas)
{
// ignore
}
}
private static JRibbonBand createDisplayMode(final Runnable normalPainter,
final Runnable snailPainter)
{
final JRibbonBand displayMode = new JRibbonBand("Display Mode", null);
final FlamingoCommandToggleGroup displayModeGroup =
new FlamingoCommandToggleGroup();
MenuUtils.addCommandToggleButton("Normal", "icons/48/normal.png",
new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
normalPainter.run();
}}, displayMode, RibbonElementPriority.TOP,
true, displayModeGroup, true);
MenuUtils.addCommandToggleButton("Snail", "icons/48/snail.png",
new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e)
{
snailPainter.run();
}}, displayMode, RibbonElementPriority.TOP,
true, displayModeGroup, false);
displayMode.setResizePolicies(MenuUtils.getStandardRestrictivePolicies(
displayMode));
return displayMode;
}
private static class SliderListener implements ChangeListener
{
final private PlotOperations operations;
final private TimeManager timeManager;
private SliderListener(final PlotOperations operations,
final TimeManager time)
{
this.operations = operations;
timeManager = time;
}
@Override
public void stateChanged(final ChangeEvent e)
{
final RangeSlider slider = (RangeSlider) e.getSource();
Date low = RangeSlider.toDate(slider.getValue()).getTime();
Date high = RangeSlider.toDate(slider.getUpperValue()).getTime();
formatBinder.updateFilterDateFormat();
operations.setPeriod(new TimePeriod.BaseTimePeriod(new HiResDate(low),
new HiResDate(high)));
HiResDate currentTime = timeManager.getTime();
if ( currentTime != null )
{
Date oldTime = currentTime.getDate();
if ( oldTime.before(low) ) {
oldTime = low;
}
if ( oldTime.after(high) ) {
oldTime = high;
}
label.setRange(low.getTime(), high.getTime());
label.setValue(oldTime.getTime());
// and enable those buttons
}
operations.performOperation(ControllablePeriod.FILTER_TO_TIME_PERIOD);
}
}
private static class LiteSliderControls implements SliderControls
{
private final RangeSlider slider;
private LiteSliderControls(RangeSlider slider)
{
this.slider = slider;
}
@Override
public HiResDate getToolboxEndTime()
{
final long val = slider.getUpperDate().getTimeInMillis();
return new HiResDate(val);
}
@Override
public HiResDate getToolboxStartTime()
{
final long val = slider.getLowerDate().getTimeInMillis();
return new HiResDate(val);
}
@Override
public void setToolboxEndTime(final HiResDate val)
{
final GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(val.getDate().getTime());
slider.setMaximum(cal);
slider.setUpperDate(cal);
}
@Override
public void setToolboxStartTime(final HiResDate val)
{
final GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(val.getDate().getTime());
slider.setMinimum(cal);
slider.setLowerDate(cal);
}
@Override
public void setEnabled(boolean enabled)
{
slider.setEnabled(enabled);
}
}
private static JRibbonBand createFilterToTime(
final LiteStepControl stepControl, final PlotOperations operations,
final TimeManager timeManager)
{
final JRibbonBand timePeriod = new JRibbonBand("Filter to time", null);
final Calendar start = new GregorianCalendar(1995, 11, 12);
final Calendar end = new GregorianCalendar(1995, 11, 12);
// Now we create the components for the sliders
final JLabel minimumValue = new JLabel();
final JLabel maximumValue = new JLabel();
final RangeSlider slider = new RangeSlider(start, end);
formatBinder.stepControl = stepControl;
formatBinder.maximumValue = maximumValue;
formatBinder.minimumValue = minimumValue;
formatBinder.slider = slider;
formatBinder.timeManager = timeManager;
formatBinder.updateFilterDateFormat();
slider.addChangeListener(new SliderListener(operations, timeManager));
slider.setEnabled(false);
slider.setPreferredSize(new Dimension(250, 200));
final JPanel sliderPanel = new JPanel();
sliderPanel.setLayout(new BoxLayout(sliderPanel, BoxLayout.Y_AXIS));
sliderPanel.setPreferredSize(new Dimension(250, 200));
// Label's panel
final JPanel valuePanel = new JPanel();
valuePanel.setLayout(new BoxLayout(valuePanel, BoxLayout.X_AXIS));
valuePanel.add(minimumValue);
valuePanel.add(Box.createGlue());
valuePanel.add(maximumValue);
valuePanel.setPreferredSize(new Dimension(250, 200));
timePeriod.addRibbonComponent(new JRibbonComponent(slider));
timePeriod.addRibbonComponent(new JRibbonComponent(valuePanel));
// tie in to the stepper
final SliderControls iSlider = new LiteSliderControls(slider);
stepControl.setSliderControls(iSlider);
// listen out for time being reset
// we also need to listen out for the stepper control mode changing
stepControl.addStepperListener(new LiteStepperListener(null) {
@Override
public void reset()
{
minimumValue.setText(" ");
maximumValue.setText(" ");
}});
return timePeriod;
}
/**
* convenience class to bulk enable/disable controls in a panel
*
* @param panel
* @param enabled
*/
private static void setButtonsEnabled(final JPanel panel,
final boolean enabled)
{
final Component[] items = panel.getComponents();
for (final Component item : items)
{
final boolean state = item.isEnabled();
if (state != enabled)
{
item.setEnabled(enabled);
}
}
}
}
| Improve of the Time Reset , with the idea of fixing the bug mentioned here: https://github.com/debrief/debrief/issues/3875
| org.mwc.debrief.lite/src/main/java/org/mwc/debrief/lite/menu/DebriefRibbonTimeController.java | Improve of the Time Reset , with the idea of fixing the bug mentioned here: https://github.com/debrief/debrief/issues/3875 |
|
Java | epl-1.0 | bd25ff0b38ac97ae365f31c94ef0cd2c0892d0d8 | 0 | opendaylight/yangtools,opendaylight/yangtools | /*
* Copyright (c) 2017 Pantheon Technologies s.r.o. 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
*/
package org.opendaylight.yangtools.rfc8040.parser;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableSet;
import java.util.Optional;
import org.junit.Test;
import org.opendaylight.yangtools.rfc8040.model.api.YangDataSchemaNode;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.common.XMLNamespace;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.parser.spi.meta.InvalidSubstatementException;
import org.opendaylight.yangtools.yang.parser.spi.meta.MissingSubstatementException;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
public class YangDataExtensionTest extends AbstractYangDataTest {
private static final StatementStreamSource FOO_MODULE = sourceForResource(
"/yang-data-extension-test/foo.yang");
private static final StatementStreamSource FOO_INVALID_1_MODULE = sourceForResource(
"/yang-data-extension-test/foo-invalid-1.yang");
private static final StatementStreamSource FOO_INVALID_2_MODULE = sourceForResource(
"/yang-data-extension-test/foo-invalid-2.yang");
private static final StatementStreamSource FOO_INVALID_3_MODULE = sourceForResource(
"/yang-data-extension-test/foo-invalid-3.yang");
private static final StatementStreamSource BAR_MODULE = sourceForResource(
"/yang-data-extension-test/bar.yang");
private static final StatementStreamSource BAZ_MODULE = sourceForResource(
"/yang-data-extension-test/baz.yang");
private static final StatementStreamSource FOOBAR_MODULE = sourceForResource(
"/yang-data-extension-test/foobar.yang");
private static final Revision REVISION = Revision.of("2017-06-01");
private static final QNameModule FOO_QNAMEMODULE = QNameModule.create(XMLNamespace.of("foo"), REVISION);
@Test
public void testYangData() throws Exception {
final var schemaContext = REACTOR.newBuild().addSources(FOO_MODULE, IETF_RESTCONF_MODULE).buildEffective();
assertNotNull(schemaContext);
final var extensions = schemaContext.getExtensions();
assertEquals(1, extensions.size());
final var foo = schemaContext.findModule(FOO_QNAMEMODULE).orElseThrow();
final var unknownSchemaNodes = foo.getUnknownSchemaNodes();
assertEquals(2, unknownSchemaNodes.size());
YangDataSchemaNode myYangDataANode = null;
YangDataSchemaNode myYangDataBNode = null;
for (var unknownSchemaNode : unknownSchemaNodes) {
assertThat(unknownSchemaNode, instanceOf(YangDataSchemaNode.class));
final var yangDataSchemaNode = (YangDataSchemaNode) unknownSchemaNode;
if ("my-yang-data-a".equals(unknownSchemaNode.getNodeParameter())) {
myYangDataANode = yangDataSchemaNode;
} else if ("my-yang-data-b".equals(yangDataSchemaNode.getNodeParameter())) {
myYangDataBNode = yangDataSchemaNode;
}
}
assertNotNull(myYangDataANode);
assertNotNull(myYangDataBNode);
}
@Test
public void testConfigStatementBeingIgnoredInYangDataBody() throws Exception {
final var schemaContext = REACTOR.newBuild().addSources(BAZ_MODULE, IETF_RESTCONF_MODULE).buildEffective();
assertNotNull(schemaContext);
final var baz = schemaContext.findModule("baz", REVISION).get();
final var unknownSchemaNodes = baz.getUnknownSchemaNodes();
assertEquals(1, unknownSchemaNodes.size());
final var unknownSchemaNode = unknownSchemaNodes.iterator().next();
assertThat(unknownSchemaNode, instanceOf(YangDataSchemaNode.class));
final var myYangDataNode = (YangDataSchemaNode) unknownSchemaNode;
assertNotNull(myYangDataNode);
final var yangDataChildren = myYangDataNode.getChildNodes();
assertEquals(1, yangDataChildren.size());
final var childInYangData = yangDataChildren.iterator().next();
assertThat(childInYangData, instanceOf(ContainerSchemaNode.class));
final var contInYangData = (ContainerSchemaNode) childInYangData;
assertEquals(Optional.empty(), contInYangData.effectiveConfig());
final var innerCont = (ContainerSchemaNode) contInYangData.getDataChildByName(
QName.create(baz.getQNameModule(), "inner-cont"));
assertNotNull(innerCont);
assertEquals(Optional.empty(), innerCont.effectiveConfig());
final var grpCont = (ContainerSchemaNode) contInYangData.getDataChildByName(
QName.create(baz.getQNameModule(), "grp-cont"));
assertNotNull(grpCont);
assertEquals(Optional.empty(), grpCont.effectiveConfig());
}
@Test
public void testIfFeatureStatementBeingIgnoredInYangDataBody() throws Exception {
final var schemaContext = REACTOR.newBuild()
.setSupportedFeatures(ImmutableSet.of())
.addSources(FOOBAR_MODULE, IETF_RESTCONF_MODULE)
.buildEffective();
assertNotNull(schemaContext);
final var foobar = schemaContext.findModule("foobar", REVISION).get();
final var unknownSchemaNodes = foobar.getUnknownSchemaNodes();
assertEquals(1, unknownSchemaNodes.size());
final var unknownSchemaNode = unknownSchemaNodes.iterator().next();
assertThat(unknownSchemaNode, instanceOf(YangDataSchemaNode.class));
final var myYangDataNode = (YangDataSchemaNode) unknownSchemaNode;
assertNotNull(myYangDataNode);
final var yangDataChildren = myYangDataNode.getChildNodes();
assertEquals(1, yangDataChildren.size());
final var childInYangData = yangDataChildren.iterator().next();
assertThat(childInYangData, instanceOf(ContainerSchemaNode.class));
final var contInYangData = (ContainerSchemaNode) childInYangData;
final var innerCont = (ContainerSchemaNode) contInYangData.getDataChildByName(
QName.create(foobar.getQNameModule(), "inner-cont"));
assertNotNull(innerCont);
final var grpCont = (ContainerSchemaNode) contInYangData.getDataChildByName(
QName.create(foobar.getQNameModule(), "grp-cont"));
assertNotNull(grpCont);
}
@Test
public void testYangDataBeingIgnored() throws Exception {
// yang-data statement is ignored if it does not appear as a top-level statement
// i.e., it will not appear in the final SchemaContext
final var schemaContext = REACTOR.newBuild().addSources(BAR_MODULE, IETF_RESTCONF_MODULE).buildEffective();
assertNotNull(schemaContext);
final var bar = schemaContext.findModule("bar", REVISION).get();
final var cont = (ContainerSchemaNode) bar.getDataChildByName(
QName.create(bar.getQNameModule(), "cont"));
assertNotNull(cont);
final var extensions = schemaContext.getExtensions();
assertEquals(1, extensions.size());
final var unknownSchemaNodes = cont.getUnknownSchemaNodes();
assertEquals(0, unknownSchemaNodes.size());
}
@Test
public void testYangDataWithMissingTopLevelContainer() {
final var build = REACTOR.newBuild().addSources(FOO_INVALID_1_MODULE, IETF_RESTCONF_MODULE);
final var cause = assertThrows(ReactorException.class, () -> build.buildEffective()).getCause();
assertThat(cause, instanceOf(MissingSubstatementException.class));
assertThat(cause.getMessage(), startsWith("yang-data requires at least one substatement [at "));
}
@Test
public void testYangDataWithTwoTopLevelContainers() {
final var build = REACTOR.newBuild().addSources(FOO_INVALID_2_MODULE, IETF_RESTCONF_MODULE);
final var cause = assertThrows(ReactorException.class, () -> build.buildEffective()).getCause();
assertThat(cause, instanceOf(InvalidSubstatementException.class));
assertThat(cause.getMessage(),
startsWith("yang-data requires exactly one container data node definition, found ["));
}
}
| parser/rfc8040-parser-support/src/test/java/org/opendaylight/yangtools/rfc8040/parser/YangDataExtensionTest.java | /*
* Copyright (c) 2017 Pantheon Technologies s.r.o. 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
*/
package org.opendaylight.yangtools.rfc8040.parser;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableSet;
import java.util.Collection;
import java.util.Optional;
import org.junit.Test;
import org.opendaylight.yangtools.rfc8040.model.api.YangDataSchemaNode;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.common.XMLNamespace;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.parser.spi.meta.InvalidSubstatementException;
import org.opendaylight.yangtools.yang.parser.spi.meta.MissingSubstatementException;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor.BuildAction;
public class YangDataExtensionTest extends AbstractYangDataTest {
private static final StatementStreamSource FOO_MODULE = sourceForResource(
"/yang-data-extension-test/foo.yang");
private static final StatementStreamSource FOO_INVALID_1_MODULE = sourceForResource(
"/yang-data-extension-test/foo-invalid-1.yang");
private static final StatementStreamSource FOO_INVALID_2_MODULE = sourceForResource(
"/yang-data-extension-test/foo-invalid-2.yang");
private static final StatementStreamSource FOO_INVALID_3_MODULE = sourceForResource(
"/yang-data-extension-test/foo-invalid-3.yang");
private static final StatementStreamSource BAR_MODULE = sourceForResource(
"/yang-data-extension-test/bar.yang");
private static final StatementStreamSource BAZ_MODULE = sourceForResource(
"/yang-data-extension-test/baz.yang");
private static final StatementStreamSource FOOBAR_MODULE = sourceForResource(
"/yang-data-extension-test/foobar.yang");
private static final Revision REVISION = Revision.of("2017-06-01");
private static final QNameModule FOO_QNAMEMODULE = QNameModule.create(XMLNamespace.of("foo"), REVISION);
@Test
public void testYangData() throws Exception {
final SchemaContext schemaContext = REACTOR.newBuild().addSources(FOO_MODULE, IETF_RESTCONF_MODULE)
.buildEffective();
assertNotNull(schemaContext);
final Collection<? extends ExtensionDefinition> extensions = schemaContext.getExtensions();
assertEquals(1, extensions.size());
final Module foo = schemaContext.findModule(FOO_QNAMEMODULE).get();
final Collection<? extends UnknownSchemaNode> unknownSchemaNodes = foo.getUnknownSchemaNodes();
assertEquals(2, unknownSchemaNodes.size());
YangDataSchemaNode myYangDataANode = null;
YangDataSchemaNode myYangDataBNode = null;
for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
assertThat(unknownSchemaNode, instanceOf(YangDataSchemaNode.class));
final YangDataSchemaNode yangDataSchemaNode = (YangDataSchemaNode) unknownSchemaNode;
if ("my-yang-data-a".equals(yangDataSchemaNode.getNodeParameter())) {
myYangDataANode = yangDataSchemaNode;
} else if ("my-yang-data-b".equals(yangDataSchemaNode.getNodeParameter())) {
myYangDataBNode = yangDataSchemaNode;
}
}
assertNotNull(myYangDataANode);
assertNotNull(myYangDataBNode);
}
@Test
public void testConfigStatementBeingIgnoredInYangDataBody() throws Exception {
final SchemaContext schemaContext = REACTOR.newBuild().addSources(BAZ_MODULE, IETF_RESTCONF_MODULE)
.buildEffective();
assertNotNull(schemaContext);
final Module baz = schemaContext.findModule("baz", REVISION).get();
final Collection<? extends UnknownSchemaNode> unknownSchemaNodes = baz.getUnknownSchemaNodes();
assertEquals(1, unknownSchemaNodes.size());
final UnknownSchemaNode unknownSchemaNode = unknownSchemaNodes.iterator().next();
assertThat(unknownSchemaNode, instanceOf(YangDataSchemaNode.class));
final YangDataSchemaNode myYangDataNode = (YangDataSchemaNode) unknownSchemaNode;
assertNotNull(myYangDataNode);
final Collection<? extends DataSchemaNode> yangDataChildren = myYangDataNode.getChildNodes();
assertEquals(1, yangDataChildren.size());
final DataSchemaNode childInYangData = yangDataChildren.iterator().next();
assertThat(childInYangData, instanceOf(ContainerSchemaNode.class));
final ContainerSchemaNode contInYangData = (ContainerSchemaNode) childInYangData;
assertEquals(Optional.empty(), contInYangData.effectiveConfig());
final ContainerSchemaNode innerCont = (ContainerSchemaNode) contInYangData.getDataChildByName(
QName.create(baz.getQNameModule(), "inner-cont"));
assertNotNull(innerCont);
assertEquals(Optional.empty(), innerCont.effectiveConfig());
final ContainerSchemaNode grpCont = (ContainerSchemaNode) contInYangData.getDataChildByName(
QName.create(baz.getQNameModule(), "grp-cont"));
assertNotNull(grpCont);
assertEquals(Optional.empty(), grpCont.effectiveConfig());
}
@Test
public void testIfFeatureStatementBeingIgnoredInYangDataBody() throws Exception {
final SchemaContext schemaContext = REACTOR.newBuild().setSupportedFeatures(ImmutableSet.of())
.addSources(FOOBAR_MODULE, IETF_RESTCONF_MODULE).buildEffective();
assertNotNull(schemaContext);
final Module foobar = schemaContext.findModule("foobar", REVISION).get();
final Collection<? extends UnknownSchemaNode> unknownSchemaNodes = foobar.getUnknownSchemaNodes();
assertEquals(1, unknownSchemaNodes.size());
final UnknownSchemaNode unknownSchemaNode = unknownSchemaNodes.iterator().next();
assertThat(unknownSchemaNode, instanceOf(YangDataSchemaNode.class));
final YangDataSchemaNode myYangDataNode = (YangDataSchemaNode) unknownSchemaNode;
assertNotNull(myYangDataNode);
final Collection<? extends DataSchemaNode> yangDataChildren = myYangDataNode.getChildNodes();
assertEquals(1, yangDataChildren.size());
final DataSchemaNode childInYangData = yangDataChildren.iterator().next();
assertThat(childInYangData, instanceOf(ContainerSchemaNode.class));
final ContainerSchemaNode contInYangData = (ContainerSchemaNode) childInYangData;
final ContainerSchemaNode innerCont = (ContainerSchemaNode) contInYangData.getDataChildByName(
QName.create(foobar.getQNameModule(), "inner-cont"));
assertNotNull(innerCont);
final ContainerSchemaNode grpCont = (ContainerSchemaNode) contInYangData.getDataChildByName(
QName.create(foobar.getQNameModule(), "grp-cont"));
assertNotNull(grpCont);
}
@Test
public void testYangDataBeingIgnored() throws Exception {
// yang-data statement is ignored if it does not appear as a top-level statement
// i.e., it will not appear in the final SchemaContext
final SchemaContext schemaContext = REACTOR.newBuild().addSources(BAR_MODULE, IETF_RESTCONF_MODULE)
.buildEffective();
assertNotNull(schemaContext);
final Module bar = schemaContext.findModule("bar", REVISION).get();
final ContainerSchemaNode cont = (ContainerSchemaNode) bar.getDataChildByName(
QName.create(bar.getQNameModule(), "cont"));
assertNotNull(cont);
final Collection<? extends ExtensionDefinition> extensions = schemaContext.getExtensions();
assertEquals(1, extensions.size());
final Collection<? extends UnknownSchemaNode> unknownSchemaNodes = cont.getUnknownSchemaNodes();
assertEquals(0, unknownSchemaNodes.size());
}
@Test
public void testYangDataWithMissingTopLevelContainer() {
final BuildAction build = REACTOR.newBuild().addSources(FOO_INVALID_1_MODULE, IETF_RESTCONF_MODULE);
final ReactorException ex = assertThrows(ReactorException.class, () -> build.buildEffective());
final Throwable cause = ex.getCause();
assertThat(cause, instanceOf(MissingSubstatementException.class));
assertThat(cause.getMessage(), startsWith("yang-data requires at least one substatement [at "));
}
@Test
public void testYangDataWithTwoTopLevelContainers() {
final BuildAction build = REACTOR.newBuild().addSources(FOO_INVALID_2_MODULE, IETF_RESTCONF_MODULE);
final ReactorException ex = assertThrows(ReactorException.class, () -> build.buildEffective());
final Throwable cause = ex.getCause();
assertThat(cause, instanceOf(InvalidSubstatementException.class));
assertThat(cause.getMessage(),
startsWith("yang-data requires exactly one container data node definition, found ["));
}
}
| Modernize YangDataExtensionTest
Use local variable type inference to reduce verbosity a bit.
Change-Id: I3006823047e8f8643c781ab0b086ff014aab1bc3
Signed-off-by: Robert Varga <[email protected]>
| parser/rfc8040-parser-support/src/test/java/org/opendaylight/yangtools/rfc8040/parser/YangDataExtensionTest.java | Modernize YangDataExtensionTest |
|
Java | epl-1.0 | 856977bf098355ff8d6d9d687586dbbae89ffc8e | 0 | vadimnehta/mdht,drbgfc/mdht,sarpkayanehta/mdht,drbgfc/mdht,vadimnehta/mdht,sarpkayanehta/mdht,mdht/mdht,mdht/mdht,drbgfc/mdht,mdht/mdht,drbgfc/mdht,drbgfc/mdht,mdht/mdht,drbgfc/mdht,vadimnehta/mdht,vadimnehta/mdht,sarpkayanehta/mdht,mdht/mdht,vadimnehta/mdht,sarpkayanehta/mdht,vadimnehta/mdht,sarpkayanehta/mdht,sarpkayanehta/mdht | /*******************************************************************************
* Copyright (c) 2009 David A Carlson.
* 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:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*
* $Id$
*******************************************************************************/
package org.openhealthtools.mdht.uml.cda.dita;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import org.eclipse.core.runtime.IPath;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.openhealthtools.mdht.uml.cda.core.util.CDAModelUtil;
import org.openhealthtools.mdht.uml.cda.dita.internal.Logger;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetCode;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;
import org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil;
public class TransformValueSet extends TransformAbstract {
public TransformValueSet(DitaTransformerOptions options) {
super(options);
}
private void appendBody(PrintWriter writer, Enumeration umlEnumeration) {
writer.println("<body>");
writer.println("<!-- THIS IS GENERATED CONTENT, DO NOT EDIT -->");
writer.println("<section id=\"definition\">");
appendDefinition(writer, umlEnumeration);
appendConcepts(writer, umlEnumeration);
writer.println("</section>");
writer.println("</body>");
writer.println("</topic>");
}
private void appendConcepts(PrintWriter writer, Enumeration umlEnumeration) {
String codeSystemName = null;
ValueSetVersion valueSetVersion = TermProfileUtil.getValueSetVersion(umlEnumeration);
if (valueSetVersion != null && valueSetVersion.getCodeSystem() != null) {
codeSystemName = valueSetVersion.getCodeSystem().getBase_Enumeration().getName();
}
if (!umlEnumeration.getOwnedLiterals().isEmpty()) {
writer.println("<table><tgroup cols=\"4\">");
writer.println("<colspec colname=\"col1\" colwidth=\"1*\"/>");
writer.println("<colspec colname=\"col2\" colwidth=\"2*\"/>");
writer.println("<colspec colname=\"col3\" colwidth=\"1*\"/>");
writer.println("<colspec colname=\"col4\" colwidth=\"3*\"/>");
writer.println("<thead><row>");
writer.println("<entry>Concept Code</entry><entry>Concept Name</entry><entry>Code System</entry><entry>Description</entry>");
writer.println("</row></thead><tbody>");
for (EnumerationLiteral literal : umlEnumeration.getOwnedLiterals()) {
ValueSetCode valueSetCode = TermProfileUtil.getValueSetCode(literal);
writer.print("<row>");
// Concept Code
writer.print("<entry>" + literal.getName() + "</entry>");
// Concept Name
writer.print("<entry>");
if (valueSetCode != null && valueSetCode.getConceptName() != null) {
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetCode.getConceptName()));
}
writer.print("</entry>");
// Code System
writer.print("<entry>");
if (valueSetCode != null && valueSetCode.getCodeSystem() != null) {
writer.print(valueSetCode.getCodeSystem().getBase_Enumeration().getName());
} else if (codeSystemName != null) {
writer.print(codeSystemName);
}
writer.print("</entry>");
// Definition
writer.print("<entry>");
if (!literal.getOwnedComments().isEmpty()) {
Comment comment = literal.getOwnedComments().get(0);
writer.print(comment.getBody());
}
writer.print("</entry>");
// Usage Note
// writer.print("<entry>");
// if (valueSetCode != null && valueSetCode.getUsageNote() != null) {
// writer.print(valueSetCode.getUsageNote());
// }
// writer.print("</entry>");
writer.println("</row>");
}
writer.println("</tbody></tgroup></table>");
}
}
private void appendDefinition(PrintWriter writer, Enumeration umlEnumeration) {
writer.println("<table><tgroup cols=\"2\">");
writer.println("<colspec colname=\"col1\" colwidth=\"1*\"/>");
writer.println("<colspec colname=\"col2\" colwidth=\"4*\"/>");
writer.println("<tbody>");
ValueSetVersion valueSetVersion = TermProfileUtil.getValueSetVersion(umlEnumeration);
if (valueSetVersion != null) {
String valueSetId = valueSetVersion.getIdentifier() != null
? valueSetVersion.getIdentifier()
: "(OID not specified)";
writer.print("<row><entry>Value Set</entry><entry>");
writer.print(umlEnumeration.getName());
writer.print(" - " + valueSetId);
writer.println("</entry></row>");
if (valueSetVersion.getCodeSystem() != null) {
String codeSystemId = valueSetVersion.getCodeSystem().getIdentifier() != null
? valueSetVersion.getCodeSystem().getIdentifier()
: "(OID not specified)";
writer.print("<row><entry>Code System</entry><entry>");
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetVersion.getCodeSystem().getBase_Enumeration().getName()));
writer.print(" - " + codeSystemId);
writer.println("</entry></row>");
}
if (valueSetVersion.getVersion() != null) {
writer.print("<row><entry>Version</entry><entry>");
writer.print(valueSetVersion.getVersion());
writer.println("</entry></row>");
}
if (valueSetVersion.getSource() != null) {
writer.print("<row><entry>Source</entry><entry>");
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetVersion.getSource()));
writer.println("</entry></row>");
}
if (valueSetVersion.getUrl() != null) {
writer.print("<row><entry>Source URL</entry><entry>");
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetVersion.getUrl()));
writer.println("</entry></row>");
}
if (valueSetVersion.getDefinition() != null) {
writer.print("<row><entry>Definition</entry><entry>");
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetVersion.getDefinition()));
writer.println("</entry></row>");
}
}
for (Comment comment : umlEnumeration.getOwnedComments()) {
writer.print("<row><entry>Description</entry><entry>");
writer.println(comment.getBody());
writer.println("</entry></row>");
}
writer.println("</tbody></tgroup></table>");
}
private void appendHeader(PrintWriter writer, Enumeration umlEnumeration) {
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.println("<!DOCTYPE topic PUBLIC \"-//OASIS//DTD DITA Topic//EN\" \"topic.dtd\">");
writer.println("<topic id=\"classId\" xml:lang=\"en-us\">");
writer.print("<title>");
writer.print(UMLUtil.splitName(umlEnumeration));
writer.println("</title>");
ValueSetVersion valueSetVersion = TermProfileUtil.getValueSetVersion(umlEnumeration);
String valueSetId = valueSetVersion != null && valueSetVersion.getIdentifier() != null
? valueSetVersion.getIdentifier()
: "not specified";
// CodeSystemVersion codeSystem = null;
// Enumeration codeSystemEnum = null;
// if (valueSetVersion != null && valueSetVersion.getCodeSystem() != null) {
// codeSystem = valueSetVersion.getCodeSystem();
// codeSystemEnum = codeSystem.getBase_Enumeration();
// }
//
// writer.print("<shortdesc id=\"shortdesc\">");
// if (valueSetVersion != null) {
// writer.print("[OID: <tt>" + valueSetId + "</tt>");
// if (codeSystemEnum != null) {
// writer.print(" from code system: " + CDAModelUtil.fixNonXMLCharacters(codeSystemEnum.getName()));
// }
// writer.print("]");
// }
// writer.println("</shortdesc>");
writer.println("<prolog id=\"prolog\">");
if (valueSetVersion != null) {
writer.println("<resourceid id=\"" + valueSetId + "\"/>");
}
writer.println("</prolog>");
}
@Override
public Object caseEnumeration(Enumeration umlEnumeration) {
String pathFolder = "terminology";
String fileName = CDAModelUtil.validFileName(umlEnumeration.getName()) + ".dita";
IPath filePath = transformerOptions.getOutputPath().append(pathFolder).addTrailingSeparator().append(fileName);
File file = filePath.toFile();
PrintWriter writer = null;
// if (!file.exists()) {
try {
file.createNewFile();
writer = new PrintWriter(file);
appendHeader(writer, umlEnumeration);
appendBody(writer, umlEnumeration);
} catch (FileNotFoundException e) {
Logger.logException(e);
} catch (IOException e1) {
Logger.logException(e1);
} finally {
if (writer != null) {
writer.close();
}
}
// }
transformerOptions.getValueSetList().add(fileName);
return umlEnumeration;
}
}
| cda/plugins/org.openhealthtools.mdht.uml.cda.dita/src/org/openhealthtools/mdht/uml/cda/dita/TransformValueSet.java | /*******************************************************************************
* Copyright (c) 2009 David A Carlson.
* 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:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*
* $Id$
*******************************************************************************/
package org.openhealthtools.mdht.uml.cda.dita;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import org.eclipse.core.runtime.IPath;
import org.eclipse.uml2.uml.Comment;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.openhealthtools.mdht.uml.cda.core.util.CDAModelUtil;
import org.openhealthtools.mdht.uml.cda.dita.internal.Logger;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetCode;
import org.openhealthtools.mdht.uml.term.core.profile.ValueSetVersion;
import org.openhealthtools.mdht.uml.term.core.util.TermProfileUtil;
public class TransformValueSet extends TransformAbstract {
public TransformValueSet(DitaTransformerOptions options) {
super(options);
}
private void appendBody(PrintWriter writer, Enumeration umlEnumeration) {
writer.println("<body>");
writer.println("<!-- THIS IS GENERATED CONTENT, DO NOT EDIT -->");
writer.println("<section id=\"definition\">");
appendDefinition(writer, umlEnumeration);
appendConcepts(writer, umlEnumeration);
writer.println("</section>");
writer.println("</body>");
writer.println("</topic>");
}
private void appendConcepts(PrintWriter writer, Enumeration umlEnumeration) {
String codeSystemName = null;
ValueSetVersion valueSetVersion = TermProfileUtil.getValueSetVersion(umlEnumeration);
if (valueSetVersion != null && valueSetVersion.getCodeSystem() != null) {
codeSystemName = valueSetVersion.getCodeSystem().getBase_Enumeration().getName();
}
if (!umlEnumeration.getOwnedLiterals().isEmpty()) {
writer.println("<table><tgroup cols=\"4\">");
writer.println("<colspec colname=\"col1\" colwidth=\"1*\"/>");
writer.println("<colspec colname=\"col2\" colwidth=\"2*\"/>");
writer.println("<colspec colname=\"col3\" colwidth=\"1*\"/>");
writer.println("<colspec colname=\"col4\" colwidth=\"3*\"/>");
writer.println("<thead><row>");
writer.println("<entry>Concept Code</entry><entry>Concept Name</entry><entry>Code System</entry><entry>Description</entry>");
writer.println("</row></thead><tbody>");
for (EnumerationLiteral literal : umlEnumeration.getOwnedLiterals()) {
ValueSetCode valueSetCode = TermProfileUtil.getValueSetCode(literal);
writer.print("<row>");
// Concept Code
writer.print("<entry>" + literal.getName() + "</entry>");
// Concept Name
writer.print("<entry>");
if (valueSetCode != null && valueSetCode.getConceptName() != null) {
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetCode.getConceptName()));
}
writer.print("</entry>");
// Code System
writer.print("<entry>");
if (valueSetCode != null && valueSetCode.getCodeSystem() != null) {
writer.print(valueSetCode.getCodeSystem().getBase_Enumeration().getName());
} else if (codeSystemName != null) {
writer.print(codeSystemName);
}
writer.print("</entry>");
// Definition
writer.print("<entry>");
if (!literal.getOwnedComments().isEmpty()) {
Comment comment = literal.getOwnedComments().get(0);
writer.print(comment.getBody());
}
writer.print("</entry>");
// Usage Note
// writer.print("<entry>");
// if (valueSetCode != null && valueSetCode.getUsageNote() != null) {
// writer.print(valueSetCode.getUsageNote());
// }
// writer.print("</entry>");
writer.println("</row>");
}
writer.println("</tbody></tgroup></table>");
}
}
private void appendDefinition(PrintWriter writer, Enumeration umlEnumeration) {
writer.println("<table><tgroup cols=\"2\">");
writer.println("<colspec colname=\"col1\" colwidth=\"1*\"/>");
writer.println("<colspec colname=\"col2\" colwidth=\"4*\"/>");
writer.println("<tbody>");
ValueSetVersion valueSetVersion = TermProfileUtil.getValueSetVersion(umlEnumeration);
if (valueSetVersion != null) {
String valueSetId = valueSetVersion.getIdentifier() != null
? valueSetVersion.getIdentifier()
: "(OID not specified)";
writer.print("<row><entry>Value Set</entry><entry>");
writer.print(umlEnumeration.getName());
writer.print(" - " + valueSetId);
writer.println("</entry></row>");
if (valueSetVersion.getCodeSystem() != null) {
String codeSystemId = valueSetVersion.getCodeSystem().getIdentifier() != null
? valueSetVersion.getCodeSystem().getIdentifier()
: "(OID not specified)";
writer.print("<row><entry>Code System</entry><entry>");
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetVersion.getCodeSystem().getBase_Enumeration().getName()));
writer.print(" - " + codeSystemId);
writer.println("</entry></row>");
}
if (valueSetVersion.getVersion() != null) {
writer.print("<row><entry>Version</entry><entry>");
writer.print(valueSetVersion.getVersion());
writer.println("</entry></row>");
}
if (valueSetVersion.getSource() != null) {
writer.print("<row><entry>Source</entry><entry>");
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetVersion.getSource()));
writer.println("</entry></row>");
}
if (valueSetVersion.getUrl() != null) {
writer.print("<row><entry>Source URL</entry><entry>");
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetVersion.getUrl()));
writer.println("</entry></row>");
}
if (valueSetVersion.getDefinition() != null) {
writer.print("<row><entry>Definition</entry><entry>");
writer.print(CDAModelUtil.fixNonXMLCharacters(valueSetVersion.getDefinition()));
writer.println("</entry></row>");
}
}
for (Comment comment : umlEnumeration.getOwnedComments()) {
writer.print("<row><entry>Description</entry><entry>");
writer.println(comment.getBody());
writer.println("</entry></row>");
}
writer.println("</tbody></tgroup></table>");
}
private void appendHeader(PrintWriter writer, Enumeration umlEnumeration) {
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.println("<!DOCTYPE topic PUBLIC \"-//OASIS//DTD DITA Topic//EN\" \"topic.dtd\">");
writer.println("<topic id=\"classId\" xml:lang=\"en-us\">");
writer.print("<title>");
writer.print(UMLUtil.splitName(umlEnumeration));
writer.println("</title>");
ValueSetVersion valueSetVersion = TermProfileUtil.getValueSetVersion(umlEnumeration);
String valueSetId = valueSetVersion.getIdentifier() != null
? valueSetVersion.getIdentifier()
: "not specified";
// CodeSystemVersion codeSystem = null;
// Enumeration codeSystemEnum = null;
// if (valueSetVersion != null && valueSetVersion.getCodeSystem() != null) {
// codeSystem = valueSetVersion.getCodeSystem();
// codeSystemEnum = codeSystem.getBase_Enumeration();
// }
//
// writer.print("<shortdesc id=\"shortdesc\">");
// if (valueSetVersion != null) {
// writer.print("[OID: <tt>" + valueSetId + "</tt>");
// if (codeSystemEnum != null) {
// writer.print(" from code system: " + CDAModelUtil.fixNonXMLCharacters(codeSystemEnum.getName()));
// }
// writer.print("]");
// }
// writer.println("</shortdesc>");
writer.println("<prolog id=\"prolog\">");
if (valueSetVersion != null) {
writer.println("<resourceid id=\"" + valueSetId + "\"/>");
}
writer.println("</prolog>");
}
@Override
public Object caseEnumeration(Enumeration umlEnumeration) {
String pathFolder = "terminology";
String fileName = CDAModelUtil.validFileName(umlEnumeration.getName()) + ".dita";
IPath filePath = transformerOptions.getOutputPath().append(pathFolder).addTrailingSeparator().append(fileName);
File file = filePath.toFile();
PrintWriter writer = null;
// if (!file.exists()) {
try {
file.createNewFile();
writer = new PrintWriter(file);
appendHeader(writer, umlEnumeration);
appendBody(writer, umlEnumeration);
} catch (FileNotFoundException e) {
Logger.logException(e);
} catch (IOException e1) {
Logger.logException(e1);
} finally {
if (writer != null) {
writer.close();
}
}
// }
transformerOptions.getValueSetList().add(fileName);
return umlEnumeration;
}
}
| Add test for enumerations without ValueSetVersion stereotype. | cda/plugins/org.openhealthtools.mdht.uml.cda.dita/src/org/openhealthtools/mdht/uml/cda/dita/TransformValueSet.java | Add test for enumerations without ValueSetVersion stereotype. |
|
Java | agpl-3.0 | bb45007bd99911bc607824f43ca8418f90db302c | 0 | elki-project/elki,elki-project/elki,elki-project/elki | package de.lmu.ifi.dbs.elki.visualization.visualizers.scatterplot.outlier;
/*
This file is part of ELKI:
Environment for Developing KDD-Applications Supported by Index-Structures
Copyright (C) 2012
Ludwig-Maximilians-Universität München
Lehr- und Forschungseinheit für Datenbanksysteme
ELKI Development Team
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/>.
*/
import java.util.Collection;
import org.apache.batik.util.SVGConstants;
import org.w3c.dom.Element;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.database.datastore.DataStoreListener;
import de.lmu.ifi.dbs.elki.database.ids.DBIDIter;
import de.lmu.ifi.dbs.elki.database.ids.DBIDRef;
import de.lmu.ifi.dbs.elki.result.HierarchicalResult;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.result.ResultUtil;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult;
import de.lmu.ifi.dbs.elki.utilities.documentation.Reference;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ObjectParameter;
import de.lmu.ifi.dbs.elki.utilities.scaling.ScalingFunction;
import de.lmu.ifi.dbs.elki.utilities.scaling.outlier.OutlierScalingFunction;
import de.lmu.ifi.dbs.elki.visualization.VisualizationTask;
import de.lmu.ifi.dbs.elki.visualization.colors.ColorLibrary;
import de.lmu.ifi.dbs.elki.visualization.css.CSSClass;
import de.lmu.ifi.dbs.elki.visualization.projector.ScatterPlotProjector;
import de.lmu.ifi.dbs.elki.visualization.style.ClassStylingPolicy;
import de.lmu.ifi.dbs.elki.visualization.style.StyleLibrary;
import de.lmu.ifi.dbs.elki.visualization.style.StyleResult;
import de.lmu.ifi.dbs.elki.visualization.style.StylingPolicy;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil;
import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisFactory;
import de.lmu.ifi.dbs.elki.visualization.visualizers.Visualization;
import de.lmu.ifi.dbs.elki.visualization.visualizers.scatterplot.AbstractScatterplotVisualization;
import de.lmu.ifi.dbs.elki.visualization.visualizers.thumbs.ThumbnailVisualization;
/**
* Generates a SVG-Element containing bubbles. A Bubble is a circle visualizing
* an outlierness-score, with its center at the position of the visualized
* object and its radius depending on the objects score.
*
* @author Remigius Wojdanowski
* @author Erich Schubert
*
* @apiviz.stereotype factory
* @apiviz.uses Instance oneway - - «create»
*/
@Reference(authors = "E. Achtert, H.-P. Kriegel, L. Reichert, E. Schubert, R. Wojdanowski, A. Zimek", title = "Visual Evaluation of Outlier Detection Models", booktitle = "Proceedings of the 15th International Conference on Database Systems for Advanced Applications (DASFAA), Tsukuba, Japan, 2010", url = "http://dx.doi.org/10.1007/978-3-642-12098-5_34")
public class BubbleVisualization extends AbstractVisFactory {
/**
* Generic tag to indicate the type of element. Used in IDs, CSS-Classes etc.
*/
public static final String BUBBLE = "bubble";
/**
* A short name characterizing this Visualizer.
*/
public static final String NAME = "Outlier Bubbles";
/**
* Current settings
*/
protected Parameterizer settings;
/**
* Constructor.
*
* @param settings Settings
*/
public BubbleVisualization(Parameterizer settings) {
super();
this.settings = settings;
thumbmask |= ThumbnailVisualization.ON_DATA | ThumbnailVisualization.ON_STYLE;
}
@Override
public Visualization makeVisualization(VisualizationTask task) {
if(settings.scaling != null && settings.scaling instanceof OutlierScalingFunction) {
final OutlierResult outlierResult = task.getResult();
((OutlierScalingFunction) settings.scaling).prepare(outlierResult);
}
return new Instance(task);
}
@Override
public void processNewResult(HierarchicalResult baseResult, Result result) {
Collection<OutlierResult> ors = ResultUtil.filterResults(result, OutlierResult.class);
for(OutlierResult o : ors) {
Collection<ScatterPlotProjector<?>> ps = ResultUtil.filterResults(baseResult, ScatterPlotProjector.class);
boolean vis = true;
// Quick and dirty hack: hide if parent result is also an outlier result
// Since that probably is already visible and we're redundant.
for(Result r : o.getHierarchy().getParents(o)) {
if(r instanceof OutlierResult) {
vis = false;
break;
}
}
for(ScatterPlotProjector<?> p : ps) {
final VisualizationTask task = new VisualizationTask(NAME, o, p.getRelation(), this);
task.level = VisualizationTask.LEVEL_DATA;
if(!vis) {
task.initDefaultVisibility(false);
}
baseResult.getHierarchy().add(o, task);
baseResult.getHierarchy().add(p, task);
}
}
}
/**
* Factory for producing bubble visualizations
*
* @author Erich Schubert
*
* @apiviz.has OutlierResult oneway - - visualizes
*/
public class Instance extends AbstractScatterplotVisualization implements DataStoreListener {
/**
* The outlier result to visualize
*/
protected OutlierResult result;
/**
* Constructor.
*
* @param task Visualization task
*/
public Instance(VisualizationTask task) {
super(task);
this.result = task.getResult();
context.addDataStoreListener(this);
context.addResultListener(this);
incrementalRedraw();
}
@Override
public void destroy() {
super.destroy();
context.removeResultListener(this);
context.removeDataStoreListener(this);
}
@Override
public void redraw() {
final StyleResult style = context.getStyleResult();
StylingPolicy stylepolicy = style.getStylingPolicy();
// bubble size
final double bubble_size = style.getStyleLibrary().getSize(StyleLibrary.BUBBLEPLOT);
if(stylepolicy instanceof ClassStylingPolicy) {
ClassStylingPolicy colors = (ClassStylingPolicy) stylepolicy;
setupCSS(svgp, colors);
// draw data
for(DBIDIter objId = sample.getSample().iter(); objId.valid(); objId.advance()) {
final double radius = getScaledForId(objId);
if(radius > 0.01 && !Double.isInfinite(radius)) {
final NumberVector<?> vec = rel.get(objId);
if(vec != null) {
double[] v = proj.fastProjectDataToRenderSpace(vec);
Element circle = svgp.svgCircle(v[0], v[1], radius * bubble_size);
SVGUtil.addCSSClass(circle, BUBBLE + colors.getStyleForDBID(objId));
layer.appendChild(circle);
}
}
}
}
else {
// draw data
for(DBIDIter objId = sample.getSample().iter(); objId.valid(); objId.advance()) {
final double radius = getScaledForId(objId);
if(radius > 0.01 && !Double.isInfinite(radius)) {
final NumberVector<?> vec = rel.get(objId);
if(vec != null) {
double[] v = proj.fastProjectDataToRenderSpace(vec);
Element circle = svgp.svgCircle(v[0], v[1], radius * bubble_size);
int color = stylepolicy.getColorForDBID(objId);
final StringBuilder cssstyle = new StringBuilder();
if(settings.fill) {
cssstyle.append(SVGConstants.CSS_FILL_PROPERTY).append(':').append(SVGUtil.colorToString(color));
cssstyle.append(SVGConstants.CSS_FILL_OPACITY_PROPERTY).append(":0.5");
}
else {
cssstyle.append(SVGConstants.CSS_STROKE_VALUE).append(':').append(SVGUtil.colorToString(color));
cssstyle.append(SVGConstants.CSS_FILL_PROPERTY).append(':').append(SVGConstants.CSS_NONE_VALUE);
}
SVGUtil.setAtt(circle, SVGConstants.SVG_STYLE_ATTRIBUTE, cssstyle.toString());
layer.appendChild(circle);
}
}
}
}
}
@Override
public void resultChanged(Result current) {
super.resultChanged(current);
if(sample == current || context.getStyleResult() == current) {
synchronizedRedraw();
}
}
/**
* Registers the Bubble-CSS-Class at a SVGPlot.
*
* @param svgp the SVGPlot to register the Tooltip-CSS-Class.
* @param policy Clustering to use
*/
private void setupCSS(SVGPlot svgp, ClassStylingPolicy policy) {
final StyleLibrary style = context.getStyleResult().getStyleLibrary();
ColorLibrary colors = style.getColorSet(StyleLibrary.PLOT);
// creating IDs manually because cluster often return a null-ID.
for(int clusterID = policy.getMinStyle(); clusterID < policy.getMaxStyle(); clusterID++) {
CSSClass bubble = new CSSClass(svgp, BUBBLE + clusterID);
bubble.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, style.getLineWidth(StyleLibrary.PLOT));
String color = colors.getColor(clusterID);
if(settings.fill) {
bubble.setStatement(SVGConstants.CSS_FILL_PROPERTY, color);
bubble.setStatement(SVGConstants.CSS_FILL_OPACITY_PROPERTY, 0.5);
}
else {
// for diamond-shaped strokes, see bugs.sun.com, bug ID 6294396
bubble.setStatement(SVGConstants.CSS_STROKE_VALUE, color);
bubble.setStatement(SVGConstants.CSS_FILL_PROPERTY, SVGConstants.CSS_NONE_VALUE);
}
svgp.addCSSClassOrLogError(bubble);
}
}
/**
* Convenience method to apply scalings in the right order.
*
* @param id object ID to get scaled score for
* @return a Double representing a outlierness-score, after it has modified
* by the given scales.
*/
protected double getScaledForId(DBIDRef id) {
double d = result.getScores().get(id).doubleValue();
if(Double.isNaN(d) || Double.isInfinite(d)) {
return 0.0;
}
if(settings.scaling == null) {
return result.getOutlierMeta().normalizeScore(d);
}
else {
return settings.scaling.getScaled(d);
}
}
}
/**
* Parameterization class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class Parameterizer extends AbstractParameterizer {
/**
* Flag for half-transparent filling of bubbles.
*
* <p>
* Key: {@code -bubble.fill}
* </p>
*/
public static final OptionID FILL_ID = new OptionID("bubble.fill", "Half-transparent filling of bubbles.");
/**
* Parameter for scaling functions
*
* <p>
* Key: {@code -bubble.scaling}
* </p>
*/
public static final OptionID SCALING_ID = new OptionID("bubble.scaling", "Additional scaling function for bubbles.");
/**
* Fill parameter.
*/
protected boolean fill;
/**
* Scaling function to use for Bubbles
*/
protected ScalingFunction scaling;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
Flag fillF = new Flag(FILL_ID);
if(config.grab(fillF)) {
fill = fillF.isTrue();
}
ObjectParameter<ScalingFunction> scalingP = new ObjectParameter<ScalingFunction>(SCALING_ID, OutlierScalingFunction.class, true);
if(config.grab(scalingP)) {
scaling = scalingP.instantiateClass(config);
}
}
@Override
protected BubbleVisualization makeInstance() {
return new BubbleVisualization(this);
}
}
} | src/de/lmu/ifi/dbs/elki/visualization/visualizers/scatterplot/outlier/BubbleVisualization.java | package de.lmu.ifi.dbs.elki.visualization.visualizers.scatterplot.outlier;
/*
This file is part of ELKI:
Environment for Developing KDD-Applications Supported by Index-Structures
Copyright (C) 2012
Ludwig-Maximilians-Universität München
Lehr- und Forschungseinheit für Datenbanksysteme
ELKI Development Team
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/>.
*/
import java.util.Collection;
import org.apache.batik.util.SVGConstants;
import org.w3c.dom.Element;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.database.datastore.DataStoreListener;
import de.lmu.ifi.dbs.elki.database.ids.DBIDIter;
import de.lmu.ifi.dbs.elki.database.ids.DBIDRef;
import de.lmu.ifi.dbs.elki.result.HierarchicalResult;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.result.ResultUtil;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult;
import de.lmu.ifi.dbs.elki.utilities.documentation.Reference;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ObjectParameter;
import de.lmu.ifi.dbs.elki.utilities.scaling.ScalingFunction;
import de.lmu.ifi.dbs.elki.utilities.scaling.outlier.OutlierScalingFunction;
import de.lmu.ifi.dbs.elki.visualization.VisualizationTask;
import de.lmu.ifi.dbs.elki.visualization.colors.ColorLibrary;
import de.lmu.ifi.dbs.elki.visualization.css.CSSClass;
import de.lmu.ifi.dbs.elki.visualization.projector.ScatterPlotProjector;
import de.lmu.ifi.dbs.elki.visualization.style.ClassStylingPolicy;
import de.lmu.ifi.dbs.elki.visualization.style.StyleLibrary;
import de.lmu.ifi.dbs.elki.visualization.style.StylingPolicy;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil;
import de.lmu.ifi.dbs.elki.visualization.visualizers.AbstractVisFactory;
import de.lmu.ifi.dbs.elki.visualization.visualizers.Visualization;
import de.lmu.ifi.dbs.elki.visualization.visualizers.scatterplot.AbstractScatterplotVisualization;
import de.lmu.ifi.dbs.elki.visualization.visualizers.thumbs.ThumbnailVisualization;
/**
* Generates a SVG-Element containing bubbles. A Bubble is a circle visualizing
* an outlierness-score, with its center at the position of the visualized
* object and its radius depending on the objects score.
*
* @author Remigius Wojdanowski
* @author Erich Schubert
*
* @apiviz.stereotype factory
* @apiviz.uses Instance oneway - - «create»
*/
@Reference(authors = "E. Achtert, H.-P. Kriegel, L. Reichert, E. Schubert, R. Wojdanowski, A. Zimek", title = "Visual Evaluation of Outlier Detection Models", booktitle = "Proceedings of the 15th International Conference on Database Systems for Advanced Applications (DASFAA), Tsukuba, Japan, 2010", url = "http://dx.doi.org/10.1007/978-3-642-12098-5_34")
public class BubbleVisualization extends AbstractVisFactory {
/**
* Generic tag to indicate the type of element. Used in IDs, CSS-Classes etc.
*/
public static final String BUBBLE = "bubble";
/**
* A short name characterizing this Visualizer.
*/
public static final String NAME = "Outlier Bubbles";
/**
* Current settings
*/
protected Parameterizer settings;
/**
* Constructor.
*
* @param settings Settings
*/
public BubbleVisualization(Parameterizer settings) {
super();
this.settings = settings;
thumbmask |= ThumbnailVisualization.ON_DATA | ThumbnailVisualization.ON_STYLE;
}
@Override
public Visualization makeVisualization(VisualizationTask task) {
if(settings.scaling != null && settings.scaling instanceof OutlierScalingFunction) {
final OutlierResult outlierResult = task.getResult();
((OutlierScalingFunction) settings.scaling).prepare(outlierResult);
}
return new Instance(task);
}
@Override
public void processNewResult(HierarchicalResult baseResult, Result result) {
Collection<OutlierResult> ors = ResultUtil.filterResults(result, OutlierResult.class);
for(OutlierResult o : ors) {
Collection<ScatterPlotProjector<?>> ps = ResultUtil.filterResults(baseResult, ScatterPlotProjector.class);
boolean vis = true;
// Quick and dirty hack: hide if parent result is also an outlier result
// Since that probably is already visible and we're redundant.
for(Result r : o.getHierarchy().getParents(o)) {
if(r instanceof OutlierResult) {
vis = false;
break;
}
}
for(ScatterPlotProjector<?> p : ps) {
final VisualizationTask task = new VisualizationTask(NAME, o, p.getRelation(), this);
task.level = VisualizationTask.LEVEL_DATA;
if(!vis) {
task.initDefaultVisibility(false);
}
baseResult.getHierarchy().add(o, task);
baseResult.getHierarchy().add(p, task);
}
}
}
/**
* Factory for producing bubble visualizations
*
* @author Erich Schubert
*
* @apiviz.has OutlierResult oneway - - visualizes
*/
public class Instance extends AbstractScatterplotVisualization implements DataStoreListener {
/**
* The outlier result to visualize
*/
protected OutlierResult result;
/**
* Constructor.
*
* @param task Visualization task
*/
public Instance(VisualizationTask task) {
super(task);
this.result = task.getResult();
context.addDataStoreListener(this);
context.addResultListener(this);
incrementalRedraw();
}
@Override
public void destroy() {
super.destroy();
context.removeResultListener(this);
context.removeDataStoreListener(this);
}
@Override
public void redraw() {
StylingPolicy stylepolicy = context.getStyleResult().getStylingPolicy();
// bubble size
final double bubble_size = context.getStyleLibrary().getSize(StyleLibrary.BUBBLEPLOT);
if(stylepolicy instanceof ClassStylingPolicy) {
ClassStylingPolicy colors = (ClassStylingPolicy) stylepolicy;
setupCSS(svgp, colors);
// draw data
for(DBIDIter objId = sample.getSample().iter(); objId.valid(); objId.advance()) {
final double radius = getScaledForId(objId);
if(radius > 0.01 && !Double.isInfinite(radius)) {
final NumberVector<?> vec = rel.get(objId);
if(vec != null) {
double[] v = proj.fastProjectDataToRenderSpace(vec);
Element circle = svgp.svgCircle(v[0], v[1], radius * bubble_size);
SVGUtil.addCSSClass(circle, BUBBLE + colors.getStyleForDBID(objId));
layer.appendChild(circle);
}
}
}
}
else {
// draw data
for(DBIDIter objId = sample.getSample().iter(); objId.valid(); objId.advance()) {
final double radius = getScaledForId(objId);
if(radius > 0.01 && !Double.isInfinite(radius)) {
final NumberVector<?> vec = rel.get(objId);
if(vec != null) {
double[] v = proj.fastProjectDataToRenderSpace(vec);
Element circle = svgp.svgCircle(v[0], v[1], radius * bubble_size);
int color = stylepolicy.getColorForDBID(objId);
final StringBuilder style = new StringBuilder();
if(settings.fill) {
style.append(SVGConstants.CSS_FILL_PROPERTY).append(':').append(SVGUtil.colorToString(color));
style.append(SVGConstants.CSS_FILL_OPACITY_PROPERTY).append(":0.5");
}
else {
style.append(SVGConstants.CSS_STROKE_VALUE).append(':').append(SVGUtil.colorToString(color));
style.append(SVGConstants.CSS_FILL_PROPERTY).append(':').append(SVGConstants.CSS_NONE_VALUE);
}
SVGUtil.setAtt(circle, SVGConstants.SVG_STYLE_ATTRIBUTE, style.toString());
layer.appendChild(circle);
}
}
}
}
}
@Override
public void resultChanged(Result current) {
super.resultChanged(current);
if(sample == current || context.getStyleResult() == current) {
synchronizedRedraw();
}
}
/**
* Registers the Bubble-CSS-Class at a SVGPlot.
*
* @param svgp the SVGPlot to register the Tooltip-CSS-Class.
* @param policy Clustering to use
*/
private void setupCSS(SVGPlot svgp, ClassStylingPolicy policy) {
ColorLibrary colors = context.getStyleLibrary().getColorSet(StyleLibrary.PLOT);
// creating IDs manually because cluster often return a null-ID.
for(int clusterID = policy.getMinStyle(); clusterID < policy.getMaxStyle(); clusterID++) {
CSSClass bubble = new CSSClass(svgp, BUBBLE + clusterID);
bubble.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, context.getStyleLibrary().getLineWidth(StyleLibrary.PLOT));
String color = colors.getColor(clusterID);
if(settings.fill) {
bubble.setStatement(SVGConstants.CSS_FILL_PROPERTY, color);
bubble.setStatement(SVGConstants.CSS_FILL_OPACITY_PROPERTY, 0.5);
}
else {
// for diamond-shaped strokes, see bugs.sun.com, bug ID 6294396
bubble.setStatement(SVGConstants.CSS_STROKE_VALUE, color);
bubble.setStatement(SVGConstants.CSS_FILL_PROPERTY, SVGConstants.CSS_NONE_VALUE);
}
svgp.addCSSClassOrLogError(bubble);
}
}
/**
* Convenience method to apply scalings in the right order.
*
* @param id object ID to get scaled score for
* @return a Double representing a outlierness-score, after it has modified
* by the given scales.
*/
protected double getScaledForId(DBIDRef id) {
double d = result.getScores().get(id).doubleValue();
if(Double.isNaN(d) || Double.isInfinite(d)) {
return 0.0;
}
if(settings.scaling == null) {
return result.getOutlierMeta().normalizeScore(d);
}
else {
return settings.scaling.getScaled(d);
}
}
}
/**
* Parameterization class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class Parameterizer extends AbstractParameterizer {
/**
* Flag for half-transparent filling of bubbles.
*
* <p>
* Key: {@code -bubble.fill}
* </p>
*/
public static final OptionID FILL_ID = new OptionID("bubble.fill", "Half-transparent filling of bubbles.");
/**
* Parameter for scaling functions
*
* <p>
* Key: {@code -bubble.scaling}
* </p>
*/
public static final OptionID SCALING_ID = new OptionID("bubble.scaling", "Additional scaling function for bubbles.");
/**
* Fill parameter.
*/
protected boolean fill;
/**
* Scaling function to use for Bubbles
*/
protected ScalingFunction scaling;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
Flag fillF = new Flag(FILL_ID);
if(config.grab(fillF)) {
fill = fillF.isTrue();
}
ObjectParameter<ScalingFunction> scalingP = new ObjectParameter<ScalingFunction>(SCALING_ID, OutlierScalingFunction.class, true);
if(config.grab(scalingP)) {
scaling = scalingP.instantiateClass(config);
}
}
@Override
protected BubbleVisualization makeInstance() {
return new BubbleVisualization(this);
}
}
} | Resolve warnings.
| src/de/lmu/ifi/dbs/elki/visualization/visualizers/scatterplot/outlier/BubbleVisualization.java | Resolve warnings. |
|
Java | agpl-3.0 | 5d4aa17e3745816580eb25678bf515b4168ec098 | 0 | akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow,akvo/akvo-flow | /*
* Copyright (C) 2020 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package com.gallatinsystems.surveyal.dao;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyUtils;
import com.gallatinsystems.survey.dao.TranslationDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.gallatinsystems.survey.domain.Translation;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import org.akvo.flow.api.app.DataStoreTestUtil;
import org.junit.jupiter.api.AfterEach;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SurveyUtilsTest {
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private DataStoreTestUtil dataStoreTestUtil = new DataStoreTestUtil();
@BeforeEach
public void setUp() {
helper.setUp();
}
@AfterEach
public void tearDown() {
helper.tearDown();
}
@Test
public void testCopyTemplateSurvey() throws Exception {
Survey sourceSurvey = createSurvey(1, 1);
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), true);
List<QuestionGroup> qgs = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(1, qgs.size());
assertTrue(qgs.get(0).getImmutable());
List<Question> questions = new QuestionDao().listQuestionsBySurvey(copiedSurvey.getKey().getId());
assertEquals(1, questions.size());
assertTrue(questions.get(0).getImmutable());
}
@Test
public void testCopyTranslationsOfTemplateSurvey() throws Exception {
Survey sourceSurvey = createSurveyWithTranslations();
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), true);
List<Translation> translations = new TranslationDao().listByFormId(copiedSurvey.getKey().getId());
assertEquals(3, translations.size());
List<QuestionGroup> qgs = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(qgs.get(0).getKey().getId(), translations.get(0).getParentId());
assertEquals( "uno", translations.get(2).getText());
}
@Test
public void testCopySurvey() throws Exception {
Survey sourceSurvey = createSurvey(6, 4);
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), false);
List<QuestionGroup> copiedQuestionGroups = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(6, copiedQuestionGroups.size());
List<Question> copiedSurveyQuestions = new QuestionDao().listQuestionsBySurvey(copiedSurvey.getKey().getId());
assertEquals(24, copiedSurveyQuestions.size());
List<Question> copiedQuestionsForOneGroup = new QuestionDao().listQuestionsInOrderForGroup(copiedQuestionGroups.get(0).getKey().getId());
assertEquals(4, copiedQuestionsForOneGroup.size());
assertEquals(copiedSurvey.getKey().getId(), copiedQuestionsForOneGroup.get(0).getSurveyId());
}
@Test
public void testCopyTranslations() throws Exception {
Survey sourceSurvey = createSurveyWithTranslations();
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), false);
List<Translation> translations = new TranslationDao().listByFormId(copiedSurvey.getKey().getId());
assertEquals(3, translations.size());
List<QuestionGroup> qgs = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(qgs.get(0).getKey().getId(), translations.get(0).getParentId());
assertEquals( "uno", translations.get(2).getText());
}
private Survey copySurvey(Survey sourceSurvey) {
SurveyDto dto = new SurveyDto();
dto.setName(sourceSurvey.getName());
dto.setSurveyGroupId(sourceSurvey.getSurveyGroupId());
final Survey tmp = new Survey();
BeanUtils.copyProperties(sourceSurvey, tmp, Constants.EXCLUDED_PROPERTIES);
tmp.setName(dto.getName());
tmp.setSurveyGroupId(dto.getSurveyGroupId());
return new SurveyDAO().save(tmp);
}
private Survey createSurvey(int howManyQuestionGroups, int howManyQuestions) {
SurveyGroup newSg = dataStoreTestUtil.createSurveyGroup();
Survey newSurvey = dataStoreTestUtil.createSurvey(newSg);
for (int i = 0; i < howManyQuestionGroups; i++) {
QuestionGroup newQg = dataStoreTestUtil.createQuestionGroup(newSurvey);
for (int j = 0; j < howManyQuestions; j++) {
dataStoreTestUtil.createQuestion(newSurvey, newQg.getKey().getId(), Question.Type.FREE_TEXT);
}
}
return newSurvey;
}
private Survey createSurveyWithTranslations() {
SurveyGroup newSg = dataStoreTestUtil.createSurveyGroup();
Survey newSurvey = dataStoreTestUtil.createSurvey(newSg);
QuestionGroup newQg = dataStoreTestUtil.createQuestionGroup(newSurvey);
long questionGroupId = newQg.getKey().getId();
dataStoreTestUtil.createTranslation(newSurvey.getObjectId(), questionGroupId, Translation.ParentType.QUESTION_GROUP_NAME, "name", "es");
Question question = dataStoreTestUtil.createQuestion(newSurvey, questionGroupId, Question.Type.OPTION);
dataStoreTestUtil.createTranslation(newSurvey.getObjectId(), question.getKey().getId(), Translation.ParentType.QUESTION_TEXT, "hola", "es");
QuestionOption saved = dataStoreTestUtil.createQuestionOption(question);
dataStoreTestUtil.createTranslation(newSurvey.getObjectId(), saved.getKey().getId(), Translation.ParentType.QUESTION_OPTION, "uno", "es");
return newSurvey;
}
}
| GAE/test/com/gallatinsystems/surveyal/dao/SurveyUtilsTest.java | /*
* Copyright (C) 2020 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW 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 included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package com.gallatinsystems.surveyal.dao;
import com.gallatinsystems.common.Constants;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyUtils;
import com.gallatinsystems.survey.dao.TranslationDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.gallatinsystems.survey.domain.Translation;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import org.akvo.flow.api.app.DataStoreTestUtil;
import org.junit.jupiter.api.AfterEach;
import static org.junit.jupiter.api.Assertions.assertFalse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.waterforpeople.mapping.app.gwt.client.survey.SurveyDto;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SurveyUtilsTest {
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private DataStoreTestUtil dataStoreTestUtil = new DataStoreTestUtil();
@BeforeEach
public void setUp() {
helper.setUp();
}
@AfterEach
public void tearDown() {
helper.tearDown();
}
@Test
public void testCopyTemplateSurvey() throws Exception {
Survey sourceSurvey = createSurvey(1, 1);
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), true);
List<QuestionGroup> qgs = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(1, qgs.size());
assertTrue(qgs.get(0).getImmutable());
List<Question> questions = new QuestionDao().listQuestionsBySurvey(copiedSurvey.getKey().getId());
assertEquals(1, questions.size());
assertTrue(questions.get(0).getImmutable());
}
@Test
public void testCopyTranslationsOfTemplateSurvey() throws Exception {
Survey sourceSurvey = createSurveyWithTranslations();
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), true);
List<Translation> translations = new TranslationDao().listByFormId(copiedSurvey.getKey().getId());
assertEquals(3, translations.size());
List<QuestionGroup> qgs = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(qgs.get(0).getKey().getId(), translations.get(0).getParentId());
assertEquals( "uno", translations.get(2).getText());
}
@Test
public void testCopySurvey() throws Exception {
Survey sourceSurvey = createSurvey(6, 4);
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), false);
List<QuestionGroup> copiedQuestionGroups = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(6, copiedQuestionGroups.size());
List<Question> copiedSurveyQuestions = new QuestionDao().listQuestionsBySurvey(copiedSurvey.getKey().getId());
assertEquals(24, copiedSurveyQuestions.size());
Map<Integer, Question> copiedQuestionsForOneGroup = new QuestionDao().listQuestionsByQuestionGroup(copiedQuestionGroups.get(0).getKey().getId(), false);
assertEquals(4, copiedQuestionsForOneGroup.size());
}
@Test
public void testCopyTranslations() throws Exception {
Survey sourceSurvey = createSurveyWithTranslations();
Survey copiedSurvey = copySurvey(sourceSurvey);
SurveyUtils.copySurvey(copiedSurvey.getKey().getId(), sourceSurvey.getKey().getId(), false);
List<Translation> translations = new TranslationDao().listByFormId(copiedSurvey.getKey().getId());
assertEquals(3, translations.size());
List<QuestionGroup> qgs = new QuestionGroupDao().listQuestionGroupBySurvey(copiedSurvey.getKey().getId());
assertEquals(qgs.get(0).getKey().getId(), translations.get(0).getParentId());
assertEquals( "uno", translations.get(2).getText());
}
private Survey copySurvey(Survey sourceSurvey) {
SurveyDto dto = new SurveyDto();
dto.setName(sourceSurvey.getName());
dto.setSurveyGroupId(sourceSurvey.getSurveyGroupId());
final Survey tmp = new Survey();
BeanUtils.copyProperties(sourceSurvey, tmp, Constants.EXCLUDED_PROPERTIES);
tmp.setName(dto.getName());
tmp.setSurveyGroupId(dto.getSurveyGroupId());
return new SurveyDAO().save(tmp);
}
private Survey createSurvey(int howManyQuestionGroups, int howManyQuestions) {
SurveyGroup newSg = dataStoreTestUtil.createSurveyGroup();
Survey newSurvey = dataStoreTestUtil.createSurvey(newSg);
for (int i = 0; i < howManyQuestionGroups; i++) {
QuestionGroup newQg = dataStoreTestUtil.createQuestionGroup(newSurvey);
for (int j = 0; j < howManyQuestions; j++) {
dataStoreTestUtil.createQuestion(newSurvey, newQg.getKey().getId(), Question.Type.FREE_TEXT);
}
}
return newSurvey;
}
private Survey createSurveyWithTranslations() {
SurveyGroup newSg = dataStoreTestUtil.createSurveyGroup();
Survey newSurvey = dataStoreTestUtil.createSurvey(newSg);
QuestionGroup newQg = dataStoreTestUtil.createQuestionGroup(newSurvey);
long questionGroupId = newQg.getKey().getId();
dataStoreTestUtil.createTranslation(newSurvey.getObjectId(), questionGroupId, Translation.ParentType.QUESTION_GROUP_NAME, "name", "es");
Question question = dataStoreTestUtil.createQuestion(newSurvey, questionGroupId, Question.Type.OPTION);
dataStoreTestUtil.createTranslation(newSurvey.getObjectId(), question.getKey().getId(), Translation.ParentType.QUESTION_TEXT, "hola", "es");
QuestionOption saved = dataStoreTestUtil.createQuestionOption(question);
dataStoreTestUtil.createTranslation(newSurvey.getObjectId(), saved.getKey().getId(), Translation.ParentType.QUESTION_OPTION, "uno", "es");
return newSurvey;
}
}
| [#3669] Fix question retrieval method used for test
| GAE/test/com/gallatinsystems/surveyal/dao/SurveyUtilsTest.java | [#3669] Fix question retrieval method used for test |
|
Java | lgpl-2.1 | ceb71d54c93247d8c33a1b966a926896dbdb1613 | 0 | opax/exist,wolfgangmm/exist,olvidalo/exist,dizzzz/exist,eXist-db/exist,eXist-db/exist,adamretter/exist,adamretter/exist,hungerburg/exist,dizzzz/exist,lcahlander/exist,ambs/exist,lcahlander/exist,eXist-db/exist,eXist-db/exist,wolfgangmm/exist,windauer/exist,opax/exist,dizzzz/exist,ambs/exist,hungerburg/exist,adamretter/exist,ambs/exist,adamretter/exist,ambs/exist,lcahlander/exist,wolfgangmm/exist,hungerburg/exist,windauer/exist,wolfgangmm/exist,adamretter/exist,eXist-db/exist,lcahlander/exist,windauer/exist,hungerburg/exist,opax/exist,dizzzz/exist,adamretter/exist,dizzzz/exist,ambs/exist,wolfgangmm/exist,lcahlander/exist,opax/exist,windauer/exist,opax/exist,wolfgangmm/exist,hungerburg/exist,olvidalo/exist,windauer/exist,lcahlander/exist,eXist-db/exist,olvidalo/exist,olvidalo/exist,ambs/exist,olvidalo/exist,dizzzz/exist,windauer/exist | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2017 The eXist Project
* http://exist-db.org
*
* This program 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.storage.lock;
import com.evolvedbinary.j8fu.Either;
import com.evolvedbinary.j8fu.tuple.Tuple2;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.storage.NativeBroker;
import org.exist.storage.lock.Lock.LockMode;
import org.exist.storage.lock.Lock.LockType;
import org.exist.storage.txn.Txn;
import javax.annotation.Nullable;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import static org.exist.storage.lock.LockTable.LockAction.Action.*;
/**
* The Lock Table holds the details of
* threads awaiting to acquire a Lock
* and threads that have acquired a lock
*
* It is arranged by the id of the lock
* which is typically an indicator of the
* lock subject
*
* @author Adam Retter <[email protected]>
*/
public class LockTable {
public final static String PROP_DISABLE = "exist.locktable.disable";
public final static String PROP_SANITY_CHECK = "exist.locktable.sanity.check";
public final static String PROP_TRACE_STACK_DEPTH = "exist.locktable.trace.stack.depth";
private final static Logger LOG = LogManager.getLogger(LockTable.class);
private final static LockTable instance = new LockTable();
/**
* Set to false to disable all events
*/
private volatile boolean disableEvents = Boolean.getBoolean(PROP_DISABLE);
/**
* Set to true to enable sanity checking of lock leases
*/
private volatile boolean sanityCheck = Boolean.getBoolean(PROP_SANITY_CHECK);
/**
* Whether we should try and trace the stack for the lock event, -1 means all stack,
* 0 means no stack, n means n stack frames, 5 is a reasonable value
*/
private volatile int traceStackDepth = Optional.ofNullable(Integer.getInteger(PROP_TRACE_STACK_DEPTH))
.orElse(0);
/**
* List of threads attempting to acquire a lock
*
* Map<Id, Map<Lock Type, List<LockModeOwner>>>
*/
private final ConcurrentMap<String, Map<LockType, List<LockModeOwner>>> attempting = new ConcurrentHashMap<>();
/**
* Reference count of acquired locks by id and type
*
* Map<Id, Map<Lock Type, Map<Lock Mode, Map<Owner, HoldCount>>>>
*/
private final ConcurrentMap<String, Map<LockType, Map<LockMode, Map<String, Integer>>>> acquired = new ConcurrentHashMap<>();
/**
* The {@link #queue} holds lock events and lock listener events
* and is processed by the single thread {@link #queueConsumer} which uses
* {@link QueueConsumer} to ensure serializability of locking events and monitoring
*/
private final TransferQueue<Either<ListenerAction, LockAction>> queue = new LinkedTransferQueue<>();
private final Future<?> queueConsumer;
private LockTable() {
final ExecutorService executorService = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "exist-lockTable.processor"));
this.queueConsumer = executorService.submit(new QueueConsumer(queue, attempting, acquired));
// add a log listener if trace level logging is enabled
if(LOG.isTraceEnabled()) {
registerListener(new LockEventLogListener(LOG, Level.TRACE));
}
}
public static LockTable getInstance() {
return instance;
}
/**
* Set the depth at which we should trace lock events through the stack
*
* @param traceStackDepth -1 traces the whole stack, 0 means no stack traces, n means n stack frames
*/
public void setTraceStackDepth(final int traceStackDepth) {
this.traceStackDepth = traceStackDepth;
}
public void attempt(final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(Attempt, groupId, id, lockType, mode);
}
public void attemptFailed(final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(AttemptFailed, groupId, id, lockType, mode);
}
public void acquired(final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(Acquired, groupId, id, lockType, mode);
}
public void released(final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(Released, groupId, id, lockType, mode);
}
@Deprecated
public void released(final long groupId, final String id, final LockType lockType, final LockMode mode, final int count) {
event(Released, groupId, id, lockType, mode, count);
}
private void event(final LockAction.Action action, final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(action, groupId, id, lockType, mode, 1);
}
private void event(final LockAction.Action action, final long groupId, final String id, final LockType lockType, final LockMode mode, final int count) {
if(disableEvents) {
return;
}
final long timestamp = System.nanoTime();
final Thread currentThread = Thread.currentThread();
final String threadName = currentThread.getName();
@Nullable final StackTraceElement[] stackTrace = getStackTrace(currentThread);
if(ignoreEvent(threadName, id)) {
return;
}
final LockAction lockAction = new LockAction(action, groupId, id, lockType, mode, threadName, count, timestamp, stackTrace);
/**
* Very useful for debugging Lock life cycles
*/
if(sanityCheck) {
sanityCheckLockLifecycles(lockAction);
}
queue.add(Either.Right(lockAction));
}
/**
* Simple filtering to ignore events that are not of interest
*
* @param threadName The name of the thread that triggered the event
* @param id The id of the lock
*
* @return true if the event should be ignored
*/
private boolean ignoreEvent(final String threadName, final String id) {
return false;
// useful for debugging specific log events
// return threadName.startsWith("DefaultQuartzScheduler_")
// || id.equals("dom.dbx")
// || id.equals("collections.dbx")
// || id.equals("collections.dbx")
// || id.equals("structure.dbx")
// || id.equals("values.dbx")
// || id.equals("CollectionCache");
}
@Nullable
private StackTraceElement[] getStackTrace(final Thread thread) {
if(traceStackDepth == 0) {
return null;
} else {
final StackTraceElement[] stackTrace = thread.getStackTrace();
final int lastStackTraceElementIdx = stackTrace.length - 1;
final int from = findFirstExternalFrame(stackTrace);
final int to;
if (traceStackDepth == -1) {
to = lastStackTraceElementIdx;
} else {
final int calcTo = from + traceStackDepth;
if (calcTo > lastStackTraceElementIdx) {
to = lastStackTraceElementIdx;
} else {
to = calcTo;
}
}
return Arrays.copyOfRange(stackTrace, from, to);
}
}
private static final String THIS_CLASS_NAME = LockTable.class.getName();
private int findFirstExternalFrame(final StackTraceElement[] stackTrace) {
// we start with i = 1 to avoid Thread#getStackTrace() frame
for(int i = 1; i < stackTrace.length; i++) {
if(!THIS_CLASS_NAME.equals(stackTrace[i].getClassName())) {
return i;
}
}
return 0;
}
public void registerListener(final LockEventListener lockEventListener) {
final ListenerAction listenerAction = new ListenerAction(ListenerAction.Action.Register, lockEventListener);
queue.add(Either.Left(listenerAction));
}
public void deregisterListener(final LockEventListener lockEventListener) {
final ListenerAction listenerAction = new ListenerAction(ListenerAction.Action.Deregister, lockEventListener);
queue.add(Either.Left(listenerAction));
}
public boolean hasPendingEvents() {
return !queue.isEmpty();
}
/**
* Get's a copy of the current lock attempt information
*
* @return lock attempt information
*/
public Map<String, Map<LockType, List<LockModeOwner>>> getAttempting() {
return new HashMap<>(attempting);
}
/**
* Get's a copy of the current acquired lock information
*
* @return acquired lock information
*/
public Map<String, Map<LockType, Map<LockMode, Map<String, Integer>>>> getAcquired() {
return new HashMap<>(acquired);
}
public static class LockModeOwner {
final LockMode lockMode;
final String ownerThread;
public LockModeOwner(final LockMode lockMode, final String ownerThread) {
this.lockMode = lockMode;
this.ownerThread = ownerThread;
}
public LockMode getLockMode() {
return lockMode;
}
public String getOwnerThread() {
return ownerThread;
}
}
private static class QueueConsumer implements Runnable {
private final TransferQueue<Either<ListenerAction, LockAction>> queue;
private final ConcurrentMap<String, Map<LockType, List<LockModeOwner>>> attempting;
private final ConcurrentMap<String, Map<LockType, Map<LockMode, Map<String, Integer>>>> acquired;
private final List<LockEventListener> listeners = new ArrayList<>();
QueueConsumer(final TransferQueue<Either<ListenerAction, LockAction>> queue,
final ConcurrentMap<String, Map<LockType, List<LockModeOwner>>> attempting,
final ConcurrentMap<String, Map<LockType, Map<LockMode, Map<String, Integer>>>> acquired) {
this.queue = queue;
this.attempting = attempting;
this.acquired = acquired;
}
@Override
public void run() {
try {
while (true) {
final Either<ListenerAction, LockAction> event = queue.take();
if (event.isLeft()) {
processListenerAction(event.left().get());
} else {
processLockAction(event.right().get());
}
}
} catch (final InterruptedException e) {
LOG.fatal("LockTable.QueueConsumer was interrupted", e);
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
private void processListenerAction(final ListenerAction listenerAction) {
if(listenerAction.action == ListenerAction.Action.Register) {
listeners.add(listenerAction.lockEventListener);
listenerAction.lockEventListener.registered();
} else if(listenerAction.action == ListenerAction.Action.Deregister) {
listeners.remove(listenerAction.lockEventListener);
listenerAction.lockEventListener.unregistered();
}
}
private void processLockAction(final LockAction lockAction) {
if (lockAction.action == Attempt) {
notifyListenersOfAttempt(lockAction);
addToAttempting(lockAction);
} else if (lockAction.action == AttemptFailed) {
removeFromAttempting(lockAction);
notifyListenersOfAttemptFailed(lockAction);
} else if (lockAction.action == Acquired) {
removeFromAttempting(lockAction);
incrementAcquired(lockAction);
} else if (lockAction.action == Released) {
decrementAcquired(lockAction);
}
}
private void notifyListenersOfAttempt(final LockAction lockAction) {
for(final LockEventListener listener : listeners) {
try {
listener.accept(lockAction);
} catch (final Exception e) {
LOG.error("Listener '{}' error: ", listener.getClass().getName(), e);
}
}
}
private void notifyListenersOfAttemptFailed(final LockAction lockAction) {
for(final LockEventListener listener : listeners) {
try {
listener.accept(lockAction);
} catch (final Exception e) {
LOG.error("Listener '{}' error: ", listener.getClass().getName(), e);
}
}
}
private void notifyListenersOfAcquire(final LockAction lockAction, final int newReferenceCount) {
final LockAction newLockAction = lockAction.withCount(newReferenceCount);
for(final LockEventListener listener : listeners) {
try {
listener.accept(newLockAction);
} catch (final Exception e) {
LOG.error("Listener '{}' error: ", listener.getClass().getName(), e);
}
}
}
private void notifyListenersOfRelease(final LockAction lockAction, final int newReferenceCount) {
final LockAction newLockAction = lockAction.withCount(newReferenceCount);
for(final LockEventListener listener : listeners) {
try {
listener.accept(newLockAction);
} catch (final Exception e) {
LOG.error("Listener '{}' error: ", listener.getClass().getName(), e);
}
}
}
private void addToAttempting(final LockAction lockAction) {
attempting.compute(lockAction.id, (id, attempts) -> {
if (attempts == null) {
attempts = new HashMap<>();
}
attempts.compute(lockAction.lockType, (lockType, v) -> {
if (v == null) {
v = new ArrayList<>();
}
v.add(new LockModeOwner(lockAction.mode, lockAction.threadName));
return v;
});
return attempts;
});
}
private void removeFromAttempting(final LockAction lockAction) {
attempting.compute(lockAction.id, (id, attempts) -> {
if (attempts == null) {
return null;
} else {
attempts.compute(lockAction.lockType, (lockType, v) -> {
if (v == null) {
return null;
}
v.removeIf(val -> val.getLockMode() == lockAction.mode && val.getOwnerThread().equals(lockAction.threadName));
if (v.isEmpty()) {
return null;
} else {
return v;
}
});
if (attempts.isEmpty()) {
return null;
} else {
return attempts;
}
}
});
}
private void incrementAcquired(final LockAction lockAction) {
acquired.compute(lockAction.id, (id, acqu) -> {
if (acqu == null) {
acqu = new HashMap<>();
}
acqu.compute(lockAction.lockType, (lockType, v) -> {
if (v == null) {
v = new HashMap<>();
}
v.compute(lockAction.mode, (mode, ownerHolds) -> {
if (ownerHolds == null) {
ownerHolds = new HashMap<>();
}
ownerHolds.compute(lockAction.threadName, (threadName, holdCount) -> {
if(holdCount == null) {
holdCount = 0;
}
return ++holdCount;
});
final int lockModeHolds = ownerHolds.values().stream().collect(Collectors.summingInt(Integer::intValue));
notifyListenersOfAcquire(lockAction, lockModeHolds);
return ownerHolds;
});
return v;
});
return acqu;
});
}
private void decrementAcquired(final LockAction lockAction) {
acquired.compute(lockAction.id, (id, acqu) -> {
if (acqu == null) {
LOG.error("No entry found when trying to decrementAcquired for: id={}" + lockAction.id);
return null;
}
acqu.compute(lockAction.lockType, (lockType, v) -> {
if (v == null) {
LOG.error("No entry found when trying to decrementAcquired for: id={}, lockType={}", lockAction.id, lockAction.lockType);
return null;
}
v.compute(lockAction.mode, (mode, ownerHolds) -> {
if (ownerHolds == null) {
LOG.error("No entry found when trying to decrementAcquired for: id={}, lockType={}, lockMode={}", lockAction.id, lockAction.lockType, lockAction.mode);
return null;
} else {
ownerHolds.compute(lockAction.threadName, (threadName, holdCount) -> {
if(holdCount == null) {
LOG.error("No entry found when trying to decrementAcquired for: id={}, lockType={}, lockMode={}, threadName={}", lockAction.id, lockAction.lockType, lockAction.mode, lockAction.threadName);
return null;
} else if(holdCount == 0) {
LOG.error("Negative release when trying to decrementAcquired for: id={}, lockType={}, lockMode={}, threadName={}", lockAction.id, lockAction.lockType, lockAction.mode, lockAction.threadName);
return null;
} else if(holdCount == 1) {
return null;
} else {
return --holdCount;
}
});
final int lockModeHolds = ownerHolds.values().stream().collect(Collectors.summingInt(Integer::intValue));
notifyListenersOfRelease(lockAction, lockModeHolds);
if (ownerHolds.isEmpty()) {
return null;
} else {
return ownerHolds;
}
}
});
if (v.isEmpty()) {
return null;
} else {
return v;
}
});
if (acqu.isEmpty()) {
return null;
} else {
return acqu;
}
});
}
}
public interface LockEventListener {
default void registered() {}
void accept(final LockAction lockAction);
default void unregistered() {}
}
private static class ListenerAction {
enum Action {
Register,
Deregister
}
private final Action action;
private final LockEventListener lockEventListener;
public ListenerAction(final Action action, final LockEventListener lockEventListener) {
this.action = action;
this.lockEventListener = lockEventListener;
}
@Override
public String toString() {
return action.name() + " " + lockEventListener.getClass().getName();
}
}
public static class LockAction {
public enum Action {
Attempt,
AttemptFailed,
Acquired,
Released
}
public final Action action;
public final long groupId;
public final String id;
public final LockType lockType;
public final LockMode mode;
public final String threadName;
public final int count;
/**
* System#nanoTime()
*/
public final long timestamp;
@Nullable public final StackTraceElement[] stackTrace;
LockAction(final Action action, final long groupId, final String id, final LockType lockType, final LockMode mode, final String threadName, final int count, final long timestamp, @Nullable final StackTraceElement[] stackTrace) {
this.action = action;
this.groupId = groupId;
this.id = id;
this.lockType = lockType;
this.mode = mode;
this.threadName = threadName;
this.count = count;
this.timestamp = timestamp;
this.stackTrace = stackTrace;
}
public LockAction withCount(final int count) {
return new LockAction(action, groupId, id, lockType, mode, threadName, count, timestamp, stackTrace);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder()
.append(action.toString())
.append(' ')
.append(lockType.name());
if(groupId > -1) {
builder
.append("#")
.append(groupId);
}
builder.append('(')
.append(mode.toString())
.append(") of ")
.append(id);
if(stackTrace != null) {
final String reason = getSimpleStackReason();
if(reason != null) {
builder
.append(" for #")
.append(reason);
}
}
builder
.append(" by ")
.append(threadName)
.append(" at ")
.append(timestamp);
if (action == Acquired || action == Released) {
builder
.append(". count=")
.append(Integer.toString(count));
}
return builder.toString();
}
private static final String NATIVE_BROKER_CLASS_NAME = NativeBroker.class.getName();
private static final String COLLECTION_STORE_CLASS_NAME = NativeBroker.class.getName();
private static final String TXN_CLASS_NAME = Txn.class.getName();
@Nullable
public String getSimpleStackReason() {
for (final StackTraceElement stackTraceElement : stackTrace) {
final String className = stackTraceElement.getClassName();
if (className.equals(NATIVE_BROKER_CLASS_NAME) || className.equals(COLLECTION_STORE_CLASS_NAME) || className.equals(TXN_CLASS_NAME)) {
if (!(stackTraceElement.getMethodName().endsWith("LockCollection") || stackTraceElement.getMethodName().equals("lockCollectionCache"))) {
return stackTraceElement.getMethodName() + '(' + stackTraceElement.getLineNumber() + ')';
}
}
}
return null;
}
}
/** debugging tools below **/
/**
* Holds a count of READ and WRITE locks by {@link LockAction#id}
*/
private final Map<String, Tuple2<Long, Long>> lockCounts = new HashMap<>();
/**
* Checks that there are not more releases that there are acquires
*/
private void sanityCheckLockLifecycles(final LockAction lockAction) {
synchronized(lockCounts) {
long read = 0;
long write = 0;
final Tuple2<Long, Long> lockCount = lockCounts.get(lockAction.id);
if(lockCount != null) {
read = lockCount._1;
write = lockCount._2;
}
if(lockAction.action == LockAction.Action.Acquired) {
if(lockAction.mode == LockMode.READ_LOCK) {
read++;
} else if(lockAction.mode == LockMode.WRITE_LOCK) {
write++;
}
} else if(lockAction.action == LockAction.Action.Released) {
if(lockAction.mode == LockMode.READ_LOCK) {
if(read == 0) {
LOG.error("Negative READ_LOCKs", new IllegalStateException());
}
read--;
} else if(lockAction.mode == LockMode.WRITE_LOCK) {
if(write == 0) {
LOG.error("Negative WRITE_LOCKs", new IllegalStateException());
}
write--;
}
}
if(LOG.isTraceEnabled()) {
LOG.trace("QUEUE: {} (read={} write={})", lockAction.toString(), read, write);
}
lockCounts.put(lockAction.id, new Tuple2<>(read, write));
}
}
}
| src/org/exist/storage/lock/LockTable.java | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-2017 The eXist Project
* http://exist-db.org
*
* This program 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.storage.lock;
import com.evolvedbinary.j8fu.Either;
import com.evolvedbinary.j8fu.tuple.Tuple2;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.storage.NativeBroker;
import org.exist.storage.lock.Lock.LockMode;
import org.exist.storage.lock.Lock.LockType;
import org.exist.storage.txn.Txn;
import javax.annotation.Nullable;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import static org.exist.storage.lock.LockTable.LockAction.Action.*;
/**
* The Lock Table holds the details of
* threads awaiting to acquire a Lock
* and threads that have acquired a lock
*
* It is arranged by the id of the lock
* which is typically an indicator of the
* lock subject
*
* @author Adam Retter <[email protected]>
*/
public class LockTable {
public final static String PROP_DISABLE = "exist.locktable.disable";
public final static String PROP_SANITY_CHECK = "exist.locktable.sanity.check";
public final static String PROP_TRACE_STACK_DEPTH = "exist.locktable.trace.stack.depth";
private final static Logger LOG = LogManager.getLogger(LockTable.class);
private final static LockTable instance = new LockTable();
/**
* Set to false to disable all events
*/
private volatile boolean disableEvents = Boolean.getBoolean(PROP_DISABLE);
/**
* Set to true to enable sanity checking of lock leases
*/
private volatile boolean sanityCheck = Boolean.getBoolean(PROP_SANITY_CHECK);
/**
* Whether we should try and trace the stack for the lock event, -1 means all stack,
* 0 means no stack, n means n stack frames, 5 is a reasonable value
*/
private volatile int traceStackDepth = Optional.ofNullable(Integer.getInteger(PROP_TRACE_STACK_DEPTH))
.orElse(0);
/**
* List of threads attempting to acquire a lock
*
* Map<Id, Map<Lock Type, List<LockModeOwner>>>
*/
private final ConcurrentMap<String, Map<LockType, List<LockModeOwner>>> attempting = new ConcurrentHashMap<>();
/**
* Reference count of acquired locks by id and type
*
* Map<Id, Map<Lock Type, Map<Lock Mode, Map<Owner, HoldCount>>>>
*/
private final ConcurrentMap<String, Map<LockType, Map<LockMode, Map<String, Integer>>>> acquired = new ConcurrentHashMap<>();
/**
* The {@link #queue} holds lock events and lock listener events
* and is processed by the single thread {@link #queueConsumer} which uses
* {@link QueueConsumer} to ensure serializability of locking events and monitoring
*/
private final TransferQueue<Either<ListenerAction, LockAction>> queue = new LinkedTransferQueue<>();
private final Future<?> queueConsumer;
private LockTable() {
final ExecutorService executorService = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "exist-lockTable.processor"));
this.queueConsumer = executorService.submit(new QueueConsumer(queue, attempting, acquired));
// add a log listener if trace level logging is enabled
if(LOG.isTraceEnabled()) {
registerListener(new LockEventLogListener(LOG, Level.TRACE));
}
}
public static LockTable getInstance() {
return instance;
}
/**
* Set the depth at which we should trace lock events through the stack
*
* @param traceStackDepth -1 traces the whole stack, 0 means no stack traces, n means n stack frames
*/
public void setTraceStackDepth(final int traceStackDepth) {
this.traceStackDepth = traceStackDepth;
}
public void attempt(final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(Attempt, groupId, id, lockType, mode);
}
public void attemptFailed(final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(AttemptFailed, groupId, id, lockType, mode);
}
public void acquired(final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(Acquired, groupId, id, lockType, mode);
}
public void released(final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(Released, groupId, id, lockType, mode);
}
@Deprecated
public void released(final long groupId, final String id, final LockType lockType, final LockMode mode, final int count) {
event(Released, groupId, id, lockType, mode, count);
}
private void event(final LockAction.Action action, final long groupId, final String id, final LockType lockType, final LockMode mode) {
event(action, groupId, id, lockType, mode, 1);
}
private void event(final LockAction.Action action, final long groupId, final String id, final LockType lockType, final LockMode mode, final int count) {
if(disableEvents) {
return;
}
final long timestamp = System.nanoTime();
final Thread currentThread = Thread.currentThread();
final String threadName = currentThread.getName();
@Nullable final StackTraceElement[] stackTrace = getStackTrace(currentThread);
if(ignoreEvent(threadName, id)) {
return;
}
final LockAction lockAction = new LockAction(action, groupId, id, lockType, mode, threadName, count, timestamp, stackTrace);
/**
* Very useful for debugging Lock life cycles
*/
if(sanityCheck) {
sanityCheckLockLifecycles(lockAction);
}
queue.add(Either.Right(lockAction));
}
/**
* Simple filtering to ignore events that are not of interest
*
* @param threadName The name of the thread that triggered the event
* @param id The id of the lock
*
* @return true if the event should be ignored
*/
private boolean ignoreEvent(final String threadName, final String id) {
return false;
// useful for debugging specific log events
// return threadName.startsWith("DefaultQuartzScheduler_")
// || id.equals("dom.dbx")
// || id.equals("collections.dbx")
// || id.equals("collections.dbx")
// || id.equals("structure.dbx")
// || id.equals("values.dbx")
// || id.equals("CollectionCache");
}
@Nullable
private StackTraceElement[] getStackTrace(final Thread thread) {
if(traceStackDepth == 0) {
return null;
} else {
final StackTraceElement[] stackTrace = thread.getStackTrace();
final int lastStackTraceElementIdx = stackTrace.length - 1;
final int from = findFirstExternalFrame(stackTrace);
final int to;
if (traceStackDepth == -1) {
to = lastStackTraceElementIdx;
} else {
final int calcTo = from + traceStackDepth;
if (calcTo > lastStackTraceElementIdx) {
to = lastStackTraceElementIdx;
} else {
to = calcTo;
}
}
return Arrays.copyOfRange(stackTrace, from, to);
}
}
private static final String THIS_CLASS_NAME = LockTable.class.getName();
private int findFirstExternalFrame(final StackTraceElement[] stackTrace) {
// we start with i = 1 to avoid Thread#getStackTrace() frame
for(int i = 1; i < stackTrace.length; i++) {
if(!THIS_CLASS_NAME.equals(stackTrace[i].getClassName())) {
return i;
}
}
return 0;
}
public void registerListener(final LockEventListener lockEventListener) {
final ListenerAction listenerAction = new ListenerAction(ListenerAction.Action.Register, lockEventListener);
queue.add(Either.Left(listenerAction));
}
public void deregisterListener(final LockEventListener lockEventListener) {
final ListenerAction listenerAction = new ListenerAction(ListenerAction.Action.Deregister, lockEventListener);
queue.add(Either.Left(listenerAction));
}
public boolean hasPendingEvents() {
return !queue.isEmpty();
}
/**
* Get's a copy of the current lock attempt information
*
* @return lock attempt information
*/
public Map<String, Map<LockType, List<LockModeOwner>>> getAttempting() {
return new HashMap<>(attempting);
}
/**
* Get's a copy of the current acquired lock information
*
* @return acquired lock information
*/
public Map<String, Map<LockType, Map<LockMode, Map<String, Integer>>>> getAcquired() {
return new HashMap<>(acquired);
}
public static class LockModeOwner {
final LockMode lockMode;
final String ownerThread;
public LockModeOwner(final LockMode lockMode, final String ownerThread) {
this.lockMode = lockMode;
this.ownerThread = ownerThread;
}
public LockMode getLockMode() {
return lockMode;
}
public String getOwnerThread() {
return ownerThread;
}
}
private static class QueueConsumer implements Runnable {
private final TransferQueue<Either<ListenerAction, LockAction>> queue;
private final ConcurrentMap<String, Map<LockType, List<LockModeOwner>>> attempting;
private final ConcurrentMap<String, Map<LockType, Map<LockMode, Map<String, Integer>>>> acquired;
private final List<LockEventListener> listeners = new ArrayList<>();
QueueConsumer(final TransferQueue<Either<ListenerAction, LockAction>> queue,
final ConcurrentMap<String, Map<LockType, List<LockModeOwner>>> attempting,
final ConcurrentMap<String, Map<LockType, Map<LockMode, Map<String, Integer>>>> acquired) {
this.queue = queue;
this.attempting = attempting;
this.acquired = acquired;
}
@Override
public void run() {
while (true) {
try {
final Either<ListenerAction, LockAction> event = queue.take();
if(event.isLeft()) {
processListenerAction(event.left().get());
} else {
processLockAction(event.right().get());
}
} catch (final InterruptedException e) {
LOG.fatal("LockTable.QueueConsumer was interrupted");
}
}
}
private void processListenerAction(final ListenerAction listenerAction) {
if(listenerAction.action == ListenerAction.Action.Register) {
listeners.add(listenerAction.lockEventListener);
listenerAction.lockEventListener.registered();
} else if(listenerAction.action == ListenerAction.Action.Deregister) {
listeners.remove(listenerAction.lockEventListener);
listenerAction.lockEventListener.unregistered();
}
}
private void processLockAction(final LockAction lockAction) {
if (lockAction.action == Attempt) {
notifyListenersOfAttempt(lockAction);
addToAttempting(lockAction);
} else if (lockAction.action == AttemptFailed) {
removeFromAttempting(lockAction);
notifyListenersOfAttemptFailed(lockAction);
} else if (lockAction.action == Acquired) {
removeFromAttempting(lockAction);
incrementAcquired(lockAction);
} else if (lockAction.action == Released) {
decrementAcquired(lockAction);
}
}
private void notifyListenersOfAttempt(final LockAction lockAction) {
for(final LockEventListener listener : listeners) {
try {
listener.accept(lockAction);
} catch (final Exception e) {
LOG.error("Listener '{}' error: ", listener.getClass().getName(), e);
}
}
}
private void notifyListenersOfAttemptFailed(final LockAction lockAction) {
for(final LockEventListener listener : listeners) {
try {
listener.accept(lockAction);
} catch (final Exception e) {
LOG.error("Listener '{}' error: ", listener.getClass().getName(), e);
}
}
}
private void notifyListenersOfAcquire(final LockAction lockAction, final int newReferenceCount) {
final LockAction newLockAction = lockAction.withCount(newReferenceCount);
for(final LockEventListener listener : listeners) {
try {
listener.accept(newLockAction);
} catch (final Exception e) {
LOG.error("Listener '{}' error: ", listener.getClass().getName(), e);
}
}
}
private void notifyListenersOfRelease(final LockAction lockAction, final int newReferenceCount) {
final LockAction newLockAction = lockAction.withCount(newReferenceCount);
for(final LockEventListener listener : listeners) {
try {
listener.accept(newLockAction);
} catch (final Exception e) {
LOG.error("Listener '{}' error: ", listener.getClass().getName(), e);
}
}
}
private void addToAttempting(final LockAction lockAction) {
attempting.compute(lockAction.id, (id, attempts) -> {
if (attempts == null) {
attempts = new HashMap<>();
}
attempts.compute(lockAction.lockType, (lockType, v) -> {
if (v == null) {
v = new ArrayList<>();
}
v.add(new LockModeOwner(lockAction.mode, lockAction.threadName));
return v;
});
return attempts;
});
}
private void removeFromAttempting(final LockAction lockAction) {
attempting.compute(lockAction.id, (id, attempts) -> {
if (attempts == null) {
return null;
} else {
attempts.compute(lockAction.lockType, (lockType, v) -> {
if (v == null) {
return null;
}
v.removeIf(val -> val.getLockMode() == lockAction.mode && val.getOwnerThread().equals(lockAction.threadName));
if (v.isEmpty()) {
return null;
} else {
return v;
}
});
if (attempts.isEmpty()) {
return null;
} else {
return attempts;
}
}
});
}
private void incrementAcquired(final LockAction lockAction) {
acquired.compute(lockAction.id, (id, acqu) -> {
if (acqu == null) {
acqu = new HashMap<>();
}
acqu.compute(lockAction.lockType, (lockType, v) -> {
if (v == null) {
v = new HashMap<>();
}
v.compute(lockAction.mode, (mode, ownerHolds) -> {
if (ownerHolds == null) {
ownerHolds = new HashMap<>();
}
ownerHolds.compute(lockAction.threadName, (threadName, holdCount) -> {
if(holdCount == null) {
holdCount = 0;
}
return ++holdCount;
});
final int lockModeHolds = ownerHolds.values().stream().collect(Collectors.summingInt(Integer::intValue));
notifyListenersOfAcquire(lockAction, lockModeHolds);
return ownerHolds;
});
return v;
});
return acqu;
});
}
private void decrementAcquired(final LockAction lockAction) {
acquired.compute(lockAction.id, (id, acqu) -> {
if (acqu == null) {
LOG.error("No entry found when trying to decrementAcquired for: id={}" + lockAction.id);
return null;
}
acqu.compute(lockAction.lockType, (lockType, v) -> {
if (v == null) {
LOG.error("No entry found when trying to decrementAcquired for: id={}, lockType={}", lockAction.id, lockAction.lockType);
return null;
}
v.compute(lockAction.mode, (mode, ownerHolds) -> {
if (ownerHolds == null) {
LOG.error("No entry found when trying to decrementAcquired for: id={}, lockType={}, lockMode={}", lockAction.id, lockAction.lockType, lockAction.mode);
return null;
} else {
ownerHolds.compute(lockAction.threadName, (threadName, holdCount) -> {
if(holdCount == null) {
LOG.error("No entry found when trying to decrementAcquired for: id={}, lockType={}, lockMode={}, threadName={}", lockAction.id, lockAction.lockType, lockAction.mode, lockAction.threadName);
return null;
} else if(holdCount == 0) {
LOG.error("Negative release when trying to decrementAcquired for: id={}, lockType={}, lockMode={}, threadName={}", lockAction.id, lockAction.lockType, lockAction.mode, lockAction.threadName);
return null;
} else if(holdCount == 1) {
return null;
} else {
return --holdCount;
}
});
final int lockModeHolds = ownerHolds.values().stream().collect(Collectors.summingInt(Integer::intValue));
notifyListenersOfRelease(lockAction, lockModeHolds);
if (ownerHolds.isEmpty()) {
return null;
} else {
return ownerHolds;
}
}
});
if (v.isEmpty()) {
return null;
} else {
return v;
}
});
if (acqu.isEmpty()) {
return null;
} else {
return acqu;
}
});
}
}
public interface LockEventListener {
default void registered() {}
void accept(final LockAction lockAction);
default void unregistered() {}
}
private static class ListenerAction {
enum Action {
Register,
Deregister
}
private final Action action;
private final LockEventListener lockEventListener;
public ListenerAction(final Action action, final LockEventListener lockEventListener) {
this.action = action;
this.lockEventListener = lockEventListener;
}
@Override
public String toString() {
return action.name() + " " + lockEventListener.getClass().getName();
}
}
public static class LockAction {
public enum Action {
Attempt,
AttemptFailed,
Acquired,
Released
}
public final Action action;
public final long groupId;
public final String id;
public final LockType lockType;
public final LockMode mode;
public final String threadName;
public final int count;
/**
* System#nanoTime()
*/
public final long timestamp;
@Nullable public final StackTraceElement[] stackTrace;
LockAction(final Action action, final long groupId, final String id, final LockType lockType, final LockMode mode, final String threadName, final int count, final long timestamp, @Nullable final StackTraceElement[] stackTrace) {
this.action = action;
this.groupId = groupId;
this.id = id;
this.lockType = lockType;
this.mode = mode;
this.threadName = threadName;
this.count = count;
this.timestamp = timestamp;
this.stackTrace = stackTrace;
}
public LockAction withCount(final int count) {
return new LockAction(action, groupId, id, lockType, mode, threadName, count, timestamp, stackTrace);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder()
.append(action.toString())
.append(' ')
.append(lockType.name());
if(groupId > -1) {
builder
.append("#")
.append(groupId);
}
builder.append('(')
.append(mode.toString())
.append(") of ")
.append(id);
if(stackTrace != null) {
final String reason = getSimpleStackReason();
if(reason != null) {
builder
.append(" for #")
.append(reason);
}
}
builder
.append(" by ")
.append(threadName)
.append(" at ")
.append(timestamp);
if (action == Acquired || action == Released) {
builder
.append(". count=")
.append(Integer.toString(count));
}
return builder.toString();
}
private static final String NATIVE_BROKER_CLASS_NAME = NativeBroker.class.getName();
private static final String COLLECTION_STORE_CLASS_NAME = NativeBroker.class.getName();
private static final String TXN_CLASS_NAME = Txn.class.getName();
@Nullable
public String getSimpleStackReason() {
for (final StackTraceElement stackTraceElement : stackTrace) {
final String className = stackTraceElement.getClassName();
if (className.equals(NATIVE_BROKER_CLASS_NAME) || className.equals(COLLECTION_STORE_CLASS_NAME) || className.equals(TXN_CLASS_NAME)) {
if (!(stackTraceElement.getMethodName().endsWith("LockCollection") || stackTraceElement.getMethodName().equals("lockCollectionCache"))) {
return stackTraceElement.getMethodName() + '(' + stackTraceElement.getLineNumber() + ')';
}
}
}
return null;
}
}
/** debugging tools below **/
/**
* Holds a count of READ and WRITE locks by {@link LockAction#id}
*/
private final Map<String, Tuple2<Long, Long>> lockCounts = new HashMap<>();
/**
* Checks that there are not more releases that there are acquires
*/
private void sanityCheckLockLifecycles(final LockAction lockAction) {
synchronized(lockCounts) {
long read = 0;
long write = 0;
final Tuple2<Long, Long> lockCount = lockCounts.get(lockAction.id);
if(lockCount != null) {
read = lockCount._1;
write = lockCount._2;
}
if(lockAction.action == LockAction.Action.Acquired) {
if(lockAction.mode == LockMode.READ_LOCK) {
read++;
} else if(lockAction.mode == LockMode.WRITE_LOCK) {
write++;
}
} else if(lockAction.action == LockAction.Action.Released) {
if(lockAction.mode == LockMode.READ_LOCK) {
if(read == 0) {
LOG.error("Negative READ_LOCKs", new IllegalStateException());
}
read--;
} else if(lockAction.mode == LockMode.WRITE_LOCK) {
if(write == 0) {
LOG.error("Negative WRITE_LOCKs", new IllegalStateException());
}
write--;
}
}
if(LOG.isTraceEnabled()) {
LOG.trace("QUEUE: {} (read={} write={})", lockAction.toString(), read, write);
}
lockCounts.put(lockAction.id, new Tuple2<>(read, write));
}
}
}
| [bugfix] Don't prevent the Lock Table processor from being interrupted
| src/org/exist/storage/lock/LockTable.java | [bugfix] Don't prevent the Lock Table processor from being interrupted |
|
Java | lgpl-2.1 | b4aa8a67218e143c0635c5568ca2cad097304684 | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2005-06 Javlin Consulting <[email protected]>
*
* This library 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 library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.component;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.component.util.CommandBuilder;
import org.jetel.data.DataRecord;
import org.jetel.data.formatter.DelimitedDataFormatter;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.SynchronizeUtils;
import org.jetel.util.exec.DataConsumer;
import org.jetel.util.exec.LoggerDataConsumer;
import org.jetel.util.exec.ProcBox;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
/**
* <h3>Mysql data writer</h3>
*
* <!-- All records from input port 0 are loaded into mysql database. Connection to database is not through JDBC driver, this
* component uses the mysql utility for this purpose. Bad rows' description is sent to output port 0.-->
*
* <table border="1">
* <th>Component:</th>
* <tr>
* <td>
* <h4><i>Name:</i></h4>
* </td>
* <td>Mysql data writer</td>
* </tr>
* <tr>
* <td>
* <h4><i>Category:</i></h4>
* </td>
* <td></td>
* </tr>
* <tr>
* <td>
* <h4><i>Description:</i></h4>
* </td>
* <td>This component loads data to mysql database using the mysql utility. It is faster then DBOutputTable.
* Load formats data pages directly, while avoiding most of the overhead of individual row processing that inserts incur.<br>
* There is created mysql command (LOAD DATA INFILE) depending on input parameters. Data are read from given input file or
* from the input port and loaded to database.<br>
* Any generated commands/files can be optionally logged to help diagnose problems.<br>
* Before you use this component, make sure that mysql client is installed and configured on the machine where CloverETL runs and
* mysql command line tool available. </td>
* </tr>
* <tr>
* <td>
* <h4><i>Inputs:</i></h4>
* </td>
* <td>[0] - input records. It can be omitted - then <b>fileURL</b> has to be provided.</td>
* </tr>
* <tr><td><h4><i>Outputs:</i></h4></td>
* <td>[0] - optionally one output port defined/connected - info about rejected records.
* Output metadata contains three fields with row number (integer), column name (string) and error message (string).
* </td></tr>
*
* <h4><i>Comment:</i></h4>
* </td>
* <td></td>
* </tr>
* </table> <br>
* <table border="1">
* <th>XML attributes:</th>
* <tr>
* <td><b>type</b></td>
* <td>"MYSQL_DATA_WRITER"</td>
* </tr>
* <tr>
* <td><b>id</b></td>
* <td>component identification</td>
* </tr>
* <tr>
* <td><b>mysqlPath</b></td>
* <td>path to mysql utility</td>
* </tr>
* <tr>
* <td><b>database</b></td>
* <td>the name of the database to receive the data</td>
* </tr>
* <tr>
* <td><b>table</b></td>
* <td>table name, where data are loaded</td>
* </tr>
* <tr>
* <td><b>columnDelimiter</b><br>
* <i>optional</i></td>
* <td>delimiter used for each column in data (default = '\t')</br> Value of the delimiter mustn't be contained in data.</td>
* </tr>
* <tr>
* <td><b>fileURL</b><br>
* <i>optional</i></td>
* <td>Path to data file to be loaded.<br>
* Normally this file is a temporary storage for data to be passed to mysql utility.
* If <i>fileURL</i> is not specified, at Windows platform the file is created in Clover or OS temporary directory and deleted after load finishes.
* At Linux/Unix system named pipe is used instead of temporary file.
* If <i>fileURL</i> is specified, temporary file is created within given path and name and not deleted after being loaded. Next graph
* run overwrites it.<br>
* There is one more meaning of this parameter. If input port is not specified, this file is used only for reading by mysql
* utility and must already contain data in format expected by load. The file is neither deleted nor overwritten.</td>
* </tr>
* <tr>
* <td><b>commandURL</b><br>
* <i>optional</i></td>
* <td>Path to command file where LOAD DATA INFILE statement is stored.<br>
* If <i>commandURL</i> is not specified, the command file is created in Clover temporary directory and deleted after load finishes.<br>
* If <i>commandURL</i> is specified and this file doesn't exist, temporary command file is created within given path and name and not deleted after being loaded. Default command file is stored here.<br>
* If <i>commandURL</i> is specified and this file exist, this file is used instead of command file created by Clover.
* </td>
* </tr>
* <tr>
* <td><b>host</b><br>
* <i>optional</i></td>
* <td>Import data to the MySQL server on the given host. The default host is localhost.</td>
* </tr>
* <tr>
* <td><b>username</b><br>
* <i>optional</i></td>
* <td>The MySQL username to use when connecting to the server.</td>
* </tr>
* <tr>
* <td><b>password</b><br>
* <i>optional</i></td>
* <td>The password to use when connecting to the server.</td>
* </tr>
* <tr>
* <td>ignoreRows</td>
* <td>Ignore the first N lines of the data file.</td>
* </tr>
* <tr>
* <td><b>parameters</b><br>
* <i>optional</i></td>
* <td>All possible additional parameters which can be passed on to
* <a href="http://dev.mysql.com/doc/refman/5.1/en/mysql-command-options.html"> mysql utility</a> or to
* <a href="http://dev.mysql.com/doc/refman/5.1/en/load-data.html"> LOAD DATA INFILE statement</a>.<br>
* Parameters, in form <i>key=value</i>
* (or <i>key</i> - interpreted as <i>key=true</i>, if possible value are only "true" or "false") has to be separated by :;|
* {colon, semicolon, pipe}. If in parameter value occurs one of :;|, value has to be double quoted.<br>
* <b>Load parameters</b><br>
* <b><i>Parameters for mysql utility</i></b><br>
* <table>
* <tr>
* <td>skipAutoRehash</td>
* <td>Disable automatic rehashing. Disables table and column name completion. That causes mysql to start faster.<br>
* If <i>skipAutoRehash</i> attribute isn't defined, default value is true.</td>
* </tr>
* <tr>
* <td>characterSetsDir</td>
* <td>The directory where character sets are installed. See <a
* href="http://www.mysql.org/doc/refman/5.1/en/character-sets.html"> The Character Set Used for Data and Sorting</a>.</td>
* </tr>
* <tr>
* <td>compress</td>
* <td>Compress all information sent between the client and the server if both support compression.</td>
* </tr>
* <tr>
* <td>defaultCharacterSet</td>
* <td>Use <i>defaultCharacterSet</i> as the default character set. See <a
* href="http://www.mysql.org/doc/refman/5.1/en/character-sets.html"> The Character Set Used for Data and Sorting</a>.</td>
* </tr>
* <tr>
* <td>force</td>
* <td>Continue even if an SQL error occurs.</td>
* </tr>
* <tr>
* <td>noBeep</td>
* <td>Do not beep when errors occur.</td>
* </tr>
* <tr>
* <td>port</td>
* <td>The TCP/IP port number to use for the connection.</td>
* </tr>
* <tr>
* <td>protocol</td>
* <td>The connection protocol to use. One of {TCP|SOCKET|PIPE|MEMORY}.</td>
* </tr>
* <tr>
* <td>reconnect</td>
* <td>If the connection to the server is lost, automatically try to reconnect. A single reconnect attempt is made each time the connection is lost.</td>
* </tr>
* <tr>
* <td>secureAuth</td>
* <td>Do not send passwords to the server in old (pre-4.1.1) format. This prevents connections except for servers that use the newer password format.</td>
* </tr>
* <tr>
* <td>showWarnings</td>
* <td>Cause warnings to be shown after each statement if there are any.
* If <i>showWarnings</i> attribute isn't defined, default value is true.<br>
* If any output port is connected, this parameter must be used.</td>
* </tr>
* <tr>
* <td>silent</td>
* <td>Silent mode. Produce output only when errors occur.</td>
* </tr>
* <tr>
* <td>socket</td>
* <td>For connections to localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.</td>
* </tr>
* <tr>
* <td>ssl</td>
* <td>Options that begin with <i>ssl</i> attribute specify whether to connect to the server via SSL and indicate where to find
* SSL keys and certificates. See <a href="http://www.mysql.org/doc/refman/5.1/en/ssl-options.html"> SSL Command Options</a>.</td>
* </tr>
* </table>
* <b><i>Parameters for LOAD DATA INFILE statement</i></b><br>
* <table>
* <tr>
* <td>local</td>
* <td>Read input files locally from the client host.<br>
* If <i>local</i> attribute isn't defined, default value is true.</td>
* </tr>
* <tr>
* <td>lowPriority</td>
* <td>If you use <i>lowPriority</i>, execution of the LOAD DATA statement is delayed until no other clients are reading from the table.
* This affects only storage engines that use only table-level locking (MyISAM, MEMORY, MERGE).</td>
* </tr>
* <tr>
* <td>concurrent</td>
* <td>If you specify <i>concurrent</i> with a MyISAM table that satisfies the condition for concurrent inserts
* (that is, it contains no free blocks in the middle), other threads can retrieve data from the table while LOAD DATA is executing.
* Using this option affects the performance of LOAD DATA a bit, even if no other thread is using the table at the same time.</td>
* </tr>
* <tr>
* <td>ignore</td>
* <td>See the description for the <i>replace</i> attribute.</td>
* </tr>
* <tr>
* <td>replace</td>
* <td>The <i>replace</i> and <i>ignore</i> parameter control handling of input rows that duplicate existing rows on
* unique key values. If you specify <i>replace</i> parameter, input rows replace existing rows.
* In other words, rows that have the same value for a primary key or unique index as an existing row. See <a href="http://dev.mysql.com/doc/refman/5.1/en/replace.html">REPLACE Syntax</a>.<br>
* If you specify <i>ignore</i> parameter, input rows that duplicate an existing row on a unique key value are skipped.
* If you do not specify either option, the behavior depends on whether the <i>local</i> parameter is specified.
* Without <i>local</i>, an error occurs when a duplicate key value is found, and the rest of the text file is ignored.
* With <i>local</i>, the default behavior is the same as if <i>ignore</i> is specified;
* this is because the server has no way to stop transmission of the file in the middle of the operation.</td>
* </tr>
* <tr>
* <td>fieldsEnclosedBy</td>
* <td>It is used for enclosing each filed in data by char. <br>
* When data is read from input port this attribute is ignored.</td>
* </tr>
* <tr>
* <td>fieldsIsOptionallyEnclosed</td>
* <td>It decide if <i>fieldsEnclosedBy</i> is used for each columns or not. <br>
* It can be used only with <i>fieldsEnclosedBy</i> attribute. <br>
* When data is read from input port this attribute is ignored.</td>
* </tr>
* <tr>
* <td>fieldsEscapedBy</td>
* <td>It is used form escaping fields by char. <br>
* When data is read from input port this attribute is ignored.</td>
* </tr>
* <tr>
* <td>linesStartingBy</td>
* <td>If all the lines you want to read in have a common prefix that you want to ignore,
* you can use <i>linesStartingBy</i> to skip over the prefix, and anything before it.
* If a line does not include the prefix, the entire line is skipped.</td>
* </tr>
* <tr>
* <td>recordDelimiter</td>
* <td>Specifies the record delimiter. (default = '\n' (newline character)).</td>
* </tr>
* <tr>
* <td>columns</td>
* <td>This option takes a comma-separated list of column names as its value. The order of the column names indicates how to
* match data file columns with table columns.<br>
* </td>
* </tr>
* </table></td>
* </tr>
* </table>
*
* <h4>Example:</h4>
* Reading data from input port:
*
* <pre>
* <Node
* mysqlPath="mysql"
* database="testdb"
* table="test"
* id="MYSQL_DATA_WRITER1"
* type="MYSQL_DATA_WRITER"
* />
* </pre>
*
* Reading data from flat file:
*
* <pre>
* <Node
* mysqlPath="mysql"
* database="testdb"
* table="test"
* columnDelimiter=","
* fileURL="${WORKSPACE}/data/delimited/mysqlFlat.dat"
* parameters="fieldsEnclosedBy=*|fieldsIsOptionallyEnclosed"
* id="MYSQL_DATA_WRITER0"
* type="MYSQL_DATA_WRITER"/>
* />
*
* @author Miroslav Haupt ([email protected])
* (c) Javlin Consulting (www.javlinconsulting.cz)
* @see org.jetel.graph.TransformationGraph
* @see org.jetel.graph.Node
* @see org.jetel.graph.Edge
* @since 24.9.2007
*
*/
public class MysqlDataWriter extends BulkLoader {
private static Log logger = LogFactory.getLog(MysqlDataWriter.class);
/** Description of the Field */
private static final String XML_MYSQL_PATH_ATTRIBUTE = "mysqlPath";
private static final String XML_HOST_ATTRIBUTE = "host";
private static final String XML_COMMAND_URL_ATTRIBUTE = "commandURL";
private static final String XML_IGNORE_ROWS_ATTRIBUTE = "ignoreRows";
// params for mysql client
private static final String MYSQL_SKIP_AUTO_REHASH_PARAM = "skipAutoRehash";
private static final String MYSQL_CHARACTER_SETS_DIR_PARAM = "characterSetsDir";
private static final String MYSQL_COMPRESS_PARAM = "compress";
private static final String MYSQL_DEFAULT_CHARACTER_SET_PARAM = "defaultCharacterSet";
private static final String MYSQL_FORCE_PARAM = "force";
private static final String MYSQL_NO_BEEP_PARAM = "noBeep";
private static final String MYSQL_PORT_PARAM = "port";
private static final String MYSQL_PROTOCOL_PARAM = "protocol";
private static final String MYSQL_RECONNECT_PARAM = "reconnect";
private static final String MYSQL_SECURE_AUTH_PARAM = "secureAuth";
private static final String MYSQL_SHOW_WARNINGS_PARAM = "showWarnings";
private static final String MYSQL_SILENT_PARAM = "silent";
private static final String MYSQL_SOCKET_PARAM = "socket";
private static final String MYSQL_SSL_PARAM = "ssl";
// params for LOAD DATA INFILE statement
private static final String LOAD_LOCAL_PARAM = "local";
private static final String LOAD_LOW_PRIORITY_PARAM = "lowPriority";
private static final String LOAD_CONCURRENT_PARAM = "concurrent";
private static final String LOAD_REPLACE_PARAM = "replace";
private static final String LOAD_IGNORE_PARAM = "ignore";
private static final String LOAD_FIELDS_ENCLOSED_BY_PARAM = "fieldsEnclosedBy";
private static final String LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM = "fieldsIsOptionallyEnclosed";
private static final String LOAD_FIELDS_ESCAPED_BY_PARAM = "fieldsEscapedBy";
private static final String LOAD_LINES_STARTING_BY_PARAM = "linesStartingBy";
private static final String LOAD_RECORD_DELIMITER_PARAM = "recordDelimiter";
private static final String LOAD_COLUMNS_PARAM = "columns";
// switches for mysql client,these switches have own xml attributes
private static final String MYSQL_DATABASE_SWITCH = "database";
private static final String MYSQL_HOST_SWITCH = "host";
private static final String MYSQL_USER_SWITCH = "user";
private static final String MYSQL_PASSWORD_SWITCH = "password";
// switches for mysql client
private static final String MYSQL_SKIP_AUTO_REHASH_SWITCH = "skip-auto-rehash";
private static final String MYSQL_CHARACTER_SETS_DIR_SWITCH = "character-sets-dir";
private static final String MYSQL_COMPRESS_SWITCH = "compress";
private static final String MYSQL_DEFAULT_CHARACTER_SET_SWITCH = "default-character-set";
private static final String MYSQL_EXECUTE_SWITCH = "execute";
private static final String MYSQL_FORCE_SWITCH = "force";
private static final String MYSQL_LOCAL_INFILE_SWITCH = "local-infile";
private static final String MYSQL_NO_BEEP_SWITCH = "no-beep";
private static final String MYSQL_PORT_SWITCH = "port";
private static final String MYSQL_PROTOCOL_SWITCH = "protocol";
private static final String MYSQL_RECONNECT_SWITCH = "reconnect";
private static final String MYSQL_SECURE_AUTH_SWITCH = "secure-auth";
private static final String MYSQL_SHOW_WARNINGS_SWITCH = "show-warnings";
private static final String MYSQL_SILENT_SWITCH = "silent";
private static final String MYSQL_SOCKET_SWITCH = "socket";
private static final String MYSQL_SSL_SWITCH = "ssl*";
// keywords for LOAD DATA INFILE statement
private static final String LOAD_LOCAL_KEYWORD = "LOCAL";
private static final String LOAD_LOW_PRIORITY_KEYWORD = "LOW_PRIORITY";
private static final String LOAD_CONCURRENT_KEYWORD = "CONCURRENT";
private static final String LOAD_REPLACE_KEYWORD = "REPLACE";
private static final String LOAD_IGNORE_KEYWORD = "IGNORE";
private static final String LOAD_FIELDS_ENCLOSED_BY_KEYWORD = "ENCLOSED BY";
private static final String LOAD_FIELDS_OPTIONALLY_ENCLOSED_KEYWORD = "OPTIONALLY";
private static final String LOAD_FIELDS_ESCAPED_BY_KEYWORD = "ESCAPED BY";
private static final String LOAD_LINES_STARTING_BY_KEYWORD = "STARTING BY";
private static final String LOAD_RECORD_DELIMITER_KEYWORD = "TERMINATED BY";
public final static String COMPONENT_TYPE = "MYSQL_DATA_WRITER";
private final static String LINE_SEPARATOR = System.getProperty("line.separator");
private final static String SWITCH_MARK = "--";
private final static String EXCHANGE_FILE_PREFIX = "mysqlExchange";
private final static String MYSQL_FILE_NAME_PREFIX = "mysql";
private final static String DEFAULT_COLUMN_DELIMITER = "\t";
private final static String DEFAULT_RECORD_DELIMITER = "\n";
private final static String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
private final static String DEFAULT_TIME_FORMAT = "HH:mm:ss";
private final static String DEFAULT_YEAR_FORMAT = "yyyy";
// variables for dbload's command
private int ignoreRows = UNUSED_INT;
private String commandURL;
private File commandFile;
/**
* flag that determine if execute() method was already executed;
* used for deleting temp data file and reporting about it
*/
private boolean alreadyExecuted = false;
private boolean isDataReadDirectlyFromFile;
/**
* Constructor for the MysqlDataWriter object
*
* @param id Description of the Parameter
*/
public MysqlDataWriter(String id, String mysqlPath, String database, String table) {
super(id, mysqlPath, database);
this.table = table;
columnDelimiter = DEFAULT_COLUMN_DELIMITER;
}
/**
* Main processing method for the MysqlDataWriter object
*
* @since April 4, 2002
*/
public Result execute() throws Exception {
alreadyExecuted = true;
ProcBox box;
int processExitValue = 0;
if (isDataReadFromPort) {
if (ProcBox.isWindowsPlatform() || dataURL != null) {
// dataFile is used for exchange data
readFromPortAndWriteByFormatter();
box = createProcBox();
processExitValue = box.join();
} else { // data is send to process through named pipe
processExitValue = runWithPipe();
}
} else {
processExitValue = readDataDirectlyFromFile();
}
if (processExitValue != 0) {
throw new JetelException("Mysql utility has failed.");
}
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
/**
* Create command line for process, where mysql utility is running.
* Example: mysql --skip-auto-rehash --database=testdb
* --execute=source /tmp/mysql47459.ctl --local-infile --show-warnings
*
* @return array first field is name of mysql utility and the others fields are parameters
* @throws ComponentNotReadyException when command file isn't created
*/
private String[] createCommandLineForDbLoader() throws ComponentNotReadyException {
if (ProcBox.isWindowsPlatform()) {
loadUtilityPath = StringUtils.backslashToSlash(loadUtilityPath);
}
CommandBuilder cmdBuilder = new CommandBuilder(properties, SWITCH_MARK);
cmdBuilder.add(loadUtilityPath);
cmdBuilder.addBooleanParam(MYSQL_SKIP_AUTO_REHASH_PARAM, MYSQL_SKIP_AUTO_REHASH_SWITCH, true);
cmdBuilder.addAttribute(MYSQL_HOST_SWITCH, host);
cmdBuilder.addAttribute(MYSQL_USER_SWITCH, user);
cmdBuilder.addAttribute(MYSQL_PASSWORD_SWITCH, password);
cmdBuilder.addAttribute(MYSQL_DATABASE_SWITCH, database);
cmdBuilder.addParam(MYSQL_CHARACTER_SETS_DIR_PARAM, MYSQL_CHARACTER_SETS_DIR_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_COMPRESS_PARAM, MYSQL_COMPRESS_SWITCH);
cmdBuilder.addParam(MYSQL_DEFAULT_CHARACTER_SET_PARAM, MYSQL_DEFAULT_CHARACTER_SET_SWITCH);
String commandFileName = createCommandFile();
if (ProcBox.isWindowsPlatform()) {
commandFileName = StringUtils.backslashToSlash(commandFileName);
}
cmdBuilder.addAttribute(MYSQL_EXECUTE_SWITCH, "source " + commandFileName);
cmdBuilder.addBooleanParam(MYSQL_FORCE_PARAM, MYSQL_FORCE_SWITCH);
cmdBuilder.addBooleanParam("", MYSQL_LOCAL_INFILE_SWITCH, true);
cmdBuilder.addBooleanParam(MYSQL_NO_BEEP_PARAM, MYSQL_NO_BEEP_SWITCH);
cmdBuilder.addParam(MYSQL_PORT_PARAM, MYSQL_PORT_SWITCH);
cmdBuilder.addParam(MYSQL_PROTOCOL_PARAM, MYSQL_PROTOCOL_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_RECONNECT_PARAM, MYSQL_RECONNECT_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_SECURE_AUTH_PARAM, MYSQL_SECURE_AUTH_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_SHOW_WARNINGS_PARAM, MYSQL_SHOW_WARNINGS_SWITCH, true);
cmdBuilder.addBooleanParam(MYSQL_SILENT_PARAM, MYSQL_SILENT_SWITCH);
cmdBuilder.addParam(MYSQL_SOCKET_PARAM, MYSQL_SOCKET_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_SSL_PARAM, MYSQL_SSL_SWITCH);
return cmdBuilder.getCommand();
}
/**
* Create file that contains LOAD DATA INFILE command and return its name.
*
* @return name of the command file
* @throws ComponentNotReadyException when command file isn't created
*/
String createCommandFile() throws ComponentNotReadyException {
try {
if (commandURL != null) {
commandFile = getFile(commandURL);
if (commandFile.exists()) {
return commandFile.getCanonicalPath();
} else {
commandFile.createNewFile();
}
} else {
commandFile = File.createTempFile(MYSQL_FILE_NAME_PREFIX,
CONTROL_FILE_NAME_SUFFIX, getTempDir());
}
saveCommandFile(commandFile);
return commandFile.getCanonicalPath();
} catch (IOException ioe) {
throw new ComponentNotReadyException(this,
"Can't create command file for mysql utility.", ioe);
}
}
/**
* Save default LOAD DATA INFILE command to the file.
*
* @throws IOException when error occured
*/
private void saveCommandFile(File commandFile) throws IOException {
FileWriter commandWriter = new FileWriter(commandFile);
String command = getDefaultCommandFileContent();
logger.debug("Command file content: " + command);
commandWriter.write(command);
commandWriter.close();
}
/**
* Create and return string that contains LOAD DATA INFILE command.
* @return string that contains LOAD DATA INFILE command
* @throws IOException
*/
private String getDefaultCommandFileContent() throws IOException {
// LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
CommandBuilder cmdBuilder = new CommandBuilder(properties, SPACE_CHAR);
cmdBuilder.add("LOAD DATA");
cmdBuilder.addBooleanParam(LOAD_LOW_PRIORITY_PARAM, LOAD_LOW_PRIORITY_KEYWORD);
cmdBuilder.addBooleanParam(LOAD_CONCURRENT_PARAM, LOAD_CONCURRENT_KEYWORD);
cmdBuilder.addBooleanParam(LOAD_LOCAL_PARAM, LOAD_LOCAL_KEYWORD, true);
cmdBuilder.add("INFILE " + StringUtils.quote(getDataFilePath()) + LINE_SEPARATOR);
// [REPLACE | IGNORE]
if (cmdBuilder.addBooleanParam(LOAD_REPLACE_PARAM, LOAD_REPLACE_KEYWORD)
|| cmdBuilder.addBooleanParam(LOAD_IGNORE_PARAM, LOAD_IGNORE_KEYWORD)) {
cmdBuilder.add(LINE_SEPARATOR);
}
// INTO TABLE tbl_name
cmdBuilder.add("INTO TABLE " + table + LINE_SEPARATOR);
// [FIELDS
// [TERMINATED BY 'string']
// [[OPTIONALLY] ENCLOSED BY 'char']
// [ESCAPED BY 'char']
// ]
if (!columnDelimiter.equals(DEFAULT_COLUMN_DELIMITER) ||
properties.containsKey(LOAD_FIELDS_ENCLOSED_BY_PARAM) ||
properties.containsKey(LOAD_FIELDS_ESCAPED_BY_PARAM)) {
cmdBuilder.add("FIELDS" + LINE_SEPARATOR);
cmdBuilder.add("TERMINATED BY " + StringUtils.quote(columnDelimiter) + LINE_SEPARATOR);
cmdBuilder.addBooleanParam(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM,
LOAD_FIELDS_OPTIONALLY_ENCLOSED_KEYWORD);
if (cmdBuilder.addParam(LOAD_FIELDS_ENCLOSED_BY_PARAM, LOAD_FIELDS_ENCLOSED_BY_KEYWORD, true)) {
cmdBuilder.add(LINE_SEPARATOR);
}
if (cmdBuilder.addParam(LOAD_FIELDS_ESCAPED_BY_PARAM, LOAD_FIELDS_ESCAPED_BY_KEYWORD, true)) {
cmdBuilder.add(LINE_SEPARATOR);
}
}
// [LINES
// [STARTING BY 'string']
// [TERMINATED BY 'string']
// ]
if (properties.containsKey(LOAD_LINES_STARTING_BY_PARAM) ||
properties.containsKey(LOAD_RECORD_DELIMITER_PARAM)) {
cmdBuilder.add("LINES" + LINE_SEPARATOR);
if (cmdBuilder.addParam(LOAD_LINES_STARTING_BY_PARAM, LOAD_LINES_STARTING_BY_KEYWORD, true)) {
cmdBuilder.add(LINE_SEPARATOR);
}
if (cmdBuilder.addParam(LOAD_RECORD_DELIMITER_PARAM, LOAD_RECORD_DELIMITER_KEYWORD, true)) {
cmdBuilder.add(LINE_SEPARATOR);
}
}
// [IGNORE number LINES]
if (ignoreRows != UNUSED_INT) {
cmdBuilder.add("IGNORE " + ignoreRows + " LINES" + LINE_SEPARATOR);
}
// [(col_name_or_user_var,...)]
if (properties.containsKey(LOAD_COLUMNS_PARAM)) {
cmdBuilder.add("'" + properties.getProperty(LOAD_COLUMNS_PARAM) + "'");
}
return cmdBuilder.getCommandAsString();
}
private String getDataFilePath() throws IOException {
if (ProcBox.isWindowsPlatform()) {
// convert "C:\examples\xxx.dat" to "C:/examples/xxx.dat"
return StringUtils.backslashToSlash(dataFile.getCanonicalPath());
}
return dataFile.getCanonicalPath();
}
/**
* Description of the Method
*
* @exception ComponentNotReadyException Description of the Exception
* @since April 4, 2002
*/
public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
isDataReadDirectlyFromFile = !isDataReadFromPort &&
!StringUtils.isEmpty(dataURL);
checkParams();
// data is read directly from file -> file isn't used for exchange
if (isDataReadDirectlyFromFile) {
dataFile = openFile(dataURL);
} else {
createFileForExchange();
}
commandLine = createCommandLineForDbLoader();
printCommandLineToLog(commandLine, logger);
if (isDataReadFromPort) {
dbMetadata = createLoadUtilityMetadata(columnDelimiter, getRecordDelimiter());
// init of data formatter
formatter = new DelimitedDataFormatter(CHARSET_NAME);
formatter.init(dbMetadata);
}
errConsumer = new LoggerDataConsumer(LoggerDataConsumer.LVL_ERROR, 0);
if (isDataWrittenToPort) {
try {
// create data consumer and check metadata
consumer = new MysqlPortDataConsumer(getOutputPort(WRITE_TO_PORT));
} catch (ComponentNotReadyException cnre) {
free();
throw new ComponentNotReadyException(this, "Error during initialization of MysqlPortDataConsumer.", cnre);
}
} else {
consumer = new LoggerDataConsumer(LoggerDataConsumer.LVL_DEBUG, 0);
}
}
private void createFileForExchange() throws ComponentNotReadyException {
if (ProcBox.isWindowsPlatform() || dataURL != null) {
if (dataURL != null) {
dataFile = getFile(dataURL);
dataFile.delete();
} else {
dataFile = createTempFile(EXCHANGE_FILE_PREFIX);
}
} else {
dataFile = createTempFile(EXCHANGE_FILE_PREFIX);
}
}
/**
* Checks if mandatory attributes are defined.
* And check combination of some parameters.
*
* @throws ComponentNotReadyException if any of conditions isn't fulfilled
*/
private void checkParams() throws ComponentNotReadyException {
if (StringUtils.isEmpty(loadUtilityPath)) {
throw new ComponentNotReadyException(this, StringUtils.quote(XML_MYSQL_PATH_ATTRIBUTE)
+ " attribute have to be set.");
}
if (StringUtils.isEmpty(database)) {
throw new ComponentNotReadyException(this,
StringUtils.quote(XML_DATABASE_ATTRIBUTE) + " attribute have to be set.");
}
if (StringUtils.isEmpty(table) && !fileExists(commandURL)) {
throw new ComponentNotReadyException(this,
StringUtils.quote(XML_TABLE_ATTRIBUTE) + " attribute has to be specified or " +
StringUtils.quote(XML_COMMAND_URL_ATTRIBUTE) +
" attribute has to be specified and file at the URL must exists.");
}
if (!isDataReadFromPort && !fileExists(dataURL) && !fileExists(commandURL)) {
throw new ComponentNotReadyException(this, "Input port or " +
StringUtils.quote(XML_FILE_URL_ATTRIBUTE) +
" attribute or " + StringUtils.quote(XML_COMMAND_URL_ATTRIBUTE) +
" attribute have to be specified and specified file must exist.");
}
if (ignoreRows != UNUSED_INT && ignoreRows < 0) {
throw new ComponentNotReadyException(this,
XML_IGNORE_ROWS_ATTRIBUTE + " mustn't be less than 0.");
}
// check combination
if (properties.containsKey(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM)
&& !properties.containsKey(LOAD_FIELDS_ENCLOSED_BY_PARAM)) {
logger.warn("Attribute " + StringUtils.quote(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM)
+ " is ignored because it has to be used in combination with "
+ StringUtils.quote(LOAD_FIELDS_ENCLOSED_BY_PARAM) + " attribute.");
}
// if any output port is connected, MYSQL_SHOW_WARNINGS_SWITCH parameter must be used
// MYSQL_SHOW_WARNINGS_SWITCH is used when MYSQL_SHOW_WARNINGS_PARAM isn't defined
// or when MYSQL_SHOW_WARNINGS_PARAM=true
if (isDataWrittenToPort) {
if (properties.containsKey(MYSQL_SHOW_WARNINGS_PARAM) &&
"false".equalsIgnoreCase(properties.getProperty(MYSQL_SHOW_WARNINGS_PARAM))) {
properties.setProperty(MYSQL_SHOW_WARNINGS_PARAM, "true");
logger.warn("If any output port is connected, " +
StringUtils.quote(MYSQL_SHOW_WARNINGS_PARAM) +
" parameter mustn't equals false. " +
StringUtils.quote(MYSQL_SHOW_WARNINGS_PARAM) + " parameters was set to true.");
}
}
// report on ignoring some attributes
if (isDataReadFromPort) {
if (properties.containsKey(LOAD_FIELDS_ENCLOSED_BY_PARAM)) {
logger.warn("Attribute " + StringUtils.quote(LOAD_FIELDS_ENCLOSED_BY_PARAM)
+ " is ignored because it is used only when data is read directly from file.");
}
if (properties.containsKey(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM)) {
logger.warn("Attribute " + StringUtils.quote(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM)
+ " is ignored because it is used only when data is read directly from file.");
}
if (properties.containsKey(LOAD_FIELDS_ESCAPED_BY_PARAM)) {
logger.warn("Attribute " + StringUtils.quote(LOAD_FIELDS_ESCAPED_BY_PARAM)
+ " is ignored because it is used only when data is read directly from file.");
}
}
}
@Override
protected void setLoadUtilityDateFormat(DataFieldMetadata field) {
setLoadUtilityDateFormat(field, DEFAULT_TIME_FORMAT, DEFAULT_DATE_FORMAT,
DEFAULT_DATETIME_FORMAT, DEFAULT_YEAR_FORMAT);
}
private String getRecordDelimiter() {
if (properties.containsKey(LOAD_RECORD_DELIMITER_PARAM)) {
return (String) properties.get(LOAD_RECORD_DELIMITER_PARAM);
} else {
return DEFAULT_RECORD_DELIMITER;
}
}
@Override
public synchronized void free() {
if(!isInitialized()) return;
super.free();
deleteDataFile();
deleteTempFile(commandFile, commandURL, logger);
alreadyExecuted = false;
}
/**
* Deletes data file which was used for exchange data.
*/
private void deleteDataFile() {
if (dataFile == null) {
return;
}
if (!alreadyExecuted) {
return;
}
if (isDataReadFromPort && dataURL == null && !dataFile.delete()) {
logger.warn("Temp data file was not deleted.");
}
}
/**
* Description of the Method
*
* @param nodeXML
* Description of Parameter
* @return Description of the Returned Value
* @since May 21, 2002
*/
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
try {
MysqlDataWriter mysqlDataWriter = new MysqlDataWriter(
xattribs.getString(XML_ID_ATTRIBUTE),
xattribs.getString(XML_MYSQL_PATH_ATTRIBUTE),
xattribs.getString(XML_DATABASE_ATTRIBUTE),
xattribs.getString(XML_TABLE_ATTRIBUTE));
if (xattribs.exists(XML_FILE_URL_ATTRIBUTE)) {
mysqlDataWriter.setFileUrl(xattribs.getString(XML_FILE_URL_ATTRIBUTE));
}
if (xattribs.exists(XML_COLUMN_DELIMITER_ATTRIBUTE)) {
mysqlDataWriter.setColumnDelimiter(xattribs.getString(XML_COLUMN_DELIMITER_ATTRIBUTE));
}
if (xattribs.exists(XML_HOST_ATTRIBUTE)) {
mysqlDataWriter.setHost(xattribs.getString(XML_HOST_ATTRIBUTE));
}
if (xattribs.exists(XML_USER_ATTRIBUTE)) {
mysqlDataWriter.setUser(xattribs.getString(XML_USER_ATTRIBUTE));
}
if (xattribs.exists(XML_PASSWORD_ATTRIBUTE)) {
mysqlDataWriter.setPassword(xattribs.getString(XML_PASSWORD_ATTRIBUTE));
}
if (xattribs.exists(XML_COMMAND_URL_ATTRIBUTE)) {
mysqlDataWriter.setCommandURL((xattribs.getString(XML_COMMAND_URL_ATTRIBUTE)));
}
if (xattribs.exists(XML_IGNORE_ROWS_ATTRIBUTE)) {
mysqlDataWriter.setIgnoreRows(xattribs.getInteger(XML_IGNORE_ROWS_ATTRIBUTE));
}
if (xattribs.exists(XML_PARAMETERS_ATTRIBUTE)) {
mysqlDataWriter.setParameters(xattribs.getString(XML_PARAMETERS_ATTRIBUTE));
}
return mysqlDataWriter;
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" +
xattribs.getString(XML_ID_ATTRIBUTE, " unknown ID ") +
":" + ex.getMessage(), ex);
}
}
@Override
public void toXML(Element xmlElement) {
super.toXML(xmlElement);
xmlElement.setAttribute(XML_MYSQL_PATH_ATTRIBUTE, loadUtilityPath);
if (!DEFAULT_COLUMN_DELIMITER.equals(columnDelimiter)) {
xmlElement.setAttribute(XML_COLUMN_DELIMITER_ATTRIBUTE, columnDelimiter);
}
if (!StringUtils.isEmpty(host)) {
xmlElement.setAttribute(XML_HOST_ATTRIBUTE, host);
}
if (!StringUtils.isEmpty(commandURL)) {
xmlElement.setAttribute(XML_COMMAND_URL_ATTRIBUTE, commandURL);
}
if (ignoreRows != UNUSED_INT) {
xmlElement.setAttribute(XML_IGNORE_ROWS_ATTRIBUTE, String.valueOf(ignoreRows));
}
}
/** Description of the Method */
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if(!checkInputPorts(status, 0, 1)
|| !checkOutputPorts(status, 0, 1)) {
return status;
}
try {
init();
} catch (ComponentNotReadyException e) {
ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(),
ConfigurationStatus.Severity.ERROR, this,ConfigurationStatus.Priority.NORMAL);
if (!StringUtils.isEmpty(e.getAttributeName())) {
problem.setAttributeName(e.getAttributeName());
}
status.add(problem);
} finally {
free();
}
return status;
}
public String getType() {
return COMPONENT_TYPE;
}
private void setIgnoreRows(int ignoreRows) {
this.ignoreRows = ignoreRows;
}
public void setCommandURL(String commandURL) {
this.commandURL = commandURL;
}
/**
* Class for reading and parsing data from input stream, which is supposed
* to be connected to process' output, and sends them to specified output port.
*
* @see org.jetel.util.exec.ProcBox
* @see org.jetel.util.exec.DataConsumer
* @author Miroslav Haupt ([email protected])
* (c) Javlin Consulting (www.javlinconsulting.cz)
* @since 17.10.2007
*/
private class MysqlPortDataConsumer implements DataConsumer {
private BufferedReader reader; // read from input stream (=output stream of mysql process)
private DataRecord errRecord = null;
private OutputPort errPort = null;
private DataRecordMetadata errMetadata; // format as output port
private Log logger = LogFactory.getLog(MysqlPortDataConsumer.class);
private final static int ROW_NUMBER_FIELD_NO = 0;
private final static int COLUMN_NAME_FIELD_NO = 1;
private final static int ERR_MSG_FIELD_NO = 2;
private final static int NUMBER_OF_FIELDS = 3;
private String strBadRowPattern = "(.+) for column '(\\w+)' at row (\\d+)";
private Matcher badRowMatcher;
/**
* @param port Output port receiving consumed data.
* @throws ComponentNotReadyException
*/
public MysqlPortDataConsumer(OutputPort errPort) throws ComponentNotReadyException {
if (errPort == null) {
throw new ComponentNotReadyException("Output port wasn't found.");
}
this.errPort = errPort;
errMetadata = errPort.getMetadata();
if (errMetadata == null) {
throw new ComponentNotReadyException("Output port hasn't assigned metadata.");
}
checkErrPortMetadata();
errRecord = new DataRecord(errMetadata);
errRecord.init();
Pattern badRowPattern = Pattern.compile(strBadRowPattern);
badRowMatcher = badRowPattern.matcher("");
}
/**
* @see org.jetel.util.exec.DataConsumer
*/
public void setInput(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
/**
* Example of bad rows in stream:
* Warning (Code 1264): Out of range value adjusted for column 'datetimeT' at row 1
* Warning (Code 1366): Incorrect integer value: 's' for column 'smallT' at row 2
* Note (Code 1265): Data truncated for column 'decT' at row 3
*
* @see org.jetel.util.exec.DataConsumer
*/
public boolean consume() throws JetelException {
try {
String line;
if ((line = readLine()) == null) {
return false;
}
badRowMatcher.reset(line);
if (badRowMatcher.find()) {
int rowNumber = Integer.valueOf(badRowMatcher.group(3));
String columnName = badRowMatcher.group(2);
String errMsg = badRowMatcher.group(1);
setErrRecord(errRecord, rowNumber, columnName, errMsg);
errPort.writeRecord(errRecord);
}
} catch (Exception e) {
close();
throw new JetelException("Error while writing output record", e);
}
SynchronizeUtils.cloverYield();
return true;
}
/**
* Read line by reader and write it by logger and return it.
*
* @return read line
* @throws IOException
*/
private String readLine() throws IOException {
String line = reader.readLine();
if (!StringUtils.isEmpty(line)) {
logger.debug(line);
}
return line;
}
/**
* Set value in errRecord.
*
* @param errRecord destination record
* @param rowNumber number of bad row
* @param columnName column's name of bad row
* @param errMsg error message
* @return destination record
*/
private DataRecord setErrRecord(DataRecord errRecord, int rowNumber, String columnName, String errMsg) {
errRecord.reset();
errRecord.getField(ROW_NUMBER_FIELD_NO).setValue(rowNumber);
errRecord.getField(COLUMN_NAME_FIELD_NO).setValue(columnName);
errRecord.getField(ERR_MSG_FIELD_NO).setValue(errMsg);
return errRecord;
}
/**
* check metadata at error port if metadata isn't correct then throws ComponentNotReadyException
*
* @throws ComponentNotReadyException when metadata isn't correct
*/
private void checkErrPortMetadata() throws ComponentNotReadyException {
// check number of fields
if (errMetadata.getNumFields() != NUMBER_OF_FIELDS) {
throw new ComponentNotReadyException("Number of fields of " +
StringUtils.quote(errMetadata.getName()) +
" isn't equal " + NUMBER_OF_FIELDS + ".");
}
// check if first field of errMetadata is integer - rowNumber
if (errMetadata.getFieldType(ROW_NUMBER_FIELD_NO) != DataFieldMetadata.INTEGER_FIELD) {
throw new ComponentNotReadyException("First field of " + StringUtils.quote(errMetadata.getName()) +
" has different type from integer.");
}
// check if second field of errMetadata is string - columnName
if (errMetadata.getFieldType(COLUMN_NAME_FIELD_NO) != DataFieldMetadata.STRING_FIELD) {
throw new ComponentNotReadyException("Second field of " + StringUtils.quote(errMetadata.getName()) +
" has different type from string.");
}
// check if third field of errMetadata is string - errMsg
if (errMetadata.getFieldType(ERR_MSG_FIELD_NO) != DataFieldMetadata.STRING_FIELD) {
throw new ComponentNotReadyException("Third field of " + StringUtils.quote(errMetadata.getName()) +
" has different type from string.");
}
}
/**
* @see org.jetel.util.exec.DataConsumer
*/
public void close() {
try {
if (reader != null) {
reader.close();
}
} catch (IOException ioe) {
logger.warn("Reader wasn't closed.", ioe);
}
try {
if (errPort != null) {
errPort.eof();
}
} catch (Exception ie) {
logger.warn("Out port wasn't closed.", ie);
}
}
}
} | cloveretl.bulkloader/src/org/jetel/component/MysqlDataWriter.java | /*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2005-06 Javlin Consulting <[email protected]>
*
* This library 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 library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.component;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.component.util.CommandBuilder;
import org.jetel.data.DataRecord;
import org.jetel.data.formatter.DelimitedDataFormatter;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.SynchronizeUtils;
import org.jetel.util.exec.DataConsumer;
import org.jetel.util.exec.LoggerDataConsumer;
import org.jetel.util.exec.ProcBox;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
/**
* <h3>Mysql data writer</h3>
*
* <!-- All records from input port 0 are loaded into mysql database. Connection to database is not through JDBC driver, this
* component uses the mysql utility for this purpose. Bad rows' description is sent to output port 0.-->
*
* <table border="1">
* <th>Component:</th>
* <tr>
* <td>
* <h4><i>Name:</i></h4>
* </td>
* <td>Mysql data writer</td>
* </tr>
* <tr>
* <td>
* <h4><i>Category:</i></h4>
* </td>
* <td></td>
* </tr>
* <tr>
* <td>
* <h4><i>Description:</i></h4>
* </td>
* <td>This component loads data to mysql database using the mysql utility. It is faster then DBOutputTable.
* Load formats data pages directly, while avoiding most of the overhead of individual row processing that inserts incur.<br>
* There is created mysql command (LOAD DATA INFILE) depending on input parameters. Data are read from given input file or
* from the input port and loaded to database.<br>
* Any generated commands/files can be optionally logged to help diagnose problems.<br>
* Before you use this component, make sure that mysql client is installed and configured on the machine where CloverETL runs and
* mysql command line tool available. </td>
* </tr>
* <tr>
* <td>
* <h4><i>Inputs:</i></h4>
* </td>
* <td>[0] - input records. It can be omitted - then <b>fileURL</b> has to be provided.</td>
* </tr>
* <tr><td><h4><i>Outputs:</i></h4></td>
* <td>[0] - optionally one output port defined/connected - info about rejected records.
* Output metadata contains three fields with row number (integer), column name (string) and error message (string).
* </td></tr>
*
* <h4><i>Comment:</i></h4>
* </td>
* <td></td>
* </tr>
* </table> <br>
* <table border="1">
* <th>XML attributes:</th>
* <tr>
* <td><b>type</b></td>
* <td>"MYSQL_DATA_WRITER"</td>
* </tr>
* <tr>
* <td><b>id</b></td>
* <td>component identification</td>
* </tr>
* <tr>
* <td><b>mysqlPath</b></td>
* <td>path to mysql utility</td>
* </tr>
* <tr>
* <td><b>database</b></td>
* <td>the name of the database to receive the data</td>
* </tr>
* <tr>
* <td><b>table</b></td>
* <td>table name, where data are loaded</td>
* </tr>
* <tr>
* <td><b>columnDelimiter</b><br>
* <i>optional</i></td>
* <td>delimiter used for each column in data (default = '\t')</br> Value of the delimiter mustn't be contained in data.</td>
* </tr>
* <tr>
* <td><b>fileURL</b><br>
* <i>optional</i></td>
* <td>Path to data file to be loaded.<br>
* Normally this file is a temporary storage for data to be passed to mysql utility.
* If <i>fileURL</i> is not specified, at Windows platform the file is created in Clover or OS temporary directory and deleted after load finishes.
* At Linux/Unix system named pipe is used instead of temporary file.
* If <i>fileURL</i> is specified, temporary file is created within given path and name and not deleted after being loaded. Next graph
* run overwrites it.<br>
* There is one more meaning of this parameter. If input port is not specified, this file is used only for reading by mysql
* utility and must already contain data in format expected by load. The file is neither deleted nor overwritten.</td>
* </tr>
* <tr>
* <td><b>commandURL</b><br>
* <i>optional</i></td>
* <td>Path to command file where LOAD DATA INFILE statement is stored.<br>
* If <i>commandURL</i> is not specified, the command file is created in Clover temporary directory and deleted after load finishes.<br>
* If <i>commandURL</i> is specified and this file doesn't exist, temporary command file is created within given path and name and not deleted after being loaded. Default command file is stored here.<br>
* If <i>commandURL</i> is specified and this file exist, this file is used instead of command file created by Clover.
* </td>
* </tr>
* <tr>
* <td><b>host</b><br>
* <i>optional</i></td>
* <td>Import data to the MySQL server on the given host. The default host is localhost.</td>
* </tr>
* <tr>
* <td><b>username</b><br>
* <i>optional</i></td>
* <td>The MySQL username to use when connecting to the server.</td>
* </tr>
* <tr>
* <td><b>password</b><br>
* <i>optional</i></td>
* <td>The password to use when connecting to the server.</td>
* </tr>
* <tr>
* <td>ignoreRows</td>
* <td>Ignore the first N lines of the data file.</td>
* </tr>
* <tr>
* <td><b>parameters</b><br>
* <i>optional</i></td>
* <td>All possible additional parameters which can be passed on to
* <a href="http://dev.mysql.com/doc/refman/5.1/en/mysql-command-options.html"> mysql utility</a> or to
* <a href="http://dev.mysql.com/doc/refman/5.1/en/load-data.html"> LOAD DATA INFILE statement</a>.<br>
* Parameters, in form <i>key=value</i>
* (or <i>key</i> - interpreted as <i>key=true</i>, if possible value are only "true" or "false") has to be separated by :;|
* {colon, semicolon, pipe}. If in parameter value occurs one of :;|, value has to be double quoted.<br>
* <b>Load parameters</b><br>
* <b><i>Parameters for mysql utility</i></b><br>
* <table>
* <tr>
* <td>skipAutoRehash</td>
* <td>Disable automatic rehashing. Disables table and column name completion. That causes mysql to start faster.<br>
* If <i>skipAutoRehash</i> attribute isn't defined, default value is true.</td>
* </tr>
* <tr>
* <td>characterSetsDir</td>
* <td>The directory where character sets are installed. See <a
* href="http://www.mysql.org/doc/refman/5.1/en/character-sets.html"> The Character Set Used for Data and Sorting</a>.</td>
* </tr>
* <tr>
* <td>compress</td>
* <td>Compress all information sent between the client and the server if both support compression.</td>
* </tr>
* <tr>
* <td>defaultCharacterSet</td>
* <td>Use <i>defaultCharacterSet</i> as the default character set. See <a
* href="http://www.mysql.org/doc/refman/5.1/en/character-sets.html"> The Character Set Used for Data and Sorting</a>.</td>
* </tr>
* <tr>
* <td>force</td>
* <td>Continue even if an SQL error occurs.</td>
* </tr>
* <tr>
* <td>noBeep</td>
* <td>Do not beep when errors occur.</td>
* </tr>
* <tr>
* <td>port</td>
* <td>The TCP/IP port number to use for the connection.</td>
* </tr>
* <tr>
* <td>protocol</td>
* <td>The connection protocol to use. One of {TCP|SOCKET|PIPE|MEMORY}.</td>
* </tr>
* <tr>
* <td>reconnect</td>
* <td>If the connection to the server is lost, automatically try to reconnect. A single reconnect attempt is made each time the connection is lost.</td>
* </tr>
* <tr>
* <td>secureAuth</td>
* <td>Do not send passwords to the server in old (pre-4.1.1) format. This prevents connections except for servers that use the newer password format.</td>
* </tr>
* <tr>
* <td>showWarnings</td>
* <td>Cause warnings to be shown after each statement if there are any.
* If <i>showWarnings</i> attribute isn't defined, default value is true.<br>
* If any output port is connected, this parameter must be used.</td>
* </tr>
* <tr>
* <td>silent</td>
* <td>Silent mode. Produce output only when errors occur.</td>
* </tr>
* <tr>
* <td>socket</td>
* <td>For connections to localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use.</td>
* </tr>
* <tr>
* <td>ssl</td>
* <td>Options that begin with <i>ssl</i> attribute specify whether to connect to the server via SSL and indicate where to find
* SSL keys and certificates. See <a href="http://www.mysql.org/doc/refman/5.1/en/ssl-options.html"> SSL Command Options</a>.</td>
* </tr>
* </table>
* <b><i>Parameters for LOAD DATA INFILE statement</i></b><br>
* <table>
* <tr>
* <td>local</td>
* <td>Read input files locally from the client host.<br>
* If <i>local</i> attribute isn't defined, default value is true.</td>
* </tr>
* <tr>
* <td>lowPriority</td>
* <td>If you use <i>lowPriority</i>, execution of the LOAD DATA statement is delayed until no other clients are reading from the table.
* This affects only storage engines that use only table-level locking (MyISAM, MEMORY, MERGE).</td>
* </tr>
* <tr>
* <td>concurrent</td>
* <td>If you specify <i>concurrent</i> with a MyISAM table that satisfies the condition for concurrent inserts
* (that is, it contains no free blocks in the middle), other threads can retrieve data from the table while LOAD DATA is executing.
* Using this option affects the performance of LOAD DATA a bit, even if no other thread is using the table at the same time.</td>
* </tr>
* <tr>
* <td>ignore</td>
* <td>See the description for the <i>replace</i> attribute.</td>
* </tr>
* <tr>
* <td>replace</td>
* <td>The <i>replace</i> and <i>ignore</i> parameter control handling of input rows that duplicate existing rows on
* unique key values. If you specify <i>replace</i> parameter, input rows replace existing rows.
* In other words, rows that have the same value for a primary key or unique index as an existing row. See <a href="http://dev.mysql.com/doc/refman/5.1/en/replace.html">REPLACE Syntax</a>.<br>
* If you specify <i>ignore</i> parameter, input rows that duplicate an existing row on a unique key value are skipped.
* If you do not specify either option, the behavior depends on whether the <i>local</i> parameter is specified.
* Without <i>local</i>, an error occurs when a duplicate key value is found, and the rest of the text file is ignored.
* With <i>local</i>, the default behavior is the same as if <i>ignore</i> is specified;
* this is because the server has no way to stop transmission of the file in the middle of the operation.</td>
* </tr>
* <tr>
* <td>fieldsEnclosedBy</td>
* <td>It is used for enclosing each filed in data by char. <br>
* When data is read from input port this attribute is ignored.</td>
* </tr>
* <tr>
* <td>fieldsIsOptionallyEnclosed</td>
* <td>It decide if <i>fieldsEnclosedBy</i> is used for each columns or not. <br>
* It can be used only with <i>fieldsEnclosedBy</i> attribute. <br>
* When data is read from input port this attribute is ignored.</td>
* </tr>
* <tr>
* <td>fieldsEscapedBy</td>
* <td>It is used form escaping fields by char. <br>
* When data is read from input port this attribute is ignored.</td>
* </tr>
* <tr>
* <td>linesStartingBy</td>
* <td>If all the lines you want to read in have a common prefix that you want to ignore,
* you can use <i>linesStartingBy</i> to skip over the prefix, and anything before it.
* If a line does not include the prefix, the entire line is skipped.</td>
* </tr>
* <tr>
* <td>recordDelimiter</td>
* <td>Specifies the record delimiter. (default = '\n' (newline character)).</td>
* </tr>
* <tr>
* <td>columns</td>
* <td>This option takes a comma-separated list of column names as its value. The order of the column names indicates how to
* match data file columns with table columns.<br>
* </td>
* </tr>
* </table></td>
* </tr>
* </table>
*
* <h4>Example:</h4>
* Reading data from input port:
*
* <pre>
* <Node
* mysqlPath="mysql"
* database="testdb"
* table="test"
* id="MYSQL_DATA_WRITER1"
* type="MYSQL_DATA_WRITER"
* />
* </pre>
*
* Reading data from flat file:
*
* <pre>
* <Node
* mysqlPath="mysql"
* database="testdb"
* table="test"
* columnDelimiter=","
* fileURL="${WORKSPACE}/data/delimited/mysqlFlat.dat"
* parameters="fieldsEnclosedBy=*|fieldsIsOptionallyEnclosed"
* id="MYSQL_DATA_WRITER0"
* type="MYSQL_DATA_WRITER"/>
* />
*
* @author Miroslav Haupt ([email protected])
* (c) Javlin Consulting (www.javlinconsulting.cz)
* @see org.jetel.graph.TransformationGraph
* @see org.jetel.graph.Node
* @see org.jetel.graph.Edge
* @since 24.9.2007
*
*/
public class MysqlDataWriter extends BulkLoader {
private static Log logger = LogFactory.getLog(MysqlDataWriter.class);
/** Description of the Field */
private static final String XML_MYSQL_PATH_ATTRIBUTE = "mysqlPath";
private static final String XML_HOST_ATTRIBUTE = "host";
private static final String XML_COMMAND_URL_ATTRIBUTE = "commandURL";
private static final String XML_IGNORE_ROWS_ATTRIBUTE = "ignoreRows";
// params for mysql client
private static final String MYSQL_SKIP_AUTO_REHASH_PARAM = "skipAutoRehash";
private static final String MYSQL_CHARACTER_SETS_DIR_PARAM = "characterSetsDir";
private static final String MYSQL_COMPRESS_PARAM = "compress";
private static final String MYSQL_DEFAULT_CHARACTER_SET_PARAM = "defaultCharacterSet";
private static final String MYSQL_FORCE_PARAM = "force";
private static final String MYSQL_NO_BEEP_PARAM = "noBeep";
private static final String MYSQL_PORT_PARAM = "port";
private static final String MYSQL_PROTOCOL_PARAM = "protocol";
private static final String MYSQL_RECONNECT_PARAM = "reconnect";
private static final String MYSQL_SECURE_AUTH_PARAM = "secureAuth";
private static final String MYSQL_SHOW_WARNINGS_PARAM = "showWarnings";
private static final String MYSQL_SILENT_PARAM = "silent";
private static final String MYSQL_SOCKET_PARAM = "socket";
private static final String MYSQL_SSL_PARAM = "ssl";
// params for LOAD DATA INFILE statement
private static final String LOAD_LOCAL_PARAM = "local";
private static final String LOAD_LOW_PRIORITY_PARAM = "lowPriority";
private static final String LOAD_CONCURRENT_PARAM = "concurrent";
private static final String LOAD_REPLACE_PARAM = "replace";
private static final String LOAD_IGNORE_PARAM = "ignore";
private static final String LOAD_FIELDS_ENCLOSED_BY_PARAM = "fieldsEnclosedBy";
private static final String LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM = "fieldsIsOptionallyEnclosed";
private static final String LOAD_FIELDS_ESCAPED_BY_PARAM = "fieldsEscapedBy";
private static final String LOAD_LINES_STARTING_BY_PARAM = "linesStartingBy";
private static final String LOAD_RECORD_DELIMITER_PARAM = "recordDelimiter";
private static final String LOAD_COLUMNS_PARAM = "columns";
// switches for mysql client,these switches have own xml attributes
private static final String MYSQL_DATABASE_SWITCH = "database";
private static final String MYSQL_HOST_SWITCH = "host";
private static final String MYSQL_USER_SWITCH = "user";
private static final String MYSQL_PASSWORD_SWITCH = "password";
// switches for mysql client
private static final String MYSQL_SKIP_AUTO_REHASH_SWITCH = "skip-auto-rehash";
private static final String MYSQL_CHARACTER_SETS_DIR_SWITCH = "character-sets-dir";
private static final String MYSQL_COMPRESS_SWITCH = "compress";
private static final String MYSQL_DEFAULT_CHARACTER_SET_SWITCH = "default-character-set";
private static final String MYSQL_EXECUTE_SWITCH = "execute";
private static final String MYSQL_FORCE_SWITCH = "force";
private static final String MYSQL_LOCAL_INFILE_SWITCH = "local-infile";
private static final String MYSQL_NO_BEEP_SWITCH = "no-beep";
private static final String MYSQL_PORT_SWITCH = "port";
private static final String MYSQL_PROTOCOL_SWITCH = "protocol";
private static final String MYSQL_RECONNECT_SWITCH = "reconnect";
private static final String MYSQL_SECURE_AUTH_SWITCH = "secure-auth";
private static final String MYSQL_SHOW_WARNINGS_SWITCH = "show-warnings";
private static final String MYSQL_SILENT_SWITCH = "silent";
private static final String MYSQL_SOCKET_SWITCH = "socket";
private static final String MYSQL_SSL_SWITCH = "ssl*";
// keywords for LOAD DATA INFILE statement
private static final String LOAD_LOCAL_KEYWORD = "LOCAL";
private static final String LOAD_LOW_PRIORITY_KEYWORD = "LOW_PRIORITY";
private static final String LOAD_CONCURRENT_KEYWORD = "CONCURRENT";
private static final String LOAD_REPLACE_KEYWORD = "REPLACE";
private static final String LOAD_IGNORE_KEYWORD = "IGNORE";
private static final String LOAD_FIELDS_ENCLOSED_BY_KEYWORD = "ENCLOSED BY";
private static final String LOAD_FIELDS_OPTIONALLY_ENCLOSED_KEYWORD = "OPTIONALLY";
private static final String LOAD_FIELDS_ESCAPED_BY_KEYWORD = "ESCAPED BY";
private static final String LOAD_LINES_STARTING_BY_KEYWORD = "STARTING BY";
private static final String LOAD_RECORD_DELIMITER_KEYWORD = "TERMINATED BY";
public final static String COMPONENT_TYPE = "MYSQL_DATA_WRITER";
private final static String LINE_SEPARATOR = System.getProperty("line.separator");
private final static String SWITCH_MARK = "--";
private final static String EXCHANGE_FILE_PREFIX = "mysqlExchange";
private final static String MYSQL_FILE_NAME_PREFIX = "mysql";
private final static String DEFAULT_COLUMN_DELIMITER = "\t";
private final static String DEFAULT_RECORD_DELIMITER = "\n";
private final static String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
private final static String DEFAULT_TIME_FORMAT = "HH:mm:ss";
private final static String DEFAULT_YEAR_FORMAT = "yyyy";
// variables for dbload's command
private int ignoreRows = UNUSED_INT;
private String commandURL;
private File commandFile;
/**
* flag that determine if execute() method was already executed;
* used for deleting temp data file and reporting about it
*/
private boolean alreadyExecuted = false;
private boolean isDataReadDirectlyFromFile;
/**
* Constructor for the MysqlDataWriter object
*
* @param id Description of the Parameter
*/
public MysqlDataWriter(String id, String mysqlPath, String database, String table) {
super(id, mysqlPath, database);
this.table = table;
columnDelimiter = DEFAULT_COLUMN_DELIMITER;
}
/**
* Main processing method for the MysqlDataWriter object
*
* @since April 4, 2002
*/
public Result execute() throws Exception {
alreadyExecuted = true;
ProcBox box;
int processExitValue = 0;
if (isDataReadFromPort) {
if (ProcBox.isWindowsPlatform() || dataURL != null) {
// dataFile is used for exchange data
readFromPortAndWriteByFormatter();
box = createProcBox();
processExitValue = box.join();
} else { // data is send to process through named pipe
processExitValue = runWithPipe();
}
} else {
processExitValue = readDataDirectlyFromFile();
}
if (processExitValue != 0) {
throw new JetelException("Mysql utility has failed.");
}
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
/**
* Create command line for process, where mysql utility is running.
* Example: mysql --skip-auto-rehash --database=testdb
* --execute=source /tmp/mysql47459.ctl --local-infile --show-warnings
*
* @return array first field is name of mysql utility and the others fields are parameters
* @throws ComponentNotReadyException when command file isn't created
*/
private String[] createCommandLineForDbLoader() throws ComponentNotReadyException {
if (ProcBox.isWindowsPlatform()) {
loadUtilityPath = StringUtils.backslashToSlash(loadUtilityPath);
}
CommandBuilder cmdBuilder = new CommandBuilder(properties, SWITCH_MARK);
cmdBuilder.add(loadUtilityPath);
cmdBuilder.addBooleanParam(MYSQL_SKIP_AUTO_REHASH_PARAM, MYSQL_SKIP_AUTO_REHASH_SWITCH, true);
cmdBuilder.addAttribute(MYSQL_HOST_SWITCH, host);
cmdBuilder.addAttribute(MYSQL_USER_SWITCH, user);
cmdBuilder.addAttribute(MYSQL_PASSWORD_SWITCH, password);
cmdBuilder.addAttribute(MYSQL_DATABASE_SWITCH, database);
cmdBuilder.addParam(MYSQL_CHARACTER_SETS_DIR_PARAM, MYSQL_CHARACTER_SETS_DIR_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_COMPRESS_PARAM, MYSQL_COMPRESS_SWITCH);
cmdBuilder.addParam(MYSQL_DEFAULT_CHARACTER_SET_PARAM, MYSQL_DEFAULT_CHARACTER_SET_SWITCH);
String commandFileName = createCommandFile();
if (ProcBox.isWindowsPlatform()) {
commandFileName = StringUtils.backslashToSlash(commandFileName);
}
cmdBuilder.addAttribute(MYSQL_EXECUTE_SWITCH, "source " + commandFileName);
cmdBuilder.addBooleanParam(MYSQL_FORCE_PARAM, MYSQL_FORCE_SWITCH);
cmdBuilder.addBooleanParam("", MYSQL_LOCAL_INFILE_SWITCH, true);
cmdBuilder.addBooleanParam(MYSQL_NO_BEEP_PARAM, MYSQL_NO_BEEP_SWITCH);
cmdBuilder.addParam(MYSQL_PORT_PARAM, MYSQL_PORT_SWITCH);
cmdBuilder.addParam(MYSQL_PROTOCOL_PARAM, MYSQL_PROTOCOL_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_RECONNECT_PARAM, MYSQL_RECONNECT_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_SECURE_AUTH_PARAM, MYSQL_SECURE_AUTH_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_SHOW_WARNINGS_PARAM, MYSQL_SHOW_WARNINGS_SWITCH, true);
cmdBuilder.addBooleanParam(MYSQL_SILENT_PARAM, MYSQL_SILENT_SWITCH);
cmdBuilder.addParam(MYSQL_SOCKET_PARAM, MYSQL_SOCKET_SWITCH);
cmdBuilder.addBooleanParam(MYSQL_SSL_PARAM, MYSQL_SSL_SWITCH);
return cmdBuilder.getCommand();
}
/**
* Create file that contains LOAD DATA INFILE command and return its name.
*
* @return name of the command file
* @throws ComponentNotReadyException when command file isn't created
*/
String createCommandFile() throws ComponentNotReadyException {
try {
if (commandURL != null) {
commandFile = new File(commandURL);
if (commandFile.exists()) {
return commandFile.getCanonicalPath();
} else {
commandFile.createNewFile();
}
} else {
commandFile = File.createTempFile(MYSQL_FILE_NAME_PREFIX,
CONTROL_FILE_NAME_SUFFIX, getTempDir());
}
saveCommandFile(commandFile);
return commandFile.getCanonicalPath();
} catch (IOException ioe) {
throw new ComponentNotReadyException(this,
"Can't create command file for mysql utility.", ioe);
}
}
/**
* Save default LOAD DATA INFILE command to the file.
*
* @throws IOException when error occured
*/
private void saveCommandFile(File commandFile) throws IOException {
FileWriter commandWriter = new FileWriter(commandFile);
String command = getDefaultCommandFileContent();
logger.debug("Command file content: " + command);
commandWriter.write(command);
commandWriter.close();
}
/**
* Create and return string that contains LOAD DATA INFILE command.
* @return string that contains LOAD DATA INFILE command
* @throws IOException
*/
private String getDefaultCommandFileContent() throws IOException {
// LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
CommandBuilder cmdBuilder = new CommandBuilder(properties, SPACE_CHAR);
cmdBuilder.add("LOAD DATA");
cmdBuilder.addBooleanParam(LOAD_LOW_PRIORITY_PARAM, LOAD_LOW_PRIORITY_KEYWORD);
cmdBuilder.addBooleanParam(LOAD_CONCURRENT_PARAM, LOAD_CONCURRENT_KEYWORD);
cmdBuilder.addBooleanParam(LOAD_LOCAL_PARAM, LOAD_LOCAL_KEYWORD, true);
cmdBuilder.add("INFILE " + StringUtils.quote(getDataFilePath()) + LINE_SEPARATOR);
// [REPLACE | IGNORE]
if (cmdBuilder.addBooleanParam(LOAD_REPLACE_PARAM, LOAD_REPLACE_KEYWORD)
|| cmdBuilder.addBooleanParam(LOAD_IGNORE_PARAM, LOAD_IGNORE_KEYWORD)) {
cmdBuilder.add(LINE_SEPARATOR);
}
// INTO TABLE tbl_name
cmdBuilder.add("INTO TABLE " + table + LINE_SEPARATOR);
// [FIELDS
// [TERMINATED BY 'string']
// [[OPTIONALLY] ENCLOSED BY 'char']
// [ESCAPED BY 'char']
// ]
if (!columnDelimiter.equals(DEFAULT_COLUMN_DELIMITER) ||
properties.containsKey(LOAD_FIELDS_ENCLOSED_BY_PARAM) ||
properties.containsKey(LOAD_FIELDS_ESCAPED_BY_PARAM)) {
cmdBuilder.add("FIELDS" + LINE_SEPARATOR);
cmdBuilder.add("TERMINATED BY " + StringUtils.quote(columnDelimiter) + LINE_SEPARATOR);
cmdBuilder.addBooleanParam(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM,
LOAD_FIELDS_OPTIONALLY_ENCLOSED_KEYWORD);
if (cmdBuilder.addParam(LOAD_FIELDS_ENCLOSED_BY_PARAM, LOAD_FIELDS_ENCLOSED_BY_KEYWORD, true)) {
cmdBuilder.add(LINE_SEPARATOR);
}
if (cmdBuilder.addParam(LOAD_FIELDS_ESCAPED_BY_PARAM, LOAD_FIELDS_ESCAPED_BY_KEYWORD, true)) {
cmdBuilder.add(LINE_SEPARATOR);
}
}
// [LINES
// [STARTING BY 'string']
// [TERMINATED BY 'string']
// ]
if (properties.containsKey(LOAD_LINES_STARTING_BY_PARAM) ||
properties.containsKey(LOAD_RECORD_DELIMITER_PARAM)) {
cmdBuilder.add("LINES" + LINE_SEPARATOR);
if (cmdBuilder.addParam(LOAD_LINES_STARTING_BY_PARAM, LOAD_LINES_STARTING_BY_KEYWORD, true)) {
cmdBuilder.add(LINE_SEPARATOR);
}
if (cmdBuilder.addParam(LOAD_RECORD_DELIMITER_PARAM, LOAD_RECORD_DELIMITER_KEYWORD, true)) {
cmdBuilder.add(LINE_SEPARATOR);
}
}
// [IGNORE number LINES]
if (ignoreRows != UNUSED_INT) {
cmdBuilder.add("IGNORE " + ignoreRows + " LINES" + LINE_SEPARATOR);
}
// [(col_name_or_user_var,...)]
if (properties.containsKey(LOAD_COLUMNS_PARAM)) {
cmdBuilder.add("'" + properties.getProperty(LOAD_COLUMNS_PARAM) + "'");
}
return cmdBuilder.getCommandAsString();
}
private String getDataFilePath() throws IOException {
if (ProcBox.isWindowsPlatform()) {
// convert "C:\examples\xxx.dat" to "C:/examples/xxx.dat"
return StringUtils.backslashToSlash(dataFile.getCanonicalPath());
}
return dataFile.getCanonicalPath();
}
/**
* Description of the Method
*
* @exception ComponentNotReadyException Description of the Exception
* @since April 4, 2002
*/
public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
isDataReadDirectlyFromFile = !isDataReadFromPort &&
!StringUtils.isEmpty(dataURL);
checkParams();
// data is read directly from file -> file isn't used for exchange
if (isDataReadDirectlyFromFile) {
dataFile = openFile(dataURL);
} else {
createFileForExchange();
}
commandLine = createCommandLineForDbLoader();
printCommandLineToLog(commandLine, logger);
if (isDataReadFromPort) {
dbMetadata = createLoadUtilityMetadata(columnDelimiter, getRecordDelimiter());
// init of data formatter
formatter = new DelimitedDataFormatter(CHARSET_NAME);
formatter.init(dbMetadata);
}
errConsumer = new LoggerDataConsumer(LoggerDataConsumer.LVL_ERROR, 0);
if (isDataWrittenToPort) {
try {
// create data consumer and check metadata
consumer = new MysqlPortDataConsumer(getOutputPort(WRITE_TO_PORT));
} catch (ComponentNotReadyException cnre) {
free();
throw new ComponentNotReadyException(this, "Error during initialization of MysqlPortDataConsumer.", cnre);
}
} else {
consumer = new LoggerDataConsumer(LoggerDataConsumer.LVL_DEBUG, 0);
}
}
private void createFileForExchange() throws ComponentNotReadyException {
if (ProcBox.isWindowsPlatform() || dataURL != null) {
if (dataURL != null) {
dataFile = new File(dataURL);
dataFile.delete();
} else {
dataFile = createTempFile(EXCHANGE_FILE_PREFIX);
}
} else {
dataFile = createTempFile(EXCHANGE_FILE_PREFIX);
}
}
/**
* Checks if mandatory attributes are defined.
* And check combination of some parameters.
*
* @throws ComponentNotReadyException if any of conditions isn't fulfilled
*/
private void checkParams() throws ComponentNotReadyException {
if (StringUtils.isEmpty(loadUtilityPath)) {
throw new ComponentNotReadyException(this, StringUtils.quote(XML_MYSQL_PATH_ATTRIBUTE)
+ " attribute have to be set.");
}
if (StringUtils.isEmpty(database)) {
throw new ComponentNotReadyException(this,
StringUtils.quote(XML_DATABASE_ATTRIBUTE) + " attribute have to be set.");
}
if (StringUtils.isEmpty(table) && !fileExists(commandURL)) {
throw new ComponentNotReadyException(this,
StringUtils.quote(XML_TABLE_ATTRIBUTE) + " attribute has to be specified or " +
StringUtils.quote(XML_COMMAND_URL_ATTRIBUTE) +
" attribute has to be specified and file at the URL must exists.");
}
if (!isDataReadFromPort && !fileExists(dataURL) && !fileExists(commandURL)) {
throw new ComponentNotReadyException(this, "Input port or " +
StringUtils.quote(XML_FILE_URL_ATTRIBUTE) +
" attribute or " + StringUtils.quote(XML_COMMAND_URL_ATTRIBUTE) +
" attribute have to be specified and specified file must exist.");
}
if (ignoreRows != UNUSED_INT && ignoreRows < 0) {
throw new ComponentNotReadyException(this,
XML_IGNORE_ROWS_ATTRIBUTE + " mustn't be less than 0.");
}
// check combination
if (properties.containsKey(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM)
&& !properties.containsKey(LOAD_FIELDS_ENCLOSED_BY_PARAM)) {
logger.warn("Attribute " + StringUtils.quote(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM)
+ " is ignored because it has to be used in combination with "
+ StringUtils.quote(LOAD_FIELDS_ENCLOSED_BY_PARAM) + " attribute.");
}
// if any output port is connected, MYSQL_SHOW_WARNINGS_SWITCH parameter must be used
// MYSQL_SHOW_WARNINGS_SWITCH is used when MYSQL_SHOW_WARNINGS_PARAM isn't defined
// or when MYSQL_SHOW_WARNINGS_PARAM=true
if (isDataWrittenToPort) {
if (properties.containsKey(MYSQL_SHOW_WARNINGS_PARAM) &&
"false".equalsIgnoreCase(properties.getProperty(MYSQL_SHOW_WARNINGS_PARAM))) {
properties.setProperty(MYSQL_SHOW_WARNINGS_PARAM, "true");
logger.warn("If any output port is connected, " +
StringUtils.quote(MYSQL_SHOW_WARNINGS_PARAM) +
" parameter mustn't equals false. " +
StringUtils.quote(MYSQL_SHOW_WARNINGS_PARAM) + " parameters was set to true.");
}
}
// report on ignoring some attributes
if (isDataReadFromPort) {
if (properties.containsKey(LOAD_FIELDS_ENCLOSED_BY_PARAM)) {
logger.warn("Attribute " + StringUtils.quote(LOAD_FIELDS_ENCLOSED_BY_PARAM)
+ " is ignored because it is used only when data is read directly from file.");
}
if (properties.containsKey(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM)) {
logger.warn("Attribute " + StringUtils.quote(LOAD_FIELDS_IS_OPTIONALLY_ENCLOSED_PARAM)
+ " is ignored because it is used only when data is read directly from file.");
}
if (properties.containsKey(LOAD_FIELDS_ESCAPED_BY_PARAM)) {
logger.warn("Attribute " + StringUtils.quote(LOAD_FIELDS_ESCAPED_BY_PARAM)
+ " is ignored because it is used only when data is read directly from file.");
}
}
}
@Override
protected void setLoadUtilityDateFormat(DataFieldMetadata field) {
setLoadUtilityDateFormat(field, DEFAULT_TIME_FORMAT, DEFAULT_DATE_FORMAT,
DEFAULT_DATETIME_FORMAT, DEFAULT_YEAR_FORMAT);
}
private String getRecordDelimiter() {
if (properties.containsKey(LOAD_RECORD_DELIMITER_PARAM)) {
return (String) properties.get(LOAD_RECORD_DELIMITER_PARAM);
} else {
return DEFAULT_RECORD_DELIMITER;
}
}
@Override
public synchronized void free() {
if(!isInitialized()) return;
super.free();
deleteDataFile();
deleteTempFile(commandFile, commandURL, logger);
alreadyExecuted = false;
}
/**
* Deletes data file which was used for exchange data.
*/
private void deleteDataFile() {
if (dataFile == null) {
return;
}
if (!alreadyExecuted) {
return;
}
if (isDataReadFromPort && dataURL == null && !dataFile.delete()) {
logger.warn("Temp data file was not deleted.");
}
}
/**
* Description of the Method
*
* @param nodeXML
* Description of Parameter
* @return Description of the Returned Value
* @since May 21, 2002
*/
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
try {
MysqlDataWriter mysqlDataWriter = new MysqlDataWriter(
xattribs.getString(XML_ID_ATTRIBUTE),
xattribs.getString(XML_MYSQL_PATH_ATTRIBUTE),
xattribs.getString(XML_DATABASE_ATTRIBUTE),
xattribs.getString(XML_TABLE_ATTRIBUTE));
if (xattribs.exists(XML_FILE_URL_ATTRIBUTE)) {
mysqlDataWriter.setFileUrl(xattribs.getString(XML_FILE_URL_ATTRIBUTE));
}
if (xattribs.exists(XML_COLUMN_DELIMITER_ATTRIBUTE)) {
mysqlDataWriter.setColumnDelimiter(xattribs.getString(XML_COLUMN_DELIMITER_ATTRIBUTE));
}
if (xattribs.exists(XML_HOST_ATTRIBUTE)) {
mysqlDataWriter.setHost(xattribs.getString(XML_HOST_ATTRIBUTE));
}
if (xattribs.exists(XML_USER_ATTRIBUTE)) {
mysqlDataWriter.setUser(xattribs.getString(XML_USER_ATTRIBUTE));
}
if (xattribs.exists(XML_PASSWORD_ATTRIBUTE)) {
mysqlDataWriter.setPassword(xattribs.getString(XML_PASSWORD_ATTRIBUTE));
}
if (xattribs.exists(XML_COMMAND_URL_ATTRIBUTE)) {
mysqlDataWriter.setCommandURL((xattribs.getString(XML_COMMAND_URL_ATTRIBUTE)));
}
if (xattribs.exists(XML_IGNORE_ROWS_ATTRIBUTE)) {
mysqlDataWriter.setIgnoreRows(xattribs.getInteger(XML_IGNORE_ROWS_ATTRIBUTE));
}
if (xattribs.exists(XML_PARAMETERS_ATTRIBUTE)) {
mysqlDataWriter.setParameters(xattribs.getString(XML_PARAMETERS_ATTRIBUTE));
}
return mysqlDataWriter;
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" +
xattribs.getString(XML_ID_ATTRIBUTE, " unknown ID ") +
":" + ex.getMessage(), ex);
}
}
@Override
public void toXML(Element xmlElement) {
super.toXML(xmlElement);
xmlElement.setAttribute(XML_MYSQL_PATH_ATTRIBUTE, loadUtilityPath);
if (!DEFAULT_COLUMN_DELIMITER.equals(columnDelimiter)) {
xmlElement.setAttribute(XML_COLUMN_DELIMITER_ATTRIBUTE, columnDelimiter);
}
if (!StringUtils.isEmpty(host)) {
xmlElement.setAttribute(XML_HOST_ATTRIBUTE, host);
}
if (!StringUtils.isEmpty(commandURL)) {
xmlElement.setAttribute(XML_COMMAND_URL_ATTRIBUTE, commandURL);
}
if (ignoreRows != UNUSED_INT) {
xmlElement.setAttribute(XML_IGNORE_ROWS_ATTRIBUTE, String.valueOf(ignoreRows));
}
}
/** Description of the Method */
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if(!checkInputPorts(status, 0, 1)
|| !checkOutputPorts(status, 0, 1)) {
return status;
}
try {
init();
} catch (ComponentNotReadyException e) {
ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(),
ConfigurationStatus.Severity.ERROR, this,ConfigurationStatus.Priority.NORMAL);
if (!StringUtils.isEmpty(e.getAttributeName())) {
problem.setAttributeName(e.getAttributeName());
}
status.add(problem);
} finally {
free();
}
return status;
}
public String getType() {
return COMPONENT_TYPE;
}
private void setIgnoreRows(int ignoreRows) {
this.ignoreRows = ignoreRows;
}
public void setCommandURL(String commandURL) {
this.commandURL = commandURL;
}
/**
* Class for reading and parsing data from input stream, which is supposed
* to be connected to process' output, and sends them to specified output port.
*
* @see org.jetel.util.exec.ProcBox
* @see org.jetel.util.exec.DataConsumer
* @author Miroslav Haupt ([email protected])
* (c) Javlin Consulting (www.javlinconsulting.cz)
* @since 17.10.2007
*/
private class MysqlPortDataConsumer implements DataConsumer {
private BufferedReader reader; // read from input stream (=output stream of mysql process)
private DataRecord errRecord = null;
private OutputPort errPort = null;
private DataRecordMetadata errMetadata; // format as output port
private Log logger = LogFactory.getLog(MysqlPortDataConsumer.class);
private final static int ROW_NUMBER_FIELD_NO = 0;
private final static int COLUMN_NAME_FIELD_NO = 1;
private final static int ERR_MSG_FIELD_NO = 2;
private final static int NUMBER_OF_FIELDS = 3;
private String strBadRowPattern = "(.+) for column '(\\w+)' at row (\\d+)";
private Matcher badRowMatcher;
/**
* @param port Output port receiving consumed data.
* @throws ComponentNotReadyException
*/
public MysqlPortDataConsumer(OutputPort errPort) throws ComponentNotReadyException {
if (errPort == null) {
throw new ComponentNotReadyException("Output port wasn't found.");
}
this.errPort = errPort;
errMetadata = errPort.getMetadata();
if (errMetadata == null) {
throw new ComponentNotReadyException("Output port hasn't assigned metadata.");
}
checkErrPortMetadata();
errRecord = new DataRecord(errMetadata);
errRecord.init();
Pattern badRowPattern = Pattern.compile(strBadRowPattern);
badRowMatcher = badRowPattern.matcher("");
}
/**
* @see org.jetel.util.exec.DataConsumer
*/
public void setInput(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
/**
* Example of bad rows in stream:
* Warning (Code 1264): Out of range value adjusted for column 'datetimeT' at row 1
* Warning (Code 1366): Incorrect integer value: 's' for column 'smallT' at row 2
* Note (Code 1265): Data truncated for column 'decT' at row 3
*
* @see org.jetel.util.exec.DataConsumer
*/
public boolean consume() throws JetelException {
try {
String line;
if ((line = readLine()) == null) {
return false;
}
badRowMatcher.reset(line);
if (badRowMatcher.find()) {
int rowNumber = Integer.valueOf(badRowMatcher.group(3));
String columnName = badRowMatcher.group(2);
String errMsg = badRowMatcher.group(1);
setErrRecord(errRecord, rowNumber, columnName, errMsg);
errPort.writeRecord(errRecord);
}
} catch (Exception e) {
close();
throw new JetelException("Error while writing output record", e);
}
SynchronizeUtils.cloverYield();
return true;
}
/**
* Read line by reader and write it by logger and return it.
*
* @return read line
* @throws IOException
*/
private String readLine() throws IOException {
String line = reader.readLine();
if (!StringUtils.isEmpty(line)) {
logger.debug(line);
}
return line;
}
/**
* Set value in errRecord.
*
* @param errRecord destination record
* @param rowNumber number of bad row
* @param columnName column's name of bad row
* @param errMsg error message
* @return destination record
*/
private DataRecord setErrRecord(DataRecord errRecord, int rowNumber, String columnName, String errMsg) {
errRecord.reset();
errRecord.getField(ROW_NUMBER_FIELD_NO).setValue(rowNumber);
errRecord.getField(COLUMN_NAME_FIELD_NO).setValue(columnName);
errRecord.getField(ERR_MSG_FIELD_NO).setValue(errMsg);
return errRecord;
}
/**
* check metadata at error port if metadata isn't correct then throws ComponentNotReadyException
*
* @throws ComponentNotReadyException when metadata isn't correct
*/
private void checkErrPortMetadata() throws ComponentNotReadyException {
// check number of fields
if (errMetadata.getNumFields() != NUMBER_OF_FIELDS) {
throw new ComponentNotReadyException("Number of fields of " +
StringUtils.quote(errMetadata.getName()) +
" isn't equal " + NUMBER_OF_FIELDS + ".");
}
// check if first field of errMetadata is integer - rowNumber
if (errMetadata.getFieldType(ROW_NUMBER_FIELD_NO) != DataFieldMetadata.INTEGER_FIELD) {
throw new ComponentNotReadyException("First field of " + StringUtils.quote(errMetadata.getName()) +
" has different type from integer.");
}
// check if second field of errMetadata is string - columnName
if (errMetadata.getFieldType(COLUMN_NAME_FIELD_NO) != DataFieldMetadata.STRING_FIELD) {
throw new ComponentNotReadyException("Second field of " + StringUtils.quote(errMetadata.getName()) +
" has different type from string.");
}
// check if third field of errMetadata is string - errMsg
if (errMetadata.getFieldType(ERR_MSG_FIELD_NO) != DataFieldMetadata.STRING_FIELD) {
throw new ComponentNotReadyException("Third field of " + StringUtils.quote(errMetadata.getName()) +
" has different type from string.");
}
}
/**
* @see org.jetel.util.exec.DataConsumer
*/
public void close() {
try {
if (reader != null) {
reader.close();
}
} catch (IOException ioe) {
logger.warn("Reader wasn't closed.", ioe);
}
try {
if (errPort != null) {
errPort.eof();
}
} catch (Exception ie) {
logger.warn("Out port wasn't closed.", ie);
}
}
}
} | FIX: #1533 fix problem when running from different directory
git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@6017 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.bulkloader/src/org/jetel/component/MysqlDataWriter.java | FIX: #1533 fix problem when running from different directory |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.