answer
stringlengths 17
10.2M
|
|---|
package se.sics.cooja.mspmote;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.interfaces.IPAddress;
/**
* MSP430-based mote types emulated in MSPSim.
*
* @see SkyMoteType
* @see ESBMoteType
*
* @author Fredrik Osterlind, Joakim Eriksson, Niclas Finne
*/
@ClassDescription("Msp Mote Type")
public abstract class MspMoteType implements MoteType {
private static Logger logger = Logger.getLogger(MspMoteType.class);
private String identifier = null;
private String description = null;
protected Simulation simulation;
/* If source file is defined, the firmware is recompiled when loading simulations */
private File fileSource = null;
private String compileCommands = null;
private File fileFirmware = null;
private Class<? extends MoteInterface>[] moteInterfaceClasses = null;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCompileCommands() {
return compileCommands;
}
public void setCompileCommands(String commands) {
this.compileCommands = commands;
}
public File getContikiSourceFile() {
return fileSource;
}
public File getContikiFirmwareFile() {
return fileFirmware;
}
public void setContikiSourceFile(File file) {
fileSource = file;
}
public void setContikiFirmwareFile(File file) {
this.fileFirmware = file;
}
public Class<? extends MoteInterface>[] getMoteInterfaceClasses() {
return moteInterfaceClasses;
}
public void setMoteInterfaceClasses(Class<? extends MoteInterface>[] classes) {
moteInterfaceClasses = classes;
}
public final Mote generateMote(Simulation simulation) {
MspMote mote = createMote(simulation);
mote.initMote();
return mote;
}
protected abstract MspMote createMote(Simulation simulation);
public JPanel getTypeVisualizer() {
/* TODO Move to emulated layer */
JPanel panel = new JPanel();
JLabel label = new JLabel();
JPanel smallPane;
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// Identifier
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Identifier");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getIdentifier());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Description
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Description");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getDescription());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
/* Contiki source */
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Contiki source");
smallPane.add(BorderLayout.WEST, label);
if (getContikiSourceFile() != null) {
label = new JLabel(getContikiSourceFile().getName());
label.setToolTipText(getContikiSourceFile().getPath());
} else {
label = new JLabel("[not specified]");
}
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
/* Contiki firmware */
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Contiki firmware");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getContikiFirmwareFile().getName());
label.setToolTipText(getContikiFirmwareFile().getPath());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
/* Compile commands */
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Compile commands");
smallPane.add(BorderLayout.WEST, label);
JTextArea textArea = new JTextArea(getCompileCommands());
textArea.setEditable(false);
textArea.setBorder(BorderFactory.createEmptyBorder());
smallPane.add(BorderLayout.EAST, textArea);
panel.add(smallPane);
/* Icon (if available) */
if (!GUI.isVisualizedInApplet()) {
Icon moteTypeIcon = getMoteTypeIcon();
if (moteTypeIcon != null) {
smallPane = new JPanel(new BorderLayout());
label = new JLabel(moteTypeIcon);
smallPane.add(BorderLayout.CENTER, label);
panel.add(smallPane);
}
}
panel.add(Box.createRigidArea(new Dimension(0, 5)));
return panel;
}
public abstract Icon getMoteTypeIcon();
public ProjectConfig getConfig() {
logger.warn("Msp mote type project config not implemented");
return null;
}
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
// Identifier
element = new Element("identifier");
element.setText(getIdentifier());
config.add(element);
// Description
element = new Element("description");
element.setText(getDescription());
config.add(element);
// Source file
if (fileSource != null) {
element = new Element("source");
File file = simulation.getGUI().createPortablePath(fileSource);
element.setText(file.getPath().replaceAll("\\\\", "/"));
config.add(element);
element = new Element("commands");
element.setText(compileCommands);
config.add(element);
}
// Firmware file
element = new Element("firmware");
File file = simulation.getGUI().createPortablePath(fileFirmware);
element.setText(file.getPath().replaceAll("\\\\", "/"));
config.add(element);
// Mote interfaces
for (Class moteInterface : getMoteInterfaceClasses()) {
element = new Element("moteinterface");
element.setText(moteInterface.getName());
config.add(element);
}
return config;
}
public boolean setConfigXML(Simulation simulation,
Collection<Element> configXML, boolean visAvailable)
throws MoteTypeCreationException {
this.simulation = simulation;
ArrayList<Class<? extends MoteInterface>> intfClassList = new ArrayList<Class<? extends MoteInterface>>();
for (Element element : configXML) {
String name = element.getName();
if (name.equals("identifier")) {
identifier = element.getText();
} else if (name.equals("description")) {
description = element.getText();
} else if (name.equals("source")) {
fileSource = new File(element.getText());
if (!fileSource.exists()) {
fileSource = simulation.getGUI().restorePortablePath(fileSource);
}
} else if (name.equals("command")) {
/* Backwards compatibility: command is now commands */
logger.warn("Old simulation config detected: old version only supports a single compile command");
compileCommands = element.getText();
} else if (name.equals("commands")) {
compileCommands = element.getText();
} else if (name.equals("firmware")) {
fileFirmware = new File(element.getText());
if (!fileFirmware.exists()) {
fileFirmware = simulation.getGUI().restorePortablePath(fileFirmware);
}
} else if (name.equals("elf")) {
/* Backwards compatibility: elf is now firmware */
logger.warn("Old simulation config detected: firmware specified as elf");
fileFirmware = new File(element.getText());
} else if (name.equals("moteinterface")) {
String intfClass = element.getText().trim();
/* Backwards compatibility: MspIPAddress -> IPAddress */
if (intfClass.equals("se.sics.cooja.mspmote.interfaces.MspIPAddress")) {
logger.warn("Old simulation config detected: IP address interface was moved");
intfClass = IPAddress.class.getName();
}
Class<? extends MoteInterface> moteInterfaceClass =
simulation.getGUI().tryLoadClass(this, MoteInterface.class, intfClass);
if (moteInterfaceClass == null) {
logger.warn("Can't find mote interface class: " + intfClass);
} else {
intfClassList.add(moteInterfaceClass);
}
} else {
logger.fatal("Unrecognized entry in loaded configuration: " + name);
throw new MoteTypeCreationException(
"Unrecognized entry in loaded configuration: " + name);
}
}
Class<? extends MoteInterface>[] intfClasses = intfClassList.toArray(new Class[0]);
if (intfClasses.length == 0) {
/* Backwards compatibility: No interfaces specifed */
logger.warn("Old simulation config detected: no mote interfaces specified, assuming all.");
intfClasses = getAllMoteInterfaceClasses();
}
setMoteInterfaceClasses(intfClasses);
if (fileFirmware == null) {
if (fileSource == null) {
throw new MoteTypeCreationException("Neither source or firmware specified");
}
/* Backwards compatibility: Generate expected firmware file name from source */
logger.warn("Old simulation config detected: no firmware file specified, generating expected");
fileFirmware = getExpectedFirmwareFile(fileSource);
}
return configureAndInit(GUI.getTopParentContainer(), simulation, visAvailable);
}
public abstract Class<? extends MoteInterface>[] getAllMoteInterfaceClasses();
public abstract File getExpectedFirmwareFile(File source);
}
|
package de.jeha.s3pt.operations;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import de.jeha.s3pt.OperationResult;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author jenshadlich@googlemail.com
*/
public class ClearBucket extends AbstractOperation {
private static final Logger LOG = LoggerFactory.getLogger(ClearBucket.class);
private final AmazonS3 s3Client;
private final String bucketName;
private final int n;
public ClearBucket(AmazonS3 s3Client, String bucketName, int n) {
this.s3Client = s3Client;
this.bucketName = bucketName;
this.n = n;
}
@Override
public OperationResult call() throws Exception {
LOG.info("Clear bucket: n={}", n);
int deleted = 0;
boolean truncated;
do {
ObjectListing objectListing = s3Client.listObjects(bucketName);
truncated = objectListing.isTruncated();
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
LOG.debug("Delete object: {}, #deleted {}", objectSummary.getKey(), deleted);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
s3Client.deleteObject(bucketName, objectSummary.getKey());
stopWatch.stop();
LOG.debug("Time = {} ms", stopWatch.getTime());
getStats().addValue(stopWatch.getTime());
deleted++;
if (deleted >= n) {
break;
}
if (deleted % 1000 == 0) {
LOG.info("Object deleted so far: {}", deleted);
}
}
} while (truncated && deleted < n);
LOG.info("Object deleted: {}", deleted);
return new OperationResult(getStats());
}
}
|
package de.raysha.net.scs;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import de.raysha.net.scs.exception.NoSerializerFoundException;
import de.raysha.net.scs.exception.UnknownMessageException;
import de.raysha.net.scs.model.Message;
import de.raysha.net.scs.model.serialize.MessageSerializer;
import de.raysha.net.scs.utils.HashGenerator;
/**
* This class is an abstraction level for make it easy to communicate between server and client over {@link Socket}s.
*
* @author rainu
*/
public abstract class AbstractConnector {
protected static final int BUFFER_SIZE = 8096;
private static final int NORMALIZED_MESSAGE_ID_LENGTH = 32; //length of md5 string
private final Object sendMonitor = new Object();
private final Object receiveMonitor = new Object();
private final Socket socket;
protected final Map<String, Class<? extends Message>> messageIdToClass = new HashMap<String, Class<? extends Message>>();
protected final Map<Class<? extends Message>, String> classToMessageId = new HashMap<Class<? extends Message>, String>();
protected final Map<Class<? extends Message>, MessageSerializer<? extends Message>> messageSerializer =
new HashMap<Class<? extends Message>, MessageSerializer<? extends Message>>();
public AbstractConnector(Socket socket) {
this.socket = socket;
}
/**
* Register a {@link MessageSerializer} for a message-class. This serializer
* is responsible for de-/serialize the in-/out- coming messages.
*
* @param messageClass For which class is the given serializer responsible for.
* @param serializer The serailizer for the given message class.
*/
public <M extends Message> void registerSerializer(
Class<M> messageClass, MessageSerializer<M> serializer){
final String messageId = messageClass.getName();
registerSerializer(messageId, messageClass, serializer);
}
/**
* Register a {@link MessageSerializer} for a message-class. This serializer
* is responsible for de-/serialize the in-/out- coming messages.
*
* @param messageId This id will transfer between client and server! So the id must absolutely
* unique! Otherwise it can cause trouble at the de/-serialization of messages.
* @param messageClass For which class is the given serializer responsible for.
* @param serializer The serailizer for the given message class.
*/
public <M extends Message> void registerSerializer(
String messageId, Class<M> messageClass, MessageSerializer<M> serializer){
final String normalizedMessageId = normalizeMessageId(messageId);
messageIdToClass.put(normalizedMessageId, messageClass);
classToMessageId.put(messageClass, normalizedMessageId);
messageSerializer.put(messageClass, serializer);
}
private String normalizeMessageId(String messageId) {
final String md5 = HashGenerator.toMD5(messageId);
assert md5.length() == NORMALIZED_MESSAGE_ID_LENGTH;
return md5;
}
/**
* Get the {@link MessageSerializer} that is responsible for the given class. If no serializer was
* registered before, null will be returned.
*
* @param messageClass The message class.
* @return The corresponding {@link MessageSerializer} or <b>null</b> if there is no serializer for that message class.
*/
@SuppressWarnings("unchecked")
public final <M extends Message> MessageSerializer<M> getSerializerFor(Class<M> messageClass) {
return (MessageSerializer<M>) messageSerializer.get(messageClass);
}
/**
* Disconnect from my partner.
*
* @throws IOException if an I/O error occurs when closing my socket.
*/
public void disconnect() throws IOException {
socket.close();
}
/**
* Use the registered {@link MessageSerializer} to serialize the given message. If there was no serializer
* found, an {@link NoSerializerFoundException} will be thrown!
*
* @param message The message which should be serialize.
* @return The raw byte-array that contains the serialiesed message.
* @throws NoSerializerFoundException if no serialiser is registered for this type of message.
*/
protected final byte[] serialize(Message message) {
@SuppressWarnings("unchecked")
MessageSerializer<? super Message> serializer =
(MessageSerializer<? super Message>) getSerializerFor(message.getClass());
if(serializer == null){
throw new NoSerializerFoundException(message.getClass());
}
return serializer.serialize(message);
}
/**
* Use the registered {@link MessageSerializer} to deserialize the given raw message. If there was no serializer
* found, an {@link NoSerializerFoundException} will be thrown!
*
* @param messageId The received uniqe message-type-id.
* @param raw The serialized raw message, which should be deserialise.
* @return The deserialized {@link Message}-instance.
* @throws UnknownMessageException if the message id is unknown (no class is mapped for it).
* @throws NoSerializerFoundException if no serialiser is registered for this type of message.
*/
@SuppressWarnings("unchecked")
protected final <M extends Message> M deserialize(String messageId, byte[] raw){
Class<? extends Message> messageClass = messageIdToClass.get(messageId);
if(messageClass == null){
throw new UnknownMessageException(messageId);
}
MessageSerializer<? super Message> serializer =
(MessageSerializer<? super Message>) getSerializerFor(messageClass);
if(serializer == null){
throw new NoSerializerFoundException(messageClass);
}
return (M) serializer.deserialize(raw);
}
/**
* Send a {@link Message} through my {@link Socket}.
*
* @param message The message to be send.
* @throws IOException If an error occurs while sending the message.
*/
public abstract void send(Message message) throws IOException;
/**
* Sends a the given raw message.
*
* @param messageType Which type of message are the raw-content?
* @param message The raw message.
* @throws IOException If an error occurs while sending a message.
*/
protected final void sendRaw(Class<? extends Message> messageType, byte[] message) throws IOException{
final String messageId = classToMessageId.get(messageType);
byte[] rawMessageId = messageId.getBytes();
byte[] length = ByteBuffer.allocate(4).putInt(message.length + rawMessageId.length).array();
synchronized (sendMonitor) {
socket.getOutputStream().write(length);
socket.getOutputStream().write(rawMessageId);
socket.getOutputStream().write(message);
socket.getOutputStream().flush();
}
}
/**
* Receive a message from my {@link Socket}. This is a blocking call! That
* means that this method blocks until a message was received or a {@link IOException} was
* thrown.
*
* @return The received {@link Message}.
* @throws IOException If an error occurs while receiving a message.
*/
public abstract Message receive() throws IOException;
/**
* Receive the next raw message. This is a blocking call! That
* means that this method blocks until a message was received or a {@link IOException} was
* thrown.
*
* @return The received {@link RawMessage}.
* @throws IOException If an error occurs while receiving a message.
*/
protected final RawMessage receiveRaw() throws IOException{
final ByteBuffer builder;
final int length;
synchronized (receiveMonitor) {
InputStream in = socket.getInputStream();
length = receiveLength(in);
int totalRead = 0;
builder = ByteBuffer.allocate(length);
while(length > totalRead){
byte[] buffer = new byte[length - totalRead];
int read = in.read(buffer);
if(read < 0) {
break;
}
totalRead += read;
builder.put(buffer, 0, read);
}
}
builder.flip();
return parseRawMessage(builder, length);
}
private int receiveLength(InputStream in) throws IOException {
byte[] length = new byte[4];
int read = in.read(length);
if(read != 4){
throw new IOException("The protocol was not followed. No length is given!");
}
return ByteBuffer.wrap(length).getInt();
}
private RawMessage parseRawMessage(final ByteBuffer builder, final int totalLength) {
byte[] rawMessageId = new byte[NORMALIZED_MESSAGE_ID_LENGTH];
builder.get(rawMessageId, 0, NORMALIZED_MESSAGE_ID_LENGTH);
byte[] rawMessage = new byte[totalLength - NORMALIZED_MESSAGE_ID_LENGTH];
builder.get(rawMessage, 0, rawMessage.length);
return new RawMessage(new String(rawMessageId), rawMessage);
}
protected static class RawMessage {
protected final String messageId;
protected final byte[] rawMessage;
public RawMessage(String messageId, byte[] rawMessage) {
this.messageId = messageId;
this.rawMessage = rawMessage;
}
}
}
|
package com.thaiopensource.relaxng.output.xsd;
import com.thaiopensource.relaxng.edit.AbstractVisitor;
import com.thaiopensource.relaxng.edit.AttributePattern;
import com.thaiopensource.relaxng.edit.ChoiceNameClass;
import com.thaiopensource.relaxng.edit.CompositePattern;
import com.thaiopensource.relaxng.edit.DefineComponent;
import com.thaiopensource.relaxng.edit.DivComponent;
import com.thaiopensource.relaxng.edit.ElementPattern;
import com.thaiopensource.relaxng.edit.NameNameClass;
import com.thaiopensource.relaxng.edit.UnaryPattern;
import com.thaiopensource.relaxng.edit.IncludeComponent;
import com.thaiopensource.relaxng.edit.ValuePattern;
import com.thaiopensource.relaxng.parse.Context;
import com.thaiopensource.xml.util.WellKnownNamespaces;
import com.thaiopensource.xml.util.Naming;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Enumeration;
public class PrefixManager implements SourceUriGenerator {
private final Map prefixMap = new HashMap();
private final Set usedPrefixes = new HashSet();
/**
* Set of prefixes that cannot be used for schema namespace.
*/
private final Set reservedPrefixes = new HashSet();
private int nextGenIndex = 1;
static private final String[] xsdPrefixes = { "xs", "xsd" };
static private final int MAX_PREFIX_LENGTH = 10;
static class PrefixUsage {
int count;
}
class PrefixSelector extends AbstractVisitor {
private final SchemaInfo si;
private String inheritedNamespace;
private final Map namespacePrefixUsageMap = new HashMap();
PrefixSelector(SchemaInfo si) {
this.si = si;
this.inheritedNamespace = "";
si.getGrammar().componentsAccept(this);
Context context = si.getGrammar().getContext();
if (context != null) {
for (Enumeration enum = context.prefixes(); enum.hasMoreElements();) {
String prefix = (String)enum.nextElement();
if (!prefix.equals(""))
notePrefix(prefix, resolveNamespace(context.resolveNamespacePrefix(prefix)));
}
}
}
public Object visitElement(ElementPattern p) {
p.getNameClass().accept(this);
p.getChild().accept(this);
return null;
}
public Object visitAttribute(AttributePattern p) {
return p.getNameClass().accept(this);
}
public Object visitChoice(ChoiceNameClass nc) {
nc.childrenAccept(this);
return null;
}
public Object visitName(NameNameClass nc) {
notePrefix(nc.getPrefix(), resolveNamespace(nc.getNamespaceUri()));
return null;
}
public Object visitValue(ValuePattern p) {
for (Iterator iter = p.getPrefixMap().entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
String prefix = (String)entry.getKey();
if (prefix != null && !prefix.equals("")) {
String ns = resolveNamespace((String)entry.getValue());
notePrefix(prefix, ns);
if (!ns.equals(WellKnownNamespaces.XML_SCHEMA))
reservedPrefixes.add(prefix);
}
}
return null;
}
private String resolveNamespace(String ns) {
return ns == NameNameClass.INHERIT_NS ? inheritedNamespace : ns;
}
private void notePrefix(String prefix, String ns) {
if (prefix == null || ns == null || ns.equals(""))
return;
Map prefixUsageMap = (Map)namespacePrefixUsageMap.get(ns);
if (prefixUsageMap == null) {
prefixUsageMap = new HashMap();
namespacePrefixUsageMap.put(ns, prefixUsageMap);
}
PrefixUsage prefixUsage = (PrefixUsage)prefixUsageMap.get(prefix);
if (prefixUsage == null) {
prefixUsage = new PrefixUsage();
prefixUsageMap.put(prefix, prefixUsage);
}
prefixUsage.count++;
}
public Object visitComposite(CompositePattern p) {
p.childrenAccept(this);
return null;
}
public Object visitUnary(UnaryPattern p) {
return p.getChild().accept(this);
}
public Object visitDefine(DefineComponent c) {
c.getBody().accept(this);
return null;
}
public Object visitDiv(DivComponent c) {
c.componentsAccept(this);
return null;
}
public Object visitInclude(IncludeComponent c) {
String saveInheritedNamespace = inheritedNamespace;
inheritedNamespace = c.getNs();
si.getSchema(c.getHref()).componentsAccept(this);
inheritedNamespace = saveInheritedNamespace;
return null;
}
void assignPrefixes() {
for (Iterator iter = namespacePrefixUsageMap.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next();
String ns = (String)entry.getKey();
if (!ns.equals("") && !ns.equals(WellKnownNamespaces.XML)) {
Map prefixUsageMap = (Map)entry.getValue();
if (prefixUsageMap != null) {
Map.Entry best = null;
for (Iterator entryIter = prefixUsageMap.entrySet().iterator(); entryIter.hasNext();) {
Map.Entry tem = (Map.Entry)entryIter.next();
if ((best == null
|| ((PrefixUsage)tem.getValue()).count > ((PrefixUsage)best.getValue()).count)
&& prefixOk((String)tem.getKey(), ns))
best = tem;
}
if (best != null)
usePrefix((String)best.getKey(), ns);
}
}
}
}
}
PrefixManager(SchemaInfo si) {
usePrefix("xml", WellKnownNamespaces.XML);
new PrefixSelector(si).assignPrefixes();
}
String getPrefix(String namespace) {
String prefix = (String)prefixMap.get(namespace);
if (prefix == null && namespace.equals(WellKnownNamespaces.XML_SCHEMA)) {
for (int i = 0; i < xsdPrefixes.length; i++)
if (tryUsePrefix(xsdPrefixes[i], namespace))
return xsdPrefixes[i];
}
if (prefix == null)
prefix = tryUseUri(namespace);
if (prefix == null) {
do {
prefix = "ns" + Integer.toString(nextGenIndex++);
} while (!tryUsePrefix(prefix, namespace));
}
return prefix;
}
private String tryUseUri(String namespace) {
String segment = chooseSegment(namespace);
if (segment == null)
return null;
if (segment.length() <= MAX_PREFIX_LENGTH && tryUsePrefix(segment, namespace))
return segment;
for (int i = 1; i <= segment.length(); i++) {
String prefix = segment.substring(0, i);
if (tryUsePrefix(prefix, namespace))
return prefix;
}
return null;
}
private boolean tryUsePrefix(String prefix, String namespace) {
if (!prefixOk(prefix, namespace))
return false;
usePrefix(prefix, namespace);
return true;
}
private boolean prefixOk(String prefix, String namespace) {
return (!usedPrefixes.contains(prefix)
&& !(reservedPrefixes.contains(prefix) && namespace.equals(WellKnownNamespaces.XML_SCHEMA)));
}
private void usePrefix(String prefix, String namespace) {
usedPrefixes.add(prefix);
prefixMap.put(namespace, prefix);
}
static private String chooseSegment(String ns) {
int off = ns.indexOf('
if (off >= 0) {
String segment = ns.substring(off + 1).toLowerCase();
if (Naming.isNcname(segment))
return segment;
}
else
off = ns.length();
for (;;) {
int i = ns.lastIndexOf('/', off - 1);
if (i < 0 || (i > 0 && ns.charAt(i - 1) == '/'))
break;
String segment = ns.substring(i + 1, off).toLowerCase();
if (segmentOk(segment))
return segment;
off = i;
}
off = ns.indexOf(':');
if (off >= 0) {
String segment = ns.substring(off + 1).toLowerCase();
if (segmentOk(segment))
return segment;
}
return null;
}
private static boolean segmentOk(String segment) {
return Naming.isNcname(segment) && !segment.equals("ns") && !segment.equals("namespace");
}
public String generateSourceUri(String ns) {
// TODO add method to OutputDirectory to do this properly
if (ns.equals(""))
return "local";
else
return "/" + getPrefix(ns);
}
}
|
package brooklyn.entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import brooklyn.config.ConfigKey;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.entity.rebind.Rebindable;
import brooklyn.event.AttributeSensor;
import brooklyn.location.Location;
import brooklyn.management.Task;
import brooklyn.mementos.EntityMemento;
import brooklyn.policy.Enricher;
import brooklyn.policy.Policy;
/**
* The basic interface for a Brooklyn entity.
* <p>
* Implementors of entities are strongly encouraged to extend {@link brooklyn.entity.basic.AbstractEntity}.
* <p>
* To instantiate an entity, see {@code managementContext.getEntityManager().createEntity(entitySpec)}.
* Also see {@link brooklyn.entity.basic.ApplicationBuilder},
* {@link brooklyn.entity.basic.AbstractEntity#addChild(EntitySpec)}, and
* {@link brooklyn.entity.proxying.EntitySpecs}.
* <p>
* Entities may not be {@link Serializable} in subsequent releases!
*
* @see brooklyn.entity.basic.AbstractEntity
*/
public interface Entity extends Serializable, Rebindable<EntityMemento> {
/**
* The unique identifier for this entity.
*/
String getId();
/**
* A display name; recommended to be a concise single-line description.
*/
String getDisplayName();
/**
* Information about the type of this entity; analogous to Java's object.getClass.
*/
EntityType getEntityType();
/**
* @return the {@link Application} this entity is registered with, or null if not registered.
*/
Application getApplication();
/**
* @return the id of the {@link Application} this entity is registered with, or null if not registered.
*/
String getApplicationId();
/**
* The parent of this entity, null if no parent.
*
* The parent is normally the entity responsible for creating/destroying/managing this entity.
*
* @see #setParent(Entity)
* @see #clearParent
*/
Entity getParent();
/**
* Return the entities that are children of (i.e. "owned by") this entity
*/
Collection<Entity> getChildren();
/**
* Sets the parent (i.e. "owner") of this entity. Returns this entity, for convenience.
*
* @see #getParent
* @see #clearParent
*/
Entity setParent(Entity parent);
/**
* Clears the parent (i.e. "owner") of this entity. Also cleans up any references within its parent entity.
*
* @see #getParent
* @see #setParent
*/
void clearParent();
/**
* Add a child {@link Entity}, and set this entity as its parent,
* returning the added child.
*
* TODO Signature will change to {@code <T extends Entity> T addChild(T child)}, but
* that currently breaks groovy AbstractEntity subclasses sometimes so deferring that
* until (hopefully) the next release. For now use addChild(EntitySpec).
*/
Entity addChild(Entity child);
/**
* Creates an {@link Entity} from the given spec and adds it, setting this entity as the parent,
* returning the added child. */
<T extends Entity> T addChild(EntitySpec<T> spec);
/**
* Removes the specified child {@link Entity}; its parent will be set to null.
*
* @return True if the given entity was contained in the set of children
*/
boolean removeChild(Entity child);
/**
* @deprecated since 0.5; see getParent()
*/
@Deprecated
Entity getOwner();
/**
* @deprecated since 0.5; see getChildren()
*/
@Deprecated
Collection<Entity> getOwnedChildren();
/**
* @deprecated since 0.5; see setOwner(Entity)
*/
@Deprecated
Entity setOwner(Entity group);
/**
* @deprecated since 0.5; see clearParent()
*/
@Deprecated
void clearOwner();
/**
* @deprecated since 0.5; see addChild(Entity)
*/
@Deprecated
Entity addOwnedChild(Entity child);
/**
* @deprecated since 0.5; see removeChild(Entity)
*/
@Deprecated
boolean removeOwnedChild(Entity child);
/**
* @return an immutable thread-safe view of the policies.
*/
Collection<Policy> getPolicies();
/**
* @return an immutable thread-safe view of the enrichers.
*/
Collection<Enricher> getEnrichers();
/**
* The {@link Collection} of {@link Group}s that this entity is a member of.
*
* Groupings can be used to allow easy management/monitoring of a group of entities.
*/
Collection<Group> getGroups();
/**
* Add this entity as a member of the given {@link Group}.
*/
void addGroup(Group group);
/**
* Return all the {@link Location}s this entity is deployed to.
*/
Collection<Location> getLocations();
/**
* Gets the value of the given attribute on this entity, or null if has not been set.
*
* Attributes can be things like workrate and status information, as well as
* configuration (e.g. url/jmxHost/jmxPort), etc.
*/
<T> T getAttribute(AttributeSensor<T> sensor);
/**
* Gets the given configuration value for this entity, which may be inherited from
* its parent.
*/
<T> T getConfig(ConfigKey<T> key);
/**
* Invokes the given effector, with the given parameters to that effector.
*/
<T> Task<T> invoke(Effector<T> eff, Map<String,?> parameters);
/**
* Adds the given policy to this entity. Also calls policy.setEntity if available.
*/
void addPolicy(Policy policy);
/**
* Removes the given policy from this entity.
* @return True if the policy existed at this entity; false otherwise
*/
boolean removePolicy(Policy policy);
/**
* Adds the given enricher to this entity. Also calls enricher.setEntity if available.
*/
void addEnricher(Enricher enricher);
/**
* Removes the given enricher from this entity.
* @return True if the policy enricher at this entity; false otherwise
*/
boolean removeEnricher(Enricher enricher);
}
|
package org.sana.core;
import com.google.gson.annotations.Expose;
import org.sana.api.IObserver;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* An entity that collects data.
*
* @author Sana Development
*
*/
public class Observer extends Model implements IObserver{
/**
* Simple user representation
*/
public static class User{
public String first_name = null;
public String last_name = null;
public String username = null;
public String password = null;
public boolean is_admin = false;
public String[] groups = new String[0];
}
@Expose
public User user = new User();
public String username = null;
public String password = null;
@Expose
public String role;
private String phone_number;
@Expose
Set<Location> locations = new HashSet<>();
/** Default Constructor */
public Observer() {
user = new User();
}
public Observer(Observer obj){
setUsername(obj.getUsername());
setPassword(obj.getPassword());
setRole(obj.getRole());
setLocations(obj.getLocations());
}
/**
* Creates a new instance with a specified unique id.
*
* @param uuid The UUID of the instance
*/
public Observer(String uuid){
super();
setUuid(uuid);
user = new User();
}
public User getUser() {
return user;
}
/*
* (non-Javadoc)
* @see org.sana.api.IObserver#getUsername()
*/
public String getUsername() {
return user.username;
}
/**
* Sets the username for an instance of this class.
*
* @param username the username to set
*/
public void setUsername(String username) {
user.username = username;
}
/*
* (non-Javadoc)
* @see org.sana.api.IObserver#getPassword()
*/
public String getPassword() {
return user.password;
}
/**
* Sets the password for an instance of this class.
*
* @param password the password to set
*/
public void setPassword(String password) {
user.password = password;
}
/*
* (non-Javadoc)
* @see org.sana.api.IObserver#getRole()
*/
public String getRole() {
return role;
}
/**
* Sets the role for an instance of this class.
*
* @param role the role to set
*/
public void setRole(String role) {
this.role = role;
}
public String getPhoneNumber() {
return phone_number;
}
/**
* Sets the role for an instance of this class.
*
* @param phone_number the role to set
*/
public void setPhoneNumber(String phone_number) {
this.phone_number = phone_number;
}
public String getFirstName(){
return user.first_name;
}
public void setFirstName(String name){
user.first_name = name;
}
public String getLastName(){
return user.last_name;
}
public void setLastName(String name){
user.last_name = name;
}
public List<Location> getLocations(){
return new ArrayList<>(locations);
}
public void setLocations(Collection<Location> locations){
this.locations.clear();
this.locations.addAll(locations);
}
public void setLocations(String[] locations) {
this.locations.clear();
for (String location : locations) {
Location l = new Location();
l.setUuid(location);
this.locations.add(l);
}
}
public boolean isAdmin() {
return user.is_admin;
}
public boolean setIsAdmin(boolean isAdmin) {
return user.is_admin = isAdmin;
}
}
|
package de.springbootbuch.webmvc;
import java.io.IOException;
import javax.inject.Provider;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* Part of springbootbuch.de.
*
* @author Michael J. Simons
* @author @rotnroll666
*/
@Component
public class DemoFilter implements Filter {
private static final Logger LOG = LoggerFactory
.getLogger(DemoFilter.class);
private final Provider<ShoppingCart> shoppingCart;
public DemoFilter(
Provider<ShoppingCart> shoppingCart) {
this.shoppingCart = shoppingCart;
}
// halber nicht gezeigt
@Override
public void init(
FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
chain.doFilter(request, response);
if(request instanceof HttpServletRequest && ((HttpServletRequest)request).getSession(false) != null) {
LOG.info(
"Request from {}",
shoppingCart.get()
.getContent().isEmpty() ? "" : "not"
);
}
}
@Override
public void destroy() {
}
}
|
package com.unidev.spring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* Component for fetching random values
* @author denis
*/
@Component
public class Randoms {
private static Logger LOG = LoggerFactory.getLogger(Randoms.class);
private Random random = null;
/**
* Fetch random value from list
* @return Random list value or null if empty or null
*/
public <T> T randomValue(List<T> list) {
if (CollectionUtils.isEmpty(list)) {
LOG.warn("Can't get random value from list {}", list);
return null;
}
int size = list.size();
int id = random.nextInt(size);
return list.get(id);
}
/**
* Fetch random value from collection
* @return Random collection value or null if empty or null
*/
public <T> T randomValue(Collection<T> collection) {
if (CollectionUtils.isEmpty(collection)) {
LOG.warn("Can't get random value from collection {}", collection);
return null;
}
int size = collection.size();
int id = random.nextInt(size);
Iterator<T> iterator = collection.iterator();
T value = null;
for(int i = 0;i<id;i++) {
value = iterator.next();
}
return value;
}
/**
* Get random value from var-arg
* @return
*/
public <T> T randomValue(T... array) {
if (array == null || array.length == 0) {
LOG.warn("Can't get random value from array {}", array);
return null;
}
int size = array.length;
int id = random.nextInt(size);
return array[id];
}
/**
* Generate sequence of random values from provided dictionary string
* @return
*/
public String randomValue(String dictionary, int minLength, int maxLength, boolean firstCharUpperCase) {
int count = minLength + random.nextInt(maxLength - minLength);
String result = "";
for (int i = 0; i < count; i++) {
int id = random.nextInt(dictionary.length());
Character c = dictionary.charAt(id);
if (i == 0 && firstCharUpperCase) {
c = Character.toUpperCase(c);
}
result += c;
}
return result;
}
/**
* Get random sleep value in seconds
* @return Selected sleep value
*/
public int randomSleepValue(int min, int max) {
if (min == max) {
return min;
}
int sleep = 1000 + (1000 * (min + random.nextInt(max - min)));
LOG.debug("Selected sleep value {}", sleep);
return sleep;
}
/**
* Get random value between min and max
* @return
*/
public long randomValue(long min, long max) {
if (min == max) {
return min;
}
return min + random.nextInt((int)(max - min));
}
/**
* Get random values from collection
* @return
*/
public <T> List<T> randomValues(List<T> list, int count) {
List<T> result = new ArrayList<>();
for(int i = 0;i<count;i++) {
int id = random.nextInt(list.size());
T item = list.get(id);
result.add(item);
}
return result;
}
public Random getRandom() {
return random;
}
@Autowired
public void setRandom(Random random) {
this.random = random;
}
}
|
package eu.bitwalker.useragentutils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Enum constants for most common browsers, including e-mail clients and bots.
* @author harald
*
*/
public enum Browser {
/**
* Outlook email client
*/
OUTLOOK( Manufacturer.MICROSOFT, null, 100, "Outlook", new String[] {"MSOffice"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, "MSOffice (([0-9]+))"), // before IE7
/**
* Microsoft Outlook 2007 identifies itself as MSIE7 but uses the html rendering engine of Word 2007.
* Example user agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.1.4322; MSOffice 12)
*/
OUTLOOK2007( Manufacturer.MICROSOFT, Browser.OUTLOOK, 107, "Outlook 2007", new String[] {"MSOffice 12"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2013( Manufacturer.MICROSOFT, Browser.OUTLOOK, 109, "Outlook 2013", new String[] {"Microsoft Outlook 15"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2010( Manufacturer.MICROSOFT, Browser.OUTLOOK, 108, "Outlook 2010", new String[] {"MSOffice 14", "Microsoft Outlook 14"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
/**
* Family of Internet Explorer browsers
*/
IE( Manufacturer.MICROSOFT, null, 1, "Internet Explorer", new String[] { "MSIE", "Trident", "IE " }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "MSIE (([\\d]+)\\.([\\w]+))" ), // before Mozilla
/**
* Since version 7 Outlook Express is identifying itself. By detecting Outlook Express we can not
* identify the Internet Explorer version which is probably used for the rendering.
* Obviously this product is now called Windows Live Mail Desktop or just Windows Live Mail.
*/
OUTLOOK_EXPRESS7( Manufacturer.MICROSOFT, Browser.IE, 110, "Windows Live Mail", new String[] {"Outlook-Express/7.0"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.TRIDENT, null), // before IE7, previously known as Outlook Express. First released in 2006, offered with different name later
/**
* Since 2007 the mobile edition of Internet Explorer identifies itself as IEMobile in the user-agent.
* If previous versions have to be detected, use the operating system information as well.
*/
IEMOBILE11( Manufacturer.MICROSOFT, Browser.IE, 125, "IE Mobile 11", new String[] { "IEMobile/11" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE10( Manufacturer.MICROSOFT, Browser.IE, 124, "IE Mobile 10", new String[] { "IEMobile/10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE9( Manufacturer.MICROSOFT, Browser.IE, 123, "IE Mobile 9", new String[] { "IEMobile/9" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE7( Manufacturer.MICROSOFT, Browser.IE, 121, "IE Mobile 7", new String[] { "IEMobile 7" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE6( Manufacturer.MICROSOFT, Browser.IE, 120, "IE Mobile 6", new String[] { "IEMobile 6" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE11( Manufacturer.MICROSOFT, Browser.IE, 95, "Internet Explorer 11", new String[] { "Trident/7", "IE 11." }, new String[] {"MSIE 7"}, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "(?:Trident\\/7|IE)(?:\\.[0-9]*;)?(?:.*rv:| )(([0-9]+)\\.?([0-9]+))" ), // before Mozilla
IE10( Manufacturer.MICROSOFT, Browser.IE, 92, "Internet Explorer 10", new String[] { "MSIE 10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE9( Manufacturer.MICROSOFT, Browser.IE, 90, "Internet Explorer 9", new String[] { "MSIE 9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE8( Manufacturer.MICROSOFT, Browser.IE, 80, "Internet Explorer 8", new String[] { "MSIE 8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE7( Manufacturer.MICROSOFT, Browser.IE, 70, "Internet Explorer 7", new String[] { "MSIE 7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE6( Manufacturer.MICROSOFT, Browser.IE, 60, "Internet Explorer 6", new String[] { "MSIE 6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE5_5( Manufacturer.MICROSOFT, Browser.IE, 55, "Internet Explorer 5.5", new String[] { "MSIE 5.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE5( Manufacturer.MICROSOFT, Browser.IE, 50, "Internet Explorer 5", new String[] { "MSIE 5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
/**
* Google Chrome browser
*/
CHROME( Manufacturer.GOOGLE, null, 1, "Chrome", new String[] { "Chrome", "CrMo", "CriOS" }, new String[] { "OPR/", "Web Preview" } , BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Chrome\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // before Mozilla
CHROME_MOBILE( Manufacturer.GOOGLE, Browser.CHROME, 100, "Chrome Mobile", new String[] { "CrMo","CriOS", "Mobile Safari" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "(?:CriOS|CrMo|Chrome)\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ),
CHROME40( Manufacturer.GOOGLE, Browser.CHROME, 45, "Chrome 40", new String[] { "Chrome/40" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME39( Manufacturer.GOOGLE, Browser.CHROME, 44, "Chrome 39", new String[] { "Chrome/39" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME38( Manufacturer.GOOGLE, Browser.CHROME, 43, "Chrome 38", new String[] { "Chrome/38" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME37( Manufacturer.GOOGLE, Browser.CHROME, 42, "Chrome 37", new String[] { "Chrome/37" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME36( Manufacturer.GOOGLE, Browser.CHROME, 41, "Chrome 36", new String[] { "Chrome/36" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME35( Manufacturer.GOOGLE, Browser.CHROME, 40, "Chrome 35", new String[] { "Chrome/35" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME34( Manufacturer.GOOGLE, Browser.CHROME, 39, "Chrome 34", new String[] { "Chrome/34" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME33( Manufacturer.GOOGLE, Browser.CHROME, 38, "Chrome 33", new String[] { "Chrome/33" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME32( Manufacturer.GOOGLE, Browser.CHROME, 37, "Chrome 32", new String[] { "Chrome/32" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME31( Manufacturer.GOOGLE, Browser.CHROME, 36, "Chrome 31", new String[] { "Chrome/31" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME30( Manufacturer.GOOGLE, Browser.CHROME, 35, "Chrome 30", new String[] { "Chrome/30" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME29( Manufacturer.GOOGLE, Browser.CHROME, 34, "Chrome 29", new String[] { "Chrome/29" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME28( Manufacturer.GOOGLE, Browser.CHROME, 33, "Chrome 28", new String[] { "Chrome/28" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME27( Manufacturer.GOOGLE, Browser.CHROME, 32, "Chrome 27", new String[] { "Chrome/27" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME26( Manufacturer.GOOGLE, Browser.CHROME, 31, "Chrome 26", new String[] { "Chrome/26" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME25( Manufacturer.GOOGLE, Browser.CHROME, 30, "Chrome 25", new String[] { "Chrome/25" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME24( Manufacturer.GOOGLE, Browser.CHROME, 29, "Chrome 24", new String[] { "Chrome/24" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME23( Manufacturer.GOOGLE, Browser.CHROME, 28, "Chrome 23", new String[] { "Chrome/23" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME22( Manufacturer.GOOGLE, Browser.CHROME, 27, "Chrome 22", new String[] { "Chrome/22" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME21( Manufacturer.GOOGLE, Browser.CHROME, 26, "Chrome 21", new String[] { "Chrome/21" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME20( Manufacturer.GOOGLE, Browser.CHROME, 25, "Chrome 20", new String[] { "Chrome/20" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME19( Manufacturer.GOOGLE, Browser.CHROME, 24, "Chrome 19", new String[] { "Chrome/19" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME18( Manufacturer.GOOGLE, Browser.CHROME, 23, "Chrome 18", new String[] { "Chrome/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME17( Manufacturer.GOOGLE, Browser.CHROME, 22, "Chrome 17", new String[] { "Chrome/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME16( Manufacturer.GOOGLE, Browser.CHROME, 21, "Chrome 16", new String[] { "Chrome/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME15( Manufacturer.GOOGLE, Browser.CHROME, 20, "Chrome 15", new String[] { "Chrome/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME14( Manufacturer.GOOGLE, Browser.CHROME, 19, "Chrome 14", new String[] { "Chrome/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME13( Manufacturer.GOOGLE, Browser.CHROME, 18, "Chrome 13", new String[] { "Chrome/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME12( Manufacturer.GOOGLE, Browser.CHROME, 17, "Chrome 12", new String[] { "Chrome/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME11( Manufacturer.GOOGLE, Browser.CHROME, 16, "Chrome 11", new String[] { "Chrome/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME10( Manufacturer.GOOGLE, Browser.CHROME, 15, "Chrome 10", new String[] { "Chrome/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME9( Manufacturer.GOOGLE, Browser.CHROME, 10, "Chrome 9", new String[] { "Chrome/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME8( Manufacturer.GOOGLE, Browser.CHROME, 5, "Chrome 8", new String[] { "Chrome/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
OMNIWEB( Manufacturer.OTHER, null, 2, "Omniweb", new String[] { "OmniWeb" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null),
SAFARI( Manufacturer.APPLE, null, 1, "Safari", new String[] { "Safari" }, new String[] { "OPR/", "Coast/", "Web Preview","Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Version\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // before AppleWebKit
BLACKBERRY10( Manufacturer.BLACKBERRY, Browser.SAFARI, 10, "BlackBerry", new String[] { "BB10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null),
MOBILE_SAFARI( Manufacturer.APPLE, Browser.SAFARI, 2, "Mobile Safari", new String[] { "Mobile Safari","Mobile/" }, new String[] { "Coast/", "Googlebot-Mobile" }, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // before Safari
SILK( Manufacturer.AMAZON, Browser.SAFARI, 15, "Silk", new String[] { "Silk/" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Silk\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\-[\\w]+)?)" ),
SAFARI8( Manufacturer.APPLE, Browser.SAFARI, 8, "Safari 8", new String[] { "Version/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI7( Manufacturer.APPLE, Browser.SAFARI, 7, "Safari 7", new String[] { "Version/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI6( Manufacturer.APPLE, Browser.SAFARI, 6, "Safari 6", new String[] { "Version/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI5( Manufacturer.APPLE, Browser.SAFARI, 3, "Safari 5", new String[] { "Version/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI4( Manufacturer.APPLE, Browser.SAFARI, 4, "Safari 4", new String[] { "Version/4" }, new String[] { "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
COAST( Manufacturer.OPERA, null, 500, "Opera", new String[] { " Coast/" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "Coast\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
COAST1( Manufacturer.OPERA, Browser.COAST, 501, "Opera", new String[] { " Coast/1." }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "Coast\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA( Manufacturer.OPERA, null, 1, "Opera", new String[] { " OPR/", "Opera" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Opera\\/(([\\d]+)\\.([\\w]+))"), // before MSIE
OPERA_MINI( Manufacturer.OPERA, Browser.OPERA, 20, "Opera Mini", new String[] { "Opera Mini"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.PRESTO, null), // Opera for mobile devices
OPERA25( Manufacturer.OPERA, Browser.OPERA, 25, "Opera 25", new String[] { "OPR/25." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA24( Manufacturer.OPERA, Browser.OPERA, 24, "Opera 24", new String[] { "OPR/24." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA23( Manufacturer.OPERA, Browser.OPERA, 23, "Opera 23", new String[] { "OPR/23." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA20( Manufacturer.OPERA, Browser.OPERA, 21, "Opera 20", new String[] { "OPR/20." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA19( Manufacturer.OPERA, Browser.OPERA, 19, "Opera 19", new String[] { "OPR/19." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA18( Manufacturer.OPERA, Browser.OPERA, 18, "Opera 18", new String[] { "OPR/18." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA17( Manufacturer.OPERA, Browser.OPERA, 17, "Opera 17", new String[] { "OPR/17." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA16( Manufacturer.OPERA, Browser.OPERA, 16, "Opera 16", new String[] { "OPR/16." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA15( Manufacturer.OPERA, Browser.OPERA, 15, "Opera 15", new String[] { "OPR/15." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA12( Manufacturer.OPERA, Browser.OPERA, 12, "Opera 12", new String[] { "Opera/12", "Version/12." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA11( Manufacturer.OPERA, Browser.OPERA, 11, "Opera 11", new String[] { "Version/11." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA10( Manufacturer.OPERA, Browser.OPERA, 10, "Opera 10", new String[] { "Opera/9.8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA9( Manufacturer.OPERA, Browser.OPERA, 5, "Opera 9", new String[] { "Opera/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, null),
KONQUEROR( Manufacturer.OTHER, null, 1, "Konqueror", new String[] { "Konqueror"}, null, BrowserType.WEB_BROWSER, RenderingEngine.KHTML, "Konqueror\\/(([0-9]+)\\.?([\\w]+)?(-[\\w]+)?)" ),
DOLFIN2( Manufacturer.SAMSUNG, null, 1, "Samsung Dolphin 2", new String[] { "Dolfin/2" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // webkit based browser for the bada os
/*
* Apple WebKit compatible client. Can be a browser or an application with embedded browser using UIWebView.
*/
APPLE_WEB_KIT( Manufacturer.APPLE, null, 50, "Apple WebKit", new String[] { "AppleWebKit" }, new String[] { "OPR/", "Web Preview", "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_ITUNES( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 52, "iTunes", new String[] { "iTunes" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_APPSTORE( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 53, "App Store", new String[] { "MacAppStore" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
ADOBE_AIR( Manufacturer.ADOBE, Browser.APPLE_WEB_KIT, 1, "Adobe AIR application", new String[] { "AdobeAIR" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
LOTUS_NOTES( Manufacturer.OTHER, null, 3, "Lotus Notes", new String[] { "Lotus-Notes" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, "Lotus-Notes\\/(([\\d]+)\\.([\\w]+))"), // before Mozilla
CAMINO( Manufacturer.OTHER, null, 5, "Camino", new String[] { "Camino" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Camino\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
CAMINO2( Manufacturer.OTHER, Browser.CAMINO, 17, "Camino 2", new String[] { "Camino/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FLOCK( Manufacturer.OTHER, null, 4, "Flock", new String[]{"Flock"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Flock\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"),
FIREFOX( Manufacturer.MOZILLA, null, 10, "Firefox", new String[] { "Firefox" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Firefox\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
FIREFOX3MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 31, "Firefox 3 Mobile", new String[] { "Firefox/3.5 Maemo" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX_MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 200, "Firefox Mobile", new String[] { "Mobile" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX_MOBILE23(Manufacturer.MOZILLA, FIREFOX_MOBILE, 223, "Firefox Mobile 23", new String[] { "Firefox/23" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX40( Manufacturer.MOZILLA, Browser.FIREFOX, 217, "Firefox 40", new String[] { "Firefox/40" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX39( Manufacturer.MOZILLA, Browser.FIREFOX, 216, "Firefox 39", new String[] { "Firefox/39" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX38( Manufacturer.MOZILLA, Browser.FIREFOX, 215, "Firefox 38", new String[] { "Firefox/38" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX37( Manufacturer.MOZILLA, Browser.FIREFOX, 214, "Firefox 37", new String[] { "Firefox/37" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX36( Manufacturer.MOZILLA, Browser.FIREFOX, 213, "Firefox 36", new String[] { "Firefox/36" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX35( Manufacturer.MOZILLA, Browser.FIREFOX, 212, "Firefox 35", new String[] { "Firefox/35" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX34( Manufacturer.MOZILLA, Browser.FIREFOX, 211, "Firefox 34", new String[] { "Firefox/34" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX33( Manufacturer.MOZILLA, Browser.FIREFOX, 210, "Firefox 33", new String[] { "Firefox/33" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX32( Manufacturer.MOZILLA, Browser.FIREFOX, 109, "Firefox 32", new String[] { "Firefox/32" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX31( Manufacturer.MOZILLA, Browser.FIREFOX, 310, "Firefox 31", new String[] { "Firefox/31" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX30( Manufacturer.MOZILLA, Browser.FIREFOX, 300, "Firefox 30", new String[] { "Firefox/30" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX29( Manufacturer.MOZILLA, Browser.FIREFOX, 290, "Firefox 29", new String[] { "Firefox/29" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX28( Manufacturer.MOZILLA, Browser.FIREFOX, 280, "Firefox 28", new String[] { "Firefox/28" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX27( Manufacturer.MOZILLA, Browser.FIREFOX, 108, "Firefox 27", new String[] { "Firefox/27" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX26( Manufacturer.MOZILLA, Browser.FIREFOX, 107, "Firefox 26", new String[] { "Firefox/26" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX25( Manufacturer.MOZILLA, Browser.FIREFOX, 106, "Firefox 25", new String[] { "Firefox/25" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX24( Manufacturer.MOZILLA, Browser.FIREFOX, 105, "Firefox 24", new String[] { "Firefox/24" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX23( Manufacturer.MOZILLA, Browser.FIREFOX, 104, "Firefox 23", new String[] { "Firefox/23" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX22( Manufacturer.MOZILLA, Browser.FIREFOX, 103, "Firefox 22", new String[] { "Firefox/22" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX21( Manufacturer.MOZILLA, Browser.FIREFOX, 102, "Firefox 21", new String[] { "Firefox/21" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX20( Manufacturer.MOZILLA, Browser.FIREFOX, 101, "Firefox 20", new String[] { "Firefox/20" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX19( Manufacturer.MOZILLA, Browser.FIREFOX, 100, "Firefox 19", new String[] { "Firefox/19" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX18( Manufacturer.MOZILLA, Browser.FIREFOX, 99, "Firefox 18", new String[] { "Firefox/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX17( Manufacturer.MOZILLA, Browser.FIREFOX, 98, "Firefox 17", new String[] { "Firefox/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX16( Manufacturer.MOZILLA, Browser.FIREFOX, 97, "Firefox 16", new String[] { "Firefox/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX15( Manufacturer.MOZILLA, Browser.FIREFOX, 96, "Firefox 15", new String[] { "Firefox/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX14( Manufacturer.MOZILLA, Browser.FIREFOX, 95, "Firefox 14", new String[] { "Firefox/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX13( Manufacturer.MOZILLA, Browser.FIREFOX, 94, "Firefox 13", new String[] { "Firefox/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX12( Manufacturer.MOZILLA, Browser.FIREFOX, 93, "Firefox 12", new String[] { "Firefox/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX11( Manufacturer.MOZILLA, Browser.FIREFOX, 92, "Firefox 11", new String[] { "Firefox/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX10( Manufacturer.MOZILLA, Browser.FIREFOX, 91, "Firefox 10", new String[] { "Firefox/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX9( Manufacturer.MOZILLA, Browser.FIREFOX, 90, "Firefox 9", new String[] { "Firefox/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX8( Manufacturer.MOZILLA, Browser.FIREFOX, 80, "Firefox 8", new String[] { "Firefox/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX7( Manufacturer.MOZILLA, Browser.FIREFOX, 70, "Firefox 7", new String[] { "Firefox/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX6( Manufacturer.MOZILLA, Browser.FIREFOX, 60, "Firefox 6", new String[] { "Firefox/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX5( Manufacturer.MOZILLA, Browser.FIREFOX, 50, "Firefox 5", new String[] { "Firefox/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX4( Manufacturer.MOZILLA, Browser.FIREFOX, 40, "Firefox 4", new String[] { "Firefox/4" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX3( Manufacturer.MOZILLA, Browser.FIREFOX, 30, "Firefox 3", new String[] { "Firefox/3" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX2( Manufacturer.MOZILLA, Browser.FIREFOX, 20, "Firefox 2", new String[] { "Firefox/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX1_5( Manufacturer.MOZILLA, Browser.FIREFOX, 15, "Firefox 1.5", new String[] { "Firefox/1.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
/*
* Thunderbird email client, based on the same Gecko engine Firefox is using.
*/
THUNDERBIRD( Manufacturer.MOZILLA, null, 110, "Thunderbird", new String[] { "Thunderbird" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, "Thunderbird\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
THUNDERBIRD12( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 185, "Thunderbird 12", new String[] { "Thunderbird/12" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD11( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 184, "Thunderbird 11", new String[] { "Thunderbird/11" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD10( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 183, "Thunderbird 10", new String[] { "Thunderbird/10" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD8( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 180, "Thunderbird 8", new String[] { "Thunderbird/8" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD7( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 170, "Thunderbird 7", new String[] { "Thunderbird/7" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD6( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 160, "Thunderbird 6", new String[] { "Thunderbird/6" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD3( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 130, "Thunderbird 3", new String[] { "Thunderbird/3" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD2( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 120, "Thunderbird 2", new String[] { "Thunderbird/2" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
SEAMONKEY( Manufacturer.OTHER, null, 15, "SeaMonkey", new String[]{"SeaMonkey"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "SeaMonkey\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
BOT( Manufacturer.OTHER, null,12, "Robot/Spider", new String[] {"Googlebot", "Web Preview", "bot", "spider", "crawler", "Feedfetcher", "Slurp", "Twiceler", "Nutch", "BecomeBot"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
BOT_MOBILE( Manufacturer.OTHER, Browser.BOT, 20 , "Mobil Robot/Spider", new String[] {"Googlebot-Mobile"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
MOZILLA( Manufacturer.MOZILLA, null, 1, "Mozilla", new String[] { "Mozilla", "Moozilla" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.OTHER, null), // rest of the mozilla browsers
CFNETWORK( Manufacturer.OTHER, null, 6, "CFNetwork", new String[] { "CFNetwork" }, null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ), // Mac OS X cocoa library
EUDORA( Manufacturer.OTHER, null, 7, "Eudora", new String[] { "Eudora", "EUDORA" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ), // email client by Qualcomm
POCOMAIL( Manufacturer.OTHER, null, 8, "PocoMail", new String[] { "PocoMail" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ),
THEBAT( Manufacturer.OTHER, null, 9, "The Bat!", new String[]{"The Bat"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null), // Email Client
NETFRONT( Manufacturer.OTHER, null, 10, "NetFront", new String[]{"NetFront"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.OTHER, null), // mobile device browser
EVOLUTION( Manufacturer.OTHER, null, 11, "Evolution", new String[]{"CamelHttpStream"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null),
LYNX( Manufacturer.OTHER, null, 13, "Lynx", new String[]{"Lynx"}, null, BrowserType.TEXT_BROWSER, RenderingEngine.OTHER, "Lynx\\/(([0-9]+)\\.([\\d]+)\\.?([\\w-+]+)?\\.?([\\w-+]+)?)"),
DOWNLOAD( Manufacturer.OTHER, null, 16, "Downloading Tool", new String[]{"cURL","wget", "ggpht.com", "Apache-HttpClient"}, null, BrowserType.TOOL, RenderingEngine.OTHER, null),
UNKNOWN( Manufacturer.OTHER, null, 14, "Unknown", new String[0], null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ),
@Deprecated
APPLE_MAIL( Manufacturer.APPLE, null, 51, "Apple Mail", new String[0], null, BrowserType.EMAIL_CLIENT, RenderingEngine.WEBKIT, null); // not detectable any longer.
/*
* An id for each browser version which is unique per manufacturer.
*/
private final short id;
private final String name;
private final String[] aliases;
private final String[] excludeList; // don't match when these values are in the agent-string
private final BrowserType browserType;
private final Manufacturer manufacturer;
private final RenderingEngine renderingEngine;
private final Browser parent;
private List<Browser> children;
private Pattern versionRegEx;
private static List<Browser> topLevelBrowsers;
private Browser(Manufacturer manufacturer, Browser parent, int versionId, String name, String[] aliases, String[] exclude, BrowserType browserType, RenderingEngine renderingEngine, String versionRegexString) {
this.id = (short) ( ( manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.parent = parent;
this.children = new ArrayList<Browser>();
this.aliases = toLowerCase(aliases);
this.excludeList = toLowerCase(exclude);
this.browserType = browserType;
this.manufacturer = manufacturer;
this.renderingEngine = renderingEngine;
if (versionRegexString != null)
this.versionRegEx = Pattern.compile(versionRegexString);
if (this.parent == null)
addTopLevelBrowser(this);
else
this.parent.children.add(this);
}
private static String[] toLowerCase(String[] strArr) {
if (strArr == null) return null;
String[] res = new String[strArr.length];
for (int i=0; i<strArr.length; i++) {
res[i] = strArr[i].toLowerCase();
}
return res;
}
// create collection of top level browsers during initialization
private static void addTopLevelBrowser(Browser browser) {
if(topLevelBrowsers == null)
topLevelBrowsers = new ArrayList<Browser>();
topLevelBrowsers.add(browser);
}
public short getId() {
return id;
}
public String getName() {
return name;
}
private Pattern getVersionRegEx() {
if (this.versionRegEx == null) {
if (this.getGroup() != this)
return this.getGroup().getVersionRegEx();
else
return null;
}
return this.versionRegEx;
}
/**
* Detects the detailed version information of the browser. Depends on the userAgent to be available.
* Returns null if it can not detect the version information.
* @return Version
*/
public Version getVersion(String userAgentString) {
Pattern pattern = this.getVersionRegEx();
if (userAgentString != null && pattern != null) {
Matcher matcher = pattern.matcher(userAgentString);
if (matcher.find()) {
String fullVersionString = matcher.group(1);
String majorVersion = matcher.group(2);
String minorVersion = "0";
if (matcher.groupCount() > 2) // usually but not always there is a minor version
minorVersion = matcher.group(3);
return new Version (fullVersionString,majorVersion,minorVersion);
}
}
return null;
}
/**
* @return the browserType
*/
public BrowserType getBrowserType() {
return browserType;
}
/**
* @return the manufacturer
*/
public Manufacturer getManufacturer() {
return manufacturer;
}
/**
* @return the rendering engine
*/
public RenderingEngine getRenderingEngine() {
return renderingEngine;
}
/**
* @return top level browser family
*/
public Browser getGroup() {
if (this.parent != null) {
return parent.getGroup();
}
return this;
}
/*
* Checks if the given user-agent string matches to the browser.
* Only checks for one specific browser.
*/
public boolean isInUserAgentString(String agentString)
{
if (agentString == null)
return false;
String agentStringLowerCase = agentString.toLowerCase();
return isInUserAgentLowercaseString(agentStringLowerCase);
}
private boolean isInUserAgentLowercaseString(String agentStringLowerCase) {
for (String alias : aliases)
{
if (agentStringLowerCase.contains(alias))
return true;
}
return false;
}
/**
* Checks if the given user-agent does not contain one of the tokens which should not match.
* In most cases there are no excluding tokens, so the impact should be small.
* @param agentString
* @return
*/
private boolean containsExcludeToken(String agentString)
{
if (agentString == null)
return false;
String agentStringLowerCase = agentString.toLowerCase();
return containsExcludeTokenLowercase(agentStringLowerCase);
}
private boolean containsExcludeTokenLowercase(String agentStringLowerCase) {
if (excludeList != null) {
for (String exclude : excludeList) {
if (agentStringLowerCase.contains(exclude))
return true;
}
}
return false;
}
private Browser checkUserAgent(String agentString) {
if (agentString == null) {
return null;
}
String agentLowercaseString = agentString.toLowerCase();
if (this.isInUserAgentLowercaseString(agentLowercaseString)) {
if (this.children.size() > 0) {
for (Browser childBrowser : this.children) {
Browser match = childBrowser.checkUserAgent(agentString);
if (match != null) {
return match;
}
}
}
// if children didn't match we continue checking the current to prevent false positives
if (!this.containsExcludeTokenLowercase(agentLowercaseString)) {
return this;
}
}
return null;
}
/**
* Iterates over all Browsers to compare the browser signature with
* the user agent string. If no match can be found Browser.UNKNOWN will
* be returned.
* Starts with the top level browsers and only if one of those matches
* checks children browsers.
* Steps out of loop as soon as there is a match.
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString)
{
return parseUserAgentString(agentString, topLevelBrowsers);
}
/**
* Iterates over the given Browsers (incl. children) to compare the browser
* signature with the user agent string.
* If no match can be found Browser.UNKNOWN will be returned.
* Steps out of loop as soon as there is a match.
* Be aware that if the order of the provided Browsers is incorrect or if the set is too limited it can lead to false matches!
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString, List<Browser> browsers)
{
for (Browser browser : browsers) {
Browser match = browser.checkUserAgent(agentString);
if (match != null) {
return match; // either current operatingSystem or a child object
}
}
return Browser.UNKNOWN;
}
public static Browser valueOf(short id)
{
for (Browser browser : Browser.values())
{
if (browser.getId() == id)
return browser;
}
// same behavior as standard valueOf(string) method
throw new IllegalArgumentException(
"No enum const for id " + id);
}
}
|
package com.novoda.merlin;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import static com.novoda.merlin.MerlinsBeard.NetworkType.*;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
@RunWith(MerlinRobolectricTestRunner.class)
public class MerlinsBeardShould {
@Mock
private ConnectivityManager mockConnectivityManager;
@Mock
private NetworkInfo mockNetworkInfo;
private MerlinsBeard merlinsBeard;
@Before
public void setUp() {
initMocks(this);
merlinsBeard = new MerlinsBeard(mockConnectivityManager);
}
@Test
public void returnFalseForIsConnectedWhenNetworkConnectionIsUnavailable() {
when(mockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo);
when(mockNetworkInfo.isConnected()).thenReturn(false);
assertThat(merlinsBeard.isConnected()).isFalse();
}
@Test
public void returnFalseForIsConnectedWhenNetworkConnectionIsNull() {
when(mockConnectivityManager.getActiveNetworkInfo()).thenReturn(null);
assertThat(merlinsBeard.isConnected()).isFalse();
}
@Test
public void returnTrueForIsConnectedWhenNetworkConnectionIsAvailable() {
when(mockConnectivityManager.getActiveNetworkInfo()).thenReturn(mockNetworkInfo);
when(mockNetworkInfo.isConnected()).thenReturn(true);
assertThat(merlinsBeard.isConnected()).isTrue();
}
@Test
public void returnTrueForIsConnectedToWifiWhenNetworkConnectedToWifiIsConnected() {
when(mockConnectivityManager.getNetworkInfo(WIFI.getValue())).thenReturn(mockNetworkInfo);
when(mockNetworkInfo.isConnected()).thenReturn(true);
assertThat(merlinsBeard.isConnectedTo(WIFI)).isTrue();
}
@Test
public void returnFalseForIsConnectedToWifiWhenNetworkConnectedToWifiIsNotConnected() {
when(mockConnectivityManager.getNetworkInfo(WIFI.getValue())).thenReturn(mockNetworkInfo);
when(mockNetworkInfo.isConnected()).thenReturn(false);
assertThat(merlinsBeard.isConnectedTo(WIFI)).isFalse();
}
@Test
public void returnFalseForIsConnectedToWifiWhenNetworkConnectionIsNotAvailable() {
when(mockConnectivityManager.getNetworkInfo(WIFI.getValue())).thenReturn(null);
assertThat(merlinsBeard.isConnectedTo(WIFI)).isFalse();
}
}
|
package com.felhr.usbserial;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbRequest;
import android.util.Log;
import java.util.concurrent.atomic.AtomicBoolean;
public class CH34xSerialDevice extends UsbSerialDevice
{
private static final String CLASS_ID = CH34xSerialDevice.class.getSimpleName();
private static final int DEFAULT_BAUDRATE = 9600;
private static final int REQTYPE_HOST_FROM_DEVICE = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_IN;
private static final int REQTYPE_HOST_TO_DEVICE = 0x40;
private static final int CH341_REQ_WRITE_REG = 0x9A;
private static final int CH341_REQ_READ_REG = 0x95;
private static final int CH341_REG_BREAK1 = 0x05;
private static final int CH341_REG_BREAK2 = 0x18;
private static final int CH341_NBREAK_BITS_REG1 = 0x01;
private static final int CH341_NBREAK_BITS_REG2 = 0x40;
// Baud rates values
private static final int CH34X_300_1312 = 0xd980;
private static final int CH34X_300_0f2c = 0xeb;
private static final int CH34X_600_1312 = 0x6481;
private static final int CH34X_600_0f2c = 0x76;
private static final int CH34X_1200_1312 = 0xb281;
private static final int CH34X_1200_0f2c = 0x3b;
private static final int CH34X_2400_1312 = 0xd981;
private static final int CH34X_2400_0f2c = 0x1e;
private static final int CH34X_4800_1312 = 0x6482;
private static final int CH34X_4800_0f2c = 0x0f;
private static final int CH34X_9600_1312 = 0xb282;
private static final int CH34X_9600_0f2c = 0x08;
private static final int CH34X_19200_1312 = 0xd982;
private static final int CH34X_19200_0f2c_rest = 0x07;
private static final int CH34X_38400_1312 = 0x6483;
private static final int CH34X_57600_1312 = 0x9883;
private static final int CH34X_115200_1312 = 0xcc83;
private static final int CH34X_230400_1312 = 0xe683;
private static final int CH34X_460800_1312 = 0xf383;
private static final int CH34X_921600_1312 = 0xf387;
// Parity values
private static final int CH34X_PARITY_NONE = 0xc3;
private static final int CH34X_PARITY_ODD = 0xcb;
private static final int CH34X_PARITY_EVEN = 0xdb;
private static final int CH34X_PARITY_MARK = 0xeb;
private static final int CH34X_PARITY_SPACE = 0xfb;
//Flow control values
private static final int CH34X_FLOW_CONTROL_NONE = 0x0000;
private static final int CH34X_FLOW_CONTROL_RTS_CTS = 0x0101;
private static final int CH34X_FLOW_CONTROL_DSR_DTR = 0x0202;
// XON/XOFF doesnt appear to be supported directly from hardware
private UsbInterface mInterface;
private UsbEndpoint inEndpoint;
private UsbEndpoint outEndpoint;
private UsbRequest requestIN;
private FlowControlThread flowControlThread;
private UsbCTSCallback ctsCallback;
private UsbDSRCallback dsrCallback;
private boolean rtsCtsEnabled;
private boolean dtrDsrEnabled;
private boolean dtr = false;
private boolean rts = false;
private boolean ctsState = false;
private boolean dsrState = false;
public CH34xSerialDevice(UsbDevice device, UsbDeviceConnection connection)
{
super(device, connection);
}
public CH34xSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
{
super(device, connection);
rtsCtsEnabled = false;
dtrDsrEnabled = false;
mInterface = device.getInterface(iface >= 0 ? iface : 0);
}
@Override
public boolean open()
{
boolean ret = openCH34X();
if(ret)
{
// Initialize UsbRequest
requestIN = new UsbRequest();
requestIN.initialize(connection, inEndpoint);
// Restart the working thread if it has been killed before and get and claim interface
restartWorkingThread();
restartWriteThread();
// Pass references to the threads
setThreadsParams(requestIN, outEndpoint);
asyncMode = true;
return true;
}else
{
return false;
}
}
@Override
public void close()
{
killWorkingThread();
killWriteThread();
connection.releaseInterface(mInterface);
}
@Override
public boolean syncOpen()
{
boolean ret = openCH34X();
if(ret)
{
setSyncParams(inEndpoint, outEndpoint);
asyncMode = false;
return true;
}else
{
return false;
}
}
@Override
public void syncClose()
{
connection.releaseInterface(mInterface);
}
@Override
public void setBaudRate(int baudRate)
{
if(baudRate <= 300)
{
int ret = setBaudRate(CH34X_300_1312, CH34X_300_0f2c); //300
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 300 && baudRate <= 600)
{
int ret = setBaudRate(CH34X_600_1312, CH34X_600_0f2c); //600
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 600 && baudRate <= 1200)
{
int ret = setBaudRate(CH34X_1200_1312, CH34X_1200_0f2c); //1200
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 1200 && baudRate <=2400)
{
int ret = setBaudRate(CH34X_2400_1312, CH34X_2400_0f2c); //2400
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 2400 && baudRate <= 4800)
{
int ret = setBaudRate(CH34X_4800_1312, CH34X_4800_0f2c); //4800
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 4800 && baudRate <= 9600)
{
int ret = setBaudRate(CH34X_9600_1312, CH34X_9600_0f2c); //9600
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 9600 && baudRate <= 19200)
{
int ret = setBaudRate(CH34X_19200_1312, CH34X_19200_0f2c_rest); //19200
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 19200 && baudRate <= 38400)
{
int ret = setBaudRate(CH34X_38400_1312, CH34X_19200_0f2c_rest); //38400
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 38400 && baudRate <= 57600)
{
int ret = setBaudRate(CH34X_57600_1312, CH34X_19200_0f2c_rest); //57600
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 57600 && baudRate <= 115200) //115200
{
int ret = setBaudRate(CH34X_115200_1312, CH34X_19200_0f2c_rest);
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 115200 && baudRate <= 230400) //230400
{
int ret = setBaudRate(CH34X_230400_1312, CH34X_19200_0f2c_rest);
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 230400 && baudRate <= 460800) //460800
{
int ret = setBaudRate(CH34X_460800_1312, CH34X_19200_0f2c_rest);
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}else if(baudRate > 460800 && baudRate <= 921600)
{
int ret = setBaudRate(CH34X_921600_1312, CH34X_19200_0f2c_rest);
if(ret == -1)
Log.i(CLASS_ID, "SetBaudRate failed!");
}
}
@Override
public void setDataBits(int dataBits)
{
// TODO Auto-generated method stub
}
@Override
public void setStopBits(int stopBits)
{
// TODO Auto-generated method stub
}
@Override
public void setParity(int parity)
{
switch(parity)
{
case UsbSerialInterface.PARITY_NONE:
setCh340xParity(CH34X_PARITY_NONE);
break;
case UsbSerialInterface.PARITY_ODD:
setCh340xParity(CH34X_PARITY_ODD);
break;
case UsbSerialInterface.PARITY_EVEN:
setCh340xParity(CH34X_PARITY_EVEN);
break;
case UsbSerialInterface.PARITY_MARK:
setCh340xParity(CH34X_PARITY_MARK);
break;
case UsbSerialInterface.PARITY_SPACE:
setCh340xParity(CH34X_PARITY_SPACE);
break;
default:
break;
}
}
@Override
public void setFlowControl(int flowControl)
{
switch(flowControl)
{
case UsbSerialInterface.FLOW_CONTROL_OFF:
setCh340xFlow(CH34X_FLOW_CONTROL_NONE);
break;
case UsbSerialInterface.FLOW_CONTROL_RTS_CTS:
setCh340xFlow(CH34X_FLOW_CONTROL_RTS_CTS);
break;
case UsbSerialInterface.FLOW_CONTROL_DSR_DTR:
setCh340xFlow(CH34X_FLOW_CONTROL_DSR_DTR);
break;
default:
break;
}
}
@Override
public void setRTS(boolean state)
{
rts = state;
writeHandshakeByte();
}
@Override
public void setDTR(boolean state)
{
dtr = state;
writeHandshakeByte();
}
@Override
public void getCTS(UsbCTSCallback ctsCallback)
{
//TODO
}
@Override
public void getDSR(UsbDSRCallback dsrCallback)
{
//TODO
}
@Override
public void getBreak(UsbBreakCallback breakCallback)
{
//TODO
}
@Override
public void getFrame(UsbFrameCallback frameCallback)
{
//TODO
}
@Override
public void getOverrun(UsbOverrunCallback overrunCallback)
{
//TODO
}
@Override
public void getParity(UsbParityCallback parityCallback)
{
//TODO
}
private boolean openCH34X()
{
if(connection.claimInterface(mInterface, true))
{
Log.i(CLASS_ID, "Interface succesfully claimed");
}else
{
Log.i(CLASS_ID, "Interface could not be claimed");
return false;
}
// Assign endpoints
int numberEndpoints = mInterface.getEndpointCount();
for(int i=0;i<=numberEndpoints-1;i++)
{
UsbEndpoint endpoint = mInterface.getEndpoint(i);
if(endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK
&& endpoint.getDirection() == UsbConstants.USB_DIR_IN)
{
inEndpoint = endpoint;
}else if(endpoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK
&& endpoint.getDirection() == UsbConstants.USB_DIR_OUT)
{
outEndpoint = endpoint;
}
}
return init() == 0;
}
private int init()
{
/*
Init the device at 9600 bauds
*/
if(setControlCommandOut(0xa1, 0xc29c, 0xb2b9, null) < 0)
{
Log.i(CLASS_ID, "init failed!
return -1;
}
if(setControlCommandOut(0xa4, 0xdf, 0, null) < 0)
{
Log.i(CLASS_ID, "init failed!
return -1;
}
if(setControlCommandOut(0xa4, 0x9f, 0, null) < 0)
{
Log.i(CLASS_ID, "init failed!
return -1;
}
if(checkState("init #4", 0x95, 0x0706, new int[]{0x9f, 0xee}) == -1)
return -1;
if(setControlCommandOut(0x9a, 0x2727, 0x0000, null) < 0)
{
Log.i(CLASS_ID, "init failed!
return -1;
}
if(setControlCommandOut(0x9a, 0x1312, 0xb282, null) < 0)
{
Log.i(CLASS_ID, "init failed!
return -1;
}
if(setControlCommandOut(0x9a, 0x0f2c, 0x0008, null) < 0)
{
Log.i(CLASS_ID, "init failed!
return -1;
}
if(setControlCommandOut(0x9a, 0x2518, 0x00c3, null) < 0)
{
Log.i(CLASS_ID, "init failed!
return -1;
}
if(checkState("init #9", 0x95, 0x0706, new int[]{0x9f, 0xee}) == -1)
return -1;
if(setControlCommandOut(0x9a, 0x2727, 0x0000, null) < 0)
{
Log.i(CLASS_ID, "init failed!
return -1;
}
return 0;
}
private int setBaudRate(int index1312, int index0f2c)
{
if(setControlCommandOut(CH341_REQ_WRITE_REG, 0x1312, index1312, null) < 0)
return -1;
if(setControlCommandOut(CH341_REQ_WRITE_REG, 0x0f2c, index0f2c, null) < 0)
return -1;
if(checkState("set_baud_rate", 0x95, 0x0706, new int[]{0x9f, 0xee}) == -1)
return -1;
if(setControlCommandOut(CH341_REQ_WRITE_REG, 0x2727, 0, null) < 0)
return -1;
return 0;
}
private int setCh340xParity(int indexParity)
{
if(setControlCommandOut(CH341_REQ_WRITE_REG, 0x2518, indexParity, null) < 0)
return -1;
if(checkState("set_parity", 0x95, 0x0706, new int[]{0x9f, 0xee}) == -1)
return -1;
if(setControlCommandOut(CH341_REQ_WRITE_REG, 0x2727, 0, null) < 0)
return -1;
return 0;
}
private int setCh340xFlow(int flowControl)
{
if(checkState("set_flow_control", 0x95, 0x0706, new int[]{0x9f, 0xee}) == -1)
return -1;
if(setControlCommandOut(CH341_REQ_WRITE_REG, 0x2727, flowControl, null) == -1)
return -1;
return 0;
}
private int checkState(String msg, int request, int value, int[] expected)
{
byte[] buffer = new byte[expected.length];
int ret = setControlCommandIn(request, value, 0, buffer);
if (ret != expected.length)
{
Log.i(CLASS_ID, ("Expected " + expected.length + " bytes, but get " + ret + " [" + msg + "]"));
return -1;
}else
{
return 0;
}
}
private boolean checkCTS()
{
byte[] buffer = new byte[2];
int ret = setControlCommandIn(CH341_REQ_READ_REG, 0x0706, 0, buffer);
if(ret != 2)
{
Log.i(CLASS_ID, ("Expected " + "2" + " bytes, but get " + ret));
return false;
}
if((buffer[0] & 0x01) == 0x00) //CTS ON
{
return true;
}else // CTS OFF
{
return false;
}
}
private boolean checkDSR()
{
byte[] buffer = new byte[2];
int ret = setControlCommandIn(CH341_REQ_READ_REG, 0x0706, 0, buffer);
if(ret != 2)
{
Log.i(CLASS_ID, ("Expected " + "2" + " bytes, but get " + ret));
return false;
}
if((buffer[1] & 0x01) == 0x00) //DSR ON
{
return true;
}else // DSR OFF
{
return false;
}
}
private int writeHandshakeByte()
{
if(setControlCommandOut(0xa4, ~((dtr ? 1 << 5 : 0) | (rts ? 1 << 6 : 0)), 0, null) < 0)
{
Log.i(CLASS_ID, "Failed to set handshake byte");
return -1;
}
return 0;
}
private int setControlCommandOut(int request, int value, int index, byte[] data)
{
int dataLength = 0;
if(data != null)
{
dataLength = data.length;
}
int response = connection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, value, index, data, dataLength, USB_TIMEOUT);
Log.i(CLASS_ID,"Control Transfer Response: " + String.valueOf(response));
return response;
}
private int setControlCommandIn(int request, int value, int index, byte[] data)
{
int dataLength = 0;
if(data != null)
{
dataLength = data.length;
}
int response = connection.controlTransfer(REQTYPE_HOST_FROM_DEVICE, request, value, index, data, dataLength, USB_TIMEOUT);
Log.i(CLASS_ID,"Control Transfer Response: " + String.valueOf(response));
return response;
}
private void startFlowControlThread()
{
flowControlThread.start();
}
private void stopFlowControlThread()
{
flowControlThread.stopThread();
flowControlThread = null;
}
private class FlowControlThread extends Thread
{
private long time = 100; // 100ms
private boolean firstTime;
private AtomicBoolean keep;
public FlowControlThread()
{
keep = new AtomicBoolean(true);
firstTime = true;
}
@Override
public void run()
{
while(keep.get())
{
if(!firstTime)
{
// Check CTS status
if(rtsCtsEnabled)
{
boolean cts = pollForCTS();
if(ctsState != cts)
{
ctsState = !ctsState;
if (ctsCallback != null)
ctsCallback.onCTSChanged(ctsState);
}
}
// Check DSR status
if(dtrDsrEnabled)
{
boolean dsr = pollForDSR();
if(dsrState != dsr)
{
dsrState = !dsrState;
if (dsrCallback != null)
dsrCallback.onDSRChanged(dsrState);
}
}
}else
{
if(rtsCtsEnabled && ctsCallback != null)
ctsCallback.onCTSChanged(ctsState);
if(dtrDsrEnabled && dsrCallback != null)
dsrCallback.onDSRChanged(dsrState);
firstTime = false;
}
}
}
public void stopThread()
{
keep.set(false);
}
public boolean pollForCTS()
{
synchronized(this)
{
try
{
wait(time);
} catch(InterruptedException e)
{
e.printStackTrace();
}
}
return checkCTS();
}
public boolean pollForDSR()
{
synchronized(this)
{
try
{
wait(time);
} catch(InterruptedException e)
{
e.printStackTrace();
}
}
return checkDSR();
}
}
}
|
package application;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* The main class to store and provide the URLs for the bot.
*/
public class UrlPool
{
/**
* All checked URL list.
*/
private ArrayList<String> checkedUrls;
/**
* URL list where the keywords was found.
*/
private ArrayList<String> foundUrls;
/**
* URL queue to add new found links and take the links for BotThead.
*/
private LinkedList<String> urlQueue;
/**
* Class constructor.
*/
public UrlPool()
{
checkedUrls = new ArrayList<>();
foundUrls = new ArrayList<>();
urlQueue = new LinkedList<>();
}
/**
* Get next URL to check.
*
* @return the next URL to check or null in case of empty queue
*/
public synchronized String getNextUrlToCheck()
{
return urlQueue.pollFirst();
}
/**
* Add URL to the queue if it has not be check yet.
*
* @param url to add
*/
public synchronized void addUrlToCheck(String url)
{
if (false == checkedUrls.contains(url) && false == urlQueue.contains(url)) {
urlQueue.addLast(url);
}
}
/**
* Add URL list to the queue if it has not be check yet.
*
* @param urls list to add
*/
public synchronized void addUrlToCheck(ArrayList<String> urls)
{
for (String url : urls) {
addUrlToCheck(url);
}
}
/**
* Add URL to found list.
*
* @param url to add
*/
public synchronized void addUrlAssFound(String url)
{
if (false == foundUrls.contains(url)) {
foundUrls.add(url);
} else {
System.out.println("Trying to add URL to found list, but it is already there.");
}
}
/**
* Mark URL as checked.
*
* @param url to mark
*/
public synchronized void markUrlAsChecked(String url) {
if (false == checkedUrls.contains(url)) {
checkedUrls.add(url);
}
}
/**
* Unmark URL as checked.
*
* @param url to mark
*/
public synchronized void unmarkUrlAsChecked(String url) {
if (checkedUrls.contains(url)) {
checkedUrls.remove(url);
}
}
/**
* Get total number of checked URLs.
*
* @return total checked
*/
public synchronized int getTotalCheckedUrl()
{
return checkedUrls.size();
}
/**
* Get total number URLs where the keyword was found.
*
* @return total found
*/
public synchronized int getTotalFoundUrl()
{
return foundUrls.size();
}
/**
* Get a list of URLs where the keyword was found.
*
* @return found URLs
*/
public synchronized ArrayList<String> getFoundUrls()
{
return foundUrls;
}
}
|
package exercise.cpc.chess.board;
//Please see the AUTHORS file for details.
import java.util.ArrayList;
import java.util.List;
import exercise.cpc.chess.pieces.piece.ChessPiece;
import exercise.cpc.chess.pieces.piece.position.Position;
import exercise.cpc.data.input.impl.dimensions.DataInputDimensions;
public class ChessBoard {
// TODO for tests add what pieces cross in what places
private List<Position> freePositions = new ArrayList<Position>();
private List<Position> piecesPositions = new ArrayList<Position>();
private DataInputDimensions dimensions;
public ChessBoard(DataInputDimensions dimensions) {
this.dimensions = dimensions;
}
public void initialize() {
for (int y = 0; y < dimensions.getM(); ++y) {
for (int x = 0; x < dimensions.getN(); ++x) {
freePositions.add(new Position(x, y));
}
}
}
/**
* Only if could place piece on the board will return true.
* Then if false this board is not useful.
*
* @param piece
* @return false if couldn't place given piece on the board
* true if could.
*/
public boolean placePieceInPlaceWhereHasNotGotCollisions(ChessPiece piece) {
if (!isValid(piece.getX(), piece.getY())) {
return false;
}
System.out.println(freePositions.size());
// just for debug
boolean state = piece.checkCollisions(freePositions, piecesPositions);
System.out.println(freePositions.size());
return state;
}
private boolean isValid(int x, int y) {
if (x < 0 || x > dimensions.getN() || y < 0 || y > dimensions.getM()) {
return false;
}
return true;
}
}
|
package fi.csc.microarray.config;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.UUID;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import fi.csc.microarray.util.XmlUtil;
/**
* Simple tool for centrally changing configuration of the Chipster server environment.
*
* @author Aleksi Kallio
*
*/
public class ConfigTool {
static final String CURRENT_R_VERSION = "R-2.9";
private final String brokerDir = "activemq";
private final String webstartDir = "webstart";
private final static String[] componentDirsWithConfig = new String[] {
"comp",
"auth",
"fileserver",
"manager",
"client",
"webstart"
};
private String[][] configs = new String[][] {
{"message broker (ActiveMQ) host", "myhost.mydomain"},
{"message broker protocol", "tcp"},
{"message broker port", "61616"},
{"file broker host", "myhost.mydomain"},
{"file broker port", "8080"},
{"URL of Web Start files", "http://myhost.mydomain"},
{"Web Start www-server port", "8081"},
{"manager www-console port", "8082"},
{CURRENT_R_VERSION + ".x command", "/opt/chipster/tools/" + CURRENT_R_VERSION + ".0/"},
{"max. simultanous jobs (more recommended when compute service on separate node)", "3"}
};
private final int KEY_INDEX = 0;
private final int VAL_INDEX = 1;
private final int BROKER_HOST_INDEX = 0;
private final int BROKER_PROTOCOL_INDEX = 1;
private final int BROKER_PORT_INDEX = 2;
private final int FILEBROKER_HOST_INDEX = 3;
private final int FILEBROKER_PORT_INDEX = 4;
private final int WS_CODEBASE_INDEX = 5;
private final int WS_PORT = 6;
private final int MANAGER_PORT = 7;
private final int R_COMMAND_INDEX = 8;
private final int MAX_JOBS_INDEX = 9;
private String[][] passwords = new String[][] {
{"comp", ""},
{"auth", ""},
{"filebroker", ""},
{"manager", ""}
};
private HashMap<String, Document> documentsToWrite = new HashMap<String, Document>();
public ConfigTool() throws ParserConfigurationException {
System.out.println("Chipster ConfigTool");
System.out.println("");
System.out.println("No changes are written before you verify them");
System.out.println("");
}
public static void main(String[] args) throws Exception {
ConfigTool configTool = new ConfigTool();
UpgradeTool upgradeTool = new UpgradeTool();
SetupTool setupTool = new SetupTool();
if (args.length == 0) {
fail();
} else if ("configure".equals(args[0])) {
configTool.configure();
} else if ("genpasswd".equals(args[0])) {
configTool.genpasswd();
} else if ("setup".equals(args[0])) {
setupTool.setup();
} else if (args[0].startsWith("upgrade")) {
String[] parts = args[0].split("_");
int fromMajor = Integer.parseInt(parts[1]);
int toMajor = Integer.parseInt(parts[2]);
if (args.length > 1) {
upgradeTool.upgrade(new File(args[1]), fromMajor, toMajor);
} else {
System.out.println("Please specify location of the old installation directory as an argument (e.g., \"./upgrade.sh /opt/chipster-1.2.3\")");
}
} else {
fail();
}
}
private static void fail() {
System.out.println("Illegal arguments! Please specify one of: configure, genpasswd, setup, upgrade_<major version number of source>_<major version number of target>");
}
private void genpasswd() throws Exception {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// STEP 1. GATHER DATA
// generate passwords
for (int i = 0; i < passwords.length; i++) {
passwords[i][VAL_INDEX] = UUID.randomUUID().toString();
}
// STEP 2. UPDATE CONFIGS
// update all Chipster configs
for (String componentDir : getComponentDirsWithConfig()) {
if (new File(componentDir).exists()) {
File configFile = new File(componentDir + File.separator + DirectoryLayout.CONF_DIR + File.separator + Configuration.CONFIG_FILENAME);
updateChipsterConfigFilePasswords(configFile);
}
}
// update ActiveMQ config
File activemqConfigFile = new File(brokerDir + File.separator + DirectoryLayout.CONF_DIR + File.separator + "activemq.xml");
if (activemqConfigFile.exists()) {
updateActivemqConfigFilePasswords(activemqConfigFile);
}
verifyChanges(in);
} catch (Throwable t) {
t.printStackTrace();
System.err.println("\nQuitting, no changes written to disk!");
return;
}
// STEP 3. WRITE CHANGES
writeChangesToDisk();
}
private void writeChangesToDisk() throws TransformerException, UnsupportedEncodingException, FileNotFoundException {
// write out files
for (String file : documentsToWrite.keySet()) {
System.out.println("Writing changes to " + file + "...");
XmlUtil.printXml(documentsToWrite.get(file), new OutputStreamWriter(new FileOutputStream(file)));
}
System.out.println("\nAll changes successfully written!");
}
public static void verifyChanges(BufferedReader in) throws Exception {
verifyChanges(in, "Please verify changes. Should changes be written to disk");
}
public static void verifyChanges(BufferedReader in, String question) throws Exception {
System.out.println(question + " [yes/no]?");
String answer = in.readLine();
if (!"yes".equals(answer)) {
throw new Exception("User decided to abort");
}
}
public void configure() throws Exception {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// STEP 1. GATHER DATA
// sniff current host
try {
String host = InetAddress.getLocalHost().getHostName();
configs[BROKER_HOST_INDEX][VAL_INDEX] = host;
configs[FILEBROKER_HOST_INDEX][VAL_INDEX] = host;
configs[WS_CODEBASE_INDEX][VAL_INDEX] = "http://" + host + ":8081";
} catch (UnknownHostException e) {
// ignore, sniffing failed
}
// gather required data
for (int i = 0; i < configs.length; i++) {
System.out.println("Please specify " + configs[i][KEY_INDEX] + " [" + configs[i][VAL_INDEX] + "]: ");
String line = in.readLine();
if (!line.trim().equals("")) {
configs[i][VAL_INDEX] = line;
}
}
// STEP 2. UPDATE CONFIGS
// update all Chipster configs
for (String componentDir : getComponentDirsWithConfig()) {
if (new File(componentDir).exists()) {
File configFile = new File(componentDir + File.separator + DirectoryLayout.CONF_DIR + File.separator + Configuration.CONFIG_FILENAME);
updateChipsterConfigFile(configFile);
}
}
File wsClientConfigFile = new File("webstart" + File.separator + DirectoryLayout.WEB_ROOT + File.separator + Configuration.CONFIG_FILENAME);
if (wsClientConfigFile.exists()) {
updateChipsterConfigFile(wsClientConfigFile);
}
File runtimesConfigFile = new File("comp" + File.separator + DirectoryLayout.CONF_DIR + File.separator + "runtimes.xml");
if (runtimesConfigFile.exists()) {
updateRuntimesConfigFile(runtimesConfigFile);
}
// update ActiveMQ config
File activemqConfigFile = new File(brokerDir + File.separator + DirectoryLayout.CONF_DIR + File.separator + "activemq.xml");
if (activemqConfigFile.exists()) {
updateActivemqConfigFile(activemqConfigFile);
}
// update Web Start config
File wsConfigFile = new File(webstartDir + File.separator + DirectoryLayout.WEB_ROOT + File.separator + "chipster.jnlp");
if (wsConfigFile.exists()) {
updateWsConfigFile(wsConfigFile);
}
verifyChanges(in);
} catch (Throwable t) {
t.printStackTrace();
System.err.println("\nQuitting, no changes written to disk!");
return;
}
// STEP 3. WRITE CHANGES
writeChangesToDisk();
}
private void updateActivemqConfigFile(File configFile) throws Exception {
Document doc = openForUpdating("ActiveMQ", configFile);
Element broker = (Element)doc.getDocumentElement().getElementsByTagName("broker").item(0);
Element transportConnectors = (Element)broker.getElementsByTagName("transportConnectors").item(0);
Element transportConnector = (Element)transportConnectors.getElementsByTagName("transportConnector").item(0); // edit first in the list (could use attribute name to decide right one)..
String uri = configs[BROKER_PROTOCOL_INDEX][VAL_INDEX] + "://" + configs[BROKER_HOST_INDEX][VAL_INDEX] + ":" + configs[BROKER_PORT_INDEX][VAL_INDEX];
updateElementAttribute(transportConnector, "uri", uri);
writeLater(configFile, doc);
}
private void updateWsConfigFile(File configFile) throws Exception {
Document doc = openForUpdating("Web Start", configFile);
Element jnlp = (Element)doc.getDocumentElement();
updateElementAttribute(jnlp, "codebase", configs[WS_CODEBASE_INDEX][VAL_INDEX]);
Element applicationDesc = (Element)jnlp.getElementsByTagName("application-desc").item(0);
NodeList arguments = applicationDesc.getElementsByTagName("argument");
Element lastArgument = (Element)arguments.item(arguments.getLength() - 1);
String url = "http://" + configs[BROKER_HOST_INDEX][VAL_INDEX] + ":" + configs[WS_PORT][VAL_INDEX] + "/" + Configuration.CONFIG_FILENAME;
updateElementValue(lastArgument, "configuration URL (for Web Start)", url);
writeLater(configFile, doc);
}
private void updateActivemqConfigFilePasswords(File configFile) throws Exception {
Document doc = openForUpdating("ActiveMQ", configFile);
Element broker = (Element)doc.getDocumentElement().getElementsByTagName("broker").item(0);
NodeList users = ((Element)((Element)((Element)broker.getElementsByTagName("plugins").item(0)).getElementsByTagName("simpleAuthenticationPlugin").item(0)).getElementsByTagName("users").item(0)).getElementsByTagName("authenticationUser");
for (int i = 0; i < users.getLength(); i++) {
for (int p = 0; p < passwords.length; p++) {
Element user = (Element)users.item(i);
if (user.getAttribute("username").equals(passwords[p][KEY_INDEX])) {
updateElementAttribute(user, "password for " + passwords[p][KEY_INDEX], "password", passwords[p][VAL_INDEX]);
break;
}
}
}
writeLater(configFile, doc);
}
private void updateChipsterConfigFilePasswords(File configFile) throws Exception {
Document doc = openForUpdating("Chipster", configFile);
Element securityModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "security");
Element usernameElement = XmlUtil.getChildWithAttributeValue(securityModule, "entryKey", "username");
String username = ((Element)usernameElement.getElementsByTagName("value").item(0)).getTextContent();
for (int i = 0; i < passwords.length; i++) {
if (username.equals(passwords[i][KEY_INDEX])) {
updateConfigEntryValue(securityModule, "password", passwords[i][VAL_INDEX]);
break;
}
}
writeLater(configFile, doc);
}
private void updateChipsterConfigFile(File configFile) throws Exception {
Document doc = openForUpdating("Chipster", configFile);
Element messagingModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "messaging");
updateConfigEntryValue(messagingModule, "broker-host", configs[BROKER_HOST_INDEX][VAL_INDEX]);
updateConfigEntryValue(messagingModule, "broker-protocol", configs[BROKER_PROTOCOL_INDEX][VAL_INDEX]);
updateConfigEntryValue(messagingModule, "broker-port", configs[BROKER_PORT_INDEX][VAL_INDEX]);
Element filebrokerModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "filebroker");
if (filebrokerModule != null) {
updateConfigEntryValue(filebrokerModule, "port", configs[FILEBROKER_PORT_INDEX][VAL_INDEX]);
updateConfigEntryValue(filebrokerModule, "url", createFilebrokerUrl());
}
Element analyserModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "comp");
if (analyserModule != null) {
updateConfigEntryValue(analyserModule, "max-jobs", configs[MAX_JOBS_INDEX][VAL_INDEX]);
}
Element webstartModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "webstart");
if (webstartModule != null) {
updateConfigEntryValue(webstartModule, "port", configs[WS_PORT][VAL_INDEX]);
}
Element managerModule = XmlUtil.getChildWithAttributeValue(doc.getDocumentElement(), "moduleId", "manager");
if (managerModule != null) {
updateConfigEntryValue(managerModule, "web-console-port", configs[MANAGER_PORT][VAL_INDEX]);
}
writeLater(configFile, doc);
}
private void updateRuntimesConfigFile(File configFile) throws Exception {
boolean ok = false;
Document doc = openForUpdating("Runtimes", configFile);
Element runtimesElement = (Element)doc.getElementsByTagName("runtimes").item(0);
for (Element runtimeElement: XmlUtil.getChildElements(runtimesElement, "runtime")) {
String runtimeName = XmlUtil.getChildElement(runtimeElement, "name").getTextContent();
if (runtimeName.equals(CURRENT_R_VERSION)) {
Element handlerElement = XmlUtil.getChildElement(runtimeElement, "handler");
for (Element parameterElement: XmlUtil.getChildElements(handlerElement, "parameter")) {
String paramName = XmlUtil.getChildElement(parameterElement, "name").getTextContent();
if (paramName.equals("command")) {
Element commandValueElement = XmlUtil.getChildElement(parameterElement, "value");
updateElementValue(commandValueElement, "R-2.6.1 command", configs[R_COMMAND_INDEX][VAL_INDEX]);
ok = true;
}
}
}
}
if (ok) {
writeLater(configFile, doc);
} else {
throw new RuntimeException("Could not update R-2.6.1 command to runtimes.xml");
}
}
private String createFilebrokerUrl() {
return "http://" + configs[FILEBROKER_HOST_INDEX][VAL_INDEX];
}
private void updateConfigEntryValue(Element module, String name, String newValue) {
Element entry = XmlUtil.getChildWithAttributeValue(module, "entryKey", name);
Element value = (Element)entry.getElementsByTagName("value").item(0);
updateElementValue(value, name, newValue);
}
private void updateElementValue(Element element, String logicalName, String newValue) {
System.out.println(" changing " + logicalName + ": " + element.getTextContent() + " -> " + newValue);
element.setTextContent(newValue);
}
private void updateElementAttribute(Element element, String attrName, String attrValue) {
updateElementAttribute(element, attrName, attrName, attrValue);
}
private void updateElementAttribute(Element element, String logicalName, String attrName, String attrValue) {
System.out.println(" changing " + logicalName + ": " + element.getAttribute(attrName) + " -> " + attrValue);
element.setAttribute(attrName, attrValue);
}
private void writeLater(File configFile, Document doc) throws TransformerException, UnsupportedEncodingException, FileNotFoundException {
documentsToWrite.put(configFile.getAbsolutePath(), doc);
System.out.println("");
}
private Document openForUpdating(String name, File configFile) throws SAXException, IOException, ParserConfigurationException {
System.out.println("Updating " + name + " config in " + configFile.getAbsolutePath());
Document doc = XmlUtil.parseFile(configFile);
return doc;
}
public static String[] getComponentDirsWithConfig() {
return componentDirsWithConfig;
}
}
|
package nju.software.jxjs.dao;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import nju.software.jxjs.model.PubXtglYhb;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
/**
* A data access object (DAO) providing persistence and search support for
* PubXtglYhb entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see software.tjspxt.data.dataobject.PubXtglYhb
* @author MyEclipse Persistence Tools
*/
@Repository
public class XtglYhbDao extends BaseDao {
private static final Logger log = LoggerFactory
.getLogger(XtglYhbDao.class);
// property constants
public static final String YHDM = "yhdm";
public static final String YHMC = "yhmc";
public static final String YHKL = "yhkl";
public static final String YHBM = "yhbm";
public static final String KLTS = "klts";
public static final String KLDA = "klda";
public static final String YHSF = "yhsf";
public static final String QJYY = "qjyy";
public static final String GRNZB = "grnzb";
public static final String QTNZB = "qtnzb";
public static final String GRBAJS = "grbajs";
public static final String PHONE = "phone";
public static final String XFQX = "xfqx";
public static final String SSFWZXQX = "ssfwzxqx";
public static final String JBXXJ_CODE = "jbxxjCode";
public static final String FAZT = "fazt";
public static final String FASL = "fasl";
public static final String FYBH = "fybh";
public static final String YHZT = "yhzt";
protected void initDao() {
// do nothing
}
public void save(PubXtglYhb transientInstance) {
log.debug("saving PubXtglYhb instance");
try {
getHibernateTemplate().saveOrUpdate(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(PubXtglYhb persistentInstance) {
log.debug("deleting PubXtglYhb instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public PubXtglYhb findById(java.lang.Integer id) {
log.debug("getting PubXtglYhb instance with id: " + id);
try {
PubXtglYhb instance = (PubXtglYhb) getHibernateTemplate().get(
"software.tjspxt.data.dataobject.PubXtglYhb", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List<PubXtglYhb> findByExample(PubXtglYhb instance) {
log.debug("finding PubXtglYhb instance by example");
try {
List<PubXtglYhb> results = (List<PubXtglYhb>) getHibernateTemplate()
.findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding PubXtglYhb instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from PubXtglYhb as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List<PubXtglYhb> findByYhdm(Object yhdm) {
return findByProperty(YHDM, yhdm);
}
public List<PubXtglYhb> findByYhmc(Object yhmc) {
return findByProperty(YHMC, yhmc);
}
public List<PubXtglYhb> findByYhkl(Object yhkl) {
return findByProperty(YHKL, yhkl);
}
public List<PubXtglYhb> findByYhbm(Object yhbm) {
return findByProperty(YHBM, yhbm);
}
public List<PubXtglYhb> findByKlts(Object klts) {
return findByProperty(KLTS, klts);
}
public List<PubXtglYhb> findByKlda(Object klda) {
return findByProperty(KLDA, klda);
}
public List<PubXtglYhb> findByYhsf(Object yhsf) {
return findByProperty(YHSF, yhsf);
}
public List<PubXtglYhb> findByQjyy(Object qjyy) {
return findByProperty(QJYY, qjyy);
}
public List<PubXtglYhb> findByGrnzb(Object grnzb) {
return findByProperty(GRNZB, grnzb);
}
public List<PubXtglYhb> findByQtnzb(Object qtnzb) {
return findByProperty(QTNZB, qtnzb);
}
public List<PubXtglYhb> findByGrbajs(Object grbajs) {
return findByProperty(GRBAJS, grbajs);
}
public List<PubXtglYhb> findByPhone(Object phone) {
return findByProperty(PHONE, phone);
}
public List<PubXtglYhb> findByXfqx(Object xfqx) {
return findByProperty(XFQX, xfqx);
}
public List<PubXtglYhb> findBySsfwzxqx(Object ssfwzxqx) {
return findByProperty(SSFWZXQX, ssfwzxqx);
}
public List<PubXtglYhb> findByJbxxjCode(Object jbxxjCode) {
return findByProperty(JBXXJ_CODE, jbxxjCode);
}
public List<PubXtglYhb> findByFazt(Object fazt) {
return findByProperty(FAZT, fazt);
}
public List<PubXtglYhb> findByFasl(Object fasl) {
return findByProperty(FASL, fasl);
}
public List<PubXtglYhb> findByFybh(Object fybh) {
return findByProperty(FYBH, fybh);
}
public List<PubXtglYhb> findByYhzt(Object yhzt) {
return findByProperty(YHZT, yhzt);
}
public List findAll() {
log.debug("finding all PubXtglYhb instances");
try {
String queryString = "from PubXtglYhb";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public PubXtglYhb merge(PubXtglYhb detachedInstance) {
log.debug("merging PubXtglYhb instance");
try {
PubXtglYhb result = (PubXtglYhb) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(PubXtglYhb instance) {
log.debug("attaching dirty PubXtglYhb instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(PubXtglYhb instance) {
log.debug("attaching clean PubXtglYhb instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
@SuppressWarnings("unchecked")
public List<PubXtglYhb> getXtyhList(long fybh, String yhdm, String yhmc,
String yhbm, String yhsf, String yhzt) {
String hql = "from PubXtglYhb where fybh=" + fybh;
if (yhdm != null) {
hql += " and yhdm like '%" + yhdm + "%'";
}
if (yhmc != null) {
hql += " and yhmc like '%" + yhmc + "%'";
}
if (!yhbm.equals("")) {
hql += " and yhbm = " + Long.parseLong(yhbm);
}
if (!yhsf.equals("")) {
hql += " and yhsf = '" + yhsf + "'";
}
if (!yhzt.equals("")) {
hql += " and yhzt=" + (yhzt.equals("true") ? 1 : 0);
}
if (log.isInfoEnabled()) {
log.info("getXtyhList(long,String,String,String,String,String) by sql: "
+ hql);
}
return (List<PubXtglYhb>) getHibernateTemplate().find(hql);
}
public boolean getXtyhNumberbyBm(long yhbm){
String hql = "select count(*) from PubXtglYhb where yhbm = " + yhbm;
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query query = s.createQuery(hql);
long count = 0;
if (query.uniqueResult() != null)
count = (Long) query.uniqueResult();
return count > 0 ? true : false;
}
public long getMaxYhbh() {
String hql = "select max(yhbh) from PubXtglYhb";
Session s = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
Query query = s.createQuery(hql);
long maxbh = 0;
if (query.uniqueResult() != null)
maxbh = (Long) query.uniqueResult();
return maxbh;
}
public PubXtglYhb getPubXtglYhbByYhdm(String yhdm) {
String hql = "from PubXtglYhb where yhdm=?";
List<PubXtglYhb> PubXtglYhbs = (List<PubXtglYhb>) getHibernateTemplate().find(hql, yhdm);
if (null == PubXtglYhbs)
PubXtglYhbs = new ArrayList<PubXtglYhb>();
return PubXtglYhbs.size() == 0 ? null : PubXtglYhbs.get(0);
}
public PubXtglYhb getPubXtglYhbByYhmc(String yhmc) {
String hql = "from PubXtglYhb where yhdm=?";
List<PubXtglYhb> PubXtglYhbs = (List<PubXtglYhb>) getHibernateTemplate().find(hql, yhmc);
if (null == PubXtglYhbs)
PubXtglYhbs = new ArrayList<PubXtglYhb>();
return PubXtglYhbs.size() == 0 ? null : PubXtglYhbs.get(0);
}
public static XtglYhbDao getFromApplicationContext(ApplicationContext ctx) {
return (XtglYhbDao) ctx.getBean("PubXtglYhbDAO");
}
}
|
package frc.team4215.stronghold;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Victor;
import jaci.openrio.toast.lib.log.Logger;
import jaci.openrio.toast.lib.module.IterativeModule;
import jaci.openrio.toast.lib.registry.Registrar;
public class RobotModule extends IterativeModule {
Victor left;
Victor right;
Victor left2;
Victor right2;
DriveTrain chassis;
Joystick leftStick;
Joystick rightStick;
Joystick thirdstick;
UI driveStation;
UltraSonic ult;
public static Logger logger;
private static String ModuleName =
"stronghold";
private static String ModuleVersion =
"0.0.2";
@Override
public String getModuleName() {
return ModuleName;
}
@Override
public String getModuleVersion() {
return ModuleVersion;
}
@Override
public void robotInit() {
logger = new Logger("stronghold", Logger.ATTR_DEFAULT);
left = Registrar.victor(3);
left2 = Registrar.victor(1);
right = Registrar.victor(2);
right2 = Registrar.victor(0);
chassis = new DriveTrain(left,left2, right,right2);
rightStick = new Joystick(1);
thirdstick = new Joystick(2);
driveStation = new UI(rightStick, thirdstick);
ult = new UltraSonic(3);
// I2CGyro.initGyro();
// I2CGyro.pingerStart();
I2CAccel.initAccel();
I2CAccel.pingerStart();
}
@Override
public void teleopInit(){
}
@Override
public void teleopPeriodic(){
/*
double[] inputs = driveStation.getInputs();
chassis.drive(inputs[0], inputs[1]);
*/
int[] accel = I2CAccel.getAccel();
logger.info(accel[0] + " ,"
+ accel[1] + " ,"
+ accel[2]);
}
@Override
public void disabledInit(){
I2CAccel.pingerStop();
}
@Override
public void autonomousPeriodic(){
}
}
|
package graphql.parser;
import graphql.Internal;
import graphql.language.SourceLocation;
import org.antlr.v4.runtime.Token;
@Internal
public class SourceLocationHelper {
public static SourceLocation mkSourceLocation(MultiSourceReader multiSourceReader, Token token) {
// multi source reader lines are 0 based while Antler lines are 1's based
// Antler columns ironically are 0 based - go figure!
int tokenLine = token.getLine() - 1;
MultiSourceReader.SourceAndLine sourceAndLine = multiSourceReader.getSourceAndLineFromOverallLine(tokenLine);
// graphql spec says line numbers and columns start at 1
int line = sourceAndLine.getLine() + 1;
int column = token.getCharPositionInLine() + 1;
return new SourceLocation(line, column, sourceAndLine.getSourceName());
}
}
|
package graphql.schema;
import graphql.AssertException;
import graphql.Internal;
import graphql.PublicApi;
import graphql.language.InterfaceTypeDefinition;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
import static graphql.Assert.assertNotNull;
import static graphql.Assert.assertValidName;
import static java.lang.String.format;
@PublicApi
public class GraphQLInterfaceType implements GraphQLType, GraphQLOutputType, GraphQLFieldsContainer, GraphQLCompositeType, GraphQLUnmodifiedType, GraphQLNullableType {
private final String name;
private final String description;
private final Map<String, GraphQLFieldDefinition> fieldDefinitionsByName = new LinkedHashMap<>();
private final TypeResolver typeResolver;
private final InterfaceTypeDefinition definition;
@Internal
public GraphQLInterfaceType(String name, String description, List<GraphQLFieldDefinition> fieldDefinitions, TypeResolver typeResolver) {
this(name, description, fieldDefinitions, typeResolver, null);
}
@Internal
public GraphQLInterfaceType(String name, String description, List<GraphQLFieldDefinition> fieldDefinitions, TypeResolver typeResolver, InterfaceTypeDefinition definition) {
assertValidName(name);
assertNotNull(typeResolver, "typeResolver can't null");
assertNotNull(fieldDefinitions, "fieldDefinitions can't null");
this.name = name;
this.description = description;
buildDefinitionMap(fieldDefinitions);
this.typeResolver = typeResolver;
this.definition = definition;
}
private void buildDefinitionMap(List<GraphQLFieldDefinition> fieldDefinitions) {
for (GraphQLFieldDefinition fieldDefinition : fieldDefinitions) {
String name = fieldDefinition.getName();
if (fieldDefinitionsByName.containsKey(name))
throw new AssertException(format("Duplicated definition for field '%s' in interface '%s'", name, this.name));
fieldDefinitionsByName.put(name, fieldDefinition);
}
}
public GraphQLFieldDefinition getFieldDefinition(String name) {
return fieldDefinitionsByName.get(name);
}
public List<GraphQLFieldDefinition> getFieldDefinitions() {
return new ArrayList<>(fieldDefinitionsByName.values());
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public TypeResolver getTypeResolver() {
return typeResolver;
}
public InterfaceTypeDefinition getDefinition() {
return definition;
}
@Override
public String toString() {
return "GraphQLInterfaceType{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", fieldDefinitionsByName=" + fieldDefinitionsByName.keySet() +
", typeResolver=" + typeResolver +
'}';
}
public static Builder newInterface() {
return new Builder();
}
@PublicApi
public static class Builder {
private String name;
private String description;
private List<GraphQLFieldDefinition> fields = new ArrayList<>();
private TypeResolver typeResolver;
private InterfaceTypeDefinition definition;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Builder definition(InterfaceTypeDefinition definition) {
this.definition = definition;
return this;
}
public Builder field(GraphQLFieldDefinition fieldDefinition) {
fields.add(fieldDefinition);
return this;
}
/**
* Take a field builder in a function definition and apply. Can be used in a jdk8 lambda
* e.g.:
* <pre>
* {@code
* field(f -> f.name("fieldName"))
* }
* </pre>
*
* @param builderFunction a supplier for the builder impl
*
* @return this
*/
public Builder field(UnaryOperator<GraphQLFieldDefinition.Builder> builderFunction) {
assertNotNull(builderFunction, "builderFunction can't be null");
GraphQLFieldDefinition.Builder builder = GraphQLFieldDefinition.newFieldDefinition();
builder = builderFunction.apply(builder);
return field(builder);
}
/**
* Same effect as the field(GraphQLFieldDefinition). Builder.build() is called
* from within
*
* @param builder an un-built/incomplete GraphQLFieldDefinition
*
* @return this
*/
public Builder field(GraphQLFieldDefinition.Builder builder) {
this.fields.add(builder.build());
return this;
}
public Builder fields(List<GraphQLFieldDefinition> fieldDefinitions) {
assertNotNull(fieldDefinitions, "fieldDefinitions can't be null");
fields.addAll(fieldDefinitions);
return this;
}
public Builder typeResolver(TypeResolver typeResolver) {
this.typeResolver = typeResolver;
return this;
}
public GraphQLInterfaceType build() {
return new GraphQLInterfaceType(name, description, fields, typeResolver, definition);
}
}
}
|
package hudson.plugins.antexec;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.model.*;
import java.io.IOException;
import java.io.PrintStream;
public class AntExecUtils {
public static FilePath getAntHome(AbstractBuild build, PrintStream logger, EnvVars env, Boolean isUnix, String antHome, Boolean verbose) throws IOException, InterruptedException {
String envAntHome = env.get("ANT_HOME");
String useAntHome = null;
String antExe = isUnix ? "/bin/ant" : "\\bin\\ant.bat";
//Setup ANT_HOME from Environment or job configuration screen
if (envAntHome != null && envAntHome.length() > 0 && !envAntHome.equals("")) {
useAntHome = envAntHome;
if (verbose != null && verbose)
logger.println(Messages.AntExec_AntHomeEnvVarFound(useAntHome));
} else {
if (verbose != null && verbose) logger.println(Messages.AntExec_AntHomeEnvVarNotFound());
}
//Forcing configured ANT_HOME in Environment
if (antHome != null && antHome.length() > 0 && !antHome.equals("")) {
if (useAntHome != null) {
logger.println(Messages._AntExec_AntHomeReplacing(useAntHome, antHome));
} else {
logger.println(Messages._AntExec_AntHomeReplacing("", antHome));
if (build.getBuiltOn().createPath(antHome).exists()) {
logger.println(build.getBuiltOn().createPath(antHome) + " exists!");
}
}
useAntHome = antHome;
//Change ANT_HOME in environment
env.put("ANT_HOME", useAntHome);
logger.println(Messages.AntExec_EnvironmentChanged("ANT_HOME", useAntHome));
//Add ANT_HOME/bin into the environment PATH
String newAntPath = isUnix ? useAntHome + "/bin:" + env.get("PATH") : useAntHome + "\\bin;" + env.get("PATH");
env.put("PATH", newAntPath);
logger.println(Messages.AntExec_EnvironmentChanged("PATH", newAntPath));
//Add ANT_HOME/lib into the environment LD_LIBRARY_PATH
if(isUnix) {
env.put("LD_LIBRARY_PATH", useAntHome + "/lib:"+env.get("LD_LIBRARY_PATH"));
logger.println(Messages.AntExec_EnvironmentAdded("LD_LIBRARY_PATH", useAntHome + "/lib"));
}
if (env.containsKey("JAVA_HOME")) {
env.put("PATH", isUnix ? env.get("JAVA_HOME") + "/bin:" + env.get("PATH") : env.get("JAVA_HOME") + "\\bin;" + env.get("PATH"));
logger.println(Messages.AntExec_EnvironmentAdded("PATH", isUnix ? env.get("JAVA_HOME") + "/bin" : env.get("JAVA_HOME") + "\\bin"));
}
}
if (useAntHome == null) {
logger.println(Messages.AntExec_AntHomeValidation());
logger.println("Trying to run ant from PATH ...");
return build.getBuiltOn().createPath("ant");
} else {
if (build.getBuiltOn().createPath(useAntHome + antExe).exists()) {
logger.println(build.getBuiltOn().createPath(useAntHome + antExe) + " exists!");
}
return build.getBuiltOn().createPath(useAntHome + antExe);
}
}
static FilePath makeBuildFile(String targetSource, AbstractBuild build) throws IOException, InterruptedException {
FilePath buildFile = new FilePath(build.getWorkspace(), AntExec.buildXml);
StringBuilder sb = new StringBuilder();
sb.append("<project default=\"AntExec_Builder\" xmlns:antcontrib=\"antlib:net.sf.antcontrib\" basedir=\".\">\n");
sb.append("<target name=\"AntExec_Builder\">\n\n");
sb.append(targetSource);
sb.append("\n</target>\n");
sb.append("</project>\n");
buildFile.write(sb.toString(), null);
return buildFile;
}
}
|
package hudson.plugins.ec2;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Node;
import hudson.model.Slave;
import hudson.plugins.ec2.util.AmazonEC2Factory;
import hudson.plugins.ec2.util.ResettableCountDownLatch;
import hudson.slaves.NodeProperty;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.RetentionStrategy;
import hudson.util.ListBoxModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AvailabilityZone;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.DeleteTagsRequest;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceBlockDeviceMapping;
import com.amazonaws.services.ec2.model.InstanceStateName;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
/**
* Agent running on EC2.
*
* @author Kohsuke Kawaguchi
*/
@SuppressWarnings("serial")
public abstract class EC2AbstractSlave extends Slave {
public static final Boolean DEFAULT_METADATA_ENDPOINT_ENABLED = Boolean.TRUE;
public static final Boolean DEFAULT_METADATA_TOKENS_REQUIRED = Boolean.FALSE;
public static final Integer DEFAULT_METADATA_HOPS_LIMIT = 1;
private static final Logger LOGGER = Logger.getLogger(EC2AbstractSlave.class.getName());
protected String instanceId;
/**
* Comes from {@link SlaveTemplate#initScript}.
*/
public final String initScript;
public final String tmpDir;
public final String remoteAdmin; // e.g. 'ubuntu'
public final String templateDescription;
public final String jvmopts; // e.g. -Xmx1g
public final boolean stopOnTerminate;
public final String idleTerminationMinutes;
@Deprecated
public transient boolean useDedicatedTenancy;
public boolean isConnected = false;
public List<EC2Tag> tags;
public final String cloudName;
public AMITypeData amiType;
public int maxTotalUses;
public final Tenancy tenancy;
private String instanceType;
private Boolean metadataEndpointEnabled;
private Boolean metadataTokensRequired;
private Integer metadataHopsLimit;
// Temporary stuff that is obtained live from EC2
public transient String publicDNS;
public transient String privateDNS;
/* The last instance data to be fetched for the agent */
protected transient Instance lastFetchInstance = null;
/* The time at which we fetched the last instance data */
protected transient long lastFetchTime;
/** Terminate was scheduled */
protected transient ResettableCountDownLatch terminateScheduled = new ResettableCountDownLatch(1, false);
/*
* The time (in milliseconds) after which we will always re-fetch externally changeable EC2 data when we are asked
* for it
*/
protected static final long MIN_FETCH_TIME = Long.getLong("hudson.plugins.ec2.EC2AbstractSlave.MIN_FETCH_TIME",
TimeUnit.SECONDS.toMillis(20));
protected final int launchTimeout;
// Deprecated by the AMITypeData data structure
@Deprecated
protected transient int sshPort;
@Deprecated
public transient String rootCommandPrefix; // e.g. 'sudo'
@Deprecated
public transient boolean usePrivateDnsName;
public transient String slaveCommandPrefix;
public transient String slaveCommandSuffix;
private transient long createdTime;
public static final String TEST_ZONE = "testZone";
public EC2AbstractSlave(String name, String instanceId, String templateDescription, String remoteFS, int numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy<EC2Computer> retentionStrategy, String initScript, String tmpDir, List<? extends NodeProperty<?>> nodeProperties, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, List<EC2Tag> tags, String cloudName, int launchTimeout, AMITypeData amiType, ConnectionStrategy connectionStrategy, int maxTotalUses, Tenancy tenancy,
Boolean metadataEndpointEnabled, Boolean metadataTokensRequired, Integer metadataHopsLimit)
throws FormException, IOException {
super(name, remoteFS, launcher);
setNumExecutors(numExecutors);
setMode(mode);
setLabelString(labelString);
setRetentionStrategy(retentionStrategy);
setNodeProperties(nodeProperties);
this.instanceId = instanceId;
this.templateDescription = templateDescription;
this.initScript = initScript;
this.tmpDir = tmpDir;
this.remoteAdmin = remoteAdmin;
this.jvmopts = jvmopts;
this.stopOnTerminate = stopOnTerminate;
this.idleTerminationMinutes = idleTerminationMinutes;
this.tags = tags;
this.usePrivateDnsName = connectionStrategy == ConnectionStrategy.PRIVATE_DNS;
this.useDedicatedTenancy = tenancy == Tenancy.Dedicated;
this.cloudName = cloudName;
this.launchTimeout = launchTimeout;
this.amiType = amiType;
this.maxTotalUses = maxTotalUses;
this.tenancy = tenancy != null ? tenancy : Tenancy.Default;
this.metadataEndpointEnabled = metadataEndpointEnabled;
this.metadataTokensRequired = metadataTokensRequired;
this.metadataHopsLimit = metadataHopsLimit;
readResolve();
}
@Deprecated
public EC2AbstractSlave(String name, String instanceId, String templateDescription, String remoteFS, int numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy<EC2Computer> retentionStrategy, String initScript, String tmpDir, List<? extends NodeProperty<?>> nodeProperties, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, List<EC2Tag> tags, String cloudName, int launchTimeout, AMITypeData amiType, ConnectionStrategy connectionStrategy, int maxTotalUses, Tenancy tenancy)
throws FormException, IOException {
this(name, instanceId, templateDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, initScript, tmpDir, nodeProperties, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, tags, cloudName, launchTimeout, amiType, connectionStrategy, maxTotalUses, tenancy, DEFAULT_METADATA_ENDPOINT_ENABLED, DEFAULT_METADATA_TOKENS_REQUIRED, DEFAULT_METADATA_HOPS_LIMIT);
}
@Deprecated
public EC2AbstractSlave(String name, String instanceId, String templateDescription, String remoteFS, int numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy<EC2Computer> retentionStrategy, String initScript, String tmpDir, List<? extends NodeProperty<?>> nodeProperties, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, List<EC2Tag> tags, String cloudName, boolean useDedicatedTenancy, int launchTimeout, AMITypeData amiType, ConnectionStrategy connectionStrategy, int maxTotalUses)
throws FormException, IOException {
this(name, instanceId, templateDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, initScript, tmpDir, nodeProperties, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, tags, cloudName, launchTimeout, amiType, connectionStrategy, maxTotalUses, Tenancy.backwardsCompatible(useDedicatedTenancy));
}
@Deprecated
public EC2AbstractSlave(String name, String instanceId, String templateDescription, String remoteFS, int numExecutors, Mode mode, String labelString, ComputerLauncher launcher, RetentionStrategy<EC2Computer> retentionStrategy, String initScript, String tmpDir, List<? extends NodeProperty<?>> nodeProperties, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, List<EC2Tag> tags, String cloudName, boolean usePrivateDnsName, boolean useDedicatedTenancy, int launchTimeout, AMITypeData amiType)
throws FormException, IOException {
this(name, instanceId, templateDescription, remoteFS, numExecutors, mode, labelString, launcher, retentionStrategy, initScript, tmpDir, nodeProperties, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, tags, cloudName, useDedicatedTenancy, launchTimeout, amiType, ConnectionStrategy.backwardsCompatible(usePrivateDnsName, false, false), -1);
}
@Override
protected Object readResolve() {
/*
* If instanceId is null, this object was deserialized from an old version of the plugin, where this field did
* not exist (prior to version 1.18). In those versions, the node name *was* the instance ID, so we can get it
* from there.
*/
if (instanceId == null) {
instanceId = getNodeName();
}
if (amiType == null) {
amiType = new UnixData(rootCommandPrefix, slaveCommandPrefix, slaveCommandSuffix, Integer.toString(sshPort));
}
if (maxTotalUses == 0) {
EC2Cloud cloud = getCloud();
if (cloud != null) {
SlaveTemplate template = cloud.getTemplate(templateDescription);
if (template != null) {
if (template.getMaxTotalUses() == -1) {
maxTotalUses = -1;
}
}
}
}
if (terminateScheduled == null) {
terminateScheduled = new ResettableCountDownLatch(1, false);
}
return this;
}
public EC2Cloud getCloud() {
return (EC2Cloud) Jenkins.get().getCloud(cloudName);
}
/* package */static int toNumExecutors(InstanceType it) {
switch (it) {
case T1Micro:
return 1;
case M1Small:
return 1;
case M1Medium:
return 2;
case M3Medium:
return 2;
case T3Nano:
return 2;
case T3aNano:
return 2;
case T3Micro:
return 2;
case T3aMicro:
return 2;
case T3Small:
return 2;
case T3aSmall:
return 2;
case T3Medium:
return 2;
case T3aMedium:
return 2;
case A1Large:
return 2;
case T3Large:
return 3;
case T3aLarge:
return 3;
case M1Large:
return 4;
case M3Large:
return 4;
case M4Large:
return 4;
case M5Large:
return 4;
case M5aLarge:
return 4;
case T3Xlarge:
return 5;
case T3aXlarge:
return 5;
case A1Xlarge:
return 5;
case C1Medium:
return 5;
case M2Xlarge:
return 6;
case C3Large:
return 7;
case C4Large:
return 7;
case C5Large:
return 7;
case C5dLarge:
return 7;
case M1Xlarge:
return 8;
case T32xlarge:
return 10;
case T3a2xlarge:
return 10;
case A12xlarge:
return 10;
case M22xlarge:
return 13;
case M3Xlarge:
return 13;
case M4Xlarge:
return 13;
case M5Xlarge:
return 13;
case M5aXlarge:
return 13;
case A14xlarge:
return 14;
case C3Xlarge:
return 14;
case C4Xlarge:
return 14;
case C5Xlarge:
return 14;
case C5dXlarge:
return 14;
case C1Xlarge:
return 20;
case M24xlarge:
return 26;
case M32xlarge:
return 26;
case M42xlarge:
return 26;
case M52xlarge:
return 26;
case M5a2xlarge:
return 26;
case G22xlarge:
return 26;
case C32xlarge:
return 28;
case C42xlarge:
return 28;
case C52xlarge:
return 28;
case C5d2xlarge:
return 28;
case Cc14xlarge:
return 33;
case Cg14xlarge:
return 33;
case Hi14xlarge:
return 35;
case Hs18xlarge:
return 35;
case C34xlarge:
return 55;
case C44xlarge:
return 55;
case C54xlarge:
return 55;
case C5d4xlarge:
return 55;
case M44xlarge:
return 55;
case M54xlarge:
return 55;
case M5a4xlarge:
return 55;
case Cc28xlarge:
return 88;
case Cr18xlarge:
return 88;
case C38xlarge:
return 108;
case C48xlarge:
return 108;
case C59xlarge:
return 108;
case C5d9xlarge:
return 108;
case M410xlarge:
return 120;
case M512xlarge:
return 120;
case M5a12xlarge:
return 120;
case M416xlarge:
return 160;
case C518xlarge:
return 216;
case C5d18xlarge:
return 216;
case M524xlarge:
return 240;
case M5a24xlarge:
return 240;
case Dl124xlarge:
return 250;
case Mac1Metal:
return 1;
// We don't have a suggestion, but we don't want to fail completely
// surely?
default:
return 1;
}
}
/**
* EC2 instance ID.
*/
public String getInstanceId() {
return instanceId;
}
@Override
public Computer createComputer() {
return new EC2Computer(this);
}
/**
* Returns view of AWS EC2 Instance.
*
* @param instanceId instance id.
* @param cloud cloud provider (EC2Cloud compatible).
* @return instance in EC2.
*/
public static Instance getInstance(String instanceId, EC2Cloud cloud) {
Instance i = null;
try {
i = CloudHelper.getInstanceWithRetry(instanceId, cloud);
} catch (InterruptedException e) {
// We'll just retry next time we test for idleness.
LOGGER.fine("InterruptedException while get " + instanceId + " Exception: " + e);
}
return i;
}
/**
* Terminates the instance in EC2.
*/
public abstract void terminate();
void stop() {
try {
AmazonEC2 ec2 = getCloud().connect();
StopInstancesRequest request = new StopInstancesRequest(Collections.singletonList(getInstanceId()));
LOGGER.fine("Sending stop request for " + getInstanceId());
ec2.stopInstances(request);
LOGGER.info("EC2 instance stop request sent for " + getInstanceId());
Computer computer = toComputer();
if (computer != null) {
computer.disconnect(null);
}
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to stop EC2 instance: " + getInstanceId(), e);
}
}
boolean terminateInstance() {
try {
AmazonEC2 ec2 = getCloud().connect();
TerminateInstancesRequest request = new TerminateInstancesRequest(Collections.singletonList(getInstanceId()));
LOGGER.fine("Sending terminate request for " + getInstanceId());
ec2.terminateInstances(request);
LOGGER.info("EC2 instance terminate request sent for " + getInstanceId());
return true;
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to terminate EC2 instance: " + getInstanceId(), e);
return false;
}
}
@Override
public Node reconfigure(final StaplerRequest req, JSONObject form) throws FormException {
if (form == null) {
return null;
}
EC2AbstractSlave result = (EC2AbstractSlave) super.reconfigure(req, form);
if (result != null) {
/* Get rid of the old tags, as represented by ourselves. */
clearLiveInstancedata();
/* Set the new tags, as represented by our successor */
result.pushLiveInstancedata();
return result;
}
return null;
}
@Override
public boolean isAcceptingTasks() {
return terminateScheduled.getCount() == 0;
}
void idleTimeout() {
LOGGER.info("EC2 instance idle time expired: " + getInstanceId());
if (!stopOnTerminate) {
terminate();
} else {
stop();
}
}
void launchTimeout(){
LOGGER.info("EC2 instance failed to launch: " + getInstanceId());
terminate();
}
public long getLaunchTimeoutInMillis() {
// this should be fine as long as launchTimeout remains an int type
return launchTimeout * 1000L;
}
public String getRemoteAdmin() {
if (remoteAdmin == null || remoteAdmin.length() == 0)
return amiType.isWindows() ? "Administrator" : "root";
return remoteAdmin;
}
String getRootCommandPrefix() {
String commandPrefix = (amiType.isUnix() ? ((UnixData) amiType).getRootCommandPrefix() : (amiType.isMac() ? ((MacData) amiType).getRootCommandPrefix() : ""));
if (commandPrefix == null || commandPrefix.length() == 0)
return "";
return commandPrefix + " ";
}
String getSlaveCommandPrefix() {
String commandPrefix = (amiType.isUnix() ? ((UnixData) amiType).getSlaveCommandPrefix() :(amiType.isMac() ? ((MacData) amiType).getSlaveCommandPrefix() : ""));
if (commandPrefix == null || commandPrefix.length() == 0)
return "";
return commandPrefix + " ";
}
String getSlaveCommandSuffix() {
String commandSuffix = (amiType.isUnix() ? ((UnixData) amiType).getSlaveCommandSuffix() :(amiType.isMac() ? ((MacData) amiType).getSlaveCommandSuffix() : ""));
if (commandSuffix == null || commandSuffix.length() == 0)
return "";
return " " + commandSuffix;
}
String getJvmopts() {
return Util.fixNull(jvmopts);
}
public int getSshPort() {
String sshPort = (amiType.isUnix() ? ((UnixData) amiType).getSshPort() :(amiType.isMac() ? ((MacData) amiType).getSshPort() : "22"));
if (sshPort == null || sshPort.length() == 0)
return 22;
int port = 0;
try {
port = Integer.parseInt(sshPort);
} catch (Exception e) {
}
return port != 0 ? port : 22;
}
public boolean getStopOnTerminate() {
return stopOnTerminate;
}
/**
* Called when the agent is connected to Jenkins
*/
public void onConnected() {
isConnected = true;
}
protected boolean isAlive(boolean force) {
fetchLiveInstanceData(force);
if (lastFetchInstance == null)
return false;
if (lastFetchInstance.getState().getName().equals(InstanceStateName.Terminated.toString()))
return false;
return true;
}
/*
* Much of the EC2 data is beyond our direct control, therefore we need to refresh it from time to time to ensure we
* reflect the reality of the instances.
*/
private void fetchLiveInstanceData(boolean force) throws AmazonClientException {
/*
* If we've grabbed the data recently, don't bother getting it again unless we are forced
*/
long now = System.currentTimeMillis();
if ((lastFetchTime > 0) && (now - lastFetchTime < MIN_FETCH_TIME) && !force) {
return;
}
if (getInstanceId() == null || getInstanceId().isEmpty()) {
/*
* The getInstanceId() implementation on EC2SpotSlave can return null if the spot request doesn't yet know
* the instance id that it is starting. What happens is that null is passed to getInstanceId() which
* searches AWS but without an instanceID the search returns some random box. We then fetch its metadata,
* including tags, and then later, when the spot request eventually gets the instanceID correctly we push
* the saved tags from that random box up to the new spot resulting in confusion and delay.
*/
return;
}
Instance i = null;
try {
i = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud());
} catch (InterruptedException e) {
// We'll just retry next time we test for idleness.
LOGGER.fine("InterruptedException while get " + getInstanceId()
+ " Exception: " + e);
return;
}
lastFetchTime = now;
lastFetchInstance = i;
if (i == null)
return;
publicDNS = i.getPublicDnsName();
privateDNS = i.getPrivateIpAddress();
createdTime = i.getLaunchTime().getTime();
instanceType = i.getInstanceType();
/*
* Only fetch tags from live instance if tags are set. This check is required to mitigate a race condition
* when fetchLiveInstanceData() is called before pushLiveInstancedata().
*/
if(!i.getTags().isEmpty()) {
tags = new LinkedList<EC2Tag>();
for (Tag t : i.getTags()) {
tags.add(new EC2Tag(t.getKey(), t.getValue()));
}
}
}
/*
* Clears all existing tag data so that we can force the instance into a known state
*/
protected void clearLiveInstancedata() throws AmazonClientException {
Instance inst = null;
try {
inst = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud());
} catch (InterruptedException e) {
// We'll just retry next time we test for idleness.
LOGGER.fine("InterruptedException while get " + getInstanceId()
+ " Exception: " + e);
return;
}
/* Now that we have our instance, we can clear the tags on it */
if (!tags.isEmpty()) {
HashSet<Tag> instTags = new HashSet<Tag>();
for (EC2Tag t : tags) {
instTags.add(new Tag(t.getName(), t.getValue()));
}
List<String> resources = getResourcesToTag(inst);
DeleteTagsRequest tagRequest = new DeleteTagsRequest();
tagRequest.withResources(resources).setTags(instTags);
getCloud().connect().deleteTags(tagRequest);
}
}
/*
* Sets tags on an instance and on the volumes attached to it. This will not clear existing tag data, so call
* clearLiveInstancedata if needed
*/
protected void pushLiveInstancedata() throws AmazonClientException {
Instance inst = null;
try {
inst = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud());
} catch (InterruptedException e) {
// We'll just retry next time we test for idleness.
LOGGER.fine("InterruptedException while get " + getInstanceId()
+ " Exception: " + e);
}
/* Now that we have our instance, we can set tags on it */
if (inst != null && tags != null && !tags.isEmpty()) {
HashSet<Tag> instTags = new HashSet<Tag>();
for (EC2Tag t : tags) {
instTags.add(new Tag(t.getName(), t.getValue()));
}
List<String> resources = getResourcesToTag(inst);
CreateTagsRequest tagRequest = new CreateTagsRequest();
tagRequest.withResources(resources).setTags(instTags);
getCloud().connect().createTags(tagRequest);
}
}
/*
* Get resources to tag, that is the instance itself and the volumes attached to it.
*/
private List<String> getResourcesToTag(Instance inst) {
List<String> resources = new ArrayList<>();
resources.add(inst.getInstanceId());
for(InstanceBlockDeviceMapping blockDeviceMapping : inst.getBlockDeviceMappings()) {
resources.add(blockDeviceMapping.getEbs().getVolumeId());
}
return resources;
}
public String getPublicDNS() {
fetchLiveInstanceData(false);
return publicDNS;
}
public String getPrivateDNS() {
fetchLiveInstanceData(false);
return privateDNS;
}
public String getInstanceType() {
fetchLiveInstanceData(false);
return instanceType;
}
public List<EC2Tag> getTags() {
fetchLiveInstanceData(false);
return Collections.unmodifiableList(tags);
}
public long getCreatedTime() {
fetchLiveInstanceData(false);
return createdTime;
}
@Deprecated
public boolean getUsePrivateDnsName() {
return usePrivateDnsName;
}
public Secret getAdminPassword() {
return amiType.isWindows() ? ((WindowsData) amiType).getPassword() : Secret.fromString("");
}
public boolean isUseHTTPS() {
return amiType.isWindows() && ((WindowsData) amiType).isUseHTTPS();
}
public int getBootDelay() {
return amiType.isWindows() ? ((WindowsData) amiType).getBootDelayInMillis() : 0;
}
public boolean isSpecifyPassword() {
return amiType.isWindows() && ((WindowsData) amiType).isSpecifyPassword();
}
public boolean isAllowSelfSignedCertificate() {
return amiType.isWindows() && ((WindowsData) amiType).isAllowSelfSignedCertificate();
}
public static ListBoxModel fillZoneItems(AWSCredentialsProvider credentialsProvider, String region) {
ListBoxModel model = new ListBoxModel();
if (!StringUtils.isEmpty(region)) {
AmazonEC2 client = AmazonEC2Factory.getInstance().connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region));
DescribeAvailabilityZonesResult zones = client.describeAvailabilityZones();
List<AvailabilityZone> zoneList = zones.getAvailabilityZones();
model.add("<not specified>", "");
for (AvailabilityZone z : zoneList) {
model.add(z.getZoneName(), z.getZoneName());
}
}
return model;
}
/*
* Used to determine if the agent is On Demand or Spot
*/
abstract public String getEc2Type();
public static abstract class DescriptorImpl extends SlaveDescriptor {
@Override
public abstract String getDisplayName();
@Override
public boolean isInstantiable() {
return false;
}
public ListBoxModel doFillZoneItems(@QueryParameter boolean useInstanceProfileForCredentials,
@QueryParameter String credentialsId,
@QueryParameter String region,
@QueryParameter String roleArn,
@QueryParameter String roleSessionName) {
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId, roleArn, roleSessionName, region);
return fillZoneItems(credentialsProvider, region);
}
public List<Descriptor<AMITypeData>> getAMITypeDescriptors() {
return Jenkins.get().getDescriptorList(AMITypeData.class);
}
}
}
|
package com.khartec.waltz.jobs;
import com.khartec.waltz.common.SetUtilities;
import com.khartec.waltz.model.*;
import com.khartec.waltz.model.survey.*;
import com.khartec.waltz.service.DIConfiguration;
import com.khartec.waltz.service.survey.SurveyInstanceService;
import com.khartec.waltz.service.survey.SurveyQuestionService;
import com.khartec.waltz.service.survey.SurveyRunService;
import com.khartec.waltz.service.survey.SurveyTemplateService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.Collections;
import java.util.List;
import java.util.stream.LongStream;
import static com.khartec.waltz.common.DateTimeUtilities.nowUtc;
import static java.util.stream.Collectors.toList;
public class SurveyHarness {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(DIConfiguration.class);
surveyTempateHarness(ctx);
// surveyRunHarness(ctx);
// surveyResponseHarness(ctx);
}
private static void surveyTempateHarness(AnnotationConfigApplicationContext ctx) {
SurveyTemplateService surveyTemplateService = ctx.getBean(SurveyTemplateService.class);
SurveyQuestionService surveyQuestionService = ctx.getBean(SurveyQuestionService.class);
SurveyTemplate surveyTemplate = ImmutableSurveyTemplate.builder()
.name("AAA")
.description("BBB")
.ownerId(1L)
.targetEntityKind(EntityKind.CHANGE_INITIATIVE)
.status(SurveyTemplateStatus.ACTIVE)
.createdAt(nowUtc())
.build();
long templateId = surveyTemplateService.create("admin", surveyTemplate);
System.out.println("Created: template create with ID = " + templateId);
SurveyQuestion surveyQuestion = ImmutableSurveyQuestion.builder()
.surveyTemplateId(templateId)
.sectionName("SSS")
.questionText("QQQ")
.helpText("HHH")
.fieldType(SurveyQuestionFieldType.TEXTAREA)
.position(1)
.isMandatory(false)
.allowComment(true)
.build();
long questionId = surveyQuestionService.create(surveyQuestion);
System.out.println("Created: question create with ID = " + questionId);
}
private static void surveyRunHarness(AnnotationConfigApplicationContext ctx) {
SurveyQuestionService surveyQuestionService = ctx.getBean(SurveyQuestionService.class);
surveyQuestionService.findForSurveyTemplate(1).forEach(System.out::println);
IdSelectionOptions idSelectionOptions = ImmutableIdSelectionOptions.builder()
.entityReference(ImmutableEntityReference.mkRef(EntityKind.APP_GROUP, 1))
.scope(HierarchyQueryScope.EXACT)
.build();
SurveyRunCreateCommand surveyRunCreateCommand = ImmutableSurveyRunCreateCommand.builder()
.surveyTemplateId(1L)
.name("Q1 Quality Survey")
.selectionOptions(idSelectionOptions)
.issuanceKind(SurveyIssuanceKind.INDIVIDUAL)
.involvementKindIds(SetUtilities.fromCollection(
LongStream.range(1, 5).mapToObj(Long::valueOf)
.collect(toList())))
.contactEmail("jack.livingston12@gmail.com")
.build();
SurveyRunService surveyRunService = ctx.getBean(SurveyRunService.class);
String userName = "livingston@mail.com";
long surveyRunId = surveyRunService.createSurveyRun(userName, surveyRunCreateCommand).id().get();
List<SurveyInstanceRecipient> surveyInstanceRecipients = surveyRunService.generateSurveyInstanceRecipients(surveyRunId);
surveyInstanceRecipients.forEach(r -> System.out.println(
r.surveyInstance().surveyEntity().name().get()
+ " => "
+ r.person().email()));
System.out.println("Generated recipients count: " + surveyInstanceRecipients.size());
surveyRunService.createSurveyInstancesAndRecipients(surveyRunId, surveyInstanceRecipients.subList(0, 5));
ImmutableSurveyRunChangeCommand surveyRunChangeCommand = ImmutableSurveyRunChangeCommand.builder()
.surveyTemplateId(1L)
.name("Q2 Quality Survey")
.selectionOptions(idSelectionOptions)
.issuanceKind(SurveyIssuanceKind.GROUP)
.involvementKindIds(SetUtilities.fromCollection(
LongStream.range(3, 7).mapToObj(Long::valueOf)
.collect(toList())))
.contactEmail("jack.livingston12@gmail.com")
.build();
// update survey run
surveyRunService.updateSurveyRun(userName, surveyRunId, surveyRunChangeCommand);
List<SurveyInstanceRecipient> updatedSurveyInstanceRecipients = surveyRunService.generateSurveyInstanceRecipients(surveyRunId);
System.out.println("Updated Generated recipients count: " + updatedSurveyInstanceRecipients.size());
// generate the instances and recipients again
surveyRunService.createSurveyInstancesAndRecipients(surveyRunId, Collections.emptyList());
// finally publish
surveyRunService.updateSurveyRunStatus(userName, surveyRunId, SurveyRunStatus.ISSUED);
}
private static void surveyResponseHarness(AnnotationConfigApplicationContext ctx) {
String userName = "1258battle@gmail.com";
SurveyQuestionService surveyQuestionService = ctx.getBean(SurveyQuestionService.class);
SurveyInstanceService surveyInstanceService = ctx.getBean(SurveyInstanceService.class);
List<SurveyInstance> instances = surveyInstanceService.findForRecipient(userName);
System.out.println("===========Instances==========");
System.out.println(instances);
SurveyInstance instance = instances.get(0);
List<SurveyQuestion> questions = surveyQuestionService.findForSurveyInstance(instance.id().get());
System.out.println("===========Questions==========");
System.out.println(questions);
List<SurveyInstanceQuestionResponse> responses = surveyInstanceService.findResponses(instance.id().get());
System.out.println("===========Responses==========");
System.out.println(responses);
ImmutableSurveyQuestionResponse insertResponse = ImmutableSurveyQuestionResponse.builder()
.questionId(1L)
.comment("some comment")
.stringResponse("some response")
.build();
surveyInstanceService.saveResponse(userName, instance.id().get(), insertResponse);
System.out.println("===========Inserted Responses==========");
System.out.println(surveyInstanceService.findResponses(instance.id().get()));
ImmutableSurveyQuestionResponse updateResponse = insertResponse
.withStringResponse("updated string response");
surveyInstanceService.saveResponse(userName, instance.id().get(), updateResponse);
System.out.println("===========Updated Responses==========");
System.out.println(surveyInstanceService.findResponses(instance.id().get()));
surveyInstanceService.updateStatus(
userName,
instance.id().get(),
ImmutableSurveyInstanceStatusChangeCommand.builder()
.newStatus(SurveyInstanceStatus.IN_PROGRESS)
.build());
}
}
|
package com.box.l10n.mojito.service.tm;
import com.box.l10n.mojito.common.StreamUtil;
import com.box.l10n.mojito.entity.Asset;
import com.box.l10n.mojito.entity.Locale;
import com.box.l10n.mojito.entity.PluralForm;
import com.box.l10n.mojito.entity.PollableTask;
import com.box.l10n.mojito.entity.Repository;
import com.box.l10n.mojito.entity.RepositoryLocale;
import com.box.l10n.mojito.entity.TM;
import com.box.l10n.mojito.entity.TMTextUnit;
import com.box.l10n.mojito.entity.TMTextUnitCurrentVariant;
import com.box.l10n.mojito.entity.TMTextUnitVariant;
import com.box.l10n.mojito.entity.TMXliff;
import com.box.l10n.mojito.okapi.AbstractImportTranslationsStep;
import com.box.l10n.mojito.okapi.CheckForDoNotTranslateStep;
import com.box.l10n.mojito.okapi.CopyFormsOnImport;
import com.box.l10n.mojito.okapi.FilterEventsToInMemoryRawDocumentStep;
import com.box.l10n.mojito.okapi.ImportTranslationsByIdStep;
import com.box.l10n.mojito.okapi.ImportTranslationsByMd5Step;
import com.box.l10n.mojito.okapi.ImportTranslationsFromLocalizedAssetStep;
import com.box.l10n.mojito.okapi.ImportTranslationsFromLocalizedAssetStep.StatusForEqualTarget;
import com.box.l10n.mojito.okapi.ImportTranslationsStepAnnotation;
import com.box.l10n.mojito.okapi.ImportTranslationsWithTranslationKitStep;
import com.box.l10n.mojito.okapi.InheritanceMode;
import com.box.l10n.mojito.okapi.PseudoLocalizeStep;
import com.box.l10n.mojito.okapi.RawDocument;
import com.box.l10n.mojito.okapi.Status;
import com.box.l10n.mojito.okapi.TranslateStep;
import com.box.l10n.mojito.okapi.XLIFFWriter;
import com.box.l10n.mojito.okapi.qualitycheck.Parameters;
import com.box.l10n.mojito.okapi.qualitycheck.QualityCheckStep;
import com.box.l10n.mojito.rest.asset.FilterConfigIdOverride;
import com.box.l10n.mojito.security.AuditorAwareImpl;
import com.box.l10n.mojito.service.WordCountService;
import com.box.l10n.mojito.service.asset.AssetRepository;
import com.box.l10n.mojito.service.assetExtraction.extractor.AssetExtractor;
import com.box.l10n.mojito.service.assetintegritychecker.integritychecker.IntegrityCheckStep;
import com.box.l10n.mojito.service.locale.LocaleService;
import com.box.l10n.mojito.service.pollableTask.InjectCurrentTask;
import com.box.l10n.mojito.service.pollableTask.Pollable;
import com.box.l10n.mojito.service.pollableTask.PollableFuture;
import com.box.l10n.mojito.service.pollableTask.PollableFutureTaskResult;
import com.box.l10n.mojito.service.repository.RepositoryRepository;
import com.box.l10n.mojito.xliff.XliffUtils;
import com.google.common.base.Preconditions;
import com.ibm.icu.text.MessageFormat;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import javax.persistence.EntityManager;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.exceptions.OkapiBadFilterInputException;
import net.sf.okapi.common.pipeline.BasePipelineStep;
import net.sf.okapi.common.pipelinedriver.IPipelineDriver;
import net.sf.okapi.common.pipelinedriver.PipelineDriver;
import net.sf.okapi.filters.xliff.XLIFFFilter;
import net.sf.okapi.steps.common.FilterEventsWriterStep;
import net.sf.okapi.steps.common.RawDocumentToFilterEventsStep;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service to manage {@link TM}s (translation memories).
* <p/>
* Allows to add {@link TMTextUnit}s (entities to be translated) and
* {@link TMTextUnitVariant} (actual translations). The current translations are
* marked using {@link TMTextUnitCurrentVariant}.
*
* @author jaurambault
*/
@Service
public class TMService {
/**
* logger
*/
static Logger logger = LoggerFactory.getLogger(TMService.class);
@Autowired
TMTextUnitRepository tmTextUnitRepository;
@Autowired
TMTextUnitVariantRepository tmTextUnitVariantRepository;
@Autowired
LocaleService localeService;
@Autowired
TMTextUnitCurrentVariantRepository tmTextUnitCurrentVariantRepository;
@Autowired
EntityManager entityManager;
@Autowired
AssetExtractor assetExtractor;
@Autowired
RepositoryRepository repositoryRepository;
@Autowired
XliffUtils xliffUtils;
@Autowired
WordCountService wordCountService;
@Autowired
AssetRepository assetRepository;
@Autowired
TMXliffRepository tmXliffRepository;
@Autowired
AuditorAwareImpl auditorAwareImpl;
/**
* Adds a {@link TMTextUnit} in a {@link TM}.
*
* @param tmId the {@link TM} id (must be valid)
* @param assetId the {@link Asset} id (must be valid)
* @param name the text unit name
* @param content the text unit content
* @param comment the text unit comment, can be {@code null}
* @return the create {@link TMTextUnit}
* @throws DataIntegrityViolationException If trying to create a
* {@link TMTextUnit} with same logical key as an existing one or TM id
* invalid
*/
@Transactional
public TMTextUnit addTMTextUnit(Long tmId, Long assetId, String name, String content, String comment) {
return addTMTextUnit(tmId, assetId, name, content, comment, null, null, null);
}
/**
* Adds a {@link TMTextUnit} in a {@link TM}.
*
* @param tmId the {@link TM} id (must be valid)
* @param assetId the {@link Asset} id (must be valid)
* @param name the text unit name
* @param content the text unit content
* @param comment the text unit comment, can be {@code null}
* @param createdDate to specify a creation date (can be used to re-import
* old TM), can be {@code null}
* @return the create {@link TMTextUnit}
* @throws DataIntegrityViolationException If trying to create a
* {@link TMTextUnit} with same logical key as an existing one or TM id
* invalid
*/
@Transactional
public TMTextUnit addTMTextUnit(
Long tmId,
Long assetId,
String name,
String content,
String comment,
DateTime createdDate,
PluralForm puralForm,
String pluralFormOther) {
logger.debug("Add TMTextUnit in tmId: {} with name: {}, content: {}, comment: {}", tmId, name, content, comment);
TMTextUnit tmTextUnit = new TMTextUnit();
tmTextUnit.setTm(entityManager.getReference(TM.class, tmId));
tmTextUnit.setAsset(entityManager.getReference(Asset.class, assetId));
tmTextUnit.setName(name);
tmTextUnit.setContent(content);
tmTextUnit.setComment(comment);
tmTextUnit.setMd5(computeTMTextUnitMD5(name, content, comment));
//TODO(P1) Compute word count for english, root locale is hard coded is {@link RepositoryService}
tmTextUnit.setWordCount(wordCountService.getEnglishWordCount(content));
tmTextUnit.setContentMd5(DigestUtils.md5Hex(content));
tmTextUnit.setCreatedDate(createdDate);
tmTextUnit.setPluralForm(puralForm);
tmTextUnit.setPluralFormOther(pluralFormOther);
tmTextUnit.setCreatedByUser(auditorAwareImpl.getCurrentAuditor());
tmTextUnit = tmTextUnitRepository.save(tmTextUnit);
logger.trace("TMTextUnit saved");
logger.debug("Add a current TMTextUnitVariant for the source text ie. the default locale");
TMTextUnitVariant addTMTextUnitVariant = addTMTextUnitVariant(tmTextUnit.getId(), localeService.getDefaultLocaleId(), content, comment, TMTextUnitVariant.Status.APPROVED, true, createdDate);
makeTMTextUnitVariantCurrent(tmId, tmTextUnit.getId(), localeService.getDefaultLocaleId(), addTMTextUnitVariant.getId());
return tmTextUnit;
}
/**
* Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
* locale other than the default locale.
* <p/>
* Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
* references a {@link TMTextUnitVariant} that has same content, the
* {@link TMTextUnitVariant} is returned and no entities are created.
*
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @return the created {@link TMTextUnitVariant} or an existing one with
* same content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public TMTextUnitVariant addCurrentTMTextUnitVariant(Long tmTextUnitId, Long localeId, String content) {
return addTMTextUnitCurrentVariant(tmTextUnitId, localeId, content, null).getTmTextUnitVariant();
}
/**
* Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
* locale other than the default locale.
* <p/>
* Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
* references a {@link TMTextUnitVariant} that has same content, the
* {@link TMTextUnitVariant} is returned and no entities are created.
*
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @param status the translation status
* @param includedInLocalizedFile indicate if the translation should be
* included or not in the localized files
* @return the created {@link TMTextUnitVariant} or an existing one with
* same content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public TMTextUnitVariant addCurrentTMTextUnitVariant(Long tmTextUnitId, Long localeId, String content, TMTextUnitVariant.Status status, boolean includedInLocalizedFile) {
return addCurrentTMTextUnitVariant(tmTextUnitId, localeId, content, status, includedInLocalizedFile, null);
}
/**
* Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
* locale other than the default locale.
* <p/>
* Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
* references a {@link TMTextUnitVariant} that has same content, the
* {@link TMTextUnitVariant} is returned and no entities are created.
*
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @param status the translation status
* @param includedInLocalizedFile indicate if the translation should be
* included or not in the localized files
* @param createdDate to specify a creation date (can be used to re-import
* old TM), can be {@code null}
* @return the created {@link TMTextUnitVariant} or an existing one with
* same content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public TMTextUnitVariant addCurrentTMTextUnitVariant(Long tmTextUnitId, Long localeId, String content, TMTextUnitVariant.Status status, boolean includedInLocalizedFile, DateTime createdDate) {
return addTMTextUnitCurrentVariant(tmTextUnitId, localeId, content, null, status, includedInLocalizedFile, createdDate).getTmTextUnitVariant();
}
/**
* Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
* locale other than the default locale.
* <p/>
* Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
* references a {@link TMTextUnitVariant} that has same content, the
* {@link TMTextUnitVariant} is returned and no entities are created.
*
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @param comment the translation comment, can be {@code null}
* @return the {@link TMTextUnitCurrentVariant} that holds the created
* {@link TMTextUnitVariant} or an existing one with same content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public TMTextUnitCurrentVariant addTMTextUnitCurrentVariant(Long tmTextUnitId, Long localeId, String content, String comment) {
return addTMTextUnitCurrentVariant(tmTextUnitId, localeId, content, comment, TMTextUnitVariant.Status.APPROVED);
}
/**
* @see TMService#addTMTextUnitCurrentVariant(Long, Long, String, String,
* boolean, boolean)
*
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @param comment the translation comment, can be {@code null}
* @param status the translation status
* @return the {@link TMTextUnitCurrentVariant} that holds the created
* {@link TMTextUnitVariant} or an existing one with same content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public TMTextUnitCurrentVariant addTMTextUnitCurrentVariant(Long tmTextUnitId, Long localeId, String content, String comment, TMTextUnitVariant.Status status) {
return addTMTextUnitCurrentVariant(tmTextUnitId, localeId, content, comment, status, true);
}
/**
* Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
* locale other than the default locale.
* <p/>
* Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
* references a {@link TMTextUnitVariant} that has same content, the
* {@link TMTextUnitVariant} is returned and no entities are created.
*
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @param comment the translation comment, can be {@code null}
* @param status the translation status
* @param includedInLocalizedFile indicate if the translation should be
* included or not in the localized files
* @return the {@link TMTextUnitCurrentVariant} that holds the created
* {@link TMTextUnitVariant} or an existing one with same content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public TMTextUnitCurrentVariant addTMTextUnitCurrentVariant(
Long tmTextUnitId,
Long localeId,
String content,
String comment,
TMTextUnitVariant.Status status,
boolean includedInLocalizedFile) {
return addTMTextUnitCurrentVariant(tmTextUnitId, localeId, content, comment, status, includedInLocalizedFile, null);
}
/**
* Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
* locale other than the default locale.
* <p/>
* Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
* references a {@link TMTextUnitVariant} that has same content, the
* {@link TMTextUnitVariant} is returned and no entities are created.
*
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @param comment the translation comment, can be {@code null}
* @param status the translation status
* @param includedInLocalizedFile indicate if the translation should be
* included or not in the localized files
* @param createdDate to specify a creation date (can be used to re-import
* old TM), can be {@code null}
* @return the {@link TMTextUnitCurrentVariant} that holds the created
* {@link TMTextUnitVariant} or an existing one with same content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public TMTextUnitCurrentVariant addTMTextUnitCurrentVariant(
Long tmTextUnitId,
Long localeId,
String content,
String comment,
TMTextUnitVariant.Status status,
boolean includedInLocalizedFile,
DateTime createdDate) {
return addTMTextUnitCurrentVariantWithResult(tmTextUnitId, localeId, content, comment, status, includedInLocalizedFile, createdDate).getTmTextUnitCurrentVariant();
}
/**
* Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
* locale other than the default locale.
* <p/>
* Also checks for an existing {@link TMTextUnitCurrentVariant} and if it
* references a {@link TMTextUnitVariant} that has same content, the
* {@link TMTextUnitVariant} is returned and no entities are created.
*
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @param comment the translation comment, can be {@code null}
* @param status the translation status
* @param includedInLocalizedFile indicate if the translation should be
* included or not in the localized files
* @param createdDate to specify a creation date (can be used to re-import
* old TM), can be {@code null}
* @return the result that contains the {@link TMTextUnitCurrentVariant} and
* indicates if it was updated or not. The {@link TMTextUnitCurrentVariant}
* holds the created {@link TMTextUnitVariant} or an existing one with same
* content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public AddTMTextUnitCurrentVariantResult addTMTextUnitCurrentVariantWithResult(
Long tmTextUnitId,
Long localeId,
String content,
String comment,
TMTextUnitVariant.Status status,
boolean includedInLocalizedFile,
DateTime createdDate) {
logger.debug("Check if there is a current TMTextUnitVariant");
TMTextUnitCurrentVariant currentTmTextUnitCurrentVariant = tmTextUnitCurrentVariantRepository.findByLocale_IdAndTmTextUnit_Id(localeId, tmTextUnitId);
TMTextUnit tmTextUnit = tmTextUnitRepository.findOne(tmTextUnitId);
if (tmTextUnit == null) {
String msg = MessageFormat.format("Unable to find the TMTextUnit with ID: {0}. The TMTextUnitVariant and "
+ "TMTextUnitCurrentVariant will not be created.", tmTextUnitId);
throw new RuntimeException(msg);
}
return addTMTextUnitCurrentVariantWithResult(currentTmTextUnitCurrentVariant,
tmTextUnit.getTm().getId(),
tmTextUnitId,
localeId,
content,
comment,
status,
includedInLocalizedFile,
createdDate);
}
/**
* Adds a current {@link TMTextUnitVariant} in a {@link TMTextUnit} for a
* locale other than the default locale.
* <p/>
* Requires the {@link TMTextUnitCurrentVariant} and TM id for optimization
* purpose.
*
* @param tmTextUnitCurrentVariant current variant or null is there is none
* @param tmId the {@link TM} id in which the translation is added
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation (default locale not
* accepted)
* @param content the translation content
* @param comment the translation comment, can be {@code null}
* @param status the translation status
* @param includedInLocalizedFile indicate if the translation should be
* included or not in the localized files
* @param createdDate to specify a creation date (can be used to re-import
* old TM), can be {@code null}
* @return the result that contains the {@link TMTextUnitCurrentVariant} and
* indicates if it was updated or not. The {@link TMTextUnitCurrentVariant}
* holds the created {@link TMTextUnitVariant} or an existing one with same
* content
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public AddTMTextUnitCurrentVariantResult addTMTextUnitCurrentVariantWithResult(
TMTextUnitCurrentVariant tmTextUnitCurrentVariant,
Long tmId,
Long tmTextUnitId,
Long localeId,
String content,
String comment,
TMTextUnitVariant.Status status,
boolean includedInLocalizedFile,
DateTime createdDate) {
if (localeService.getDefaultLocaleId().equals(localeId)) {
throw new RuntimeException("Cannot add text unit variant for the default locale");
}
boolean noUpdate = false;
TMTextUnitVariant tmTextUnitVariant;
if (tmTextUnitCurrentVariant == null) {
logger.debug("There is no currrent text unit variant, add entities");
tmTextUnitVariant = addTMTextUnitVariant(tmTextUnitId, localeId, content, comment, status, includedInLocalizedFile, createdDate);
tmTextUnitCurrentVariant = makeTMTextUnitVariantCurrent(tmId, tmTextUnitId, localeId, tmTextUnitVariant.getId());
logger.trace("Put the actual tmTextUnitVariant instead of the proxy");
tmTextUnitCurrentVariant.setTmTextUnitVariant(tmTextUnitVariant);
} else {
logger.debug("There is a current text unit variant, check if an update is needed");
TMTextUnitVariant currentTmTextUnitVariant = tmTextUnitCurrentVariant.getTmTextUnitVariant();
boolean updateNeeded = isUpdateNeededForTmTextUnitVariant(
currentTmTextUnitVariant.getStatus(),
currentTmTextUnitVariant.getContentMD5(),
currentTmTextUnitVariant.isIncludedInLocalizedFile(),
currentTmTextUnitVariant.getComment(),
status,
DigestUtils.md5Hex(content),
includedInLocalizedFile,
comment);
if (updateNeeded) {
logger.debug("The current text unit variant has different content, comment or needs review. Add entities");
tmTextUnitVariant = addTMTextUnitVariant(tmTextUnitId, localeId, content, comment, status, includedInLocalizedFile, createdDate);
logger.debug("Updating the current TextUnitVariant with id: {} current for locale: {}", tmTextUnitVariant.getId(), localeId);
tmTextUnitCurrentVariant.setTmTextUnitVariant(tmTextUnitVariant);
tmTextUnitCurrentVariantRepository.save(tmTextUnitCurrentVariant);
} else {
logger.debug("The current text unit variant has same content, comment and review status, don't add entities and return it instead");
noUpdate = true;
}
}
return new AddTMTextUnitCurrentVariantResult(!noUpdate, tmTextUnitCurrentVariant);
}
/**
* Indicates if a {@link TMTextUnitVariant} should be updated by looking at
* new/old content, status, comments, etc
*
* @param currentStatus
* @param currentContentMd5
* @param currentIncludedInLocalizedFile
* @param currentComment
* @param newStatus
* @param newContentMd5
* @param newIncludedInLocalizedFile
* @param newComment
* @return
*/
public boolean isUpdateNeededForTmTextUnitVariant(
TMTextUnitVariant.Status currentStatus,
String currentContentMd5,
boolean currentIncludedInLocalizedFile,
String currentComment,
TMTextUnitVariant.Status newStatus,
String newContentMd5,
boolean newIncludedInLocalizedFile,
String newComment) {
return !(currentContentMd5.equals(newContentMd5)
&& currentStatus.equals(newStatus)
&& currentIncludedInLocalizedFile == newIncludedInLocalizedFile
&& Objects.equals(currentComment, newComment));
}
/**
* Adds a {@link TMTextUnitVariant} in a {@link TMTextUnit}.
* <p/>
* No checks are performed on the locale or for duplicated content. If this
* is a requirement use {@link #addCurrentTMTextUnitVariant(java.lang.Long, java.lang.Long, java.lang.String)
*
* @param tmTextUnitId the text unit that will contain the translation
* @param localeId locale id of the translation
* @param content the translation content
* @param comment comment for the translation, can be {@code null}
* @param status the translation status
* @param includedInLocalizedFile indicate if the translation should be
* included or not in the localized files
* @return the created {@link TMTextUnitVariant}
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
protected TMTextUnitVariant addTMTextUnitVariant(
Long tmTextUnitId,
Long localeId,
String content,
String comment,
TMTextUnitVariant.Status status,
boolean includedInLocalizedFile) {
return addTMTextUnitVariant(tmTextUnitId, localeId, content, comment, status, includedInLocalizedFile, null);
}
/**
* Adds a {@link TMTextUnitVariant} in a {@link TMTextUnit}.
* <p/>
* No checks are performed on the locale or for duplicated content. If this
* is a requirement use {@link #addCurrentTMTextUnitVariant(java.lang.Long, java.lang.Long, java.lang.String)
*
* @param tmTextUnitId the text unit that will contain the translation
* @param localeId locale id of the translation
* @param content the translation content
* @param comment comment for the translation, can be {@code null}
* @param status the translation status
* @param includedInLocalizedFile indicate if the translation should be
* included or not in the localized files
* @param createdDate to specify a creation date (can be used to re-import
* old TM), can be {@code null}
* @return the created {@link TMTextUnitVariant}
* @throws DataIntegrityViolationException If tmTextUnitId or localeId are
* invalid
*/
public TMTextUnitVariant addTMTextUnitVariant(
Long tmTextUnitId,
Long localeId,
String content,
String comment,
TMTextUnitVariant.Status status,
boolean includedInLocalizedFile,
DateTime createdDate) {
logger.debug("Add TMTextUnitVariant for tmId: {} locale id: {}, content: {}", tmTextUnitId, localeId, content);
Preconditions.checkNotNull(content, "content must not be null when adding a TMTextUnitVariant");
TMTextUnit tmTextUnit = entityManager.getReference(TMTextUnit.class, tmTextUnitId);
Locale locale = entityManager.getReference(Locale.class, localeId);
TMTextUnitVariant tmTextUnitVariant = new TMTextUnitVariant();
tmTextUnitVariant.setTmTextUnit(tmTextUnit);
tmTextUnitVariant.setLocale(locale);
tmTextUnitVariant.setContent(content);
tmTextUnitVariant.setContentMD5(DigestUtils.md5Hex(content));
tmTextUnitVariant.setComment(comment);
tmTextUnitVariant.setStatus(status);
tmTextUnitVariant.setIncludedInLocalizedFile(includedInLocalizedFile);
tmTextUnitVariant.setCreatedDate(createdDate);
tmTextUnitVariant.setCreatedByUser(auditorAwareImpl.getCurrentAuditor());
tmTextUnitVariant = tmTextUnitVariantRepository.save(tmTextUnitVariant);
logger.trace("TMTextUnitVariant saved");
return tmTextUnitVariant;
}
/**
* Makes a {@link TMTextUnitVariant} current in a {@link TMTextUnit} for a
* given locale.
*
* @param tmId the TM id (must be the same as the tmTextUnit.getTm()) - used
* for denormalization
* @param tmTextUnitId the text unit that will contains the translation
* @param localeId locale id of the translation
* @param tmTextUnitVariantId the text unit variant id to be made current
* @return {@link TMTextUnitCurrentVariant} that contains the
* {@link TMTextUnitVariant}
* @throws DataIntegrityViolationException If tmId, tmTextUnitId or localeId
* are invalid
*/
protected TMTextUnitCurrentVariant makeTMTextUnitVariantCurrent(Long tmId, Long tmTextUnitId, Long localeId, Long tmTextUnitVariantId) {
logger.debug("Make the TMTextUnitVariant with id: {} current for locale: {}", tmTextUnitVariantId, localeId);
TMTextUnitCurrentVariant tmTextUnitCurrentVariant = new TMTextUnitCurrentVariant();
tmTextUnitCurrentVariant.setTm(entityManager.getReference(TM.class, tmId));
tmTextUnitCurrentVariant.setTmTextUnit(entityManager.getReference(TMTextUnit.class, tmTextUnitId));
tmTextUnitCurrentVariant.setTmTextUnitVariant(entityManager.getReference(TMTextUnitVariant.class, tmTextUnitVariantId));
tmTextUnitCurrentVariant.setLocale(entityManager.getReference(Locale.class, localeId));
tmTextUnitCurrentVariantRepository.save(tmTextUnitCurrentVariant);
logger.trace("TMTextUnitCurrentVariant persisted");
return tmTextUnitCurrentVariant;
}
/**
* Computes a MD5 hash for a {@link TMTextUnit}.
*
* @param name the text unit name
* @param content the text unit content
* @param comment the text unit comment
* @return the MD5 hash in Hex
*/
public String computeTMTextUnitMD5(String name, String content, String comment) {
return DigestUtils.md5Hex(name + content + comment);
}
/**
* Parses the XLIFF (from a translation kit) content and extract the
* new/changed variants. Then updates the TM with these new variants.
*
* @param xliffContent The content of the localized XLIFF TODO(P1) Use BCP47
* tag instead of Locale object?
* @param importStatus specific status to use when importing translation
* @return the imported XLIFF with information for each text unit about the
* import process
* @throws OkapiBadFilterInputException when XLIFF document is invalid
*/
public UpdateTMWithXLIFFResult updateTMWithTranslationKitXLIFF(
String xliffContent,
TMTextUnitVariant.Status importStatus) throws OkapiBadFilterInputException {
return updateTMWithXliff(xliffContent, importStatus, new ImportTranslationsWithTranslationKitStep());
}
public UpdateTMWithXLIFFResult updateTMWithXLIFFById(
String xliffContent,
TMTextUnitVariant.Status importStatus) throws OkapiBadFilterInputException {
return updateTMWithXliff(xliffContent, importStatus, new ImportTranslationsByIdStep());
}
/**
* Parses the XLIFF content and extract the new/changed variants by doing
* MD5 lookup for a given repository. Then updates the TM with these new
* variants. If the XLIFF is linked to an existing translation kit, use
* {@link #updateTMWithTranslationKitXLIFF(java.lang.String, com.box.l10n.mojito.entity.TMTextUnitVariant.Status) }
*
* @param xliffContent The content of the localized XLIFF TODO(P1) Use BCP47
* tag instead of Locale object?
* @param importStatus specific status to use when importing translation
* @param repository the repository in which to perform the import
* @return the imported XLIFF with information for each text unit about the
* import process
* @throws OkapiBadFilterInputException when XLIFF document is invalid
*/
public UpdateTMWithXLIFFResult updateTMWithXLIFFByMd5(
String xliffContent,
TMTextUnitVariant.Status importStatus,
Repository repository) throws OkapiBadFilterInputException {
return updateTMWithXliff(xliffContent, importStatus, new ImportTranslationsByMd5Step(repository));
}
/**
* Update TM with XLIFF.
*
* @param xliffContent The content of the localized XLIFF TODO(P1) Use BCP47
* tag instead of Locale object?
* @param importStatus specific status to use when importing translation
* @param abstractImportTranslationsStep defines which import logic to apply
* @return the imported XLIFF with information for each text unit about the
* import process
* @throws OkapiBadFilterInputException
*/
private UpdateTMWithXLIFFResult updateTMWithXliff(
String xliffContent,
TMTextUnitVariant.Status importStatus,
AbstractImportTranslationsStep abstractImportTranslationsStep) throws OkapiBadFilterInputException {
logger.debug("Configuring pipeline for localized XLIFF processing");
IPipelineDriver driver = new PipelineDriver();
driver.addStep(new RawDocumentToFilterEventsStep(new XLIFFFilter()));
driver.addStep(getConfiguredQualityStep());
IntegrityCheckStep integrityCheckStep = new IntegrityCheckStep();
driver.addStep(integrityCheckStep);
abstractImportTranslationsStep.setImportWithStatus(importStatus);
driver.addStep(abstractImportTranslationsStep);
//TODO(P1) It sounds like it's not possible to the XLIFFFilter for the output
// because the note is readonly mode and we need to override it to provide more information
logger.debug("Prepare FilterEventsWriterStep to use an XLIFFWriter with outputstream (allows only one doc to be processed)");
FilterEventsWriterStep filterEventsWriterStep = new FilterEventsWriterStep(new XLIFFWriter());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
filterEventsWriterStep.setOutputStream(byteArrayOutputStream);
filterEventsWriterStep.setOutputEncoding(StandardCharsets.UTF_8.toString());
driver.addStep(filterEventsWriterStep);
// We need to read first the target language, because if we wait for okapi to read
// it from the file it is too late to write the output with the XLIFFWriter
// (missing target language)
String targetLanguage = xliffUtils.getTargetLanguage(xliffContent);
LocaleId targetLocaleId = targetLanguage != null ? LocaleId.fromBCP47(targetLanguage) : LocaleId.EMPTY;
RawDocument rawDocument = new RawDocument(xliffContent, LocaleId.ENGLISH, targetLocaleId);
driver.addBatchItem(rawDocument, RawDocument.getFakeOutputURIForStream(), null);
logger.debug("Start processing batch");
driver.processBatch();
logger.debug("Get the Import report");
ImportTranslationsStepAnnotation importTranslationsStepAnnotation = rawDocument.getAnnotation(ImportTranslationsStepAnnotation.class);
UpdateTMWithXLIFFResult updateReport = new UpdateTMWithXLIFFResult();
updateReport.setXliffContent(StreamUtil.getUTF8OutputStreamAsString(byteArrayOutputStream));
updateReport.setComment(importTranslationsStepAnnotation.getComment());
return updateReport;
}
/**
* @return A {@code QualityCheckStep} that will only perform the needed
* checks
*/
private QualityCheckStep getConfiguredQualityStep() {
Parameters parameters = new Parameters();
parameters.disableAllChecks();
// only enable the checks we want
parameters.setEmptyTarget(true);
parameters.setTargetSameAsSource(true);
parameters.setTargetSameAsSourceForSameLanguage(true);
parameters.setLeadingWS(true);
parameters.setTrailingWS(true);
parameters.setDoubledWord(true);
parameters.setCheckXliffSchema(true);
QualityCheckStep qualityCheckStep = new QualityCheckStep();
qualityCheckStep.setParameters(parameters);
return qualityCheckStep;
}
/**
* Exports an {@link Asset} as XLIFF for a given locale.
*
* @param assetId {@link Asset#id} to be exported
* @param bcp47Tag bcp47tag of the locale that needs to be exported
* @return an XLIFF that contains {@link Asset}'s translation for that
* locale
*/
@Transactional
public String exportAssetAsXLIFF(Long assetId, String bcp47Tag) {
logger.debug("Export data for asset id: {} and locale: {}", assetId, bcp47Tag);
logger.trace("Create XLIFFWriter");
XLIFFWriter xliffWriter = new XLIFFWriter();
logger.trace("Prepare FilterEventsWriterStep to use an XLIFFWriter with outputstream (allows only one doc to be processed)");
FilterEventsWriterStep filterEventsWriterStep = new FilterEventsWriterStep(xliffWriter);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
filterEventsWriterStep.setOutputStream(byteArrayOutputStream);
filterEventsWriterStep.setOutputEncoding(StandardCharsets.UTF_8.toString());
logger.trace("Prepare the Okapi pipeline");
IPipelineDriver driver = new PipelineDriver();
driver.addStep(new RawDocumentToFilterEventsStep(new TMExportFilter(assetId)));
driver.addStep(filterEventsWriterStep);
logger.trace("Add single document with fake output URI to be processed with an outputStream");
Locale locale = localeService.findByBcp47Tag(bcp47Tag);
RawDocument rawDocument = new RawDocument(RawDocument.EMPTY, LocaleId.ENGLISH, LocaleId.fromBCP47(locale.getBcp47Tag()));
driver.addBatchItem(rawDocument, RawDocument.getFakeOutputURIForStream(), null);
logger.debug("Start processing batch");
driver.processBatch();
logger.trace("Get the output result from the stream");
return StreamUtil.getUTF8OutputStreamAsString(byteArrayOutputStream);
}
/**
* Parses the given content and adds the translation for every text unit.
* Returns the content of the localized content.
*
* TODO(P1) This needs to support other file formats
*
* @param asset The {@link Asset} used to get translations
* @param content The content to be localized
* @param repositoryLocale the repository locale used to fetch the
* translation. Also used for the output tag if outputBcp47tag is null.
* @param outputBcp47tag Optional, can be null. Allows to generate the file
* for a bcp47 tag that is different from the repository locale (which is
* still used to fetch the translations). This can be used to generate a
* file with tag "fr" even if the translations are stored with fr-FR
* repository locale.
* @param inheritanceMode
* @param status
* @return the localized asset
*/
public String generateLocalized(
Asset asset,
String content,
RepositoryLocale repositoryLocale,
String outputBcp47tag,
FilterConfigIdOverride filterConfigIdOverride,
InheritanceMode inheritanceMode,
Status status) {
String bcp47Tag;
if (outputBcp47tag == null) {
bcp47Tag = repositoryLocale.getLocale().getBcp47Tag();
} else {
logger.debug("An output bcp47 tag: {} is specified (won't use the default tag (from the repository locale)", outputBcp47tag);
bcp47Tag = outputBcp47tag;
}
logger.debug("Configuring pipeline for localized XLIFF generation");
BasePipelineStep translateStep = (BasePipelineStep) new TranslateStep(asset, repositoryLocale, inheritanceMode, status);
return generateLocalizedBase(asset, content, filterConfigIdOverride, bcp47Tag, translateStep);
}
/**
* Parses the given content and adds the pseudo localization for every text
* unit. Returns the pseudolocalized content.
*
* @param asset The {@link Asset} used to get translations
* @param content The content to be pseudolocalized
* @return the pseudolocalized asset
*/
public String generatePseudoLocalized(
Asset asset,
String content,
FilterConfigIdOverride filterConfigIdOverride) {
String bcp47tag = "en-x-psaccent";
BasePipelineStep pseudoLocalizedStep = (BasePipelineStep) new PseudoLocalizeStep();
return generateLocalizedBase(asset, content, filterConfigIdOverride, bcp47tag, pseudoLocalizedStep);
}
/**
* Parses the given content and adds the translation for every text unit.
* Returns the content of the localized content.
*
* TODO(P1) This needs to support other file formats
*
* @param asset The {@link Asset} used to get translations
* @param content The content to be localized
* @param filterConfigIdOverride
* @param outputBcp47tag Optional, can be null. Allows to generate the file
* for a bcp47 tag that is different from the repository locale (which is
* still used to fetch the translations). This can be used to generate a
* file with tag "fr" even if the translations are stored with fr-FR
* repository locale.
* @param step
* @return the localized asset
*/
private String generateLocalizedBase(Asset asset, String content, FilterConfigIdOverride filterConfigIdOverride, String outputBcp47tag, BasePipelineStep step) {
IPipelineDriver driver = new PipelineDriver();
driver.addStep(new RawDocumentToFilterEventsStep());
driver.addStep(new CheckForDoNotTranslateStep());
driver.addStep(step);
//TODO(P1) see assetExtractor comments
logger.debug("Adding all supported filters to the pipeline driver");
driver.setFilterConfigurationMapper(assetExtractor.getConfiguredFilterConfigurationMapper());
FilterEventsToInMemoryRawDocumentStep filterEventsToInMemoryRawDocumentStep = new FilterEventsToInMemoryRawDocumentStep();
driver.addStep(filterEventsToInMemoryRawDocumentStep);
LocaleId targetLocaleId = LocaleId.fromBCP47(outputBcp47tag);
RawDocument rawDocument = new RawDocument(content, LocaleId.ENGLISH, targetLocaleId);
//TODO(P1) see assetExtractor comments
String filterConfigId;
if (filterConfigIdOverride != null) {
filterConfigId = filterConfigIdOverride.getOkapiFilterId();
} else {
filterConfigId = assetExtractor.getFilterConfigIdForAsset(asset);
}
rawDocument.setFilterConfigId(filterConfigId);
logger.debug("Set filter config {} for asset {}", filterConfigId, asset.getPath());
driver.addBatchItem(rawDocument);
logger.debug("Start processing batch");
driver.processBatch();
String localizedContent = filterEventsToInMemoryRawDocumentStep.getOutput(rawDocument);
return localizedContent;
}
/**
* Imports a localized version of an asset.
*
* The target strings are checked against the source strings and if they are
* equals the status of the imported translation is defined by
* statusForEqualTarget. When SKIPED is specified the import is actually
* skipped.
*
* For not fully translated locales, targets are imported only if they are
* different from target of the parent locale.
*
* @param asset the asset for which the content will be imported
* @param content the localized asset content
* @param repositoryLocale the locale of the content to be imported
* @param statusForEqualtarget the status of the text unit variant when
* the source equals the target
* @param filterConfigIdOverride to override the filter used to process the
* asset
* @return
*/
@Pollable(async = true, message = "Import localized asset")
public PollableFuture importLocalizedAsset(
Asset asset,
String content,
RepositoryLocale repositoryLocale,
StatusForEqualTarget statusForEqualtarget,
FilterConfigIdOverride filterConfigIdOverride) {
PollableFuture pollableFuture = new PollableFutureTaskResult();
String bcp47Tag = repositoryLocale.getLocale().getBcp47Tag();
logger.debug("Configuring pipeline to import localized file");
IPipelineDriver driver = new PipelineDriver();
driver.addStep(new RawDocumentToFilterEventsStep());
driver.addStep(new CheckForDoNotTranslateStep());
driver.addStep(new ImportTranslationsFromLocalizedAssetStep(asset, repositoryLocale, statusForEqualtarget));
logger.debug("Adding all supported filters to the pipeline driver");
driver.setFilterConfigurationMapper(assetExtractor.getConfiguredFilterConfigurationMapper());
FilterEventsToInMemoryRawDocumentStep filterEventsToInMemoryRawDocumentStep = new FilterEventsToInMemoryRawDocumentStep();
driver.addStep(filterEventsToInMemoryRawDocumentStep);
LocaleId targetLocaleId = LocaleId.fromBCP47(bcp47Tag);
RawDocument rawDocument = new RawDocument(content, LocaleId.ENGLISH, targetLocaleId);
rawDocument.setAnnotation(new CopyFormsOnImport());
String filterConfigId;
if (filterConfigIdOverride != null) {
filterConfigId = filterConfigIdOverride.getOkapiFilterId();
} else {
filterConfigId = assetExtractor.getFilterConfigIdForAsset(asset);
}
rawDocument.setFilterConfigId(filterConfigId);
logger.debug("Set filter config {} for asset {}", filterConfigId, asset.getPath());
driver.addBatchItem(rawDocument);
logger.debug("Start processing batch");
processBatchInTransaction(driver);
return pollableFuture;
}
@Transactional
void processBatchInTransaction(IPipelineDriver driver) {
driver.processBatch();
}
/**
* Exports an {@link Asset} as XLIFF for a given locale asynchronously.
*
* @param tmXliffId {@link TMXliff#id} to persist generated XLIFF
* @param assetId {@link Asset#id} to be exported
* @param bcp47Tag bcp47tag of the locale that needs to be exported
* @param currentTask
* @return {@link PollableFutureTaskResult} that contains an XLIFF as result
*/
@Pollable(async = true, message = "Export asset as xliff")
public PollableFuture<String> exportAssetAsXLIFFAsync(
Long tmXliffId,
Long assetId,
String bcp47Tag,
@InjectCurrentTask PollableTask currentTask) {
PollableFutureTaskResult<String> pollableFutureTaskResult = new PollableFutureTaskResult<>();
String xliff = exportAssetAsXLIFF(assetId, bcp47Tag);
TMXliff tmXliff = tmXliffRepository.findOne(tmXliffId);
tmXliff.setAsset(assetRepository.findOne(assetId));
tmXliff.setLocale(localeService.findByBcp47Tag(bcp47Tag));
tmXliff.setContent(xliff);
tmXliff.setPollableTask(currentTask);
tmXliffRepository.save(tmXliff);
pollableFutureTaskResult.setResult(xliff);
return pollableFutureTaskResult;
}
public TMXliff createTMXliff(Long assetId, String bcp47Tag, String content, PollableTask pollableTask) {
TMXliff tmXliff = new TMXliff();
tmXliff.setAsset(assetRepository.findOne(assetId));
tmXliff.setLocale(localeService.findByBcp47Tag(bcp47Tag));
tmXliff.setContent(content);
tmXliff.setPollableTask(pollableTask);
tmXliff = tmXliffRepository.save(tmXliff);
return tmXliff;
}
}
|
package io.seqware.pancancer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import net.sourceforge.seqware.pipeline.workflowV2.AbstractWorkflowDataModel;
import net.sourceforge.seqware.pipeline.workflowV2.model.Job;
import net.sourceforge.seqware.pipeline.workflowV2.model.SqwFile;
import org.apache.commons.lang.StringUtils;
import io.seqware.pancancer.Version;
import java.util.UUID;
public class CgpSomaticCore extends AbstractWorkflowDataModel {
private static String OUTDIR = "outdir";
private static String TIMEDIR;
private static String COUNTDIR;
private static String BBDIR;
private boolean cleanup = false;
private boolean cleanupBams = false;
// datetime all upload files will be named with
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String dateString = df.format(Calendar.getInstance().getTime());
private String workflowName = Version.WORKFLOW_SHORT_NAME_VERSION;
// MEMORY variables //
private String memGenerateBasFile, memPackageResults, memMarkTime,
memQcMetrics, memGenotype, memContam,
memBbMerge,
// ascat memory
memAlleleCount, memAscat, memAscatFinalise,
// pindel memory
memPindelInput, memPindelPerThread, memPindelVcf, memPindelMerge , memPindelFlag,
// brass memory
memBrassInput, memBrassCoverPerThread, memBrassCoverMerge, memBrassGroup, memBrassIsize,
memBrassNormCn, memBrassFilter, memBrassSplit,
memBrassAssemblePerThread, memBrassGrass, memBrassTabix,
// caveman memory
memCaveCnPrep,
memCavemanSetup, memCavemanSplit, memCavemanSplitConcat,
memCavemanMstepPerThread, memCavemanMerge, memCavemanEstepPerThread,
memCavemanMergeResults, memCavemanAddIds, memCavemanFlag
;
// workflow variables
private String // reference variables
species, assembly, refFrom, bbFrom,
// sequencing type/protocol
seqType, seqProtocol,
//GNOS identifiers
pemFile, uploadPemFile, gnosServer, uploadServer,
// ascat variables
gender,
// pindel variables
refExclude, pindelGermline,
//general variables
installBase, refBase, genomeFa, testBase,
//contamination variables
contamDownSampOneIn
;
private int coresAddressable, memWorkflowOverhead, memHostMbAvailable;
// UUID
private String uuid = UUID.randomUUID().toString().toLowerCase();
// if localFileMode, this is the path at which the workflow will find the XML files used for metadata in the upload of VCF
// private String localXMLMetadataPath = null;
// private String localBamFilePathPrefix = null;
// used for downloading from S3
// private boolean downloadBamsFromS3 = false;
// private String normalS3Url = "";
// private ArrayList<String> tumorS3Urls = null;
// private String S3DownloadKey = "";
// private String S3DownloadSecretKey = "";
private void init() {
try {
//optional properties
String outDir = OUTDIR;
String outPrefix = "";
if (hasPropertyAndNotNull("output_dir")) {
outDir = getProperty("output_dir");
}
if (hasPropertyAndNotNull("output_prefix")) {
outPrefix = getProperty("output_prefix");
}
if (!"".equals(outPrefix)) {
if (outPrefix.endsWith("/")) {
OUTDIR = outPrefix+outDir;
} else {
OUTDIR = outPrefix + "/" + outDir;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
TIMEDIR = OUTDIR + "/timings";
COUNTDIR = OUTDIR + "/ngsCounts";
BBDIR = OUTDIR + "/bbCounts";
}
@Override
public void setupDirectory() {
//since setupDirectory is the first method run, we use it to initialize variables too.
init();
// creates a dir1 directory in the current working directory where the workflow runs
addDirectory(OUTDIR);
addDirectory(TIMEDIR);
addDirectory(COUNTDIR);
addDirectory(BBDIR);
}
@Override
public Map<String, SqwFile> setupFiles() {
try {
if(hasPropertyAndNotNull("cleanup")) {
cleanup = Boolean.valueOf(getProperty("cleanup"));
}
if(hasPropertyAndNotNull("cleanupBams")) {
cleanupBams = Boolean.valueOf(getProperty("cleanupBams"));
}
// used by steps that can use all available cores
coresAddressable = Integer.valueOf(getProperty("coresAddressable"));
// MEMORY //
memGenerateBasFile = getProperty("memGenerateBasFile");
memPackageResults = getProperty("memPackageResults");
memMarkTime = getProperty("memMarkTime");
memQcMetrics = getProperty("memQcMetrics");
memGenotype = getProperty("memGenotype");
memContam = getProperty("memContam");
memBbMerge = getProperty("memBbMerge");
memAlleleCount = getProperty("memAlleleCount");
memAscat = getProperty("memAscat");
memAscatFinalise = getProperty("memAscatFinalise");
memPindelInput = getProperty("memPindelInput");
memPindelPerThread = getProperty("memPindelPerThread");
memPindelVcf = getProperty("memPindelVcf");
memPindelMerge = getProperty("memPindelMerge");
memPindelFlag = getProperty("memPindelFlag");
memBrassInput = getProperty("memBrassInput");
memBrassCoverPerThread = getProperty("memBrassCoverPerThread");
memBrassCoverMerge = getProperty("memBrassCoverMerge");
memBrassGroup = getProperty("memBrassGroup");
memBrassIsize = getProperty("memBrassIsize");
memBrassNormCn = getProperty("memBrassNormCn");
memBrassFilter = getProperty("memBrassFilter");
memBrassSplit = getProperty("memBrassSplit");
memBrassAssemblePerThread = getProperty("memBrassAssemblePerThread");
memBrassGrass = getProperty("memBrassGrass");
memBrassTabix = getProperty("memBrassTabix");
memCaveCnPrep = getProperty("memCaveCnPrep");
memCavemanSetup = getProperty("memCavemanSetup");
memCavemanSplit = getProperty("memCavemanSplit");
memCavemanSplitConcat = getProperty("memCavemanSplitConcat");
memCavemanMstepPerThread = getProperty("memCavemanMstepPerThread");
memCavemanMerge = getProperty("memCavemanMerge");
memCavemanEstepPerThread = getProperty("memCavemanEstepPerThread");
memCavemanMergeResults = getProperty("memCavemanMergeResults");
memCavemanAddIds = getProperty("memCavemanAddIds");
memCavemanFlag = getProperty("memCavemanFlag");
memWorkflowOverhead = Integer.valueOf(getProperty("memWorkflowOverhead"));
memHostMbAvailable = Integer.valueOf(getProperty("memHostMbAvailable"));
contamDownSampOneIn = getProperty("contamDownSampOneIn");
// REFERENCE INFO //
species = getProperty("species");
assembly = getProperty("assembly");
refFrom = getProperty("refFrom");
bbFrom = getProperty("bbFrom");
// Sequencing info
seqType = getProperty("seqType");
if(seqType.equals("WGS")) {
seqProtocol = "genomic";
}
// Specific to ASCAT workflow //
gender = getProperty("gender");
// pindel specific
refExclude = getProperty("refExclude");
//environment
installBase = "/opt/wtsi-cgp";
refBase = OUTDIR + "/reference_files";
genomeFa = refBase + "/genome.fa";
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return getFiles();
}
@Override
public void buildWorkflow() {
Job startDownload = markTime("download", "start");
startDownload.setMaxMemory(memMarkTime);
String tmpRef = OUTDIR + "/" + "ref.tar.gz";
Job pullRef = pullRef(refFrom, tmpRef);
pullRef.addParent(startDownload);
pullRef.setMaxMemory(memMarkTime);
String tmpBbRef = OUTDIR + "/" + "bb.tar.gz";
Job pullBbRef = pullRef(bbFrom, tmpBbRef);
pullBbRef.addParent(startDownload);
pullBbRef.setMaxMemory(memMarkTime);
Job unpackRef = unpackRef(tmpRef, null);
unpackRef.addParent(pullRef);
unpackRef.setMaxMemory(memMarkTime);
Job unpackBbRef = unpackRef(tmpBbRef, "reference_files");
unpackBbRef.addParent(unpackRef);
unpackBbRef.setMaxMemory(memMarkTime);
Job startWorkflow = markTime("workflow", "start");
startWorkflow.setMaxMemory(memMarkTime);
startWorkflow.addParent(unpackRef);
startWorkflow.addParent(pullBbRef);
try {
List<Job> downloadJobsList = new ArrayList<Job>();
String controlBam = getProperty("controlBam");
// @todo need to add code to generate BAS for BAM
Job controlBasJob = basFileBaseJob(0, controlBam, "control", 0);
controlBasJob.setMaxMemory(memGenerateBasFile);
controlBasJob.addParent(unpackRef);
downloadJobsList.add(controlBasJob);
List<String> tumourBams = new ArrayList<String>();
List<Job> tumourBasJobs = new ArrayList<Job>();
List<String> rawBams = Arrays.asList(getProperty("tumourBams").split(":"));
if(rawBams.size() == 0) {
throw new RuntimeException("Propertie tumourBams has no list of BAM files");
}
int tumBamCount = rawBams.size();
for(int i=0; i<tumBamCount; i++) {
String tumourBam = rawBams.get(i);
Job tumourBasJob = basFileBaseJob(tumBamCount, tumourBam, "tumours", i+1);
tumourBasJob.setMaxMemory(memGenerateBasFile);
tumourBasJob.addParent(unpackRef);
tumourBasJobs.add(tumourBasJob);
tumourBams.add(tumourBam);
downloadJobsList.add(tumourBasJob);
}
Job genotypeJob = genoptypeBaseJob(tumourBams, controlBam);
genotypeJob.setMaxMemory(memGenotype);
addJobParents(genotypeJob, downloadJobsList);
Job genotypePackJob = packageGenotype(tumourBams, controlBam);
genotypePackJob.setMaxMemory("4000");
genotypePackJob.addParent(genotypeJob);
Job contaminationJob = contaminationBaseJob(tumBamCount, controlBam, "control");
contaminationJob.setMaxMemory(memContam);
addJobParents(contaminationJob, downloadJobsList);
// packaging must have parent cavemanTbiCleanJob
// these are not paired but per individual sample
List<Job> bbAlleleCountJobs = new ArrayList<Job>();
for(int i=0; i<23; i++) { // not 1-22+X
for(int j=0; j<tumBamCount; j++) {
Job bbAlleleCountJob = bbAlleleCount(j, tumourBams.get(j), "tumour", i);
bbAlleleCountJob.setMaxMemory(memAlleleCount);
addJobParents(bbAlleleCountJob, downloadJobsList);
bbAlleleCountJobs.add(bbAlleleCountJob);
}
Job bbAlleleCountJob = bbAlleleCount(1, controlBam, "control", i);
bbAlleleCountJob.setMaxMemory(memAlleleCount);
addJobParents(bbAlleleCountJob, downloadJobsList);
bbAlleleCountJobs.add(bbAlleleCountJob);
}
Job bbAlleleMergeJob = bbAlleleMerge(controlBam);
bbAlleleMergeJob.setMaxMemory(memBbMerge);
for(Job j : bbAlleleCountJobs) {
bbAlleleMergeJob.addParent(j);
}
// donor based workflow section
Job[] cavemanFlagJobs = new Job [tumBamCount];
for(int i=0; i<tumBamCount; i++) {
Job cavemanFlagJob = buildPairWorkflow(downloadJobsList, controlBam, tumourBams.get(i), i);
cavemanFlagJobs[i] = cavemanFlagJob;
}
Job endWorkflow = markTime("workflow", "end");
endWorkflow.setMaxMemory(memMarkTime);
for(Job cavemanFlagJob : cavemanFlagJobs) {
endWorkflow.addParent(cavemanFlagJob);
}
Job metricsJob = getMetricsJob(tumourBams, controlBam);
metricsJob.setMaxMemory(memQcMetrics);
metricsJob.addParent(endWorkflow);
Job renameGenotypeJob = renameSampleFile(tumourBams, OUTDIR, "genotype.tar.gz");
renameGenotypeJob.setMaxMemory("4000");
renameGenotypeJob.addParent(genotypePackJob);
Job renameGenotypeMd5Job = renameSampleFile(tumourBams, OUTDIR, "genotype.tar.gz.md5");
renameGenotypeMd5Job.setMaxMemory("4000");
renameGenotypeMd5Job.addParent(genotypePackJob);
Job packageContamJob = packageContam(tumourBams, controlBam);
packageContamJob.setMaxMemory("4000");
for(Job cavemanFlagJob : cavemanFlagJobs) {
packageContamJob.addParent(cavemanFlagJob);
}
Job renameContamJob = renameSampleFile(tumourBams, OUTDIR, "verifyBamId.tar.gz");
renameContamJob.setMaxMemory("4000");
renameContamJob.addParent(packageContamJob);
Job renameContamMd5Job = renameSampleFile(tumourBams, OUTDIR, "verifyBamId.tar.gz.md5");
renameContamMd5Job.setMaxMemory("4000");
renameContamMd5Job.addParent(packageContamJob);
Job renameImputeJob = renameSampleFile(tumourBams, OUTDIR + "/bbCounts", "imputeCounts.tar.gz");
renameImputeJob.setMaxMemory("4000");
renameImputeJob.addParent(bbAlleleMergeJob);
Job renameImputeMd5Job = renameSampleFile(tumourBams, OUTDIR + "/bbCounts", "imputeCounts.tar.gz.md5");
renameImputeMd5Job.setMaxMemory("4000");
renameImputeMd5Job.addParent(bbAlleleMergeJob);
// delete just the BAM inputs and not the output dir
if (cleanup || cleanupBams) {
Job cleanInputsJob = cleanJob();
cleanInputsJob.addParent(metricsJob);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
}
/**
* This builds the workflow for a pair of samples
* The generic buildWorkflow section will choose the pair to be processed and
* setup the control sample download
*/
private Job buildPairWorkflow(List downloadJobsList, String controlBam, String tumourBam, int tumourCount) {
/**
* ASCAT - Copynumber
* Depends on
* - tumour/control BAMs
* - Gender, will attempt to determine if not specified
*/
Job[] alleleCountJobs = new Job[2];
for(int i=0; i<2; i++) {
Job alleleCountJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "allele_count", i+1);
alleleCountJob.setMaxMemory(memAlleleCount);
addJobParents(alleleCountJob, downloadJobsList);
alleleCountJobs[i] = alleleCountJob;
}
Job ascatJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "ascat", 1);
ascatJob.setMaxMemory(memAscat);
ascatJob.addParent(alleleCountJobs[0]);
ascatJob.addParent(alleleCountJobs[1]);
Job ascatFinaliseJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "finalise", 1);
ascatFinaliseJob.setMaxMemory(memAscatFinalise);
ascatFinaliseJob.addParent(ascatJob);
Job ascatPackage = packageResults(tumourCount, "ascat", "cnv", tumourBam, "copynumber.caveman.vcf.gz", workflowName, "somatic", dateString);
ascatPackage.setMaxMemory(memPackageResults);
ascatPackage.addParent(ascatFinaliseJob);
Job contaminationJob = contaminationBaseJob(tumourCount, tumourBam, "tumour");
contaminationJob.setMaxMemory(memContam);
contaminationJob.addParent(ascatFinaliseJob);
/**
* CaVEMan setup is here to allow better workflow graph
* Messy but necessary
*/
Job caveCnPrepJobs[] = new Job[2];
for(int i=0; i<2; i++) {
Job caveCnPrepJob;
if(i==0) {
caveCnPrepJob = caveCnPrep(tumourCount, "tumour");
}
else {
caveCnPrepJob = caveCnPrep(tumourCount, "normal");
}
addJobParents(caveCnPrepJob, downloadJobsList);
caveCnPrepJob.addParent(ascatFinaliseJob); // ASCAT dependency!!!
caveCnPrepJobs[i] = caveCnPrepJob;
}
Job cavemanSetupJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "setup", 1);
cavemanSetupJob.setMaxMemory(memCavemanSetup);
cavemanSetupJob.addParent(caveCnPrepJobs[0]);
cavemanSetupJob.addParent(caveCnPrepJobs[1]);
// some dependencies handled by ascat step
/**
* Pindel - InDel calling
* Depends on:
* - tumour/control BAMs
*/
Job[] pindelInputJobs = new Job[2];
for(int i=0; i<2; i++) {
Job inputParse = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "input", i+1);
// If you tell SGE you are using ,multiple cores it multiplies the requested memory for you
inputParse.setMaxMemory( memPindelInput );
addJobParents(inputParse, downloadJobsList);
pindelInputJobs[i] = inputParse;
}
int pindelNormalisedThreads = pindelNormalisedThreads(memPindelPerThread, coresAddressable);
int totalPindelMem = Integer.valueOf(memPindelPerThread) + (Integer.valueOf(memWorkflowOverhead) / pindelNormalisedThreads);
Job pindelJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "pindel", 1);
pindelJob.getCommand().addArgument("-l " + pindelNormalisedThreads);
pindelJob.getCommand().addArgument("-c " + pindelNormalisedThreads);
pindelJob.setMaxMemory(Integer.toString(totalPindelMem));
pindelJob.setThreads(pindelNormalisedThreads);
pindelJob.addParent(pindelInputJobs[0]);
pindelJob.addParent(pindelInputJobs[1]);
// determine number of refs to process
// we know that this is static for PanCancer so be lazy 24 jobs (1-22,X,Y)
// but pindel needs to know the exclude list so hard code this
Job pinVcfJobs[] = new Job[24];
for(int i=0; i<24; i++) {
Job pinVcfJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "pin2vcf", i+1);
pinVcfJob.setMaxMemory(memPindelVcf);
pinVcfJob.addParent(pindelJob);
pinVcfJobs[i] = pinVcfJob;
}
Job pindelMergeJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "merge", 1);
pindelMergeJob.setMaxMemory(memPindelMerge);
for (Job parent : pinVcfJobs) {
pindelMergeJob.addParent(parent);
}
Job pindelFlagJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "flag", 1);
pindelFlagJob.setMaxMemory(memPindelFlag);
pindelFlagJob.addParent(pindelMergeJob);
pindelFlagJob.addParent(cavemanSetupJob);
Job pindelPackage = packageResults(tumourCount, "pindel", "indel", tumourBam, "flagged.vcf.gz", workflowName, "somatic", dateString);
pindelPackage.setMaxMemory(memPackageResults);
pindelPackage.addParent(pindelFlagJob);
/**
* BRASS - BReakpoint AnalySiS
* Depends on:
* - tumour/control BAMs
* - ASCAT output at filter step
*/
Job brassInputJobs[] = new Job[2];
for(int i=0; i<2; i++) {
Job brassInputJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "input", i+1);
brassInputJob.setMaxMemory(memBrassInput);
addJobParents(brassInputJob, downloadJobsList);
brassInputJobs[i] = brassInputJob;
}
int brassCoverNormalisedThreads = getMemNormalisedThread(memBrassCoverPerThread, coresAddressable);
int totalBrassCoverMem = Integer.valueOf(memBrassCoverPerThread) + (Integer.valueOf(memWorkflowOverhead) / brassCoverNormalisedThreads);
Job brassCoverJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "cover", 1);
brassCoverJob.getCommand().addArgument("-l " + brassCoverNormalisedThreads);
brassCoverJob.getCommand().addArgument("-c " + brassCoverNormalisedThreads);
brassCoverJob.setMaxMemory(Integer.toString(totalBrassCoverMem));
brassCoverJob.setThreads(brassCoverNormalisedThreads);
brassCoverJob.addParent(brassInputJobs[0]);
brassCoverJob.addParent(brassInputJobs[1]);
Job brassCoverMergeJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "merge", 1);
brassCoverMergeJob.setMaxMemory(memBrassCoverMerge);
brassCoverMergeJob.addParent(brassCoverJob);
Job brassGroupJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "group", 1);
brassGroupJob.setMaxMemory(memBrassGroup);
brassGroupJob.addParent(brassCoverJob);
Job brassIsizeJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "isize", 1);
brassIsizeJob.setMaxMemory(memBrassIsize);
brassIsizeJob.addParent(brassCoverMergeJob);
Job brassNormCnJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "normcn", 1);
brassNormCnJob.setMaxMemory(memBrassNormCn);
brassNormCnJob.addParent(brassCoverMergeJob);
Job brassFilterJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "filter", 1);
brassFilterJob.setMaxMemory(memBrassFilter);
brassFilterJob.addParent(brassGroupJob);
brassFilterJob.addParent(brassIsizeJob);
brassFilterJob.addParent(brassNormCnJob);
brassFilterJob.addParent(ascatFinaliseJob); // NOTE: dependency on ASCAT!!
Job brassSplitJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "split", 1);
brassSplitJob.setMaxMemory(memBrassSplit);
brassSplitJob.addParent(brassFilterJob);
int brassAssNormalisedThreads = getMemNormalisedThread(memBrassAssemblePerThread, coresAddressable);
int totalBrassAssMem = Integer.valueOf(memBrassAssemblePerThread) + (Integer.valueOf(memWorkflowOverhead) / brassAssNormalisedThreads);
Job brassAssembleJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "assemble", 1);
brassAssembleJob.getCommand().addArgument("-l " + brassAssNormalisedThreads);
brassAssembleJob.getCommand().addArgument("-c " + brassAssNormalisedThreads);
brassAssembleJob.setMaxMemory(Integer.toString(totalBrassAssMem));
brassAssembleJob.setThreads(brassAssNormalisedThreads);
brassAssembleJob.addParent(brassSplitJob);
Job brassGrassJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "grass", 1);
brassGrassJob.setMaxMemory(memBrassGrass);
brassGrassJob.addParent(brassAssembleJob);
Job brassTabixJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "tabix", 1);
brassTabixJob.setMaxMemory(memBrassTabix);
brassTabixJob.addParent(brassGrassJob);
Job brassPackage = packageResults(tumourCount, "brass", "sv", tumourBam, "annot.vcf.gz", workflowName, "somatic", dateString);
brassPackage.setMaxMemory(memPackageResults);
brassPackage.addParent(brassTabixJob);
/**
* CaVEMan - SNV analysis
* !! see above as setup done earlier to help with workflow structure !!
* Depends on:
* - tumour/control BAMs (but depend on BAS for better workflow)
* - ASCAT from outset
* - pindel at flag step
*/
// should really line count the fai file
Job cavemanSplitJobs[] = new Job[86];
for(int i=0; i<86; i++) {
Job cavemanSplitJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "split", i+1);
cavemanSplitJob.setMaxMemory(memCavemanSplit);
cavemanSplitJob.addParent(cavemanSetupJob);
cavemanSplitJobs[i] = cavemanSplitJob;
}
Job cavemanSplitConcatJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "split_concat", 1);
cavemanSplitConcatJob.setMaxMemory(memCavemanSplitConcat);
for (Job cavemanSplitJob : cavemanSplitJobs) {
cavemanSplitConcatJob.addParent(cavemanSplitJob);
}
int mstepNormalisedThreads = getMemNormalisedThread(memCavemanMstepPerThread, coresAddressable);
int totalMstepMem = Integer.valueOf(memCavemanMstepPerThread) + (Integer.valueOf(memWorkflowOverhead) / mstepNormalisedThreads);
Job cavemanMstepJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "mstep", 1);
cavemanMstepJob.getCommand().addArgument("-l " + mstepNormalisedThreads);
cavemanMstepJob.getCommand().addArgument("-t " + mstepNormalisedThreads);
cavemanMstepJob.setMaxMemory(Integer.toString(totalMstepMem));
cavemanMstepJob.setThreads(mstepNormalisedThreads);
cavemanMstepJob.addParent(cavemanSplitConcatJob);
Job cavemanMergeJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "merge", 1);
cavemanMergeJob.setMaxMemory(memCavemanMerge);
cavemanMergeJob.addParent(cavemanMstepJob);
int estepNormalisedThreads = getMemNormalisedThread(memCavemanEstepPerThread, coresAddressable);
int totalEstepMem = Integer.valueOf(memCavemanEstepPerThread) + (Integer.valueOf(memWorkflowOverhead) / estepNormalisedThreads);
Job cavemanEstepJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "estep", 1);
cavemanEstepJob.getCommand().addArgument("-l " + estepNormalisedThreads);
cavemanEstepJob.getCommand().addArgument("-t " + estepNormalisedThreads);
cavemanEstepJob.setMaxMemory(Integer.toString(totalEstepMem));
cavemanEstepJob.setThreads(estepNormalisedThreads);
cavemanEstepJob.addParent(cavemanMergeJob);
Job cavemanMergeResultsJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "merge_results", 1);
cavemanMergeResultsJob.setMaxMemory(memCavemanMergeResults);
cavemanMergeResultsJob.addParent(cavemanEstepJob);
Job cavemanAddIdsJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "add_ids", 1);
cavemanAddIdsJob.setMaxMemory(memCavemanAddIds);
cavemanAddIdsJob.addParent(cavemanMergeResultsJob);
Job cavemanFlagJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "flag", 1);
cavemanFlagJob.setMaxMemory(memCavemanFlag);
addJobParents(cavemanFlagJob, downloadJobsList);
cavemanFlagJob.addParent(pindelFlagJob); // PINDEL dependency
cavemanFlagJob.addParent(cavemanAddIdsJob);
cavemanFlagJob.addParent(contaminationJob);
Job cavemanPackage = packageResults(tumourCount, "caveman", "snv_mnv", tumourBam, "flagged.muts.vcf.gz", workflowName, "somatic", dateString);
cavemanPackage.setMaxMemory(memPackageResults);
cavemanPackage.addParent(cavemanFlagJob);
return cavemanFlagJob;
}
private void addJobParents(Job child, List<Job> parents) {
for(int i=0; i<parents.size(); i++) {
child.addParent(parents.get(i));
}
}
/**
* This allows for other processes to run along side if the number of cores
* will allow. Added in an attempt to prevent increased wall time for the
* whole workflow.
*
* @param memPerThread Memory in MB consumed by each thread
* @param totalCores Total number of cores available to the workflow
* @return Number of threads usable based on per-thread and system overhead.
*/
private int pindelNormalisedThreads(String memPerThread, int totalCores) {
int sensibleCores = totalCores;
if(sensibleCores > 12) {
sensibleCores = totalCores - 2;
}
int pindelNormalisedThreads = getMemNormalisedThread(memPerThread, sensibleCores);
return pindelNormalisedThreads;
}
private Job bbAlleleCount(int sampleIndex, String bam, String process, int index) {
Job thisJob = prepTimedJob(sampleIndex, "bbAllele", process, index);
int chr = index+1;
thisJob.getCommand()
.addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh")
.addArgument(installBase)
.addArgument(getWorkflowBaseDir()+ "/bin/execute_with_sample.pl " + bam)
.addArgument("alleleCounter")
.addArgument("-l " + refBase + "/battenberg/1000genomesloci/1000genomesloci2012_chr" + chr + ".txt")
.addArgument("-o " + BBDIR + "/%SM%." + chr + ".tsv")
.addArgument("-b " + bam)
;
return thisJob;
}
private Job bbAlleleMerge(String controlBam) {
Job thisJob = prepTimedJob(0, "bbAllele", "merge", 1);
thisJob.getCommand()
.addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh")
.addArgument(installBase)
.addArgument(getWorkflowBaseDir()+ "/bin/packageImpute.pl")
.addArgument(controlBam)
.addArgument(BBDIR)
;
return thisJob;
}
private Job renameSampleFile(List<String> bams, String dir, String extension) {
Job thisJob = getWorkflow().createBashJob("renameSampleFile");
for(String bam : bams) {
thisJob.getCommand()
.addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh")
.addArgument(installBase)
.addArgument(getWorkflowBaseDir()+ "/bin/execute_with_sample.pl " + bam)
.addArgument("cp " + dir + "/" + "%SM%." + extension)
.addArgument(OUTDIR + "/" + "%SM%." + workflowName + "." + dateString + ".somatic." + extension)
.addArgument(";");
;
}
return thisJob;
}
private Job packageResults(int tumourCount, String algName, String resultType, String tumourBam, String baseVcf, String workflowName, String somaticOrGermline, String date) {
//#packageResults.pl outdir 0772aed3-4df7-403f-802a-808df2935cd1/c007f362d965b32174ec030825262714.bam outdir/caveman snv_mnv flagged.muts.vcf.gz
Job thisJob = getWorkflow().createBashJob("packageResults");
thisJob.getCommand()
.addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh")
.addArgument(installBase)
.addArgument(getWorkflowBaseDir() + "/bin/packageResults.pl")
.addArgument(OUTDIR)
.addArgument(tumourBam)
.addArgument(OUTDIR + "/" + tumourCount + "/" + algName)
.addArgument(resultType)
.addArgument(baseVcf)
.addArgument(workflowName)
.addArgument(somaticOrGermline)
.addArgument(date)
;
return thisJob;
}
private int getMemNormalisedThread(String perThreadMemory, int threads) {
int usableThreads = 0;
// memWorkflowOverhead, memHostMbAvailable
int memoryAvail = memHostMbAvailable - memWorkflowOverhead;
if((memoryAvail / threads) >= Integer.valueOf(perThreadMemory)) {
usableThreads = threads;
}
else {
usableThreads = memoryAvail / Integer.valueOf(perThreadMemory);
}
if(usableThreads == 0) {
throw new RuntimeException("memHostMbAvailable - memWorkflowOverhead = memoryAvail (" +
memHostMbAvailable + " - " + memWorkflowOverhead + " = " + memoryAvail +
") is less than one of the mem*PerThread parameters in provided ini file.");
}
return usableThreads;
}
private Job basFileBaseJob(int tumourCount, String sampleBam, String process, int index) {
Job thisJob = prepTimedJob(tumourCount, "basFileGenerate", process, index);
thisJob.getCommand()
.addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh")
.addArgument(installBase)
.addArgument("bam_stats")
.addArgument("-i " + sampleBam)
.addArgument("-o " + sampleBam + ".bas")
;
return thisJob;
}
private Job getMetricsJob(List<String> tumourBams, String controlBam) {
//die "USAGE: rootOfOutdir ordered.bam [ordered.bam2]";
Job thisJob = getWorkflow().createBashJob("metrics");
thisJob.getCommand()
.addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh")
.addArgument(installBase)
.addArgument(getWorkflowBaseDir()+ "/bin/qc_and_metrics.pl")
.addArgument(OUTDIR)
.addArgument(controlBam);
for(String bam : tumourBams) {
thisJob.getCommand().addArgument(bam);
}
return thisJob;
}
private Job caveCnPrep(int tumourCount, String type) {
thisJob.getCommand().addArgument("rm -f ./*/*.bam; ");
|
/**
* created at Sep 17, 2001
* @author Jeka
*/
package com.intellij.refactoring.changeSignature;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
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.javadoc.PsiDocTagValue;
import com.intellij.psi.scope.processor.VariablesProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.*;
import com.intellij.psi.xml.XmlElement;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.rename.JavaUnresolvableLocalCollisionDetector;
import com.intellij.refactoring.rename.RenameUtil;
import com.intellij.refactoring.rename.UnresolvableCollisionUsageInfo;
import com.intellij.refactoring.ui.ConflictsDialog;
import com.intellij.refactoring.util.*;
import com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo;
import com.intellij.refactoring.util.usageInfo.NoConstructorClassUsageInfo;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NotNull;
import java.util.*;
public class ChangeSignatureProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.changeSignature.ChangeSignatureProcessor");
@Modifier private final String myNewVisibility;
private final ChangeInfoImpl myChangeInfo;
private final PsiManager myManager;
private final PsiElementFactory myFactory;
private final boolean myGenerateDelegate;
private final Set<PsiMethod> myPropagateParametersMethods;
private final Set<PsiMethod> myPropagateExceptionsMethods;
public ChangeSignatureProcessor(Project project,
PsiMethod method,
final boolean generateDelegate,
@Modifier String newVisibility,
String newName,
PsiType newType,
@NotNull ParameterInfoImpl[] parameterInfo) {
this(project, method, generateDelegate, newVisibility, newName,
newType != null ? CanonicalTypes.createTypeWrapper(newType) : null,
parameterInfo, null, null, null);
}
public ChangeSignatureProcessor(Project project,
PsiMethod method,
final boolean generateDelegate,
String newVisibility,
String newName,
PsiType newType,
ParameterInfoImpl[] parameterInfo,
ThrownExceptionInfo[] exceptionInfos) {
this(project, method, generateDelegate, newVisibility, newName,
newType != null ? CanonicalTypes.createTypeWrapper(newType) : null,
parameterInfo, exceptionInfos, null, null);
}
public ChangeSignatureProcessor(Project project,
PsiMethod method,
boolean generateDelegate,
String newVisibility,
String newName,
CanonicalTypes.Type newType,
@NotNull ParameterInfoImpl[] parameterInfo,
ThrownExceptionInfo[] thrownExceptions,
Set<PsiMethod> propagateParametersMethods,
Set<PsiMethod> propagateExceptionsMethods) {
super(project);
myManager = PsiManager.getInstance(project);
myFactory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
myGenerateDelegate = generateDelegate;
myPropagateParametersMethods = propagateParametersMethods != null ? propagateParametersMethods : new HashSet<PsiMethod>();
myPropagateExceptionsMethods = propagateExceptionsMethods != null ? propagateExceptionsMethods : new HashSet<PsiMethod>();
LOG.assertTrue(method.isValid());
if (newVisibility == null) {
myNewVisibility = VisibilityUtil.getVisibilityModifier(method.getModifierList());
} else {
myNewVisibility = newVisibility;
}
myChangeInfo = new ChangeInfoImpl(myNewVisibility, method, newName, newType, parameterInfo, thrownExceptions);
LOG.assertTrue(myChangeInfo.getMethod().isValid());
}
protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) {
return new ChangeSignatureViewDescriptor(myChangeInfo.getMethod());
}
@NotNull
protected UsageInfo[] findUsages() {
ArrayList<UsageInfo> result = new ArrayList<UsageInfo>();
final PsiMethod method = myChangeInfo.getMethod();
findSimpleUsages(method, result);
final UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]);
return UsageViewUtil.removeDuplicatedUsages(usageInfos);
}
private void findSimpleUsages(final PsiMethod method, final ArrayList<UsageInfo> result) {
PsiMethod[] overridingMethods = findSimpleUsagesWithoutParameters(method, result, true, true, true);
findUsagesInCallers (result);
//Parameter name changes are not propagated
findParametersUsage(method, result, overridingMethods);
}
private PsiMethod[] findSimpleUsagesWithoutParameters(final PsiMethod method,
final ArrayList<UsageInfo> result,
boolean isToModifyArgs,
boolean isToThrowExceptions,
boolean isOriginal) {
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(myProject);
PsiMethod[] overridingMethods = OverridingMethodsSearch.search(method, method.getUseScope(), true).toArray(PsiMethod.EMPTY_ARRAY);
for (PsiMethod overridingMethod : overridingMethods) {
result.add(new OverriderUsageInfo(overridingMethod, method, isOriginal, isToModifyArgs, isToThrowExceptions));
}
boolean needToChangeCalls = !myGenerateDelegate && (myChangeInfo.isNameChanged || myChangeInfo.isParameterSetOrOrderChanged || myChangeInfo.isExceptionSetOrOrderChanged || myChangeInfo.isVisibilityChanged/*for checking inaccessible*/);
if (needToChangeCalls) {
int parameterCount = method.getParameterList().getParametersCount();
PsiReference[] refs = MethodReferencesSearch.search(method, projectScope, true).toArray(PsiReference.EMPTY_ARRAY);
for (PsiReference ref : refs) {
PsiElement element = ref.getElement();
boolean isToCatchExceptions = isToThrowExceptions && needToCatchExceptions(RefactoringUtil.getEnclosingMethod(element));
if (!isToCatchExceptions) {
if (RefactoringUtil.isMethodUsage(element)) {
PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(element);
if (!method.isVarArgs() && list.getExpressions().length != parameterCount) continue;
}
}
if (RefactoringUtil.isMethodUsage(element)) {
result.add(new MethodCallUsageInfo(element, isToModifyArgs, isToCatchExceptions));
}
else if (element instanceof PsiDocTagValue) {
result.add(new UsageInfo(ref.getElement()));
}
else if (element instanceof PsiMethod && ((PsiMethod)element).isConstructor()) {
DefaultConstructorImplicitUsageInfo implicitUsageInfo = new DefaultConstructorImplicitUsageInfo((PsiMethod)element, method);
result.add(implicitUsageInfo);
}
else if(element instanceof PsiClass) {
result.add(new NoConstructorClassUsageInfo((PsiClass)element));
}
else if (ref instanceof PsiCallReference) {
result.add(new CallReferenceUsageInfo((PsiCallReference) ref));
}
else {
result.add(new MoveRenameUsageInfo(element, ref, method));
}
}
//if (method.isConstructor() && parameterCount == 0) {
// RefactoringUtil.visitImplicitConstructorUsages(method.getContainingClass(),
// new DefaultConstructorUsageCollector(result));
}
else if (myChangeInfo.isParameterTypesChanged) {
PsiReference[] refs = MethodReferencesSearch.search(method, projectScope, true).toArray(PsiReference.EMPTY_ARRAY);
for (PsiReference reference : refs) {
final PsiElement element = reference.getElement();
if (element instanceof PsiDocTagValue) {
result.add(new UsageInfo(reference));
}
else if (element instanceof XmlElement) {
result.add(new MoveRenameUsageInfo(reference, method));
}
}
}
// Conflicts
detectLocalsCollisionsInMethod(method, result, isOriginal);
for (final PsiMethod overridingMethod : overridingMethods) {
detectLocalsCollisionsInMethod(overridingMethod, result, isOriginal);
}
return overridingMethods;
}
private void findUsagesInCallers(final ArrayList<UsageInfo> usages) {
for (PsiMethod caller : myPropagateParametersMethods) {
usages.add(new CallerUsageInfo(caller, true, myPropagateExceptionsMethods.contains(caller)));
}
for (PsiMethod caller : myPropagateExceptionsMethods) {
usages.add(new CallerUsageInfo(caller, myPropagateParametersMethods.contains(caller), true));
}
Set<PsiMethod> merged = new HashSet<PsiMethod>();
merged.addAll(myPropagateParametersMethods);
merged.addAll(myPropagateExceptionsMethods);
for (final PsiMethod method : merged) {
findSimpleUsagesWithoutParameters(method, usages, myPropagateParametersMethods.contains(method),
myPropagateExceptionsMethods.contains(method), false);
}
}
private boolean needToChangeCalls() {
return myChangeInfo.isNameChanged || myChangeInfo.isParameterSetOrOrderChanged || myChangeInfo.isExceptionSetOrOrderChanged;
}
private boolean needToCatchExceptions(PsiMethod caller) {
return myChangeInfo.isExceptionSetOrOrderChanged && !myPropagateExceptionsMethods.contains(caller);
}
private void detectLocalsCollisionsInMethod(final PsiMethod method,
final ArrayList<UsageInfo> result,
boolean isOriginal) {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final Set<PsiParameter> deletedOrRenamedParameters = new HashSet<PsiParameter>();
if (isOriginal) {
deletedOrRenamedParameters.addAll(Arrays.asList(parameters));
for (ParameterInfoImpl parameterInfo : myChangeInfo.newParms) {
if (parameterInfo.oldParameterIndex >= 0) {
final PsiParameter parameter = parameters[parameterInfo.oldParameterIndex];
if (parameterInfo.getName().equals(parameter.getName())) {
deletedOrRenamedParameters.remove(parameter);
}
}
}
}
for (ParameterInfoImpl parameterInfo : myChangeInfo.newParms) {
final int oldParameterIndex = parameterInfo.oldParameterIndex;
final String newName = parameterInfo.getName();
if (oldParameterIndex >= 0) {
if (isOriginal) { //Name changes take place only in primary method
final PsiParameter parameter = parameters[oldParameterIndex];
if (!newName.equals(parameter.getName())) {
JavaUnresolvableLocalCollisionDetector.visitLocalsCollisions(parameter, newName, method.getBody(), null, new JavaUnresolvableLocalCollisionDetector.CollidingVariableVisitor() {
public void visitCollidingElement(final PsiVariable collidingVariable) {
if (!(collidingVariable instanceof PsiField) && !deletedOrRenamedParameters.contains(collidingVariable)) {
result.add(new RenamedParameterCollidesWithLocalUsageInfo(parameter, collidingVariable, method));
}
}
});
}
}
}
else {
JavaUnresolvableLocalCollisionDetector.visitLocalsCollisions(method, newName, method.getBody(), null, new JavaUnresolvableLocalCollisionDetector.CollidingVariableVisitor() {
public void visitCollidingElement(PsiVariable collidingVariable) {
if (!(collidingVariable instanceof PsiField) && !deletedOrRenamedParameters.contains(collidingVariable)) {
result.add(new NewParameterCollidesWithLocalUsageInfo(collidingVariable, collidingVariable, method));
}
}
});
}
}
}
private void findParametersUsage(final PsiMethod method, ArrayList<UsageInfo> result, PsiMethod[] overriders) {
PsiParameter[] parameters = method.getParameterList().getParameters();
for (ParameterInfoImpl info : myChangeInfo.newParms) {
if (info.oldParameterIndex >= 0) {
PsiParameter parameter = parameters[info.oldParameterIndex];
if (!info.getName().equals(parameter.getName())) {
addParameterUsages(parameter, result, info);
for (PsiMethod overrider : overriders) {
PsiParameter parameter1 = overrider.getParameterList().getParameters()[info.oldParameterIndex];
if (parameter.getName().equals(parameter1.getName())) {
addParameterUsages(parameter1, result, info);
}
}
}
}
}
}
protected void refreshElements(PsiElement[] elements) {
boolean condition = elements.length == 1 && elements[0] instanceof PsiMethod;
LOG.assertTrue(condition);
myChangeInfo.updateMethod((PsiMethod) elements[0]);
}
private void addMethodConflicts(Collection<String> conflicts) {
String newMethodName = myChangeInfo.newName;
try {
PsiMethod prototype;
PsiManager manager = PsiManager.getInstance(myProject);
PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
final PsiMethod method = myChangeInfo.getMethod();
final CanonicalTypes.Type returnType = myChangeInfo.newReturnType;
if (returnType != null) {
prototype = factory.createMethod(newMethodName, returnType.getType(method, manager));
}
else {
prototype = factory.createConstructor();
prototype.setName(newMethodName);
}
ParameterInfoImpl[] parameters = myChangeInfo.newParms;
for (ParameterInfoImpl info : parameters) {
final PsiType parameterType = info.createType(method, manager);
PsiParameter param = factory.createParameter(info.getName(), parameterType);
prototype.getParameterList().add(param);
}
ConflictsUtil.checkMethodConflicts(
method.getContainingClass(),
method,
prototype, conflicts);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
Set<String> conflictDescriptions = new HashSet<String>();
UsageInfo[] usagesIn = refUsages.get();
addMethodConflicts(conflictDescriptions);
conflictDescriptions.addAll(RenameUtil.getConflictDescriptions(usagesIn));
Set<UsageInfo> usagesSet = new HashSet<UsageInfo>(Arrays.asList(usagesIn));
RenameUtil.removeConflictUsages(usagesSet);
if (myChangeInfo.isVisibilityChanged) {
try {
addInaccessibilityDescriptions(usagesSet, conflictDescriptions);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
if (myPrepareSuccessfulSwingThreadCallback != null && !conflictDescriptions.isEmpty()) {
ConflictsDialog dialog = new ConflictsDialog(myProject, conflictDescriptions);
dialog.show();
if (!dialog.isOK()) return false;
}
if (myChangeInfo.isReturnTypeChanged) {
askToRemoveCovariantOverriders (usagesSet);
}
refUsages.set(usagesSet.toArray(new UsageInfo[usagesSet.size()]));
prepareSuccessful();
return true;
}
private void addInaccessibilityDescriptions(Set<UsageInfo> usages, Set<String> conflictDescriptions) throws IncorrectOperationException {
PsiMethod method = myChangeInfo.getMethod();
PsiModifierList modifierList = (PsiModifierList)method.getModifierList().copy();
RefactoringUtil.setVisibility(modifierList, myNewVisibility);
for (Iterator<UsageInfo> iterator = usages.iterator(); iterator.hasNext();) {
UsageInfo usageInfo = iterator.next();
PsiElement element = usageInfo.getElement();
if (element != null) {
if (element instanceof PsiReferenceExpression) {
PsiClass accessObjectClass = null;
PsiExpression qualifier = ((PsiReferenceExpression)element).getQualifierExpression();
if (qualifier != null) {
accessObjectClass = (PsiClass)PsiUtil.getAccessObjectClass(qualifier).getElement();
}
if (!JavaPsiFacade.getInstance(element.getProject()).getResolveHelper()
.isAccessible(method, modifierList, element, accessObjectClass, null)) {
String message =
RefactoringBundle.message("0.with.1.visibility.is.not.accesible.from.2",
RefactoringUIUtil.getDescription(method, true),
myNewVisibility,
RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(element), true));
conflictDescriptions.add(message);
if (!needToChangeCalls()) {
iterator.remove();
}
}
}
}
}
}
private void askToRemoveCovariantOverriders(Set<UsageInfo> usages) {
if (PsiUtil.isLanguageLevel5OrHigher(myChangeInfo.getMethod())) {
List<UsageInfo> covariantOverriderInfos = new ArrayList<UsageInfo>();
for (UsageInfo usageInfo : usages) {
if (usageInfo instanceof OverriderUsageInfo) {
final OverriderUsageInfo info = (OverriderUsageInfo)usageInfo;
PsiMethod overrider = info.getElement();
PsiMethod baseMethod = info.getBaseMethod();
PsiSubstitutor substitutor = calculateSubstitutor(overrider, baseMethod);
PsiType type;
try {
type = substitutor.substitute(myChangeInfo.newReturnType.getType(myChangeInfo.getMethod(), myManager));
}
catch (IncorrectOperationException e) {
LOG.error(e);
return;
}
final PsiType overriderType = overrider.getReturnType();
if (overriderType != null && type.isAssignableFrom(overriderType)) {
covariantOverriderInfos.add(usageInfo);
}
}
}
// to be able to do filtering
preprocessCovariantOverriders(covariantOverriderInfos);
if (!covariantOverriderInfos.isEmpty()) {
if (ApplicationManager.getApplication().isUnitTestMode() || !isProcessCovariantOverriders()) {
for (UsageInfo usageInfo : covariantOverriderInfos) {
usages.remove(usageInfo);
}
}
}
}
}
protected void preprocessCovariantOverriders(final List<UsageInfo> covariantOverriderInfos) {
}
protected boolean isProcessCovariantOverriders() {
return Messages.showYesNoDialog(myProject, RefactoringBundle.message("do.you.want.to.process.overriding.methods.with.covariant.return.type"),
ChangeSignatureHandler.REFACTORING_NAME, Messages.getQuestionIcon())
== DialogWrapper.OK_EXIT_CODE;
}
protected void performRefactoring(UsageInfo[] usages) {
PsiElementFactory factory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
try {
if (myChangeInfo.isNameChanged) {
myChangeInfo.newNameIdentifier = factory.createIdentifier(myChangeInfo.newName);
}
if (myChangeInfo.isReturnTypeChanged) {
myChangeInfo.newTypeElement = myChangeInfo.newReturnType.getType(myChangeInfo.getMethod(), myManager);
}
if (myGenerateDelegate) {
generateDelegate();
}
for (UsageInfo usage : usages) {
if (usage instanceof CallerUsageInfo) {
final CallerUsageInfo callerUsageInfo = (CallerUsageInfo)usage;
processCallerMethod(callerUsageInfo.getMethod(), null, callerUsageInfo.isToInsertParameter(),
callerUsageInfo.isToInsertException());
}
else if (usage instanceof OverriderUsageInfo) {
OverriderUsageInfo info = (OverriderUsageInfo)usage;
final PsiMethod method = info.getElement();
final PsiMethod baseMethod = info.getBaseMethod();
if (info.isOriginalOverrider()) {
processPrimaryMethod(method, baseMethod, false);
}
else {
processCallerMethod(method, baseMethod, info.isToInsertArgs(), info.isToCatchExceptions());
}
}
}
LOG.assertTrue(myChangeInfo.getMethod().isValid());
processPrimaryMethod(myChangeInfo.getMethod(), null, true);
List<UsageInfo> postponedUsages = new ArrayList<UsageInfo>();
for (UsageInfo usage : usages) {
PsiElement element = usage.getElement();
if (element == null) continue;
if (usage instanceof DefaultConstructorImplicitUsageInfo) {
final DefaultConstructorImplicitUsageInfo defConstructorUsage = (DefaultConstructorImplicitUsageInfo)usage;
addSuperCall(defConstructorUsage.getConstructor(), defConstructorUsage.getBaseConstructor(),usages);
}
else if (usage instanceof NoConstructorClassUsageInfo) {
addDefaultConstructor(((NoConstructorClassUsageInfo)usage).getPsiClass(),usages);
}
else if (element instanceof PsiJavaCodeReferenceElement) {
if (usage instanceof MethodCallUsageInfo) {
final MethodCallUsageInfo methodCallInfo = (MethodCallUsageInfo)usage;
processMethodUsage(methodCallInfo.getElement(), myChangeInfo, methodCallInfo.isToChangeArguments(),
methodCallInfo.isToCatchExceptions(), methodCallInfo.getReferencedMethod(), usages);
}
else if (usage instanceof MyParameterUsageInfo) {
String newName = ((MyParameterUsageInfo)usage).newParameterName;
String oldName = ((MyParameterUsageInfo)usage).oldParameterName;
processParameterUsage((PsiReferenceExpression)element, oldName, newName);
} else {
postponedUsages.add(usage);
}
}
else if (usage instanceof CallReferenceUsageInfo) {
((CallReferenceUsageInfo) usage).getReference().handleChangeSignature(myChangeInfo);
}
else if (element instanceof PsiEnumConstant) {
fixActualArgumentsList(((PsiEnumConstant)element).getArgumentList(), myChangeInfo, true);
}
else if (!(usage instanceof OverriderUsageInfo)) {
postponedUsages.add(usage);
}
}
for (UsageInfo usageInfo : postponedUsages) {
PsiElement element = usageInfo.getElement();
if (element == null) continue;
PsiReference reference = usageInfo instanceof MoveRenameUsageInfo ?
usageInfo.getReference() :
element.getReference();
if (reference != null) {
PsiElement target = null;
if (usageInfo instanceof MyParameterUsageInfo) {
String newParameterName = ((MyParameterUsageInfo)usageInfo).newParameterName;
PsiParameter[] newParams = myChangeInfo.getMethod().getParameterList().getParameters();
for (PsiParameter newParam : newParams) {
if (newParam.getName().equals(newParameterName)) {
target = newParam;
break;
}
}
}
else {
target = myChangeInfo.getMethod();
}
if (target != null) {
reference.bindToElement(target);
}
}
}
LOG.assertTrue(myChangeInfo.getMethod().isValid());
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}
private void generateDelegate() throws IncorrectOperationException {
final PsiMethod delegate = (PsiMethod)myChangeInfo.getMethod().copy();
final PsiClass targetClass = myChangeInfo.getMethod().getContainingClass();
LOG.assertTrue(!targetClass.isInterface());
makeEmptyBody(myFactory, delegate);
final PsiCallExpression callExpression = addDelegatingCallTemplate(delegate, myChangeInfo.newName);
addDelegateArguments(callExpression);
targetClass.addBefore(delegate, myChangeInfo.getMethod());
}
private void addDelegateArguments(final PsiCallExpression callExpression) throws IncorrectOperationException {
final ParameterInfoImpl[] newParms = myChangeInfo.newParms;
for (int i = 0; i < newParms.length; i++) {
ParameterInfoImpl newParm = newParms[i];
final PsiExpression actualArg;
if (newParm.oldParameterIndex >= 0) {
actualArg = myFactory.createExpressionFromText(myChangeInfo.oldParameterNames[newParm.oldParameterIndex], callExpression);
}
else {
actualArg = myChangeInfo.getValue(i, callExpression);
}
callExpression.getArgumentList().add(actualArg);
}
}
public static void makeEmptyBody(final PsiElementFactory factory, final PsiMethod delegate) throws IncorrectOperationException {
PsiCodeBlock body = delegate.getBody();
if (body != null) {
body.replace(factory.createCodeBlock());
}
else {
delegate.add(factory.createCodeBlock());
}
delegate.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, false);
}
public static PsiCallExpression addDelegatingCallTemplate(final PsiMethod delegate, final String newName) throws IncorrectOperationException {
Project project = delegate.getProject();
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
PsiCodeBlock body = delegate.getBody();
assert body != null;
final PsiCallExpression callExpression;
if (delegate.isConstructor()) {
PsiElement callStatement = factory.createStatementFromText("this();", null);
callStatement = CodeStyleManager.getInstance(project).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiExpressionStatement) callStatement).getExpression();
} else {
if (PsiType.VOID.equals(delegate.getReturnType())) {
PsiElement callStatement = factory.createStatementFromText(newName + "();", null);
callStatement = CodeStyleManager.getInstance(project).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiExpressionStatement) callStatement).getExpression();
}
else {
PsiElement callStatement = factory.createStatementFromText("return " + newName + "();", null);
callStatement = CodeStyleManager.getInstance(project).reformat(callStatement);
callStatement = body.add(callStatement);
callExpression = (PsiCallExpression)((PsiReturnStatement) callStatement).getReturnValue();
}
}
return callExpression;
}
private void addDefaultConstructor(PsiClass aClass, final UsageInfo[] usages) throws IncorrectOperationException {
if (!(aClass instanceof PsiAnonymousClass)) {
PsiMethod defaultConstructor = myFactory.createMethodFromText(aClass.getName() + "(){}", aClass);
defaultConstructor = (PsiMethod) CodeStyleManager.getInstance(myProject).reformat(defaultConstructor);
defaultConstructor = (PsiMethod) aClass.add(defaultConstructor);
defaultConstructor.getModifierList().setModifierProperty(VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true);
addSuperCall(defaultConstructor, null, usages);
} else {
final PsiElement parent = aClass.getParent();
if (parent instanceof PsiNewExpression) {
final PsiExpressionList argumentList = ((PsiNewExpression) parent).getArgumentList();
fixActualArgumentsList(argumentList, myChangeInfo, true);
}
}
}
private void addSuperCall(PsiMethod constructor, PsiMethod callee, final UsageInfo[] usages) throws IncorrectOperationException {
PsiExpressionStatement superCall = (PsiExpressionStatement) myFactory.createStatementFromText("super();", constructor);
PsiCodeBlock body = constructor.getBody();
assert body != null;
PsiStatement[] statements = body.getStatements();
if (statements.length > 0) {
superCall = (PsiExpressionStatement) body.addBefore(superCall, statements[0]);
} else {
superCall = (PsiExpressionStatement) body.add(superCall);
}
PsiMethodCallExpression callExpression = (PsiMethodCallExpression) superCall.getExpression();
processMethodUsage(callExpression.getMethodExpression(), myChangeInfo, true, false, callee, usages);
}
private PsiParameter createNewParameter(ParameterInfoImpl newParm,
PsiSubstitutor substitutor) throws IncorrectOperationException {
final PsiElementFactory factory = JavaPsiFacade.getInstance(myProject).getElementFactory();
final PsiType type = substitutor.substitute(newParm.createType(myChangeInfo.getMethod().getParameterList(), myManager));
return factory.createParameter(newParm.getName(), type);
}
protected String getCommandName() {
return RefactoringBundle.message("changing.signature.of.0", UsageViewUtil.getDescriptiveName(myChangeInfo.getMethod()));
}
private void processMethodUsage(PsiElement ref,
ChangeInfoImpl changeInfo,
boolean toChangeArguments,
boolean toCatchExceptions,
PsiMethod callee, final UsageInfo[] usages) throws IncorrectOperationException {
if (changeInfo.isNameChanged) {
if (ref instanceof PsiJavaCodeReferenceElement) {
PsiElement last = ((PsiJavaCodeReferenceElement)ref).getReferenceNameElement();
if (last instanceof PsiIdentifier && last.getText().equals(changeInfo.oldName)) {
last.replace(changeInfo.newNameIdentifier);
}
}
}
final PsiMethod caller = RefactoringUtil.getEnclosingMethod(ref);
if (toChangeArguments) {
final PsiExpressionList list = RefactoringUtil.getArgumentListByMethodReference(ref);
boolean toInsertDefaultValue = !myPropagateParametersMethods.contains(caller);
if (toInsertDefaultValue && ref instanceof PsiReferenceExpression) {
final PsiExpression qualifierExpression = ((PsiReferenceExpression) ref).getQualifierExpression();
if (qualifierExpression instanceof PsiSuperExpression && callerSignatureIsAboutToChangeToo(caller, usages)) {
toInsertDefaultValue = false;
}
}
fixActualArgumentsList(list, changeInfo, toInsertDefaultValue);
}
if (toCatchExceptions) {
if (!(ref instanceof PsiReferenceExpression && ((PsiReferenceExpression)ref).getQualifierExpression() instanceof PsiSuperExpression)) {
if (needToCatchExceptions(caller)) {
PsiClassType[] newExceptions = callee != null ? getCalleeChangedExceptionInfo(callee) : getPrimaryChangedExceptionInfo(changeInfo);
fixExceptions(ref, newExceptions);
}
}
}
}
private static boolean callerSignatureIsAboutToChangeToo(final PsiMethod caller, final UsageInfo[] usages) {
for (UsageInfo usage : usages) {
if (usage instanceof MethodCallUsageInfo && MethodSignatureUtil.isSuperMethod(((MethodCallUsageInfo)usage).getReferencedMethod(), caller)) return true;
}
return false;
}
private static PsiClassType[] getCalleeChangedExceptionInfo(final PsiMethod callee) {
return callee.getThrowsList().getReferencedTypes(); //Callee method's throws list is already modified!
}
private PsiClassType[] getPrimaryChangedExceptionInfo(ChangeInfoImpl changeInfo) throws IncorrectOperationException {
PsiClassType[] newExceptions = new PsiClassType[changeInfo.newExceptions.length];
for (int i = 0; i < newExceptions.length; i++) {
newExceptions[i] = (PsiClassType)changeInfo.newExceptions[i].myType.getType(myChangeInfo.getMethod(), myManager); //context really does not matter here
}
return newExceptions;
}
private void fixExceptions(PsiElement ref, PsiClassType[] newExceptions) throws IncorrectOperationException {
//methods' throws lists are already modified, may use ExceptionUtil.collectUnhandledExceptions
newExceptions = filterCheckedExceptions(newExceptions);
PsiElement context = PsiTreeUtil.getParentOfType(ref, PsiTryStatement.class, PsiMethod.class);
if (context instanceof PsiTryStatement) {
PsiTryStatement tryStatement = (PsiTryStatement)context;
PsiCodeBlock tryBlock = tryStatement.getTryBlock();
//Remove unused catches
PsiClassType[] classes = ExceptionUtil.collectUnhandledExceptions(tryBlock, tryBlock);
PsiParameter[] catchParameters = tryStatement.getCatchBlockParameters();
for (PsiParameter parameter : catchParameters) {
final PsiType caughtType = parameter.getType();
if (!(caughtType instanceof PsiClassType)) continue;
if (ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)caughtType)) continue;
if (!isCatchParameterRedundant((PsiClassType)caughtType, classes)) continue;
parameter.getParent().delete(); //delete catch section
}
PsiClassType[] exceptionsToAdd = filterUnhandledExceptions(newExceptions, tryBlock);
addExceptions(exceptionsToAdd, tryStatement);
adjustPossibleEmptyTryStatement(tryStatement);
}
else {
newExceptions = filterUnhandledExceptions(newExceptions, ref);
if (newExceptions.length > 0) {
//Add new try statement
PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
PsiTryStatement tryStatement = (PsiTryStatement)elementFactory.createStatementFromText("try {} catch (Exception e) {}", null);
PsiStatement anchor = PsiTreeUtil.getParentOfType(ref, PsiStatement.class);
LOG.assertTrue(anchor != null);
tryStatement.getTryBlock().add(anchor);
tryStatement = (PsiTryStatement)anchor.getParent().addAfter(tryStatement, anchor);
addExceptions(newExceptions, tryStatement);
anchor.delete();
tryStatement.getCatchSections()[0].delete(); //Delete dummy catch section
}
}
}
private static PsiClassType[] filterCheckedExceptions(PsiClassType[] exceptions) {
List<PsiClassType> result = new ArrayList<PsiClassType>();
for (PsiClassType exceptionType : exceptions) {
if (!ExceptionUtil.isUncheckedException(exceptionType)) result.add(exceptionType);
}
return result.toArray(new PsiClassType[result.size()]);
}
private static void adjustPossibleEmptyTryStatement(PsiTryStatement tryStatement) throws IncorrectOperationException {
PsiCodeBlock tryBlock = tryStatement.getTryBlock();
if (tryBlock != null) {
if (tryStatement.getCatchSections().length == 0 &&
tryStatement.getFinallyBlock() == null) {
PsiElement firstBodyElement = tryBlock.getFirstBodyElement();
if (firstBodyElement != null) {
tryStatement.getParent().addRangeAfter(firstBodyElement, tryBlock.getLastBodyElement(), tryStatement);
}
tryStatement.delete();
}
}
}
private static void addExceptions(PsiClassType[] exceptionsToAdd, PsiTryStatement tryStatement) throws IncorrectOperationException {
for (PsiClassType type : exceptionsToAdd) {
final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(tryStatement.getProject());
String name = styleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type).names[0];
name = styleManager.suggestUniqueVariableName(name, tryStatement, false);
PsiCatchSection catchSection =
JavaPsiFacade.getInstance(tryStatement.getProject()).getElementFactory().createCatchSection(type, name, tryStatement);
tryStatement.add(catchSection);
}
}
private void fixPrimaryThrowsLists(PsiMethod method, PsiClassType[] newExceptions) throws IncorrectOperationException {
PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
PsiJavaCodeReferenceElement[] refs = new PsiJavaCodeReferenceElement[newExceptions.length];
for (int i = 0; i < refs.length; i++) {
refs[i] = elementFactory.createReferenceElementByType(newExceptions[i]);
}
PsiReferenceList throwsList = elementFactory.createReferenceList(refs);
replaceThrowsList(method, throwsList);
}
private void replaceThrowsList(PsiMethod method, PsiReferenceList throwsList) throws IncorrectOperationException {
PsiReferenceList methodThrowsList = (PsiReferenceList)method.getThrowsList().replace(throwsList);
methodThrowsList = (PsiReferenceList)JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(methodThrowsList);
myManager.getCodeStyleManager().reformatRange(method, method.getParameterList().getTextRange().getEndOffset(),
methodThrowsList.getTextRange().getEndOffset());
}
private static PsiClassType[] filterUnhandledExceptions(PsiClassType[] exceptions, PsiElement place) {
List<PsiClassType> result = new ArrayList<PsiClassType>();
for (PsiClassType exception : exceptions) {
if (!ExceptionUtil.isHandled(exception, place)) result.add(exception);
}
return result.toArray(new PsiClassType[result.size()]);
}
private static boolean isCatchParameterRedundant (PsiClassType catchParamType, PsiType[] thrownTypes) {
for (PsiType exceptionType : thrownTypes) {
if (exceptionType.isConvertibleFrom(catchParamType)) return false;
}
return true;
}
private static int getNonVarargCount(ChangeInfoImpl changeInfo, PsiExpression[] args) {
if (!changeInfo.wasVararg) return args.length;
return changeInfo.oldParameterTypes.length - 1;
}
//This methods works equally well for primary usages as well as for propagated callers' usages
private void fixActualArgumentsList(PsiExpressionList list,
ChangeInfoImpl changeInfo,
boolean toInsertDefaultValue) throws IncorrectOperationException {
final PsiElementFactory factory = JavaPsiFacade.getInstance(list.getProject()).getElementFactory();
if (changeInfo.isParameterSetOrOrderChanged) {
if (changeInfo.isPropagationEnabled) {
final ParameterInfoImpl[] createdParmsInfo = changeInfo.getCreatedParmsInfoWithoutVarargs();
for (ParameterInfoImpl info : createdParmsInfo) {
PsiExpression newArg;
if (toInsertDefaultValue) {
newArg = createDefaultValue(factory, info, list);
}
else {
newArg = factory.createExpressionFromText(info.getName(), list);
}
list.add(newArg);
}
}
else {
final PsiExpression[] args = list.getExpressions();
final int nonVarargCount = getNonVarargCount(changeInfo, args);
final int varargCount = args.length - nonVarargCount;
PsiExpression[] newVarargInitializers = null;
final int newArgsLength;
final int newNonVarargCount;
if (changeInfo.arrayToVarargs) {
newNonVarargCount = changeInfo.newParms.length - 1;
final ParameterInfoImpl lastNewParm = changeInfo.newParms[changeInfo.newParms.length - 1];
final PsiExpression arrayToConvert = args[lastNewParm.oldParameterIndex];
if (arrayToConvert instanceof PsiNewExpression) {
final PsiNewExpression expression = (PsiNewExpression)arrayToConvert;
final PsiArrayInitializerExpression arrayInitializer = expression.getArrayInitializer();
if (arrayInitializer != null) {
newVarargInitializers = arrayInitializer.getInitializers();
}
}
newArgsLength = newVarargInitializers == null ? changeInfo.newParms.length : newNonVarargCount + newVarargInitializers.length;
}
else if (changeInfo.retainsVarargs) {
newNonVarargCount = changeInfo.newParms.length - 1;
newArgsLength = newNonVarargCount + varargCount;
}
else if (changeInfo.obtainsVarags) {
newNonVarargCount = changeInfo.newParms.length - 1;
newArgsLength = newNonVarargCount;
}
else {
newNonVarargCount = changeInfo.newParms.length;
newArgsLength = changeInfo.newParms.length;
}
final PsiExpression[] newArgs = new PsiExpression[newArgsLength];
for (int i = 0; i < newNonVarargCount; i++) {
newArgs [i] = createActualArgument(list, changeInfo.newParms [i], toInsertDefaultValue, args);
}
if (changeInfo.arrayToVarargs) {
if (newVarargInitializers == null) {
newArgs [newNonVarargCount] = createActualArgument(list, changeInfo.newParms [newNonVarargCount], toInsertDefaultValue, args);
}
else {
for (int i = 0; i < newVarargInitializers.length; i++) {
newArgs [i + newNonVarargCount] = newVarargInitializers [i];
}
}
}
else {
final int newVarargCount = newArgsLength - newNonVarargCount;
LOG.assertTrue(newVarargCount == 0 || newVarargCount == varargCount);
for (int i = 0; i < newVarargCount; i++) {
newArgs[newNonVarargCount + i] = args[nonVarargCount + i];
}
}
ChangeSignatureUtil.synchronizeList(list, Arrays.asList(newArgs), ExpressionList.INSTANCE, changeInfo.toRemoveParm);
}
}
}
private PsiExpression createActualArgument(final PsiExpressionList list, final ParameterInfoImpl info, final boolean toInsertDefaultValue,
final PsiExpression[] args) throws IncorrectOperationException {
final PsiElementFactory factory = JavaPsiFacade.getInstance(list.getProject()).getElementFactory();
final int index = info.oldParameterIndex;
if (index >= 0) {
return args[index];
} else {
if (toInsertDefaultValue) {
return createDefaultValue(factory, info, list);
} else {
return factory.createExpressionFromText(info.getName(), list);
}
}
}
private PsiExpression createDefaultValue(final PsiElementFactory factory, final ParameterInfoImpl info, final PsiExpressionList list)
throws IncorrectOperationException {
if (info.useAnySingleVariable) {
final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(list.getProject()).getResolveHelper();
final PsiType type = info.getTypeWrapper().getType(myChangeInfo.getMethod(), myManager);
final VariablesProcessor processor = new VariablesProcessor(false) {
protected boolean check(PsiVariable var, ResolveState state) {
if (var instanceof PsiField && !resolveHelper.isAccessible((PsiField)var, list, null)) return false;
final PsiType varType = state.get(PsiSubstitutor.KEY).substitute(var.getType());
return type.isAssignableFrom(varType);
}
public boolean execute(PsiElement pe, ResolveState state) {
super.execute(pe, state);
return size() < 2;
}
};
PsiScopesUtil.treeWalkUp(processor, list, null);
if (processor.size() == 1) {
final PsiVariable result = processor.getResult(0);
return factory.createExpressionFromText(result.getName(), list);
}
}
final PsiCallExpression callExpression = PsiTreeUtil.getParentOfType(list, PsiCallExpression.class);
return callExpression != null ? info.getValue(callExpression) : factory.createExpressionFromText(info.defaultValue, list);
}
private static void addParameterUsages(PsiParameter parameter,
ArrayList<UsageInfo> results,
ParameterInfoImpl info) {
PsiManager manager = parameter.getManager();
GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject());
for (PsiReference psiReference : ReferencesSearch.search(parameter, projectScope, false)) {
PsiElement parmRef = psiReference.getElement();
UsageInfo usageInfo = new MyParameterUsageInfo(parmRef, parameter.getName(), info.getName());
results.add(usageInfo);
}
}
private void processCallerMethod(PsiMethod caller,
PsiMethod baseMethod,
boolean toInsertParams,
boolean toInsertThrows) throws IncorrectOperationException {
LOG.assertTrue(toInsertParams || toInsertThrows);
if (toInsertParams) {
List<PsiParameter> newParameters = new ArrayList<PsiParameter>();
newParameters.addAll(Arrays.asList(caller.getParameterList().getParameters()));
final ParameterInfoImpl[] primaryNewParms = myChangeInfo.newParms;
PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : calculateSubstitutor(caller, baseMethod);
for (ParameterInfoImpl info : primaryNewParms) {
if (info.oldParameterIndex < 0) newParameters.add(createNewParameter(info, substitutor));
}
PsiParameter[] arrayed = newParameters.toArray(new PsiParameter[newParameters.size()]);
boolean[] toRemoveParm = new boolean[arrayed.length];
Arrays.fill(toRemoveParm, false);
resolveParameterVsFieldsConflicts(arrayed, caller, caller.getParameterList(), toRemoveParm);
}
if (toInsertThrows) {
List<PsiJavaCodeReferenceElement> newThrowns = new ArrayList<PsiJavaCodeReferenceElement>();
final PsiReferenceList throwsList = caller.getThrowsList();
newThrowns.addAll(Arrays.asList(throwsList.getReferenceElements()));
final ThrownExceptionInfo[] primaryNewExns = myChangeInfo.newExceptions;
for (ThrownExceptionInfo thrownExceptionInfo : primaryNewExns) {
if (thrownExceptionInfo.oldIndex < 0) {
final PsiClassType type = (PsiClassType)thrownExceptionInfo.createType(caller, myManager);
final PsiJavaCodeReferenceElement ref =
JavaPsiFacade.getInstance(caller.getProject()).getElementFactory().createReferenceElementByType(type);
newThrowns.add(ref);
}
}
PsiJavaCodeReferenceElement[] arrayed = newThrowns.toArray(new PsiJavaCodeReferenceElement[newThrowns.size()]);
boolean[] toRemoveParm = new boolean[arrayed.length];
Arrays.fill(toRemoveParm, false);
ChangeSignatureUtil.synchronizeList(throwsList, Arrays.asList(arrayed), ThrowsList.INSTANCE, toRemoveParm);
}
}
private void processPrimaryMethod(PsiMethod method,
PsiMethod baseMethod,
boolean isOriginal) throws IncorrectOperationException {
PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
if (myChangeInfo.isVisibilityChanged) {
PsiModifierList modifierList = method.getModifierList();
final String highestVisibility = isOriginal ?
myNewVisibility :
VisibilityUtil.getHighestVisibility(myNewVisibility, VisibilityUtil.getVisibilityModifier(modifierList));
RefactoringUtil.setVisibility(modifierList, highestVisibility);
}
if (myChangeInfo.isNameChanged) {
String newName = baseMethod == null ? myChangeInfo.newName :
RefactoringUtil.suggestNewOverriderName(method.getName(), baseMethod.getName(), myChangeInfo.newName);
if (newName != null && !newName.equals(method.getName())) {
final PsiIdentifier nameId = method.getNameIdentifier();
assert nameId != null;
nameId.replace(JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory().createIdentifier(newName));
}
}
final PsiSubstitutor substitutor = baseMethod == null ? PsiSubstitutor.EMPTY : calculateSubstitutor(method, baseMethod);
if (myChangeInfo.isReturnTypeChanged) {
final PsiType returnType = substitutor.substitute(myChangeInfo.newTypeElement);
// don't modify return type for non-Java overriders (EJB)
if (method.getName().equals(myChangeInfo.newName)) {
method.getReturnTypeElement().replace(factory.createTypeElement(returnType));
}
}
PsiParameterList list = method.getParameterList();
PsiParameter[] parameters = list.getParameters();
PsiParameter[] newParms = new PsiParameter[myChangeInfo.newParms.length];
for (int i = 0; i < newParms.length; i++) {
ParameterInfoImpl info = myChangeInfo.newParms[i];
int index = info.oldParameterIndex;
if (index >= 0) {
PsiParameter parameter = parameters[index];
newParms[i] = parameter;
String oldName = myChangeInfo.oldParameterNames[index];
if (!oldName.equals(info.getName()) && oldName.equals(parameter.getName())) {
PsiIdentifier newIdentifier = factory.createIdentifier(info.getName());
parameter.getNameIdentifier().replace(newIdentifier);
}
String oldType = myChangeInfo.oldParameterTypes[index];
if (!oldType.equals(info.getTypeText())) {
parameter.normalizeDeclaration();
PsiType newType = substitutor.substitute(info.createType(myChangeInfo.getMethod().getParameterList(), myManager));
parameter.getTypeElement().replace(factory.createTypeElement(newType));
}
} else {
newParms[i] = createNewParameter(info, substitutor);
}
}
resolveParameterVsFieldsConflicts(newParms, method, list, myChangeInfo.toRemoveParm);
fixJavadocsForChangedMethod(method);
if (myChangeInfo.isExceptionSetOrOrderChanged) {
final PsiClassType[] newExceptions = getPrimaryChangedExceptionInfo(myChangeInfo);
fixPrimaryThrowsLists(method, newExceptions);
}
}
private static void resolveParameterVsFieldsConflicts(final PsiParameter[] newParms,
final PsiMethod method,
final PsiParameterList list,
boolean[] toRemoveParm) throws IncorrectOperationException {
List<FieldConflictsResolver> conflictResolvers = new ArrayList<FieldConflictsResolver>();
for (PsiParameter parameter : newParms) {
conflictResolvers.add(new FieldConflictsResolver(parameter.getName(), method.getBody()));
}
ChangeSignatureUtil.synchronizeList(list, Arrays.asList(newParms), ParameterList.INSTANCE, toRemoveParm);
for (FieldConflictsResolver fieldConflictsResolver : conflictResolvers) {
fieldConflictsResolver.fix();
}
}
private static PsiSubstitutor calculateSubstitutor(PsiMethod derivedMethod, PsiMethod baseMethod) {
PsiSubstitutor substitutor;
if (derivedMethod.getManager().areElementsEquivalent(derivedMethod, baseMethod)) {
substitutor = PsiSubstitutor.EMPTY;
} else {
final PsiClass baseClass = baseMethod.getContainingClass();
final PsiClass derivedClass = derivedMethod.getContainingClass();
if(baseClass != null && derivedClass != null && InheritanceUtil.isInheritorOrSelf(derivedClass, baseClass, true)) {
final PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getSuperClassSubstitutor(baseClass, derivedClass, PsiSubstitutor.EMPTY);
final MethodSignature superMethodSignature = baseMethod.getSignature(superClassSubstitutor);
final MethodSignature methodSignature = derivedMethod.getSignature(PsiSubstitutor.EMPTY);
final PsiSubstitutor superMethodSubstitutor = MethodSignatureUtil.getSuperMethodSignatureSubstitutor(methodSignature, superMethodSignature);
substitutor = superMethodSubstitutor != null ? superMethodSubstitutor : superClassSubstitutor;
} else {
substitutor = PsiSubstitutor.EMPTY;
}
}
return substitutor;
}
private static void processParameterUsage(PsiReferenceExpression ref, String oldName, String newName)
throws IncorrectOperationException {
PsiElement last = ref.getReferenceNameElement();
if (last instanceof PsiIdentifier && last.getText().equals(oldName)) {
PsiElementFactory factory = JavaPsiFacade.getInstance(ref.getProject()).getElementFactory();
PsiIdentifier newNameIdentifier = factory.createIdentifier(newName);
last.replace(newNameIdentifier);
}
}
private static class MyParameterUsageInfo extends UsageInfo {
final String oldParameterName;
final String newParameterName;
public MyParameterUsageInfo(PsiElement element, String oldParameterName, String newParameterName) {
super(element);
this.oldParameterName = oldParameterName;
this.newParameterName = newParameterName;
}
}
private static class RenamedParameterCollidesWithLocalUsageInfo extends UnresolvableCollisionUsageInfo {
private final PsiElement myCollidingElement;
private final PsiMethod myMethod;
public RenamedParameterCollidesWithLocalUsageInfo(PsiParameter parameter, PsiElement collidingElement, PsiMethod method) {
super(parameter, collidingElement);
myCollidingElement = collidingElement;
myMethod = method;
}
public String getDescription() {
return RefactoringBundle.message("there.is.already.a.0.in.the.1.it.will.conflict.with.the.renamed.parameter",
RefactoringUIUtil.getDescription(myCollidingElement, true),
RefactoringUIUtil.getDescription(myMethod, true));
}
}
private void fixJavadocsForChangedMethod(PsiMethod method) throws IncorrectOperationException {
final PsiParameter[] parameters = method.getParameterList().getParameters();
final ParameterInfoImpl[] newParms = myChangeInfo.newParms;
LOG.assertTrue(parameters.length == newParms.length);
final Set<PsiParameter> newParameters = new HashSet<PsiParameter>();
for (int i = 0; i < newParms.length; i++) {
ParameterInfoImpl newParm = newParms[i];
if (newParm.oldParameterIndex < 0 ||
!newParm.getName().equals(myChangeInfo.oldParameterNames[newParm.oldParameterIndex])) {
newParameters.add(parameters[i]);
}
}
RefactoringUtil.fixJavadocsForParams(method, newParameters);
}
private static class ExpressionList implements ChangeSignatureUtil.ChildrenGenerator<PsiExpressionList, PsiExpression> {
public static final ExpressionList INSTANCE = new ExpressionList();
public List<PsiExpression> getChildren(PsiExpressionList psiExpressionList) {
return Arrays.asList(psiExpressionList.getExpressions());
}
}
private static class ParameterList implements ChangeSignatureUtil.ChildrenGenerator<PsiParameterList, PsiParameter> {
public static final ParameterList INSTANCE = new ParameterList();
public List<PsiParameter> getChildren(PsiParameterList psiParameterList) {
return Arrays.asList(psiParameterList.getParameters());
}
}
private static class ThrowsList implements ChangeSignatureUtil.ChildrenGenerator<PsiReferenceList, PsiJavaCodeReferenceElement> {
public static final ThrowsList INSTANCE = new ThrowsList();
public List<PsiJavaCodeReferenceElement> getChildren(PsiReferenceList throwsList) {
return Arrays.asList(throwsList.getReferenceElements());
}
}
}
|
package org.motechproject.nms.region.service.impl;
import org.apache.commons.io.IOUtils;
import org.datanucleus.store.rdbms.query.ForwardQueryResult;
import org.motechproject.mds.query.SqlQueryExecution;
import org.motechproject.metrics.service.Timer;
import org.motechproject.nms.csv.exception.CsvImportDataException;
import org.motechproject.nms.csv.utils.ConstraintViolationUtils;
import org.motechproject.nms.csv.utils.CsvImporterBuilder;
import org.motechproject.nms.csv.utils.CsvMapImporter;
import org.motechproject.nms.csv.utils.GetLong;
import org.motechproject.nms.csv.utils.GetString;
import org.motechproject.nms.region.domain.LocationEnum;
import org.motechproject.nms.region.domain.State;
import org.motechproject.nms.region.domain.District;
import org.motechproject.nms.region.domain.Taluka;
import org.motechproject.nms.region.domain.Village;
import org.motechproject.nms.region.domain.HealthBlock;
import org.motechproject.nms.region.domain.HealthFacility;
import org.motechproject.nms.region.domain.HealthSubFacility;
import org.motechproject.nms.region.domain.LocationFinder;
import org.motechproject.nms.region.exception.InvalidLocationException;
import org.motechproject.nms.region.repository.StateDataService;
import org.motechproject.nms.region.repository.DistrictDataService;
import org.motechproject.nms.region.repository.TalukaDataService;
import org.motechproject.nms.region.repository.VillageDataService;
import org.motechproject.nms.region.repository.HealthBlockDataService;
import org.motechproject.nms.region.repository.HealthFacilityDataService;
import org.motechproject.nms.region.repository.HealthSubFacilityDataService;
import org.motechproject.nms.region.service.DistrictService;
import org.motechproject.nms.region.service.HealthBlockService;
import org.motechproject.nms.region.service.HealthFacilityService;
import org.motechproject.nms.region.service.HealthSubFacilityService;
import org.motechproject.nms.region.service.LocationService;
import org.motechproject.nms.region.service.StateService;
import org.motechproject.nms.region.service.TalukaService;
import org.motechproject.nms.region.service.VillageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.prefs.CsvPreference;
import javax.jdo.Query;
import javax.validation.ConstraintViolationException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.List;
import static org.motechproject.nms.region.domain.LocationEnum.VILLAGEHEALTHSUBFACILITY;
import static org.motechproject.nms.region.utils.LocationConstants.CODE_SQL_STRING;
import static org.motechproject.nms.region.utils.LocationConstants.CSV_STATE_ID;
import static org.motechproject.nms.region.utils.LocationConstants.DISTRICT_ID;
import static org.motechproject.nms.region.utils.LocationConstants.DISTRICT_NAME;
import static org.motechproject.nms.region.utils.LocationConstants.HEALTHBLOCK_ID;
import static org.motechproject.nms.region.utils.LocationConstants.HEALTHBLOCK_NAME;
import static org.motechproject.nms.region.utils.LocationConstants.HEALTHFACILITY_ID;
import static org.motechproject.nms.region.utils.LocationConstants.HEALTHFACILITY_NAME;
import static org.motechproject.nms.region.utils.LocationConstants.HEALTHSUBFACILITY_ID;
import static org.motechproject.nms.region.utils.LocationConstants.HEALTHSUBFACILITY_NAME;
import static org.motechproject.nms.region.utils.LocationConstants.INVALID;
import static org.motechproject.nms.region.utils.LocationConstants.LOCATION_PART_SIZE;
import static org.motechproject.nms.region.utils.LocationConstants.NON_CENSUS_VILLAGE;
import static org.motechproject.nms.region.utils.LocationConstants.OR_SQL_STRING;
import static org.motechproject.nms.region.utils.LocationConstants.PHC_ID;
import static org.motechproject.nms.region.utils.LocationConstants.PHC_NAME;
import static org.motechproject.nms.region.utils.LocationConstants.SMALL_LOCATION_PART_SIZE;
import static org.motechproject.nms.region.utils.LocationConstants.STATE_ID;
import static org.motechproject.nms.region.utils.LocationConstants.SUBCENTRE_ID;
import static org.motechproject.nms.region.utils.LocationConstants.SUBCENTRE_NAME;
import static org.motechproject.nms.region.utils.LocationConstants.TALUKA_ID;
import static org.motechproject.nms.region.utils.LocationConstants.TALUKA_NAME;
import static org.motechproject.nms.region.utils.LocationConstants.VILLAGE_ID;
import static org.motechproject.nms.region.utils.LocationConstants.VILLAGE_NAME;
/**
* Location service impl to get location objects
*/
@Service("locationService")
public class LocationServiceImpl implements LocationService {
private static final Logger LOGGER = LoggerFactory.getLogger(LocationServiceImpl.class);
private StateService stateService;
private StateDataService stateDataService;
private DistrictService districtService;
private TalukaService talukaService;
private VillageService villageService;
private HealthBlockService healthBlockService;
private HealthFacilityService healthFacilityService;
private HealthSubFacilityService healthSubFacilityService;
private DistrictDataService districtDataService;
private TalukaDataService talukaDataService;
private VillageDataService villageDataService;
private HealthBlockDataService healthBlockDataService;
private HealthFacilityDataService healthFacilityDataService;
private HealthSubFacilityDataService healthSubFacilityDataService;
@Autowired
public LocationServiceImpl(StateService stateService, StateDataService stateDataService, DistrictService districtService,
TalukaService talukaService, VillageService villageService,
HealthBlockService healthBlockService, HealthFacilityService healthFacilityService,
HealthSubFacilityService healthSubFacilityService, DistrictDataService districtDataService, TalukaDataService talukaDataService, VillageDataService villageDataService, HealthBlockDataService healthBlockDataService, HealthFacilityDataService healthFacilityDataService, HealthSubFacilityDataService healthSubFacilityDataService) {
this.stateService = stateService;
this.stateDataService = stateDataService;
this.districtService = districtService;
this.talukaService = talukaService;
this.villageService = villageService;
this.healthBlockService = healthBlockService;
this.healthFacilityService = healthFacilityService;
this.healthSubFacilityService = healthSubFacilityService;
this.districtDataService = districtDataService;
this.talukaDataService = talukaDataService;
this.villageDataService = villageDataService;
this.healthBlockDataService = healthBlockDataService;
this.healthFacilityDataService = healthFacilityDataService;
this.healthSubFacilityDataService = healthSubFacilityDataService;
}
private boolean isValidID(final Map<String, Object> map, final String key) {
Object obj = map.get(key);
if (obj == null || obj.toString().isEmpty() || "NULL".equalsIgnoreCase(obj.toString())) {
return false;
}
if (obj.getClass().equals(Long.class)) {
return (Long) obj > 0L;
}
return !"0".equals(obj);
}
public Map<String, Object> getLocations(Map<String, Object> map) throws InvalidLocationException {
return getLocations(map, false);
}
@Override // NO CHECKSTYLE Cyclomatic Complexity
@SuppressWarnings("PMD")
public Map<String, Object> getLocations(Map<String, Object> map, boolean createIfNotExists) throws InvalidLocationException {
Map<String, Object> locations = new HashMap<>();
LOGGER.info("map {}", isValidID(map, STATE_ID));
// set state
if (!isValidID(map, STATE_ID)) {
return locations;
}
State state = stateDataService.findByCode((Long) map.get(STATE_ID));
LOGGER.info("state {}", state);
if (state == null) { // we are here because stateId wasn't null but fetch returned no data
throw new InvalidLocationException(String.format(INVALID, STATE_ID, map.get(STATE_ID)));
}
locations.put(STATE_ID, state);
// set district
if (!isValidID(map, DISTRICT_ID)) {
return locations;
}
District district = districtService.findByStateAndCode(state, (Long) map.get(DISTRICT_ID));
if (district == null) {
throw new InvalidLocationException(String.format(INVALID, DISTRICT_ID, map.get(DISTRICT_ID)));
}
locations.put(DISTRICT_ID, district);
// set and/or create taluka
if (!isValidID(map, TALUKA_ID)) {
return locations;
}
Taluka taluka = talukaService.findByDistrictAndCode(district, (String) map.get(TALUKA_ID));
if (taluka == null && createIfNotExists) {
taluka = new Taluka();
taluka.setCode((String) map.get(TALUKA_ID));
taluka.setName((String) map.get(TALUKA_NAME));
taluka.setDistrict(district);
district.getTalukas().add(taluka);
LOGGER.debug(String.format("Created %s in %s with id %d", taluka, district, taluka.getId()));
}
locations.put(TALUKA_ID, taluka);
// set and/or create village
Long svid = map.get(NON_CENSUS_VILLAGE) == null ? 0 : (Long) map.get(NON_CENSUS_VILLAGE);
Long vcode = map.get(VILLAGE_ID) == null ? 0 : (Long) map.get(VILLAGE_ID);
Village village = new Village();
if (vcode != 0 || svid != 0) {
village = villageService.findByTalukaAndVcodeAndSvid(taluka, vcode, svid);
if (village == null && createIfNotExists) {
village = new Village();
village.setSvid(svid);
village.setVcode(vcode);
village.setTaluka(taluka);
village.setName((String) map.get(VILLAGE_NAME));
taluka.getVillages().add(village);
LOGGER.debug(String.format("Created %s in %s with id %d", village, taluka, village.getId()));
}
locations.put(VILLAGE_ID + NON_CENSUS_VILLAGE, village);
}
// set and/or create health block
if (!isValidID(map, HEALTHBLOCK_ID)) {
return locations;
}
HealthBlock healthBlock = healthBlockService.findByDistrictAndCode(district, (Long) map.get(HEALTHBLOCK_ID));
if (healthBlock == null && createIfNotExists) {
healthBlock = new HealthBlock();
healthBlock.addTaluka(taluka);
healthBlock.setDistrict(district);
healthBlock.setCode((Long) map.get(HEALTHBLOCK_ID));
healthBlock.setName((String) map.get(HEALTHBLOCK_NAME));
taluka.addHealthBlock(healthBlock);
district.getHealthBlocks().add(healthBlock);
LOGGER.debug(String.format("Created %s in %s with id %d", healthBlock, taluka, healthBlock.getId()));
}
locations.put(HEALTHBLOCK_ID, healthBlock);
// set and/or create health facility
if (!isValidID(map, PHC_ID)) {
return locations;
}
HealthFacility healthFacility = healthFacilityService.findByHealthBlockAndCode(healthBlock, (Long) map.get(PHC_ID));
if (healthFacility == null && createIfNotExists) {
healthFacility = new HealthFacility();
healthFacility.setHealthBlock(healthBlock);
healthFacility.setCode((Long) map.get(PHC_ID));
healthFacility.setName((String) map.get(PHC_NAME));
healthBlock.getHealthFacilities().add(healthFacility);
LOGGER.debug(String.format("Created %s in %s with id %d", healthFacility, healthBlock, healthFacility.getId()));
}
locations.put(PHC_ID, healthFacility);
// set and/or create health sub-facility
if (!isValidID(map, SUBCENTRE_ID)) {
return locations;
}
HealthSubFacility healthSubFacility = healthSubFacilityService.findByHealthFacilityAndCode(healthFacility, (Long) map.get(SUBCENTRE_ID));
if (healthSubFacility == null && createIfNotExists) {
healthSubFacility = new HealthSubFacility();
healthSubFacility.addVillage(village);
healthSubFacility.setHealthFacility(healthFacility);
healthSubFacility.setCode((Long) map.get(SUBCENTRE_ID));
healthSubFacility.setName((String) map.get(SUBCENTRE_NAME));
healthFacility.getHealthSubFacilities().add(healthSubFacility);
village.addHealthSubFacility(healthSubFacility);
LOGGER.debug(String.format("Created %s in %s with id %d", healthSubFacility, healthFacility, healthSubFacility.getId()));
}
locations.put(SUBCENTRE_ID, healthSubFacility);
return locations;
}
@Override
public Taluka updateTaluka(Map<String, Object> flw, Boolean createIfNotExists) {
State state = stateDataService.findByCode((Long) flw.get(STATE_ID));
District district = districtService.findByStateAndCode(state, (Long) flw.get(DISTRICT_ID));
// set and/or create taluka
if (!isValidID(flw, TALUKA_ID)) {
return null;
}
Taluka taluka = talukaService.findByDistrictAndCode(district, (String) flw.get(TALUKA_ID));
if (taluka == null && createIfNotExists) {
taluka = new Taluka();
taluka.setCode((String) flw.get(TALUKA_ID));
taluka.setName((String) flw.get(TALUKA_NAME));
taluka.setDistrict(district);
LOGGER.debug(String.format("taluka: %s", taluka.toString()));
district.getTalukas().add(taluka);
LOGGER.debug(String.format("Created %s in %s with id %d", taluka, district, taluka.getId()));
}
return taluka;
}
@Override
public HealthBlock updateBlock(Map<String, Object> flw, Taluka taluka, Boolean createIfNotExists) {
// set and/or create health block
if (!isValidID(flw, HEALTHBLOCK_ID)) {
return null;
}
HealthBlock healthBlock = healthBlockService.findByTalukaAndCode(taluka, (Long) flw.get(HEALTHBLOCK_ID));
if (healthBlock == null && createIfNotExists) {
healthBlock = new HealthBlock();
healthBlock.addTaluka(taluka);
healthBlock.setDistrict(taluka.getDistrict());
healthBlock.setCode((Long) flw.get(HEALTHBLOCK_ID));
healthBlock.setName((String) flw.get(HEALTHBLOCK_NAME));
taluka.addHealthBlock(healthBlock);
LOGGER.debug(String.format("Created %s in %s with id %d", healthBlock, taluka, healthBlock.getId()));
}
return healthBlock;
}
@Override
public HealthFacility updateFacility(Map<String, Object> flw, HealthBlock healthBlock, Boolean createIfNotExists) {
// set and/or create health facility
if (!isValidID(flw, PHC_ID)) {
return null;
}
HealthFacility healthFacility = healthFacilityService.findByHealthBlockAndCode(healthBlock, (Long) flw.get(PHC_ID));
if (healthFacility == null && createIfNotExists) {
healthFacility = new HealthFacility();
healthFacility.setHealthBlock(healthBlock);
healthFacility.setCode((Long) flw.get(PHC_ID));
healthFacility.setName((String) flw.get(PHC_NAME));
healthBlock.getHealthFacilities().add(healthFacility);
LOGGER.debug(String.format("Created %s in %s with id %d", healthFacility, healthBlock, healthFacility.getId()));
}
return healthFacility;
}
@Override
public HealthSubFacility updateSubFacility(Map<String, Object> flw, HealthFacility healthFacility, Boolean createIfNotExists) {
// set and/or create health sub-facility
if (!isValidID(flw, SUBCENTRE_ID)) {
return null;
}
HealthSubFacility healthSubFacility = healthSubFacilityService.findByHealthFacilityAndCode(healthFacility, (Long) flw.get(SUBCENTRE_ID));
if (healthSubFacility == null && createIfNotExists) {
healthSubFacility = new HealthSubFacility();
healthSubFacility.setHealthFacility(healthFacility);
healthSubFacility.setCode((Long) flw.get(SUBCENTRE_ID));
healthSubFacility.setName((String) flw.get(SUBCENTRE_NAME));
healthFacility.getHealthSubFacilities().add(healthSubFacility);
LOGGER.debug(String.format("Created %s in %s with id %d", healthSubFacility, healthFacility, healthSubFacility.getId()));
}
return healthSubFacility;
}
@Override
public Village updateVillage(Map<String, Object> flw, Taluka taluka, Boolean createIfNotExists) {
// set and/or create village
Long svid = flw.get(NON_CENSUS_VILLAGE) == null ? 0 : (Long) flw.get(NON_CENSUS_VILLAGE);
Long vcode = flw.get(VILLAGE_ID) == null ? 0 : (Long) flw.get(VILLAGE_ID);
if (vcode != 0 || svid != 0) {
Village village = villageService.findByTalukaAndVcodeAndSvid(taluka, vcode, svid);
if (village == null && createIfNotExists) {
village = new Village();
village.setSvid(svid);
village.setVcode(vcode);
village.setTaluka(taluka);
village.setName((String) flw.get(VILLAGE_NAME));
taluka.getVillages().add(village);
LOGGER.debug(String.format("Created %s in %s with id %d", village, taluka, village.getId()));
}
return village;
}
return null;
}
@Override
public State getState(Long stateId) {
return stateDataService.findByCode(stateId);
}
@Override
public District getDistrict(Long stateId, Long districtId) {
State state = getState(stateId);
if (state != null) {
return districtService.findByStateAndCode(state, districtId);
}
return null;
}
@Override
public Taluka getTaluka(Long stateId, Long districtId, String talukaId) {
District district = getDistrict(stateId, districtId);
if (district != null) {
return talukaService.findByDistrictAndCode(district, talukaId);
}
return null;
}
@Override
public Village getVillage(Long stateId, Long districtId, String talukaId, Long vCode, Long svid) {
Taluka taluka = getTaluka(stateId, districtId, talukaId);
if (taluka != null) {
return villageService.findByTalukaAndVcodeAndSvid(taluka, vCode, svid);
}
return null;
}
@Override
public Village getCensusVillage(Long stateId, Long districtId, String talukaId, Long vCode) {
return getVillage(stateId, districtId, talukaId, vCode, 0L);
}
@Override
public Village getNonCensusVillage(Long stateId, Long districtId, String talukaId, Long svid) {
return getVillage(stateId, districtId, talukaId, 0L, svid);
}
@Override
public HealthBlock getHealthBlock(Long stateId, Long districtId, String talukaId, Long healthBlockId) {
Taluka taluka = getTaluka(stateId, districtId, talukaId);
if (taluka != null) {
return healthBlockService.findByTalukaAndCode(taluka, healthBlockId);
}
return null;
}
@Override
public HealthFacility getHealthFacility(Long stateId, Long districtId, String talukaId, Long healthBlockId,
Long healthFacilityId) {
HealthBlock healthBlock = getHealthBlock(stateId, districtId, talukaId, healthBlockId);
if (healthBlock != null) {
return healthFacilityService.findByHealthBlockAndCode(healthBlock, healthFacilityId);
}
return null;
}
@Override
public HealthSubFacility getHealthSubFacility(Long stateId, Long districtId, String talukaId,
Long healthBlockId, Long healthFacilityId,
Long healthSubFacilityId) {
HealthFacility healthFacility = getHealthFacility(stateId, districtId, talukaId, healthBlockId,
healthFacilityId);
if (healthFacility != null) {
return healthSubFacilityService.findByHealthFacilityAndCode(healthFacility, healthSubFacilityId);
}
return null;
}
@Override //NO CHECKSTYLE Cyclomatic Complexity
public LocationFinder updateLocations(List<Map<String, Object>> recordList) { //NOPMD NcssMethodCount
int count = 0;
Map<String, State> stateHashMap = new HashMap<>();
Map<String, District> districtHashMap = new HashMap<>();
Map<String, Taluka> talukaHashMap = new HashMap<>();
Map<String, Village> villageHashMap = new HashMap<>();
Map<String, HealthBlock> healthBlockHashMap = new HashMap<>();
Map<String, HealthFacility> healthFacilityHashMap = new HashMap<>();
Map<String, HealthSubFacility> healthSubFacilityHashMap = new HashMap<>();
LocationFinder locationFinder = new LocationFinder();
try {
for(Map<String, Object> record : recordList) {
count++;
StringBuffer mapKey = new StringBuffer(record.get(STATE_ID).toString());
if (isValidID(record, STATE_ID)) {
stateHashMap.put(mapKey.toString(), null);
mapKey.append("_");
mapKey.append(record.get(DISTRICT_ID).toString());
if (isValidID(record, DISTRICT_ID)) {
districtHashMap.put(mapKey.toString(), null);
if (isValidID(record, TALUKA_ID)) {
Taluka taluka = new Taluka();
taluka.setCode(record.get(TALUKA_ID).toString().trim());
taluka.setName((String) record.get(TALUKA_NAME));
mapKey.append("_");
mapKey.append(Long.parseLong(record.get(TALUKA_ID).toString().trim()));
talukaHashMap.put(mapKey.toString(), taluka);
Long svid = record.get(NON_CENSUS_VILLAGE) == null ? 0 : (Long) record.get(NON_CENSUS_VILLAGE);
Long vcode = record.get(VILLAGE_ID) == null ? 0 : (Long) record.get(VILLAGE_ID);
if (vcode != 0 || svid != 0) {
Village village = new Village();
village.setSvid(svid);
village.setVcode(vcode);
village.setName((String) record.get(VILLAGE_NAME));
villageHashMap.put(mapKey.toString() + "_" + vcode.toString() + "_" +
svid.toString(), village);
}
mapKey = new StringBuffer(record.get(STATE_ID).toString() + "_" +
record.get(DISTRICT_ID).toString());
if (isValidID(record, HEALTHBLOCK_ID)) {
HealthBlock healthBlock = new HealthBlock();
healthBlock.setCode((Long) record.get(HEALTHBLOCK_ID));
healthBlock.setName((String) record.get(HEALTHBLOCK_NAME));
mapKey.append("_");
mapKey.append((Long) record.get(HEALTHBLOCK_ID));
healthBlockHashMap.put(mapKey.toString(), healthBlock);
if (isValidID(record, PHC_ID)) {
HealthFacility healthFacility = new HealthFacility();
healthFacility.setCode((Long) record.get(PHC_ID));
healthFacility.setName((String) record.get(PHC_NAME));
mapKey.append("_");
mapKey.append((Long) record.get(PHC_ID));
healthFacilityHashMap.put(mapKey.toString(), healthFacility);
if (isValidID(record, SUBCENTRE_ID)) {
HealthSubFacility healthSubFacility = new HealthSubFacility();
healthSubFacility.setCode((Long) record.get(SUBCENTRE_ID));
healthSubFacility.setName((String) record.get(SUBCENTRE_NAME));
mapKey.append("_");
mapKey.append((Long) record.get(SUBCENTRE_ID));
healthSubFacilityHashMap.put(mapKey.toString(), healthSubFacility);
}
}
}
}
}
}
}
} catch (ConstraintViolationException e) {
throw new CsvImportDataException(String.format("Locations import error, constraints violated: %s",
ConstraintViolationUtils.toString(e.getConstraintViolations())), e);
}
if (!stateHashMap.isEmpty()) {
fillStates(stateHashMap);
locationFinder.setStateHashMap(stateHashMap);
if (!districtHashMap.isEmpty()) {
fillDistricts(districtHashMap, stateHashMap);
locationFinder.setDistrictHashMap(districtHashMap);
if (!talukaHashMap.isEmpty()) {
fillTalukas(talukaHashMap, districtHashMap);
locationFinder.setTalukaHashMap(talukaHashMap);
if (!villageHashMap.isEmpty()) {
fillVillages(villageHashMap, talukaHashMap);
locationFinder.setVillageHashMap(villageHashMap);
}
if (!healthBlockHashMap.isEmpty()) {
fillHealthBlocks(healthBlockHashMap, districtHashMap);
locationFinder.setHealthBlockHashMap(healthBlockHashMap);
if (!healthFacilityHashMap.isEmpty()) {
fillHealthFacilities(healthFacilityHashMap, healthBlockHashMap);
locationFinder.setHealthFacilityHashMap(healthFacilityHashMap);
if (!healthSubFacilityHashMap.isEmpty()) {
fillHealthSubFacilities(healthSubFacilityHashMap, healthFacilityHashMap);
locationFinder.setHealthSubFacilityHashMap(healthSubFacilityHashMap);
}
}
}
}
}
}
LOGGER.debug("Locations processed. Records Processed : {}", count);
return locationFinder;
}
@Override // NO CHECKSTYLE Cyclomatic Complexity
public void createLocations(Long stateID, LocationEnum locationType, String fileLocation) throws IOException {
MultipartFile rchImportFile = findByStateId(stateID, locationType.toString(), fileLocation);
try {
InputStream in = rchImportFile.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
Map<String, CellProcessor> cellProcessorMapper = null;
List<Map<String, Object>> recordList;
switch (locationType) {
case DISTRICT : cellProcessorMapper = getDistrictMapping(); break;
case TALUKA : cellProcessorMapper = getTalukaMapping(); break;
case VILLAGE : cellProcessorMapper = getVillageMapping(); break;
case HEALTHBLOCK : cellProcessorMapper = getHealthBlockMapping(); break;
case TALUKAHEALTHBLOCK : cellProcessorMapper = getTalukaHealthBlockMapping(); break;
case HEALTHFACILITY : cellProcessorMapper = getHealthFacilityMapping(); break;
case HEALTHSUBFACILITY : cellProcessorMapper = getHealthSubFacilityMapping(); break;
case VILLAGEHEALTHSUBFACILITY: cellProcessorMapper = getVillageHealthSubFacilityMapping();
}
recordList = readCsv(bufferedReader, cellProcessorMapper);
Long partitionSize = LOCATION_PART_SIZE;
if (locationType.equals(VILLAGEHEALTHSUBFACILITY)) {
partitionSize = SMALL_LOCATION_PART_SIZE;
}
int count = 0;
int partNumber = 0;
Long totalUpdatedRecords = 0L;
while (count < recordList.size()) {
List<Map<String, Object>> recordListPart = new ArrayList<>();
while (recordListPart.size() < partitionSize && count < recordList.size()) {
recordListPart.add(recordList.get(count));
count++;
}
partNumber++;
if (recordListPart.size()>0) {
totalUpdatedRecords += createLocationPart(recordListPart, locationType, rchImportFile.getOriginalFilename(), partNumber);
}
recordListPart.clear();
}
LOGGER.debug("File {} processed. {} records updated", rchImportFile.getOriginalFilename(), totalUpdatedRecords);
} catch(NullPointerException e) {
LOGGER.error("{} File Error", locationType, e);
}
}
public Long createLocationPart(List<Map<String, Object>> recordList, LocationEnum locationType, String rchImportFileName, int partNumber) { //NOPMD NcssMethodCount
Map<String, State> stateHashMap;
Map<String, District> districtHashMap;
Map<String, Taluka> talukaHashMap;
Map<String, HealthBlock> healthBlockHashMap;
Map<String, HealthFacility> healthFacilityHashMap;
Long updatedRecords = 0L;
switch (locationType) {
case DISTRICT :
stateHashMap = stateService.fillStateIds(recordList);
updatedRecords = districtService.createUpdateDistricts(recordList, stateHashMap);
break;
case TALUKA:
stateHashMap = stateService.fillStateIds(recordList);
districtHashMap = districtService.fillDistrictIds(recordList, stateHashMap);
updatedRecords = talukaService.createUpdateTalukas(recordList, districtHashMap);
break;
case VILLAGE:
stateHashMap = stateService.fillStateIds(recordList);
districtHashMap = districtService.fillDistrictIds(recordList, stateHashMap);
talukaHashMap = talukaService.fillTalukaIds(recordList, districtHashMap);
updatedRecords = villageService.createUpdateVillages(recordList, talukaHashMap);
break;
case HEALTHBLOCK:
stateHashMap = stateService.fillStateIds(recordList);
districtHashMap = districtService.fillDistrictIds(recordList, stateHashMap);
talukaHashMap = talukaService.fillTalukaIds(recordList, districtHashMap);
updatedRecords = healthBlockService.createUpdateHealthBlocks(recordList, districtHashMap, talukaHashMap);
break;
case TALUKAHEALTHBLOCK:
updatedRecords = healthBlockService.createUpdateTalukaHealthBlock(recordList);
break;
case HEALTHFACILITY:
stateHashMap = stateService.fillStateIds(recordList);
districtHashMap = districtService.fillDistrictIds(recordList, stateHashMap);
talukaHashMap = talukaService.fillTalukaIds(recordList, districtHashMap);
healthBlockHashMap = healthBlockService.fillHealthBlockIds(recordList, districtHashMap);
updatedRecords = healthFacilityService.createUpdateHealthFacilities(recordList, talukaHashMap, healthBlockHashMap);
break;
case HEALTHSUBFACILITY:
stateHashMap = stateService.fillStateIds(recordList);
districtHashMap = districtService.fillDistrictIds(recordList, stateHashMap);
talukaHashMap = talukaService.fillTalukaIds(recordList, districtHashMap);
//Adding Health Facilities using Talukas as HealthBlock code is not given
healthFacilityHashMap = healthFacilityService.fillHealthFacilitiesFromTalukas(recordList, talukaHashMap);
updatedRecords = healthSubFacilityService.createUpdateHealthSubFacilities(recordList, talukaHashMap, healthFacilityHashMap);
break;
case VILLAGEHEALTHSUBFACILITY:
updatedRecords = healthSubFacilityService.createUpdateVillageHealthSubFacility(recordList);
break;
}
LOGGER.debug("File {}, Part {} processed. {} records updated", rchImportFileName, partNumber, updatedRecords);
return updatedRecords;
}
private Map<String, CellProcessor> getDistrictMapping() {
Map<String, CellProcessor> mapping = new HashMap<>();
mapping.put(CSV_STATE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(DISTRICT_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(DISTRICT_NAME, new org.supercsv.cellprocessor.Optional(new GetString()));
return mapping;
}
private Map<String, CellProcessor> getTalukaMapping() {
Map<String, CellProcessor> mapping = new HashMap<>();
mapping.put(CSV_STATE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(TALUKA_ID, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(TALUKA_NAME, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(DISTRICT_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
return mapping;
}
private Map<String, CellProcessor> getVillageMapping() {
Map<String, CellProcessor> mapping = new HashMap<>();
mapping.put(CSV_STATE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(DISTRICT_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(TALUKA_ID, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(NON_CENSUS_VILLAGE, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(VILLAGE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(VILLAGE_NAME, new org.supercsv.cellprocessor.Optional(new GetString()));
return mapping;
}
private Map<String, CellProcessor> getHealthBlockMapping() {
Map<String, CellProcessor> mapping = new HashMap<>();
mapping.put(CSV_STATE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHBLOCK_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHBLOCK_NAME, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(DISTRICT_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(TALUKA_ID, new org.supercsv.cellprocessor.Optional(new GetString()));
return mapping;
}
private Map<String, CellProcessor> getTalukaHealthBlockMapping() {
Map<String, CellProcessor> mapping = new HashMap<>();
mapping.put(CSV_STATE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHBLOCK_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(TALUKA_NAME, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(TALUKA_ID, new org.supercsv.cellprocessor.Optional(new GetString()));
return mapping;
}
private Map<String, CellProcessor> getHealthFacilityMapping() {
Map<String, CellProcessor> mapping = new HashMap<>();
mapping.put(CSV_STATE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHFACILITY_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHFACILITY_NAME, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(TALUKA_ID, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(DISTRICT_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHBLOCK_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
return mapping;
}
private Map<String, CellProcessor> getHealthSubFacilityMapping() {
Map<String, CellProcessor> mapping = new HashMap<>();
mapping.put(CSV_STATE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHSUBFACILITY_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHSUBFACILITY_NAME, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(TALUKA_ID, new org.supercsv.cellprocessor.Optional(new GetString()));
mapping.put(DISTRICT_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHFACILITY_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
return mapping;
}
private Map<String, CellProcessor> getVillageHealthSubFacilityMapping() {
Map<String, CellProcessor> mapping = new HashMap<>();
mapping.put(CSV_STATE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(HEALTHSUBFACILITY_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(VILLAGE_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
mapping.put(DISTRICT_ID, new org.supercsv.cellprocessor.Optional(new GetLong()));
return mapping;
}
private MultipartFile findByStateId(Long stateId, String locationType, String fileLocation) throws IOException {
MultipartFile csvFilesByStateIdAndRchUserType = null;
File file = new File(fileLocation);
File[] files = file.listFiles();
if (files != null) {
for(File f: files){
String[] fileNameSplitter = f.getName().split("_");
if(fileNameSplitter[1].equalsIgnoreCase(stateId.toString()) && fileNameSplitter[0].equalsIgnoreCase(locationType)){
try {
FileInputStream input = new FileInputStream(f);
csvFilesByStateIdAndRchUserType = new MockMultipartFile("file",
f.getName(), "text/plain", IOUtils.toByteArray(input));
} catch (IOException e) {
LOGGER.debug("IO Exception", e);
}
}
}
}
return csvFilesByStateIdAndRchUserType;
}
private List<Map<String, Object>> readCsv(BufferedReader bufferedReader, Map<String, CellProcessor> cellProcessorMapper) throws IOException {
int count = 0;
CsvMapImporter csvImporter = new CsvImporterBuilder()
.setProcessorMapping(cellProcessorMapper)
.setPreferences(CsvPreference.TAB_PREFERENCE)
.createAndOpen(bufferedReader);
List<Map<String, Object>> recordList = new ArrayList<>();
Map<String, Object> record;
while (null != (record = csvImporter.read())) {
recordList.add(record);
count++;
}
LOGGER.debug("{} records added to object", count);
return recordList;
}
/**
* Fills the stateHashMap with State objects from database
* @param stateHashMap contains (stateCode, State) with dummy State objects
*/
private void fillStates(Map<String, State> stateHashMap) {
Timer queryTimer = new Timer();
final Set<String> stateKeys = stateHashMap.keySet();
@SuppressWarnings("unchecked")
SqlQueryExecution<List<State>> queryExecution = new SqlQueryExecution<List<State>>() {
@Override
public String getSqlQuery() {
String query = "SELECT * from nms_states where";
int count = stateKeys.size();
for (String stateString : stateKeys) {
count
query += " code = " + stateString;
if (count > 0) {
query += OR_SQL_STRING;
}
}
LOGGER.debug("STATE Query: {}", query);
return query;
}
@Override
public List<State> execute(Query query) {
query.setClass(State.class);
ForwardQueryResult fqr = (ForwardQueryResult) query.execute();
List<State> states;
if (fqr.isEmpty()) {
return null;
}
states = (List<State>) fqr;
return states;
}
};
List<State> states = stateDataService.executeSQLQuery(queryExecution);
LOGGER.debug("STATE Query time: {}", queryTimer.time());
for (State state : states) {
stateHashMap.put(state.getCode().toString(), state);
}
}
/**
* Fills districtHashMap with District objects from database
* @param districtHashMap contains (stateCode_districtCode, District) with dummy District objects
* @param stateHashMap contains (stateCode, State) with original State objects from database
*/
private void fillDistricts(Map<String, District> districtHashMap, final Map<String, State> stateHashMap) {
Timer queryTimer = new Timer();
final Set<String> districtKeys = districtHashMap.keySet();
Map<Long, String> stateIdMap = new HashMap<>();
for (String stateKey : stateHashMap.keySet()) {
stateIdMap.put(stateHashMap.get(stateKey).getId(), stateKey);
}
@SuppressWarnings("unchecked")
SqlQueryExecution<List<District>> queryExecution = new SqlQueryExecution<List<District>>() {
@Override
public String getSqlQuery() {
String query = "SELECT * from nms_districts where";
int count = districtKeys.size();
for (String districtString : districtKeys) {
count
String[] ids = districtString.split("_");
Long stateId = stateHashMap.get(ids[0]).getId();
query += CODE_SQL_STRING + ids[1] + " and state_id_oid = " + stateId + ")";
if (count > 0) {
query += OR_SQL_STRING;
}
}
LOGGER.debug("DISTRICT Query: {}", query);
return query;
}
@Override
public List<District> execute(Query query) {
query.setClass(District.class);
ForwardQueryResult fqr = (ForwardQueryResult) query.execute();
List<District> districts;
if (fqr.isEmpty()) {
return null;
}
districts = (List<District>) fqr;
return districts;
}
};
List<District> districts = districtDataService.executeSQLQuery(queryExecution);
LOGGER.debug("DISTRICT Query time: {}", queryTimer.time());
for (District district : districts) {
String stateKey = stateIdMap.get(district.getState().getId());
districtHashMap.put(stateKey + "_" + district.getCode(), district);
}
}
/**
* Fills talukaHashMap with Taluka objects from the database
* @param talukaHashMap contains (stateCode_districtCode_talukaCode, Taluka) with dummy Taluka objects
* @param districtHashMap contains (stateCode_districtCode, District) with original District objects from database
*/
private void fillTalukas(Map<String, Taluka> talukaHashMap, final Map<String, District> districtHashMap) {
Timer queryTimer = new Timer();
final Set<String> talukaKeys = talukaHashMap.keySet();
Map<Long, String> districtIdMap = new HashMap<>();
for (String districtKey : districtHashMap.keySet()) {
districtIdMap.put(districtHashMap.get(districtKey).getId(), districtKey);
}
@SuppressWarnings("unchecked")
SqlQueryExecution<List<Taluka>> queryExecution = new SqlQueryExecution<List<Taluka>>() {
@Override
public String getSqlQuery() {
String query = "SELECT * from nms_talukas where";
int count = talukaKeys.size();
for (String talukaString : talukaKeys) {
count
String[] ids = talukaString.split("_");
Long districtId = districtHashMap.get(ids[0] + "_" + ids[1]).getId();
query += CODE_SQL_STRING + ids[2] + " and district_id_oid = " + districtId + ")";
if (count > 0) {
query += OR_SQL_STRING;
}
}
LOGGER.debug("TALUKA Query: {}", query);
return query;
}
@Override
public List<Taluka> execute(Query query) {
query.setClass(Taluka.class);
ForwardQueryResult fqr = (ForwardQueryResult) query.execute();
List<Taluka> talukas;
if (fqr.isEmpty()) {
return null;
}
talukas = (List<Taluka>) fqr;
return talukas;
}
};
List<Taluka> talukas = talukaDataService.executeSQLQuery(queryExecution);
LOGGER.debug("TALUKA Query time: {}", queryTimer.time());
if(talukas != null && !talukas.isEmpty()) {
for (Taluka taluka : talukas) {
String districtKey = districtIdMap.get(taluka.getDistrict().getId());
talukaHashMap.put(districtKey + "_" + Long.parseLong(taluka.getCode()), taluka);
}
}
}
/**
* Fills villageHashMap with Village objects from database
* @param villageHashMap contains (stateCode_districtCode_talukaCode_villageCode_Svid, Village) with dummy Village objects
* @param talukaHashMap contains (stateCode_districtCode_talukaCode, Taluka) with original Taluka objects from database
*/
private void fillVillages(Map<String, Village> villageHashMap, final Map<String, Taluka> talukaHashMap) {
Timer queryTimer = new Timer();
final Set<String> villageKeys = villageHashMap.keySet();
Map<Long, String> talukaIdMap = new HashMap<>();
for (String districtKey : talukaHashMap.keySet()) {
talukaIdMap.put(talukaHashMap.get(districtKey).getId(), districtKey);
}
@SuppressWarnings("unchecked")
SqlQueryExecution<List<Village>> queryExecution = new SqlQueryExecution<List<Village>>() {
@Override
public String getSqlQuery() {
String query = "SELECT * from nms_villages where";
int count = villageKeys.size();
for (String villageString : villageKeys) {
count
String[] ids = villageString.split("_");
Long talukaId = talukaHashMap.get(ids[0] + "_" + ids[1] + "_" + ids[2]).getId();
query += " (vcode = " + ids[3] + " and svid = " + ids[4] + " and taluka_id_oid = " + talukaId + ")";
if (count > 0) {
query += OR_SQL_STRING;
}
}
LOGGER.debug("VILLAGE Query: {}", query);
return query;
}
@Override
public List<Village> execute(Query query) {
query.setClass(Village.class);
ForwardQueryResult fqr = (ForwardQueryResult) query.execute();
List<Village> villages;
if (fqr.isEmpty()) {
return null;
}
villages = (List<Village>) fqr;
return villages;
}
};
List<Village> villages = villageDataService.executeSQLQuery(queryExecution);
LOGGER.debug("VILLAGE Query time: {}", queryTimer.time());
if(villages != null && !villages.isEmpty()) {
for (Village village : villages) {
String talukaKey = talukaIdMap.get(village.getTaluka().getId());
villageHashMap.put(talukaKey + "_" + village.getVcode() + "_" + village.getSvid(), village);
}
}
}
/**
* Fills healthBlockHashMap with HealthBlock objects from database
* @param healthBlockHashMap contains (stateCode_districtCode_healthBlockCode, HealthBlock) with dummy HealthBlock objects
* @param districtHashMap contains (stateCode_districtCode, District) with original District objects from database
*/
private void fillHealthBlocks(Map<String, HealthBlock> healthBlockHashMap, final Map<String, District> districtHashMap) {
Timer queryTimer = new Timer();
final Set<String> healthBlockKeys = healthBlockHashMap.keySet();
Map<Long, String> districtIdMap = new HashMap<>();
for (String districtKey : districtHashMap.keySet()) {
districtIdMap.put(districtHashMap.get(districtKey).getId(), districtKey);
}
@SuppressWarnings("unchecked")
SqlQueryExecution<List<HealthBlock>> queryExecution = new SqlQueryExecution<List<HealthBlock>>() {
@Override
public String getSqlQuery() {
String query = "SELECT * from nms_health_blocks where";
int count = healthBlockKeys.size();
for (String healthBlockString : healthBlockKeys) {
count
String[] ids = healthBlockString.split("_");
Long districtId = districtHashMap.get(ids[0] + "_" + ids[1]).getId();
query += "(code = " + ids[2] + " and district_id_OID = " + districtId + ")";
if (count > 0) {
query += OR_SQL_STRING;
}
}
LOGGER.debug("HEALTHBLOCK Query: {}", query);
return query;
}
@Override
public List<HealthBlock> execute(Query query) {
query.setClass(HealthBlock.class);
ForwardQueryResult fqr = (ForwardQueryResult) query.execute();
List<HealthBlock> healthBlocks;
if (fqr.isEmpty()) {
return null;
}
healthBlocks = (List<HealthBlock>) fqr;
return healthBlocks;
}
};
List<HealthBlock> healthBlocks = healthBlockDataService.executeSQLQuery(queryExecution);
LOGGER.debug("HEALTHBLOCK Query time: {}", queryTimer.time());
if(healthBlocks != null && !healthBlocks.isEmpty()) {
for (HealthBlock healthBlock : healthBlocks) {
String districtKey = districtIdMap.get(healthBlock.getDistrict().getId());
healthBlockHashMap.put(districtKey + "_" + healthBlock.getCode(), healthBlock);
}
}
}
/**
* Fills healthFacilityHashMap with HealthFacility objects from the database
* @param healthFacilityHashMap contains (stateCode_districtCode_healthBlockCode_healthFacilityCode, HealthFacility)
* with dummy HealthFacility objects
* @param healthBlockHashMap contains (stateCode_districtCode_healthBlockCode, HealthBlock)
* with original HealthBlock objects from database
*/
private void fillHealthFacilities(Map<String, HealthFacility> healthFacilityHashMap, final Map<String, HealthBlock> healthBlockHashMap) {
Timer queryTimer = new Timer();
final Set<String> healthFacilityKeys = healthFacilityHashMap.keySet();
Map<Long, String> healthBlockIdMap = new HashMap<>();
for (String healthBlockKey : healthBlockHashMap.keySet()) {
healthBlockIdMap.put(healthBlockHashMap.get(healthBlockKey).getId(), healthBlockKey);
}
@SuppressWarnings("unchecked")
SqlQueryExecution<List<HealthFacility>> queryExecution = new SqlQueryExecution<List<HealthFacility>>() {
@Override
public String getSqlQuery() {
String query = "SELECT * from nms_health_facilities where";
int count = healthFacilityKeys.size();
for (String healthFacilityString : healthFacilityKeys) {
count
String[] ids = healthFacilityString.split("_");
Long healthBlockId = healthBlockHashMap.get(ids[0] + "_" + ids[1] + "_" + ids[2]).getId();
query += CODE_SQL_STRING + ids[3] + " and healthBlock_id_oid = " + healthBlockId + ")";
if (count > 0) {
query += OR_SQL_STRING;
}
}
LOGGER.debug("HEALTHFACILITY Query: {}", query);
return query;
}
@Override
public List<HealthFacility> execute(Query query) {
query.setClass(HealthFacility.class);
ForwardQueryResult fqr = (ForwardQueryResult) query.execute();
List<HealthFacility> healthFacilities;
if (fqr.isEmpty()) {
return null;
}
healthFacilities = (List<HealthFacility>) fqr;
return healthFacilities;
}
};
List<HealthFacility> healthFacilities = healthFacilityDataService.executeSQLQuery(queryExecution);
LOGGER.debug("HEALTHFACILITY Query time: {}", queryTimer.time());
if(healthFacilities != null && !healthFacilities.isEmpty()) {
for (HealthFacility healthFacility : healthFacilities) {
String healthBlockKey = healthBlockIdMap.get(healthFacility.getHealthBlock().getId());
healthFacilityHashMap.put(healthBlockKey + "_" + healthFacility.getCode(), healthFacility);
}
}
}
/**
* Fills healthSubFacilityHashMap with HealthSubFacility objects from the database
* @param healthSubFacilityHashMap contains (stateCode_districtCode_healthBlockCode_healthFacilityCode_healthSubFacilityCode, HealthSubFacility)
* with dummy HealthSubFacility objects
* @param healthFacilityHashMap contains (stateCode_districtCode_healthBlockCode_healthFacilityCode, HealthFacility)
* with original HealthFacility objects from database
*/
private void fillHealthSubFacilities(Map<String, HealthSubFacility> healthSubFacilityHashMap, final Map<String, HealthFacility> healthFacilityHashMap) {
Timer queryTimer = new Timer();
final Set<String> healthSubFacilityKeys = healthSubFacilityHashMap.keySet();
Map<Long, String> healthFacilityIdMap = new HashMap<>();
for (String healthFacilityKey : healthFacilityHashMap.keySet()) {
healthFacilityIdMap.put(healthFacilityHashMap.get(healthFacilityKey).getId(), healthFacilityKey);
}
@SuppressWarnings("unchecked")
SqlQueryExecution<List<HealthSubFacility>> queryExecution = new SqlQueryExecution<List<HealthSubFacility>>() {
@Override
public String getSqlQuery() {
String query = "SELECT * from nms_health_sub_facilities where";
int count = healthSubFacilityKeys.size();
for (String healthFacilityString : healthSubFacilityKeys) {
count
String[] ids = healthFacilityString.split("_");
Long healthFacilityId = healthFacilityHashMap.get(ids[0] + "_" + ids[1] + "_" + ids[2] + "_" + ids[3]).getId();
query += CODE_SQL_STRING + ids[4] + " and healthFacility_id_oid = " + healthFacilityId + ")";
if (count > 0) {
query += OR_SQL_STRING;
}
}
LOGGER.debug("HEALTHSUBFACILITY Query: {}", query);
return query;
}
@Override
public List<HealthSubFacility> execute(Query query) {
query.setClass(HealthSubFacility.class);
ForwardQueryResult fqr = (ForwardQueryResult) query.execute();
List<HealthSubFacility> healthSubFacilities;
if (fqr.isEmpty()) {
return null;
}
healthSubFacilities = (List<HealthSubFacility>) fqr;
return healthSubFacilities;
}
};
List<HealthSubFacility> healthSubFacilities = healthSubFacilityDataService.executeSQLQuery(queryExecution);
LOGGER.debug("HEALTHSUBFACILITY Query time: {}", queryTimer.time());
if(healthSubFacilities != null && !healthSubFacilities.isEmpty()) {
for (HealthSubFacility healthSubFacility : healthSubFacilities) {
String healthFacilityKey = healthFacilityIdMap.get(healthSubFacility.getHealthFacility().getId());
healthSubFacilityHashMap.put(healthFacilityKey + "_" + healthSubFacility.getCode(), healthSubFacility);
}
}
}
}
|
package lan.dk.podcastserver.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lan.dk.podcastserver.utils.jDomUtils;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.io.Serializable;
import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.Set;
@Table(name = "podcast")
@Entity
@JsonIgnoreProperties(ignoreUnknown = true)
public class Podcast implements Serializable {
private int id;
private String title;
private String url;
private String signature;
private String type;
private ZonedDateTime lastUpdate;
private Set<Item> items = new HashSet<>();
private Cover cover;
private String description;
private Boolean hasToBeDeleted;
private Set<Tag> tags = new HashSet<>();
public Podcast() {
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "type")
@Basic
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Column(name = "title")
@Basic
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "url", length = 65535)
@Basic
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Column(name = "signature")
@Basic
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
@Column(name = "last_update")
@Type(type = "org.jadira.usertype.dateandtime.threeten.PersistentZonedDateTime")
public ZonedDateTime getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(ZonedDateTime lastUpdate) {
this.lastUpdate = lastUpdate;
}
@OneToMany(mappedBy = "podcast", fetch = FetchType.LAZY, cascade=CascadeType.ALL, orphanRemoval=true)
@OrderBy("pubdate DESC")
@Fetch(FetchMode.SUBSELECT)
public Set<Item> getItems() {
return items;
}
public void setItems(Set<Item> items) {
this.items = items;
}
@OneToOne(fetch = FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, orphanRemoval=true)
@JoinColumn(name="cover_id")
public Cover getCover() {
return cover;
}
public void setCover(Cover cover) {
this.cover = cover;
}
@Column(name = "description", length = 65535 )
@Basic
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "hasToBeDeleted")
@Basic
public Boolean getHasToBeDeleted() {
return hasToBeDeleted;
}
public void setHasToBeDeleted(Boolean hasToBeDeleted) {
this.hasToBeDeleted = hasToBeDeleted;
}
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinTable(name="PODCAST_TAG",
joinColumns={@JoinColumn(name="PODCAST_ID", referencedColumnName="ID")},
inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
@Fetch(FetchMode.SUBSELECT)
public Set<Tag> getTags() {
return tags;
}
public Podcast setTags(Set<Tag> tags) {
this.tags = tags;
return this;
}
@Override
public String toString() {
return "Podcast{" +
"id=" + id +
", title='" + title + '\'' +
", url='" + url + '\'' +
", signature='" + signature + '\'' +
", type='" + type + '\'' +
", lastUpdate=" + lastUpdate +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Podcast that = (Podcast) o;
return id == that.id && !(lastUpdate != null ? !lastUpdate.equals(that.lastUpdate) : that.lastUpdate != null) && !(signature != null ? !signature.equals(that.signature) : that.signature != null) && !(title != null ? !title.equals(that.title) : that.title != null) && !(url != null ? !url.equals(that.url) : that.url != null);
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (url != null ? url.hashCode() : 0);
result = 31 * result + (signature != null ? signature.hashCode() : 0);
result = 31 * result + (lastUpdate != null ? lastUpdate.hashCode() : 0);
return result;
}
/* XML Methods */
@Transient @JsonIgnore
public String toXML(String serveurURL) {
return jDomUtils.podcastToXMLGeneric(this, serveurURL);
}
@Transient @JsonIgnore
public Podcast addTag(Tag tag) {
this.tags.add(tag);
return this;
}
@Transient @JsonIgnore
public boolean containsItem(Item item) {
return items.contains(item);
}
}
|
package org.stevedowning.remo.internal.common.future;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.stevedowning.remo.Callback;
import org.stevedowning.remo.Future;
import org.stevedowning.remo.Result;
public class BasicFuture<T> implements Future<T> {
private volatile boolean isDone, isCancelled, isError;
private volatile InterruptedException interruptedException;
private volatile ExecutionException executionException;
private volatile IOException ioException;
private volatile T val;
private final CountDownLatch doneLatch;
private final Queue<Callback<T>> callbacks;
// TODO: Allow the client to provide an optional executor service that runs callbacks.
// Watch out for deadlock opportunities when this happens.
public BasicFuture() {
isDone = false;
isCancelled = false;
isError = false;
interruptedException = null;
executionException = null;
val = null;
callbacks = new ConcurrentLinkedQueue<Callback<T>>();
doneLatch = new CountDownLatch(1);
}
public boolean cancel() {
// Quick check to avoid a potentially blocking call.
if (isDone) return false;
return setCancelled();
}
public BasicFuture<T> addCallback(Callback<T> callback) {
if (callback == null) return this;
if (isDone) {
callback.handleResult(this);
} else {
callbacks.offer(callback);
// Clear this callback out if we've hit the race condition that leaves it in
// the queue after we think we're done pumping everything out.
if (isDone && callbacks.remove(callback)) {
callback.handleResult(this);
}
}
return this;
}
public BasicFuture<T> addCancellationAction(Runnable action) {
if (action == null) return this;
addCallback((Result<T> result) -> { if (isCancelled) action.run(); });
return this;
}
public T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, IOException {
if (doneLatch.await(timeout, unit)) {
return get();
} else {
throw new InterruptedException();
}
}
public T get() throws InterruptedException, ExecutionException, IOException {
doneLatch.await();
if (executionException != null) {
throw executionException;
} else if (interruptedException != null) {
throw interruptedException;
} else if (ioException != null) {
throw ioException;
} else {
return val;
}
}
public boolean isDone() { return isDone; }
public boolean isError() { return isError; }
public boolean isCancelled() { return isError; }
public boolean isSuccess() { return isDone && !isError && !isCancelled; }
public synchronized boolean setVal(T val) {
if (isDone) return false;
this.val = val;
harden();
return true;
}
private synchronized boolean setCancelled() {
if (isDone) return false;
isCancelled = true;
return setException(new InterruptedException());
}
public synchronized boolean setException(InterruptedException ex) {
if (isDone) return false;
interruptedException = ex;
isError = !isCancelled; // Importantly, cancellation isn't an error state.
harden();
return true;
}
public synchronized boolean setException(IOException ex) {
if (isDone) return false;
ioException = ex;
isError = true;
harden();
return true;
}
public synchronized boolean setException(ExecutionException ex) {
if (isDone) return false;
executionException = ex;
isError = true;
harden();
return true;
}
/**
* Lock down this future. It's already received its result. It's no longer mutable.
*/
private synchronized void harden() {
isDone = true;
doneLatch.countDown();
invokeCallbacks();
}
private void invokeCallbacks() {
for (Callback<T> callback; (callback = callbacks.poll()) != null;) {
callback.handleResult(this);
}
}
}
|
package markpeng.kaggle;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.WhitespaceTokenizer;
import org.apache.lucene.analysis.shingle.ShingleFilter;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.util.Version;
import org.apache.mahout.classifier.naivebayes.BayesUtils;
import org.apache.mahout.classifier.naivebayes.ComplementaryNaiveBayesClassifier;
import org.apache.mahout.classifier.naivebayes.NaiveBayesModel;
import org.apache.mahout.common.Pair;
import org.apache.mahout.common.iterator.sequencefile.SequenceFileIterable;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.Vector.Element;
import org.apache.mahout.vectorizer.TFIDF;
import com.google.common.collect.ConcurrentHashMultiset;
import com.google.common.collect.Multiset;
public class NaiveBayesPredictor {
private static final int BUFFER_LENGTH = 1000;
private static final String newLine = System.getProperty("line.separator");
private static final int MAX_NGRAM = 2;
private static final int MIN_DF = 2;
private static final double MAX_DF_PERCENT = 0.85;
public static Map<String, Integer> readDictionary(Configuration conf,
String dictionaryPath) {
Map<String, Integer> dictionnary = new HashMap<String, Integer>();
System.out.println("Loading word dictionary file ......");
File checker = new File(dictionaryPath);
if (checker.isDirectory()) {
for (final File fileEntry : checker.listFiles()) {
if (fileEntry.getName().startsWith("dictionary.file-")) {
String filePath = fileEntry.getAbsolutePath();
for (Pair<Text, IntWritable> pair : new SequenceFileIterable<Text, IntWritable>(
new Path(filePath), true, conf)) {
dictionnary.put(pair.getFirst().toString(), pair
.getSecond().get());
}
}
}
} else {
for (Pair<Text, IntWritable> pair : new SequenceFileIterable<Text, IntWritable>(
new Path(dictionaryPath), true, conf)) {
dictionnary.put(pair.getFirst().toString(), pair.getSecond()
.get());
}
}
return dictionnary;
}
public static Map<Integer, Long> readDocumentFrequency(Configuration conf,
String documentFrequencyPath) {
Map<Integer, Long> documentFrequency = new HashMap<Integer, Long>();
System.out.println("Loading document frequency file ......");
File checker = new File(documentFrequencyPath);
if (checker.isDirectory()) {
for (final File fileEntry : checker.listFiles()) {
if (fileEntry.getName().startsWith("part-r-")) {
String filePath = fileEntry.getAbsolutePath();
for (Pair<IntWritable, LongWritable> pair : new SequenceFileIterable<IntWritable, LongWritable>(
new Path(filePath), true, conf)) {
documentFrequency.put(pair.getFirst().get(), pair
.getSecond().get());
}
}
}
} else {
for (Pair<IntWritable, LongWritable> pair : new SequenceFileIterable<IntWritable, LongWritable>(
new Path(documentFrequencyPath), true, conf)) {
documentFrequency.put(pair.getFirst().get(), pair.getSecond()
.get());
}
}
return documentFrequency;
}
public static void main(String[] args) throws Exception {
// args = new String[6];
// args[0] = "/home/markpeng/test/cnb_model";
// args[1] = "/home/markpeng/test/cnb_labelindex";
// args[2] = "/home/markpeng/test/train_10samples_filtered-vector";
// args[3] =
// "/home/markpeng/test/train_10samples_filtered-vector/df-count";
// args[4] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/dataSample";
// args[5] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/dataSample/submission.csv";
// args[0] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/result/mmc_train_filtered_cnb_model";
// args[1] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/result/mmc_train_filtered_cnb_labelindex";
// args[2] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/result/dictionary.file-0";
// args[3] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/result/df-count";
// args[4] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/dataSample";
// args[5] =
// "/home/markpeng/Share/Kaggle/Microsoft Malware Classification/dataSample/submission.csv";
if (args.length < 7) {
System.out
.println("Arguments: [model] [fileType] [label index] [dictionnary] [document frequency] [test folder] [output csv]");
return;
}
String modelPath = args[0];
String fileType = args[1];
String labelIndexPath = args[2];
String dictionaryPath = args[3];
String documentFrequencyPath = args[4];
String testFolderPath = args[5];
String csvFilePath = args[6];
File checker = new File(testFolderPath);
if (checker.exists()) {
Configuration configuration = new Configuration();
// model is a matrix (wordId, labelId) => probability score
NaiveBayesModel model = NaiveBayesModel.materialize(new Path(
modelPath), configuration);
ComplementaryNaiveBayesClassifier classifier = new ComplementaryNaiveBayesClassifier(
model);
// labels is a map label => classId
Map<Integer, String> labels = BayesUtils.readLabelIndex(
configuration, new Path(labelIndexPath));
// word => word_id
Map<String, Integer> dictionary = readDictionary(configuration,
dictionaryPath);
// word_id => DF
Map<Integer, Long> documentFrequency = readDocumentFrequency(
configuration, documentFrequencyPath);
int labelCount = labels.size();
int documentCount = documentFrequency.get(-1).intValue();
System.out.println("Number of labels: " + labelCount);
System.out.println("Number of documents in training set: "
+ documentCount);
// get all test file path
List<String> asmFiles = new ArrayList<String>();
for (final File fileEntry : checker.listFiles()) {
if (fileEntry.getName().contains("." + fileType + "_filtered")) {
String tmp = fileEntry.getAbsolutePath();
asmFiles.add(tmp);
}
}
StringBuffer outputStr = new StringBuffer();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(csvFilePath, false), "UTF-8"));
try {
// write header
outputStr
.append("\"Id\",\"Prediction1\",\"Prediction2\",\"Prediction3\","
+ "\"Prediction4\",\"Prediction5\",\"Prediction6\","
+ "\"Prediction7\",\"Prediction8\",\"Prediction9\""
+ newLine);
for (String asmFile : asmFiles) {
File f = new File(asmFile);
String fileName = f.getName()
.replace("." + fileType + "_filtered", "").trim();
// read test file content
BufferedReader reader = new BufferedReader(new FileReader(
asmFile));
try {
StringBuffer text = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
text.append(line + newLine);
}
Multiset<String> words = ConcurrentHashMultiset
.create();
// extract words from current line
TokenStream ts = new WhitespaceTokenizer(
Version.LUCENE_46, new StringReader(
text.toString()));
// TokenStream ts = new StandardTokenizer(
// Version.LUCENE_46, new StringReader(
// text.toString()));
// get n-gram filter (N=2)
ts = new ShingleFilter(ts, MAX_NGRAM, MAX_NGRAM);
CharTermAttribute termAtt = ts
.addAttribute(CharTermAttribute.class);
ts.reset();
int wordCount = 0;
while (ts.incrementToken()) {
if (termAtt.length() > 0) {
String word = termAtt.toString();
Integer wordId = dictionary.get(word);
// if the word is not in the dictionary, skip it
if (wordId != null) {
words.add(word);
wordCount++;
// System.out.println(word);
}
}
}
// Fixed error : close ts:TokenStream
ts.end();
ts.close();
// create vector wordId => weight using tfidf
Vector vector = new RandomAccessSparseVector(100000);
TFIDF tfidf = new TFIDF();
int l2norm = 0;
for (Multiset.Entry<String> entry : words.entrySet()) {
String word = entry.getElement();
int count = entry.getCount();
Integer wordId = dictionary.get(word);
Long freq = documentFrequency.get(wordId);
if (freq < MIN_DF)
continue;
if (((double) freq / documentCount) >= MAX_DF_PERCENT)
continue;
// it ignores wordCount (length)
// TF => Math.sqrt(freq)
// IDF => Math.log(numDocs/(double)(docFreq+1))+1.0
double tfIdfValue = tfidf.calculate(count,
freq.intValue(), wordCount, documentCount);
l2norm += Math.pow(tfIdfValue, 2);
}
for (Multiset.Entry<String> entry : words.entrySet()) {
String word = entry.getElement();
int count = entry.getCount();
Integer wordId = dictionary.get(word);
Long freq = documentFrequency.get(wordId);
if (freq < MIN_DF)
continue;
if (((double) freq / documentCount) >= MAX_DF_PERCENT)
continue;
// it ignores wordCount (length)
// TF => Math.sqrt(freq)
// IDF => Math.log(numDocs/(double)(docFreq+1))+1.0
double tfIdfValue = tfidf.calculate(count,
freq.intValue(), wordCount, documentCount);
// enforce L2 Euclidean norm
tfIdfValue = (double) tfIdfValue
/ Math.sqrt(l2norm);
vector.setQuick(wordId, tfIdfValue);
}
// With the classifier, we get one score for each label
// The label with the highest score is the one the file
// is more likely to be associated to\
TreeMap<Integer, Double> map = new TreeMap<Integer, Double>();
Vector resultVector = classifier.classifyFull(vector);
double bestScore = -Double.MAX_VALUE;
double minScore = Double.MAX_VALUE;
double sumScore = -1;
int bestCategoryId = -1;
for (Element element : resultVector.all()) {
int categoryId = element.index();
double score = element.get();
// use log normalization
map.put(categoryId, score);
if (score > bestScore) {
bestScore = score;
bestCategoryId = categoryId;
}
if (score < minScore)
minScore = score;
sumScore += score;
}
System.out.println(fileName + " => "
+ labels.get(bestCategoryId));
// compute Euclidean length of the vector
// double unitLength = 0;
// for (Integer id : map.keySet()) {
// double score = map.get(id);
// // normalize by mean score
// unitLength += Math.pow(score, 2);
// unitLength = Math.sqrt(unitLength);
// compuate mean and sd
// double mean = 0;
// double sd = 0;
// for (Integer id : map.keySet()) {
// double score = map.get(id);
// mean += score;
// mean = mean / 9;
// for (Integer id : map.keySet()) {
// double score = map.get(id);
// sd += Math.pow(score - mean, 2);
// sd = sd / 9;
// sd = Math.sqrt(sd);
// write to csv
outputStr.append("\"" + fileName + "\",");
int count = 0;
for (Integer id : map.keySet()) {
double score = map.get(id);
// normalize by standard score
// score = (double) (score - mean) / sd;
// normalize by unit vector length
// score = (double) score / unitLength;
// max-min normalization
// score = (double) (score - minScore)
// / (bestScore - minScore);
// use equal probability if not valid
// if (Double.isInfinite(score) ||
// Double.isNaN(score)
// || score == 0)
// score = 0.5;
// score = (double) 1 / 9;
if (count < map.size() - 1)
outputStr.append(score + ",");
else
outputStr.append(score);
count++;
}
outputStr.append(newLine);
if (outputStr.length() >= BUFFER_LENGTH) {
out.write(outputStr.toString());
out.flush();
outputStr.setLength(0);
}
} finally {
reader.close();
}
} // end of asm file loop
} finally {
out.write(outputStr.toString());
out.flush();
out.close();
}
}
}
}
|
package me.ampayne2.ampmenus.menus;
import me.ampayne2.ampmenus.events.ItemClickEvent;
import me.ampayne2.ampmenus.items.MenuItem;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
/**
* A utility that allows creating inventories with items that do stuff when clicked.
*/
public class ItemMenu implements Listener, Menu {
private String name;
private int size;
private Plugin plugin;
private MenuItem[] menuItems;
private Menu parent;
/**
* The ItemStack that appears in empty slots.
*/
private static final ItemStack EMPTY_SLOT;
/**
* Creates a new ItemMenu.
*
* @param name The name of the inventory.
* @param size The size of the inventory.
* @param plugin The Plugin instance.
* @param parent The ItemMenu's parent.
*/
public ItemMenu(String name, int size, Plugin plugin, Menu parent) {
this.name = name;
this.size = size;
this.plugin = plugin;
this.menuItems = new MenuItem[size];
this.parent = parent;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
/**
* Creates a new ItemMenu with no parent.
*
* @param name The name of the inventory.
* @param size The size of the inventory.
* @param plugin The Plugin instance.
*/
public ItemMenu(String name, int size, Plugin plugin) {
this(name, size, plugin, null);
}
@Override
public String getName() {
return name;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean hasParent() {
return parent != null;
}
@Override
public Menu getParent() {
return parent;
}
@Override
public void setParent(Menu parent) {
this.parent = parent;
}
/**
* Sets the {@link me.ampayne2.ampmenus.items.MenuItem} of a slot.
*
* @param position The slot position.
* @param menuItem The {@link me.ampayne2.ampmenus.items.MenuItem}.
* @return The ItemMenu.
*/
public ItemMenu setItem(int position, MenuItem menuItem) {
menuItems[position] = menuItem;
return this;
}
/**
* Opens the ItemMenu for a player.
*
* @param player The player.
*/
@Override
public void open(Player player) {
Inventory inventory = Bukkit.createInventory(player, size, name);
for (int i = 0; i < menuItems.length; i++) {
if (menuItems[i] == null) {
inventory.setItem(i, EMPTY_SLOT);
} else {
inventory.setItem(i, menuItems[i].getFinalIcon(player));
}
}
player.openInventory(inventory);
}
@Override
@SuppressWarnings("deprecation")
public void update(Player player) {
if (player.getOpenInventory() != null) {
Inventory inventory = player.getOpenInventory().getTopInventory();
if (inventory.getTitle().equals(name)) {
for (int i = 0; i < menuItems.length; i++) {
if (menuItems[i] == null) {
inventory.setItem(i, EMPTY_SLOT);
} else {
inventory.setItem(i, menuItems[i].getFinalIcon(player));
}
}
player.updateInventory();
}
}
}
/**
* Handles InventoryClickEvents for the ItemMenu.
*/
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
if (event.getInventory().getTitle().equals(name)) {
event.setCancelled(true);
if (event.getClick() == ClickType.LEFT) {
int slot = event.getRawSlot();
if (slot >= 0 && slot < size && menuItems[slot] != null) {
Player player = (Player) event.getWhoClicked();
ItemClickEvent itemClickEvent = new ItemClickEvent(player);
menuItems[slot].onItemClick(itemClickEvent);
if (itemClickEvent.willUpdate()) {
update(player);
} else {
player.updateInventory();
if (itemClickEvent.willClose() || itemClickEvent.willGoBack()) {
final String playerName = player.getName();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
Player p = Bukkit.getPlayerExact(playerName);
if (p != null) {
p.closeInventory();
}
}
}, 1);
}
if (itemClickEvent.willGoBack() && hasParent()) {
final String playerName = player.getName();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
Player p = Bukkit.getPlayerExact(playerName);
if (p != null) {
parent.open(p);
}
}
}, 3);
}
}
}
}
}
}
@Override
public void destroy() {
HandlerList.unregisterAll(this);
plugin = null;
menuItems = null;
}
static {
EMPTY_SLOT = new ItemStack(Material.STAINED_GLASS_PANE, 1, DyeColor.GRAY.getData());
ItemMeta meta = EMPTY_SLOT.getItemMeta();
meta.setDisplayName(" ");
EMPTY_SLOT.setItemMeta(meta);
}
}
|
package org.eclipselabs.emfjson.rotten;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
/**
*
* @author guillaume
*
*/
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
|
package me.vilsol.blockly2java;
import me.vilsol.blockly2java.annotations.BBlock;
import me.vilsol.blockly2java.annotations.BField;
import me.vilsol.blockly2java.annotations.BStatement;
import me.vilsol.blockly2java.annotations.BValue;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Blockly2Java {
private static final Blockly2Java instance = new Blockly2Java();
private final Map<String, BlocklyBlock> blocks = new HashMap<>();
private final Pattern nodePattern = Pattern.compile("(<.*?>)([^<>]*)");
private final Pattern attributePattern = Pattern.compile("([a-zA-Z0-9]+)=\"(.+?)\"");
protected static Blockly2Java getInstance() {
return instance;
}
/**
* Register a class to be used as an object for converting blockly to java object
*
* @param block The class of the object
*/
public static void registerClass(Class<?> block){
BBlock b = block.getAnnotation(BBlock.class);
if(b == null){
throw new RuntimeException("Tried to register block (" + block.getName() + ") without @BBlock annotation");
}
Map<String, Field> blockFields = new HashMap<>();
Map<String, Field> blockValues = new HashMap<>();
Map<String, Field> blockStatements = new HashMap<>();
Field[] fields = block.getDeclaredFields();
for(Field field : fields){
Annotation f;
if((f = field.getAnnotation(BField.class)) != null){
blockFields.put(((BField) f).value(), field);
}else if((f = field.getAnnotation(BValue.class)) != null){
if(field.getDeclaringClass().getAnnotation(BBlock.class) == null){
throw new RuntimeException("Class:" + block.getName() + " Should be a @BBlock class!");
}
blockValues.put(((BValue) f).value(), field);
}else if((f = field.getAnnotation(BStatement.class)) != null){
if(!field.getType().isAssignableFrom(List.class)){
throw new RuntimeException("Class:" + block.getName() + " Field:" + field.getName() + " Should be a list!");
}
blockStatements.put(((BStatement) f).value(), field);
}
if(f != null){
field.setAccessible(true);
}
}
getInstance().blocks.put(b.value(), new BlocklyBlock(block, b.value(), blockFields, blockValues, blockStatements));
}
/**
* Parse blockly XML structure and convert into an object
*
* @param blockly Blockly XML structure
* @return List of parent-most blocks
*/
public static ArrayList<Object> parseBlockly(String blockly){
Matcher m = getInstance().nodePattern.matcher(blockly);
Stack<Node> nodes = new Stack<>();
ArrayList<Object> blocks = new ArrayList<>();
Node lastNode = null;
int ignoreBlocks = 0;
while(m.find()){
if(!m.group(1).startsWith("</")) {
Node node = getNode(m.group(1), m.group(2));
if(node.getName().equals("mutation")){
continue;
}
if(node.getName().equals("next")){
nodes.pop();
lastNode = nodes.peek();
ignoreBlocks++;
continue;
}
if (lastNode != null) {
lastNode.addSubnode(node);
}
nodes.add(node);
lastNode = node;
}else{
if(m.group(1).equals("</mutation>")){
continue;
}
if(nodes.size() > 0) {
if (nodes.peek().getName().equals("block") && ignoreBlocks > 0) {
ignoreBlocks
} else if (!m.group(1).contains("next")) {
nodes.pop();
if (nodes.size() > 0) {
lastNode = nodes.peek();
}
}
}
if(nodes.size() == 0){
if(m.group(1).equals("</block>")) {
blocks.add(parseBlock(lastNode));
}
}
}
}
return blocks;
}
private static Object parseBlock(Node node){
BlocklyBlock baseBlock = getInstance().blocks.get(node.getAttributes().get("type"));
if(baseBlock == null){
throw new RuntimeException("No block with type '" + node.getAttributes().get("type") + "' registered!");
}
Object base = baseBlock.newInstance();
fillBlock(baseBlock, base, node);
return base;
}
private static void fillBlock(BlocklyBlock block, Object base, Node node){
if(node.getSubnodes() == null || node.getSubnodes().size() == 0){
return;
}
for(Node s : node.getSubnodes()){
String fieldName = s.getAttributes().get("name");
switch(s.getName()){
case "field":
Field field = block.getFields().get(fieldName);
if(field == null){
throw new RuntimeException("Field '" + fieldName + "' not found in " + base.getClass().getName());
}
if(field.getType().equals(int.class) || field.getType().equals(Integer.class)){
setValue(base, fieldName, field, Integer.parseInt(s.getValue()));
}else if(field.getType().equals(double.class) || field.getType().equals(Double.class)) {
setValue(base, fieldName, field, Double.parseDouble(s.getValue()));
}else if(field.getType().equals(float.class) || field.getType().equals(Float.class)) {
setValue(base, fieldName, field, Float.parseFloat(s.getValue()));
}else if(field.getType().equals(long.class) || field.getType().equals(Long.class)) {
setValue(base, fieldName, field, Long.parseLong(s.getValue()));
}else if(field.getType().equals(boolean.class) || field.getType().equals(Boolean.class)) {
setValue(base, fieldName, field, Boolean.parseBoolean(s.getValue()));
}else if(field.getType().isEnum()) {
setValue(base, fieldName, field, field.getType().getEnumConstants()[Integer.parseInt(s.getValue())]);
}else{
setValue(base, fieldName, field, s.getValue());
}
break;
case "value":
setValue(base, fieldName, block.getValues().get(fieldName), parseBlock(s.getSubnodes().iterator().next()));
break;
case "statement":
List<Object> objects = new ArrayList<>();
if(s.getSubnodes() != null && s.getSubnodes().size() > 0){
for(Node n : s.getSubnodes()){
objects.add(parseBlock(n));
}
}
setValue(base, fieldName, block.getStatements().get(fieldName), objects);
break;
}
}
if(base instanceof BlocklyAfterParsed){
((BlocklyAfterParsed) base).onFinish();
}
}
private static void setValue(Object object, String fieldName, Field field, Object value){
try {
field.set(object, value);
} catch (Exception e) {
if(field == null){
throw new RuntimeException("Object '" + object.getClass().getName() + "' does not contain field '" + fieldName + "'");
}else{
throw new RuntimeException("Exception '" + e.getMessage() + "' whilst trying to set '" + fieldName + "' in object " + object.getClass().getName());
}
}
}
private static Node getNode(String node, String value){
String name = node.split("\\s")[0].split(">")[0].substring(1);
Matcher m = getInstance().attributePattern.matcher(node);
Map<String, String> attributes = new HashMap<>();
while(m.find()){
attributes.put(m.group(1), m.group(2));
}
return new Node(name, attributes, value);
}
}
|
package mesosphere.marathon.client;
import java.util.List;
import java.util.Set;
import feign.Param;
import feign.RequestLine;
import mesosphere.marathon.client.model.v2.App;
import mesosphere.marathon.client.model.v2.DeleteAppTaskResponse;
import mesosphere.marathon.client.model.v2.DeleteAppTasksResponse;
import mesosphere.marathon.client.model.v2.Deployment;
import mesosphere.marathon.client.model.v2.EmbeddedAppResource;
import mesosphere.marathon.client.model.v2.GetAppResponse;
import mesosphere.marathon.client.model.v2.GetAppTasksResponse;
import mesosphere.marathon.client.model.v2.GetAppsResponse;
import mesosphere.marathon.client.model.v2.GetServerInfoResponse;
import mesosphere.marathon.client.model.v2.GetTasksResponse;
import mesosphere.marathon.client.model.v2.Group;
import mesosphere.marathon.client.model.v2.Result;
import mesosphere.marathon.client.utils.AppIdNormalizer;
import mesosphere.marathon.client.utils.MarathonException;
public interface Marathon {
// Apps
@RequestLine("GET /v2/apps")
GetAppsResponse getApps();
@RequestLine("GET /v2/apps?cmd={cmd}&id={id}&label={labelSelector}")
GetAppsResponse filterApps(@Param("cmd") String commandSubstring,
@Param(value = "id", expander = AppIdNormalizer.class) String idSubstring,
@Param("labelSelector") String labelSelector);
@RequestLine("GET /v2/apps?cmd={cmd}&id={id}&label={labelSelector}&embed={embed}")
GetAppsResponse filterApps(@Param("cmd") String commandSubstring,
@Param(value = "id", expander = AppIdNormalizer.class) String idSubstring,
@Param("labelSelector") String labelSelector,
@Param("embed") Set<EmbeddedAppResource> embeddedResources);
@RequestLine("GET /v2/apps/{id}")
GetAppResponse getApp(@Param(value = "id", expander = AppIdNormalizer.class) String id) throws MarathonException;
@RequestLine("GET /v2/apps/{id}/tasks")
GetAppTasksResponse getAppTasks(@Param(value = "id", expander = AppIdNormalizer.class) String id);
@RequestLine("GET /v2/tasks")
GetTasksResponse getTasks();
@RequestLine("POST /v2/apps")
App createApp(App app) throws MarathonException;
@RequestLine("PUT /v2/apps/{app_id}?force={force}")
void updateApp(@Param(value = "app_id", expander = AppIdNormalizer.class) String appId, App app,
@Param("force") boolean force) throws MarathonException;
@RequestLine("POST /v2/apps/{id}/restart?force={force}")
void restartApp(@Param(value = "id", expander = AppIdNormalizer.class) String id,
@Param("force") boolean force);
@RequestLine("DELETE /v2/apps/{id}")
Result deleteApp(@Param(value = "id", expander = AppIdNormalizer.class) String id) throws MarathonException;
@RequestLine("DELETE /v2/apps/{app_id}/tasks?host={host}&scale={scale}")
DeleteAppTasksResponse deleteAppTasks(@Param(value = "app_id", expander = AppIdNormalizer.class) String appId,
@Param("host") String host, @Param("scale") String scale);
@RequestLine("DELETE /v2/apps/{app_id}/tasks/{task_id}?scale={scale}")
DeleteAppTaskResponse deleteAppTask(@Param(value = "app_id", expander = AppIdNormalizer.class) String appId,
@Param("task_id") String taskId, @Param("scale") String scale);
// Groups
@RequestLine("POST /v2/groups")
Result createGroup(Group group) throws MarathonException;
@RequestLine("PUT /v2/groups/{id}")
Result updateGroup(@Param("id") String id, Group group, @Param("force") boolean force,
@Param("dryRun") boolean dryRun) throws MarathonException;
@RequestLine("DELETE /v2/groups/{id}")
Result deleteGroup(@Param("id") String id) throws MarathonException;
@RequestLine("GET /v2/groups/{id}")
Group getGroup(@Param("id") String id) throws MarathonException;
// Tasks
// Deployments
@RequestLine("GET /v2/deployments")
List<Deployment> getDeployments();
@RequestLine("DELETE /v2/deployments/{deploymentId}")
void cancelDeploymentAndRollback(@Param("deploymentId") String id);
@RequestLine("DELETE /v2/deployments/{deploymentId}?force=true")
void cancelDeployment(@Param("deploymentId") String id);
// Event Subscriptions
// Queue
// Server Info
@RequestLine("GET /v2/info")
GetServerInfoResponse getServerInfo();
// Miscellaneous
}
|
package io.subutai.core.localpeer.impl.container;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import io.subutai.common.command.CommandUtil;
import io.subutai.common.command.RequestBuilder;
import io.subutai.common.host.ContainerHostInfo;
import io.subutai.common.host.HostInterface;
import io.subutai.common.host.NullHostInterface;
import io.subutai.common.peer.ContainerCreationException;
import io.subutai.common.peer.ResourceHost;
import io.subutai.common.protocol.TemplateKurjun;
import io.subutai.common.quota.ContainerQuota;
import io.subutai.common.quota.ContainerResource;
import io.subutai.common.settings.Common;
import io.subutai.common.util.JsonUtil;
import io.subutai.common.util.NumUtil;
import io.subutai.common.util.ServiceLocator;
import io.subutai.core.hostregistry.api.HostDisconnectedException;
import io.subutai.core.hostregistry.api.HostRegistry;
import io.subutai.core.registration.api.RegistrationManager;
public class CreateContainerTask implements Callable<ContainerHostInfo>
{
protected static final Logger LOG = LoggerFactory.getLogger( CreateContainerTask.class );
private final ResourceHost resourceHost;
private final String hostname;
private final TemplateKurjun template;
private final String ip;
private final int vlan;
private final int timeoutSec;
private final String environmentId;
private final ContainerQuota quota;
protected CommandUtil commandUtil = new CommandUtil();
private HostRegistry hostRegistry;
public CreateContainerTask( HostRegistry hostRegistry, final ResourceHost resourceHost,
final TemplateKurjun template, final String hostname, final ContainerQuota quota,
final String ip, final int vlan, final int timeoutSec, final String environmentId )
{
Preconditions.checkNotNull( resourceHost );
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ) );
Preconditions.checkNotNull( template );
Preconditions.checkArgument( timeoutSec > 0 );
Preconditions.checkArgument( !Strings.isNullOrEmpty( ip ) && ip.matches( Common.CIDR_REGEX ) );
Preconditions.checkArgument( NumUtil.isIntBetween( vlan, Common.MIN_VLAN_ID, Common.MAX_VLAN_ID ) );
Preconditions.checkArgument( !Strings.isNullOrEmpty( environmentId ) );
this.hostRegistry = hostRegistry;
this.resourceHost = resourceHost;
this.template = template;
this.hostname = hostname;
this.ip = ip;
this.vlan = vlan;
this.timeoutSec = timeoutSec;
this.environmentId = environmentId;
this.quota = quota;
}
public static RegistrationManager getRegistrationManager() throws NamingException
{
return ServiceLocator.getServiceNoCache( RegistrationManager.class );
}
@Override
public ContainerHostInfo call() throws Exception
{
// commandUtil.execute( new RequestBuilder( "subutai clone" ).withCmdArgs(
// Lists.newArrayList( template.getName(), hostname, "-i", String.format( "\"%s %s\"", ip,
// vlan ), "-t",
// getRegistrationManager().generateContainerTTLToken( ( timeoutSec + 10 ) * 1000L )
// .getToken() ) )
// .withTimeout( 1 ).daemon(), resourceHost );
List<BatchAction> actions = new ArrayList<>();
BatchAction cloneAction = new BatchAction( "clone",
Lists.newArrayList( template.getName(), hostname, "-i", String.format( "\"%s %s\"", ip, vlan ), "-t",
getRegistrationManager().generateContainerTTLToken( ( timeoutSec + 10 ) * 1000L )
.getToken() ) );
actions.add( cloneAction );
for ( ContainerResource r : quota.getAllResources() )
{
BatchAction quotaAction = new BatchAction( "quota" );
quotaAction.addArgument( hostname );
quotaAction.addArgument( r.getContainerResourceType().getKey() );
quotaAction.addArgument( "-s" );
quotaAction.addArgument( r.getWriteValue() );
actions.add( quotaAction );
}
final ArrayList<String> arg = Lists.newArrayList( JsonUtil.toJson( actions ) );
commandUtil.execute( new RequestBuilder( "subutai batch -json" ).withCmdArgs( arg ), resourceHost );
long start = System.currentTimeMillis();
ContainerHostInfo hostInfo = null;
String ip = null;
long timePass = System.currentTimeMillis() - start;
final int limit = timeoutSec * 1000;
int counter = 0;
while ( timePass < limit && ( Strings.isNullOrEmpty( ip ) ) )
{
TimeUnit.SECONDS.sleep( 1 );
counter++;
if ( counter % 30 == 0 )
{
LOG.debug( String.format( "Still waiting for %s. Time: %d/%d. %d sec", hostname, timePass, limit,
counter ) );
}
try
{
hostInfo = hostRegistry.getContainerHostInfoByHostname( hostname );
HostInterface intf = hostInfo.getHostInterfaces().findByName( Common.DEFAULT_CONTAINER_INTERFACE );
if ( !( intf instanceof NullHostInterface ) )
{
ip = intf.getIp();
}
}
catch ( HostDisconnectedException e )
{
//ignore
}
timePass = System.currentTimeMillis() - start;
}
if ( hostInfo == null )
{
throw new ContainerCreationException(
String.format( "Container %s did not connect within timeout with proper IP", hostname ) );
}
else
{
//TODO sign CH key with PEK identified by LocalPeerId+environmentId
//at this point the CH key is already in the KeyStore and might be just updated.
}
LOG.info( String.format( "Container '%s' successfully created.", hostname ) );
LOG.debug( hostInfo.toString() );
return hostInfo;
}
protected class BatchAction
{
private String action;
private List<String> args = new ArrayList<>();
public BatchAction( final String action, final List<String> args )
{
this.action = action;
this.args = args;
}
public BatchAction( final String quota )
{
this.action = action;
}
public void addArgument( final String arg )
{
this.args.add( arg );
}
}
}
|
package mho.wheels.iterables;
import mho.wheels.math.MathUtils;
import mho.wheels.ordering.Ordering;
import mho.wheels.random.IsaacPRNG;
import mho.wheels.structures.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.*;
import static mho.wheels.ordering.Ordering.lt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* <p>A {@code RandomProvider} produces {@code Iterable}s that randomly generate some set of values with a specified
* distribution. A {@code RandomProvider} is deterministic, but not immutable: its state changes every time a random
* value is generated. It may be reverted to its original state with {@link RandomProvider#reset}.
*
* <p>{@code RandomProvider} uses the cryptographically-secure ISAAC pseudorandom number generator, implemented in
* {@link mho.wheels.random.IsaacPRNG}. The source of its randomness is a {@code int[]} seed. It contains two scale
* parameters which some of the distributions depend on; the exact relationship between the parameters and the
* distributions is specified in the distribution's documentation.
*
* <p>To create an instance which shares a generator with {@code this}, use {@link RandomProvider#copy()}. To create
* an instance which copies the generator, use {@link RandomProvider#deepCopy()}.
*
* <p>Note that sometimes the documentation will say things like "returns an {@code Iterable} containing all
* {@code String}s". This cannot strictly be true, since {@link java.util.Random} has a finite period, and will
* therefore produce only a finite number of {@code String}s. So in general, the documentation often pretends that the
* source of randomness is perfect (but still deterministic).
*/
public final strictfp class RandomProvider extends IterableProvider {
/**
* A list of all {@code Ordering}s.
*/
private static final List<Ordering> ORDERINGS = toList(ExhaustiveProvider.INSTANCE.orderings());
/**
* A list of all {@code RoundingMode}s.
*/
private static final List<RoundingMode> ROUNDING_MODES = toList(ExhaustiveProvider.INSTANCE.roundingModes());
/**
* The default value of {@code scale}.
*/
private static final int DEFAULT_SCALE = 32;
/**
* The default value of {@code secondaryScale}.
*/
private static final int DEFAULT_SECONDARY_SCALE = 8;
/**
* Sometimes a "special element" (for example, null) is inserted into an {@code Iterable} with some probability.
* That probability is 1/{@code SPECIAL_ELEMENT_RATIO}.
*/
private static final int SPECIAL_ELEMENT_RATIO = 50;
/**
* A list of numbers which determines exactly which values will be deterministically output over the life of
* {@code this}. It must have length {@link mho.wheels.random.IsaacPRNG#SIZE}.
*/
private final @NotNull List<Integer> seed;
/**
* A pseudorandom number generator. It changes state every time a random number is generated.
*/
private @NotNull IsaacPRNG prng;
/**
* A parameter that determines the size of some of the generated objects.
*/
private int scale = DEFAULT_SCALE;
/**
* Another parameter that determines the size of some of the generated objects.
*/
private int secondaryScale = DEFAULT_SECONDARY_SCALE;
/**
* Constructs a {@code RandomProvider} with a seed generated from the current system time.
*
* <ul>
* <li>(conjecture) Any {@code RandomProvider} with default {@code scale} and {@code secondaryScale} may be
* constructed with this constructor.</li>
* </ul>
*/
public RandomProvider() {
prng = new IsaacPRNG();
seed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
seed.add(prng.nextInt());
}
prng = new IsaacPRNG(seed);
}
/**
* Constructs a {@code RandomProvider} with a given seed.
*
* <ul>
* <li>{@code seed} must have length {@link mho.wheels.random.IsaacPRNG#SIZE}.</li>
* <li>Any {@code RandomProvider} with default {@code scale} and {@code secondaryScale} may be constructed with
* this constructor.</li>
* </ul>
*
* @param seed the source of randomness
*/
public RandomProvider(@NotNull List<Integer> seed) {
if (seed.size() != IsaacPRNG.SIZE) {
throw new IllegalArgumentException("seed must have length mho.wheels.random.IsaacPRNG#SIZE, which is " +
IsaacPRNG.SIZE + ". Length of invalid seed: " + seed.size());
}
this.seed = seed;
prng = new IsaacPRNG(seed);
}
/**
* A {@code RandomProvider} used for testing. This allows for deterministic testing without manually setting up a
* lengthy seed each time.
*/
public static @NotNull RandomProvider example() {
IsaacPRNG prng = IsaacPRNG.example();
List<Integer> seed = new ArrayList<>();
for (int i = 0; i < IsaacPRNG.SIZE; i++) {
seed.add(prng.nextInt());
}
return new RandomProvider(seed);
}
/**
* Returns {@code this}'s scale parameter.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return the scale parameter of {@code this}
*/
public int getScale() {
return scale;
}
/**
* Returns {@code this}'s other scale parameter.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return the other scale parameter of {@code this}
*/
public int getSecondaryScale() {
return secondaryScale;
}
/**
* Returns {@code this}'s seed. Makes a defensive copy.
*
* <ul>
* <li>The result is an array of {@link mho.wheels.random.IsaacPRNG#SIZE} {@code int}s.</li>
* </ul>
*
* @return the seed of {@code this}
*/
public @NotNull List<Integer> getSeed() {
return toList(seed);
}
/**
* A {@code RandomProvider} with the same fields as {@code this}. The copy shares {@code prng} with the original.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return A copy of {@code this}.
*/
public @NotNull RandomProvider copy() {
RandomProvider copy = new RandomProvider(seed);
copy.scale = scale;
copy.secondaryScale = secondaryScale;
copy.prng = prng;
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this}. The copy receives a new copy of {@code prng},
* so generating values from the copy will not affect the state of the original's {@code prng}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return A copy of {@code this}.
*/
public @NotNull RandomProvider deepCopy() {
RandomProvider copy = new RandomProvider(seed);
copy.scale = scale;
copy.secondaryScale = secondaryScale;
copy.prng = prng.copy();
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this} except for a new scale.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code scale} may be any {@code int}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param scale the new scale
* @return A copy of {@code this} with a new scale
*/
@Override
public @NotNull RandomProvider withScale(int scale) {
RandomProvider copy = copy();
copy.scale = scale;
return copy;
}
/**
* A {@code RandomProvider} with the same fields as {@code this} except for a new secondary scale.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code secondaryScale} mat be any {@code int}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @param secondaryScale the new secondary scale
* @return A copy of {@code this} with a new secondary scale
*/
@Override
public @NotNull RandomProvider withSecondaryScale(int secondaryScale) {
RandomProvider copy = copy();
copy.secondaryScale = secondaryScale;
return copy;
}
/**
* Put the {@code prng} back in its original state. Creating a {@code RandomProvider}, generating some values,
* resetting, and generating the same types of values again will result in the same values.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*/
@Override
public void reset() {
prng = new IsaacPRNG(seed);
}
/**
* Returns an id which has a good chance of being different in two instances with unequal {@code prng}s. It's used
* in {@link RandomProvider#toString()} to distinguish between different {@code RandomProvider} instances.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code this} may be any {@code long}.</li>
* </ul>
*/
public long getId() {
return prng.getId();
}
/**
* Returns a randomly-generated {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code int}.</li>
* </ul>
*
* @return an {@code int}
*/
public int nextInt() {
return prng.nextInt();
}
/**
* An {@code Iterable} that generates all {@code Integer}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> integers() {
return fromSupplier(this::nextInt);
}
/**
* Returns a randomly-generated {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be any {@code long}.</li>
* </ul>
*
* @return a {@code long}
*/
public long nextLong() {
int a = nextInt();
int b = nextInt();
return (long) a << 32 | b & 0xffffffffL;
}
/**
* An {@code Iterable} that generates all {@code Long}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> longs() {
return fromSupplier(this::nextLong);
}
/**
* Returns a randomly-generated {@code boolean} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @return a {@code boolean}
*/
public boolean nextBoolean() {
return (nextInt() & 1) != 0;
}
/**
* An {@code Iterator} that generates both {@code Boolean}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Boolean> booleans() {
return fromSupplier(this::nextBoolean);
}
private int nextIntPow2(int bits) {
return nextInt() & ((1 << bits) - 1);
}
private @NotNull Iterable<Integer> intsPow2(int bits) {
int mask = (1 << bits) - 1;
return map(i -> i & mask, integers());
}
private long nextLongPow2(int bits) {
return nextLong() & ((1L << bits) - 1);
}
private @NotNull Iterable<Long> longsPow2(int bits) {
long mask = (1L << bits) - 1;
return map(l -> l & mask, longs());
}
private @NotNull BigInteger nextBigIntegerPow2(int bits) {
byte[] bytes = new byte[bits / 8 + 1];
int x = 0;
for (int i = 0; i < bytes.length; i++) {
if (i % 4 == 0) {
x = nextInt();
}
bytes[i] = (byte) x;
x >>= 8;
}
bytes[0] &= (1 << (bits % 8)) - 1;
return new BigInteger(bytes);
}
private @NotNull Iterable<BigInteger> bigIntegersPow2(int bits) {
return fromSupplier(() -> this.nextBigIntegerPow2(bits));
}
private int nextIntBounded(int n) {
int i;
do {
i = nextIntPow2(MathUtils.ceilingLog2(n));
} while (i >= n);
return i;
}
private @NotNull Iterable<Integer> integersBounded(int n) {
return filter(i -> i < n, intsPow2(MathUtils.ceilingLog2(n)));
}
private long nextLongBounded(long n) {
long l;
do {
l = nextLongPow2(MathUtils.ceilingLog2(n));
} while (l >= n);
return l;
}
private @NotNull Iterable<Long> longsBounded(long n) {
return filter(l -> l < n, longsPow2(MathUtils.ceilingLog2(n)));
}
private @NotNull BigInteger nextBigIntegerBounded(@NotNull BigInteger n) {
int maxBits = MathUtils.ceilingLog2(n);
BigInteger i;
do {
i = nextBigIntegerPow2(maxBits);
} while (ge(i, n));
return i;
}
private @NotNull Iterable<BigInteger> bigIntegersBounded(@NotNull BigInteger n) {
return filter(i -> lt(i, n), bigIntegersPow2(MathUtils.ceilingLog2(n)));
}
/**
* Returns a randomly-generated value taken from a given list.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code xs} cannot be empty.</li>
* <li>The result may be any value of type {@code T}, or null.</li>
* </ul>
*
* @param xs the source list
* @param <T> the type of {@code xs}'s elements
* @return a value from {@code xs}
*/
public @Nullable <T> T nextUniformSample(@NotNull List<T> xs) {
return xs.get(nextFromRange(0, xs.size() - 1));
}
/**
* An {@code Iterable} that uniformly generates elements from a (possibly null-containing) list.
*
* <ul>
* <li>{@code xs} cannot be null.</li>
* <li>The result is non-removable and either empty or infinite.</li>
* </ul>
*
* Length is 0 if {@code xs} is empty, infinite otherwise
*
* @param xs the source list
* @param <T> the type of {@code xs}'s elements
* @return uniformly-distributed elements of {@code xs}
*/
@Override
public @NotNull <T> Iterable<T> uniformSample(@NotNull List<T> xs) {
return map(xs::get, range(0, xs.size() - 1));
}
/**
* Returns a randomly-generated character taken from a given {@code String}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code s} cannot be empty.</li>
* <li>The result may be any {@code char}.</li>
* </ul>
*
* @param s the source {@code String}
* @return a {@code char} from {@code s}
*/
public char nextUniformSample(@NotNull String s) {
return s.charAt(nextFromRange(0, s.length() - 1));
}
/**
* An {@code Iterable} that uniformly generates {@code Character}s from a {@code String}.
*
* <ul>
* <li>{@code xs} cannot be null.</li>
* <li>The result is an empty or infinite non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is 0 if {@code s} is empty, infinite otherwise
*
* @param s the source {@code String}
* @return uniformly-distributed {@code Character}s from {@code s}
*/
@Override
public @NotNull Iterable<Character> uniformSample(@NotNull String s) {
return map(s::charAt, range(0, s.length() - 1));
}
/**
* Returns a randomly-generated {@code Ordering} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return an {@code Ordering}
*/
public @NotNull Ordering nextOrdering() {
//noinspection ConstantConditions
return nextUniformSample(ORDERINGS);
}
/**
* An {@code Iterator} that generates all {@code Ordering}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Ordering> orderings() {
return uniformSample(ORDERINGS);
}
/**
* Returns a randomly-generated {@code RoundingMode} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not null.</li>
* </ul>
*
* @return a {@code RoundingMode}
*/
public @NotNull RoundingMode nextRoundingMode() {
//noinspection ConstantConditions
return nextUniformSample(ROUNDING_MODES);
}
/**
* An {@code Iterable} that generates all {@code RoundingMode}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<RoundingMode> roundingModes() {
return uniformSample(ROUNDING_MODES);
}
/**
* Returns a randomly-generated positive {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code byte}
*/
public byte nextPositiveByte() {
byte b;
do {
b = nextNaturalByte();
} while (b == 0);
return b;
}
/**
* An {@code Iterable} that generates all positive {@code Byte}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> positiveBytes() {
return fromSupplier(this::nextPositiveByte);
}
/**
* Returns a randomly-generated positive {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code short}
*/
public short nextPositiveShort() {
short s;
do {
s = nextNaturalShort();
} while (s == 0);
return s;
}
/**
* An {@code Iterable} that generates all positive {@code Short}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> positiveShorts() {
return fromSupplier(this::nextPositiveShort);
}
/**
* Returns a randomly-generated positive {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code int}
*/
public int nextPositiveInt() {
int i;
do {
i = nextInt();
} while (i <= 0);
return i;
}
/**
* An {@code Iterable} that generates all positive {@code Integer}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> positiveIntegers() {
return fromSupplier(this::nextPositiveInt);
}
/**
* Returns a randomly-generated positive {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is positive.</li>
* </ul>
*
* @return a positive {@code long}
*/
public long nextPositiveLong() {
long l;
do {
l = nextLong();
} while (l <= 0);
return l;
}
/**
* An {@code Iterable} that generates all positive {@code Long}s from a uniform distribution from a uniform
* distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> positiveLongs() {
return fromSupplier(this::nextPositiveLong);
}
/**
* Returns a randomly-generated negative {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code byte}
*/
public byte nextNegativeByte() {
return (byte) ~nextNaturalByte();
}
/**
* An {@code Iterable} that generates all negative {@code Byte}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> negativeBytes() {
return fromSupplier(this::nextNegativeByte);
}
/**
* Returns a randomly-generated negative {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code short}
*/
public short nextNegativeShort() {
return (short) ~nextNaturalShort();
}
/**
* An {@code Iterable} that generates all negative {@code Short}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> negativeShorts() {
return fromSupplier(this::nextNegativeShort);
}
/**
* Returns a randomly-generated negative {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code int}
*/
public int nextNegativeInt() {
int i;
do {
i = nextInt();
} while (i >= 0);
return i;
}
/**
* An {@code Iterable} that generates all negative {@code Integer}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> negativeIntegers() {
return fromSupplier(this::nextNegativeInt);
}
/**
* Returns a randomly-generated negative {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is negative.</li>
* </ul>
*
* @return a negative {@code long}
*/
public long nextNegativeLong() {
long l;
do {
l = nextLong();
} while (l >= 0);
return l;
}
/**
* An {@code Iterable} that generates all negative {@code Long}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> negativeLongs() {
return fromSupplier(this::nextNegativeLong);
}
/**
* Returns a randomly-generated natural (non-negative) {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not negative.</li>
* </ul>
*
* @return a natural {@code byte}
*/
public byte nextNaturalByte() {
return (byte) nextIntPow2(7);
}
/**
* An {@code Iterable} that generates all natural {@code Byte}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> naturalBytes() {
return fromSupplier(this::nextNaturalByte);
}
/**
* Returns a randomly-generated natural (non-negative) {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not negative.</li>
* </ul>
*
* @return a natural {@code short}
*/
public short nextNaturalShort() {
return (short) nextIntPow2(15);
}
/**
* An {@code Iterable} that generates all natural {@code Short}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> naturalShorts() {
return fromSupplier(this::nextNaturalShort);
}
/**
* Returns a randomly-generated natural (non-negative) {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not negative.</li>
* </ul>
*
* @return a natural {@code int}
*/
public int nextNaturalInt() {
return nextIntPow2(31);
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s (including 0) from a uniform distribution.
* Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> naturalIntegers() {
return fromSupplier(this::nextNaturalInt);
}
/**
* Returns a randomly-generated natural (non-negative) {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not negative.</li>
* </ul>
*
* @return a natural {@code long}
*/
public long nextNaturalLong() {
return nextLongPow2(63);
}
/**
* An {@code Iterable} that generates all natural {@code Long}s (including 0) from a uniform distribution. Does
* not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Long> naturalLongs() {
return fromSupplier(this::nextNaturalLong);
}
/**
* Returns a randomly-generated nonzero {@code byte} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code byte}
*/
public long nextNonzeroByte() {
byte b;
do {
b = nextByte();
} while (b == 0);
return b;
}
/**
* Returns a randomly-generated nonzero {@code short} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code short}
*/
public long nextNonzeroShort() {
short s;
do {
s = nextShort();
} while (s == 0);
return s;
}
/**
* Returns a randomly-generated nonzero {@code int} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code int}
*/
public long nextNonzeroInt() {
int i;
do {
i = nextInt();
} while (i == 0);
return i;
}
/**
* Returns a randomly-generated nonzero {@code long} from a uniform distribution.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>The result is not zero.</li>
* </ul>
*
* @return a nonzero {@code long}
*/
public long nextNonzeroLong() {
long l;
do {
l = nextLong();
} while (l == 0);
return l;
}
public byte nextByte() {
return (byte) nextIntPow2(8);
}
/**
* An {@code Iterable} that generates all {@code Byte}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Byte> bytes() {
return fromSupplier(this::nextByte);
}
public short nextShort() {
return (short) nextIntPow2(16);
}
/**
* An {@code Iterable} that generates all {@code Short}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Short> shorts() {
return fromSupplier(this::nextShort);
}
public char nextAsciiChar() {
return (char) nextIntPow2(7);
}
/**
* An {@code Iterable} that generates all ASCII {@code Character}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Character> asciiCharacters() {
return fromSupplier(this::nextAsciiChar);
}
public char nextChar() {
return (char) nextIntPow2(16);
}
/**
* An {@code Iterable} that generates all {@code Character}s from a uniform distribution. Does not support
* removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Character> characters() {
return fromSupplier(this::nextChar);
}
public byte nextFromRangeUp(byte a) {
return (byte) (nextIntBounded((1 << 7) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Byte}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Byte}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Byte}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Byte> rangeUp(byte a) {
return map(i -> (byte) (i + a), integersBounded((1 << 7) - a));
}
public short nextFromRangeUp(short a) {
return (short) (nextIntBounded((1 << 15) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Short}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Short}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Short}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Short> rangeUp(short a) {
return map(i -> (short) (i + a), integersBounded((1 << 15) - a));
}
public int nextFromRangeUp(int a) {
return (int) (nextLongBounded((1L << 31) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Integer}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Integer}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Integer> rangeUp(int a) {
return map(l -> (int) (l + a), longsBounded((1L << 31) - a));
}
public long nextFromRangeUp(long a) {
BigInteger ba = BigInteger.valueOf(a);
return nextBigIntegerBounded(BigInteger.ONE.shiftLeft(63).subtract(ba)).add(ba).longValueExact();
}
/**
* An {@code Iterable} that uniformly generates {@code Long}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Long}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Long}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Long> rangeUp(long a) {
return map(
i -> i.add(BigInteger.valueOf(a)).longValueExact(),
bigIntegersBounded(BigInteger.ONE.shiftLeft(63).subtract(BigInteger.valueOf(a)))
);
}
public char nextFromRangeUp(char a) {
return (char) (nextIntBounded((1 << 16) - a) + a);
}
/**
* An {@code Iterable} that uniformly generates {@code Characters}s greater than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive lower bound of the generated elements
* @return uniformly-distributed {@code Character}s greater than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Character> rangeUp(char a) {
return map(i -> (char) (i + a), integersBounded((1 << 16) - a));
}
public byte nextFromRangeDown(byte a) {
int offset = 1 << 7;
return (byte) (nextIntBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Byte}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code byte}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Byte}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Byte}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Byte> rangeDown(byte a) {
int offset = 1 << 7;
return map(i -> (byte) (i - offset), integersBounded(a + offset + 1));
}
public short nextFromRangeDown(short a) {
int offset = 1 << 15;
return (short) (nextIntBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Short}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code short}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Short}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Short}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Short> rangeDown(short a) {
int offset = 1 << 15;
return map(i -> (short) (i - offset), integersBounded(a + offset + 1));
}
public int nextFromRangeDown(int a) {
long offset = 1L << 31;
return (int) (nextLongBounded(a + offset + 1) - offset);
}
/**
* An {@code Iterable} that uniformly generates {@code Integer}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Integer}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Integer> rangeDown(int a) {
long offset = 1L << 31;
return map(l -> (int) (l - offset), longsBounded(a + offset + 1));
}
public long nextFromRangeDown(long a) {
BigInteger offset = BigInteger.ONE.shiftLeft(63);
BigInteger ba = BigInteger.valueOf(a);
return nextBigIntegerBounded(ba.add(BigInteger.ONE).add(offset)).subtract(offset).longValueExact();
}
/**
* An {@code Iterable} that uniformly generates {@code Long}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code long}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Long}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Long}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Long> rangeDown(long a) {
BigInteger offset = BigInteger.ONE.shiftLeft(63);
return map(
i -> i.subtract(offset).longValueExact(),
bigIntegersBounded(BigInteger.valueOf(a).add(BigInteger.ONE).add(offset))
);
}
public char nextFromRangeDown(char a) {
return (char) nextIntBounded(a + 1);
}
/**
* An {@code Iterable} that uniformly generates {@code Character}s less than or equal to {@code a}.
*
* <ul>
* <li>{@code a} may be any {@code char}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Character}s.</li>
* </ul>
*
* Length is infinite
*
* @param a the inclusive upper bound of the generated elements
* @return uniformly-distributed {@code Character}s less than or equal to {@code a}
*/
@Override
public @NotNull Iterable<Character> rangeDown(char a) {
return fromSupplier(() -> nextFromRangeDown(a));
}
public byte nextFromRange(byte a, byte b) {
return (byte) (nextIntBounded((int) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Byte> range(byte a, byte b) {
if (a > b) return Collections.emptyList();
return map(i -> (byte) (i + a), integersBounded((int) b - a + 1));
}
public short nextFromRange(short a, short b) {
return (short) (nextIntBounded((int) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Short> range(short a, short b) {
if (a > b) return Collections.emptyList();
return map(i -> (short) (i + a), integersBounded((int) b - a + 1));
}
public int nextFromRange(int a, int b) {
return (int) (nextLongBounded((long) b - a + 1) + a);
}
@Override
public @NotNull Iterable<Integer> range(int a, int b) {
if (a > b) return Collections.emptyList();
return map(i -> (int) (i + a), longsBounded((long) b - a + 1));
}
public long nextFromRange(long a, long b) {
BigInteger ba = BigInteger.valueOf(a);
BigInteger bb = BigInteger.valueOf(b);
return nextBigIntegerBounded(bb.subtract(ba).add(BigInteger.ONE)).add(ba).longValueExact();
}
public @NotNull Iterable<Long> range(long a, long b) {
if (a > b) return Collections.emptyList();
return map(
i -> i.add(BigInteger.valueOf(a)).longValueExact(),
bigIntegersBounded(BigInteger.valueOf(b).subtract(BigInteger.valueOf(a)).add(BigInteger.ONE))
);
}
public @NotNull BigInteger nextFromRange(@NotNull BigInteger a, @NotNull BigInteger b) {
return nextBigIntegerBounded(b.subtract(a).add(BigInteger.ONE)).add(a);
}
@Override
public @NotNull Iterable<BigInteger> range(@NotNull BigInteger a, @NotNull BigInteger b) {
if (gt(a, b)) return Collections.emptyList();
return map(i -> i.add(a), bigIntegersBounded(b.subtract(a).add(BigInteger.ONE)));
}
public char nextFromRange(char a, char b) {
return (char) (nextIntBounded(b - a + 1) + a);
}
@Override
public @NotNull Iterable<Character> range(char a, char b) {
if (a > b) return Collections.emptyList();
return map(i -> (char) (i + a), integersBounded(b - a + 1));
}
public int nextPositiveIntGeometric() {
int i;
int j = 0;
do {
i = nextFromRange(0, scale - 1);
j++;
} while (i != 0);
return j;
}
/**
* An {@code Iterable} that generates all positive {@code Integer}s chosen from a geometric distribution with mean
* {@code scale}. The distribution is truncated at {@code Integer.MAX_VALUE}. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing positive {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> positiveIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextPositiveIntGeometric);
}
public int nextNegativeIntGeometric() {
return -nextPositiveIntGeometric();
}
@Override
public @NotNull Iterable<Integer> negativeIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNegativeIntGeometric);
}
public int nextNaturalIntGeometric() {
return withScale(scale + 1).nextPositiveIntGeometric() - 1;
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s (including 0) chosen from a geometric
* distribution with mean {@code scale}. The distribution is truncated at {@code Integer.MAX_VALUE}. Does not
* support removal.
*
* <ul>
* <li>{@code this} must have a positive scale. The scale cannot be {@code Integer.MAX_VALUE}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing natural {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> naturalIntegersGeometric() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
return map(i -> i - 1, withScale(scale + 1).positiveIntegersGeometric());
}
public int nextNonzeroIntGeometric() {
int i = nextPositiveIntGeometric();
return nextBoolean() ? i : -i;
}
@Override
public @NotNull Iterable<Integer> nonzeroIntegersGeometric() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNonzeroIntGeometric);
}
public int nextIntGeometric() {
int i = nextNaturalIntGeometric();
return nextBoolean() ? i : -i;
}
@Override
public @NotNull Iterable<Integer> integersGeometric() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
if (scale == Integer.MAX_VALUE) {
throw new IllegalStateException("this cannot have a scale of Integer.MAX_VALUE, or " + scale);
}
return fromSupplier(this::nextIntGeometric);
}
public int nextIntGeometricFromRangeUp(int a) {
int i;
do {
i = withScale(scale - a + 1).nextPositiveIntGeometric() + a - 1;
} while (i < a);
return i;
}
/**
* An {@code Iterable} that generates all natural {@code Integer}s greater than or equal to {@code a}, chosen from
* a geometric distribution with mean {@code scale}. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale greater than {@code a} and less than {@code Integer.MAX_VALUE}+a.</li>
* <li>{@code a} may be any {@code int}.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code Integer}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Integer> rangeUpGeometric(int a) {
if (scale <= a) {
throw new IllegalStateException("this must have a scale greater than a, which is " + a +
". Invalid scale: " + scale);
}
if (a < 1 && scale >= Integer.MAX_VALUE + a) {
throw new IllegalStateException("this must have a scale less than Integer.MAX_VALUE + a, which is " +
(Integer.MAX_VALUE + a));
}
return filter(j -> j >= a, map(i -> i + a - 1, withScale(scale - a + 1).positiveIntegersGeometric()));
}
public int nextIntGeometricFromRangeDown(int a) {
int i;
do {
i = a - withScale(scale - a + 1).nextPositiveIntGeometric() + 1;
} while (i > a);
return i;
}
@Override
public @NotNull Iterable<Integer> rangeDownGeometric(int a) {
if (scale >= a) {
throw new IllegalStateException("this must have a scale less than a, which is " + a + ". Invalid scale: " +
scale);
}
if (a > -1 && scale <= a - Integer.MAX_VALUE) {
throw new IllegalStateException("this must have a scale greater than a - Integer.MAX_VALUE, which is " +
(a - Integer.MAX_VALUE));
}
return filter(j -> j <= a, map(i -> a - i + 1, withScale(a - scale + 1).positiveIntegersGeometric()));
}
public @NotNull BigInteger nextPositiveBigInteger() {
int size = nextPositiveIntGeometric();
BigInteger i = nextBigIntegerPow2(size);
i = i.setBit(size - 1);
return i;
}
/**
* An {@code Iterable} that generates all positive {@code BigInteger}s. The bit size is chosen from a geometric
* distribution mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing positive {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
public @NotNull Iterable<BigInteger> positiveBigIntegers() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextPositiveBigInteger);
}
public @NotNull BigInteger nextNegativeBigInteger() {
return nextPositiveBigInteger().negate();
}
/**
* An {@code Iterable} that generates all negative {@code BigInteger}s. The bit size is chosen from a geometric
* distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing negative {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> negativeBigIntegers() {
return map(BigInteger::negate, positiveBigIntegers());
}
public @NotNull BigInteger nextNaturalBigInteger() {
int size = nextNaturalIntGeometric();
BigInteger i = nextBigIntegerPow2(size);
if (size != 0) {
i = i.setBit(size - 1);
}
return i;
}
/**
* An {@code Iterable} that generates all natural {@code BigInteger}s (including 0). The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size. Does not support removal.
*
* <ul>
* <li>{@code this} must have a positive scale.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing negative {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> naturalBigIntegers() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
return fromSupplier(this::nextNaturalBigInteger);
}
public @NotNull BigInteger nextNonzeroBigInteger() {
BigInteger i = nextPositiveBigInteger();
return nextBoolean() ? i : i.negate();
}
/**
* An {@code Iterable} that generates all nonzero {@code BigInteger}s. The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size; the sign is also chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a scale of at least 2.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing nonzero {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> nonzeroBigIntegers() {
if (scale < 2) {
throw new IllegalStateException("this must have a scale of at least 2. Invalid scale: " + scale);
}
return fromSupplier(this::nextNonzeroBigInteger);
}
public @NotNull BigInteger nextBigInteger() {
BigInteger i = nextNaturalBigInteger();
return nextBoolean() ? i : i.negate();
}
/**
* An {@code Iterable} that generates all natural {@code BigInteger}s. The bit size is chosen from a
* geometric distribution with mean {@code scale}, and then the {@code BigInteger} is chosen uniformly from all
* {@code BigInteger}s with that bit size; the sign is also chosen uniformly. Does not support removal.
*
* <ul>
* <li>{@code this} must have a positive scale.</li>
* <li>The result is an infinite, non-removable {@code Iterable} containing {@code BigInteger}s.</li>
* </ul>
*
* Length is infinite
*/
@Override
public @NotNull Iterable<BigInteger> bigIntegers() {
if (scale < 1) {
throw new IllegalStateException("this must have a positive scale. Invalid scale: " + scale);
}
return fromSupplier(this::nextBigInteger);
}
public @NotNull BigInteger nextFromRangeUp(@NotNull BigInteger a) {
int minBitLength = a.signum() == -1 ? 0 : a.bitLength();
int absBitLength = a.abs().bitLength();
int size = nextIntGeometricFromRangeUp(minBitLength);
BigInteger i;
if (size != absBitLength) {
i = nextBigIntegerPow2(size);
if (size != 0) {
boolean mostSignificantBit = i.testBit(size - 1);
if (!mostSignificantBit) {
i = i.setBit(size - 1);
if (size < absBitLength && a.signum() == -1) {
i = i.negate();
}
}
}
} else {
if (a.signum() != -1) {
i = nextBigIntegerBounded(BigInteger.ONE.shiftLeft(absBitLength).subtract(a)).add(a);
} else {
BigInteger b = BigInteger.ONE.shiftLeft(absBitLength - 1);
BigInteger x = nextBigIntegerBounded(b.add(a.negate().subtract(b)).add(BigInteger.ONE));
i = lt(x, b) ? x.add(b) : b.negate().subtract(x.subtract(b));
}
}
return i;
}
@Override
public @NotNull Iterable<BigInteger> rangeUp(@NotNull BigInteger a) {
int minBitLength = a.signum() == -1 ? 0 : a.bitLength();
if (scale <= minBitLength) {
throw new IllegalStateException("this must have a scale greater than minBitLength, which is " +
minBitLength + ". Invalid scale: " + scale);
}
if (minBitLength == 0 && scale == Integer.MAX_VALUE) {
throw new IllegalStateException("If {@code minBitLength} is 0, {@code scale} cannot be" +
" {@code Integer.MAX_VALUE}.");
}
return fromSupplier(() -> nextFromRangeUp(a));
}
public @NotNull BigInteger nextFromRangeDown(@NotNull BigInteger a) {
return nextFromRangeUp(a.negate()).negate();
}
@Override
public @NotNull Iterable<BigInteger> rangeDown(@NotNull BigInteger a) {
int minBitLength = a.signum() == 1 ? 0 : a.negate().bitLength();
if (scale <= minBitLength) {
throw new IllegalStateException("this must have a scale greater than minBitLength, which is " +
minBitLength + ". Invalid scale: " + scale);
}
if (minBitLength == 0 && scale == Integer.MAX_VALUE) {
throw new IllegalStateException("If {@code minBitLength} is 0, {@code scale} cannot be" +
" {@code Integer.MAX_VALUE}.");
}
return fromSupplier(() -> nextFromRangeDown(a));
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) positive floats from a uniform
* distribution. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> positiveOrdinaryFloats() {
return map(Math::abs, filter(
f -> Float.isFinite(f) && !Float.isNaN(f) && !f.equals(-0.0f) && !f.equals(0.0f),
floats()
));
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) negative floats from a uniform
* distribution. Negative zero is not included. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> negativeOrdinaryFloats() {
return map(f -> -f, positiveOrdinaryFloats());
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) floats from a uniform distribution.
* Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Float> ordinaryFloats() {
return filter(f -> Float.isFinite(f) && !Float.isNaN(f) && !f.equals(-0.0f), floats());
}
/**
* An {@code Iterable} that generates all {@code Float}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Float> floats() {
return () -> new Iterator<Float>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public Float next() {
float next;
boolean problematicNaN;
do {
int floatBits = generator.nextInt();
next = Float.intBitsToFloat(floatBits);
problematicNaN = Float.isNaN(next) && floatBits != 0x7fc00000;
} while (problematicNaN);
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) positive floats from a uniform
* distribution. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> positiveOrdinaryDoubles() {
return map(Math::abs, filter(
d -> Double.isFinite(d) && !Double.isNaN(d) && !d.equals(-0.0) && !d.equals(0.0),
doubles()
));
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) negative floats from a uniform
* distribution. Negative zero is not included. Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> negativeOrdinaryDoubles() {
return map(d -> -d, positiveOrdinaryDoubles());
}
/**
* An {@code Iterable} that generates all ordinary (neither NaN nor infinite) floats from a uniform distribution.
* Does not support removal.
*
* Length is infinite.
*/
@Override
public @NotNull Iterable<Double> ordinaryDoubles() {
return filter(d -> Double.isFinite(d) && !Double.isNaN(d) && !d.equals(-0.0), doubles());
}
/**
* An {@code Iterable} that generates all {@code Double}s from a uniform distribution. Does not support removal.
*
* Length is infinite
*/
@Override
public @NotNull Iterable<Double> doubles() {
return () -> new Iterator<Double>() {
private Random generator = new Random(0x6af477d9a7e54fcaL);
@Override
public boolean hasNext() {
return true;
}
@Override
public Double next() {
double next;
boolean problematicNaN;
do {
long doubleBits = generator.nextLong();
next = Double.longBitsToDouble(doubleBits);
problematicNaN = Double.isNaN(next) && doubleBits != 0x7ff8000000000000L;
} while (problematicNaN);
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<BigDecimal> positiveBigDecimals() {
return map(
p -> new BigDecimal(p.a, p.b),
pairs(negativeBigIntegers(), integersGeometric())
);
}
@Override
public @NotNull Iterable<BigDecimal> negativeBigDecimals() {
return map(
p -> new BigDecimal(p.a, p.b),
pairs(negativeBigIntegers(), integersGeometric())
);
}
@Override
public @NotNull Iterable<BigDecimal> bigDecimals() {
return map(p -> new BigDecimal(p.a, p.b), pairs(bigIntegers(), integersGeometric()));
}
public @NotNull <T> Iterable<T> addSpecialElement(@Nullable T x, @NotNull Iterable<T> xs) {
return () -> new Iterator<T>() {
private Iterator<T> xsi = xs.iterator();
private Iterator<Integer> specialSelector = integersBounded(SPECIAL_ELEMENT_RATIO).iterator();
boolean specialSelection = specialSelector.next() == 0;
@Override
public boolean hasNext() {
return specialSelection || xsi.hasNext();
}
@Override
public T next() {
boolean previousSelection = specialSelection;
specialSelection = specialSelector.next() == 0;
return previousSelection ? x : xsi.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull <T> Iterable<T> withNull(@NotNull Iterable<T> xs) {
return addSpecialElement(null, xs);
}
@Override
public @NotNull <T> Iterable<Optional<T>> optionals(@NotNull Iterable<T> xs) {
return addSpecialElement(Optional.<T>empty(), map(Optional::of, xs));
}
@Override
public @NotNull <T> Iterable<NullableOptional<T>> nullableOptionals(@NotNull Iterable<T> xs) {
return addSpecialElement(NullableOptional.<T>empty(), map(NullableOptional::of, xs));
}
@Override
public @NotNull <A, B> Iterable<Pair<A, B>> pairs(@NotNull Iterable<A> as, @NotNull Iterable<B> bs) {
return zip(as, bs);
}
@Override
public @NotNull <A, B, C> Iterable<Triple<A, B, C>> triples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs
) {
return zip3(as, bs, cs);
}
@Override
public
@NotNull <A, B, C, D> Iterable<Quadruple<A, B, C, D>> quadruples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds
) {
return zip4(as, bs, cs, ds);
}
@Override
public @NotNull <A, B, C, D, E> Iterable<Quintuple<A, B, C, D, E>> quintuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es
) {
return zip5(as, bs, cs, ds, es);
}
@Override
public @NotNull <A, B, C, D, E, F> Iterable<Sextuple<A, B, C, D, E, F>> sextuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs
) {
return zip6(as, bs, cs, ds, es, fs);
}
@Override
public @NotNull <A, B, C, D, E, F, G> Iterable<Septuple<A, B, C, D, E, F, G>> septuples(
@NotNull Iterable<A> as,
@NotNull Iterable<B> bs,
@NotNull Iterable<C> cs,
@NotNull Iterable<D> ds,
@NotNull Iterable<E> es,
@NotNull Iterable<F> fs,
@NotNull Iterable<G> gs
) {
return zip7(as, bs, cs, ds, es, fs, gs);
}
@Override
public @NotNull <T> Iterable<Pair<T, T>> pairs(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(2, xs);
return zip(xss.get(0), xss.get(1));
}
@Override
public @NotNull <T> Iterable<Triple<T, T, T>> triples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(3, xs);
return zip3(xss.get(0), xss.get(1), xss.get(2));
}
@Override
public @NotNull <T> Iterable<Quadruple<T, T, T, T>> quadruples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(4, xs);
return zip4(xss.get(0), xss.get(1), xss.get(2), xss.get(3));
}
@Override
public @NotNull <T> Iterable<Quintuple<T, T, T, T, T>> quintuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(5, xs);
return zip5(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4));
}
@Override
public @NotNull <T> Iterable<Sextuple<T, T, T, T, T, T>> sextuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(6, xs);
return zip6(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5));
}
@Override
public @NotNull <T> Iterable<Septuple<T, T, T, T, T, T, T>> septuples(@NotNull Iterable<T> xs) {
List<Iterable<T>> xss = demux(7, xs);
return zip7(xss.get(0), xss.get(1), xss.get(2), xss.get(3), xss.get(4), xss.get(5), xss.get(6));
}
@Override
public @NotNull <T> Iterable<List<T>> lists(int size, @NotNull Iterable<T> xs) {
if (size == 0) {
return repeat(Collections.emptyList());
} else {
return transpose(demux(size, xs));
}
}
@Override
public @NotNull <T> Iterable<List<T>> listsAtLeast(int minSize, @NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList());
return () -> new Iterator<List<T>>() {
private final Iterator<T> xsi = cycle(xs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
int size = sizes.next() + minSize;
List<T> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(xsi.next());
}
return list;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull <T> Iterable<List<T>> lists(@NotNull Iterable<T> xs) {
if (isEmpty(xs)) return Collections.singletonList(Collections.emptyList());
return () -> new Iterator<List<T>>() {
private final Iterator<T> xsi = cycle(xs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public List<T> next() {
int size = sizes.next();
List<T> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(xsi.next());
}
return list;
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings(int size, @NotNull Iterable<Character> cs) {
return map(IterableUtils::charsToString, transpose(demux(size, cs)));
}
@Override
public @NotNull Iterable<String> stringsAtLeast(int minSize, @NotNull Iterable<Character> cs) {
if (isEmpty(cs)) return Arrays.asList("");
return () -> new Iterator<String>() {
private final Iterator<Character> csi = cycle(cs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public String next() {
int size = sizes.next() + minSize;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(csi.next());
}
return sb.toString();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings(int size) {
return strings(size, characters());
}
@Override
public @NotNull Iterable<String> stringsAtLeast(int minSize) {
return stringsAtLeast(minSize, characters());
}
@Override
public @NotNull Iterable<String> strings(@NotNull Iterable<Character> cs) {
if (isEmpty(cs)) return Arrays.asList("");
return () -> new Iterator<String>() {
private final Iterator<Character> csi = cycle(cs).iterator();
private final Iterator<Integer> sizes = naturalIntegersGeometric().iterator();
@Override
public boolean hasNext() {
return true;
}
@Override
public String next() {
int size = sizes.next();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(csi.next());
}
return sb.toString();
}
@Override
public void remove() {
throw new UnsupportedOperationException("cannot remove from this iterator");
}
};
}
@Override
public @NotNull Iterable<String> strings() {
return strings(characters());
}
/**
* Determines whether {@code this} is equal to {@code that}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>{@code that} may be any {@code Object}.</li>
* <li>The result may be either {@code boolean}.</li>
* </ul>
*
* @param that The {@code RandomProvider} to be compared with {@code this}
* @return {@code this}={@code that}
*/
/**
* Calculates the hash code of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>(conjecture) The result may be any {@code int}.</li>
* </ul>
*
* @return {@code this}'s hash code.
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RandomProvider that = (RandomProvider) o;
return scale == that.scale && secondaryScale == that.secondaryScale &&
seed.equals(that.seed) && prng.equals(that.prng);
}
@Override
public int hashCode() {
int result = seed.hashCode();
result = 31 * result + prng.hashCode();
result = 31 * result + scale;
result = 31 * result + secondaryScale;
return result;
}
/**
* Creates a {@code String} representation of {@code this}.
*
* <ul>
* <li>{@code this} may be any {@code RandomProvider}.</li>
* <li>See tests and demos for example results.</li>
* </ul>
*
* @return a {@code String} representation of {@code this}
*/
public String toString() {
return "RandomProvider[@" + getId() + ", " + scale + ", " + secondaryScale + "]";
}
/**
* Ensures that {@code this} is valid. Must return true for any {@code RandomProvider} used outside this class.
*/
public void validate() {
prng.validate();
assertEquals(toString(), seed.size(), IsaacPRNG.SIZE);
}
}
|
package org.spoofax.interpreter.library.interpreter;
import java.io.IOException;
import org.spoofax.interpreter.ConcreteInterpreter;
import org.spoofax.interpreter.core.InterpreterErrorExit;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.core.InterpreterExit;
import org.spoofax.interpreter.core.UndefinedStrategyException;
import org.spoofax.interpreter.library.IOAgent;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.interpreter.terms.ITermPrinter;
import org.spoofax.jsglr.client.ParseException;
import org.spoofax.jsglr.shared.BadTokenException;
import org.spoofax.jsglr.shared.SGLRException;
import org.spoofax.jsglr.shared.TokenExpectedException;
import org.spoofax.terms.AbstractTermFactory;
import org.spoofax.terms.StrategoTerm;
/**
* Interpreter instance that can be tossed around as any StrategoTerm.
*
* @author Tobi Vollebregt
*/
public class SpoofaxInterpreterTerm extends StrategoTerm {
private static final long serialVersionUID = -4810841797754395882L;
private final ConcreteInterpreter interpreter;
private String lastError;
public SpoofaxInterpreterTerm(ITermFactory termFactory, IOAgent ioAgent) {
super(MUTABLE);
interpreter = new ConcreteInterpreter(termFactory);
interpreter.setIOAgent(ioAgent);
}
public void setLastError(String err) {
lastError = err;
}
public String getLastError() {
return lastError;
}
public IStrategoTerm current() {
return interpreter.current();
}
// Based on org.spoofax.interpreter.ui.SpoofaxInterpreter.
public boolean eval(String line) {
final IOAgent ioAgent = interpreter.getIOAgent();
String err = null;
setLastError(null);
try {
if(interpreter.parseAndInvoke(line))
return true;
err = "command failed";
// fall through
} catch (TokenExpectedException e) {
err = e.getMessage();
} catch (InterpreterErrorExit e) {
err = e.getMessage();
} catch (BadTokenException e) {
err = e.getMessage();
} catch (ParseException e) {
err = e.getMessage();
} catch (InterpreterExit e) {
err = e.getMessage();
} catch (UndefinedStrategyException e) {
err = e.getMessage();
} catch (SGLRException e) {
err = e.getMessage();
} catch (InterpreterException e) {
if(e.getCause() != null)
err = e.getCause().getMessage();
else
err = e.getMessage();
}
if (err != null) {
ioAgent.printError(err);
setLastError(err);
}
return false;
}
public int getSubtermCount() {
return 0;
}
public IStrategoTerm getSubterm(int index) {
throw new UnsupportedOperationException();
}
public IStrategoTerm[] getAllSubterms() {
return AbstractTermFactory.EMPTY;
}
public int getTermType() {
return BLOB;
}
public void prettyPrint(ITermPrinter pp) {
pp.print(toString());
}
public void writeAsString(Appendable output, int maxDepth)
throws IOException {
output.append(getClass().getName());
}
@Override
protected boolean doSlowMatch(IStrategoTerm second, int commonStorageType) {
return second == this;
}
@Override
protected int hashFunction() {
return System.identityHashCode(this);
}
}
|
package org.springframework.richclient.components;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.springframework.binding.form.FormModel;
import org.springframework.binding.value.ValueModel;
import org.springframework.binding.value.support.BufferedCollectionValueModel;
import org.springframework.binding.value.support.ListListModel;
import org.springframework.context.MessageSource;
import org.springframework.richclient.application.ApplicationServicesLocator;
import org.springframework.richclient.form.binding.support.AbstractBinding;
import org.springframework.richclient.image.IconSource;
import org.springframework.richclient.list.DynamicListModel;
/**
* Binding to manage a {@link ShuttleList} component.
*
* @author lstreepy
*/
public class ShuttleListBinding extends AbstractBinding {
private ShuttleList list;
private ListModel model;
private ValueModel selectedItemsHolder = null;
private ValueModel selectableItemsHolder;
private Comparator comparator;
private Class selectedItemType;
private Class concreteSelectedType;
private String formId;
/**
* Construct a binding.
*
* @param list ShuttleList to bind
* @param formModel The form model holding the bound property
* @param formPropertyPath Path to the property to bind
*/
public ShuttleListBinding(final ShuttleList list, final FormModel formModel, final String formPropertyPath) {
super(formModel, formPropertyPath, null);
this.list = list;
}
public void setComparator(Comparator comparator) {
this.comparator = comparator;
}
public void setModel(ListModel model) {
this.model = model;
}
public void setRenderer(ListCellRenderer renderer) {
list.setCellRenderer(renderer);
}
public ListCellRenderer getRenderer() {
return list.getCellRenderer();
}
public void setSelectableItemsHolder(ValueModel selectableItemsHolder) {
this.selectableItemsHolder = selectableItemsHolder;
}
public void setSelectedItemsHolder(ValueModel selectedItemsHolder) {
this.selectedItemsHolder = selectedItemsHolder;
}
public void setSelectedItemType(final Class selectedItemType) {
this.selectedItemType = selectedItemType;
}
protected Class getSelectedItemType() {
if (this.selectedItemType == null && this.selectedItemsHolder != null
&& this.selectedItemsHolder.getValue() != null) {
setSelectedItemType(this.selectedItemsHolder.getValue().getClass());
}
return this.selectedItemType;
}
protected JComponent doBindControl() {
list.setModel(createModel());
if (selectedItemsHolder != null) {
setSelectedValue(null);
list.addListSelectionListener(new ListSelectedValueMediator());
}
if (comparator != null) {
list.setComparator(comparator);
}
// Get the icon to use for the edit button
list.setEditIcon(getEditIcon(), getEditIconText());
list.setListLabels(getChosenLabel(), getSourceLabel());
return list;
}
private String getSourceLabel() {
return getMsgText("shuttleList.sourceList.label", null);
}
private String getChosenLabel() {
return getMsgText("shuttleList.chosenList.label", null);
}
/**
* Look for Edit Text by searching the ApplicationServices for:
* formId.shuttleList.editText if nothing try shuttleList.editText
*
* @return string
*/
private String getEditIconText() {
return getMsgText("shuttleList.editText", "Edit...");
}
private String getMsgText(String key, String defaultMsg) {
final MessageSource messageSource = (MessageSource) ApplicationServicesLocator.services().getService(
MessageSource.class);
String text = null;
if (getFormId() != null) {
if (getProperty() != null) {
text = messageSource.getMessage(getFormId() + "." + getProperty() + "." + key, null, null, null);
}
if (text == null) {
text = messageSource.getMessage(getFormId() + "." + key, null, null, null);
}
}
if (text == null) {
text = messageSource.getMessage(key, null, defaultMsg, null);
}
return text;
}
/**
* Using the application services, check for: formId.shuttleList.edit if not
* there shuttleList.edit
*
* @return an Icon
*/
private Icon getEditIcon() {
final IconSource iconSource = (IconSource) ApplicationServicesLocator.services().getService(IconSource.class);
// @TODO find the form Id.
Icon icon = null;
if (getFormId() != null) {
icon = iconSource.getIcon(getFormId() + ".shuttleList.edit");
}
if (icon == null) {
icon = iconSource.getIcon("shuttleList.edit");
}
return icon;
}
/**
* Determine if the selected item type can be multi-valued (is a collection
* or an array.
*
* @return boolean <code>true</code> if the <code>selectedItemType</code>
* is a Collection or an Array.
*/
protected boolean isSelectedItemAnArray() {
Class itemType = getSelectedItemType();
return itemType != null && itemType.isArray();
}
protected boolean isSelectedItemACollection() {
return getSelectedItemType() != null && Collection.class.isAssignableFrom(getSelectedItemType());
}
protected Class getConcreteSelectedType() {
if (concreteSelectedType == null) {
if (isSelectedItemACollection()) {
concreteSelectedType = BufferedCollectionValueModel.getConcreteCollectionType(getSelectedItemType());
}
else if (isSelectedItemAnArray()) {
concreteSelectedType = getSelectedItemType().getComponentType();
}
}
return concreteSelectedType;
}
protected void setSelectedValue(final PropertyChangeListener silentValueChangeHandler) {
final int[] indices = indicesOf(selectedItemsHolder.getValue());
if (indices.length < 1) {
list.clearSelection();
}
else {
list.setSelectedIndices(indices);
// The selection may now be different than what is reflected in
// collection property if this is SINGLE_INTERVAL_SELECTION, so
// modify if needed...
updateSelectionHolderFromList(silentValueChangeHandler);
}
}
/**
* Return an array of indices in the selectableItems for each element in the
* provided set. The set can be either a Collection or an Array.
*
* @param itemSet Either an array or a Collection of items
* @return array of indices of the elements in itemSet within the
* selectableItems
*/
protected int[] indicesOf(final Object itemSet) {
int[] ret = null;
if (itemSet instanceof Collection) {
Collection collection = (Collection) itemSet;
ret = new int[collection.size()];
int i = 0;
for (Iterator iter = collection.iterator(); iter.hasNext(); i++) {
ret[i] = indexOf(iter.next());
}
}
else if (itemSet == null) {
ret = new int[0];
}
else if (itemSet.getClass().isArray()) {
Object[] items = (Object[]) itemSet;
ret = new int[items.length];
for (int i = 0; i < items.length; i++) {
ret[i] = indexOf(items[i]);
}
}
else {
throw new IllegalArgumentException("itemSet must be eithe an Array or a Collection");
}
return ret;
}
protected int indexOf(final Object o) {
final ListModel listModel = list.getModel();
final int size = listModel.getSize();
for (int i = 0; i < size; i++) {
if (equalByComparator(o, listModel.getElementAt(i))) {
return i;
}
}
return -1;
}
private ListModel createModel() {
if (model != null)
return model;
ListListModel model;
if (selectableItemsHolder != null) {
model = new DynamicListModel(selectableItemsHolder);
}
else {
model = new ListListModel();
}
model.setComparator(comparator);
model.sort();
return model;
}
protected void updateSelectionHolderFromList(final PropertyChangeListener silentValueChangeHandler) {
final Object[] selected = list.getSelectedValues();
if (isSelectedItemACollection()) {
try {
// In order to properly handle buffered forms, we will
// create a new collection to hold the new selection.
final Collection newSelection = (Collection) getConcreteSelectedType().newInstance();
if (selected != null && selected.length > 0) {
for (int i = 0; i < selected.length; i++) {
newSelection.add(selected[i]);
}
}
// Only modify the selectedItemsHolder if the selection is
// actually changed.
final Collection oldSelection = (Collection) selectedItemsHolder.getValue();
if (oldSelection == null || oldSelection.size() != newSelection.size()
|| !collectionsEqual(oldSelection, newSelection)) {
if (silentValueChangeHandler != null) {
selectedItemsHolder.setValueSilently(newSelection, silentValueChangeHandler);
}
else {
selectedItemsHolder.setValue(newSelection);
}
}
}
catch (InstantiationException e1) {
throw new RuntimeException("Unable to instantiate new concrete collection class for new selection.", e1);
}
catch (IllegalAccessException e1) {
throw new RuntimeException(e1);
}
}
else if (isSelectedItemAnArray()) {
final Object[] newSelection = (Object[]) Array.newInstance(getConcreteSelectedType(), selected.length);
for (int i = 0; i < selected.length; i++) {
newSelection[i] = selected[i];
}
// Only modify the selectedItemsHolder if the selection is actually
// changed.
final Object[] oldSelection = (Object[]) selectedItemsHolder.getValue();
if (oldSelection == null || oldSelection.length != newSelection.length
|| !arraysEqual(oldSelection, newSelection)) {
if (silentValueChangeHandler != null) {
selectedItemsHolder.setValueSilently(newSelection, silentValueChangeHandler);
}
else {
selectedItemsHolder.setValue(newSelection);
}
}
}
}
/**
* Compare two arrays for equality using the configured comparator.
*
* @param a1 First array to compare
* @param a2 Second array to compare
* @return boolean true if they are equal
*/
protected boolean arraysEqual(Object[] a1, Object[] a2) {
if (a1 != null && a2 != null && a1.length == a2.length) {
// Loop over each element and compare them using our comparator
for (int i = 0; i < a1.length; i++) {
if (!equalByComparator(a1[i], a2[i])) {
return false;
}
}
return true;
}
else if (a1 == null && a2 == null) {
return true;
}
return false;
}
/**
* Compare two collections for equality using the configured comparator.
* Element order must be the same for the collections to compare equal.
*
* @param a1 First collection to compare
* @param a2 Second collection to compare
* @return boolean true if they are equal
*/
protected boolean collectionsEqual(Collection a1, Collection a2) {
if (a1 != null && a2 != null && a1.size() == a2.size()) {
// Loop over each element and compare them using our comparator
Iterator iterA1 = a1.iterator();
Iterator iterA2 = a2.iterator();
while (iterA1.hasNext()) {
if (!equalByComparator(iterA1.next(), iterA2.next())) {
return false;
}
}
}
else if (a1 == null && a2 == null) {
return true;
}
return false;
}
/**
* Using the configured comparator (or equals if not configured), determine
* if two objects are equal.
*
* @param o1 Object to compare
* @param o2 Object to compare
* @return boolean true if objects are equal
*/
private boolean equalByComparator(Object o1, Object o2) {
return comparator == null ? o1.equals(o2) : comparator.compare(o1, o2) == 0;
}
protected void readOnlyChanged() {
list.setEnabled(isEnabled() && !isReadOnly());
}
protected void enabledChanged() {
list.setEnabled(isEnabled() && !isReadOnly());
}
/**
* @return Returns the formId.
*/
protected String getFormId() {
return formId;
}
/**
* @param formId The formId to set.
*/
protected void setFormId(String formId) {
this.formId = formId;
}
/**
* Inner class to mediate the list selection events into calls to
* {@link #updateSelectionHolderFromList}.
*/
private class ListSelectedValueMediator implements ListSelectionListener {
private final PropertyChangeListener valueChangeHandler;
public ListSelectedValueMediator() {
valueChangeHandler = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
setSelectedValue(valueChangeHandler);
}
};
selectedItemsHolder.addValueChangeListener(valueChangeHandler);
}
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
updateSelectionHolderFromList(valueChangeHandler);
}
}
}
}
|
package fitnesse.testsystems.slim.tables;
import java.util.*;
import fitnesse.testsystems.ExecutionResult;
import fitnesse.testsystems.TestResult;
import fitnesse.testsystems.slim.SlimTestContext;
import fitnesse.testsystems.slim.Table;
import fitnesse.testsystems.slim.results.SlimExceptionResult;
import fitnesse.testsystems.slim.results.SlimTestResult;
public class QueryTable extends SlimTable {
private static final String COMMENT_COLUMN_MARKER = "
protected List<String> fieldNames = new ArrayList<String>();
public QueryTable(Table table, String id, SlimTestContext testContext) {
super(table, id, testContext);
}
protected String getTableType() {
return "queryTable";
}
public boolean matches(String actual, String expected) {
if (actual == null || expected == null)
return false;
if (actual.equals(replaceSymbols(expected)))
return true;
Comparator c = new Comparator(actual, expected);
return c.matches();
}
public SlimTestResult matchMessage(String actual, String expected) {
if (actual == null)
return SlimTestResult.fail("NULL");
if (actual.equals(replaceSymbols(expected)))
return SlimTestResult.pass(replaceSymbolsWithFullExpansion(expected));
Comparator c = new Comparator(actual, expected);
return c.evaluate();
}
@Override
public List<SlimAssertion> getAssertions() throws SyntaxError {
if (table.getRowCount() < 2)
throw new SyntaxError("Query tables must have at least two rows.");
assignColumns();
SlimAssertion make = constructFixture(getFixtureName());
SlimAssertion ti = makeAssertion(callFunction(getTableName(), "table", tableAsList()),
new SilentReturnExpectation(0, 0));
SlimAssertion qi = makeAssertion(callFunction(getTableName(), "query"),
new QueryTableExpectation());
return Arrays.asList(make, ti, qi);
}
private void assignColumns() {
int cols = table.getColumnCountInRow(1);
for (int col = 0; col < cols; col++)
fieldNames.add(table.getCellContents(col, 1));
}
public class QueryTableExpectation implements SlimExpectation {
@Override
public TestResult evaluateExpectation(Object queryReturn) {
SlimTestResult testResult;
if (queryReturn == null) {
testResult = SlimTestResult.testNotRun();
} else if (queryReturn instanceof List) {
testResult = new SlimTestResult(scanRowsForMatches((List<List<List<Object>>>) queryReturn));
testResult.setVariables(getSymbolsToStore());
} else {
testResult = SlimTestResult.error(String.format("The query method returned: %s", queryReturn));
table.updateContent(0, 0, testResult);
getTestContext().increment(testResult.getExecutionResult());
}
return testResult;
}
@Override
public SlimExceptionResult evaluateException(SlimExceptionResult exceptionResult) {
table.updateContent(0, 0, exceptionResult);
getTestContext().incrementErroredTestsCount();
return exceptionResult;
}
}
private ExecutionResult scanRowsForMatches(List<List<List<Object>>> queryResultList) {
final QueryResults queryResults = new QueryResults(queryResultList);
Collection<MatchedResult> potentialMatches = queryResults.scorePotentialMatches();
List<MatchedResult> potentialMatchesByScore = new ArrayList<MatchedResult>(potentialMatches);
Collections.sort(potentialMatchesByScore, MatchedResult.compareByScore());
return markRows(queryResults, potentialMatchesByScore);
}
protected ExecutionResult markRows(QueryResults queryResults, Iterable<MatchedResult> potentialMatchesByScore) {
List<Integer> unmatchedTableRows = unmatchedRows(table.getRowCount());
unmatchedTableRows.remove(Integer.valueOf(0));
unmatchedTableRows.remove(Integer.valueOf(1));
List<Integer> unmatchedResultRows = unmatchedRows(queryResults.getRows().size());
while (!isEmpty(potentialMatchesByScore)) {
MatchedResult bestMatch = takeBestMatch(potentialMatchesByScore);
markFieldsInMatchedRow(bestMatch.tableRow, bestMatch.resultRow, queryResults);
unmatchedTableRows.remove(bestMatch.tableRow);
unmatchedResultRows.remove(bestMatch.resultRow);
}
markMissingRows(unmatchedTableRows);
markSurplusRows(queryResults, unmatchedResultRows);
return unmatchedTableRows.size() > 0 || unmatchedResultRows.size() > 0 ? ExecutionResult.FAIL : ExecutionResult.PASS;
}
protected MatchedResult takeBestMatch(Iterable<MatchedResult> potentialMatchesByScore) {
MatchedResult bestResult = potentialMatchesByScore.iterator().next();
removeOtherwiseMatchedResults(potentialMatchesByScore, bestResult);
return bestResult;
}
protected boolean isEmpty(Iterable<MatchedResult> iterable) {
return !iterable.iterator().hasNext();
}
protected void removeOtherwiseMatchedResults(Iterable<MatchedResult> potentialMatchesByScore, MatchedResult bestResult) {
Iterator<MatchedResult> iterator = potentialMatchesByScore.iterator();
while (iterator.hasNext()) {
MatchedResult otherResult = iterator.next();
if (otherResult.tableRow.equals(bestResult.tableRow) || otherResult.resultRow.equals(bestResult.resultRow))
iterator.remove();
}
}
protected List<Integer> unmatchedRows(int rowCount) {
List<Integer> result = new ArrayList<Integer>(rowCount);
for (int i = 0; i < rowCount; i++) {
result.add(i);
}
return result;
}
protected void markMissingRows(List<Integer> missingRows) {
for (int missingRow : missingRows) {
markMissingRow(missingRow);
}
}
protected void markMissingRow(int missingRow) {
replaceAllvariablesInRow(missingRow);
SlimTestResult testResult = SlimTestResult.fail(null, table.getCellContents(0, missingRow), "missing");
table.updateContent(0, missingRow, testResult);
getTestContext().increment(testResult.getExecutionResult());
}
protected void markSurplusRows(final QueryResults queryResults, List<Integer> unmatchedRows) {
for (int unmatchedRow : unmatchedRows) {
List<String> surplusRow = queryResults.getList(fieldNames, unmatchedRow);
int newTableRow = table.addRow(surplusRow);
SlimTestResult testResult = SlimTestResult.fail(surplusRow.get(0), null, "surplus");
table.updateContent(0, newTableRow, testResult);
getTestContext().increment(ExecutionResult.FAIL);
markMissingFields(surplusRow, newTableRow);
}
}
private void markMissingFields(List<String> surplusRow, int newTableRow) {
for (int col = 0; col < surplusRow.size(); col++) {
String surplusField = surplusRow.get(col);
if (surplusField == null) {
String fieldName = fieldNames.get(col);
SlimTestResult testResult = SlimTestResult.fail(String.format("field %s not present", fieldName));
table.updateContent(col, newTableRow, testResult);
getTestContext().increment(testResult.getExecutionResult());
}
}
}
protected void replaceAllvariablesInRow(int tableRow) {
int columns = table.getColumnCountInRow(tableRow);
for (int col = 0; col < columns; col++) {
String contents = table.getCellContents(col, tableRow);
table.substitute(col, tableRow, replaceSymbolsWithFullExpansion(contents));
}
}
protected void markFieldsInMatchedRow(int tableRow, int matchedRow, QueryResults queryResults) {
int columns = table.getColumnCountInRow(tableRow);
for (int col = 0; col < columns; col++) {
markField(tableRow, matchedRow, col, queryResults);
}
}
protected TestResult markField(int tableRow, int matchedRow, int col, QueryResults queryResults) {
if (col >= fieldNames.size())
return null; // ignore strange table geometry.
String fieldName = fieldNames.get(col);
String actualValue = queryResults.getCell(fieldName, matchedRow);
String expectedValue = table.getCellContents(col, tableRow);
SlimTestResult testResult;
if (fieldName.startsWith(COMMENT_COLUMN_MARKER))
testResult = SlimTestResult.plain();
else if (actualValue == null)
testResult = SlimTestResult.fail(String.format("field %s not present", fieldName), expectedValue);
else if (expectedValue == null || expectedValue.length() == 0)
testResult = SlimTestResult.ignore(actualValue);
else {
String symbolName = ifSymbolAssignment(expectedValue);
if (symbolName != null) {
setSymbol(symbolName, actualValue, true);
testResult = SlimTestResult.ignore(String.format("$%s<-[%s]", symbolName, actualValue));
} else {
testResult = matchMessage(actualValue, expectedValue);
if (testResult == null)
testResult = SlimTestResult.fail(actualValue, replaceSymbolsWithFullExpansion(expectedValue));
else if (testResult.getExecutionResult() == ExecutionResult.PASS)
testResult = markMatch(tableRow, matchedRow, col, testResult.getMessage());
}
}
table.updateContent(col, tableRow, testResult);
getTestContext().increment(testResult.getExecutionResult());
return testResult;
}
protected SlimTestResult markMatch(int tableRow, int matchedRow, int col, String message) {
return SlimTestResult.pass(message);
}
protected class QueryResults {
private List<QueryResultRow> rows = new ArrayList<QueryResultRow>();
public QueryResults(List<List<List<Object>>> queryResultTable) {
for (int i = 0; i < queryResultTable.size(); i++) {
rows.add(new QueryResultRow(i, queryResultTable.get(i)));
}
rows = Collections.unmodifiableList(rows);
}
public Collection<MatchedResult> scorePotentialMatches() {
Collection<MatchedResult> result = new ArrayList<MatchedResult>();
int rows = table.getRowCount();
for (int tableRow = 2; tableRow < rows; tableRow++)
result.addAll(new QueryMatcher(fieldNames).scoreMatches(tableRow));
return result;
}
public List<String> getList(List<String> fieldNames, int row) {
List<String> result = new ArrayList<String>();
for (String name : fieldNames)
result.add(rows.get(row).get(name));
return result;
}
public String getCell(String name, int row) {
return rows.get(row).get(name);
}
public List<QueryResultRow> getRows() {
return rows;
}
private class QueryMatcher {
private final List<String> fields;
private QueryMatcher(List<String> fields) {
this.fields = fields;
}
public Collection<MatchedResult> scoreMatches(int tableRow) {
Collection<MatchedResult> result = new ArrayList<MatchedResult>();
for (QueryResultRow row : rows) {
MatchedResult match = scoreMatch(table, tableRow, row);
if (match.score > 0)
result.add(match);
}
return result;
}
private MatchedResult scoreMatch(Table table, int tableRow, QueryResultRow row) {
int score = 0;
for (int fieldIndex = 0; fieldIndex < fields.size(); fieldIndex++) {
String fieldName = fields.get(fieldIndex);
if (!fieldName.startsWith(COMMENT_COLUMN_MARKER)) {
String actualValue = row.get(fieldName);
String expectedValue = table.getCellContents(fieldIndex, tableRow);
if (matches(actualValue, expectedValue)) {
score++;
}
}
}
return new MatchedResult(tableRow, row.index, score);
}
}
private class QueryResultRow {
private final int index;
private final Map<String, String> values;
public QueryResultRow(int index, List<List<Object>> values) {
this.index = index;
Map<String, String> rowMap = new HashMap<String, String>();
for (List<Object> columnPair : values) {
String fieldName = (String) columnPair.get(0);
String fieldValue = (String) columnPair.get(1);
rowMap.put(fieldName, fieldValue);
}
this.values = rowMap;
}
public String get(String fieldName) {
return values.get(fieldName);
}
}
}
protected static class MatchedResult {
final Integer tableRow;
final Integer resultRow;
final int score;
public MatchedResult(int tableRow, int resultRow, int score) {
this.tableRow = tableRow;
this.resultRow = resultRow;
this.score = score;
}
public static java.util.Comparator<MatchedResult> compareByScore() {
return new java.util.Comparator<MatchedResult>() {
@Override
public int compare(MatchedResult o1, MatchedResult o2) {
return o2.score - o1.score;
}
};
}
}
}
|
package net.gleamynode.apiviz;
import static net.gleamynode.apiviz.Constant.*;
import static net.gleamynode.apiviz.EdgeType.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.Doc;
import com.sun.javadoc.FieldDoc;
import com.sun.javadoc.MethodDoc;
import com.sun.javadoc.PackageDoc;
import com.sun.javadoc.Parameter;
import com.sun.javadoc.RootDoc;
import com.sun.javadoc.SeeTag;
import com.sun.javadoc.Tag;
public class ClassDocGraph {
private final RootDoc root;
private final Map<String, ClassDoc> nodes = new TreeMap<String, ClassDoc>();
private final Map<ClassDoc, Set<Edge>> edges = new HashMap<ClassDoc, Set<Edge>>();
private final Map<ClassDoc, Set<Edge>> reversedEdges = new HashMap<ClassDoc, Set<Edge>>();
public ClassDocGraph(RootDoc root) {
this.root = root;
root.printNotice("Building graph for all classes...");
for (ClassDoc node: root.classes()) {
addNode(node, true);
}
}
private void addNode(ClassDoc node, boolean addRelatedClasses) {
String key = node.qualifiedName();
if (!nodes.containsKey(key)) {
nodes.put(key, node);
edges.put(node, new TreeSet<Edge>());
}
if (addRelatedClasses) {
addRelatedClasses(node);
}
}
private void addRelatedClasses(ClassDoc type) {
// Generalization
ClassDoc superType = type.superclass();
if (superType != null &&
!superType.qualifiedName().equals("java.lang.Object") &&
!superType.qualifiedName().equals("java.lang.Annotation") &&
!superType.qualifiedName().equals("java.lang.Enum")) {
addNode(superType, false);
addEdge(new Edge(GENERALIZATION, type, superType));
}
// Realization
for (ClassDoc i: type.interfaces()) {
if (i.qualifiedName().equals("java.lang.annotation.Annotation")) {
continue;
}
addNode(i, false);
addEdge(new Edge(REALIZATION, type, i));
}
// Apply custom doclet tags first.
for (Tag t: type.tags()) {
if (t.name().equals(TAG_USES)) {
addEdge(new Edge(root, DEPENDENCY, type, t.text()));
} else if (t.name().equals(TAG_HAS)) {
addEdge(new Edge(root, NAVIGABILITY, type, t.text()));
} else if (t.name().equals(TAG_OWNS)) {
addEdge(new Edge(root, AGGREGATION, type, t.text()));
} else if (t.name().equals(TAG_COMPOSED_OF)) {
addEdge(new Edge(root, COMPOSITION, type, t.text()));
}
}
// Add an edge with '<<see also>>' label for the classes with @see
// tags, but avoid duplication.
for (SeeTag t: type.seeTags()) {
try {
if (t.referencedClass() == null) {
continue;
}
} catch (Exception e) {
continue;
}
String a = type.qualifiedName();
String b = t.referencedClass().qualifiedName();
addNode(t.referencedClass(), false);
if (a.compareTo(b) != 0) {
if (a.compareTo(b) < 0) {
addEdge(new Edge(
root, SEE_ALSO, type,
b + " - - «see also»"));
} else {
addEdge(new Edge(
root, SEE_ALSO, t.referencedClass(),
a + " - - «see also»"));
}
}
}
}
private void addEdge(Edge edge) {
edges.get(edge.getSource()).add(edge);
Set<Edge> reversedEdgeSubset = reversedEdges.get(edge.getTarget());
if (reversedEdgeSubset == null) {
reversedEdgeSubset = new TreeSet<Edge>();
reversedEdges.put((ClassDoc) edge.getTarget(), reversedEdgeSubset);
}
reversedEdgeSubset.add(edge);
}
public String getOverviewSummaryDiagram() {
Map<String, PackageDoc> packages = new TreeMap<String, PackageDoc>();
Set<Edge> edgesToRender = new TreeSet<Edge>();
addPackageDependencies(packages, edgesToRender);
// Replace direct dependencies with transitive dependencies
// if possible to simplify the diagram.
//// Build the matrix first.
Map<Doc, Set<Doc>> dependencies = new HashMap<Doc, Set<Doc>>();
for (Edge edge: edgesToRender) {
Set<Doc> nextDependencies = dependencies.get(edge.getSource());
if (nextDependencies == null) {
nextDependencies = new HashSet<Doc>();
dependencies.put(edge.getSource(), nextDependencies);
}
nextDependencies.add(edge.getTarget());
}
//// Remove the edges which doesn't change the effective relationship
//// which can be calculated by indirect (transitive) dependency resolution.
for (int i = edgesToRender.size(); i > 0 ; i
for (Edge edge: edgesToRender) {
if (isIndirectlyReachable(dependencies, edge.getSource(), edge.getTarget())) {
edgesToRender.remove(edge);
Set<Doc> targets = dependencies.get(edge.getSource());
if (targets != null) {
targets.remove(edge.getTarget());
}
break;
}
}
}
// Get the least common prefix to compact the diagram even further.
int minPackageNameLen = Integer.MAX_VALUE;
int maxPackageNameLen = Integer.MIN_VALUE;
for (String pname: packages.keySet()) {
if (pname.length() > maxPackageNameLen) {
maxPackageNameLen = pname.length();
}
if (pname.length() < minPackageNameLen) {
minPackageNameLen = pname.length();
}
}
if (minPackageNameLen == 0) {
throw new IllegalStateException("Unexpected empty package name");
}
int prefixLen;
String firstPackageName = packages.keySet().iterator().next();
for (prefixLen = minPackageNameLen; prefixLen > 0; prefixLen
if (firstPackageName.charAt(prefixLen - 1) != '.') {
continue;
}
String candidatePrefix = firstPackageName.substring(0, prefixLen);
boolean found = true;
for (String pname: packages.keySet()) {
if (!pname.startsWith(candidatePrefix)) {
found = false;
break;
}
}
if (found) {
break;
}
}
StringBuilder buf = new StringBuilder(16384);
buf.append(
"digraph APIVIZ {" + NEWLINE +
"rankdir=RL;" + NEWLINE +
"ranksep=0.3;" + NEWLINE +
"nodesep=0.3;" + NEWLINE +
"mclimit=128;" + NEWLINE +
"outputorder=edgesfirst;" + NEWLINE +
"center=1;" + NEWLINE +
"remincross=true;" + NEWLINE +
"searchsize=65536;" + NEWLINE +
"edge [fontsize=10, fontname=\"" + NORMAL_FONT + "\", " +
"style=\"setlinewidth(0.6)\"]; " + NEWLINE +
"node [shape=box, fontsize=10, fontname=\"" + NORMAL_FONT + "\", " +
"width=0.1, height=0.1, style=\"setlinewidth(0.6)\"]; " + NEWLINE);
for (PackageDoc pkg: packages.values()) {
renderPackage(buf, pkg, prefixLen);
}
for (Edge edge: edgesToRender) {
renderEdge(null, buf, edge);
}
buf.append("}" + NEWLINE);
return buf.toString();
}
@SuppressWarnings("deprecation")
private void addPackageDependencies(
Map<String, PackageDoc> packages, Set<Edge> edgesToRender) {
for (ClassDoc node: nodes.values()) {
if (!node.isIncluded()) {
continue;
}
PackageDoc pkg = node.containingPackage();
packages.put(pkg.name(), pkg);
// Generate dependency nodes from known relationships.
addPackageDependency(edgesToRender, edges.get(node));
addPackageDependency(edgesToRender, reversedEdges.get(node));
// And then try all fields and parameter types.
for (FieldDoc f: node.fields()) {
if (f.type().asClassDoc() != null) {
addPackageDependency(edgesToRender, pkg, f.type().asClassDoc().containingPackage());
}
}
// And all methods.
for (MethodDoc m: node.methods()) {
if (m.returnType().asClassDoc() != null) {
addPackageDependency(edgesToRender, pkg, m.returnType().asClassDoc().containingPackage());
}
for (Parameter p: m.parameters()) {
if (p.type().asClassDoc() != null) {
addPackageDependency(edgesToRender, pkg, p.type().asClassDoc().containingPackage());
}
}
}
// This is likely to be removed in the future.. but this is the
// most precise way to figure out the dependencies in JavaDoc.
PackageDoc[] importedPackages;
try {
importedPackages = node.importedPackages();
} catch (Exception e) {
importedPackages = null;
}
if (importedPackages != null) {
for (PackageDoc p: importedPackages) {
addPackageDependency(edgesToRender, pkg, p);
}
}
ClassDoc[] importedClasses;
try {
importedClasses = node.importedClasses();
} catch (Exception e) {
importedClasses = null;
}
if (importedClasses != null) {
for (ClassDoc c: importedClasses) {
addPackageDependency(edgesToRender, pkg, c.containingPackage());
}
}
}
}
private static void addPackageDependency(
Set<Edge> edgesToRender, Set<Edge> candidates) {
if (candidates == null) {
return;
}
for (Edge edge: candidates) {
if (edge.getType() == SEE_ALSO) {
continue;
}
PackageDoc source = ((ClassDoc) edge.getSource()).containingPackage();
PackageDoc target = ((ClassDoc) edge.getTarget()).containingPackage();
addPackageDependency(edgesToRender, source, target);
}
}
private static void addPackageDependency(
Set<Edge> edgesToRender, PackageDoc source, PackageDoc target) {
if (source != target && source.isIncluded() && target.isIncluded()) {
edgesToRender.add(
new Edge(EdgeType.DEPENDENCY, source, target));
}
}
private static boolean isIndirectlyReachable(Map<Doc, Set<Doc>> dependencyGraph, Doc source, Doc target) {
Set<Doc> intermediaryTargets = dependencyGraph.get(source);
if (intermediaryTargets == null || intermediaryTargets.isEmpty()) {
return false;
}
Set<Doc> visited = new HashSet<Doc>();
visited.add(source);
for (Doc t: intermediaryTargets) {
if (t == target) {
continue;
}
if (isIndirectlyReachable(dependencyGraph, t, target, visited)) {
return true;
}
}
return false;
}
private static boolean isIndirectlyReachable(Map<Doc, Set<Doc>> dependencyGraph, Doc source, Doc target, Set<Doc> visited) {
if (visited.contains(source)) {
// Evade cyclic dependency.
return false;
}
visited.add(source);
Set<Doc> intermediaryTargets = dependencyGraph.get(source);
if (intermediaryTargets == null || intermediaryTargets.isEmpty()) {
return false;
}
for (Doc t: intermediaryTargets) {
if (t == target) {
return true;
}
if (isIndirectlyReachable(dependencyGraph, t, target, visited)) {
return true;
}
}
return false;
}
public String getPackageSummaryDiagram(PackageDoc pkg) {
StringBuilder buf = new StringBuilder(16384);
buf.append(
"digraph APIVIZ {" + NEWLINE +
"rankdir=RL;" + NEWLINE +
"ranksep=0.3;" + NEWLINE +
"nodesep=0.3;" + NEWLINE +
"mclimit=1024;" + NEWLINE +
"outputorder=edgesfirst;" + NEWLINE +
"center=1;" + NEWLINE +
"remincross=true;" + NEWLINE +
"searchsize=65536;" + NEWLINE +
"edge [fontsize=10, fontname=\"" + NORMAL_FONT + "\", " +
"style=\"setlinewidth(0.6)\"]; " + NEWLINE +
"node [shape=box, fontsize=10, fontname=\"" + NORMAL_FONT + "\", " +
"width=0.1, height=0.1, style=\"setlinewidth(0.6)\"]; " + NEWLINE);
Map<String, ClassDoc> nodesToRender = new TreeMap<String, ClassDoc>();
Set<Edge> edgesToRender = new TreeSet<Edge>();
for (ClassDoc node: nodes.values()) {
fetchSubgraph(pkg, node, nodesToRender, edgesToRender, true, false, true);
}
renderSubgraph(pkg, null, buf, nodesToRender, edgesToRender);
buf.append("}" + NEWLINE);
return buf.toString();
}
private void fetchSubgraph(
PackageDoc pkg, ClassDoc cls,
Map<String, ClassDoc> nodesToRender, Set<Edge> edgesToRender,
boolean useHidden, boolean useSee, boolean forceInherit) {
if (useHidden && cls.tags(TAG_HIDDEN).length > 0) {
return;
}
for (Tag t: pkg.tags(TAG_EXCLUDE)) {
if (Pattern.compile(t.text().trim()).matcher(cls.qualifiedName()).find()) {
return;
}
}
if (cls.containingPackage() == pkg) {
Set<Edge> directEdges = edges.get(cls);
nodesToRender.put(cls.qualifiedName(), cls);
for (Edge edge: directEdges) {
if (!useSee && edge.getType() == SEE_ALSO) {
continue;
}
ClassDoc source = (ClassDoc) edge.getSource();
ClassDoc target = (ClassDoc) edge.getTarget();
boolean excluded = false;
if (forceInherit || cls.tags(TAG_INHERIT).length > 0) {
for (Tag t: pkg.tags(TAG_EXCLUDE)) {
Pattern p = Pattern.compile(t.text().trim());
if (p.matcher(source.qualifiedName()).find()) {
excluded = true;
break;
}
if (p.matcher(target.qualifiedName()).find()) {
excluded = true;
break;
}
}
if (excluded) {
continue;
}
}
for (Tag t: cls.tags(TAG_EXCLUDE)) {
Pattern p = Pattern.compile(t.text().trim());
if (p.matcher(source.qualifiedName()).find()) {
excluded = true;
break;
}
if (p.matcher(target.qualifiedName()).find()) {
excluded = true;
break;
}
}
if (excluded) {
continue;
}
edgesToRender.add(edge);
nodesToRender.put(source.qualifiedName(), source);
nodesToRender.put(target.qualifiedName(), target);
}
Set<Edge> reversedDirectEdges = reversedEdges.get(cls);
if (reversedDirectEdges != null) {
for (Edge edge: reversedDirectEdges) {
if (!useSee && edge.getType() == SEE_ALSO) {
continue;
}
ClassDoc source = (ClassDoc) edge.getSource();
ClassDoc target = (ClassDoc) edge.getTarget();
boolean excluded = false;
if (forceInherit || cls.tags(TAG_INHERIT).length > 0) {
for (Tag t: pkg.tags(TAG_EXCLUDE)) {
Pattern p = Pattern.compile(t.text().trim());
if (p.matcher(source.qualifiedName()).find()) {
excluded = true;
break;
}
if (p.matcher(target.qualifiedName()).find()) {
excluded = true;
break;
}
}
if (excluded) {
continue;
}
}
for (Tag t: cls.tags(TAG_EXCLUDE)) {
Pattern p = Pattern.compile(t.text().trim());
if (p.matcher(source.qualifiedName()).find()) {
excluded = true;
break;
}
if (p.matcher(target.qualifiedName()).find()) {
excluded = true;
break;
}
}
if (excluded) {
continue;
}
edgesToRender.add(edge);
nodesToRender.put(source.qualifiedName(), source);
nodesToRender.put(target.qualifiedName(), target);
}
}
}
}
public String getClassDiagram(ClassDoc cls) {
PackageDoc pkg = cls.containingPackage();
StringBuilder buf = new StringBuilder(16384);
buf.append(
"digraph APIVIZ {" + NEWLINE +
"rankdir=BT;" + NEWLINE +
"ranksep=0.3;" + NEWLINE +
"nodesep=0.3;" + NEWLINE +
"mclimit=128;" + NEWLINE +
"outputorder=edgesfirst;" + NEWLINE +
"center=1;" + NEWLINE +
"remincross=true;" + NEWLINE +
"searchsize=65536;" + NEWLINE +
"edge [fontsize=10, fontname=\"" + NORMAL_FONT + "\", " +
"style=\"setlinewidth(0.6)\"]; " + NEWLINE +
"node [shape=box, fontsize=10, fontname=\"" + NORMAL_FONT + "\", " +
"width=0.1, height=0.1, style=\"setlinewidth(0.6)\"]; " + NEWLINE);
Map<String, ClassDoc> nodesToRender = new TreeMap<String, ClassDoc>();
Set<Edge> edgesToRender = new TreeSet<Edge>();
fetchSubgraph(pkg, cls, nodesToRender, edgesToRender, false, true, false);
renderSubgraph(pkg, cls, buf, nodesToRender, edgesToRender);
buf.append("}" + NEWLINE);
return buf.toString();
}
private static void renderSubgraph(PackageDoc pkg, ClassDoc cls,
StringBuilder buf, Map<String, ClassDoc> nodesToRender,
Set<Edge> edgesToRender) {
for (ClassDoc node: nodesToRender.values()) {
renderClass(pkg, cls, buf, node);
}
for (Edge edge: edgesToRender) {
renderEdge(pkg, buf, edge);
}
}
private static void renderPackage(
StringBuilder buf, PackageDoc pkg, int prefixLen) {
String href = pkg.name().replace('.', '/') + "/package-summary.html";
buf.append(getNodeId(pkg));
buf.append(" [label=\"");
buf.append(pkg.name().substring(prefixLen));
buf.append("\", style=\"filled");
if (pkg.tags("@deprecated").length > 0) {
buf.append(",dotted");
}
buf.append("\", fillcolor=\"");
buf.append(getFillColor(pkg));
buf.append("\", href=\"");
buf.append(href);
buf.append("\"];");
buf.append(NEWLINE);
}
private static void renderClass(PackageDoc pkg, ClassDoc cls, StringBuilder buf, ClassDoc node) {
String stereotype = getStereotype(node);
String fillColor = getFillColor(pkg, cls, node);
String lineColor = getLineColor(pkg, node);
String fontColor = getFontColor(pkg, node);
String href = getPath(pkg, node);
buf.append(getNodeId(node));
buf.append(" [label=\"");
if (stereotype != null) {
buf.append("«");
buf.append(stereotype);
buf.append("»\\n");
}
buf.append(getNodeLabel(pkg, node));
buf.append("\"");
if (node.isAbstract() && !node.isInterface()) {
buf.append(", fontname=\"");
buf.append(ITALIC_FONT);
buf.append("\"");
}
buf.append(", style=\"filled");
if (node.tags("@deprecated").length > 0) {
buf.append(",dotted");
}
buf.append("\", color=\"");
buf.append(lineColor);
buf.append("\", fontcolor=\"");
buf.append(fontColor);
buf.append("\", fillcolor=\"");
buf.append(fillColor);
if (href != null) {
buf.append("\", href=\"");
buf.append(href);
}
buf.append("\"];");
buf.append(NEWLINE);
}
private static void renderEdge(PackageDoc pkg, StringBuilder buf, Edge edge) {
EdgeType type = edge.getType();
String lineColor = getLineColor(pkg, edge);
String fontColor = getFontColor(pkg, edge);
buf.append(getNodeId(edge.getSource()));
buf.append(" -> ");
buf.append(getNodeId(edge.getTarget()));
buf.append(" [arrowhead=\"");
buf.append(type.getArrowHead() == null? (edge.isOneway()? "open" : "none") : type.getArrowHead());
buf.append("\", arrowtail=\"");
buf.append(type.getArrowTail());
buf.append("\", style=\"" + type.getStyle());
buf.append("\", color=\"");
buf.append(lineColor);
buf.append("\", fontcolor=\"");
buf.append(fontColor);
buf.append("\", label=\"");
buf.append(edge.getEdgeLabel());
buf.append("\", headlabel=\"");
buf.append(edge.getTargetLabel());
buf.append("\", taillabel=\"");
buf.append(edge.getSourceLabel());
buf.append("\" ];");
buf.append(NEWLINE);
}
private static String getStereotype(ClassDoc node) {
String stereotype = node.isInterface()? "interface" : null;
if (node.isException()) {
stereotype = "exception";
} else if (node.isAnnotationType()) {
stereotype = "annotation";
} else if (node.isEnum()) {
stereotype = "enum";
} else {
boolean staticType = true;
int methods = 0;
for (MethodDoc m: node.methods()) {
if (m.isConstructor()) {
continue;
}
methods ++;
if (!m.isStatic()) {
staticType = false;
break;
}
}
if (staticType && methods > 0) {
stereotype = "static";
}
}
if (node.tags(TAG_STEREOTYPE).length > 0) {
stereotype = node.tags(TAG_STEREOTYPE)[0].text();
}
return stereotype;
}
private static String getFillColor(PackageDoc pkg) {
String color = "white";
if (pkg.tags(TAG_LANDMARK).length > 0) {
color = "khaki1";
}
return color;
}
private static String getFillColor(PackageDoc pkg, ClassDoc cls, ClassDoc node) {
String color = "white";
if (cls == null) {
if (node.containingPackage() == pkg && node.tags(TAG_LANDMARK).length > 0) {
color = "khaki1";
}
} else if (cls == node) {
color = "khaki1";
}
return color;
}
private static String getLineColor(PackageDoc pkg, ClassDoc doc) {
String color = "black";
if (!(doc.containingPackage() == pkg)) {
color = "gray";
}
return color;
}
private static String getLineColor(PackageDoc pkg, Edge edge) {
if (edge.getTarget() instanceof ClassDoc) {
return getLineColor(pkg, (ClassDoc) edge.getTarget());
} else {
return "black";
}
}
private static String getFontColor(PackageDoc pkg, ClassDoc doc) {
String color = "black";
if (!(doc.containingPackage() == pkg)) {
color = "gray30";
}
return color;
}
private static String getFontColor(PackageDoc pkg, Edge edge) {
if (edge.getTarget() instanceof ClassDoc) {
return getFontColor(pkg, (ClassDoc) edge.getTarget());
} else {
return "black";
}
}
private static String getNodeId(Doc node) {
String name;
if (node instanceof ClassDoc) {
name = ((ClassDoc) node).qualifiedName();
} else {
name = node.name();
}
return name.replace('.', '_');
}
private static String getNodeLabel(PackageDoc pkg, ClassDoc node) {
if (node.containingPackage() == pkg) {
return node.name();
}
String name = node.qualifiedName();
int dotIndex = name.lastIndexOf('.');
if (dotIndex < 0) {
return name;
} else {
return name.substring(dotIndex + 1) + "\\n(" +
name.substring(0, dotIndex) + ')';
}
}
private static String getPath(PackageDoc pkg, ClassDoc node) {
if (!node.isIncluded()) {
return null;
}
String sourcePath = pkg.name().replace('.', '/');
String targetPath = node.qualifiedName().replace('.', '/') + ".html";
String[] sourcePathElements = sourcePath.split("[\\/\\\\]+");
String[] targetPathElements = targetPath.split("[\\/\\\\]+");
int maxCommonLength = Math.min(sourcePathElements.length, targetPathElements.length);
int commonLength;
for (commonLength = 0; commonLength < maxCommonLength; commonLength ++) {
if (!sourcePathElements[commonLength].equals(targetPathElements[commonLength])) {
break;
}
}
StringBuilder buf = new StringBuilder();
for (int i = 0; i < sourcePathElements.length - commonLength; i ++) {
buf.append("/..");
}
for (int i = commonLength; i < targetPathElements.length; i ++) {
buf.append('/');
buf.append(targetPathElements[i]);
}
return buf.substring(1);
}
}
|
package org.opendaylight.bgpcep.pcep.topology.provider;
import static java.util.Objects.requireNonNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.netty.util.concurrent.FutureListener;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.checkerframework.checker.lock.qual.GuardedBy;
import org.checkerframework.checker.lock.qual.Holding;
import org.opendaylight.bgpcep.pcep.topology.provider.session.stats.SessionStateImpl;
import org.opendaylight.bgpcep.pcep.topology.provider.session.stats.TopologySessionStats;
import org.opendaylight.mdsal.binding.api.WriteTransaction;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.protocol.pcep.PCEPCloseTermination;
import org.opendaylight.protocol.pcep.PCEPSession;
import org.opendaylight.protocol.pcep.PCEPTerminationReason;
import org.opendaylight.protocol.pcep.TerminationReason;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev181109.LspObject;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev181109.Path1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev181109.lsp.object.Lsp;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Message;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.MessageHeader;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Object;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.ProtocolVersion;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.LspId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.Node1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.Node1Builder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.OperationResult;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.PccSyncState;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.TearDownSessionInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.lsp.metadata.Metadata;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.pcep.client.attributes.PathComputationClient;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.pcep.client.attributes.PathComputationClientBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.pcep.client.attributes.path.computation.client.ReportedLsp;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.pcep.client.attributes.path.computation.client.ReportedLspBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.pcep.client.attributes.path.computation.client.ReportedLspKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev200120.pcep.client.attributes.path.computation.client.reported.lsp.Path;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.common.Uint8;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class for PCEP topology providers. It handles the common tasks involved in managing a PCEP server (PCE)
* endpoint, and exposing a network topology based on it. It needs to be subclassed to form a fully functional block,
* where the subclass provides handling of incoming messages.
*
* @param <S> identifier type of requests
* @param <L> identifier type for LSPs
*/
public abstract class AbstractTopologySessionListener<S, L> implements TopologySessionListener, TopologySessionStats {
static final MessageHeader MESSAGE_HEADER = new MessageHeader() {
private final ProtocolVersion version = new ProtocolVersion(Uint8.ONE);
@Override
public Class<MessageHeader> implementedInterface() {
return MessageHeader.class;
}
@Override
public ProtocolVersion getVersion() {
return this.version;
}
};
static final String MISSING_XML_TAG = "Mandatory XML tags are missing.";
private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologySessionListener.class);
@GuardedBy("this")
final Map<L, String> lsps = new HashMap<>();
@GuardedBy("this")
final SessionStateImpl listenerState;
@GuardedBy("this")
private final Map<S, PCEPRequest> requests = new HashMap<>();
@GuardedBy("this")
private final Map<String, ReportedLsp> lspData = new HashMap<>();
private final ServerSessionManager serverSessionManager;
private InstanceIdentifier<PathComputationClient> pccIdentifier;
@GuardedBy("this")
private TopologyNodeState nodeState;
private final AtomicBoolean synced = new AtomicBoolean(false);
@GuardedBy("this")
private PCEPSession session;
@GuardedBy("this")
private SyncOptimization syncOptimization;
@GuardedBy("this")
private boolean triggeredResyncInProcess;
AbstractTopologySessionListener(final ServerSessionManager serverSessionManager) {
this.serverSessionManager = requireNonNull(serverSessionManager);
this.listenerState = new SessionStateImpl(this);
}
@Override
public final synchronized void onSessionUp(final PCEPSession psession) {
/*
* The session went up. Look up the router in Inventory model,
* create it if it is not there (marking that fact for later
* deletion), and mark it as synchronizing. Also create it in
* the topology model, with empty LSP list.
*/
final InetAddress peerAddress = psession.getRemoteAddress();
this.syncOptimization = new SyncOptimization(psession);
final TopologyNodeState state = this.serverSessionManager.takeNodeState(peerAddress,
this, isLspDbRetreived());
// takeNodeState(..) may fail when the server session manager is being restarted due to configuration change
if (state == null) {
LOG.error("Unable to fetch topology node state for PCEP session. Closing session {}", psession);
psession.close(TerminationReason.UNKNOWN);
this.onSessionTerminated(psession, new PCEPCloseTermination(TerminationReason.UNKNOWN));
return;
}
if (this.session != null || this.nodeState != null) {
LOG.error("PCEP session is already up with {}. Closing session {}", psession.getRemoteAddress(), psession);
psession.close(TerminationReason.UNKNOWN);
this.onSessionTerminated(psession, new PCEPCloseTermination(TerminationReason.UNKNOWN));
return;
}
this.session = psession;
this.nodeState = state;
LOG.trace("Peer {} resolved to topology node {}", peerAddress, state.getNodeId());
// Our augmentation in the topology node
final PathComputationClientBuilder pccBuilder = new PathComputationClientBuilder();
onSessionUp(psession, pccBuilder);
this.synced.set(isSynchronized());
pccBuilder.setIpAddress(IetfInetUtil.INSTANCE.ipAddressNoZoneFor(peerAddress));
final InstanceIdentifier<Node1> topologyAugment = state.getNodeId().augmentation(Node1.class);
this.pccIdentifier = topologyAugment.child(PathComputationClient.class);
final Node initialNodeState = state.getInitialNodeState();
final boolean isNodePresent = isLspDbRetreived() && initialNodeState != null;
if (isNodePresent) {
loadLspData(initialNodeState, this.lspData, this.lsps, isIncrementalSynchro());
pccBuilder.setReportedLsp(initialNodeState.augmentation(Node1.class)
.getPathComputationClient().getReportedLsp());
}
state.storeNode(topologyAugment,
new Node1Builder().setPathComputationClient(pccBuilder.build()).build(), this.session);
this.listenerState.init(psession);
this.serverSessionManager.bind(this.nodeState.getNodeId(), this.listenerState);
LOG.info("Session with {} attached to topology node {}", psession.getRemoteAddress(), state.getNodeId());
}
synchronized void updatePccState(final PccSyncState pccSyncState) {
if (this.nodeState == null) {
LOG.info("Server Session Manager is closed.");
AbstractTopologySessionListener.this.session.close(TerminationReason.UNKNOWN);
return;
}
final MessageContext ctx = new MessageContext(this.nodeState.getChain().newWriteOnlyTransaction());
updatePccNode(ctx, new PathComputationClientBuilder().setStateSync(pccSyncState).build());
if (pccSyncState != PccSyncState.Synchronized) {
this.synced.set(false);
this.triggeredResyncInProcess = true;
}
// All set, commit the modifications
ctx.trans.commit().addCallback(new FutureCallback<CommitInfo>() {
@Override
public void onSuccess(final CommitInfo result) {
LOG.trace("Pcc Internal state for session {} updated successfully",
AbstractTopologySessionListener.this.session);
}
@Override
public void onFailure(final Throwable throwable) {
LOG.error("Failed to update Pcc internal state for session {}",
AbstractTopologySessionListener.this.session, throwable);
AbstractTopologySessionListener.this.session.close(TerminationReason.UNKNOWN);
}
}, MoreExecutors.directExecutor());
}
synchronized boolean isTriggeredSyncInProcess() {
return this.triggeredResyncInProcess;
}
/**
* Tear down the given PCEP session. It's OK to call this method even after the session
* is already down. It always clear up the current session status.
*/
@Holding("this")
@SuppressWarnings("checkstyle:IllegalCatch")
private synchronized void tearDown(final PCEPSession psession) {
requireNonNull(psession);
this.serverSessionManager.releaseNodeState(this.nodeState, psession, isLspDbPersisted());
clearNodeState();
try {
if (this.session != null) {
this.session.close();
}
psession.close();
} catch (final Exception e) {
LOG.error("Session {} cannot be closed.", psession, e);
}
this.session = null;
this.syncOptimization = null;
// Clear all requests we know about
for (final Entry<S, PCEPRequest> e : this.requests.entrySet()) {
final PCEPRequest r = e.getValue();
switch (r.getState()) {
case DONE:
// Done is done, nothing to do
LOG.trace("Request {} was done when session went down.", e.getKey());
break;
case UNACKED:
// Peer has not acked: results in failure
LOG.info("Request {} was incomplete when session went down, failing the instruction", e.getKey());
r.done(OperationResults.NOACK);
break;
case UNSENT:
// Peer has not been sent to the peer: results in cancellation
LOG.debug("Request {} was not sent when session went down, cancelling the instruction", e.getKey());
r.done(OperationResults.UNSENT);
break;
default:
break;
}
}
this.requests.clear();
}
@Override
public final synchronized void onSessionDown(final PCEPSession psession, final Exception exception) {
LOG.warn("Session {} went down unexpectedly", psession, exception);
tearDown(psession);
}
@Override
public final synchronized void onSessionTerminated(final PCEPSession psession, final PCEPTerminationReason reason) {
LOG.info("Session {} terminated by peer with reason {}", psession, reason);
tearDown(psession);
}
@Override
public final synchronized void onMessage(final PCEPSession psession, final Message message) {
if (this.nodeState == null) {
LOG.warn("Topology node state is null. Unhandled message {} on session {}", message, psession);
psession.close(TerminationReason.UNKNOWN);
return;
}
final MessageContext ctx = new MessageContext(this.nodeState.getChain().newWriteOnlyTransaction());
if (onMessage(ctx, message)) {
LOG.warn("Unhandled message {} on session {}", message, psession);
//cancel not supported, submit empty transaction
ctx.trans.commit().addCallback(new FutureCallback<CommitInfo>() {
@Override
public void onSuccess(final CommitInfo result) {
LOG.trace("Successful commit");
}
@Override
public void onFailure(final Throwable trw) {
LOG.error("Failed commit", trw);
}
}, MoreExecutors.directExecutor());
return;
}
ctx.trans.commit().addCallback(new FutureCallback<CommitInfo>() {
@Override
public void onSuccess(final CommitInfo result) {
LOG.trace("Internal state for session {} updated successfully", psession);
ctx.notifyRequests();
}
@Override
public void onFailure(final Throwable throwable) {
LOG.error("Failed to update internal state for session {}, closing it", psession, throwable);
ctx.notifyRequests();
psession.close(TerminationReason.UNKNOWN);
}
}, MoreExecutors.directExecutor());
}
@Override
public synchronized void close() {
clearNodeState();
if (this.session != null) {
LOG.info("Closing session {}", session);
this.session.close(TerminationReason.UNKNOWN);
}
}
private synchronized void clearNodeState() {
if (this.nodeState != null) {
this.serverSessionManager.unbind(this.nodeState.getNodeId());
this.nodeState = null;
}
}
final synchronized PCEPRequest removeRequest(final S id) {
final PCEPRequest ret = this.requests.remove(id);
if (ret != null) {
this.listenerState.processRequestStats(ret.getElapsedMillis());
}
LOG.trace("Removed request {} object {}", id, ret);
return ret;
}
final synchronized ListenableFuture<OperationResult> sendMessage(final Message message, final S requestId,
final Metadata metadata) {
final io.netty.util.concurrent.Future<Void> f = this.session.sendMessage(message);
this.listenerState.updateStatefulSentMsg(message);
final PCEPRequest req = new PCEPRequest(metadata);
this.requests.put(requestId, req);
final short rpcTimeout = this.serverSessionManager.getRpcTimeout();
LOG.trace("RPC response timeout value is {} seconds", rpcTimeout);
if (rpcTimeout > 0) {
setupTimeoutHandler(requestId, req, rpcTimeout);
}
f.addListener((FutureListener<Void>) future -> {
if (!future.isSuccess()) {
synchronized (AbstractTopologySessionListener.this) {
AbstractTopologySessionListener.this.requests.remove(requestId);
}
req.done(OperationResults.UNSENT);
LOG.info("Failed to send request {}, instruction cancelled", requestId, future.cause());
} else {
req.sent();
LOG.trace("Request {} sent to peer (object {})", requestId, req);
}
});
return req.getFuture();
}
private void setupTimeoutHandler(final S requestId, final PCEPRequest req, final short timeout) {
final Timer timer = req.getTimer();
timer.schedule(new TimerTask() {
@Override
public void run() {
synchronized (AbstractTopologySessionListener.this) {
AbstractTopologySessionListener.this.requests.remove(requestId);
}
req.done();
LOG.info("Request {} timed-out waiting for response", requestId);
}
}, TimeUnit.SECONDS.toMillis(timeout));
LOG.trace("Set up response timeout handler for request {}", requestId);
}
/**
* Update an LSP in the data store.
*
* @param ctx Message context
* @param id Revision-specific LSP identifier
* @param lspName LSP name
* @param rlb Reported LSP builder
* @param solicited True if the update was solicited
* @param remove True if this is an LSP path removal
*/
protected final synchronized void updateLsp(final MessageContext ctx, final L id, final String lspName,
final ReportedLspBuilder rlb, final boolean solicited, final boolean remove) {
final String name;
if (lspName == null) {
name = this.lsps.get(id);
if (name == null) {
LOG.error("PLSPID {} seen for the first time, not reporting the LSP", id);
return;
}
} else {
name = lspName;
}
LOG.debug("Saved LSP {} with name {}", id, name);
this.lsps.put(id, name);
final ReportedLsp previous = this.lspData.get(name);
// if no previous report about the lsp exist, just proceed
if (previous != null) {
final List<Path> updatedPaths = makeBeforeBreak(rlb, previous, name, remove);
// if all paths or the last path were deleted, delete whole tunnel
if (updatedPaths.isEmpty()) {
LOG.debug("All paths were removed, removing LSP with {}.", id);
removeLsp(ctx, id);
return;
}
rlb.setPath(updatedPaths);
}
rlb.withKey(new ReportedLspKey(name));
rlb.setName(name);
// If this is an unsolicited update. We need to make sure we retain the metadata already present
if (solicited) {
this.nodeState.setLspMetadata(name, rlb.getMetadata());
} else {
rlb.setMetadata(this.nodeState.getLspMetadata(name));
}
final ReportedLsp rl = rlb.build();
ctx.trans.put(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier.child(ReportedLsp.class, rlb.key()), rl);
LOG.debug("LSP {} updated to MD-SAL", name);
this.lspData.put(name, rl);
}
private static List<Path> makeBeforeBreak(final ReportedLspBuilder rlb, final ReportedLsp previous,
final String name, final boolean remove) {
// just one path should be reported
final Path path = Iterables.getOnlyElement(rlb.getPath().values());
final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId reportedLspId =
path.getLspId();
final List<Path> updatedPaths;
//lspId = 0 and remove = false -> tunnel is down, still exists but no path is signaled
//remove existing tunnel's paths now, as explicit path remove will not come
if (!remove && reportedLspId.getValue().toJava() == 0) {
updatedPaths = new ArrayList<>();
LOG.debug("Remove previous paths {} to this lsp name {}", previous.getPath(), name);
} else {
// check previous report for existing paths
final Collection<Path> prev = previous.nonnullPath().values();
updatedPaths = new ArrayList<>(prev);
LOG.debug("Found previous paths {} to this lsp name {}", updatedPaths, name);
for (final Path prevPath : prev) {
//we found reported path in previous reports
if (prevPath.getLspId().getValue().toJava() == 0 || prevPath.getLspId().equals(reportedLspId)) {
LOG.debug("Match on lsp-id {}", prevPath.getLspId().getValue());
// path that was reported previously and does have the same lsp-id, path will be updated
final boolean r = updatedPaths.remove(prevPath);
LOG.trace("Request removed? {}", r);
}
}
}
// if the path does not exist in previous report, add it to path list, it's a new ERO
// only one path will be added
//lspId is 0 means confirmation message that shouldn't be added (because we have no means of deleting it later)
LOG.trace("Adding new path {} to {}", path, updatedPaths);
updatedPaths.add(path);
if (remove) {
if (reportedLspId.getValue().toJava() == 0) {
// if lsp-id also 0, remove all paths
LOG.debug("Removing all paths.");
updatedPaths.clear();
} else {
// path is marked to be removed
LOG.debug("Removing path {} from {}", path, updatedPaths);
final boolean r = updatedPaths.remove(path);
LOG.trace("Request removed? {}", r);
}
}
LOG.debug("Setting new paths {} to lsp {}", updatedPaths, name);
return updatedPaths;
}
/**
* Indicate that the peer has completed state synchronization.
*
* @param ctx Message context
*/
protected final synchronized void stateSynchronizationAchieved(final MessageContext ctx) {
if (this.synced.getAndSet(true)) {
LOG.debug("State synchronization achieved while synchronizing, not updating state");
return;
}
if (this.triggeredResyncInProcess) {
this.triggeredResyncInProcess = false;
}
updatePccNode(ctx, new PathComputationClientBuilder().setStateSync(PccSyncState.Synchronized).build());
// The node has completed synchronization, cleanup metadata no longer reported back
this.nodeState.cleanupExcept(this.lsps.values());
LOG.debug("Session {} achieved synchronized state", this.session);
}
protected final synchronized void updatePccNode(final MessageContext ctx, final PathComputationClient pcc) {
ctx.trans.merge(LogicalDatastoreType.OPERATIONAL, this.pccIdentifier, pcc);
}
protected final InstanceIdentifier<ReportedLsp> lspIdentifier(final String name) {
return this.pccIdentifier.child(ReportedLsp.class, new ReportedLspKey(name));
}
/**
* Remove LSP from the database.
*
* @param ctx Message Context
* @param id Revision-specific LSP identifier
*/
protected final synchronized void removeLsp(final MessageContext ctx, final L id) {
final String name = this.lsps.remove(id);
LOG.debug("LSP {} removed", name);
ctx.trans.delete(LogicalDatastoreType.OPERATIONAL, lspIdentifier(name));
this.lspData.remove(name);
}
@SuppressWarnings("checkstyle:OverloadMethodsDeclarationOrder")
protected abstract void onSessionUp(PCEPSession session, PathComputationClientBuilder pccBuilder);
/**
* Perform revision-specific message processing when a message arrives.
*
* @param ctx Message processing context
* @param message Protocol message
* @return True if the message type is not handle.
*/
@SuppressWarnings("checkstyle:OverloadMethodsDeclarationOrder")
protected abstract boolean onMessage(MessageContext ctx, Message message);
final String lookupLspName(final L id) {
requireNonNull(id, "ID parameter null.");
return this.lsps.get(id);
}
/**
* Reads operational data on this node. Doesn't attempt to read the data,
* if the node does not exist. In this case returns null.
*
* @param id InstanceIdentifier of the node
* @return null if the node does not exists, or operational data
*/
final synchronized <T extends DataObject> FluentFuture<Optional<T>>
readOperationalData(final InstanceIdentifier<T> id) {
if (this.nodeState == null) {
return null;
}
return this.nodeState.readOperationalData(id);
}
protected abstract Object validateReportedLsp(Optional<ReportedLsp> rep, LspId input);
protected abstract void loadLspData(Node node, Map<String, ReportedLsp> lspData, Map<L, String> lsps,
boolean incrementalSynchro);
final boolean isLspDbPersisted() {
return this.syncOptimization != null && this.syncOptimization.isSyncAvoidanceEnabled();
}
final boolean isLspDbRetreived() {
return this.syncOptimization != null && this.syncOptimization.isDbVersionPresent();
}
/**
* Is Incremental synchronization if LSP-DB-VERSION are included,
* LSP-DB-VERSION TLV values doesnt match, and LSP-SYNC-CAPABILITY is enabled.
*/
final synchronized boolean isIncrementalSynchro() {
return this.syncOptimization != null && this.syncOptimization.isSyncAvoidanceEnabled()
&& this.syncOptimization.isDeltaSyncEnabled();
}
final synchronized boolean isTriggeredInitialSynchro() {
return this.syncOptimization != null && this.syncOptimization.isTriggeredInitSyncEnabled();
}
final synchronized boolean isTriggeredReSyncEnabled() {
return this.syncOptimization != null && this.syncOptimization.isTriggeredReSyncEnabled();
}
protected final synchronized boolean isSynchronized() {
return this.syncOptimization != null && this.syncOptimization.doesLspDbMatch();
}
@Override
public int getDelegatedLspsCount() {
final Stream<ReportedLsp> stream;
synchronized (this) {
stream = ImmutableList.copyOf(this.lspData.values()).stream();
}
return Math.toIntExact(stream
.map(ReportedLsp::getPath).filter(pathList -> pathList != null && !pathList.isEmpty())
// pick the first path, as delegate status should be same in each path
.map(pathList -> pathList.values().iterator().next())
.map(path -> path.augmentation(Path1.class)).filter(Objects::nonNull)
.map(LspObject::getLsp).filter(Objects::nonNull)
.filter(Lsp::isDelegate)
.count());
}
@Override
public boolean isSessionSynchronized() {
return this.synced.get();
}
@Override
public synchronized ListenableFuture<RpcResult<Void>> tearDownSession(final TearDownSessionInput input) {
close();
return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
}
static final class MessageContext {
private final Collection<PCEPRequest> requests = new ArrayList<>();
private final WriteTransaction trans;
private MessageContext(final WriteTransaction trans) {
this.trans = requireNonNull(trans);
}
void resolveRequest(final PCEPRequest req) {
this.requests.add(req);
}
@SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
justification = "https://github.com/spotbugs/spotbugs/issues/811")
private void notifyRequests() {
for (final PCEPRequest r : this.requests) {
r.done(OperationResults.SUCCESS);
}
}
}
}
|
package com.andyadc.scaffold.showcase.test;
import com.andyadc.scaffold.showcase.auth.entity.AuthUser;
import com.andyadc.scaffold.showcase.auth.service.AuthService;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
/**
* @author andaicheng
* @version 2017/4/24
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext.xml"})
public class AuthServiceTest {
@Autowired
private AuthService authService;
@Ignore
@Test
public void testSaveAuthUser() {
AuthUser authUser = new AuthUser();
authUser.setName("2");
authUser.setAccount("2");
authUser.setPassword("54erwdfge2");
authUser.setSalt("ssss");
authUser.setState((byte) 1);
authUser.setIsDeleted((byte) 0);
authUser.setCreateTime(new Date());
authUser = authService.saveAuthUser(authUser);
System.out.println(authUser.getId());
}
@Before
public void before() {
System.out.println("
}
@After
public void after() {
System.out.println("
}
}
|
package fr.eni.QCM.Controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.eni.QCM.BO.Proposition;
import fr.eni.QCM.BO.Question;
import fr.eni.QCM.BO.Test;
import fr.eni.QCM.BO.TypeTest;
import fr.eni.QCM.DAL.PropositionDAO;
import fr.eni.QCM.DAL.QuestionDAO;
import fr.eni.QCM.DAL.TestDAO;
import fr.eni.QCM.DAL.TypeTestDAO;
/**
* Servlet implementation class listTest
*/
@WebServlet("/Reponse")
public class PropositionController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@SuppressWarnings("unused")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
//VARIABLES
Proposition p = null;
//ADD
if(request.getParameter("addProp") != null){
String libelle = request.getParameter("libelle");
int reponse = Integer.valueOf(request.getParameter("verite"));
int idQuestion = Integer.valueOf(request.getParameter("addProp"));
try {
PropositionDAO.creerPropo(libelle, reponse, idQuestion);
} catch (SQLException e) {e.printStackTrace();}
//TODO: CHANGER PAR LE BON LIEN VERS LA QUESTION
int idSectionADD = 0;
try {
idSectionADD = QuestionDAO.getOne(idQuestion).getSection().getId();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s = "./Question?update="+idQuestion+"§ion="+idSectionADD;
request.getRequestDispatcher(s).forward(request, response);
}
//DELETE
else if(request.getParameter("delProp") != null){
System.out.println("ENTRER DANS LA PARTIE delProp");
int idProp = Integer.valueOf(request.getParameter("delProp"));
int idQuestionDEL = 0;
int idSectionDEL = 0;
try {
idQuestionDEL = PropositionDAO.getOne(idProp).getQuestion().getId();
idSectionDEL = QuestionDAO.getOne(idQuestionDEL).getSection().getId();
PropositionDAO.delPropo(idProp);
} catch (SQLException e) {e.printStackTrace();}
//TODO: CHANGER PAR LE BON LIEN VERS LA QUESTION
String s = "./Question?update="+idQuestionDEL+"§ion="+idSectionDEL;
System.out.println("LIEN DE LA REDIRECTION : "+s);
response.sendRedirect(s);
}
//UPDATE
else if(request.getParameter("updProp") != null){
System.out.println("ENTRER DANS UPDATE");
String libelle = request.getParameter("libelle");
System.out.println("Valeur de libelle");
System.out.println(libelle);
int reponse = Integer.valueOf(request.getParameter("verite"));
int idPropo = Integer.valueOf(request.getParameter("updProp"));
try {
PropositionDAO.updatePropo(libelle, reponse, idPropo);
} catch (SQLException e) {e.printStackTrace();}
//TODO: CHANGER PAR LE BON LIEN VERS LA QUESTION
int idQuestion = 0;
int idSection = 0;
try {
idQuestion = PropositionDAO.getOne(idPropo).getQuestion().getId();
idSection = QuestionDAO.getOne(idQuestion).getSection().getId();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s = "./Question?update="+idQuestion+"§ion="+idSection;
response.sendRedirect(s);
}
//TOTAL
else{
try {
Question q = QuestionDAO.getOne(Integer.valueOf(request.getParameter("idQuestion")));
request.setAttribute("question", q);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (request.getParameter("idProp") != null){
try {
request.setAttribute("proposition", PropositionDAO.getOne(Integer.valueOf(request.getParameter("idProp"))));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
request.getRequestDispatcher("/CreerReponse").forward(request, response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
|
package org.mobicents.protocols.ss7.indicator;
import org.mobicents.protocols.ss7.sccp.SccpProtocolVersion;
import javolution.xml.XMLFormat;
import javolution.xml.XMLSerializable;
import javolution.xml.stream.XMLStreamException;
/**
* The AI is the first field within Calling Party Address (CgPA) and Called Party Address (CdPA) and is one octet in length. Its
* function is to indicate which information elements are present so that the address can be interpreted in other words, it
* indicates the type of addressing information that is to be found in the address field so the receiving node knows how to
* interpret that data.
*
* @author amit bhayani
* @author kulikov
* @author sergey vetyutnev
*/
public class AddressIndicator implements XMLSerializable {
private static final String VALUE = "value";
// Global title indicator
private GlobalTitleIndicator globalTitleIndicator;
// point code indicator
private boolean pcPresent;
// ssn indicator
private boolean ssnPresent;
// routing indicator
private RoutingIndicator routingIndicator;
// reservedForNationalBit value - usually it is false
private boolean reservedForNationalUseBit;
public AddressIndicator() {
}
public AddressIndicator(boolean pcPresent, boolean ssnPresent, RoutingIndicator rti, GlobalTitleIndicator gti) {
this.pcPresent = pcPresent;
this.ssnPresent = ssnPresent;
this.routingIndicator = rti;
this.globalTitleIndicator = gti;
}
public AddressIndicator(byte v, SccpProtocolVersion sccpProtocolVersion) {
init(v, sccpProtocolVersion);
}
private void init(byte v, SccpProtocolVersion sccpProtocolVersion) {
if (sccpProtocolVersion == SccpProtocolVersion.ANSI) {
ssnPresent = (v & 0x01) == 0x01;
pcPresent = (v & 0x02) == 0x02;
int gtiCode = ((v >> 2) & 0x0f);
switch (gtiCode) {
case 1:
globalTitleIndicator = GlobalTitleIndicator.GLOBAL_TITLE_INCLUDES_TRANSLATION_TYPE_NUMBERING_PLAN_AND_ENCODING_SCHEME;
break;
case 2:
globalTitleIndicator = GlobalTitleIndicator.GLOBAL_TITLE_INCLUDES_TRANSLATION_TYPE_ONLY;
break;
default:
globalTitleIndicator = GlobalTitleIndicator.NO_GLOBAL_TITLE_INCLUDED;
break;
}
} else {
pcPresent = (v & 0x01) == 0x01;
ssnPresent = (v & 0x02) == 0x02;
globalTitleIndicator = GlobalTitleIndicator.valueOf((v >> 2) & 0x0f);
if (globalTitleIndicator == null) // making of NO_GLOBAL_TITLE_INCLUDED for an unknown value
globalTitleIndicator = GlobalTitleIndicator.NO_GLOBAL_TITLE_INCLUDED;
}
routingIndicator = ((v >> 6) & 0x01) == 0x01 ? RoutingIndicator.ROUTING_BASED_ON_DPC_AND_SSN
: RoutingIndicator.ROUTING_BASED_ON_GLOBAL_TITLE;
reservedForNationalUseBit = (v & 0x80) == 0x80;
}
public GlobalTitleIndicator getGlobalTitleIndicator() {
return globalTitleIndicator;
}
public boolean isPCPresent() {
return pcPresent;
}
public boolean isSSNPresent() {
return ssnPresent;
}
public RoutingIndicator getRoutingIndicator() {
return routingIndicator;
}
public boolean isReservedForNationalUseBit() {
return reservedForNationalUseBit;
}
public byte getValue(SccpProtocolVersion sccpProtocolVersion) {
int b = 0;
if (sccpProtocolVersion == SccpProtocolVersion.ANSI) {
if (ssnPresent) {
b |= 0x01;
}
if (pcPresent) {
b |= 0x02;
}
int gtiCode = 0;
switch (globalTitleIndicator) {
case GLOBAL_TITLE_INCLUDES_TRANSLATION_TYPE_NUMBERING_PLAN_AND_ENCODING_SCHEME:
gtiCode = 1;
break;
case GLOBAL_TITLE_INCLUDES_TRANSLATION_TYPE_ONLY:
gtiCode = 2;
break;
}
b |= (gtiCode << 2);
} else {
if (pcPresent) {
b |= 0x01;
}
if (ssnPresent) {
b |= 0x02;
}
b |= (globalTitleIndicator.getValue() << 2);
}
if (routingIndicator == RoutingIndicator.ROUTING_BASED_ON_DPC_AND_SSN) {
b |= 0x40;
}
if (sccpProtocolVersion == SccpProtocolVersion.ANSI) {
b |= 0x80;
}
return (byte) b;
}
// default XML representation.
protected static final XMLFormat<AddressIndicator> XML = new XMLFormat<AddressIndicator>(AddressIndicator.class) {
public void write(AddressIndicator ai, OutputElement xml) throws XMLStreamException {
xml.setAttribute(VALUE, ai.getValue(SccpProtocolVersion.ITU));
}
public void read(InputElement xml, AddressIndicator ai) throws XMLStreamException {
byte b = (byte) xml.getAttribute(VALUE).toInt();
ai.init(b, SccpProtocolVersion.ITU);
}
};
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((globalTitleIndicator == null) ? 0 : globalTitleIndicator.hashCode());
result = prime * result + (pcPresent ? 1231 : 1237);
result = prime * result + ((routingIndicator == null) ? 0 : routingIndicator.hashCode());
result = prime * result + (ssnPresent ? 1231 : 1237);
result = prime * result + (reservedForNationalUseBit ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AddressIndicator other = (AddressIndicator) obj;
if (globalTitleIndicator != other.globalTitleIndicator)
return false;
if (pcPresent != other.pcPresent)
return false;
if (routingIndicator != other.routingIndicator)
return false;
if (ssnPresent != other.ssnPresent)
return false;
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("AddressIndicator[");
sb.append("globalTitleIndicator=");
sb.append(globalTitleIndicator);
sb.append(", pcPresent=");
sb.append(pcPresent);
sb.append(", ssnPresent=");
sb.append(ssnPresent);
sb.append(", routingIndicator=");
sb.append(routingIndicator);
if (reservedForNationalUseBit)
sb.append(", reservedForNationalUseBit");
sb.append("]");
return sb.toString();
}
}
|
package net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.EscapingStopCharTester;
import net.openhft.chronicle.bytes.IORuntimeException;
import net.openhft.chronicle.bytes.StopCharTesters;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.pool.StringInterner;
import net.openhft.chronicle.core.values.IntValue;
import net.openhft.chronicle.core.values.LongValue;
import net.openhft.chronicle.util.BooleanConsumer;
import net.openhft.chronicle.util.ByteConsumer;
import net.openhft.chronicle.util.FloatConsumer;
import net.openhft.chronicle.util.ShortConsumer;
import java.nio.BufferUnderflowException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.Base64;
import java.util.UUID;
import java.util.function.*;
import static net.openhft.chronicle.bytes.NativeBytes.nativeBytes;
import static net.openhft.chronicle.wire.WireType.stringForCode;
public class TextWire implements Wire {
public static final String FIELD_SEP = "";
private static final String END_FIELD = "\n";
final Bytes<?> bytes;
final ValueOut valueOut = new TextValueOut();
final ValueIn valueIn = new TextValueIn();
String sep = "";
public TextWire(Bytes<?> bytes) {
this.bytes = bytes;
}
@Override
public Bytes<?> bytes() {
return bytes;
}
@Override
public WireOut addPadding(int paddingToAdd) {
for (int i = 0; i < paddingToAdd; i++)
bytes.append((bytes.position() & 63) == 0 ? '\n' : ' ');
return this;
}
@Override
public void copyTo(WireOut wire) {
throw new UnsupportedOperationException();
}
@Override
public ValueOut write() {
bytes.append(sep).append("\"\": ");
sep = "";
return valueOut;
}
@Override
public ValueOut writeValue() {
return valueOut;
}
@Override
public ValueOut write(WireKey key) {
CharSequence name = key.name();
if (name == null) name = Integer.toString(key.code());
bytes.append(sep).append(quotes(name)).append(": ");
sep = "";
return valueOut;
}
@Override
public ValueIn read() {
readField(Wires.acquireStringBuilder());
return valueIn;
}
private void consumeWhiteSpace() {
while (bytes.remaining() > 0 && Character.isWhitespace(bytes.readUnsignedByte(bytes.position())))
bytes.skip(1);
}
private StringBuilder readField(StringBuilder sb) {
consumeWhiteSpace();
try {
int ch = peekCode();
if (ch == '"') {
bytes.skip(1);
bytes.parseUTF(sb, EscapingStopCharTester.escaping(c -> c == '"'));
consumeWhiteSpace();
ch = readCode();
if (ch != ':')
throw new UnsupportedOperationException("Expected a : at " + bytes.toDebugString());
} else {
bytes.parseUTF(sb, EscapingStopCharTester.escaping(c -> c < ' ' || c == ':'));
}
unescape(sb);
} catch (BufferUnderflowException ignored) {
}
consumeWhiteSpace();
return sb;
}
@Override
public ValueIn read(WireKey key) {
long position = bytes.position();
StringBuilder sb = readField(Wires.acquireStringBuilder());
if (sb.length() == 0 || StringInterner.isEqual(sb, key.name()))
return valueIn;
bytes.position(position);
throw new UnsupportedOperationException("Unordered fields not supported yet. key=" + key.name());
}
@Override
public ValueIn read(StringBuilder name) {
consumeWhiteSpace();
readField(name);
return valueIn;
}
private int peekCode() {
if (bytes.remaining() < 1)
return -1;
long pos = bytes.position();
return bytes.readUnsignedByte(pos);
}
private int readCode() {
if (bytes.remaining() < 1)
return -1;
return bytes.readUnsignedByte();
}
@Override
public boolean hasNextSequenceItem() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasMapping() {
throw new UnsupportedOperationException();
}
@Override
public <T> T readDocument(Function<WireIn, T> reader, Consumer<WireIn> metaDataReader) {
throw new UnsupportedOperationException();
}
@Override
public void writeDocument(Runnable writer) {
writer.run();
}
@Override
public void writeMetaData(Runnable writer) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasDocument() {
throw new UnsupportedOperationException();
}
@Override
public void flip() {
bytes.flip();
}
@Override
public void clear() {
bytes.clear();
}
public String toString() {
return bytes.toString();
}
CharSequence quotes(CharSequence s) {
if (!needsQuotes(s)) {
return s;
}
StringBuilder sb2 = Wires.acquireAnotherStringBuilder(s);
sb2.append('"');
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
case '\\':
sb2.append('\\').append(ch);
break;
case '\n':
sb2.append("\\n");
break;
default:
sb2.append(ch);
break;
}
}
sb2.append('"');
return sb2;
}
boolean needsQuotes(CharSequence s) {
for (int i = 0; i < s.length(); i++)
if ("\" ,\n\\".indexOf(s.charAt(i)) >= 0)
return true;
return s.length() == 0;
}
@Override
public Wire writeComment(CharSequence s) {
bytes.append(sep).append("# ").append(s).append("\n");
sep = "";
return TextWire.this;
}
@Override
public Wire readComment(StringBuilder s) {
throw new UnsupportedOperationException();
}
private void unescape(StringBuilder sb) {
for (int i = 0; i < sb.length(); i++) {
char ch2 = sb.charAt(i);
if (ch2 == '\\') {
sb.deleteCharAt(i);
char ch3 = sb.charAt(i);
switch (ch3) {
case 'n':
sb.setCharAt(i, '\n');
break;
}
}
}
}
class TextValueOut implements ValueOut {
@Override
public Wire text(CharSequence s) {
bytes.append(sep).append(s == null ? "!!null" : quotes(s)).append(END_FIELD);
return TextWire.this;
}
@Override
public Wire type(CharSequence typeName) {
bytes.append(sep).append('!').append(typeName);
sep = " ";
return TextWire.this;
}
@Override
public WireOut uuid(UUID uuid) {
bytes.append(uuid.toString()).append('\n');
return TextWire.this;
}
@Override
public WireOut int64(LongValue readReady) {
// TODO support this better
bytes.append(readReady.getValue()).append('\n');
return TextWire.this;
}
@Override
public WireOut int32(IntValue value) {
throw new UnsupportedOperationException();
}
@Override
public WireOut sequence(Runnable writer) {
throw new UnsupportedOperationException();
}
@Override
public WireOut marshallable(Marshallable object) {
bytes.append(sep);
bytes.append("{ ");
object.writeMarshallable(TextWire.this);
bytes.append("}");
sep = "\n";
return TextWire.this;
}
@Override
public Wire bool(Boolean flag) {
bytes.append(sep).append(flag == null ? "!!null" : flag ? "true" : "false").append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire int8(byte i8) {
bytes.append(sep).append(i8).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public WireOut bytes(Bytes fromBytes) {
if (isText(fromBytes)) {
return text(fromBytes);
}
int length = Maths.toInt32(fromBytes.remaining());
byte[] byteArray = new byte[length];
fromBytes.read(byteArray);
return bytes(byteArray);
}
private boolean isText(Bytes fromBytes) {
for (long i = fromBytes.position(); i < fromBytes.readLimit(); i++) {
int ch = fromBytes.readUnsignedByte(i);
if ((ch < ' ' && ch != '\t') || ch >= 127)
return false;
}
return true;
}
@Override
public ValueOut writeLength(long remaining) {
throw new UnsupportedOperationException();
}
@Override
public WireOut bytes(byte[] byteArray) {
bytes.append(sep).append("!!binary ").append(Base64.getEncoder().encodeToString(byteArray)).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire uint8checked(int u8) {
bytes.append(sep).append(u8).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire int16(short i16) {
bytes.append(sep).append(i16).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire uint16checked(int u16) {
bytes.append(sep).append(u16).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire utf8(int codepoint) {
StringBuilder sb = Wires.acquireStringBuilder();
sb.appendCodePoint(codepoint);
text(sb);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire int32(int i32) {
bytes.append(sep).append(i32).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire uint32checked(long u32) {
bytes.append(sep).append(u32).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire float32(float f) {
bytes.append(sep).append(f).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire float64(double d) {
bytes.append(sep).append(d).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire int64(long i64) {
bytes.append(sep).append(i64).append(END_FIELD);
sep = FIELD_SEP;
return TextWire.this;
}
@Override
public Wire time(LocalTime localTime) {
bytes.append(localTime.toString()).append('\n');
return TextWire.this;
}
@Override
public Wire zonedDateTime(ZonedDateTime zonedDateTime) {
bytes.append(zonedDateTime.toString()).append('\n');
return TextWire.this;
}
@Override
public Wire date(LocalDate localDate) {
bytes.append(localDate.toString()).append('\n');
return TextWire.this;
}
}
class TextValueIn implements ValueIn {
@Override
public boolean hasNext() {
throw new UnsupportedOperationException();
}
@Override
public WireIn expectText(CharSequence s) {
throw new UnsupportedOperationException();
}
@Override
public WireIn uuid(Consumer<UUID> uuid) {
StringBuilder sb = Wires.acquireStringBuilder();
text(sb);
uuid.accept(UUID.fromString(sb.toString()));
return TextWire.this;
}
@Override
public WireIn bytes(Bytes toBytes) {
return bytes(toBytes::write);
}
public WireIn bytes(Consumer<byte[]> bytesConsumer) {
// TODO needs to be made much more efficient.
StringBuilder sb = Wires.acquireStringBuilder();
if (peekCode() == '!') {
bytes.parseUTF(sb, StopCharTesters.SPACE_STOP);
String str = sb.toString();
if (str.equals("!!binary")) {
sb.setLength(0);
bytes.parseUTF(sb, StopCharTesters.SPACE_STOP);
byte[] decode = Base64.getDecoder().decode(sb.toString());
bytesConsumer.accept(decode);
} else {
throw new IORuntimeException("Unsupported type " + str);
}
} else {
text(sb);
bytesConsumer.accept(sb.toString().getBytes());
}
return TextWire.this;
}
public byte[] bytes() {
// TODO needs to be made much more efficient.
StringBuilder sb = Wires.acquireStringBuilder();
if (peekCode() == '!') {
bytes.parseUTF(sb, StopCharTesters.SPACE_STOP);
String str = sb.toString();
if (str.equals("!!binary")) {
sb.setLength(0);
bytes.parseUTF(sb, StopCharTesters.SPACE_STOP);
byte[] decode = Base64.getDecoder().decode(sb.toString());
return decode ;
} else {
throw new IORuntimeException("Unsupported type " + str);
}
} else {
text(sb);
return sb.toString().getBytes();
}
}
@Override
public WireIn wireIn() {
return TextWire.this;
}
@Override
public long readLength() {
long start = bytes.position();
try {
consumeWhiteSpace();
int code = readCode();
switch (code) {
case '{':
int count = 1;
for (; ; ) {
byte b = bytes.readByte();
if (b == '{')
count += 1;
else if (b == '}') {
count -= 1;
if (count == 0)
return bytes.position() - start;
}
// do nothing
}
default:
// TODO needs to be made much more efficient.
bytes();
return bytes.position() - start;
}
} finally {
bytes.position(start);
}
}
@Override
public WireIn int64(LongValue value) {
throw new UnsupportedOperationException();
}
@Override
public WireIn int32(IntValue value) {
throw new UnsupportedOperationException();
}
@Override
public WireIn sequence(Consumer<ValueIn> reader) {
throw new UnsupportedOperationException();
}
@Override
public WireIn marshallable(Marshallable object) {
consumeWhiteSpace();
int code = readCode();
if (code != '{')
throw new IORuntimeException("Unsupported type " + (char) code);
object.readMarshallable(TextWire.this);
consumeWhiteSpace();
code = readCode();
if (code != '}')
throw new IORuntimeException("Unterminated { while reading marshallable " + object);
return TextWire.this;
}
@Override
public long int64() {
return bytes.parseLong();
}
@Override
public double float64() {
throw new UnsupportedOperationException("todo");
}
@Override
public float float32() {
throw new UnsupportedOperationException("todo");
}
public byte int8() {
long l = int64();
if (l > Byte.MAX_VALUE || l < Byte.MIN_VALUE)
throw new IllegalStateException("value=" + l + ", is greater or less than Byte.MAX_VALUE/MIN_VALUE");
return (byte) l;
}
public short int16() {
long l = int64();
if (l > Short.MAX_VALUE || l < Short.MIN_VALUE)
throw new IllegalStateException("value=" + l + ", is greater or less than Short.MAX_VALUE/MIN_VALUE");
return (short) l;
}
public int int32() {
long l = int64();
if (l > Integer.MAX_VALUE || l < Integer.MIN_VALUE)
throw new IllegalStateException("value=" + l + ", is greater or less than Integer.MAX_VALUE/MIN_VALUE");
return (int) l;
}
@Override
public Wire type(StringBuilder s) {
int code = readCode();
if (code != '!') {
throw new UnsupportedOperationException(stringForCode(code));
}
bytes.parseUTF(s, StopCharTesters.SPACE_STOP);
return TextWire.this;
}
@Override
public Wire text(StringBuilder s) {
int ch = peekCode();
StringBuilder sb = s;
if (ch == '{') {
sb.append(Bytes.toDebugString(bytes, bytes.position(), readLength()));
return TextWire.this;
}
if (ch == '"') {
bytes.skip(1);
bytes.parseUTF(sb, EscapingStopCharTester.escaping(c -> c == '"'));
consumeWhiteSpace();
} else {
bytes.parseUTF(sb, EscapingStopCharTester.escaping(StopCharTesters.COMMA_STOP));
}
unescape(sb);
return TextWire.this;
}
@Override
public WireIn text(Consumer<String> s) {
StringBuilder sb = Wires.acquireStringBuilder();
text(sb);
s.accept(sb.toString());
return TextWire.this;
}
@Override
public String text() {
StringBuilder sb = Wires.acquireStringBuilder();
text(sb);
return sb.toString();
}
@Override
public Wire bool(BooleanConsumer flag) {
StringBuilder sb = Wires.acquireStringBuilder();
bytes.parseUTF(sb, StopCharTesters.SPACE_STOP);
if (StringInterner.isEqual(sb, "true"))
flag.accept(true);
else if (StringInterner.isEqual(sb, "false"))
flag.accept(false);
else if (StringInterner.isEqual(sb, "!!null"))
flag.accept(null);
else
throw new UnsupportedOperationException();
return TextWire.this;
}
@Override
public boolean bool() {
StringBuilder sb = Wires.acquireStringBuilder();
bytes.parseUTF(sb, StopCharTesters.SPACE_STOP);
if (StringInterner.isEqual(sb, "true"))
return true;
else if (StringInterner.isEqual(sb, "false"))
return false;
else if (StringInterner.isEqual(sb, "!!null"))
throw new NullPointerException("value is null");
else
throw new UnsupportedOperationException();
}
@Override
public Wire int8(ByteConsumer i) {
i.accept((byte) bytes.parseLong());
return TextWire.this;
}
@Override
public Wire uint8(ShortConsumer i) {
i.accept((short) bytes.parseLong());
return TextWire.this;
}
@Override
public Wire int16(ShortConsumer i) {
i.accept((short) bytes.parseLong());
return TextWire.this;
}
@Override
public Wire uint16(IntConsumer i) {
i.accept((int) bytes.parseLong());
return TextWire.this;
}
@Override
public Wire uint32(LongConsumer i) {
i.accept(bytes.parseLong());
return TextWire.this;
}
@Override
public Wire int32(IntConsumer i) {
i.accept((int) bytes.parseLong());
return TextWire.this;
}
@Override
public Wire float32(FloatConsumer v) {
v.accept((float) bytes.parseDouble());
return TextWire.this;
}
@Override
public Wire float64(DoubleConsumer v) {
v.accept(bytes.parseDouble());
return TextWire.this;
}
@Override
public Wire int64(LongConsumer i) {
i.accept(bytes.parseLong());
return TextWire.this;
}
@Override
public Wire time(Consumer<LocalTime> localTime) {
StringBuilder sb = Wires.acquireStringBuilder();
text(sb);
localTime.accept(LocalTime.parse(sb.toString()));
return TextWire.this;
}
@Override
public Wire zonedDateTime(Consumer<ZonedDateTime> zonedDateTime) {
StringBuilder sb = Wires.acquireStringBuilder();
text(sb);
zonedDateTime.accept(ZonedDateTime.parse(sb.toString()));
return TextWire.this;
}
@Override
public Wire date(Consumer<LocalDate> localDate) {
StringBuilder sb = Wires.acquireStringBuilder();
text(sb);
localDate.accept(LocalDate.parse(sb.toString()));
return TextWire.this;
}
}
public static String asText(Wire wire) {
TextWire tw = new TextWire(nativeBytes());
wire.copyTo(tw);
tw.flip();
wire.flip();
return tw.toString();
}
}
|
package schedoscope.example.osm.mapreduce;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import ch.hsr.geohash.GeoHash;
public class GeohashMapper extends
Mapper<LongWritable, Text, NullWritable, Text> {
private int hashPrecision = 12;
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String[] rec = value.toString().split("\t");
String hash = GeoHash.geoHashStringWithCharacterPrecision(
Double.valueOf(rec[4]), Double.valueOf(rec[5]), hashPrecision);
String output = StringUtils.join(ArrayUtils.add(rec, hash), "\t");
context.write(NullWritable.get(), new Text(output));
}
}
|
package net.ucanaccess.converters;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import net.ucanaccess.converters.TypesMap.AccessType;
import net.ucanaccess.ext.FunctionType;
import net.ucanaccess.jdbc.UcanaccessSQLException;
import net.ucanaccess.jdbc.UcanaccessSQLException.ExceptionMessages;
import com.healthmarketscience.jackcess.DataType;
public class Functions {
private static Double rnd;
private static Double lastRnd;
public final static ArrayList<SimpleDateFormat> LDF = new ArrayList<SimpleDateFormat>();
public final static ArrayList<Boolean> LDFY = new ArrayList<Boolean>();
public final static RegionalSettings reg=new RegionalSettings();
private static boolean pointDateSeparator;
static {
pointDateSeparator=getPointDateSeparator();
addDateP("yyyy-MM-dd h:m:s a");
addDateP("yyyy-MM-dd H:m:s");
addDateP("yyyy-MM-dd");
addDateP("yyyy/MM/dd h:m:s a");
addDateP("yyyy/MM/dd H:m:s");
addDateP("yyyy/MM/dd");
addDateP(reg.getGeneralPattern(),true);
addDateP(reg.getLongDatePattern(),true);
addDateP(reg.getMediumDatePattern(),true);
addDateP(reg.getShortDatePattern(),true);
if(!Locale.getDefault().equals(Locale.US)){
RegionalSettings s=new RegionalSettings(Locale.US);
addDateP(s.getGeneralPattern(),false);
addDateP(s.getLongDatePattern(),true);
addDateP(s.getMediumDatePattern(),true);
addDateP(s.getShortDatePattern(),true);
}
addDateP("MMM dd,yyyy");
addDateP("MM dd,yyyy");
addDateP("MMM dd hh:mm:ss",false,true);
addDateP("MM dd hh:mm:ss",false,true);
addDateP("MMM yy hh:mm:ss");
addDateP("MM yy hh:mm:ss");
//locale is MM/dd/yyyy like in US but user is trying to parse something like 22/11/2003
addDateP("dd/MM/yyyy h:m:s a",true);
addDateP("dd/MM/yyyy H:m:s",true);
addDateP("dd/MM/yyyy",true);
}
private static boolean getPointDateSeparator(){
String[] dfsp=new String[]{reg.getGeneralPattern(),reg.getLongDatePattern(),reg.getMediumDatePattern(),reg.getShortDatePattern()};
for(String pattern:dfsp){
if(pattern.indexOf(".")>0&&pattern.indexOf("h.")<0&&pattern.indexOf("H.")<0){
return true;
}
}
return false;
}
private static void addDateP(String sdfs){
addDateP(sdfs,false,false);
}
private static void addDateP(String sdfs,boolean euristic){
addDateP(sdfs,euristic,false);
}
private static void addTogglePattern(String pattern){
if(pattern.indexOf("/")>0){
addDateP(pattern.replaceAll("/","-"));
if(pointDateSeparator){
addDateP(pattern.replaceAll("/","."));
}
}else
if(pattern.indexOf("-")>0){
addDateP(pattern.replaceAll(Pattern.quote("-"),"/"));
if(pointDateSeparator){
addDateP(pattern.replaceAll(Pattern.quote("-"),"."));
}
}else if(pattern.indexOf(".")>0&&pattern.indexOf("h.")<0&&pattern.indexOf("H.")<0){
addDateP(pattern.replaceAll(Pattern.quote("."),"/"));
}
}
private static void addDateP( String sdfs,boolean euristic,boolean yearOverride){
if(euristic){
if(sdfs.indexOf("a")<0&&sdfs.indexOf("H")>0){
String chg=sdfs.replaceAll("H","h")+" a";
addDateP(chg);
addTogglePattern(chg);
}
}
SimpleDateFormat sdf=new SimpleDateFormat(sdfs);
sdf.setLenient(false);
if("true".equalsIgnoreCase(reg.getRS())){
DateFormatSymbols df=new DateFormatSymbols();
df.setAmPmStrings(new String[]{"AM","PM"});
sdf.setDateFormatSymbols(df);
}
LDF.add(sdf);
LDFY.add(yearOverride);
if(euristic){
addTogglePattern(sdfs);
if(sdfs.endsWith(" a")&&sdfs.indexOf("h")>0){
String chg=sdfs.substring(0,sdfs.length()-2).trim().replaceAll("h","H");
addDateP(chg);
addTogglePattern(chg);
}
}
}
@FunctionType(functionName = "ASC", argumentTypes = { AccessType.MEMO }, returnType = AccessType.LONG)
public static Integer asc(String s) {
if (s == null || s.length() == 0)
return null;
return (int) s.charAt(0);
}
@FunctionType(functionName = "EQUALS", argumentTypes = { AccessType.COMPLEX,AccessType.COMPLEX }, returnType = AccessType.YESNO)
public static Boolean equals(Object obj1,Object obj2) {
if(obj1==null||obj2==null)return false;
if(!obj1.getClass().equals(obj2.getClass()))
return false;
if(obj1.getClass().isArray()){
return Arrays.equals((Object[])obj1,(Object[])obj2);
}
return obj1.equals(obj2);
}
@FunctionType(functionName = "EQUALSIGNOREORDER", argumentTypes = { AccessType.COMPLEX,AccessType.COMPLEX }, returnType = AccessType.YESNO)
public static Boolean equalsIgnoreOrder(Object obj1,Object obj2) {
if(obj1==null||obj2==null)return false;
if(!obj1.getClass().equals(obj2.getClass()))
return false;
if(obj1.getClass().isArray()){
List<Object> lo1= Arrays.asList((Object[])obj1);
List<Object> lo2= Arrays.asList((Object[])obj2);
return lo1.containsAll(lo2) && lo2.containsAll(lo1);
}
return obj1.equals(obj2);
}
@FunctionType(functionName = "CONTAINS", argumentTypes = { AccessType.COMPLEX,AccessType.COMPLEX }, returnType = AccessType.YESNO)
public static Boolean contains(Object obj1,Object obj2) {
if(obj1==null||obj2==null)return false;
if(!obj1.getClass().isArray())
return false;
List<Object> lo= Arrays.asList((Object[])obj1);
List<Object> arg=obj2.getClass().isArray()? Arrays.asList((Object[])obj2):
Arrays.asList(new Object[]{obj2});
return lo.containsAll(arg);
}
@FunctionType(functionName = "ATN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double atn(double v) {
return Math.atan(v);
}
@FunctionType(functionName = "SQR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double sqr(double v) {
return Math.sqrt(v);
}
@FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.YESNO)
public static boolean cbool(BigDecimal value) {
return cbool((Object) value);
}
@FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.YESNO }, returnType = AccessType.YESNO)
public static boolean cbool(Boolean value) {
return cbool((Object) value);
}
private static boolean cbool(Object obj) {
boolean r = (obj instanceof Boolean) ? (Boolean) obj
: (obj instanceof String) ? Boolean.valueOf((String) obj)
: (obj instanceof Number) ? ((Number) obj)
.doubleValue() != 0 : false;
return r;
}
@FunctionType(functionName = "CBOOL", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO)
public static boolean cbool(String value) {
return cbool((Object) value);
}
@FunctionType(functionName = "CCUR", argumentTypes = { AccessType.CURRENCY }, returnType = AccessType.CURRENCY)
public static BigDecimal ccur(BigDecimal value)
throws UcanaccessSQLException {
return value.setScale(4, BigDecimal.ROUND_HALF_UP);// .doubleValue();
}
@FunctionType(functionName = "CDATE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DATETIME)
public static Timestamp cdate(String dt) {
return dateValue(dt,false);
}
@FunctionType(functionName = "CDBL", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static Double cdbl(Double value) throws UcanaccessSQLException {
return value;
}
@FunctionType(functionName = "CDEC", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static Double cdec(Double value) throws UcanaccessSQLException {
return value;
}
@FunctionType(functionName = "CINT", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.INTEGER)
public static Short cint(Double value) throws UcanaccessSQLException {
return new BigDecimal((long) Math.floor(value + 0.499999999999999d))
.shortValueExact();
}
@FunctionType(functionName = "CINT", argumentTypes = { AccessType.YESNO }, returnType = AccessType.INTEGER)
public static Short cint(boolean value) throws UcanaccessSQLException {
return (short)(value?-1:0);
}
@FunctionType(functionName = "CLONG", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.LONG)
public static Integer clong(Double value) throws UcanaccessSQLException {
return clng(value);
}
@FunctionType(functionName = "CLONG", argumentTypes = { AccessType.LONG }, returnType = AccessType.LONG)
public static Integer clong(Integer value) throws UcanaccessSQLException {
return value;
}
@FunctionType(functionName = "CLNG", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.LONG)
public static Integer clng(Double value) throws UcanaccessSQLException {
return (int) Math.floor(value + 0.5d);
}
@FunctionType(functionName = "CLNG", argumentTypes = { AccessType.LONG }, returnType = AccessType.LONG)
public static Integer clng(Integer value) throws UcanaccessSQLException {
return value;
}
@FunctionType(functionName = "CLONG", argumentTypes = { AccessType.YESNO }, returnType = AccessType.LONG)
public static Integer clong(boolean value) throws UcanaccessSQLException {
return value?-1:0;
}
@FunctionType(functionName = "CSIGN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.SINGLE)
public static double csign(double value) {
MathContext mc = new MathContext(7);
return new BigDecimal(value, mc).doubleValue();
}
@FunctionType(functionName = "CSTR", argumentTypes = { AccessType.YESNO }, returnType = AccessType.MEMO)
public static String cstr(Boolean value) throws UcanaccessSQLException {
return cstr((Object) value);
}
@FunctionType(functionName = "CSTR", argumentTypes = { AccessType.TEXT }, returnType = AccessType.MEMO)
public static String cstr(String value) throws UcanaccessSQLException {
return value;
}
@FunctionType(functionName = "CSTR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.MEMO)
public static String cstr(double value) throws UcanaccessSQLException {
return cstr((Object) value);
}
@FunctionType(functionName = "CSTR", argumentTypes = { AccessType.LONG }, returnType = AccessType.MEMO)
public static String cstr(int value) throws UcanaccessSQLException {
return cstr((Object) value);
}
public static String cstr(Object value) throws UcanaccessSQLException {
return value == null ? null : format(value.toString(), "",true);
}
@FunctionType(functionName = "CSTR", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.MEMO)
public static String cstr(Timestamp value) throws UcanaccessSQLException {
return value == null ? null : format(value, "general date");
}
@FunctionType(functionName = "CVAR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.MEMO)
public static String cvar(Double value) throws UcanaccessSQLException {
return format(value, "general number");
}
@FunctionType(namingConflict = true, functionName = "DATEADD", argumentTypes = {
AccessType.MEMO, AccessType.LONG, AccessType.DATETIME }, returnType = AccessType.DATETIME)
public static Date dateAdd(String intv, int vl, Date dt)
throws UcanaccessSQLException {
if (dt == null || intv == null)
return null;
Calendar cl = Calendar.getInstance();
cl.setTime(dt);
if (intv.equalsIgnoreCase("yyyy")) {
cl.add(Calendar.YEAR, vl);
} else if (intv.equalsIgnoreCase("q")) {
cl.add(Calendar.MONTH, vl * 3);
} else if (intv.equalsIgnoreCase("y") || intv.equalsIgnoreCase("d")) {
cl.add(Calendar.DAY_OF_YEAR, vl);
} else if (intv.equalsIgnoreCase("m")) {
cl.add(Calendar.MONTH, vl);
} else if (intv.equalsIgnoreCase("w")) {
cl.add(Calendar.DAY_OF_WEEK, vl);
} else if (intv.equalsIgnoreCase("ww")) {
cl.add(Calendar.WEEK_OF_YEAR, vl);
} else if (intv.equalsIgnoreCase("h")) {
cl.add(Calendar.HOUR, vl);
} else if (intv.equalsIgnoreCase("n")) {
cl.add(Calendar.MINUTE, vl);
} else if (intv.equalsIgnoreCase("s")) {
cl.add(Calendar.SECOND, vl);
} else
throw new UcanaccessSQLException(
ExceptionMessages.INVALID_INTERVAL_VALUE);
return (dt instanceof Timestamp) ? new Timestamp(cl.getTimeInMillis())
: new java.sql.Date(cl.getTimeInMillis());
}
@FunctionType(namingConflict = true, functionName = "DATEADD", argumentTypes = {
AccessType.MEMO, AccessType.LONG, AccessType.DATETIME }, returnType = AccessType.DATETIME)
public static Timestamp dateAdd(String intv, int vl, Timestamp dt)
throws UcanaccessSQLException {
return (Timestamp) dateAdd(intv, vl, (Date) dt);
}
@FunctionType(namingConflict = true, functionName = "DATEADD", argumentTypes = {
AccessType.MEMO, AccessType.LONG, AccessType.MEMO }, returnType = AccessType.DATETIME)
public static Timestamp dateAdd(String intv, int vl, String dt)
throws UcanaccessSQLException {
return (Timestamp) dateAdd(intv, vl, (Date) dateValue(dt,false));
}
@FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = {
AccessType.MEMO, AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG)
public static Integer dateDiff(String intv, String dt1, String dt2) throws UcanaccessSQLException{
return dateDiff(intv,dateValue(dt1,false),dateValue(dt2,false));
}
@FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = {
AccessType.MEMO, AccessType.MEMO, AccessType.DATETIME }, returnType = AccessType.LONG)
public static Integer dateDiff(String intv, String dt1, Timestamp dt2) throws UcanaccessSQLException{
return dateDiff(intv,dateValue(dt1,false),dt2);
}
@FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = {
AccessType.MEMO, AccessType.DATETIME, AccessType.MEMO }, returnType = AccessType.LONG)
public static Integer dateDiff(String intv, Timestamp dt1, String dt2) throws UcanaccessSQLException{
return dateDiff(intv,dt1,dateValue(dt2,false));
}
@FunctionType(namingConflict = true, functionName = "DATEDIFF", argumentTypes = {
AccessType.MEMO, AccessType.DATETIME, AccessType.DATETIME }, returnType = AccessType.LONG)
public static Integer dateDiff(String intv, Timestamp dt1, Timestamp dt2)
throws UcanaccessSQLException {
if (dt1 == null || intv == null || dt2 == null)
return null;
Calendar clMin = Calendar.getInstance();
Calendar clMax = Calendar.getInstance();
int sign = dt1.after(dt2) ? -1 : 1;
if (sign == 1) {
clMax.setTime(dt2);
clMin.setTime(dt1);
} else {
clMax.setTime(dt1);
clMin.setTime(dt2);
}
clMin.set(Calendar.MILLISECOND, 0);
clMax.set(Calendar.MILLISECOND, 0);
Integer result;
if (intv.equalsIgnoreCase("yyyy")) {
result = clMax.get(Calendar.YEAR) - clMin.get(Calendar.YEAR);
} else if (intv.equalsIgnoreCase("q")) {
result = dateDiff("yyyy", dt1, dt2) * 4
+ (clMax.get(Calendar.MONTH) - clMin.get(Calendar.MONTH))
/ 3;
} else if (intv.equalsIgnoreCase("y") || intv.equalsIgnoreCase("d")) {
result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin
.getTimeInMillis()) / (1000 * 60 * 60 * 24)));
} else if (intv.equalsIgnoreCase("m")) {
result = dateDiff("yyyy", dt1, dt2) * 12
+ (clMax.get(Calendar.MONTH) - clMin.get(Calendar.MONTH));
} else if (intv.equalsIgnoreCase("w") || intv.equalsIgnoreCase("ww")) {
result = (int) Math
.floor(((double) (clMax.getTimeInMillis() - clMin
.getTimeInMillis()) / (1000 * 60 * 60 * 24 * 7)));
} else if (intv.equalsIgnoreCase("h")) {
result = (int) Math
.round(((double) (clMax.getTime().getTime() - clMin
.getTime().getTime())) / (1000d * 60 * 60));
} else if (intv.equalsIgnoreCase("n")) {
result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin
.getTimeInMillis()) / (1000 * 60)));
} else if (intv.equalsIgnoreCase("s")) {
result = (int) Math.rint(((double) (clMax.getTimeInMillis() - clMin
.getTimeInMillis()) / 1000));
} else
throw new UcanaccessSQLException(
ExceptionMessages.INVALID_INTERVAL_VALUE);
return result * sign;
}
@FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = {
AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG)
public static Integer datePart(String intv, String dt,
Integer firstDayOfWeek) throws UcanaccessSQLException {
return datePart( intv, dateValue( dt,false),
firstDayOfWeek);
}
@FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = {
AccessType.MEMO, AccessType.DATETIME, AccessType.LONG }, returnType = AccessType.LONG)
public static Integer datePart(String intv, Timestamp dt,
Integer firstDayOfWeek) throws UcanaccessSQLException {
Integer ret = (intv.equalsIgnoreCase("ww")) ? datePart(intv, dt,
firstDayOfWeek, 1) : datePart(intv, dt);
if (intv.equalsIgnoreCase("w") && firstDayOfWeek > 1) {
Calendar cl = Calendar.getInstance();
cl.setTime(dt);
ret = cl.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek + 1;
if (ret <= 0)
ret = 7 + ret;
}
return ret;
}
@FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = {
AccessType.MEMO, AccessType.MEMO, AccessType.LONG, AccessType.LONG},returnType = AccessType.LONG)
public static Integer datePart(String intv, String dt,
Integer firstDayOfWeek, Integer firstWeekOfYear) throws UcanaccessSQLException {
return datePart( intv, dateValue( dt,false),
firstDayOfWeek, firstWeekOfYear);
}
@FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = {
AccessType.MEMO, AccessType.DATETIME, AccessType.LONG,
AccessType.LONG }, returnType = AccessType.LONG)
public static Integer datePart(String intv, Timestamp dt,
Integer firstDayOfWeek, Integer firstWeekOfYear)
throws UcanaccessSQLException {
Integer ret = datePart(intv, dt);
if (intv.equalsIgnoreCase("ww")
&& (firstWeekOfYear > 1 || firstDayOfWeek > 1)) {
Calendar cl = Calendar.getInstance();
cl.setTime(dt);
cl.set(Calendar.MONTH, Calendar.JANUARY);
cl.set(Calendar.DAY_OF_MONTH, 1);
Calendar cl1 = Calendar.getInstance();
cl1.setTime(dt);
if (firstDayOfWeek == 0)
firstDayOfWeek = 1;
int dow = cl.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek + 1;
if (dow <= 0) {
dow = 7 + dow;
if (cl1.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek >= 0)
ret++;
}
if (dow > 4 && firstWeekOfYear == 2) {
ret
}
if (dow > 1 && firstWeekOfYear == 3) {
ret
}
}
return ret;
}
@FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = {
AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG)
public static Integer datePart(String intv, String dt) throws UcanaccessSQLException{
return datePart( intv, dateValue( dt,false));
}
@FunctionType(namingConflict = true, functionName = "DATEPART", argumentTypes = {
AccessType.MEMO, AccessType.DATETIME }, returnType = AccessType.LONG)
public static Integer datePart(String intv, Timestamp dt)
throws UcanaccessSQLException {
if (dt == null || intv == null)
return null;
Calendar cl = Calendar.getInstance(Locale.US);
cl.setTime(dt);
if (intv.equalsIgnoreCase("yyyy")) {
return cl.get(Calendar.YEAR);
} else if (intv.equalsIgnoreCase("q")) {
return (int) Math.ceil((cl.get(Calendar.MONTH) + 1) / 3d);
} else if (intv.equalsIgnoreCase("d")) {
return cl.get(Calendar.DAY_OF_MONTH);
} else if (intv.equalsIgnoreCase("y")) {
return cl.get(Calendar.DAY_OF_YEAR);
} else if (intv.equalsIgnoreCase("m")) {
return cl.get(Calendar.MONTH) + 1;
} else if (intv.equalsIgnoreCase("ww")) {
return cl.get(Calendar.WEEK_OF_YEAR);
} else if (intv.equalsIgnoreCase("w")) {
return cl.get(Calendar.DAY_OF_WEEK);
} else if (intv.equalsIgnoreCase("h")) {
return cl.get(Calendar.HOUR_OF_DAY);
} else if (intv.equalsIgnoreCase("n")) {
return cl.get(Calendar.MINUTE);
} else if (intv.equalsIgnoreCase("s")) {
return cl.get(Calendar.SECOND);
} else
throw new UcanaccessSQLException(
ExceptionMessages.INVALID_INTERVAL_VALUE);
}
@FunctionType(functionName = "DATESERIAL", argumentTypes = {
AccessType.LONG, AccessType.LONG, AccessType.LONG }, returnType = AccessType.DATETIME)
public static Timestamp dateSerial(int year, int month, int day) {
Calendar cl = Calendar.getInstance();
cl.setLenient(true);
cl.set(Calendar.YEAR, year);
cl.set(Calendar.MONTH, month - 1);
cl.set(Calendar.DAY_OF_MONTH, day);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MILLISECOND, 0);
return new Timestamp(cl.getTime().getTime());
}
@FunctionType(functionName = "DATEVALUE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DATETIME)
public static Timestamp dateValue(String dt) {
return dateValue( dt,true);
}
private static Timestamp dateValue(String dt, boolean onlyDate) {
if(!"true".equalsIgnoreCase(reg.getRS())&&(
!"PM".equalsIgnoreCase(reg.getPM())||!"AM".equalsIgnoreCase(reg.getAM())
)){
dt=dt.replaceAll("(?i)"+Pattern.quote(reg.getPM()), "PM").replaceAll("(?i)"+Pattern.quote(reg.getAM()),"AM");
}
for (SimpleDateFormat sdf : LDF)
try {
Timestamp t= new Timestamp(sdf.parse(dt).getTime());
if(onlyDate)t=dateValue(t);
if(LDFY.get(LDF.indexOf(sdf))){
Calendar cl = Calendar.getInstance();
int y=cl.get(Calendar.YEAR);
cl.setTime(t);
cl.set(Calendar.YEAR, y);
t=new Timestamp(cl.getTime().getTime());
}
return t;
} catch (ParseException e) {
}
return null;
}
@FunctionType(functionName = "DATEVALUE", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.DATETIME)
public static Timestamp dateValue(Timestamp dt) {
Calendar cl = Calendar.getInstance();
cl.setTime(dt);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MILLISECOND, 0);
return new Timestamp(cl.getTime().getTime());
}
@FunctionType(functionName = "FORMAT", argumentTypes = { AccessType.DOUBLE,
AccessType.TEXT }, returnType = AccessType.TEXT)
public static String format(double d, String par)
throws UcanaccessSQLException {
if ("percent".equalsIgnoreCase(par)) {
DecimalFormat formatter = new DecimalFormat("0.00");
formatter.setRoundingMode(RoundingMode.HALF_UP);
return (formatter.format(d * 100) + "%");
}
if ("fixed".equalsIgnoreCase(par)) {
DecimalFormat formatter = new DecimalFormat("0.00");
formatter.setRoundingMode(RoundingMode.HALF_UP);
return formatter.format(d);
}
if ("standard".equalsIgnoreCase(par)) {
DecimalFormat formatter = new DecimalFormat("
return formatter.format(d);
}
if ("general number".equalsIgnoreCase(par)) {
DecimalFormat formatter = new DecimalFormat();
formatter.setGroupingUsed(false);
return formatter.format(d);
}
if ("yes/no".equalsIgnoreCase(par)) {
return d == 0 ? "No" : "Yes";
}
if ("true/false".equalsIgnoreCase(par)) {
return d == 0 ? "False" : "True";
}
if ("On/Off".equalsIgnoreCase(par)) {
return d == 0 ? "Off" : "On";
}
if ("Scientific".equalsIgnoreCase(par)) {
return String.format( "%6.2E", d);
}
try {
DecimalFormat formatter = new DecimalFormat(par);
formatter.setRoundingMode(RoundingMode.HALF_UP);
return formatter.format(d);
} catch (Exception e) {
throw new UcanaccessSQLException(e);
}
}
@FunctionType(functionName = "FORMAT", argumentTypes = { AccessType.TEXT,
AccessType.TEXT }, returnType = AccessType.TEXT)
public static String format(String s, String par)
throws UcanaccessSQLException {
return format( s, par, false);
}
public static String format(String s, String par, boolean incl)
throws UcanaccessSQLException {
if (isNumeric(s)) {
if(incl){
return format(Double.parseDouble(s), par);
}
DecimalFormat df=new DecimalFormat();
try {
return format(df.parse(s).doubleValue(), par);
} catch (ParseException e) {
throw new UcanaccessSQLException(e);
}
}
if (isDate(s)) {
return format(dateValue(s,false), par);
}
return s;
}
private static String formatDate(Timestamp t,String pattern){
String ret= new SimpleDateFormat(pattern).format(t);
if(!reg.getRS().equalsIgnoreCase("true")){
if(!reg.getAM().equals("AM"))
ret=ret.replaceAll("AM", reg.getAM());
if(!reg.getPM().equals("PM"))
ret=ret.replaceAll("PM",reg.getPM());
}else{
ret=ret.replaceAll( reg.getPM(),"PM");
ret=ret.replaceAll(reg.getAM(),"AM");
}
return ret;
}
@FunctionType(functionName = "FORMAT", argumentTypes = {
AccessType.DATETIME, AccessType.TEXT }, returnType = AccessType.TEXT)
public static String format(Timestamp t, String par)
throws UcanaccessSQLException {
if ("long date".equalsIgnoreCase(par)) {
return formatDate(t,reg.getLongDatePattern());
}
if ("medium date".equalsIgnoreCase(par)) {
return formatDate(t,reg.getMediumDatePattern());
}
if ("short date".equalsIgnoreCase(par)) {
return formatDate(t,reg.getShortDatePattern());
}
if ("general date".equalsIgnoreCase(par)) {
return formatDate(t,reg.getGeneralPattern());
}
if ("long time".equalsIgnoreCase(par)) {
return formatDate(t,reg.getLongTimePattern());
}
if ("medium time".equalsIgnoreCase(par)) {
return formatDate(t,reg.getMediumTimePattern());
}
if ("short time".equalsIgnoreCase(par)) {
return formatDate(t,reg.getShortTimePattern());
}
if ("q".equalsIgnoreCase(par)) {
return String.valueOf(datePart(par, t));
}
return new SimpleDateFormat(par.replaceAll("m", "M").replaceAll("n",
"m").replaceAll("(?i)AM/PM|A/P|AMPM", "a").replaceAll("dddd", "EEEE")).format(t);
}
@FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO,
AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.MEMO)
public static String iif(boolean b, String o, String o1) {
return (String)iif(b,(Object)o,(Object) o1);
}
@FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO,
AccessType.LONG, AccessType.LONG }, returnType = AccessType.LONG)
public static Integer iif(boolean b, Integer o, Integer o1) {
return (Integer)iif(b,(Object)o,(Object) o1);
}
@FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO,
AccessType.DOUBLE, AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static Double iif(boolean b, Double o, Double o1) {
return (Double)iif(b,(Object)o,(Object) o1);
}
@FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO,
AccessType.YESNO, AccessType.YESNO }, returnType = AccessType.YESNO)
public static Boolean iif(Boolean b, Boolean o, Boolean o1) {
return (Boolean)iif(b,(Object)o,(Object) o1);
}
@FunctionType(functionName = "IIF", argumentTypes = { AccessType.YESNO,
AccessType.DATETIME, AccessType.DATETIME }, returnType = AccessType.DATETIME)
public static Timestamp iif(Boolean b, Timestamp o, Timestamp o1) {
return (Timestamp)iif(b,(Object)o,(Object) o1);
}
private static Object iif(Boolean b, Object o, Object o1) {
if(b==null) b=Boolean.FALSE;
return b ? o : o1;
}
@FunctionType(functionName = "INSTR", argumentTypes = { AccessType.LONG,
AccessType.MEMO, AccessType.MEMO }, returnType = AccessType.LONG)
public static Integer instr(Integer start, String text, String search) {
return instr(start, text, search, -1);
}
@FunctionType(functionName = "INSTR", argumentTypes = { AccessType.LONG,
AccessType.MEMO, AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG)
public static Integer instr(Integer start, String text, String search,
Integer compare) {
start
if (compare != 0)
text = text.toLowerCase();
if (text.length() <= start) {
return 0;
} else
text = text.substring(start);
return text.indexOf(search) + start + 1;
}
@FunctionType(functionName = "INSTR", argumentTypes = { AccessType.MEMO,
AccessType.MEMO }, returnType = AccessType.LONG)
public static Integer instr(String text, String search) {
return instr(1, text, search, -1);
}
@FunctionType(functionName = "INSTR", argumentTypes = { AccessType.MEMO,
AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG)
public static Integer instr(String text, String search, Integer compare) {
return instr(1, text, search, compare);
}
@FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.TEXT,
AccessType.TEXT }, returnType = AccessType.LONG)
public static Integer instrrev(String text, String search) {
return instrrev(text, search, -1, -1);
}
@FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.MEMO,
AccessType.MEMO, AccessType.LONG }, returnType = AccessType.LONG)
public static Integer instrrev(String text, String search, Integer start) {
return instrrev(text, search, start, -1);
}
@FunctionType(functionName = "INSTRREV", argumentTypes = { AccessType.MEMO,
AccessType.MEMO, AccessType.LONG, AccessType.LONG }, returnType = AccessType.LONG)
public static Integer instrrev(String text, String search, Integer start,
Integer compare) {
if (compare != 0)
text = text.toLowerCase();
if (text.length() <= start) {
return 0;
} else {
if (start > 0)
text = text.substring(0, start);
return text.lastIndexOf(search) + 1;
}
}
@FunctionType(functionName = "ISDATE", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO)
public static boolean isDate(String dt) {
return dateValue(dt) != null;
}
@FunctionType(functionName = "ISDATE", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.YESNO)
public static boolean isDate(Timestamp dt) {
return true;
}
@FunctionType(namingConflict = true, functionName = "IsNull", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO)
public static boolean isNull(String o) {
return o == null;
}
@FunctionType(functionName = "ISNUMERIC", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.YESNO)
public static boolean isNumeric(BigDecimal b) {
return true;
}
@FunctionType(functionName = "ISNUMERIC", argumentTypes = { AccessType.MEMO }, returnType = AccessType.YESNO)
public static boolean isNumeric(String s) {
try {
Currency cr=Currency.getInstance(Locale.getDefault());
if(s.startsWith(cr.getSymbol()))return isNumeric( s.substring(cr.getSymbol().length()));
if(s.startsWith("+")||s.startsWith("-"))return isNumeric( s.substring(1));
DecimalFormatSymbols dfs=DecimalFormatSymbols.getInstance();
String sep=dfs.getDecimalSeparator()+"";
String gs=dfs.getGroupingSeparator()+"";
if(s.startsWith(gs))return false;
if(s.startsWith(sep))return isNumeric( s.substring(1));
if(sep.equals("."))
s=s.replaceAll(gs,"");
else
s=s.replaceAll("\\.", "").replaceAll(sep,".");
new BigDecimal(s);
return true;
} catch (Exception e) {
}
return false;
}
@FunctionType(functionName = "LEN", argumentTypes = { AccessType.MEMO }, returnType = AccessType.LONG)
public static Integer len(String o) {
if (o == null)
return null;
return new Integer(o.length());
}
@FunctionType(functionName = "MID", argumentTypes = { AccessType.MEMO,
AccessType.LONG }, returnType = AccessType.MEMO)
public static String mid(String value, int start) {
return mid(value, start, value.length());
}
@FunctionType(functionName = "MID", argumentTypes = { AccessType.MEMO,
AccessType.LONG, AccessType.LONG }, returnType = AccessType.MEMO)
public static String mid(String value, int start, int length) {
if (value == null)
return null;
int len = start - 1 + length;
if (start < 1)
throw new RuntimeException("Invalid function call");
if (len > value.length()) {
len = value.length();
}
return value.substring(start - 1, len);
}
@FunctionType(namingConflict = true, functionName = "MONTHNAME", argumentTypes = { AccessType.LONG }, returnType = AccessType.TEXT)
public static String monthName(int i) throws UcanaccessSQLException {
return monthName(i, false);
}
@FunctionType(namingConflict = true, functionName = "MONTHNAME", argumentTypes = {
AccessType.LONG, AccessType.YESNO }, returnType = AccessType.TEXT)
public static String monthName(int i, boolean abbr)
throws UcanaccessSQLException {
i
if (i >= 0 && i <= 11) {
DateFormatSymbols dfs = new DateFormatSymbols();
return abbr ? dfs.getShortMonths()[i] : dfs.getMonths()[i];
}
throw new UcanaccessSQLException(ExceptionMessages.INVALID_MONTH_NUMBER);
}
@FunctionType(functionName = "DATE", argumentTypes = {}, returnType = AccessType.DATETIME)
public static Timestamp date() {
Calendar cl = Calendar.getInstance();
cl.set(Calendar.MILLISECOND, 0);
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
return new Timestamp(cl.getTime().getTime());
}
@FunctionType(namingConflict = true, functionName = "NOW", argumentTypes = {}, returnType = AccessType.DATETIME)
public static Timestamp now() {
Calendar cl = Calendar.getInstance();
cl.set(Calendar.MILLISECOND, 0);
return new Timestamp(cl.getTime().getTime());
}
private static Object nz(Object value, Object outher) {
return value == null ? outher : value;
}
@FunctionType(functionName = "NZ", argumentTypes = { AccessType.MEMO }, returnType = AccessType.MEMO)
public static String nz(String value) {
return value == null ? "" : value;
}
@FunctionType(functionName = "NZ", argumentTypes = { AccessType.MEMO,
AccessType.MEMO }, returnType = AccessType.MEMO)
public static String nz(String value, String outher) {
return (String) nz((Object) value, (Object) outher);
}
@FunctionType(functionName = "SIGN", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.INTEGER)
public static short sign(double n) {
return (short) (n == 0 ? 0 : (n > 0 ? 1 : -1));
}
@FunctionType(functionName = "SPACE", argumentTypes = { AccessType.LONG }, returnType = AccessType.MEMO)
public static String space(Integer nr) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nr; ++i)
sb.append(' ');
return sb.toString();
}
@FunctionType(functionName = "STR", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.TEXT)
public static String str(double d) {
String pre = d > 0 ? " " : "";
return Math.round(d) == d ? pre + Math.round(d) : pre + d;
}
@FunctionType(functionName = "TIME", argumentTypes = {}, returnType = AccessType.DATETIME)
public static Timestamp time() {
Calendar cl = Calendar.getInstance();
cl.setTime(now());
cl.set(1899, 11, 30);
return new java.sql.Timestamp(cl.getTimeInMillis());
}
@FunctionType(functionName = "VAL", argumentTypes = { AccessType.NUMERIC }, returnType = AccessType.DOUBLE)
public static Double val(BigDecimal val1) {
return val((Object) val1);
}
private static Double val(Object val1) {
if (val1 == null)
return null;
String val = val1.toString().trim();
int lp = val.lastIndexOf(".");
char[] ca = val.toCharArray();
StringBuffer sb = new StringBuffer();
int minLength = 1;
for (int i = 0; i < ca.length; i++) {
char c = ca[i];
if (((c == '-') || (c == '+')) && (i == 0)) {
++minLength;
sb.append(c);
} else if (c == ' ')
continue;
else if (Character.isDigit(c)) {
sb.append(c);
} else if (c == '.' && i == lp) {
sb.append(c);
if (i == 0 || (i == 1 && minLength == 2)) {
++minLength;
}
} else
break;
}
if (sb.length() < minLength)
return 0.0d;
else
return Double.parseDouble(sb.toString());
}
@FunctionType(functionName = "VAL", argumentTypes = { AccessType.MEMO }, returnType = AccessType.DOUBLE)
public static Double val(String val1) {
return val((Object) val1);
}
@FunctionType(functionName = "WEEKDAYNAME", argumentTypes = { AccessType.LONG }, returnType = AccessType.TEXT)
public static String weekDayName(int i) {
return weekDayName(i, false);
}
@FunctionType(functionName = "WEEKDAYNAME", argumentTypes = {
AccessType.LONG, AccessType.YESNO }, returnType = AccessType.TEXT)
public static String weekDayName(int i, boolean abbr) {
return weekDayName(i, abbr, 1);
}
@FunctionType(functionName = "WEEKDAYNAME", argumentTypes = {
AccessType.LONG, AccessType.YESNO, AccessType.LONG }, returnType = AccessType.TEXT)
public static String weekDayName(int i, boolean abbr, int s) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, i + s - 1);
String pattern = abbr ? "%ta" : "%tA";
return String.format(pattern, cal, cal);
}
@FunctionType(functionName = "WEEKDAY", argumentTypes = { AccessType.DATETIME }, returnType = AccessType.LONG)
public static Integer weekDay(Timestamp dt) throws UcanaccessSQLException {
return datePart("w", dt);
}
@FunctionType(functionName = "WEEKDAY", argumentTypes = {
AccessType.DATETIME, AccessType.LONG }, returnType = AccessType.LONG)
public static Integer weekDay(Timestamp dt, Integer firstDayOfWeek)
throws UcanaccessSQLException {
return datePart("w", dt, firstDayOfWeek);
}
@FunctionType(functionName = "STRING", argumentTypes = { AccessType.LONG,
AccessType.MEMO }, returnType = AccessType.MEMO)
public static String string(Integer nr, String str)
throws UcanaccessSQLException {
if (str == null)
return null;
String ret = "";
for (int i = 0; i < nr; ++i) {
ret += str.charAt(0);
}
return ret;
}
@FunctionType(functionName = "TIMESERIAL", argumentTypes = {
AccessType.LONG, AccessType.LONG, AccessType.LONG }, returnType = AccessType.DATETIME)
public static Timestamp timeserial(Integer h, Integer m, Integer s) {
Calendar cl = Calendar.getInstance();
cl.setTime(now());
cl.set(1899, 11, 30, h, m, s);
return new java.sql.Timestamp(cl.getTimeInMillis());
}
@FunctionType(functionName = "RND", argumentTypes = {}, returnType = AccessType.DOUBLE)
public static Double rnd() {
return rnd(null);
}
@FunctionType(functionName = "RND", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static Double rnd(Double d) {
if (d == null)
return lastRnd = Math.random();
if (d > 0)
return lastRnd = Math.random();
if (d < 0)
return rnd == null ? rnd = d : rnd;
if (d == 0)
return lastRnd == null ? lastRnd = Math.random() : lastRnd;
return null;
}
@FunctionType(functionName = "NZ", argumentTypes = { AccessType.NUMERIC,
AccessType.NUMERIC }, returnType = AccessType.NUMERIC)
public static BigDecimal nz(BigDecimal value, BigDecimal outher) {
return (BigDecimal) nz((Object) value, (Object) outher);
}
@FunctionType(functionName = "NZ", argumentTypes = { AccessType.DOUBLE,
AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static Double nz(Double value, Double outher) {
return (Double) nz((Object) value, (Object) outher);
}
@FunctionType(functionName = "NZ", argumentTypes = { AccessType.LONG,
AccessType.LONG }, returnType = AccessType.LONG)
public static Integer nz(Integer value, Integer outher) {
return (Integer) nz((Object) value, (Object) outher);
}
@FunctionType(functionName = "STRREVERSE", argumentTypes = { AccessType.MEMO}, returnType = AccessType.MEMO)
public static String strReverse(String value) {
if(value==null)return null;
return new StringBuffer(value).reverse().toString();
}
@FunctionType(functionName = "STRCONV", argumentTypes = { AccessType.MEMO,AccessType.LONG}, returnType = AccessType.MEMO)
public static String strConv(String value,int ul) {
if(value==null)return null;
if(ul==1)value= value.toUpperCase();
if(ul==2)value= value.toLowerCase();
return value;
}
@FunctionType(functionName = "STRCOMP", argumentTypes = { AccessType.MEMO,AccessType.MEMO,AccessType.LONG}, returnType = AccessType.LONG)
public static Integer strComp(String value1,String value2, Integer type) throws UcanaccessSQLException {
switch(type){
case 0:
case -1:
case 2: return value1.compareTo(value2);
case 1: return value1.toUpperCase().compareTo(value2.toUpperCase());
default: throw new UcanaccessSQLException(ExceptionMessages.INVALID_PARAMETER);
}
}
@FunctionType(functionName = "STRCOMP", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.LONG)
public static Integer strComp(String value1,String value2) throws UcanaccessSQLException {
return strComp( value1,value2, 0);
}
@FunctionType(functionName = "INT", argumentTypes = { AccessType.DOUBLE }, returnType = AccessType.LONG)
public static Integer mint(Double value) throws UcanaccessSQLException {
return new BigDecimal((long) Math.floor(value )).intValueExact();
}
@FunctionType(functionName = "INT", argumentTypes = { AccessType.YESNO }, returnType = AccessType.INTEGER)
public static Short mint(boolean value) throws UcanaccessSQLException {
return (short)(value?-1:0);
}
@FunctionType(functionName = "DDB", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double ddb(double cost, double salvage, double life,double period ){
return ddb( cost, salvage,life, period ,2d);
}
@FunctionType(functionName = "DDB", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double ddb(double cost, double salvage, double life, double period, double factor) {
if (cost<0||((life == 2d) && (period > 1d)))return 0;
if (life < 2d||((life == 2d) && (period <= 1d)))
return (cost - salvage);
if (period <= 1d)
return Math.min(cost*factor/life, cost-salvage);
double retk =Math.max( salvage -cost * Math.pow((life - factor) / life, period),0);
return Math.max( ((factor * cost) / life) * Math.pow((life - factor) / life, period - 1d)-retk,0);
}
@FunctionType(functionName = "FV", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double fv(double rate,int periods,double payment){
return fv(rate, periods, payment,0,0);
}
@FunctionType(functionName = "FV", argumentTypes = { AccessType.DOUBLE,AccessType.LONG ,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double fv(double rate,int periods,double payment,double pv){
return fv(rate, periods, payment,pv,0);
}
@FunctionType(functionName = "FV", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double fv(double rate,int periods,double payment,double pv,double type){
type=(Math.abs(type)>=1)?1:0;
double fv=pv*Math.pow(1+rate, periods);
for(int i=0;i<periods;i++){
fv+=(payment)*Math.pow(1+rate, i+type);
}
return -fv;
}
@FunctionType(functionName = "PMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double pmt(double rate, double periods, double pv) {
return pmt( rate, periods, pv,0,0);
}
@FunctionType(functionName = "PMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double pmt(double rate, double periods, double pv, double fv) {
return pmt( rate, periods, pv,0,0);
}
@FunctionType(functionName = "PMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double pmt(double rate, double periods, double pv, double fv, double type) {
type=(Math.abs(type)>=1)?1:0;
if (rate == 0) {
return -1*(fv+pv)/periods;
}
else {
return ( fv + pv * Math.pow(1+rate , periods) ) * rate
/
((type==1? 1+rate : 1) * (1 - Math.pow(1+rate, periods)));
}
}
@FunctionType(functionName = "NPER", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double nper(double rate, double pmt, double pv) {
return nper( rate, pmt, pv, 0, 0);
}
@FunctionType(functionName = "NPER", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double nper(double rate, double pmt, double pv, double fv) {
return nper( rate, pmt, pv, fv, 0);
}
@FunctionType(functionName = "NPER", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double nper(double rate, double pmt, double pv, double fv,double type) {
type=(Math.abs(type)>=1)?1:0;
double nper = 0;
if (rate == 0) {
nper = -1 * (fv + pv) / pmt;
} else {
double cr = (type==1 ? 1+rate : 1) * pmt / rate;
double val1 = ((cr - fv) < 0)
? Math.log(fv - cr)
: Math.log(cr - fv);
double val2 = ((cr - fv) < 0)
? Math.log(-pv - cr)
: Math.log(pv + cr);
double val3 = Math.log(1+ rate);
nper = (val1 - val2) / val3;
}
return nper;
}
@FunctionType(functionName = "IPMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double ipmt(double rate, double per, double nper, double pv) {
return ipmt(rate, per, nper, pv, 0,0);
}
@FunctionType(functionName = "IPMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double ipmt(double rate, double per, double nper, double pv, double fv) {
return ipmt(rate, per, nper, pv, fv,0);
}
@FunctionType(functionName = "IPMT", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double ipmt(double rate, double per, double nper, double pv, double fv, double type) {
type=(Math.abs(type)>=1)?1:0;
double ipmt = fv(rate, new Double(per).intValue() - 1, pmt(rate, nper, pv, fv, type), pv, type) * rate;
if (type==1) ipmt =ipmt/ (1 + rate);
return ipmt;
}
@FunctionType(functionName = "PV", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double pv(double rate, double nper, double pmt) {
return pv( rate, nper, pmt,0,0);
}
@FunctionType(functionName = "PV", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double pv(double rate, double nper, double pmt, double fv) {
return pv( rate, nper, pmt,fv,0);
}
@FunctionType(functionName = "PV", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double pv(double rate, double nper, double pmt, double fv, double type) {
type=(Math.abs(type)>=1)?1:0;
if (rate == 0) {
return -1*((nper*pmt)+fv);
}
else {
return (( ( 1 - Math.pow(1+rate, nper) ) / rate ) * (type==1 ? 1+rate : 1) * pmt - fv)
/
Math.pow(1+rate, nper);
}
}
@FunctionType(functionName = "PPMT", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.LONG,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double ppmt(double rate, int per, int nper, double pv) {
return ppmt(rate,per, nper, pv, 0, 0) ;
}
@FunctionType(functionName = "PPMT", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.LONG,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double ppmt(double rate, int per, int nper, double pv, double fv) {
return ppmt(rate,per, nper, pv, fv, 0) ;
}
@FunctionType(functionName = "PPMT", argumentTypes = { AccessType.DOUBLE,AccessType.LONG,AccessType.LONG,AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double ppmt(double rate, int per, int nper, double pv, double fv, double type) {
return pmt(rate, nper, pv, fv, type) - ipmt(rate, per, nper, pv, fv, type);
}
@FunctionType(functionName = "SLN", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE }, returnType = AccessType.DOUBLE)
public static double sln(double cost, double salvage, double life) {
return (cost-salvage)/life;
}
@FunctionType(functionName = "SYD", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE, AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double syd(double cost, double salvage, double life,double per) {
return (cost-salvage)*(life-per+1)*2/(life*(life+1));
}
@FunctionType(functionName = "RATE", argumentTypes = { AccessType.DOUBLE, AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double rate(double nper, double pmt, double pv) {
return rate(nper, pmt, pv, 0, 0, 0.1);
}
@FunctionType(functionName = "RATE", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE, AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double rate(double nper, double pmt, double pv, double fv) {
return rate(nper, pmt, pv, fv, 0, 0.1);
}
@FunctionType(functionName = "RATE", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE, AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double rate(double nper, double pmt, double pv, double fv, double type) {
return rate(nper, pmt, pv, fv, type, 0.1);
}
@FunctionType(functionName = "RATE", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE, AccessType.DOUBLE,AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double rate(double nper, double pmt, double pv, double fv, double type, double guess) {
type=(Math.abs(type)>=1)?1:0; //the only change to the implementation Apache POI
int FINANCIAL_MAX_ITERATIONS = 20;//Bet accuracy with 128
double FINANCIAL_PRECISION = 0.0000001;//1.0e-8
double y, y0, y1, x0, x1 = 0, f = 0, i = 0;
double rate = guess;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv;
} else {
f = Math.exp(nper * Math.log(1 + rate));
y = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
}
y0 = pv + pmt * nper + fv;
y1 = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
// find root by Newton secant method
i = x0 = 0.0;
x1 = rate;
while ((Math.abs(y0 - y1) > FINANCIAL_PRECISION) && (i < FINANCIAL_MAX_ITERATIONS)) {
rate = (y1 * x0 - y0 * x1) / (y1 - y0);
x0 = x1;
x1 = rate;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = pv * (1 + nper * rate) + pmt * (1 + rate * type) * nper + fv;
} else {
f = Math.exp(nper * Math.log(1 + rate));
y = pv * f + pmt * (1 / rate + type) * (f - 1) + fv;
}
y0 = y1;
y1 = y;
++i;
}
return rate;
}
@FunctionType(functionName = "formulaToNumeric", argumentTypes = { AccessType.DOUBLE,AccessType.MEMO}, returnType = AccessType.DOUBLE)
public static Double formulaToNumeric(Double res, String datatype){
return res;
}
@FunctionType(functionName = "formulaToNumeric", argumentTypes = { AccessType.YESNO,AccessType.MEMO}, returnType = AccessType.DOUBLE)
public static Double formulaToNumeric(Boolean res, String datatype){
if(res==null)return null;
return res.booleanValue()?-1d:0d;
}
@FunctionType(functionName = "formulaToNumeric", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.DOUBLE)
public static Double formulaToNumeric(String res, String datatype){
if(res==null)return null;
try{
DecimalFormatSymbols dfs=DecimalFormatSymbols.getInstance();
String sep=dfs.getDecimalSeparator()+"";
String gs=dfs.getGroupingSeparator()+"";
res=res.replaceAll(Pattern.quote(gs), "");
if(!sep.equalsIgnoreCase("."))
res=res.replaceAll(Pattern.quote(sep),".");
double d= val(res);
DataType dt= DataType.valueOf(datatype);
if(dt.equals( DataType.BYTE)||dt.equals( DataType.INT)||dt.equals( DataType.LONG)){
d=Math.rint(d+0.00000001);
}
return d;
}catch(Exception e){
return null;
}
}
@FunctionType(functionName = "formulaToNumeric", argumentTypes = { AccessType.DATETIME,AccessType.MEMO}, returnType = AccessType.DOUBLE)
public static Double formulaToNumeric(Timestamp res, String datatype) throws UcanaccessSQLException{
if(res==null)return null;
Calendar clbb = Calendar.getInstance();
clbb.set(1899, 11, 30,0,0,0);
return (double)dateDiff("y",new Timestamp(clbb.getTimeInMillis()),res );
}
@FunctionType(functionName = "formulaToBoolean", argumentTypes = { AccessType.YESNO,AccessType.MEMO}, returnType = AccessType.YESNO)
public static Boolean formulaToBoolean(Boolean res, String datatype){
return res;
}
@FunctionType(functionName = "formulaToBoolean", argumentTypes = { AccessType.DOUBLE,AccessType.MEMO}, returnType = AccessType.YESNO)
public static Boolean formulaToBoolean(Double res, String datatype){
if(res==null)return null;
return res!=0d;
}
@FunctionType(functionName = "formulaToBoolean", argumentTypes = { AccessType.DATETIME,AccessType.MEMO}, returnType = AccessType.YESNO)
public static Boolean formulaToBoolean(Timestamp res, String datatype){
return null;
}
@FunctionType(functionName = "formulaToBoolean", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.YESNO)
public static Boolean formulaToBoolean(String res, String datatype){
if(res==null)return null;
if(res.equals("-1"))return true;
if(res.equals("0"))return false;
return null;
}
@FunctionType(functionName = "formulaToText", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.MEMO)
public static String formulaToText(String res, String datatype){
return res;
}
@FunctionType(functionName = "formulaToText", argumentTypes = { AccessType.DOUBLE,AccessType.MEMO}, returnType = AccessType.MEMO)
public static String formulaToText(Double res, String datatype) throws UcanaccessSQLException{
if(res==null)return null;
DecimalFormatSymbols dfs=DecimalFormatSymbols.getInstance();
DecimalFormat df = new DecimalFormat("#",dfs);
df.setGroupingUsed(false);
df.setMaximumFractionDigits(100);
return df.format(res);
}
@FunctionType(functionName = "formulaToText", argumentTypes = { AccessType.YESNO,AccessType.MEMO}, returnType = AccessType.MEMO)
public static String formulaToText(Boolean res, String datatype) throws UcanaccessSQLException{
if(res==null)return null;
return res?"-1":"0";
}
@FunctionType(functionName = "formulaToText", argumentTypes = { AccessType.DATETIME,AccessType.MEMO}, returnType = AccessType.MEMO)
public static String formulaToText(Timestamp res, String datatype) throws UcanaccessSQLException{
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(res.getTime());
if(cl.get(Calendar.HOUR)==0&&cl.get(Calendar.MINUTE)==0&&cl.get(Calendar.SECOND)==0)
return format(res,"short date" );
else return format(res,"general date" );
}
@FunctionType(functionName = "formulaToDate", argumentTypes = { AccessType.DATETIME,AccessType.MEMO}, returnType = AccessType.DATETIME)
public static Timestamp formulaToDate(Timestamp res, String datatype){
return res;
}
@FunctionType(functionName = "formulaToDate", argumentTypes = { AccessType.MEMO,AccessType.MEMO}, returnType = AccessType.DATETIME)
public static Timestamp formulaToDate(String res, String datatype){
if(res==null)return null;
try{
return dateValue(res,false);
}catch(Exception e){
return null;
}
}
@FunctionType(functionName = "formulaToDate", argumentTypes = { AccessType.YESNO,AccessType.MEMO}, returnType = AccessType.DATETIME)
public static Timestamp formulaToDate(Boolean res, String datatype) throws UcanaccessSQLException{
if(res==null)return null;
Calendar clbb = Calendar.getInstance();
clbb.set(1899, 11, 30,0,0,0);
clbb.set(Calendar.MILLISECOND, 0);
return dateAdd("y", res?-1:0, new Timestamp(clbb.getTimeInMillis()));
}
@FunctionType(functionName = "formulaToDate", argumentTypes = { AccessType.DOUBLE,AccessType.MEMO}, returnType = AccessType.DATETIME)
public static Timestamp formulaToDate(Double res, String datatype) throws UcanaccessSQLException{
if(res==null)return null;
Calendar clbb = Calendar.getInstance();
clbb.set(1899, 11, 30,0,0,0);
clbb.set(Calendar.MILLISECOND, 0);
Double d=Math.floor(res);
Timestamp tr= dateAdd("y", d.intValue(), new Timestamp(clbb.getTimeInMillis()));
d=(res-res.intValue())*24;
tr= dateAdd("H",d.intValue(), tr);
d=(d-d.intValue())*60;
tr= dateAdd("N",d.intValue(), tr);
d=(d-d.intValue())*60;
tr= dateAdd("S",new Double(Math.rint(d+0.0000001)).intValue(), tr);
return tr;
}
@FunctionType(namingConflict = true,functionName = "ROUND", argumentTypes = { AccessType.DOUBLE,AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double round(double d, double p) {
double f = Math.pow(10d, p);
return Math.round(d * f) / f;
}
@FunctionType(namingConflict = true,functionName = "FIX", argumentTypes = { AccessType.DOUBLE}, returnType = AccessType.DOUBLE)
public static double fix(double d) throws UcanaccessSQLException {
return sign(d) * mint(Math.abs(d));
}
}
|
package org.realityforge.replicant.server.transport;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.replicant.server.ChannelAddress;
/**
* An object defining the state of the subscription to a particular channel and
* all the dependency relationships to other graphs.
*/
public final class SubscriptionEntry
implements Comparable<SubscriptionEntry>
{
@Nonnull
private final ChannelAddress _address;
/**
* This is a list of channels that this auto-subscribed to.
*/
@Nonnull
private final Set<ChannelAddress> _outwardSubscriptions = new HashSet<>();
@Nonnull
private final Set<ChannelAddress> _roOutwardSubscriptions = Collections.unmodifiableSet( _outwardSubscriptions );
/**
* This is a list of channels that auto-subscribed to this channel.
*/
@Nonnull
private final Set<ChannelAddress> _inwardSubscriptions = new HashSet<>();
@Nonnull
private final Set<ChannelAddress> _roInwardSubscriptions = Collections.unmodifiableSet( _inwardSubscriptions );
private boolean _explicitlySubscribed;
@Nullable
private Object _filter;
public SubscriptionEntry( @Nonnull final ChannelAddress address )
{
_address = Objects.requireNonNull( address );
}
@Nonnull
public ChannelAddress getAddress()
{
return _address;
}
/**
* Return true if this channel can be automatically un-subscribed. This means it has not
* been explicitly subscribed and has no incoming subscriptions.
*/
public boolean canUnsubscribe()
{
return !isExplicitlySubscribed() && _inwardSubscriptions.isEmpty();
}
/**
* Return true if this channel has been explicitly subscribed to from the client,
* false the subscription occurred due to a graph link.
*/
public boolean isExplicitlySubscribed()
{
return _explicitlySubscribed;
}
public void setExplicitlySubscribed( final boolean explicitlySubscribed )
{
_explicitlySubscribed = explicitlySubscribed;
}
/**
* Return the filter that was applied to this subscription. A particular channel
* may or may not have a
*/
@Nullable
public Object getFilter()
{
return _filter;
}
public void setFilter( @Nullable final Object filter )
{
_filter = filter;
}
/**
* Return the channels that were subscribed as a result of subscribing to this channel.
*/
@Nonnull
public Set<ChannelAddress> getOutwardSubscriptions()
{
return _roOutwardSubscriptions;
}
/**
* Register the specified channel as outward links. Returns the set of links that were actually added.
*/
@Nonnull
public ChannelAddress[] registerOutwardSubscriptions( @Nonnull final ChannelAddress... channels )
{
final List<ChannelAddress> results = new ArrayList<>( channels.length );
for ( final ChannelAddress channel : channels )
{
if ( !_outwardSubscriptions.contains( channel ) )
{
_outwardSubscriptions.add( channel );
results.add( channel );
}
}
return results.toArray( new ChannelAddress[ 0 ] );
}
/**
* Deregister the specified channels as outward links. Returns the set of links that were actually deregistered.
*/
@Nonnull
public ChannelAddress[] deregisterOutwardSubscriptions( @Nonnull final ChannelAddress... channels )
{
final List<ChannelAddress> results = new ArrayList<>( channels.length );
for ( final ChannelAddress channel : channels )
{
if ( _outwardSubscriptions.contains( channel ) )
{
_outwardSubscriptions.remove( channel );
results.add( channel );
}
}
return results.toArray( new ChannelAddress[ 0 ] );
}
/**
* Return the channels that were auto-subscribed to the current channel.
*/
@Nonnull
public Set<ChannelAddress> getInwardSubscriptions()
{
return _roInwardSubscriptions;
}
/**
* Register the specified channel as inward links. Returns the set of links that were actually added.
*/
@Nonnull
public ChannelAddress[] registerInwardSubscriptions( @Nonnull final ChannelAddress... channels )
{
final List<ChannelAddress> results = new ArrayList<>( channels.length );
for ( final ChannelAddress channel : channels )
{
if ( !_inwardSubscriptions.contains( channel ) )
{
_inwardSubscriptions.add( channel );
results.add( channel );
}
}
return results.toArray( new ChannelAddress[ 0 ] );
}
/**
* Deregister the specified channels as outward links. Returns the set of links that were actually deregistered.
*/
@Nonnull
public ChannelAddress[] deregisterInwardSubscriptions( @Nonnull final ChannelAddress... channels )
{
final List<ChannelAddress> results = new ArrayList<>( channels.length );
for ( final ChannelAddress channel : channels )
{
if ( _inwardSubscriptions.contains( channel ) )
{
_inwardSubscriptions.remove( channel );
results.add( channel );
}
}
return results.toArray( new ChannelAddress[ 0 ] );
}
@Override
public int compareTo( @Nonnull final SubscriptionEntry o )
{
return getAddress().compareTo( o.getAddress() );
}
}
|
package nl.meg.propertiesutility;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
*
* @author meine
*/
public class Properties {
private final Map<String, String> properties = new HashMap<>();
public Properties(){
}
public void setProperty(String key, String value){
properties.put(key, value);
}
public String getProperty(String property){
return properties.get(property);
}
public String getProperty(String property, String defaultValue){
if(properties.containsKey(property)){
return properties.get(property);
}else{
return defaultValue;
}
}
public void load(InputStream in) throws IOException{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while((line = reader.readLine()) != null){
LineType type = getType(line);
switch(type){
case EMPTY:
break;
case COMMENT:
break;
case PROPERTY:
String key = line.substring(0, line.indexOf("="));
String value = line.substring(line.indexOf("=") + 1);
setProperty(key, value);
break;
default:
throw new IllegalArgumentException("Entered line invalid: " + line + ". Expected property or comment.");
}
}
} catch (IOException ex) {
System.err.println("Error reader line");
}finally{
in.close();
}
}
public void store (OutputStream out, String comments){
throw new NotImplementedException();
}
private LineType getType(String line){
if(line.isEmpty()){
return LineType.EMPTY;
}else if(line.startsWith("
return LineType.COMMENT;
}else{
return LineType.PROPERTY;
}
}
public enum LineType {
COMMENT, PROPERTY, EMPTY;
}
}
|
package org.voltcore.messaging;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
public class SiteMailbox implements Mailbox {
final HostMessenger m_hostMessenger;
final ArrayList<Deque<VoltMessage>> m_messages = new ArrayList<Deque<VoltMessage>>();
final long m_hsId;
public SiteMailbox(HostMessenger hostMessenger, long hsId) {
this.m_hostMessenger = hostMessenger;
this.m_hsId = hsId;
for (Subject s : Subject.values()) {
m_messages.add( s.getId(), new ArrayDeque<VoltMessage>());
}
}
@Override
public void deliverFront(VoltMessage message) {
deliver(message, true);
}
@Override
public void deliver(VoltMessage message) {
deliver(message, false);
}
public void deliver(VoltMessage message, final boolean toFront) {
assert(message != null);
final Deque<VoltMessage> dq = m_messages.get(message.getSubject());
synchronized (this) {
if (toFront) {
dq.offerFirst(message);
} else {
dq.offer(message);
}
this.notify();
}
}
@Override
public VoltMessage recv() {
return recv(m_defaultSubjects);
}
@Override
public VoltMessage recvBlocking() {
return recvBlocking(m_defaultSubjects);
}
private static final Subject m_defaultSubjects[] = new Subject[] { Subject.FAILURE, Subject.DEFAULT };
@Override
public VoltMessage recvBlocking(long timeout) {
return recvBlocking(m_defaultSubjects, timeout);
}
@Override
public void send(long hsId, VoltMessage message)
{
assert(message != null);
message.m_sourceHSId = m_hsId;
m_hostMessenger.send(hsId, message);
}
@Override
public void send(long[] hsIds, VoltMessage message)
{
assert(message != null);
assert(hsIds != null);
message.m_sourceHSId = m_hsId;
m_hostMessenger.send(hsIds, message);
}
@Override
public synchronized VoltMessage recv(Subject subjects[]) {
for (Subject s : subjects) {
final Deque<VoltMessage> dq = m_messages.get(s.getId());
assert(dq != null);
VoltMessage m = dq.poll();
if (m != null) {
return m;
}
}
return null;
}
@Override
public synchronized VoltMessage recvBlocking(Subject subjects[]) {
VoltMessage message = null;
while (message == null) {
for (Subject s : subjects) {
final Deque<VoltMessage> dq = m_messages.get(s.getId());
message = dq.poll();
if (message != null) {
return message;
}
}
try {
this.wait();
} catch (InterruptedException e) {
return null;
}
}
return null;
}
@Override
public synchronized VoltMessage recvBlocking(Subject subjects[], long timeout) {
VoltMessage message = null;
for (Subject s : subjects) {
final Deque<VoltMessage> dq = m_messages.get(s.getId());
message = dq.poll();
if (message != null) {
return message;
}
}
try {
this.wait(timeout);
} catch (InterruptedException e) {
return null;
}
for (Subject s : subjects) {
final Deque<VoltMessage> dq = m_messages.get(s.getId());
message = dq.poll();
if (message != null) {
return message;
}
}
return null;
}
/**
* Get the number of messages waiting to be delivered for this mailbox.
*
* @return An integer representing the number of waiting messages.
*/
public int getWaitingCount() {
return m_messages.get(Subject.DEFAULT.getId()).size();
}
@Override
public long getHSId() {
return m_hsId;
}
@Override
public void setHSId(long hsId) {
throw new UnsupportedOperationException();
}
}
|
package nl.mpi.kinnate.ui;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import nl.mpi.arbil.ImdiTree;
import nl.mpi.arbil.LinorgSessionStorage;
import nl.mpi.arbil.XsdChecker;
import nl.mpi.arbil.data.ImdiLoader;
import nl.mpi.arbil.data.ImdiTreeObject;
import nl.mpi.kinnate.gedcomimport.GedcomImporter;
public class GedcomImportPanel {
private ImdiTree leftTree;
private JTabbedPane jTabbedPane1;
public GedcomImportPanel(ImdiTree leftTreeLocal, JTabbedPane jTabbedPaneLocal) {
jTabbedPane1 = jTabbedPaneLocal;
leftTree = leftTreeLocal;
// private ImdiTree leftTree;
//// private GraphPanel graphPanel;
//// private JungGraph jungGraph;
// private ImdiTable previewTable;
// private ImdiTableModel imdiTableModel;
// private DragTransferHandler dragTransferHandler;
}
public void startImport(File importFile) {
startImport(importFile, null);
}
public void startImport(String importFileString) {
startImport(null, importFileString);
}
public void startImport(final File importFile, final String importFileString) {
new Thread() {
@Override
public void run() {
JTextArea importTextArea = new JTextArea();
JScrollPane importScrollPane = new JScrollPane(importTextArea);
jTabbedPane1.add("Import", importScrollPane);
jTabbedPane1.setSelectedComponent(importScrollPane);
JProgressBar progressBar = new JProgressBar();
progressBar.setVisible(true);
if (importFileString != null) {
new GedcomImporter().importTestFile(importTextArea, importFileString);
} else {
new GedcomImporter().importTestFile(importTextArea, importFile);
}
progressBar.setVisible(false);
String[] treeNodesArray = LinorgSessionStorage.getSingleInstance().loadStringArray("KinGraphTree");
if (treeNodesArray != null) {
ArrayList<ImdiTreeObject> tempArray = new ArrayList<ImdiTreeObject>();
for (String currentNodeString : treeNodesArray) {
try {
ImdiTreeObject currentImdiObject = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(currentNodeString));
tempArray.add(currentImdiObject);
// JTextPane fileText = new JTextPane();
XsdChecker xsdChecker = new XsdChecker();
if (xsdChecker.simpleCheck(currentImdiObject.getFile(), currentImdiObject.getURI()) != null) {
jTabbedPane1.add("XSD Error on Import", xsdChecker);
xsdChecker.checkXML(currentImdiObject);
xsdChecker.setDividerLocation(0.5);
}
currentImdiObject.reloadNode();
// try {
// fileText.setPage(currentNodeString);
// } catch (IOException iOException) {
// fileText.setText(iOException.getMessage());
// jTabbedPane1.add("ImportedFile", fileText);
} catch (URISyntaxException exception) {
System.err.println(exception.getMessage());
exception.printStackTrace();
}
}
leftTree.rootNodeChildren = tempArray.toArray(new ImdiTreeObject[]{});
// imdiTableModel.removeAllImdiRows();
// imdiTableModel.addImdiObjects(leftTree.rootNodeChildren);
}
leftTree.requestResort();
// GraphData graphData = new GraphData();
// graphData.readData();
// graphPanel.drawNodes(graphData);
}
}.start();
}
}
|
package org.axway.grapes.server.webapp.resources;
import org.axway.grapes.commons.datamodel.Artifact;
import org.axway.grapes.commons.datamodel.ArtifactQuery;
import org.axway.grapes.commons.datamodel.License;
import org.axway.grapes.commons.datamodel.Module;
import org.axway.grapes.commons.datamodel.Organization;
import org.axway.grapes.commons.utils.JsonUtils;
import org.axway.grapes.server.GrapesTestUtils;
import org.axway.grapes.server.config.GrapesServerConfig;
import org.junit.Test;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertNull;
import static org.mockito.Mockito.mock;
public class AbstractResourceTest {
@Test
public void checkModuleJsonModel(){
final FakeResource resource = new FakeResource();
Exception exception = null;
try {
final Module module = JsonUtils.unserializeModule(resource.getModuleJsonModel());
assertNotNull(module);
}catch (Exception e){
exception = e;
}
assertNull(exception);
}
@Test
public void checkOrganizationJsonModel(){
final FakeResource resource = new FakeResource();
Exception exception = null;
try {
final Organization organization = JsonUtils.unserializeOrganization(resource.getOrganizationJsonModel());
assertNotNull(organization);
}catch (Exception e){
exception = e;
}
assertNull(exception);
}
@Test
public void checkArtifactJsonModel(){
final FakeResource resource = new FakeResource();
Exception exception = null;
try {
final Artifact artifact = JsonUtils.unserializeArtifact(resource.getArtifactJsonModel());
assertNotNull(artifact);
}catch (Exception e){
exception = e;
}
assertNull(exception);
}
@Test
public void checkArtifactPromtotionInputMessage(){
final FakeResource resource = new FakeResource();
Exception exception = null;
try {
final String inputMessage = JsonUtils.serialize(resource.getArtifactPromtotionInputMessage());
assertNotNull(inputMessage);
}catch (Exception e){
exception = e;
}
assertNull(exception);
}
@Test
public void checkLicenseJsonModel(){
final FakeResource resource = new FakeResource();
Exception exception = null;
try {
final License license = JsonUtils.unserializeLicense(resource.getLicenseJsonModel());
assertNotNull(license);
}catch (Exception e){
exception = e;
}
assertNull(exception);
}
@Test
public void checkScopes(){
final FakeResource resource = new FakeResource();
Exception exception = null;
try {
assertNotNull(resource.getScopes());
}catch (Exception e){
exception = e;
}
assertNull(exception);
}
private class FakeResource extends AbstractResource {
protected FakeResource() {
super(GrapesTestUtils.getRepoHandlerMock(), GrapesTestUtils.getServiceHandlerMock(), "", mock(GrapesServerConfig.class));
}
}
}
|
// HttpRequest.java
package ed.net.httpserver;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.regex.*;
import javax.servlet.*;
import javax.servlet.http.*;
import ed.js.*;
import ed.util.*;
import ed.appserver.*;
import ed.net.URLDecoder;
/**
* Class to represent an HTTP request. The 10gen app server exposes the variable 'request'
* which is of this type.
*
* @expose
* @docmodule system.HTTP.request
*/
public class HttpRequest extends JSObjectLame implements HttpServletRequest , Sizable {
public static final String REAL_IP_HEADER = "X-Cluster-Client-Ip";
/**
* Generate a "dummy" request, coming from a browser trying to access the
* given URL.
* @param url a URL
*/
public static HttpRequest getDummy( String url ){
return getDummy( url , "" );
}
/**
* Generate a "dummy" request, coming from a browser trying to access a
* URL with some additional headers.
* @param url a URL
* @param extraHeaders a set of headers in HTTP format, separated by "\n"
*/
public static HttpRequest getDummy( String url , String extraHeaders ){
return getDummy( url , extraHeaders , "GET");
}
/**
* Generate a "dummy" request, coming from a browser trying to access a
* URL with some additional headers.
* @param url a URL
* @param extraHeaders a set of headers in HTTP format, separated by "\n"
* @param method http method to use, GET, POST, etc
*/
public static HttpRequest getDummy( String url , String extraHeaders, String method ){
return new HttpRequest( null , method + " " + url + " HTTP/1.0\n" + extraHeaders + "\n" );
}
/**
* Read a HttpRequest from a SocketHandler.
*/
HttpRequest( HttpServer.HttpSocketHandler handler , String header ){
_handler = handler;
_rawHeader = header;
int idx = header.indexOf( "\n" );
if ( idx < 0 )
throw new RuntimeException( "something is very wrong" );
_firstLine = header.substring( 0 , idx ).trim();
int start = idx + 1;
while ( ( idx = header.indexOf( "\n" , start ) ) >= 0 ) {
final String line = header.substring( start , idx ).trim();
start = idx + 1;
int foo = line.indexOf( ":" );
if ( foo > 0 )
_headers.put( line.substring( 0 , foo ).trim() ,
line.substring( foo + 1 ).trim() );
}
// parse first line
idx = _firstLine.indexOf( " " );
if ( idx < 0 )
throw new RuntimeException( "malformed" );
_command = _firstLine.substring( 0 , idx );
int endURL = _firstLine.indexOf( " " , idx + 1 );
if ( endURL < 0 ){
_url = _firstLine.substring( idx + 1 ).trim();
_http11 = false;
}
else {
_url = _firstLine.substring( idx + 1 , endURL ).trim();
_http11 = _firstLine.indexOf( "1.1" , endURL ) > 0;
}
int endURI = _url.indexOf( "?" );
if ( endURI < 0 ){
_fullPath = Encoding._unescape( _url );
_queryString = null;
}
else {
_fullPath = Encoding._unescape( _url.substring( 0 , endURI ) );
_queryString = _url.substring( endURI + 1 );
}
}
public StringBuffer getRequestURL(){
StringBuffer buf = new StringBuffer();
String host = getHeader( "Host" );
if ( host != null )
buf.append( "http://" ).append( host );
buf.append( _fullPath );
return buf;
}
public String getFullURL(){
String host = getHeader( "Host" );
if ( host == null )
return _url;
return "http://" + host + _url;
}
public String getFullPath(){
return _fullPath;
}
public String getServletPath(){
return "";
}
public String getRequestURI(){
return _fullPath;
}
public String getContextPath(){
int idx = _fullPath.lastIndexOf( "/" );
if ( idx < 0 )
return "";
return _fullPath.substring( 0 , idx );
}
/**
* Get translated result of getPathInfo(), after doing any
* virtual-to-physical mapping on it.
*/
public String getPathTranslated(){
return this.getPathInfo(); // TODO might need some virtual-to-physical mapping here
}
public String getPathInfo(){
return getFullPath();
}
public String getRealPath( String loc ){
throw new RuntimeException( "getRealPath doesn't work" );
}
/**
* Get the URI of the request (the path without hostname or query
* arguments).
*/
public String getURI(){
return _fullPath;
}
/**
* Get the URL of the request (the path and query arguments without
* hostname).
*/
public String getURL(){
return _url;
}
public String getDirectory(){
return getDirectory( _fullPath );
}
public static String getDirectory( String uri ){
String s = uri;
int idx = s.lastIndexOf( "/" );
return s.substring( 0 , idx + 1 );
}
/**
* Gets the request's entire HTTP header as an unparsed string.
* @return the entire HTTP header
*/
public String getRawHeader(){
return _rawHeader;
}
/**
* Gets the HTTP method used in making this request.
* This will be either GET, POST, HEAD, etc...
* @return the HTTP method used
*/
public String getMethod(){
return _command;
}
/**
* Returns the query string of a request as an unparsed string.
* For a request with URL "/foo?a=1", this method would return "a=1".
* @return the query part of the request, null if there was none.
*/
public String getQueryString(){
return _queryString;
}
/**
* Gets the total size of the HTTP request.
* @return the total size of the HTTP message, including header and body
*/
public int totalSize(){
int size = _rawHeader.length();
size += getIntHeader( "Content-Length" , 0 );
return size;
}
public long approxSize( IdentitySet seen ){
return totalSize();
}
/**
* Returns the request in an approximation of HTTP protocol.
*/
public String toString(){
_finishParsing();
return _command + " " + _fullPath + " HTTP/1." + ( _http11 ? "1" : "" ) + " : " + _headers + " " + _urlParameters + " " + _postParameters;
}
public String getScheme(){
return "http";
}
public String getProtocol(){
return "HTTP/1." + ( _http11 ? "1" : "0" );
}
public boolean isHttp11(){
return _http11;
}
/**
* @unexpose
*/
public boolean keepAlive(){
String c = getHeader( "connection" );
if ( c != null )
return ! c.equalsIgnoreCase( "close" );
return _http11;
}
public boolean gzip(){
String ua = getHeader( "User-Agent" );
if ( ua == null )
return false; // weird case, no gzip
if ( ua.indexOf( "MSIE 4" ) >= 0 )
return false;
String ae = getHeader( "Accept-Encoding" );
return ae != null && ae.toLowerCase().contains( "gzip" );
}
// header stuff
public String getReferer(){
return getHeader( "referer" );
}
public String getRefererNoHost(){
String s = getReferer();
if ( s == null )
return null;
if ( s.startsWith( "http:
int idx = s.indexOf( "/" , 8 );
s = s.substring( idx );
}
return s;
}
/**
* Returns the hostname this request was directed at. This works by using
* the Host header (mandated by HTTP/1.1), and subtracting any port
* information (if any).
* @return the host to which this request was sent as a string
*/
public String getHost(){
String host = getHeader( "Host" );
if ( host == null )
return null;
host = host.trim();
if ( host.length() == 0 )
return null;
int idx = host.indexOf( ":" );
if ( idx == 0 )
return null;
if ( idx > 0 ){
host = host.substring( 0 , idx ).trim();
if ( host.length() == 0 )
return null;
}
return host;
}
/**
* Returns the port this request was directed at. This works by using the
* Host header (mandated by HTTP/1.1), and subtracting the hostname.
* @return the port this request was for
*/
public int getPort(){
String host = getHeader( "Host" );
if ( host == null )
return 0;
int idx = host.indexOf( ":" );
if ( idx < 0 )
return 0;
return StringParseUtil.parseInt( host.substring( idx + 1 ) , 0 );
}
public String getContentType(){
return getHeader( "Content-Type" );
}
public int getContentLength(){
return getIntHeader( "Content-Length" , -1 );
}
public int getServerPort(){
return getLocalPort();
}
public int getLocalPort(){
int p = getPort();
if ( p <= 0 )
return 80;
return p;
}
public String getServerName(){
return getHost();
}
public String getLocalAddr(){
return LOCALHOST.getHostAddress();
}
public String getLocalName(){
return LOCALHOST.getHostName();
}
public RequestDispatcher getRequestDispatcher( String path ){
throw new RuntimeException( "no getRequestDispatcher()" );
}
public JSObject getHeadersObject(){
return new JSDict( _headers );
}
/**
* Gets a raw HTTP header specified by the parameter.
* @param h the name of an HTTP header. Case insensitive.
* @return the header as a string or null
*/
public String getHeader( String h ){
return _headers.get( h );
}
public Enumeration getHeaders( String h ){
String v = getHeader( h );
if ( v == null )
return null;
LinkedList ll = new LinkedList();
ll.add( v );
return new CollectionEnumeration( ll );
}
public int getIntHeader( String h ){
return getIntHeader( h , -1 );
}
/**
* Gets a http header parsed into an int.
* If the header wasn't sent or can't be parsed as an int, def is returned.
* @param h the name of an HTTP header. Case insensitive.
* @return the header parsed as an int
*/
public int getIntHeader( String h , int def ){
return StringParseUtil.parseInt( getHeader( h ) , def );
}
public boolean getBooleanHeader( String h , boolean def ){
return StringParseUtil.parseBoolean( getHeader( h ) , def );
}
public long getDateHeader( String name ){
String v = getHeader( name );
if ( v == null )
return -1;
return JSDate.parseDate( v.trim() , -1 );
}
/**
* Get every HTTP header that was sent as an array of header names.
* @return an array of HTTP header names
*/
public Enumeration getHeaderNames(){
JSArray a = new JSArray();
a.addAll( _headers.keySet() );
return a.getEnumeration();
}
public Set<String> getHeaderNameKeySet(){
return _headers.keySet();
}
// cookies
/**
* Get the value for a cookie, specified by name.
* @param s a cookie name
* @return the cookie value. null if it doesn't exist
*/
public String getCookie( String s ){
if ( _cookies == null ){
JSObjectBase m = new JSObjectBase();
String temp = getHeader( "Cookie" );
if ( temp != null ){
for ( String thing : temp.split( ";" ) ){
int idx = thing.indexOf("=");
if ( idx < 0 )
continue;
m.set( thing.substring( 0 , idx ).trim() ,
thing.substring( idx + 1 ).trim() );
}
}
_cookies = m;
}
return _cookies.getAsString( s );
}
/**
* Gets the names of all cookies sent in this request.
* @return array of cookie names
*/
public JSArray getCookieNames(){
getCookie( "" );
JSArray a = new JSArray();
a.addAll( _cookies.keySet() );
return a;
}
/**
* Expose cookies as a JavaScript object.
* This is so you can request.getCookies().username
* NOTE: you can't add cookies using this object.
* @return all cookies as a JavaScript obejct
*/
public JSObject getCookiesObject(){
getCookie( "" );
return _cookies;
}
public Cookie[] getCookies(){
Collection<String> names = _cookies.keySet( false );
Cookie[] cookies = new Cookie[names.size()];
int i=0;
for ( String n : names )
cookies[i++] = new Cookie( n , _cookies.get( n ).toString() );
return cookies;
}
// param stuff
/**
* Gets all the parameter names specified in this request.
* This includes both GET and POST parameters.
* @return an array of parameter names
*/
public JSArray getParameterNamesArray(){
_finishParsing();
JSArray a = new JSArray();
for ( String s : _urlParameters.keySet() )
a.add( new JSString( s ) );
for ( String s : _postParameters.keySet() ){
JSString js = new JSString( s );
if ( ! a.contains( js ) )
a.add( js );
}
return a;
}
public Enumeration getParameterNames(){
return getParameterNamesArray().getEnumeration();
}
/**
* Parses the parameter specified by n as a boolean.
* If it doesn't exist, or can't be parsed as a boolean, def is returned.
* @param n the parameter to look up
* @return true/false if the paramater was specified, or def otherwise
*/
public boolean getBoolean( String n , boolean def ){
return StringParseUtil.parseBoolean( getParameter( n ) , def );
}
/**
* Parses the parameter specified by n as an int.
* If it doesn't exist, or can't be parsed as an int, def is returned.
* @param n the parameter to look up.
* @return number if parameter is specified, or def otherwise
*/
public int getInt( String n , int def ){
return StringParseUtil.parseInt( getParameter( n ) , def );
}
List<String> _getParameter( String name ){
List<String> l = _postParameters.get( name );
if ( l != null )
return l;
return _urlParameters.get( name );
}
/**
* Return all the parameters given for a key.
* This is used when you have multiple values for the same parameter.
* i.e. if this request was created with the URL "/foo?a=1&a=2",
* calling getParameters("a") would return [ "1" , "2" ].
* @param name a parameter name
* @return array of all values associated with this parameter
*/
public JSArray getParameters( String name ){
_finishParsing();
List<String> lst = _getParameter( name );
if ( lst == null )
return null;
JSArray a = new JSArray();
for ( String s : lst )
a.add( new JSString( s ) );
return a;
}
public String[] getParameterValues( String name ){
_finishParsing();
List<String> lst = _getParameter( name );
if ( lst == null )
return null;
String[] s = new String[lst.size()];
lst.toArray( s );
return s;
}
public Map<String,String> getParameterMap(){
_finishParsing();
Map<String,String> m = new HashMap<String,String>();
_addAll( m , _urlParameters );
_addAll( m , _postParameters );
return m;
}
private void _addAll( Map<String,String> to , Map<String,List<String>> from ){
for ( String name : from.keySet() ){
List<String> lst = from.get( name );
if ( lst == null || lst.size() == 0 )
continue;
to.put( name , lst.get(0) );
}
}
/**
* Return any value for the parameter specified by name.
* This returns the "first" value for this parameter.
* @return string value of the parameter specified by name, null if none
*/
public String getParameter( String name ){
return getParameter( name , null );
}
public String param( String name ){
return getParameter( name );
}
/**
* Return any value for the parameter specified by name.
* This returns the "first" value for the parameter, or def if this
* parameter was not given.
* @param name the name of the parameter to look up
* @param def a default in case the parameter wasn't given
* @return string value of the parameter specified by name, def if
* none
*/
public String getParameter( String name , String def ){
_finishParsing();
List<String> s = _getParameter( name );
if ( s != null && s.size() > 0 )
return s.get(0);
return def;
}
/**
* Gets all values for the parameter specified by name from either
* the query arguments or the POST arguments. If post is true,
* get all the values from the POST; otherwise, get them from the
* query arguments.
* @param name the name of a parameter to look up
* @param post true to consult the POST; false to consult the URL
* @return an array of parameter values as strings
*/
public JSArray getParameters( String name , boolean post ){
List<String> lst = post ? _postParameters.get( name ) : _urlParameters.get( name );
if ( lst == null )
return null;
JSArray a = new JSArray();
for ( String s : lst )
a.add( new JSString( s ) );
return a;
}
/**
* Gets one value for a parameter specified by name from either the
* query arguments or the POST arguments. Returns null if none was found.
* @param name the name of the parameter to look up
* @param post true to consult the POST; false to consult the URL
* @return a parameter value as a string
*/
public String getParameter( String name , boolean post ){
return getParameter( name , null , post );
}
/**
* Gets one value for a parameter specified by name from either
* the query arguments or the POST arguments, defaulting to def if
* none was found.
* @param name the name of the parameter to look up
* @param def the default to use if none is found
* @param post true to consult the POST; false to consult the URL
* @return a parameter value as a string
*/
public String getParameter( String name , String def , boolean post ){
_finishParsing();
List<String> lst = post ? _postParameters.get( name ) : _urlParameters.get( name );
if ( lst != null && lst.size() > 0 )
return lst.get(0);
return def;
}
/**
* Gets all parameters matching the name from the POST.
* @param name the name of the parameter to look up
* @return an array of all the values for the matching parameters
* in the POST
*/
public JSArray getPostParameters( String name ){
return getParameters( name , true );
}
public JSObject getPostParameters(){
_finishParsing();
return _paramsAsObject( _postParameters );
}
/**
* Gets the first parameter matching the name from the POST.
* @param name the name of the parameter to look up
* @return the value of the first matching parameter in the POST
*/
public String getPostParameter( String name ){
return getParameter( name , null , true );
}
/**
* Gets the first parameter matching the name from the POST.
* @param name the name of the parameter to look up
* @param def the default to use if no matching parameter is found
* @return the value of the first matching parameter in the POST,
* or def if none
*/
public String getPostParameter( String name , String def ){
return getParameter( name , def , true );
}
/**
* Gets all parameters matching the name from the URL.
* @param name the name of the parameter to look up
* @return an array of all the values for the matching parameters
* in the URL
*/
public JSArray getURLParameters( String name ){
return getParameters( name , false );
}
public JSObject getURLParameters(){
_finishParsing();
return _paramsAsObject( _urlParameters );
}
/**
* Gets the first parameter matching the name from the URL, or
* null if none is found.
* @param name the name of the parameter to look up
* @return the value of the first matching parameter in the URL,
* or null if none
*/
public String getURLParameter( String name ){
return getParameter( name , null , false );
}
/**
* Gets the first parameter matching the name from the URL.
* @param name the name of the parameter to look up
* @param def the default to use if no matching parameter is found
* @return the value of the first matching parameter in the URL,
* or def if none
*/
public String getURLParameter( String name , String def ){
return getParameter( name , def , false );
}
/**
* Adds a parameter to this request.
* @param name the name of the parameter to add
* @param val the value of the parameter to add
*/
public void addParameter( String name , Object val ){
_finishParsing();
_addParm( name , val == null ? null : val.toString() , true );
}
/**
* Handler for setting attributes on this request.
* Currently, overwrite all previous parameters with the given name,
* and to convert all values to strings.
* @jsset
* @param n the name of the parameter to set
* @param v the value to set as a string or an object with a
* toString() method
*/
public Object set( Object n , Object v ){
return _attributes.set( n , v );
}
/**
* Handler for getting an attribute from this object.
* Equivalent to <tt>getParameter( attribute )</tt>.
* @jsget
* @param n the name of the attribute to get
* @return the value of any parameter with this name, as a string
*/
public Object get( Object n ){
Object blah = _attributes.get( n );
if ( blah != null )
return blah;
final String name = n.toString();
String foo = getParameter( name , null );
if ( foo == null )
return null;
return new ed.js.JSString( foo );
}
/**
* attribuets are user setable things on a request
* you can do
* request.foo = 5;
* and later get
* request.foo
* @return an object that you can modify or access parameters on
*/
public JSObject getAttributes(){
return _attributes;
}
/**
* Get an uploaded file field from this request, or null if none.
* Files are uploaded in POSTs like other form fields, and have
* names like other form fields. This fetches a form value as a
* file.
* @param name the name to look up in the POST
* @return the file corresponding to this name
*/
public UploadFile getFile( String name ){
if ( _postData == null )
return null;
return _postData._files.get( name );
}
/**
* @unexpose
*/
public Object setInt( int n , Object v ){
throw new RuntimeException( "can't set things on an HttpRequest" );
}
/**
* @unexpose
*/
public Object getInt( int n ){
throw new RuntimeException( "you're stupid" );
}
/**
* Handler for iterating over all the keys in this request.
* @return all the keys in the URL and the POST
*/
public Set<String> keySet( boolean includePrototype ){
Set<String> s = new HashSet<String>();
s.addAll( _urlParameters.keySet() );
s.addAll( _postParameters.keySet() );
s.addAll( _attributes.keySet() );
return s;
}
public boolean containsKey( String s ){
return
_attributes.containsKey( s ) ||
_urlParameters.containsKey( s ) ||
_postParameters.containsKey( s );
}
public boolean containsKey( String s , boolean includePrototype ){
return containsKey( s );
}
/**
* Get the names of all the parameters in the URL.
* @return the names of all the parameters in the URL
*/
public Set<String> getURLParameterNames(){
return _urlParameters.keySet();
}
/**
* Get the names of all the parameters in the POST.
* @return the names of all the parameters in the POST
*/
public Set<String> getPostParameterNames(){
return _postParameters.keySet();
}
private final String _urlDecode( String s ){
try {
return URLDecoder.decode( s , "UTF-8" );
}
catch ( Exception e ){}
try {
return URLDecoder.decode( s , _characterEncoding );
}
catch ( Exception e ){}
try {
return URLDecoder.decode( s );
}
catch ( Exception e ){}
return s;
}
/**
* Sets parameters in the request according to the given regular
* expression. The regular expression is matched against the URI,
* and the captured groups in the regular expression become
* parameters of the request with the names supplied by the <tt>names</tt>
* parameter.
* @param regex a regular expression to match against a URL
* @param names the names of the parameters to fit to the captured
* subgroups
* @return true if the regular expression matched
*/
public boolean applyServletParams( JSRegex regex , JSArray names ){
Matcher m = regex.getCompiled().matcher( getURI() );
if ( ! m.find() )
return false;
for ( int i=1; i<=m.groupCount() && ( i - 1 ) < names.size() ; i++ )
_addParm( names.get( i - 1 ).toString() , m.group( i ) , false );
return true;
}
private void _finishParsing(){
if ( ! _parsedURL ){
_parsedURL = true;
if ( _queryString != null ){
int start = 0;
while ( start < _queryString.length() ){
int amp = _queryString.indexOf("&",start );
String thing = null;
if ( amp < 0 ){
thing = _queryString.substring( start );
start = _queryString.length();
}
else {
thing = _queryString.substring( start , amp );
start = amp + 1;
while ( start < _queryString.length() && _queryString.charAt( start ) == '&' )
start++;
}
int eq = thing.indexOf( "=" );
if ( eq < 0 )
_addParm( thing , null , false );
else
_addParm( thing.substring( 0 , eq ) , thing.substring( eq + 1 ) , false );
}
}
}
if ( ! _parsedPost && _postData != null && _command.equalsIgnoreCase( "POST" ) ){
_parsedPost = true;
_postData.go( this );
}
}
/**
* @unexpose
*/
void _addParm( String n , String val , boolean post ){
n = n.trim();
n = _urlDecode( n ); // TODO: check that i really should do this
List<String> lst = _getParamList( n , post , true );
if ( val == null ){
lst.add( val );
return;
}
val = val.trim();
val = _urlDecode( val );
lst.add( val );
}
List<String> _getParamList( String name , boolean post , boolean create ){
Map<String,List<String>> m = post ? _postParameters : _urlParameters;
List<String> l = m.get( name );
if ( l != null || ! create )
return l;
l = new ArrayList<String>();
m.put( name , l );
return l;
}
private JSObjectBase _paramsAsObject( Map<String,List<String>> params ){
JSObjectBase o = new JSObjectBase();
for ( String key : params.keySet() ){
List<String> l = params.get( key );
if ( l == null || l.size() == 0 )
continue;
if ( l.size() == 1 )
o.set( key , new JSString( l.get(0) ) );
else
o.set( key , new JSArray( l ) );
}
return o;
}
public AppRequest getAppRequest(){
return _appRequest;
}
/**
* @unexpose
*/
public void setAppRequest( AppRequest req ){
if ( _appRequest != null )
throw new RuntimeException( "req already set" );
_appRequest = req;
}
/**
* @unexpose
*/
public PostData getPostData(){
return _postData;
}
/**
* Gets the time at which this request started.
* @return date at which request started
*/
public JSDate getStart(){
return _start;
}
/**
* @unexpose
*/
public long[] getRange(){
if ( _rangeChecked )
return _range;
String s = getHeader( "Range" );
if ( s != null )
_range = _parseRange( s );
_rangeChecked = true;
return _range;
}
public String getPhysicalRemoteAddr(){
if ( _handler == null )
return null;
InetAddress addr = _handler.getInetAddress();
if ( addr == null )
return null;
return addr.getHostAddress();
}
/**
* Gets the ip of the client as a string.
* @return the ip of the client
*/
public String getRemoteIP(){
if ( _remoteIP != null )
return _remoteIP;
String ip = getHeader( HttpRequest.REAL_IP_HEADER );
if ( ip == null )
ip = getPhysicalRemoteAddr();
_remoteIP = ip;
return _remoteIP;
}
public String getRemoteAddr(){
return getRemoteIP();
}
public String getRemoteHost(){
// TODO: make this a host name
return getRemoteIP();
}
public int getRemotePort(){
return _handler.getRemotePort();
}
/**
* @unexpose
*/
public static long[] _parseRange( String s ){
if ( s == null )
return null;
s = s.trim();
if ( ! s.startsWith( "bytes=" ) )
return null;
s = s.substring( 6 ).trim();
if ( s.length() == 0 )
return null;
if ( s.matches( "\\d+" ) )
return new long[]{ Long.parseLong( s ) , Long.MAX_VALUE };
String pcs[] = s.split( "," );
if ( pcs.length == 0 )
return null;
if ( pcs.length == 1 ){
// either has to be
// -100
s = pcs[0].trim();
if ( s.length() == 0 )
return null;
if ( s.charAt( 0 ) == '-' ) // we don't support this
return null;
Matcher m = Pattern.compile( "(\\d+)\\-(\\d+)" ).matcher( s );
if ( m.find() )
return new long[]{ Long.parseLong( m.group(1) ) , Long.parseLong( m.group(2) ) };
return null;
}
long min = Long.MAX_VALUE;
long max = -1;
for ( int i=0; i<pcs.length; i++ ){
String foo = pcs[i];
Matcher m = Pattern.compile( "(\\d+)\\-(\\d+)" ).matcher( s );
if ( ! m.find() )
return null;
long l = Long.parseLong( m.group(1) );
long h = Long.parseLong( m.group(2) );
min = Math.min( min , l );
max = Math.max( min , h );
}
if ( max < 0 )
return null;
return new long[]{ min , max };
}
public boolean isRequestedSessionIdFromCookie(){
return true;
}
public boolean isRequestedSessionIdFromUrl(){
return false;
}
public boolean isRequestedSessionIdFromURL(){
return false;
}
public boolean isRequestedSessionIdValid(){
return true;
}
public String getRequestedSessionId(){
return getCookie( Session.COOKIE_NAME );
}
public Session getSession( boolean b ){
return getSession();
}
public Session getSession(){
if ( _appRequest == null )
return null;
return _appRequest.getSession();
}
public String getAuthType(){
System.err.println( "ed.net.httpserver.HttpRequest : User stuff not really supported (getAuthType)" );
return null;
}
public String getRemoteUser(){
System.err.println( "ed.net.httpserver.HttpRequest : User stuff not really supported (getRemoteUser)" );
return null;
}
public java.security.Principal getUserPrincipal(){
System.err.println( "ed.net.httpserver.HttpRequest : User stuff not really supported (getUserPrincipal)" );
return null;
}
public boolean isUserInRole( String role){
System.err.println( "ed.net.httpserver.HttpRequest : User stuff not really supported (isUserInRole)" );
return false;
}
public Locale getLocale(){
throw new RuntimeException( "Locale stuff doesn't work yet" );
}
public Enumeration getLocales(){
throw new RuntimeException( "Locale stuff doesn't work yet" );
}
public boolean isSecure(){
return false;
}
public Object getAttribute( String name ){
throw new RuntimeException( "no attribuets yet" );
}
public Enumeration getAttributeNames(){
throw new RuntimeException( "no attribuets yet" );
}
public void removeAttribute( String name ){
throw new RuntimeException( "no attribuets yet" );
}
public void setAttribute(String name, Object o ){
throw new RuntimeException( "no attribuets yet" );
}
public BufferedReader getReader(){
throw new RuntimeException( "can't get a raw reader" );
}
public ServletInputStream getInputStream(){
if ( _postData != null )
return _postData.getInputStream();
return new EmptyInputStream();
}
public void setCharacterEncoding( String env ){
throw new RuntimeException( "can't set character encoding" );
}
public String getCharacterEncoding(){
return _characterEncoding;
}
public static class EmptyInputStream extends ServletInputStream {
public int read(){
return -1;
}
}
public long created(){
return _startTime;
}
public long elapsed(){
return System.currentTimeMillis() - _startTime;
}
public int hashCode( IdentitySet seen ){
return System.identityHashCode(this);
}
final long _startTime = System.currentTimeMillis();
final HttpServer.HttpSocketHandler _handler;
final String _firstLine;
final Map<String,String> _headers = new StringMap<String>();
final JSDate _start = new JSDate();
JSObjectBase _cookies;
String _remoteIP;
boolean _parsedPost = false;
PostData _postData;
boolean _parsedURL = false;
final JSObject _attributes = new JSObjectBase();
final Map<String,List<String>> _urlParameters = new StringMap<List<String>>();
final Map<String,List<String>> _postParameters = new StringMap<List<String>>();
final String _rawHeader;
final String _command;
final String _url;
final String _fullPath;
final String _queryString;
final boolean _http11;
private AppRequest _appRequest;
private boolean _rangeChecked = false;
private long[] _range;
private String _characterEncoding = "ISO-8859-1";
private static InetAddress LOCALHOST;
static {
try {
LOCALHOST = InetAddress.getLocalHost();
}
catch ( Exception e ){
e.printStackTrace();
System.err.println( "exiting" );
System.exit(-1);
}
}
}
|
package org.animotron.manipulator;
import org.animotron.exception.AnimoException;
import org.animotron.io.PipedInput;
import org.animotron.statement.operator.AN;
import org.animotron.statement.operator.THE;
import org.animotron.statement.operator.Utils;
import org.neo4j.graphdb.Relationship;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;
import javolution.util.FastSet;
import javolution.util.FastTable;
import static org.animotron.utils.MessageDigester.longToByteArray;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class QCAVector {
private final Relationship question;
private Relationship answer = null;
private List<QCAVector> answers = null;
private List<QCAVector> context = null;
private QCAVector preceding_sibling = null;
private static boolean debug = false;
public QCAVector(Relationship question) {
this.question = question;
if (debug) System.out.println(" .... create vector 1 .... ");
}
public QCAVector(Relationship question, Relationship answer) {
this.question = question;
this.answer = answer;
if (debug) System.out.println(" .... create vector 2 .... ");
}
public QCAVector(Relationship question, QCAVector context, Relationship answer) {
this.question = question;
if (context != null) {
this.context = new FastTable<QCAVector>();
this.context.add(context);
}
this.answer = answer;
if (debug) System.out.println(" .... create vector 3 .... ");
}
public QCAVector(Relationship question, QCAVector context) {
this.question = question;
this.context = new FastTable<QCAVector>();
this.context.add(context);
if (debug) System.out.println(" .... create vector 4 .... ");
}
public QCAVector(Relationship question, List<QCAVector> context) {
this.question = question;
this.context = context;
if (debug) System.out.println(" .... create vector 4 .... ");
}
public QCAVector(Relationship question, Relationship answer, QCAVector context) {
this.question = question;
this.answer = answer;
this.context = new FastTable<QCAVector>();
this.context.add(context);
if (debug) System.out.println(" .... create vector 5 .... ");
}
public QCAVector(Relationship question, Relationship answer, List<QCAVector> context) {
this.question = question;
this.answer = answer;
this.context = context;
if (debug) System.out.println(" .... create vector 6 .... ");
}
public QCAVector(Relationship question, Relationship answer, List<QCAVector> context, QCAVector preceding_sibling) {
this.question = question;
this.answer = answer;
this.context = context;
this.preceding_sibling = preceding_sibling;
if (debug)
if (preceding_sibling == this)
System.out.println(" .... create vector 7 .... "+this);
}
public QCAVector(Relationship question, Relationship context, Relationship answer) {
this.question = question;
this.answer = answer;
this.context = new FastTable<QCAVector>();
this.context.add(new QCAVector(null, answer));
if (debug) System.out.println(" .... create vector 8 .... ");
}
public QCAVector(Relationship question, QCAVector context, QCAVector precedingSibling) throws AnimoException {
this.question = question;
//this.answer = answer;
this.context = new FastTable<QCAVector>();
this.context.add(context);
this.preceding_sibling = precedingSibling;
if (debug)
if (preceding_sibling == this)
System.out.println(" .... create vector 9 .... "+this);
cyclingDetection(question);
}
protected void cyclingDetection(Relationship op) throws AnimoException {
if (context != null)
for (QCAVector v : context)
if (v.haveRelationship(op))
throw new AnimoException(op, "cycling detected for "+op.getId()+" at "+this);
if (preceding_sibling != null)
preceding_sibling.cyclingDetection(op);
}
public Relationship getClosest() {
if (answer != null) return getAnswer();
return question;
}
public Relationship getUnrelaxedClosest() {
if (answer != null) return answer;
return question;
}
public Relationship getQuestion() {
return question;
}
public void setAnswer(Relationship r) {
answer = r;
}
public Relationship getAnswer() {
return Utils.relax(answer);
}
public Relationship getUnrelaxedAnswer() {
return answer;
}
public void addContext(List<QCAVector> cs) {
if (context == null)
context = cs;
else
context.addAll(cs);
}
public List<QCAVector> getContext() {
return context;
}
public void setPrecedingSibling(QCAVector prev) {
if (preceding_sibling == this) {
System.out.println("setPrecedingSibling "+preceding_sibling);
System.out.println(prev);
}
preceding_sibling = prev;
}
public QCAVector getPrecedingSibling() {
if (preceding_sibling == this) {
System.out.println("getPrecedingSibling "+preceding_sibling);
System.out.println(this);
}
return preceding_sibling;
}
public boolean questionEquals(QCAVector vector) {
return question.equals(vector.question);
}
protected void collectHash(DataOutputStream dos) throws IOException {
if (question != null) dos.writeLong(question.getId());
if (answer != null) dos.writeLong(answer.getId());
//System.out.println(" hash "+super.hashCode());
if (context != null) {
for (QCAVector c : context) {
//System.out.println(" - hash "+super.hashCode());
c.collectHash(dos);
}
}
}
public byte[] mashup() {
//XXX: what is this?
return longToByteArray(answer.getId());
}
public void debug(StringBuilder b, FastSet<Relationship> visited) {
b.append("QCA(");
if (question == null)
b.append("NULL");
else {
if (visited.contains(question)) {
b.append(" cycling detected "+question);
return;
}
b.append(question.getId());
b.append(" '");
b.append(question.getType());
b.append("'");
try {
PipedInput<QCAVector> thes = AN.getREFs(null, new QCAVector(question));
for (QCAVector v : thes) {
Object name = THE._.reference(v.getClosest());
if (name != null) {
b.append(" ");
b.append(name);
}
}
} catch (Exception e) {
}
}
b.append(" {");
if (context != null) {
int i = 0;
for (QCAVector c : context) {
b.append(i); i++;
b.append("=");
c.debug(b, visited);
}
}
b.append("}");
if (answer != null) {
if (visited.contains(answer)) {
b.append(" cycling detected "+answer);
return;
}
b.append(" ");
b.append(answer.getId());
b.append(" '");
b.append(answer.getType());
b.append("'");
}
if (answers != null) {
b.append(" *");
boolean first = true;
for (QCAVector a : answers) {
if (!first)
b.append(", ");
else
first = false;
a.debug(b, visited);
}
b.append("*");
}
b.append(")");
}
public String toString() {
StringBuilder b = new StringBuilder();
FastSet<Relationship> visited = new FastSet<Relationship>();
b.append("[");
b.append(super.hashCode());
b.append("] ");
if (debug) System.out.println("DEBUG START");
debug(b, visited);
if (debug) System.out.println("DEBUG END");
return b.toString();
}
public boolean haveRelationship(Relationship r) {
if (r == null)
return false;
boolean debug = false;
long id = r.getId();
if (debug) System.out.print("haveRelationship "+question+" ("+question.getType()+") ");
if (question != null && question.getId() == id) return true;
if (debug && answer != null) {
System.out.print("answers "+answer+" ("+answer.getType()+") ");
Relationship a = getAnswer();
System.out.print(a+" ("+a.getType()+") ");
}
if (debug) System.out.println();
if (answer != null && (answer.getId() == id || getAnswer().getId() == id)) return true;
if (context != null) {
for (QCAVector c : context) {
if (c.haveRelationship(r))
return true;
}
}
if (preceding_sibling != null)
return preceding_sibling.haveRelationship(r);
return false;
}
public boolean canBeMerged(QCAVector vector) {
if (question == null
|| vector.question == null
|| answer != null
|| context != null
)
return false;
if (question.getId() != vector.question.getId()) return false;
return true;
}
public boolean merged(QCAVector vector) {
if (canBeMerged(vector)) {
answer = vector.answer;
context = vector.context;
return true;
}
return false;
}
public int hashCode() {
int hash = 0;
if (question != null) hash += question.getId();
if (answer != null) hash += answer.getId();
return hash;
}
public boolean equals(Object o) {
if (o == null || !(o instanceof QCAVector)) {
return false;
}
QCAVector oV = (QCAVector) o;
//XXX:check context too?
if ((question == null && oV.question == null)
|| (question != null && oV.question != null && question.equals(oV.question)))
if ((answer == null && oV.answer == null)
|| (answer != null && oV.answer != null && answer.equals(oV.answer)))
return true;
return false;
}
public QCAVector answered(Relationship createdAnswer) {
if (preceding_sibling == this)
System.out.println("!!!answered 1 "+this);
return new QCAVector(question, createdAnswer, context, preceding_sibling);
}
public QCAVector answered(Relationship createdAnswer, QCAVector context) {
//context.removeThis(this);
if (preceding_sibling == this)
System.out.println("!!!answered 2 "+this);
FastTable<QCAVector> c = new FastTable<QCAVector>();
c.add(context);
if (this.context != null) {
for (QCAVector v : this.context) {
if (v == context) continue;
c.add(v);
}
}
return new QCAVector(question, createdAnswer, c, preceding_sibling);
}
public QCAVector answered(Relationship createdAnswer, List<QCAVector> contexts) {
if (preceding_sibling == this)
System.out.println("!!!answered 3 "+this);
return new QCAVector(question, createdAnswer, contexts, preceding_sibling);
}
public QCAVector question(Relationship q) {
if (question != null && question.equals(q) && answer == null)
return this;
return new QCAVector(q, this);
}
public QCAVector question2(Relationship q) {
if (question != null && question.equals(q) && answer == null)
return this;
if (answer == null) {
QCAVector v = new QCAVector(q, context);
v.setPrecedingSibling(this);
return v;
}
return new QCAVector(q, this);
}
public QCAVector question(Relationship q, QCAVector prev) throws AnimoException {
if (question != null && question.equals(q) && preceding_sibling == prev && answer == null)
return this;
cyclingDetection(q);
//System.out.println("question "+this);
//System.out.println(prev);
return new QCAVector(q, this, prev);
}
public void addAnswer(QCAVector i) {
if (answers == null)
answers = new FastTable<QCAVector>();
answers.add(i);
}
public List<QCAVector> getAnswers() {
return answers;
}
public void recycle() {
if (context != null) {
for (QCAVector c : context)
c.recycle();
if (context instanceof FastTable)
FastTable.recycle((FastTable<QCAVector>) context);
}
if (answers != null) {
for (QCAVector c : answers)
c.recycle();
if (answers instanceof FastTable)
FastTable.recycle((FastTable<QCAVector>) answers);
}
}
public boolean haveAnswer() {
return (
(answers != null)
|| (
(getUnrelaxedAnswer() != null) &&
(getUnrelaxedAnswer().equals(getQuestion()))
)
);
}
}
|
package com.ctrip.xpipe.service.metric;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import com.ctrip.framework.foundation.Foundation;
import com.ctrip.xpipe.concurrent.AbstractExceptionLogTask;
import com.ctrip.xpipe.concurrent.DefaultExecutorFactory;
import com.ctrip.xpipe.endpoint.HostPort;
import com.ctrip.xpipe.metric.*;
import com.ctrip.xpipe.service.foundation.CtripFoundationService;
import com.ctrip.xpipe.utils.VisibleForTesting;
import io.netty.util.HashedWheelTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.hickwall.proxy.HickwallClient;
import com.ctrip.hickwall.proxy.common.DataPoint;
import com.ctrip.xpipe.utils.XpipeThreadFactory;
/**
* @author shyin
*
* Jan 6, 2017
*/
public class HickwallMetric implements MetricProxy {
private static Logger logger = LoggerFactory.getLogger(HickwallMetric.class);
private HickwallConfig config = new HickwallConfig();
private BlockingQueue<DataPoint> datas;
private HickwallClient client;
private ArrayList<DataPoint> dataToSend = null;
private static final int NUM_MESSAGES_PER_SEND = 100;
private static final int HICKWALL_SEND_INTERVAL = 2000;
public HickwallMetric() {
start();
}
private void start() {
logger.info("Hickwall proxy started.");
datas = new ArrayBlockingQueue<>(config.getHickwallQueueSize());
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1,
XpipeThreadFactory.create("HickwallSender", true));
tryUntilConnected();
scheduled.scheduleWithFixedDelay(new AbstractExceptionLogTask() {
@Override
protected void doRun() throws Exception {
while(datas.size() >= NUM_MESSAGES_PER_SEND) {
if (dataToSend == null) {
dataToSend = new ArrayList<>();
datas.drainTo(dataToSend, NUM_MESSAGES_PER_SEND);
}
try {
client.send(dataToSend);
dataToSend = null;
} catch (IOException e) {
logger.error("Error write data to metric server{}", config.getHickwallHostPort(), e);
tryUntilConnected();
} catch (Exception e) {
logger.error("Error write data to metric server{}", config.getHickwallHostPort(), e);
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
}
}
}, HICKWALL_SEND_INTERVAL, HICKWALL_SEND_INTERVAL, TimeUnit.MILLISECONDS);
}
private void tryUntilConnected() {
while(! Thread.currentThread().isInterrupted()) {
String hickwallHostPort = config.getHickwallHostPort();
try {
logger.info("[tryUntilConnected][begin]{}", hickwallHostPort);
client = new HickwallClient(hickwallHostPort);
logger.info("[tryUntilConnected][end]{}", hickwallHostPort);
break;
} catch (IOException e) {
logger.error("Error connect to metric server {}", hickwallHostPort, e);
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
}
}
}
@Override
public void writeBinMultiDataPoint(MetricData rawData) throws MetricProxyException {
DataPoint bmp = convertToHickwallFormat(rawData);
if (!datas.offer(bmp)) {
logger.error("Hickwall queue overflow, will drop data");
}
}
private DataPoint convertToHickwallFormat(MetricData md) {
DataPoint dp = new DataPoint(metricName(md), (double) md.getValue(), md.getTimestampMilli() * 1000000);
// cluster.shard.10_2_2_2_6379.10_28_142_142 (cluster.shard.redis+port.console)
dp.setEndpoint(getEndpoint(md));
dp.getMeta().put("measurement", "fx.xpipe.delay");
dp.getTag().put("cluster", md.getClusterName());
dp.getTag().put("shard", md.getShardName());
dp.getTag().put("address", md.getHostPort().toString());
dp.getTag().put("srcaddr", getLocalIP());
dp.getTag().put("app", "fx");
dp.getTag().put("dc", md.getDcName());
return dp;
}
private String metricName(MetricData md) {
HostPort hostPort = md.getHostPort();
String metricNamePrefix = toMetricNamePrefix(md);
String metricName = metricNamePrefix;
if(hostPort != null){
metricName += "." + hostPort.getHost() + "." + hostPort.getPort() + "." + getLocalIP();
}
return metricName;
}
private String toMetricNamePrefix(MetricData metricData) {
return String.format("fx.xpipe.%s.%s.%s", metricData.getMetricType(), metricData.getClusterName(), metricData.getShardName());
}
private String getLocalIP() {
return Foundation.net().getHostAddress();
}
private String getEndpoint(MetricData md) {
String redisToPattern = getFormattedRedisAddr(md.getHostPort());
String srcConsoleIpToPattern = getFormattedSrcAddr(getLocalIP());
return String.format("%s.%s.%s.%s", md.getClusterName(), md.getShardName(), redisToPattern, srcConsoleIpToPattern);
}
@VisibleForTesting
protected String getFormattedRedisAddr(HostPort hostPort) {
return hostPort.getHost().replaceAll("\\.", "_") + "_" + hostPort.getPort();
}
@VisibleForTesting
protected String getFormattedSrcAddr(String ipAddr) {
return ipAddr.replaceAll("\\.", "_");
}
@Override
public int getOrder() {
return 0;
}
}
|
package gestock.resources.views;
import gestock.Gestock;
import gestock.controller.*;
import gestock.entity.BaseProduct;
import gestock.entity.User;
import gestock.resources.views.components.MyRenderer;
import gestock.resources.views.components.TableModel;
import gestock.util.Constants;
import sun.util.calendar.BaseCalendar;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
public class GestockView extends GFrame {
private Gestock model;
private User user;
private JLabel userName;
private AbstractButton bottomButton;
private AbstractButton parametres;
private AbstractButton chercher;
private AbstractButton catalogue;
private AbstractButton gardeManger;
private AbstractButton listeAchats;
private AbstractButton consommer;
private AbstractButton loginout;
private JPanel peuPanel;
private JPanel perimPanel;
private JTable perim;
private String[] expiryColumns;
private JTable peu;
private String[] fewColumns;
public GestockView(Gestock app, Map<BaseProduct, Integer> expireSoonProducts, List<BaseProduct> fewProducts) {
super(app.messages.getString("app.title"));
setSize(1120, 750);
this.model = app;
this.user = model.getUser();
expiryColumns = new String[]{model.messages.getString("app.table.expiresoon.name"),
model.messages.getString("app.table.expiresoon.quantity"),
model.messages.getString("app.table.expiresoon.date")};
fewColumns = new String[]{model.messages.getString("app.table.fewproducts.name"),
model.messages.getString("app.table.fewproducts.quantity"),
model.messages.getString("app.table.fewproducts.add")};
// The main panel
JPanel mainPanel = new JPanel(new BorderLayout(5, 30));
setContentPane(mainPanel);
mainPanel.setBackground(Color.WHITE);
JPanel menuUp = new JPanel();
menuUp.setLayout(new BoxLayout(menuUp, BoxLayout.X_AXIS));
mainPanel.add(menuUp, BorderLayout.NORTH);
menuUp.setBackground(Color.white);
JPanel tables = new JPanel();
tables.setLayout(new BoxLayout(tables, BoxLayout.X_AXIS));
mainPanel.add(tables, BorderLayout.CENTER);
tables.setBackground(Color.white);
JPanel bottomButtonPanel = new JPanel(new BorderLayout());
mainPanel.add(bottomButtonPanel, BorderLayout.SOUTH);
bottomButtonPanel.setBackground(Color.white);
JPanel space = new JPanel();
bottomButtonPanel.add(space, BorderLayout.SOUTH);
space.setBackground(Color.white);
bottomButton = new JButton(model.messages.getString("justbought.title"));
bottomButton.setBackground(Color.white);
bottomButtonPanel.add(bottomButton, BorderLayout.WEST);
bottomButton.setBackground(Color.WHITE);
bottomButton.setContentAreaFilled(false);
bottomButton.setOpaque(true);
bottomButton.setFont(new Font("Arial", Font.BOLD, 12));
bottomButton.setPressedIcon(new ImageIcon());
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/add64.png"));
//Image img = ImageIO.read(getClass().getResource("gestock.resources.add64.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
bottomButton.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
ex.printStackTrace();
}
bottomButton.setVerticalTextPosition(SwingConstants.BOTTOM);
bottomButton.setHorizontalTextPosition(SwingConstants.CENTER);
bottomButton.addActionListener((ActionEvent ae) -> new JustBoughtController(app));
catalogue = new JButton(model.messages.getString("catalogue.title"));
menuUp.add(catalogue);
catalogue.setBackground(Color.WHITE);
catalogue.setContentAreaFilled(false);
catalogue.setOpaque(true);
catalogue.setFont(new Font("Arial", Font.BOLD, 12));
catalogue.setPressedIcon(new ImageIcon());
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/data110.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
catalogue.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
ex.printStackTrace();
}
catalogue.setVerticalTextPosition(SwingConstants.BOTTOM);
catalogue.setHorizontalTextPosition(SwingConstants.CENTER);
catalogue.addActionListener((ActionEvent ae) -> new CatalogueController(app));
gardeManger = new JButton(model.messages.getString("pantry.title"));
menuUp.add(gardeManger);
gardeManger.setBackground(Color.WHITE);
gardeManger.setContentAreaFilled(false);
gardeManger.setOpaque(true);
gardeManger.setFont(new Font("Arial", Font.BOLD, 12));
gardeManger.setPressedIcon(new ImageIcon());
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/cutlery23.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
gardeManger.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
ex.printStackTrace();
}
gardeManger.setVerticalTextPosition(SwingConstants.BOTTOM);
gardeManger.setHorizontalTextPosition(SwingConstants.CENTER);
gardeManger.addActionListener((ActionEvent ae) -> new PantryController(app));
listeAchats = new JButton(model.messages.getString("shoppinglist.title"));
listeAchats.setBackground(Color.WHITE);
listeAchats.setContentAreaFilled(false);
listeAchats.setOpaque(true);
listeAchats.setFont(new Font("Arial", Font.BOLD, 12));
listeAchats.setPressedIcon(new ImageIcon());
menuUp.add(listeAchats);
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/shopping122.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
listeAchats.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
ex.printStackTrace();
}
listeAchats.setVerticalTextPosition(SwingConstants.BOTTOM);
listeAchats.setHorizontalTextPosition(SwingConstants.CENTER);
listeAchats.addActionListener((ActionEvent ae) -> new ShoppingListController(app));
chercher = new JButton(model.messages.getString("search.title"));
chercher.setBackground(Color.WHITE);
chercher.setContentAreaFilled(false);
chercher.setOpaque(true);
chercher.setFont(new Font("Arial", Font.BOLD, 12));
chercher.setPressedIcon(new ImageIcon());
menuUp.add(chercher);
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/search100.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
chercher.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
ex.printStackTrace();
}
chercher.setVerticalTextPosition(SwingConstants.BOTTOM);
chercher.setHorizontalTextPosition(SwingConstants.CENTER);
consommer = new JButton(model.messages.getString("consume.title"));
menuUp.add(consommer);
consommer.setBackground(Color.WHITE);
consommer.setContentAreaFilled(false);
consommer.setOpaque(true);
consommer.setFont(new Font("Arial", Font.BOLD, 12));
consommer.setPressedIcon(new ImageIcon());
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/cutlery23.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
consommer.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
ex.printStackTrace();
}
consommer.setVerticalTextPosition(SwingConstants.BOTTOM);
consommer.setHorizontalTextPosition(SwingConstants.CENTER);
consommer.addActionListener(new JustConsumedController());
menuUp.add(Box.createHorizontalGlue());
parametres = new JButton(model.messages.getString("settings.title"));
parametres.setBackground(Color.WHITE);
parametres.setContentAreaFilled(false);
parametres.setOpaque(true);
parametres.setFont(new Font("Arial", Font.BOLD, 12));
parametres.setPressedIcon(new ImageIcon());
menuUp.add(parametres);
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/network60.png"));
Image newImg = img.getScaledInstance(48, 48, Image.SCALE_SMOOTH);
parametres.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
ex.printStackTrace();
}
parametres.setVerticalTextPosition(SwingConstants.BOTTOM);
parametres.setHorizontalTextPosition(SwingConstants.CENTER);
parametres.addActionListener((ActionEvent ae) -> {
new SettingsView(model);
//setEnabled(false);
});
JPanel log = new JPanel();
log.setLayout(new BoxLayout(log, BoxLayout.Y_AXIS));
menuUp.add(log);
log.setBackground(Color.white);
userName = new JLabel(user.getName());
userName.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 20, 5, 5));
log.add(userName);
userName.setAlignmentX(SwingConstants.CENTER);
userName.setFont(new Font("Arial", Font.ITALIC, 14));
String[] loginoutText = {model.messages.getString("user.state.login"),
model.messages.getString("user.state.logout")};
loginout = new JButton((user.isLoggedIn()) ? loginoutText[1] : loginoutText[0]);
loginout.setBackground(Color.WHITE);
loginout.setContentAreaFilled(false);
loginout.setOpaque(true);
loginout.setPressedIcon(new ImageIcon());
loginout.setBorderPainted(true);
log.add(loginout);
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/logout20.png"));
Image newImg = img.getScaledInstance(16, 16, Image.SCALE_SMOOTH);
loginout.setIcon(new ImageIcon(newImg));
} catch (IOException ex) {
ex.printStackTrace();
}
loginout.setVerticalTextPosition(SwingConstants.CENTER);
loginout.setHorizontalTextPosition(SwingConstants.RIGHT);
loginout.addActionListener((ActionEvent ae) -> {
if (user.isLoggedIn()) {
user.logout();
} else {
new LoginController(app);
}
});
user.addObserver((Observable o, Object arg) -> {
if (arg != null && arg instanceof Integer) {
if (arg.equals(Constants.OBSERVER_USER_UPDATED)) {
if (user.isLoggedIn()) {
loginout.setText(loginoutText[1]);
} else {
loginout.setText(loginoutText[0]);
}
refresh();
}
}
});
tables.add(Box.createRigidArea(new Dimension((int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 30), 0)));
MyRenderer renderer = new MyRenderer();
perimPanel = new JPanel();
perimPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black),
model.messages.getString("app.table.expiresoon.title")));
tables.add(perimPanel);
perimPanel.setBackground(Color.white);
TableModel model1 = new TableModel(expiryColumns);
perim = new JTable(model1);
perimPanel.add(new JScrollPane(perim));
perim.setEnabled(false);
expireSoonProducts.forEach((k, v) -> {
model1.addRow(new Object[]{k.toString(), v, String.format("%1$td-%1$tm-%1$tY", k.getOldestBoughtProduct().getExpirationDay())});
});
perim.setGridColor(Color.black);
perim.setDefaultRenderer(Integer.class, renderer);
perim.setDefaultRenderer(String.class, renderer);
perim.setShowHorizontalLines(false);
perim.setRowHeight(25);
perim.getColumnModel().getColumn(0).setPreferredWidth(200);
perim.getColumnModel().getColumn(1).setPreferredWidth(70);
perim.getColumnModel().getColumn(2).setPreferredWidth(500);
perim.setAutoCreateRowSorter(true);
perim.setFillsViewportHeight(true);
TableRowSorter<TableModel> sorter = new TableRowSorter<>(model1);
sorter.setComparator(2, new Comparator<String>() {
@Override
public int compare(String date1, String date2) {
if (date1.equals(date2)){
return 0;
} else if (Integer.parseInt(date1.substring(6))<Integer.parseInt(date2.substring(6))) {
return 1;
} else if(Integer.parseInt(date1.substring(6))>Integer.parseInt(date2.substring(6))){
return -1;
} else if (Integer.parseInt(date1.substring(3,5))<Integer.parseInt(date2.substring(3,5))){
return 1;
} else if (Integer.parseInt(date1.substring(3,5))>Integer.parseInt(date2.substring(3,5))){
return -1;
}else if (Integer.parseInt(date1.substring(0,2))<Integer.parseInt(date2.substring(0,2))){
return 1;
} else if (Integer.parseInt(date1.substring(0,2))>Integer.parseInt(date2.substring(0,2))){
return -1;
} else {
return 0;
}
}
});
tables.add(Box.createRigidArea(new Dimension((int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 30), 0)));
peuPanel = new JPanel();
peuPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black),
model.messages.getString("app.table.fewproducts.title")));
tables.add(peuPanel);
peuPanel.setBackground(Color.white);
TableModel model2 = new TableModel(fewColumns);
peu = new JTable(model2);
peuPanel.add(new JScrollPane(peu));
peu.setEnabled(false);
fewProducts.forEach((k) -> {
JButton add = new JButton("");
model2.addRow(new Object[]{k.toString(), k.getQuantityInPantry(), add});
});
peu.setShowHorizontalLines(false);
peu.setGridColor(Color.black);
peu.setDefaultRenderer(Integer.class, renderer);
peu.setDefaultRenderer(String.class, renderer);
peu.setRowHeight(25);
peu.getColumnModel().getColumn(0).setPreferredWidth(200);
peu.getColumnModel().getColumn(1).setPreferredWidth(70);
peu.getColumnModel().getColumn(2).setPreferredWidth(120);
peu.setFillsViewportHeight(true);
TableRowSorter<TableModel> sorter1 = new TableRowSorter<TableModel>(model2);
peu.setRowSorter(sorter1);
sorter1.setComparator(0, new Comparator<String>() {
@Override
public int compare(String name1, String name2) {
return name1.compareTo(name2);
}
});
sorter1.setSortable(2, false);
peu.getColumn(model.messages.getString("app.table.fewproducts.add")).setCellRenderer(new ButtonRenderer());
peu.getColumn(model.messages.getString("app.table.fewproducts.add")).setCellEditor(
new ButtonEditor(new JCheckBox()));
tables.add(Box.createRigidArea(new Dimension((int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 30), 0)));
createMenuBar();
try {
Image img = ImageIO.read(getClass().getResource("/gestock/resources/gestock-blue.png"));
setIconImage(img);
} catch (Exception e) {
e.printStackTrace();
}
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
model.save();
System.exit(0);
}
});
setVisible(true);
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu(model.messages.getString("app.menu.file"));
JMenu helpMenu = new JMenu(model.messages.getString("app.menu.help"));
JMenu toolsMenu = new JMenu(model.messages.getString("app.menu.tools"));
fileMenu.setMnemonic(KeyEvent.VK_F);
helpMenu.setMnemonic(KeyEvent.VK_H);
toolsMenu.setMnemonic(KeyEvent.VK_T);
JMenuItem exit = new JMenuItem(model.messages.getString("app.menu.file.exit"));
JMenuItem licences = new JMenuItem(model.messages.getString("app.menu.help.licences"));
JMenu languages = new JMenu(model.messages.getString("app.menu.tools.languages"));
exit.addActionListener((ActionEvent e) -> {
model.save();
System.exit(0);
});
licences.addActionListener((ActionEvent e) -> new LicensesView());
Set<ResourceBundle> resourceBundles = new HashSet<>();
for (Locale locale : Locale.getAvailableLocales()) {
try {
ResourceBundle rb = ResourceBundle.getBundle("gestock.resources.lang.MessagesBundle", locale);
if (!rb.getLocale().getDisplayLanguage().equals(""))
resourceBundles.add(rb);
} catch (MissingResourceException ex) {
}
}
resourceBundles.forEach((k) -> {
Locale l = k.getLocale();
JMenuItem jmi = new JMenuItem(l.getDisplayLanguage(l));
languages.add(jmi);
jmi.addActionListener((ActionEvent ae) -> {
Locale.setDefault(l);
model.messages = ResourceBundle.getBundle("gestock.resources.lang.MessagesBundle", l);
model.getUser().setLocale(l);
model.getUser().setUpdated();
Thread t = new Thread(this::updateLocale);
t.run();
});
});
fileMenu.add(exit);
helpMenu.add(licences);
toolsMenu.add(languages);
menubar.add(fileMenu);
menubar.add(helpMenu);
menubar.add(toolsMenu);
setJMenuBar(menubar);
}
public void updateLocale() {
bottomButton.setText(model.messages.getString("justbought.title"));
parametres.setText(model.messages.getString("settings.title"));
chercher.setText(model.messages.getString("search.title"));
catalogue.setText(model.messages.getString("catalogue.title"));
gardeManger.setText(model.messages.getString("pantry.title"));
listeAchats.setText(model.messages.getString("shoppinglist.title"));
String[] loginoutText = {model.messages.getString("user.state.login"),
model.messages.getString("user.state.logout")};
loginout.setText((user.isLoggedIn()) ? loginoutText[1] : loginoutText[0]);
peuPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black),
model.messages.getString("app.table.fewproducts.title")));
perimPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.black),
model.messages.getString("app.table.expiresoon.title")));
expiryColumns = new String[]{model.messages.getString("app.table.expiresoon.name"),
model.messages.getString("app.table.expiresoon.quantity"),
model.messages.getString("app.table.expiresoon.date")};
fewColumns = new String[]{model.messages.getString("app.table.fewproducts.name"),
model.messages.getString("app.table.fewproducts.quantity"),
model.messages.getString("app.table.fewproducts.add")};
}
public void fillExpireSoon(Map<BaseProduct, Integer> expireSoonProducts) {
TableModel tm = new TableModel(expiryColumns);
perim.setModel(tm);
expireSoonProducts.forEach((k, v) -> {
tm.addRow(new Object[]{k.toString(), v, k.getOldestBoughtProduct().getExpirationDay()});
});
}
public void fillFewProducts(List<BaseProduct> baseProducts) {
TableModel tm = new TableModel(fewColumns);
peu.setModel(tm);
baseProducts.forEach((k) -> {
JButton add = new JButton("");
tm.addRow(new Object[]{k.toString(), k.getQuantityInPantry(), add});
});
}
}
class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
}
setText((value == null) ? "" : value.toString());
return this;
}
}
class ButtonEditor extends DefaultCellEditor {
protected JButton button;
private String label;
private boolean isPushed;
public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton();
button.setOpaque(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(table.getSelectionBackground());
} else {
button.setForeground(table.getForeground());
button.setBackground(table.getBackground());
}
label = (value == null) ? "" : value.toString();
button.setText(label);
isPushed = true;
return button;
}
public Object getCellEditorValue() {
if (isPushed) {
JOptionPane.showMessageDialog(button, label + ": Ouch!");
// System.out.println(label + ": Ouch!");
}
isPushed = false;
return new String(label);
}
public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}
protected void fireEditingStopped() {
super.fireEditingStopped();
}
}
|
// This file is part of PLplot.
// PLplot is free software; you can redistribute it and/or modify
// PLplot is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with PLplot; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
// Implementation of PLplot example 1 in Java.
package plplot.examples;
import plplot.core.*;
import java.lang.Math;
class x01 {
double xscale, yscale, xoff, yoff;
PLStream pls = new PLStream();
// Set this to true to test the xormod method
static boolean test_xor = false;
static boolean locate_mode = false;
static int fontset = 1;
static String f_name = null;
public static void main( String[] args )
{
x01 x = new x01( args );
}
public x01( String[] args )
{
// plplot initialization
// Divide page into 2x2 plots unless user overrides.
pls.ssub(2, 2);
// Parse and process command line arguments.
// plMergeOpts(options, "x01c options", notes);
pls.parseopts( args, PLStream.PL_PARSE_FULL|PLStream.PL_PARSE_NOPROGRAM );
// Print out version number.
StringBuffer version = new StringBuffer(80);
// plgver no longer works for unexplained reasons.
pls.gver(version);
System.out.println("PLplot library version: " + version);
// Initialize PLplot.
pls.init();
// Select the multi-stroke font.
if (fontset == 1)
pls.fontld( 1 );
else
pls.fontld( 0 );
// Set up the data
// Original case
xscale = 6.;
yscale = 1.;
xoff = 0.;
yoff = 0.;
// Do a plot
plot1(false);
// Set up the data
xscale = 1.;
yscale = 0.0014;
yoff = 0.0185;
// Do a plot
int digmax = 5;
pls.syax(digmax, 0);
plot1(true);
plot2();
plot3();
// Test option to save file
if (f_name != null) {
}
// Let's get some user input
// if (locate_mode) {
// for (;;) {
// if (! plGetCursor(&gin)) break;
// if (gin.keysym == PLK_Escape) break;
// pltext();
// if (gin.keysym < 0xFF && isprint(gin.keysym))
// printf("wx = %f, wy = %f, dx = %f, dy = %f, c = '%c'\n",
// gin.wX, gin.wY, gin.dX, gin.dY, gin.keysym);
// else
// printf("wx = %f, wy = %f, dx = %f, dy = %f, c = 0x%02x\n",
// gin.wX, gin.wY, gin.dX, gin.dY, gin.keysym);
// plgra();
// Don't forget to call plend() to finish off!
pls.end();
}
void plot1( boolean do_test )
{
int i;
double xmin, xmax, ymin, ymax;
double x[] = new double[60];
double y[] = new double[60];
double xs[] = new double[6];
double ys[] = new double[6];
boolean st[] = new boolean[1];
double xx[] = new double[1];
double yy[] = new double[1];
for( i=0; i < 60; i++ )
{
x[i] = xoff + xscale * (i + 1) / 60.0;
y[i] = yoff + yscale * Math.pow(x[i], 2.);
}
xmin = x[0];
xmax = x[59];
ymin = y[0];
ymax = y[59];
for( i=0; i < 6; i++ )
{
xs[i] = x[i * 10 + 3];
ys[i] = y[i * 10 + 3];
}
// Set up the viewport and window using PLENV. The range in X is 0.0 to
// 6.0, and the range in Y is 0.0 to 30.0. The axes are scaled separately
// (just = 0), and we just draw a labelled box (axis = 0).
pls.col0(1);
pls.env( xmin, xmax, ymin, ymax, 0, 0 );
pls.col0(2);
pls.lab( "(x)", "(y)", "#frPLplot Example 1 - y=x#u2" );
// Plot the data points.
pls.col0(4);
pls.poin( xs, ys, 9 );
// Draw the line through the data.
pls.col0(3);
pls.line(x, y);
// xor mode enable erasing a line/point/text by replotting it again
// it does not work in double buffering mode, however
if (do_test && test_xor ) {
pls.xormod(true, st); // enter xor mode
if (st[0]) {
for (i=0; i<60; i++) {
xx[0] = x[i];
yy[0] = y[i];
pls.poin(xx, yy,9); // draw a point
try {
Thread.sleep(50); // wait a little
}
catch (InterruptedException ie) {
}
pls.flush(); // force an update of the tk driver
pls.poin(xx, yy,9); // erase point
}
pls.xormod(false, st); // leave xor mode
}
}
}
void plot2()
{
int i;
double x[] = new double[100];
double y[] = new double[100];
// Set up the viewport and window using PLENV. The range in X is -2.0 to
// 10.0, and the range in Y is -0.4 to 2.0. The axes are scaled
// separately (just = 0), and we draw a box with axes (axis = 1).
pls.col0(1);
pls.env(-2.0, 10.0, -0.4, 1.2, 0, 1);
pls.col0(2);
pls.lab("(x)", "sin(x)/x", "#frPLplot Example 1 - Sinc Function");
// Fill up the arrays.
for (i = 0; i < 100; i++) {
x[i] = (i - 19.0) / 6.0;
y[i] = 1.0;
if (x[i] != 0.0)
y[i] = Math.sin(x[i]) / x[i];
}
// Draw the line.
pls.col0(3);
pls.wid(2);
pls.line(x, y);
pls.wid(1);
}
void plot3()
{
int i;
int space0[] = {};
int mark0[] = {};
int space1[] = {1500};
int mark1[] = {1500};
double x[] = new double[101];
double y[] = new double[101];
// For the final graph we wish to override the default tick intervals,
// and so do not use plenv().
pls.adv(0);
// Use standard viewport, and define X range from 0 to 360 degrees, Y
// range from -1.2 to 1.2.
pls.vsta();
pls.wind( 0.0, 360.0, -1.2, 1.2 );
// Draw a box with ticks spaced 60 degrees apart in X, and 0.2 in Y.
pls.col0(1);
pls.box("bcnst", 60.0, 2, "bcnstv", 0.2, 2);
// Superimpose a dashed line grid, with 1.5 mm marks and spaces.
// plstyl expects a pointer!
pls.styl(mark1, space1);
pls.col0(2);
pls.box("g", 30.0, 0, "g", 0.2, 0);
pls.styl(mark0, space0);
pls.col0(3);
pls.lab( "Angle (degrees)", "sine",
"#frPLplot Example 1 - Sine function" );
for (i = 0; i < 101; i++) {
x[i] = 3.6 * i;
y[i] = Math.sin(x[i] * Math.PI / 180.0);
}
pls.col0(4);
pls.line(x, y);
}
}
// End of x01.java
|
package org.sagebionetworks.auth;
import org.apache.commons.lang3.StringUtils;
import org.sagebionetworks.repo.model.AuthorizationConstants;
import org.sagebionetworks.repo.model.UnauthenticatedException;
import org.sagebionetworks.repo.model.oauth.JsonWebKeySet;
import org.sagebionetworks.repo.model.oauth.OAuthAuthorizationResponse;
import org.sagebionetworks.repo.model.oauth.OAuthClient;
import org.sagebionetworks.repo.model.oauth.OAuthClientIdAndSecret;
import org.sagebionetworks.repo.model.oauth.OAuthClientList;
import org.sagebionetworks.repo.model.oauth.OAuthGrantType;
import org.sagebionetworks.repo.model.oauth.OIDCAuthorizationRequest;
import org.sagebionetworks.repo.model.oauth.OIDCAuthorizationRequestDescription;
import org.sagebionetworks.repo.model.oauth.OIDCTokenResponse;
import org.sagebionetworks.repo.model.oauth.OIDConnectConfiguration;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.repo.web.ServiceUnavailableException;
import org.sagebionetworks.repo.web.UrlHelpers;
import org.sagebionetworks.repo.web.rest.doc.ControllerInfo;
import org.sagebionetworks.repo.web.service.ServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.UriComponentsBuilder;
/**
*
The OpenID Connect (OIDC) services implement OAuth 2.0 with the OpenID identity extensions.
*
*/
@Controller
@ControllerInfo(displayName="OpenID Connect Services", path="auth/v1")
@RequestMapping(UrlHelpers.AUTH_PATH)
public class OpenIDConnectController {
@Autowired
private ServiceProvider serviceProvider;
public static String getEndpoint(UriComponentsBuilder uriComponentsBuilder) {
return uriComponentsBuilder.fragment(null).replaceQuery(null).path(UrlHelpers.AUTH_PATH).build().toString();
}
/**
* Get the Open ID Configuration ("Discovery Document") for the Synapse OIDC service.
* @return
* @throws NotFoundException
*/
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.WELL_KNOWN_OPENID_CONFIGURATION, method = RequestMethod.GET)
public @ResponseBody
OIDConnectConfiguration getOIDCConfiguration(UriComponentsBuilder uriComponentsBuilder) throws NotFoundException {
return serviceProvider.getOpenIDConnectService().
getOIDCConfiguration(getEndpoint(uriComponentsBuilder));
}
/**
* Get the JSON Web Key Set for the Synapse OIDC service. This is the set of public keys
* used to verify signed JSON Web tokens generated by Synapse.
*
* @return the JSON Web Key Set
* @throws NotFoundException
*/
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.OAUTH_2_JWKS, method = RequestMethod.GET)
public @ResponseBody
JsonWebKeySet getOIDCJsonWebKeySet() throws NotFoundException {
return serviceProvider.getOpenIDConnectService().
getOIDCJsonWebKeySet();
}
/**
* Create an OAuth 2.0 client. Note: After creating the client one must also set the client secret
* and verify ownership of the host(s) in the registered redirect URIs.
*
* @param oauthClient the client metadata for the new client
* @return
* @throws NotFoundException
* @throws ServiceUnavailableException if a sector identifer URI is registered but the file cannot be read
*/
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = UrlHelpers.OAUTH_2_CLIENT, method = RequestMethod.POST)
public @ResponseBody
OAuthClient createOAuthClient(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@RequestBody OAuthClient oauthClient
) throws NotFoundException, ServiceUnavailableException {
return serviceProvider.getOpenIDConnectService().
createOpenIDConnectClient(userId, oauthClient);
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = UrlHelpers.OAUTH_2_CLIENT_SECRET, method = RequestMethod.POST)
public @ResponseBody
OAuthClientIdAndSecret createOAuthClientSecret(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@PathVariable(value = UrlHelpers.ID_PATH_VARIABLE) String clientId) {
return serviceProvider.getOpenIDConnectService().
createOAuthClientSecret(userId, clientId);
}
/**
* Get an existing OAuth 2.0 client.
*
* @param id the ID of the client to retrieve
* @return
* @throws NotFoundException
*/
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.OAUTH_2_CLIENT_ID, method = RequestMethod.GET)
public @ResponseBody
OAuthClient getOAuthClient(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@PathVariable(value = UrlHelpers.ID_PATH_VARIABLE) String id
) throws NotFoundException {
return serviceProvider.getOpenIDConnectService().
getOpenIDConnectClient(userId, id);
}
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.OAUTH_2_CLIENT, method = RequestMethod.GET)
public @ResponseBody
OAuthClientList listOAuthClients(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@RequestParam(value = UrlHelpers.NEXT_PAGE_TOKEN_PARAM) String nextPageToken
) throws NotFoundException {
return serviceProvider.getOpenIDConnectService().
listOpenIDConnectClients(userId, nextPageToken);
}
/**
* Update the metadata for an existing OAuth 2.0 client.
* Note, changing the redirect URIs will revert the 'verified' status of the client,
* necessitating re-verification.
*
* @param oauthClient the client metadata to update
* @return
* @throws NotFoundException
* @throws ServiceUnavailableException
*/
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.OAUTH_2_CLIENT_ID, method = RequestMethod.PUT)
public @ResponseBody
OAuthClient updateOAuthClient(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@RequestBody OAuthClient oauthClient
) throws NotFoundException, ServiceUnavailableException {
return serviceProvider.getOpenIDConnectService().
updateOpenIDConnectClient(userId, oauthClient);
}
/**
* Delete OAuth 2.0 client
*
* @param id the ID of the client to delete
* @throws NotFoundException
*/
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.OAUTH_2_CLIENT_ID, method = RequestMethod.DELETE)
public void deletedOpenIDClient(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@PathVariable(value = UrlHelpers.ID_PATH_VARIABLE) String id
) throws NotFoundException {
serviceProvider.getOpenIDConnectService().
deleteOpenIDConnectClient(userId, id);
}
/**
* Get a user-readable description of the authentication request.
* <br>
* This request does not need to be authenticated.
*
* @param authorizationRequest The request to be described
* @return
*/
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.OAUTH_2_AUTH_REQUEST_DESCRIPTION, method = RequestMethod.POST)
public @ResponseBody
OIDCAuthorizationRequestDescription getAuthenticationRequestDescription(
@RequestBody OIDCAuthorizationRequest authorizationRequest
) {
return serviceProvider.getOpenIDConnectService().getAuthenticationRequestDescription(authorizationRequest);
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = UrlHelpers.OAUTH_2_CONSENT, method = RequestMethod.POST)
public @ResponseBody
OAuthAuthorizationResponse authorizeClient(
@RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId,
@RequestBody OIDCAuthorizationRequest authorizationRequest
) throws NotFoundException {
return serviceProvider.getOpenIDConnectService().authorizeClient(userId, authorizationRequest);
}
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = UrlHelpers.OAUTH_2_TOKEN, method = RequestMethod.POST)
public @ResponseBody
OIDCTokenResponse getTokenResponse(
@RequestParam(value = AuthorizationConstants.OAUTH_VERIFIED_CLIENT_ID_PARAM, required=false) String userId,
@RequestParam(value = AuthorizationConstants.OAUTH2_GRANT_TYPE_PARAM) OAuthGrantType grant_type,
@RequestParam(value = AuthorizationConstants.OAUTH2_CODE_PARAM, required=false) String code,
@RequestParam(value = AuthorizationConstants.OAUTH2_REDIRECT_URI_PARAM, required=false) String redirectUri,
@RequestParam(value = AuthorizationConstants.OAUTH2_REFRESH_TOKEN_PARAM, required=false) String refresh_token,
@RequestParam(value = AuthorizationConstants.OAUTH2_SCOPE_PARAM, required=false) String scope,
@RequestParam(value = AuthorizationConstants.OAUTH2_CLAIMS_PARAM, required=false) String claims,
UriComponentsBuilder uriComponentsBuilder
) throws NotFoundException {
if (StringUtils.isEmpty(userId)) {
// the 'userId' param is actually the OAuth client ID, verified by Basic Authentication
throw new UnauthenticatedException("OAuth Client ID and secret must be passed via Basic Authentication. Credentials are missing or invalid.");
}
return serviceProvider.getOpenIDConnectService().getTokenResponse(userId, grant_type, code, redirectUri, refresh_token, scope, claims, getEndpoint(uriComponentsBuilder));
}
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.OAUTH_2_USER_INFO, method = {RequestMethod.GET})
public @ResponseBody
Object getUserInfoGET(
@RequestParam(value = AuthorizationConstants.OAUTH_VERIFIED_ACCESS_TOKEN, required=true) String accessToken,
UriComponentsBuilder uriComponentsBuilder
) throws NotFoundException {
return serviceProvider.getOpenIDConnectService().getUserInfo(accessToken, getEndpoint(uriComponentsBuilder));
}
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = UrlHelpers.OAUTH_2_USER_INFO, method = {RequestMethod.POST})
public @ResponseBody
Object getUserInfoPOST(
@RequestParam(value = AuthorizationConstants.OAUTH_VERIFIED_ACCESS_TOKEN, required=true) String accessToken,
UriComponentsBuilder uriComponentsBuilder
) throws NotFoundException {
return serviceProvider.getOpenIDConnectService().getUserInfo(accessToken, getEndpoint(uriComponentsBuilder));
}
}
|
package com.google.sitebricks.mail.imap;
import com.google.common.collect.Lists;
import java.util.*;
/**
* Extracts a full Message body from an IMAP fetch. Specifically
* a "fetch body[]" command which comes back with the raw content of the
* message including all headers and mime body parts.
* <p/>
* A faster, lighter form of fetch exists for message status info which
* would contain flags, recipients, subject, etc.
*
* @author dhanji@gmail.com (Dhanji R. Prasanna)
*/
class MessageBodyExtractor implements Extractor<List<Message>> {
private static final String BOUNDARY_PREFIX = "boundary=";
@Override
public List<Message> extract(List<String> messages) {
List<Message> emails = Lists.newArrayList();
ListIterator<String> iterator = messages.listIterator();
Message email = new Message();
// Read the leading message (command response).
String firstLine = iterator.next();
firstLine = firstLine.replaceFirst("\\* \\d+[ ]* ", "");
Queue<String> tokens = Parsing.tokenize(firstLine);
Parsing.eat(tokens, "FETCH", "(", "BODY[]");
String sizeString = Parsing.match(tokens, String.class);
int size = 0;
// Parse out size in bytes from "{NNN}"
if (sizeString != null && sizeString.length() > 2) {
size = Integer.parseInt(sizeString.substring(1, sizeString.length() - 1));
}
// OK now parse the header stream.
parseHeaderSection(iterator, email.getHeaders());
// OK now parse the body/mime stream...
// First determine the mimetype.
String mimeType = mimeType(email.getHeaders());
// Normalize mimetype case.
mimeType = mimeType.toLowerCase();
parseBodyParts(iterator, email, mimeType, boundary(mimeType));
emails.add(email);
return emails;
}
private static String mimeType(Map<String, String> headers) {
String mimeType = headers.get("Content-Type");
if (mimeType == null)
mimeType = "text/plain"; // Default to text plain mimetype.
return mimeType;
}
private static void parseBodyParts(ListIterator<String> iterator, HasBodyParts entity,
String mimeType, String boundary) {
if (mimeType.startsWith("text/plain") || mimeType.startsWith("text/html")) {
entity.setBody(readBodyAsString(iterator, boundary));
} else if (mimeType.startsWith("multipart/") /* mixed|alternative */) {
String boundaryToken = boundary(mimeType);
// Skip everything upto the first occurrence of boundary (called the "Preamble")
while (iterator.hasNext() && !boundaryToken.equals(iterator.next())) ;
// Now parse the multipart body in sequence, recursing down as needed...
while (iterator.hasNext()) {
Message.BodyPart bodyPart = new Message.BodyPart();
entity.getBodyParts().add(bodyPart);
// OK now we're in the mime stream. It may have headers.
parseHeaderSection(iterator, bodyPart.getHeaders());
// And parse the body itself (seek up to the next occurrence of boundary token).
// Recurse down this method to slurp up different content types.
String partMimeType = mimeType(bodyPart.getHeaders());
String innerBoundary = boundary(partMimeType);
// If the internal body part is not multipart alternative, then use the parent boundary.
if (innerBoundary == null) {
innerBoundary = boundary;
}
// Is this going to be a multi-level recursion?
if (partMimeType.startsWith("multipart/"))
bodyPart.setBodyParts(new ArrayList<Message.BodyPart>());
parseBodyParts(iterator, bodyPart, partMimeType, innerBoundary);
// we're only done if the last line has a terminal suffix of '--'
String lastLineRead = iterator.previous();
if (lastLineRead.startsWith(boundary + "
// Yes this is the end. Otherwise continue!
break;
} else
iterator.next();
}
} else {
entity.setBody(readBodyAsBytes(iterator, boundary));
}
}
private static String boundary(String mimeType) {
int boundaryIndex = mimeType.indexOf(BOUNDARY_PREFIX);
if (boundaryIndex == -1)
return null;
return "--" + mimeType.substring(boundaryIndex + BOUNDARY_PREFIX.length());
}
private static byte[] readBodyAsBytes(ListIterator<String> iterator, String boundary) {
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()) {
String line = iterator.next();
if (boundary != null && line.startsWith(boundary)) {
// end of section.
break;
}
builder.append(line).append("\r\n");
}
return builder.toString().getBytes();
}
private static String readBodyAsString(ListIterator<String> iterator, String boundary) {
StringBuilder textBody = new StringBuilder();
// Parse as plain text.
while (iterator.hasNext()) {
String line = iterator.next();
if (boundary != null && line.startsWith(boundary)) {
// end of section.
return textBody.toString();
}
textBody.append(line).append("\r\n");
}
return textBody.toString();
}
private static void parseHeaderSection(ListIterator<String> iterator,
Map<String, String> headers) {
while (iterator.hasNext()) {
String message = iterator.next();
// Watch for the end of sequence marker. If we see it, the mime-stream is ended.
if (Command.isEndOfSequence(message.replaceFirst("\\d+[ ]* ", "").toLowerCase()))
continue;
// A blank line indicates end of the header section.
if (message.isEmpty())
break;
parseHeaderPair(message, iterator, headers);
}
}
private static void parseHeaderPair(String message, ListIterator<String> iterator,
Map<String, String> headers) {
String[] split = message.split(": ", 2);
String value = split[1];
// Check if the next line begins with a LWSP. If it does, then it is a continuation of this
// line.
while (iterator.hasNext()) {
String next = iterator.next();
if (next.startsWith(" "))
value += ' ' + next.trim();
else {
iterator.previous();
break;
}
}
headers.put(split[0], value);
}
}
|
package cgeo.geocaching.storage;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.LoadFlag;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.list.AbstractList;
import cgeo.geocaching.list.PseudoList;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.models.Destination;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;
import cgeo.geocaching.models.LogEntry;
import cgeo.geocaching.models.Trackable;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.search.SearchSuggestionCursor;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.Version;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.android.app.AppObservable;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class DataStore {
private DataStore() {
// utility class
}
public enum StorageLocation {
HEAP,
CACHE,
DATABASE,
}
private static final Func1<Cursor,String> GET_STRING_0 = new Func1<Cursor, String>() {
@Override
public String call(final Cursor cursor) {
return cursor.getString(0);
}
};
private static final Func1<Cursor,Integer> GET_INTEGER_0 = new Func1<Cursor, Integer>() {
@Override
public Integer call(final Cursor cursor) {
return cursor.getInt(0);
}
};
// Columns and indices for the cache data
private static final String QUERY_CACHE_DATA =
"SELECT " +
"cg_caches.updated," +
"cg_caches.reason," +
"cg_caches.detailed," +
"cg_caches.detailedupdate," +
"cg_caches.visiteddate," +
"cg_caches.geocode," +
"cg_caches.cacheid," +
"cg_caches.guid," +
"cg_caches.type," +
"cg_caches.name," +
"cg_caches.owner," +
"cg_caches.owner_real," +
"cg_caches.hidden," +
"cg_caches.hint," +
"cg_caches.size," +
"cg_caches.difficulty," +
"cg_caches.direction," +
"cg_caches.distance," +
"cg_caches.terrain," +
"cg_caches.location," +
"cg_caches.personal_note," +
"cg_caches.shortdesc," +
"cg_caches.favourite_cnt," +
"cg_caches.rating," +
"cg_caches.votes," +
"cg_caches.myvote," +
"cg_caches.disabled," +
"cg_caches.archived," +
"cg_caches.members," +
"cg_caches.found," +
"cg_caches.favourite," +
"cg_caches.inventoryunknown," +
"cg_caches.onWatchlist," +
"cg_caches.reliable_latlon," +
"cg_caches.coordsChanged," +
"cg_caches.latitude," +
"cg_caches.longitude," +
"cg_caches.finalDefined," +
"cg_caches._id," +
"cg_caches.inventorycoins," +
"cg_caches.inventorytags," +
"cg_caches.logPasswordRequired," +
"cg_caches.watchlistCount";
/** The list of fields needed for mapping. */
private static final String[] WAYPOINT_COLUMNS = { "_id", "geocode", "updated", "type", "prefix", "lookup", "name", "latitude", "longitude", "note", "own", "visited" };
/** Number of days (as ms) after temporarily saved caches are deleted */
private final static long DAYS_AFTER_CACHE_IS_DELETED = 3 * 24 * 60 * 60 * 1000;
/**
* holds the column indexes of the cache table to avoid lookups
*/
private static final CacheCache cacheCache = new CacheCache();
private static SQLiteDatabase database = null;
private static final int dbVersion = 71;
public static final int customListIdOffset = 10;
private static final @NonNull String dbName = "data";
private static final @NonNull String dbTableCaches = "cg_caches";
private static final @NonNull String dbTableLists = "cg_lists";
private static final @NonNull String dbTableCachesLists = "cg_caches_lists";
private static final @NonNull String dbTableAttributes = "cg_attributes";
private static final @NonNull String dbTableWaypoints = "cg_waypoints";
private static final @NonNull String dbTableSpoilers = "cg_spoilers";
private static final @NonNull String dbTableLogs = "cg_logs";
private static final @NonNull String dbTableLogCount = "cg_logCount";
private static final @NonNull String dbTableLogImages = "cg_logImages";
private static final @NonNull String dbTableLogsOffline = "cg_logs_offline";
private static final @NonNull String dbTableTrackables = "cg_trackables";
private static final @NonNull String dbTableSearchDestinationHistory = "cg_search_destination_history";
private static final @NonNull String dbCreateCaches = ""
+ "create table " + dbTableCaches + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, "
+ "detailed integer not null default 0, "
+ "detailedupdate long, "
+ "visiteddate long, "
+ "geocode text unique not null, "
+ "reason integer not null default 0, " // cached, favorite...
+ "cacheid text, "
+ "guid text, "
+ "type text, "
+ "name text, "
+ "owner text, "
+ "owner_real text, "
+ "hidden long, "
+ "hint text, "
+ "size text, "
+ "difficulty float, "
+ "terrain float, "
+ "location text, "
+ "direction double, "
+ "distance double, "
+ "latitude double, "
+ "longitude double, "
+ "reliable_latlon integer, "
+ "personal_note text, "
+ "shortdesc text, "
+ "description text, "
+ "favourite_cnt integer, "
+ "rating float, "
+ "votes integer, "
+ "myvote float, "
+ "disabled integer not null default 0, "
+ "archived integer not null default 0, "
+ "members integer not null default 0, "
+ "found integer not null default 0, "
+ "favourite integer not null default 0, "
+ "inventorycoins integer default 0, "
+ "inventorytags integer default 0, "
+ "inventoryunknown integer default 0, "
+ "onWatchlist integer default 0, "
+ "coordsChanged integer default 0, "
+ "finalDefined integer default 0, "
+ "logPasswordRequired integer default 0,"
+ "watchlistCount integer default -1"
+ "); ";
private static final String dbCreateLists = ""
+ "create table " + dbTableLists + " ("
+ "_id integer primary key autoincrement, "
+ "title text not null, "
+ "updated long not null"
+ "); ";
private static final String dbCreateCachesLists = ""
+ "create table " + dbTableCachesLists + " ("
+ "list_id integer not null, "
+ "geocode text not null, "
+ "primary key (list_id, geocode)"
+ "); ";
private static final String dbCreateAttributes = ""
+ "create table " + dbTableAttributes + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "attribute text "
+ "); ";
private static final String dbCreateWaypoints = ""
+ "create table " + dbTableWaypoints + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type text not null default 'waypoint', "
+ "prefix text, "
+ "lookup text, "
+ "name text, "
+ "latitude double, "
+ "longitude double, "
+ "note text, "
+ "own integer default 0, "
+ "visited integer default 0"
+ "); ";
private static final String dbCreateSpoilers = ""
+ "create table " + dbTableSpoilers + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "url text, "
+ "title text, "
+ "description text "
+ "); ";
private static final String dbCreateLogs = ""
+ "create table " + dbTableLogs + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "author text, "
+ "log text, "
+ "date long, "
+ "found integer not null default 0, "
+ "friend integer "
+ "); ";
private static final String dbCreateLogCount = ""
+ "create table " + dbTableLogCount + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "count integer not null default 0 "
+ "); ";
private static final String dbCreateLogImages = ""
+ "create table " + dbTableLogImages + " ("
+ "_id integer primary key autoincrement, "
+ "log_id integer not null, "
+ "title text not null, "
+ "url text not null, "
+ "description text "
+ "); ";
private static final String dbCreateLogsOffline = ""
+ "create table " + dbTableLogsOffline + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type integer not null default 4, "
+ "log text, "
+ "date long "
+ "); ";
private static final String dbCreateTrackables = ""
+ "create table " + dbTableTrackables + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, " // date of save
+ "tbcode text not null, "
+ "guid text, "
+ "title text, "
+ "owner text, "
+ "released long, "
+ "goal text, "
+ "description text, "
+ "geocode text "
+ "); ";
private static final String dbCreateSearchDestinationHistory = ""
+ "create table " + dbTableSearchDestinationHistory + " ("
+ "_id integer primary key autoincrement, "
+ "date long not null, "
+ "latitude double, "
+ "longitude double "
+ "); ";
private static final Observable<Integer> allCachesCountObservable = Observable.create(new OnSubscribe<Integer>() {
@Override
public void call(final Subscriber<? super Integer> subscriber) {
if (isInitialized()) {
subscriber.onNext(getAllCachesCount());
subscriber.onCompleted();
}
}
}).timeout(500, TimeUnit.MILLISECONDS).retry(10).subscribeOn(Schedulers.io());
private static boolean newlyCreatedDatabase = false;
private static boolean databaseCleaned = false;
public static void init() {
if (database != null) {
return;
}
synchronized(DataStore.class) {
if (database != null) {
return;
}
final DbHelper dbHelper = new DbHelper(new DBContext(CgeoApplication.getInstance()));
try {
database = dbHelper.getWritableDatabase();
} catch (final Exception e) {
Log.e("DataStore.init: unable to open database for R/W", e);
recreateDatabase(dbHelper);
}
}
}
/**
* Attempt to recreate the database if opening has failed
*
* @param dbHelper dbHelper to use to reopen the database
*/
private static void recreateDatabase(final DbHelper dbHelper) {
final File dbPath = databasePath();
final File corruptedPath = new File(LocalStorage.getStorage(), dbPath.getName() + ".corrupted");
if (LocalStorage.copy(dbPath, corruptedPath)) {
Log.i("DataStore.init: renamed " + dbPath + " into " + corruptedPath);
} else {
Log.e("DataStore.init: unable to rename corrupted database");
}
try {
database = dbHelper.getWritableDatabase();
} catch (final Exception f) {
Log.e("DataStore.init: unable to recreate database and open it for R/W", f);
}
}
public static synchronized void closeDb() {
if (database == null) {
return;
}
cacheCache.removeAllFromCache();
PreparedStatement.clearPreparedStatements();
database.close();
database = null;
}
@NonNull
public static File getBackupFileInternal() {
return new File(LocalStorage.getStorage(), "cgeo.sqlite");
}
public static String backupDatabaseInternal() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database wasn't backed up: no external memory");
return null;
}
final File target = getBackupFileInternal();
closeDb();
final boolean backupDone = LocalStorage.copy(databasePath(), target);
init();
if (!backupDone) {
Log.e("Database could not be copied to " + target);
return null;
}
Log.i("Database was copied to " + target);
return target.getPath();
}
/**
* Move the database to/from external cgdata in a new thread,
* showing a progress window
*
*/
public static void moveDatabase(final Activity fromActivity) {
final ProgressDialog dialog = ProgressDialog.show(fromActivity, fromActivity.getString(R.string.init_dbmove_dbmove), fromActivity.getString(R.string.init_dbmove_running), true, false);
AppObservable.bindActivity(fromActivity, Observable.defer(new Func0<Observable<Boolean>>() {
@Override
public Observable<Boolean> call() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database was not moved: external memory not available");
return Observable.just(false);
}
closeDb();
final File source = databasePath();
final File target = databaseAlternatePath();
if (!LocalStorage.copy(source, target)) {
Log.e("Database could not be moved to " + target);
init();
return Observable.just(false);
}
if (!FileUtils.delete(source)) {
Log.e("Original database could not be deleted during move");
}
Settings.setDbOnSDCard(!Settings.isDbOnSDCard());
Log.i("Database was moved to " + target);
init();
return Observable.just(true);
}
})).subscribeOn(Schedulers.io()).subscribe(new Action1<Boolean>() {
@Override
public void call(final Boolean success) {
dialog.dismiss();
final String message = success ? fromActivity.getString(R.string.init_dbmove_success) : fromActivity.getString(R.string.init_dbmove_failed);
Dialogs.message(fromActivity, R.string.init_dbmove_dbmove, message);
}
});
}
@NonNull
private static File databasePath(final boolean internal) {
return new File(internal ? LocalStorage.getInternalDbDirectory() : LocalStorage.getExternalDbDirectory(), dbName);
}
@NonNull
private static File databasePath() {
return databasePath(!Settings.isDbOnSDCard());
}
@NonNull
private static File databaseAlternatePath() {
return databasePath(Settings.isDbOnSDCard());
}
public static boolean restoreDatabaseInternal() {
if (!LocalStorage.isExternalStorageAvailable()) {
Log.w("Database wasn't restored: no external memory");
return false;
}
final File sourceFile = getBackupFileInternal();
closeDb();
final boolean restoreDone = LocalStorage.copy(sourceFile, databasePath());
init();
if (restoreDone) {
Log.i("Database successfully restored from " + sourceFile.getPath());
} else {
Log.e("Could not restore database from " + sourceFile.getPath());
}
return restoreDone;
}
private static class DBContext extends ContextWrapper {
public DBContext(final Context base) {
super(base);
}
/**
* We override the default open/create as it doesn't work on OS 1.6 and
* causes issues on other devices too.
*/
@Override
public SQLiteDatabase openOrCreateDatabase(final String name, final int mode,
final CursorFactory factory) {
final File file = new File(name);
FileUtils.mkdirs(file.getParentFile());
return SQLiteDatabase.openOrCreateDatabase(file, factory);
}
}
private static class DbHelper extends SQLiteOpenHelper {
private static boolean firstRun = true;
DbHelper(final Context context) {
super(context, databasePath().getPath(), null, dbVersion);
}
@Override
public void onCreate(final SQLiteDatabase db) {
newlyCreatedDatabase = true;
db.execSQL(dbCreateCaches);
db.execSQL(dbCreateLists);
db.execSQL(dbCreateCachesLists);
db.execSQL(dbCreateAttributes);
db.execSQL(dbCreateWaypoints);
db.execSQL(dbCreateSpoilers);
db.execSQL(dbCreateLogs);
db.execSQL(dbCreateLogCount);
db.execSQL(dbCreateLogImages);
db.execSQL(dbCreateLogsOffline);
db.execSQL(dbCreateTrackables);
db.execSQL(dbCreateSearchDestinationHistory);
createIndices(db);
}
static private void createIndices(final SQLiteDatabase db) {
db.execSQL("create index if not exists in_caches_geo on " + dbTableCaches + " (geocode)");
db.execSQL("create index if not exists in_caches_guid on " + dbTableCaches + " (guid)");
db.execSQL("create index if not exists in_caches_lat on " + dbTableCaches + " (latitude)");
db.execSQL("create index if not exists in_caches_lon on " + dbTableCaches + " (longitude)");
db.execSQL("create index if not exists in_caches_reason on " + dbTableCaches + " (reason)");
db.execSQL("create index if not exists in_caches_detailed on " + dbTableCaches + " (detailed)");
db.execSQL("create index if not exists in_caches_type on " + dbTableCaches + " (type)");
db.execSQL("create index if not exists in_caches_visit_detail on " + dbTableCaches + " (visiteddate, detailedupdate)");
db.execSQL("create index if not exists in_attr_geo on " + dbTableAttributes + " (geocode)");
db.execSQL("create index if not exists in_wpts_geo on " + dbTableWaypoints + " (geocode)");
db.execSQL("create index if not exists in_wpts_geo_type on " + dbTableWaypoints + " (geocode, type)");
db.execSQL("create index if not exists in_spoil_geo on " + dbTableSpoilers + " (geocode)");
db.execSQL("create index if not exists in_logs_geo on " + dbTableLogs + " (geocode)");
db.execSQL("create index if not exists in_logcount_geo on " + dbTableLogCount + " (geocode)");
db.execSQL("create index if not exists in_logsoff_geo on " + dbTableLogsOffline + " (geocode)");
db.execSQL("create index if not exists in_trck_geo on " + dbTableTrackables + " (geocode)");
db.execSQL("create index if not exists in_lists_geo on " + dbTableCachesLists + " (geocode)");
}
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start");
try {
if (db.isReadOnly()) {
return;
}
db.beginTransaction();
if (oldVersion <= 0) { // new table
dropDatabase(db);
onCreate(db);
Log.i("Database structure created.");
}
if (oldVersion > 0) {
db.execSQL("delete from " + dbTableCaches + " where reason = 0");
if (oldVersion < 52) { // upgrade to 52
try {
db.execSQL(dbCreateSearchDestinationHistory);
Log.i("Added table " + dbTableSearchDestinationHistory + ".");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 52", e);
}
}
if (oldVersion < 53) { // upgrade to 53
try {
db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer");
Log.i("Column onWatchlist added to " + dbTableCaches + ".");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 53", e);
}
}
if (oldVersion < 54) { // update to 54
try {
db.execSQL(dbCreateLogImages);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 54", e);
}
}
if (oldVersion < 55) { // update to 55
try {
db.execSQL("alter table " + dbTableCaches + " add column personal_note text");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 55", e);
}
}
// make all internal attribute names lowercase
// @see issue #299
if (oldVersion < 56) { // update to 56
try {
db.execSQL("update " + dbTableAttributes + " set attribute = " +
"lower(attribute) where attribute like \"%_yes\" " +
"or attribute like \"%_no\"");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 56", e);
}
}
// Create missing indices. See issue #435
if (oldVersion < 57) { // update to 57
try {
db.execSQL("drop index in_a");
db.execSQL("drop index in_b");
db.execSQL("drop index in_c");
db.execSQL("drop index in_d");
db.execSQL("drop index in_e");
db.execSQL("drop index in_f");
createIndices(db);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 57", e);
}
}
if (oldVersion < 58) { // upgrade to 58
try {
db.beginTransaction();
final String dbTableCachesTemp = dbTableCaches + "_temp";
final String dbCreateCachesTemp = ""
+ "create table " + dbTableCachesTemp + " ("
+ "_id integer primary key autoincrement, "
+ "updated long not null, "
+ "detailed integer not null default 0, "
+ "detailedupdate long, "
+ "visiteddate long, "
+ "geocode text unique not null, "
+ "reason integer not null default 0, "
+ "cacheid text, "
+ "guid text, "
+ "type text, "
+ "name text, "
+ "own integer not null default 0, "
+ "owner text, "
+ "owner_real text, "
+ "hidden long, "
+ "hint text, "
+ "size text, "
+ "difficulty float, "
+ "terrain float, "
+ "location text, "
+ "direction double, "
+ "distance double, "
+ "latitude double, "
+ "longitude double, "
+ "reliable_latlon integer, "
+ "personal_note text, "
+ "shortdesc text, "
+ "description text, "
+ "favourite_cnt integer, "
+ "rating float, "
+ "votes integer, "
+ "myvote float, "
+ "disabled integer not null default 0, "
+ "archived integer not null default 0, "
+ "members integer not null default 0, "
+ "found integer not null default 0, "
+ "favourite integer not null default 0, "
+ "inventorycoins integer default 0, "
+ "inventorytags integer default 0, "
+ "inventoryunknown integer default 0, "
+ "onWatchlist integer default 0 "
+ "); ";
db.execSQL(dbCreateCachesTemp);
db.execSQL("insert into " + dbTableCachesTemp + " select _id,updated,detailed,detailedupdate,visiteddate,geocode,reason,cacheid,guid,type,name,own,owner,owner_real," +
"hidden,hint,size,difficulty,terrain,location,direction,distance,latitude,longitude, 0," +
"personal_note,shortdesc,description,favourite_cnt,rating,votes,myvote,disabled,archived,members,found,favourite,inventorycoins," +
"inventorytags,inventoryunknown,onWatchlist from " + dbTableCaches);
db.execSQL("drop table " + dbTableCaches);
db.execSQL("alter table " + dbTableCachesTemp + " rename to " + dbTableCaches);
final String dbTableWaypointsTemp = dbTableWaypoints + "_temp";
final String dbCreateWaypointsTemp = ""
+ "create table " + dbTableWaypointsTemp + " ("
+ "_id integer primary key autoincrement, "
+ "geocode text not null, "
+ "updated long not null, " // date of save
+ "type text not null default 'waypoint', "
+ "prefix text, "
+ "lookup text, "
+ "name text, "
+ "latitude double, "
+ "longitude double, "
+ "note text "
+ "); ";
db.execSQL(dbCreateWaypointsTemp);
db.execSQL("insert into " + dbTableWaypointsTemp + " select _id, geocode, updated, type, prefix, lookup, name, latitude, longitude, note from " + dbTableWaypoints);
db.execSQL("drop table " + dbTableWaypoints);
db.execSQL("alter table " + dbTableWaypointsTemp + " rename to " + dbTableWaypoints);
createIndices(db);
db.setTransactionSuccessful();
Log.i("Removed latitude_string and longitude_string columns");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 58", e);
} finally {
db.endTransaction();
}
}
if (oldVersion < 59) {
try {
// Add new indices and remove obsolete cache files
createIndices(db);
removeObsoleteCacheDirectories(db);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 59", e);
}
}
if (oldVersion < 60) {
try {
removeSecEmptyDirs();
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 60", e);
}
}
if (oldVersion < 61) {
try {
db.execSQL("alter table " + dbTableLogs + " add column friend integer");
db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 61", e);
}
}
// Introduces finalDefined on caches and own on waypoints
if (oldVersion < 62) {
try {
db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0");
db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0");
db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 62", e);
}
}
if (oldVersion < 63) {
try {
removeDoubleUnderscoreMapFiles();
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 63", e);
}
}
if (oldVersion < 64) {
try {
// No cache should ever be stored into the ALL_CACHES list. Here we use hardcoded list ids
// rather than symbolic ones because the fix must be applied with the values at the time
// of the problem. The problem was introduced in release 2012.06.01.
db.execSQL("update " + dbTableCaches + " set reason=1 where reason=2");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 64", e);
}
}
if (oldVersion < 65) {
try {
// Set all waypoints where name is Original coordinates to type ORIGINAL
db.execSQL("update " + dbTableWaypoints + " set type='original', own=0 where name='Original Coordinates'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 65:", e);
}
}
// Introduces visited feature on waypoints
if (oldVersion < 66) {
try {
db.execSQL("alter table " + dbTableWaypoints + " add column visited integer default 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 66", e);
}
}
// issue2662 OC: Leichtes Klettern / Easy climbing
if (oldVersion < 67) {
try {
db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_yes' where geocode like 'OC%' and attribute = 'climbing_yes'");
db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_no' where geocode like 'OC%' and attribute = 'climbing_no'");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 67", e);
}
}
// Introduces logPasswordRequired on caches
if (oldVersion < 68) {
try {
db.execSQL("alter table " + dbTableCaches + " add column logPasswordRequired integer default 0");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 68", e);
}
}
// description for log Images
if (oldVersion < 69) {
try {
db.execSQL("alter table " + dbTableLogImages + " add column description text");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 69", e);
}
}
// Introduces watchListCount
if (oldVersion < 70) {
try {
db.execSQL("alter table " + dbTableCaches + " add column watchlistCount integer default -1");
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 70", e);
}
}
// Introduces cachesLists
if (oldVersion < 71) {
try {
db.execSQL(dbCreateCachesLists);
createIndices(db);
db.execSQL("insert into " + dbTableCachesLists + " select reason, geocode from " + dbTableCaches);
} catch (final Exception e) {
Log.e("Failed to upgrade to ver. 71", e);
}
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": completed");
}
@Override
public void onOpen(final SQLiteDatabase db) {
if (firstRun) {
sanityChecks(db);
firstRun = false;
}
}
/**
* Execute sanity checks that should be performed once per application after the database has been
* opened.
*
* @param db the database to perform sanity checks against
*/
private static void sanityChecks(final SQLiteDatabase db) {
// Check that the history of searches is well formed as some dates seem to be missing according
// to NPE traces.
final int staleHistorySearches = db.delete(dbTableSearchDestinationHistory, "date is null", null);
if (staleHistorySearches > 0) {
Log.w(String.format(Locale.getDefault(), "DataStore.dbHelper.onOpen: removed %d bad search history entries", staleHistorySearches));
}
}
/**
* Method to remove static map files with double underscore due to issue#1670
* introduced with release on 2012-05-24.
*/
private static void removeDoubleUnderscoreMapFiles() {
final File[] geocodeDirs = LocalStorage.getStorage().listFiles();
if (ArrayUtils.isNotEmpty(geocodeDirs)) {
final FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(final File dir, final String filename) {
return filename.startsWith("map_") && filename.contains("__");
}
};
for (final File dir : geocodeDirs) {
final File[] wrongFiles = dir.listFiles(filter);
if (wrongFiles != null) {
for (final File wrongFile : wrongFiles) {
FileUtils.deleteIgnoringFailure(wrongFile);
}
}
}
}
}
/*
* Remove empty directories created in the secondary storage area.
*/
private static void removeSecEmptyDirs() {
final File[] files = LocalStorage.getStorageSec().listFiles();
if (ArrayUtils.isNotEmpty(files)) {
for (final File file : files) {
if (file.isDirectory()) {
// This will silently fail if the directory is not empty.
FileUtils.deleteIgnoringFailure(file);
}
}
}
}
private static void dropDatabase(final SQLiteDatabase db) {
db.execSQL("drop table if exists " + dbTableCachesLists);
db.execSQL("drop table if exists " + dbTableCaches);
db.execSQL("drop table if exists " + dbTableAttributes);
db.execSQL("drop table if exists " + dbTableWaypoints);
db.execSQL("drop table if exists " + dbTableSpoilers);
db.execSQL("drop table if exists " + dbTableLogs);
db.execSQL("drop table if exists " + dbTableLogCount);
db.execSQL("drop table if exists " + dbTableLogsOffline);
db.execSQL("drop table if exists " + dbTableTrackables);
}
}
/**
* Remove obsolete cache directories in c:geo private storage.
*/
public static void removeObsoleteCacheDirectories() {
removeObsoleteCacheDirectories(database);
}
/**
* Remove obsolete cache directories in c:geo private storage.
*
* @param db
* the read-write database to use
*/
private static void removeObsoleteCacheDirectories(final SQLiteDatabase db) {
final File[] files = LocalStorage.getStorage().listFiles();
if (ArrayUtils.isNotEmpty(files)) {
final Pattern oldFilePattern = Pattern.compile("^[GC|TB|EC|GK|O][A-Z0-9]{4,7}$");
final SQLiteStatement select = PreparedStatement.CHECK_IF_PRESENT.getStatement();
final List<File> toRemove = new ArrayList<>(files.length);
for (final File file : files) {
if (file.isDirectory()) {
final String geocode = file.getName();
if (oldFilePattern.matcher(geocode).find()) {
synchronized (select) {
select.bindString(1, geocode);
if (select.simpleQueryForLong() == 0) {
toRemove.add(file);
}
}
}
}
}
// Use a background thread for the real removal to avoid keeping the database locked
// if we are called from within a transaction.
Schedulers.io().createWorker().schedule(new Action0() {
@Override
public void call() {
for (final File dir : toRemove) {
Log.i("Removing obsolete cache directory for " + dir.getName());
FileUtils.deleteDirectory(dir);
}
}
});
}
}
public static boolean isThere(final String geocode, final String guid, final boolean checkTime) {
init();
long dataDetailedUpdate = 0;
int dataDetailed = 0;
try {
final Cursor cursor;
if (StringUtils.isNotBlank(geocode)) {
cursor = database.query(
dbTableCaches,
new String[]{"detailed", "detailedupdate", "updated"},
"geocode = ?",
new String[]{geocode},
null,
null,
null,
"1");
} else if (StringUtils.isNotBlank(guid)) {
cursor = database.query(
dbTableCaches,
new String[]{"detailed", "detailedupdate", "updated"},
"guid = ?",
new String[]{guid},
null,
null,
null,
"1");
} else {
return false;
}
if (cursor.moveToFirst()) {
dataDetailed = cursor.getInt(0);
dataDetailedUpdate = cursor.getLong(1);
}
cursor.close();
} catch (final Exception e) {
Log.e("DataStore.isThere", e);
}
if (dataDetailed == 0) {
// we want details, but these are not stored
return false;
}
if (checkTime && dataDetailedUpdate < (System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED)) {
// we want to check time for detailed cache, but data are older than 3 days
return false;
}
// we have some cache
return true;
}
/** is cache stored in one of the lists (not only temporary) */
public static boolean isOffline(final String geocode, final String guid) {
if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) {
return false;
}
init();
try {
final SQLiteStatement offlineListCound;
final String value;
if (StringUtils.isNotBlank(geocode)) {
offlineListCound = PreparedStatement.GEOCODE_OFFLINE.getStatement();
value = geocode;
} else {
offlineListCound = PreparedStatement.GUID_OFFLINE.getStatement();
value = guid;
}
synchronized (offlineListCound) {
offlineListCound.bindString(1, value);
return offlineListCound.simpleQueryForLong() > 0;
}
} catch (final SQLiteDoneException ignored) {
// Do nothing, it only means we have no information on the cache
} catch (final Exception e) {
Log.e("DataStore.isOffline", e);
}
return false;
}
@Nullable
public static String getGeocodeForGuid(final String guid) {
if (StringUtils.isBlank(guid)) {
return null;
}
init();
try {
final SQLiteStatement description = PreparedStatement.GEOCODE_OF_GUID.getStatement();
synchronized (description) {
description.bindString(1, guid);
return description.simpleQueryForString();
}
} catch (final SQLiteDoneException ignored) {
// Do nothing, it only means we have no information on the cache
} catch (final Exception e) {
Log.e("DataStore.getGeocodeForGuid", e);
}
return null;
}
@Nullable
public static String getGeocodeForTitle(@NonNull final String title) {
if (StringUtils.isBlank(title)) {
return null;
}
init();
try {
final SQLiteStatement sqlStatement = PreparedStatement.GEOCODE_FROM_TITLE.getStatement();
synchronized (sqlStatement) {
sqlStatement.bindString(1, title);
return sqlStatement.simpleQueryForString();
}
} catch (final SQLiteDoneException ignored) {
// Do nothing, it only means we have no information on the cache
} catch (final Exception e) {
Log.e("DataStore.getGeocodeForGuid", e);
}
return null;
}
/**
* Save/store a cache to the CacheCache
*
* @param cache
* the Cache to save in the CacheCache/DB
*
*/
public static void saveCache(final Geocache cache, final Set<LoadFlags.SaveFlag> saveFlags) {
saveCaches(Collections.singletonList(cache), saveFlags);
}
/**
* Save/store a cache to the CacheCache
*
* @param caches
* the caches to save in the CacheCache/DB
*
*/
public static void saveCaches(final Collection<Geocache> caches, final Set<LoadFlags.SaveFlag> saveFlags) {
if (CollectionUtils.isEmpty(caches)) {
return;
}
final List<String> cachesFromDatabase = new ArrayList<>();
final Map<String, Geocache> existingCaches = new HashMap<>();
// first check which caches are in the memory cache
for (final Geocache cache : caches) {
final String geocode = cache.getGeocode();
final Geocache cacheFromCache = cacheCache.getCacheFromCache(geocode);
if (cacheFromCache == null) {
cachesFromDatabase.add(geocode);
} else {
existingCaches.put(geocode, cacheFromCache);
}
}
// then load all remaining caches from the database in one step
for (final Geocache cacheFromDatabase : loadCaches(cachesFromDatabase, LoadFlags.LOAD_ALL_DB_ONLY)) {
existingCaches.put(cacheFromDatabase.getGeocode(), cacheFromDatabase);
}
final List<Geocache> toBeStored = new ArrayList<>();
// Merge with the data already stored in the CacheCache or in the database if
// the cache had not been loaded before, and update the CacheCache.
// Also, a DB update is required if the merge data comes from the CacheCache
// (as it may be more recent than the version in the database), or if the
// version coming from the database is different than the version we are entering
// into the cache (that includes absence from the database).
for (final Geocache cache : caches) {
final String geocode = cache.getGeocode();
final Geocache existingCache = existingCaches.get(geocode);
boolean dbUpdateRequired = !cache.gatherMissingFrom(existingCache) || cacheCache.getCacheFromCache(geocode) != null;
// parse the note AFTER merging the local information in
dbUpdateRequired |= cache.parseWaypointsFromNote();
cache.addStorageLocation(StorageLocation.CACHE);
cacheCache.putCacheInCache(cache);
// Only save the cache in the database if it is requested by the caller and
// the cache contains detailed information.
if (saveFlags.contains(SaveFlag.DB) && cache.isDetailed() && dbUpdateRequired) {
toBeStored.add(cache);
}
}
for (final Geocache geocache : toBeStored) {
storeIntoDatabase(geocache);
}
}
private static boolean storeIntoDatabase(final Geocache cache) {
cache.addStorageLocation(StorageLocation.DATABASE);
cacheCache.putCacheInCache(cache);
Log.d("Saving " + cache.toString() + " (" + cache.getLists() + ") to DB");
final ContentValues values = new ContentValues();
if (cache.getUpdated() == 0) {
values.put("updated", System.currentTimeMillis());
} else {
values.put("updated", cache.getUpdated());
}
values.put("reason", StoredList.STANDARD_LIST_ID);
values.put("detailed", cache.isDetailed() ? 1 : 0);
values.put("detailedupdate", cache.getDetailedUpdate());
values.put("visiteddate", cache.getVisitedDate());
values.put("geocode", cache.getGeocode());
values.put("cacheid", cache.getCacheId());
values.put("guid", cache.getGuid());
values.put("type", cache.getType().id);
values.put("name", cache.getName());
values.put("owner", cache.getOwnerDisplayName());
values.put("owner_real", cache.getOwnerUserId());
final Date hiddenDate = cache.getHiddenDate();
if (hiddenDate == null) {
values.put("hidden", 0);
} else {
values.put("hidden", hiddenDate.getTime());
}
values.put("hint", cache.getHint());
values.put("size", cache.getSize().id);
values.put("difficulty", cache.getDifficulty());
values.put("terrain", cache.getTerrain());
values.put("location", cache.getLocation());
values.put("distance", cache.getDistance());
values.put("direction", cache.getDirection());
putCoords(values, cache.getCoords());
values.put("reliable_latlon", cache.isReliableLatLon() ? 1 : 0);
values.put("shortdesc", cache.getShortDescription());
values.put("personal_note", cache.getPersonalNote());
values.put("description", cache.getDescription());
values.put("favourite_cnt", cache.getFavoritePoints());
values.put("rating", cache.getRating());
values.put("votes", cache.getVotes());
values.put("myvote", cache.getMyVote());
values.put("disabled", cache.isDisabled() ? 1 : 0);
values.put("archived", cache.isArchived() ? 1 : 0);
values.put("members", cache.isPremiumMembersOnly() ? 1 : 0);
values.put("found", cache.isFound() ? 1 : 0);
values.put("favourite", cache.isFavorite() ? 1 : 0);
values.put("inventoryunknown", cache.getInventoryItems());
values.put("onWatchlist", cache.isOnWatchlist() ? 1 : 0);
values.put("coordsChanged", cache.hasUserModifiedCoords() ? 1 : 0);
values.put("finalDefined", cache.hasFinalDefined() ? 1 : 0);
values.put("logPasswordRequired", cache.isLogPasswordRequired() ? 1 : 0);
values.put("watchlistCount",cache.getWatchlistCount());
init();
// try to update record else insert fresh..
database.beginTransaction();
try {
saveAttributesWithoutTransaction(cache);
saveWaypointsWithoutTransaction(cache);
saveSpoilersWithoutTransaction(cache);
saveLogCountsWithoutTransaction(cache);
saveInventoryWithoutTransaction(cache.getGeocode(), cache.getInventory());
saveListsWithoutTransaction(cache);
final int rows = database.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() });
if (rows == 0) {
// cache is not in the DB, insert it
/* long id = */
database.insert(dbTableCaches, null, values);
}
database.setTransactionSuccessful();
return true;
} catch (final Exception e) {
Log.e("SaveCache", e);
} finally {
database.endTransaction();
}
return false;
}
private static void saveAttributesWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
// The attributes must be fetched first because lazy loading may load
// a null set otherwise.
final List<String> attributes = cache.getAttributes();
database.delete(dbTableAttributes, "geocode = ?", new String[]{geocode});
if (attributes.isEmpty()) {
return;
}
final SQLiteStatement statement = PreparedStatement.INSERT_ATTRIBUTE.getStatement();
final long timestamp = System.currentTimeMillis();
for (final String attribute : attributes) {
statement.bindString(1, geocode);
statement.bindLong(2, timestamp);
statement.bindString(3, attribute);
statement.executeInsert();
}
}
private static void saveListsWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
// The lists must be fetched first because lazy loading may load
// a null set otherwise.
final Set<Integer> lists = cache.getLists();
if (lists.isEmpty()) {
return;
}
final SQLiteStatement statement = PreparedStatement.ADD_TO_LIST.getStatement();
for (final Integer list_id : lists) {
statement.bindLong(1, list_id);
statement.bindString(2, geocode);
statement.executeInsert();
}
}
/**
* Persists the given {@code destination} into the database.
*
* @param destination
* a destination to save
*/
public static void saveSearchedDestination(final Destination destination) {
init();
database.beginTransaction();
try {
final SQLiteStatement insertDestination = PreparedStatement.INSERT_SEARCH_DESTINATION.getStatement();
insertDestination.bindLong(1, destination.getDate());
final Geopoint coords = destination.getCoords();
insertDestination.bindDouble(2, coords.getLatitude());
insertDestination.bindDouble(3, coords.getLongitude());
insertDestination.executeInsert();
database.setTransactionSuccessful();
} catch (final Exception e) {
Log.e("Updating searchedDestinations db failed", e);
} finally {
database.endTransaction();
}
}
public static boolean saveWaypoints(final Geocache cache) {
init();
database.beginTransaction();
try {
saveWaypointsWithoutTransaction(cache);
database.setTransactionSuccessful();
return true;
} catch (final Exception e) {
Log.e("saveWaypoints", e);
} finally {
database.endTransaction();
}
return false;
}
private static void saveWaypointsWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
final List<Waypoint> waypoints = cache.getWaypoints();
if (CollectionUtils.isNotEmpty(waypoints)) {
final List<String> currentWaypointIds = new ArrayList<>();
final ContentValues values = new ContentValues();
final long timeStamp = System.currentTimeMillis();
for (final Waypoint oneWaypoint : waypoints) {
values.clear();
values.put("geocode", geocode);
values.put("updated", timeStamp);
values.put("type", oneWaypoint.getWaypointType() != null ? oneWaypoint.getWaypointType().id : null);
values.put("prefix", oneWaypoint.getPrefix());
values.put("lookup", oneWaypoint.getLookup());
values.put("name", oneWaypoint.getName());
putCoords(values, oneWaypoint.getCoords());
values.put("note", oneWaypoint.getNote());
values.put("own", oneWaypoint.isUserDefined() ? 1 : 0);
values.put("visited", oneWaypoint.isVisited() ? 1 : 0);
if (oneWaypoint.getId() < 0) {
final long rowId = database.insert(dbTableWaypoints, null, values);
oneWaypoint.setId((int) rowId);
} else {
database.update(dbTableWaypoints, values, "_id = ?", new String[] { Integer.toString(oneWaypoint.getId(), 10) });
}
currentWaypointIds.add(Integer.toString(oneWaypoint.getId()));
}
removeOutdatedWaypointsOfCache(cache, currentWaypointIds);
}
}
/**
* remove all waypoints of the given cache, where the id is not in the given list
*
* @param remainingWaypointIds
* ids of waypoints which shall not be deleted
*/
private static void removeOutdatedWaypointsOfCache(final @NonNull Geocache cache, final @NonNull Collection<String> remainingWaypointIds) {
final String idList = StringUtils.join(remainingWaypointIds, ',');
database.delete(dbTableWaypoints, "geocode = ? AND _id NOT in (" + idList + ")", new String[]{cache.getGeocode()});
}
/**
* Save coordinates into a ContentValues
*
* @param values
* a ContentValues to save coordinates in
* @param coords
* coordinates to save, or null to save empty coordinates
*/
private static void putCoords(final ContentValues values, final Geopoint coords) {
values.put("latitude", coords == null ? null : coords.getLatitude());
values.put("longitude", coords == null ? null : coords.getLongitude());
}
/**
* Retrieve coordinates from a Cursor
*
* @param cursor
* a Cursor representing a row in the database
* @param indexLat
* index of the latitude column
* @param indexLon
* index of the longitude column
* @return the coordinates, or null if latitude or longitude is null or the coordinates are invalid
*/
@Nullable
private static Geopoint getCoords(final Cursor cursor, final int indexLat, final int indexLon) {
if (cursor.isNull(indexLat) || cursor.isNull(indexLon)) {
return null;
}
return new Geopoint(cursor.getDouble(indexLat), cursor.getDouble(indexLon));
}
private static boolean saveWaypointInternal(final int id, final String geocode, final Waypoint waypoint) {
if ((StringUtils.isBlank(geocode) && id <= 0) || waypoint == null) {
return false;
}
init();
database.beginTransaction();
boolean ok = false;
try {
final ContentValues values = new ContentValues();
values.put("geocode", geocode);
values.put("updated", System.currentTimeMillis());
values.put("type", waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null);
values.put("prefix", waypoint.getPrefix());
values.put("lookup", waypoint.getLookup());
values.put("name", waypoint.getName());
putCoords(values, waypoint.getCoords());
values.put("note", waypoint.getNote());
values.put("own", waypoint.isUserDefined() ? 1 : 0);
values.put("visited", waypoint.isVisited() ? 1 : 0);
if (id <= 0) {
final long rowId = database.insert(dbTableWaypoints, null, values);
waypoint.setId((int) rowId);
ok = true;
} else {
final int rows = database.update(dbTableWaypoints, values, "_id = " + id, null);
ok = rows > 0;
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return ok;
}
public static boolean deleteWaypoint(final int id) {
if (id == 0) {
return false;
}
init();
return database.delete(dbTableWaypoints, "_id = " + id, null) > 0;
}
private static void saveSpoilersWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
database.delete(dbTableSpoilers, "geocode = ?", new String[]{geocode});
final List<Image> spoilers = cache.getSpoilers();
if (CollectionUtils.isNotEmpty(spoilers)) {
final SQLiteStatement insertSpoiler = PreparedStatement.INSERT_SPOILER.getStatement();
final long timestamp = System.currentTimeMillis();
for (final Image spoiler : spoilers) {
insertSpoiler.bindString(1, geocode);
insertSpoiler.bindLong(2, timestamp);
insertSpoiler.bindString(3, spoiler.getUrl());
insertSpoiler.bindString(4, StringUtils.defaultIfBlank(spoiler.title, ""));
final String description = spoiler.getDescription();
if (StringUtils.isNotBlank(description)) {
insertSpoiler.bindString(5, description);
} else {
insertSpoiler.bindNull(5);
}
insertSpoiler.executeInsert();
}
}
}
public static void saveLogs(final String geocode, final Iterable<LogEntry> logs) {
database.beginTransaction();
try {
saveLogsWithoutTransaction(geocode, logs);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
private static void saveLogsWithoutTransaction(final String geocode, final Iterable<LogEntry> logs) {
// TODO delete logimages referring these logs
database.delete(dbTableLogs, "geocode = ?", new String[]{geocode});
final SQLiteStatement insertLog = PreparedStatement.INSERT_LOG.getStatement();
final long timestamp = System.currentTimeMillis();
for (final LogEntry log : logs) {
insertLog.bindString(1, geocode);
insertLog.bindLong(2, timestamp);
insertLog.bindLong(3, log.getType().id);
insertLog.bindString(4, log.author);
insertLog.bindString(5, log.log);
insertLog.bindLong(6, log.date);
insertLog.bindLong(7, log.found);
insertLog.bindLong(8, log.friend ? 1 : 0);
final long logId = insertLog.executeInsert();
if (log.hasLogImages()) {
final SQLiteStatement insertImage = PreparedStatement.INSERT_LOG_IMAGE.getStatement();
for (final Image img : log.getLogImages()) {
insertImage.bindLong(1, logId);
insertImage.bindString(2, StringUtils.defaultIfBlank(img.title, ""));
insertImage.bindString(3, img.getUrl());
insertImage.bindString(4, StringUtils.defaultIfBlank(img.getDescription(), ""));
insertImage.executeInsert();
}
}
}
}
private static void saveLogCountsWithoutTransaction(final Geocache cache) {
final String geocode = cache.getGeocode();
database.delete(dbTableLogCount, "geocode = ?", new String[]{geocode});
final Map<LogType, Integer> logCounts = cache.getLogCounts();
if (MapUtils.isNotEmpty(logCounts)) {
final Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet();
final SQLiteStatement insertLogCounts = PreparedStatement.INSERT_LOG_COUNTS.getStatement();
final long timestamp = System.currentTimeMillis();
for (final Entry<LogType, Integer> pair : logCountsItems) {
insertLogCounts.bindString(1, geocode);
insertLogCounts.bindLong(2, timestamp);
insertLogCounts.bindLong(3, pair.getKey().id);
insertLogCounts.bindLong(4, pair.getValue());
insertLogCounts.executeInsert();
}
}
}
public static void saveTrackable(final Trackable trackable) {
init();
database.beginTransaction();
try {
saveInventoryWithoutTransaction(null, Collections.singletonList(trackable));
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
private static void saveInventoryWithoutTransaction(final String geocode, final List<Trackable> trackables) {
if (geocode != null) {
database.delete(dbTableTrackables, "geocode = ?", new String[]{geocode});
}
if (CollectionUtils.isNotEmpty(trackables)) {
final ContentValues values = new ContentValues();
final long timeStamp = System.currentTimeMillis();
for (final Trackable trackable : trackables) {
final String tbCode = trackable.getGeocode();
if (StringUtils.isNotBlank(tbCode)) {
database.delete(dbTableTrackables, "tbcode = ?", new String[] { tbCode });
}
values.clear();
if (geocode != null) {
values.put("geocode", geocode);
}
values.put("updated", timeStamp);
values.put("tbcode", tbCode);
values.put("guid", trackable.getGuid());
values.put("title", trackable.getName());
values.put("owner", trackable.getOwner());
final Date releasedDate = trackable.getReleased();
if (releasedDate != null) {
values.put("released", releasedDate.getTime());
} else {
values.put("released", 0L);
}
values.put("goal", trackable.getGoal());
values.put("description", trackable.getDetails());
database.insert(dbTableTrackables, null, values);
saveLogsWithoutTransaction(tbCode, trackable.getLogs());
}
}
}
@Nullable
public static Viewport getBounds(final Set<String> geocodes) {
if (CollectionUtils.isEmpty(geocodes)) {
return null;
}
final Set<Geocache> caches = loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB);
return Viewport.containing(caches);
}
/**
* Load a single Cache.
*
* @param geocode
* The Geocode GCXXXX
* @return the loaded cache (if found). Can be null
*/
@Nullable
public static Geocache loadCache(final String geocode, final EnumSet<LoadFlag> loadFlags) {
if (StringUtils.isBlank(geocode)) {
throw new IllegalArgumentException("geocode must not be empty");
}
final Set<Geocache> caches = loadCaches(Collections.singleton(geocode), loadFlags);
return caches.isEmpty() ? null : caches.iterator().next();
}
/**
* Load caches.
*
* @return Set of loaded caches. Never null.
*/
@NonNull
public static Set<Geocache> loadCaches(final Collection<String> geocodes, final EnumSet<LoadFlag> loadFlags) {
if (CollectionUtils.isEmpty(geocodes)) {
return new HashSet<>();
}
final Set<Geocache> result = new HashSet<>(geocodes.size());
final Set<String> remaining = new HashSet<>(geocodes);
if (loadFlags.contains(LoadFlag.CACHE_BEFORE)) {
for (final String geocode : geocodes) {
final Geocache cache = cacheCache.getCacheFromCache(geocode);
if (cache != null) {
result.add(cache);
remaining.remove(cache.getGeocode());
}
}
}
if (loadFlags.contains(LoadFlag.DB_MINIMAL) ||
loadFlags.contains(LoadFlag.ATTRIBUTES) ||
loadFlags.contains(LoadFlag.WAYPOINTS) ||
loadFlags.contains(LoadFlag.SPOILERS) ||
loadFlags.contains(LoadFlag.LOGS) ||
loadFlags.contains(LoadFlag.INVENTORY) ||
loadFlags.contains(LoadFlag.OFFLINE_LOG)) {
final Set<Geocache> cachesFromDB = loadCachesFromGeocodes(remaining, loadFlags);
result.addAll(cachesFromDB);
for (final Geocache cache : cachesFromDB) {
remaining.remove(cache.getGeocode());
}
}
if (loadFlags.contains(LoadFlag.CACHE_AFTER)) {
for (final String geocode : new HashSet<>(remaining)) {
final Geocache cache = cacheCache.getCacheFromCache(geocode);
if (cache != null) {
result.add(cache);
remaining.remove(cache.getGeocode());
}
}
}
if (CollectionUtils.isNotEmpty(remaining)) {
Log.d("DataStore.loadCaches(" + remaining.toString() + ") returned no results");
}
return result;
}
/**
* Load caches.
*
* @return Set of loaded caches. Never null.
*/
@NonNull
private static Set<Geocache> loadCachesFromGeocodes(final Set<String> geocodes, final EnumSet<LoadFlag> loadFlags) {
if (CollectionUtils.isEmpty(geocodes)) {
return Collections.emptySet();
}
// do not log the entire collection of geo codes to the debug log. This can be more than 100 KB of text for large lists!
init();
final StringBuilder query = new StringBuilder(QUERY_CACHE_DATA);
if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) {
query.append(',').append(dbTableLogsOffline).append(".log");
}
query.append(" FROM ").append(dbTableCaches);
if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) {
query.append(" LEFT OUTER JOIN ").append(dbTableLogsOffline).append(" ON ( ").append(dbTableCaches).append(".geocode == ").append(dbTableLogsOffline).append(".geocode) ");
}
query.append(" WHERE ").append(dbTableCaches).append('.');
query.append(whereGeocodeIn(geocodes));
final Cursor cursor = database.rawQuery(query.toString(), null);
try {
final Set<Geocache> caches = new HashSet<>();
int logIndex = -1;
while (cursor.moveToNext()) {
final Geocache cache = createCacheFromDatabaseContent(cursor);
cache.setLists(loadLists(cache.getGeocode()));
if (loadFlags.contains(LoadFlag.ATTRIBUTES)) {
cache.setAttributes(loadAttributes(cache.getGeocode()));
}
if (loadFlags.contains(LoadFlag.WAYPOINTS)) {
final List<Waypoint> waypoints = loadWaypoints(cache.getGeocode());
if (CollectionUtils.isNotEmpty(waypoints)) {
cache.setWaypoints(waypoints, false);
}
}
if (loadFlags.contains(LoadFlag.SPOILERS)) {
final List<Image> spoilers = loadSpoilers(cache.getGeocode());
cache.setSpoilers(spoilers);
}
if (loadFlags.contains(LoadFlag.LOGS)) {
final Map<LogType, Integer> logCounts = loadLogCounts(cache.getGeocode());
if (MapUtils.isNotEmpty(logCounts)) {
cache.getLogCounts().clear();
cache.getLogCounts().putAll(logCounts);
}
}
if (loadFlags.contains(LoadFlag.INVENTORY)) {
final List<Trackable> inventory = loadInventory(cache.getGeocode());
if (CollectionUtils.isNotEmpty(inventory)) {
cache.setInventory(inventory);
}
}
if (loadFlags.contains(LoadFlag.OFFLINE_LOG)) {
if (logIndex < 0) {
logIndex = cursor.getColumnIndex("log");
}
cache.setLogOffline(!cursor.isNull(logIndex));
}
cache.addStorageLocation(StorageLocation.DATABASE);
cacheCache.putCacheInCache(cache);
caches.add(cache);
}
return caches;
} finally {
cursor.close();
}
}
/**
* Builds a where for a viewport with the size enhanced by 50%.
*
*/
@NonNull
private static StringBuilder buildCoordinateWhere(final String dbTable, final Viewport viewport) {
return viewport.resize(1.5).sqlWhere(dbTable);
}
/**
* creates a Cache from the cursor. Doesn't next.
*
* @return Cache from DB
*/
@NonNull
private static Geocache createCacheFromDatabaseContent(final Cursor cursor) {
final Geocache cache = new Geocache();
cache.setUpdated(cursor.getLong(0));
cache.setDetailed(cursor.getInt(2) == 1);
cache.setDetailedUpdate(cursor.getLong(3));
cache.setVisitedDate(cursor.getLong(4));
cache.setGeocode(cursor.getString(5));
cache.setCacheId(cursor.getString(6));
cache.setGuid(cursor.getString(7));
cache.setType(CacheType.getById(cursor.getString(8)));
cache.setName(cursor.getString(9));
cache.setOwnerDisplayName(cursor.getString(10));
cache.setOwnerUserId(cursor.getString(11));
final long dateValue = cursor.getLong(12);
if (dateValue != 0) {
cache.setHidden(new Date(dateValue));
}
// do not set cache.hint
cache.setSize(CacheSize.getById(cursor.getString(14)));
cache.setDifficulty(cursor.getFloat(15));
final int directionIndex = 16;
if (cursor.isNull(directionIndex)) {
cache.setDirection(null);
} else {
cache.setDirection(cursor.getFloat(directionIndex));
}
final int distanceIndex = 17;
if (cursor.isNull(distanceIndex)) {
cache.setDistance(null);
} else {
cache.setDistance(cursor.getFloat(distanceIndex));
}
cache.setTerrain(cursor.getFloat(18));
// do not set cache.location
cache.setPersonalNote(cursor.getString(20));
// do not set cache.shortdesc
// do not set cache.description
cache.setFavoritePoints(cursor.getInt(22));
cache.setRating(cursor.getFloat(23));
cache.setVotes(cursor.getInt(24));
cache.setMyVote(cursor.getFloat(25));
cache.setDisabled(cursor.getInt(26) == 1);
cache.setArchived(cursor.getInt(27) == 1);
cache.setPremiumMembersOnly(cursor.getInt(28) == 1);
cache.setFound(cursor.getInt(29) == 1);
cache.setFavorite(cursor.getInt(30) == 1);
cache.setInventoryItems(cursor.getInt(31));
cache.setOnWatchlist(cursor.getInt(32) == 1);
cache.setReliableLatLon(cursor.getInt(33) > 0);
cache.setUserModifiedCoords(cursor.getInt(34) > 0);
cache.setCoords(getCoords(cursor, 35, 36));
cache.setFinalDefined(cursor.getInt(37) > 0);
cache.setLogPasswordRequired(cursor.getInt(41) > 0);
cache.setWatchlistCount(cursor.getInt(42));
Log.d("Loading " + cache.toString() + " from DB");
return cache;
}
@Nullable
public static List<String> loadAttributes(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
return queryToColl(dbTableAttributes,
new String[]{"attribute"},
"geocode = ?",
new String[]{geocode},
null,
"100",
new LinkedList<String>(),
GET_STRING_0);
}
@Nullable
public static Set<Integer> loadLists(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
return queryToColl(dbTableCachesLists,
new String[]{"list_id"},
"geocode = ?",
new String[]{geocode},
null,
"100",
new HashSet<Integer>(),
GET_INTEGER_0);
}
@Nullable
public static Waypoint loadWaypoint(final int id) {
if (id == 0) {
return null;
}
init();
final Cursor cursor = database.query(
dbTableWaypoints,
WAYPOINT_COLUMNS,
"_id = ?",
new String[]{Integer.toString(id)},
null,
null,
null,
"1");
Log.d("DataStore.loadWaypoint(" + id + ")");
final Waypoint waypoint = cursor.moveToFirst() ? createWaypointFromDatabaseContent(cursor) : null;
cursor.close();
return waypoint;
}
@Nullable
public static List<Waypoint> loadWaypoints(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
return queryToColl(dbTableWaypoints,
WAYPOINT_COLUMNS,
"geocode = ?",
new String[]{geocode},
"_id",
"100",
new LinkedList<Waypoint>(),
new Func1<Cursor, Waypoint>() {
@Override
public Waypoint call(final Cursor cursor) {
return createWaypointFromDatabaseContent(cursor);
}
});
}
@NonNull
private static Waypoint createWaypointFromDatabaseContent(final Cursor cursor) {
final String name = cursor.getString(cursor.getColumnIndex("name"));
final WaypointType type = WaypointType.findById(cursor.getString(cursor.getColumnIndex("type")));
final boolean own = cursor.getInt(cursor.getColumnIndex("own")) != 0;
final Waypoint waypoint = new Waypoint(name, type, own);
waypoint.setVisited(cursor.getInt(cursor.getColumnIndex("visited")) != 0);
waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id")));
waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode")));
waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix")));
waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup")));
waypoint.setCoords(getCoords(cursor, cursor.getColumnIndex("latitude"), cursor.getColumnIndex("longitude")));
waypoint.setNote(cursor.getString(cursor.getColumnIndex("note")));
return waypoint;
}
@Nullable
private static List<Image> loadSpoilers(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
return queryToColl(dbTableSpoilers,
new String[]{"url", "title", "description"},
"geocode = ?",
new String[]{geocode},
null,
"100",
new LinkedList<Image>(),
new Func1<Cursor, Image>() {
@Override
public Image call(final Cursor cursor) {
return new Image.Builder()
.setUrl(cursor.getString(0))
.setTitle(cursor.getString(1))
.setDescription(cursor.getString(2))
.build();
}
});
}
/**
* Loads the history of previously entered destinations from
* the database. If no destinations exist, an {@link Collections#emptyList()} will be returned.
*
* @return A list of previously entered destinations or an empty list.
*/
@NonNull
public static List<Destination> loadHistoryOfSearchedLocations() {
return queryToColl(dbTableSearchDestinationHistory,
new String[]{"_id", "date", "latitude", "longitude"},
"latitude IS NOT NULL AND longitude IS NOT NULL",
null,
"date desc",
"100",
new LinkedList<Destination>(),
new Func1<Cursor, Destination>() {
@Override
public Destination call(final Cursor cursor) {
return new Destination(cursor.getLong(0), cursor.getLong(1), getCoords(cursor, 2, 3));
}
});
}
public static boolean clearSearchedDestinations() {
init();
database.beginTransaction();
try {
database.delete(dbTableSearchDestinationHistory, null, null);
database.setTransactionSuccessful();
return true;
} catch (final Exception e) {
Log.e("Unable to clear searched destinations", e);
} finally {
database.endTransaction();
}
return false;
}
/**
* @return an immutable, non null list of logs
*/
@NonNull
public static List<LogEntry> loadLogs(final String geocode) {
final List<LogEntry> logs = new ArrayList<>();
if (StringUtils.isBlank(geocode)) {
return logs;
}
init();
final Cursor cursor = database.rawQuery(
// 0 1 2 3 4 5 6 7 8 9 10 11
"SELECT cg_logs._id as cg_logs_id, type, author, log, date, found, friend, " + dbTableLogImages + "._id as cg_logImages_id, log_id, title, url, description"
+ " FROM " + dbTableLogs + " LEFT OUTER JOIN " + dbTableLogImages
+ " ON ( cg_logs._id = log_id ) WHERE geocode = ? ORDER BY date desc, cg_logs._id asc", new String[]{geocode});
LogEntry.Builder log = null;
while (cursor.moveToNext() && logs.size() < 100) {
if (log == null || log.getId() != cursor.getInt(0)) {
// Start of a new log entry group (we may have several entries if the log has several images).
if (log != null) {
logs.add(log.build());
}
log = new LogEntry.Builder()
.setAuthor(cursor.getString(2))
.setDate(cursor.getLong(4))
.setLogType(LogType.getById(cursor.getInt(1)))
.setLog(cursor.getString(3))
.setId(cursor.getInt(0))
.setFound(cursor.getInt(5))
.setFriend(cursor.getInt(6) == 1);
if (!cursor.isNull(7)) {
log.addLogImage(new Image.Builder().setUrl(cursor.getString(10)).setTitle(cursor.getString(9)).setDescription(cursor.getString(11)).build());
}
} else {
// We cannot get several lines for the same log entry if it does not contain an image.
assert(!cursor.isNull(7));
log.addLogImage(new Image.Builder().setUrl(cursor.getString(10)).setTitle(cursor.getString(9)).setDescription(cursor.getString(11)).build());
}
}
if (log != null) {
logs.add(log.build());
}
cursor.close();
return Collections.unmodifiableList(logs);
}
@Nullable
public static Map<LogType, Integer> loadLogCounts(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
final Map<LogType, Integer> logCounts = new EnumMap<>(LogType.class);
final Cursor cursor = database.query(
dbTableLogCount,
new String[]{"type", "count"},
"geocode = ?",
new String[]{geocode},
null,
null,
null,
"100");
while (cursor.moveToNext()) {
logCounts.put(LogType.getById(cursor.getInt(0)), cursor.getInt(1));
}
cursor.close();
return logCounts;
}
@Nullable
private static List<Trackable> loadInventory(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
final List<Trackable> trackables = new ArrayList<>();
final Cursor cursor = database.query(
dbTableTrackables,
new String[]{"_id", "updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"},
"geocode = ?",
new String[]{geocode},
null,
null,
"title COLLATE NOCASE ASC",
"100");
while (cursor.moveToNext()) {
trackables.add(createTrackableFromDatabaseContent(cursor));
}
cursor.close();
return trackables;
}
@Nullable
public static Trackable loadTrackable(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
final Cursor cursor = database.query(
dbTableTrackables,
new String[]{"updated", "tbcode", "guid", "title", "owner", "released", "goal", "description"},
"tbcode = ?",
new String[]{geocode},
null,
null,
null,
"1");
final Trackable trackable = cursor.moveToFirst() ? createTrackableFromDatabaseContent(cursor) : null;
cursor.close();
return trackable;
}
@NonNull
private static Trackable createTrackableFromDatabaseContent(final Cursor cursor) {
final Trackable trackable = new Trackable();
trackable.setGeocode(cursor.getString(cursor.getColumnIndex("tbcode")));
trackable.setGuid(cursor.getString(cursor.getColumnIndex("guid")));
trackable.setName(cursor.getString(cursor.getColumnIndex("title")));
trackable.setOwner(cursor.getString(cursor.getColumnIndex("owner")));
final String released = cursor.getString(cursor.getColumnIndex("released"));
if (released != null) {
try {
final long releaseMilliSeconds = Long.parseLong(released);
trackable.setReleased(new Date(releaseMilliSeconds));
} catch (final NumberFormatException e) {
Log.e("createTrackableFromDatabaseContent", e);
}
}
trackable.setGoal(cursor.getString(cursor.getColumnIndex("goal")));
trackable.setDetails(cursor.getString(cursor.getColumnIndex("description")));
trackable.setLogs(loadLogs(trackable.getGeocode()));
return trackable;
}
/**
* Number of caches stored for a given type and/or list
*
*/
public static int getAllStoredCachesCount(final CacheType cacheType, final int list) {
if (cacheType == null) {
throw new IllegalArgumentException("cacheType must not be null");
}
if (list <= 0) {
throw new IllegalArgumentException("list must be > 0");
}
init();
try {
final SQLiteStatement compiledStmnt;
synchronized (PreparedStatement.COUNT_TYPE_LIST) {
// All the statements here are used only once and are protected through the current synchronized block
if (list == PseudoList.ALL_LIST.id) {
if (cacheType == CacheType.ALL) {
compiledStmnt = PreparedStatement.COUNT_ALL_TYPES_ALL_LIST.getStatement();
} else {
compiledStmnt = PreparedStatement.COUNT_TYPE_ALL_LIST.getStatement();
compiledStmnt.bindString(1, cacheType.id);
}
} else if (cacheType == CacheType.ALL) {
compiledStmnt = PreparedStatement.COUNT_ALL_TYPES_LIST.getStatement();
compiledStmnt.bindLong(1, list);
} else {
compiledStmnt = PreparedStatement.COUNT_TYPE_LIST.getStatement();
compiledStmnt.bindString(1, cacheType.id);
compiledStmnt.bindLong(1, list);
}
return (int) compiledStmnt.simpleQueryForLong();
}
} catch (final Exception e) {
Log.e("DataStore.loadAllStoredCachesCount", e);
}
return 0;
}
public static int getAllHistoryCachesCount() {
init();
try {
return (int) PreparedStatement.HISTORY_COUNT.simpleQueryForLong();
} catch (final Exception e) {
Log.e("DataStore.getAllHistoricCachesCount", e);
}
return 0;
}
@NonNull
private static<T, U extends Collection<? super T>> U queryToColl(@NonNull final String table,
final String[] columns,
final String selection,
final String[] selectionArgs,
final String orderBy,
final String limit,
final U result,
final Func1<? super Cursor, ? extends T> func) {
init();
final Cursor cursor = database.query(table, columns, selection, selectionArgs, null, null, orderBy, limit);
return cursorToColl(cursor, result, func);
}
private static <T, U extends Collection<? super T>> U cursorToColl(final Cursor cursor, final U result, final Func1<? super Cursor, ? extends T> func) {
try {
while (cursor.moveToNext()) {
result.add(func.call(cursor));
}
return result;
} finally {
cursor.close();
}
}
/**
* Return a batch of stored geocodes.
*
* @param coords
* the current coordinates to sort by distance, or null to sort by geocode
* @return a non-null set of geocodes
*/
@NonNull
private static Set<String> loadBatchOfStoredGeocodes(final Geopoint coords, final CacheType cacheType, final int listId) {
if (cacheType == null) {
throw new IllegalArgumentException("cacheType must not be null");
}
final StringBuilder selection = new StringBuilder();
selection.append(" detailed = 1 ");
String[] selectionArgs = null;
if (cacheType != CacheType.ALL) {
selection.append(" and type = ?");
selectionArgs = new String[] { String.valueOf(cacheType.id) };
}
selection.append(" and geocode in (SELECT geocode FROM ");
selection.append(dbTableCachesLists);
selection.append(" WHERE list_id ");
selection.append(listId != PseudoList.ALL_LIST.id ? "=" + Math.max(listId, 1) : ">= " + StoredList.STANDARD_LIST_ID);
selection.append(")");
try {
if (coords != null) {
return queryToColl(dbTableCaches,
new String[]{"geocode", "(abs(latitude-" + String.format((Locale) null, "%.6f", coords.getLatitude()) +
") + abs(longitude-" + String.format((Locale) null, "%.6f", coords.getLongitude()) + ")) as dif"},
selection.toString(),
selectionArgs,
"dif",
null,
new HashSet<String>(),
GET_STRING_0);
}
return queryToColl(dbTableCaches,
new String[] { "geocode" },
selection.toString(),
selectionArgs,
"geocode",
null,
new HashSet<String>(),
GET_STRING_0);
} catch (final Exception e) {
Log.e("DataStore.loadBatchOfStoredGeocodes", e);
return Collections.emptySet();
}
}
@NonNull
private static Set<String> loadBatchOfHistoricGeocodes(final boolean detailedOnly, final CacheType cacheType) {
final StringBuilder selection = new StringBuilder("visiteddate > 0");
if (detailedOnly) {
selection.append(" and detailed = 1");
}
String[] selectionArgs = null;
if (cacheType != CacheType.ALL) {
selection.append(" and type = ?");
selectionArgs = new String[] { String.valueOf(cacheType.id) };
}
try {
return queryToColl(dbTableCaches,
new String[]{"geocode"},
selection.toString(),
selectionArgs,
"visiteddate",
null,
new HashSet<String>(),
GET_STRING_0);
} catch (final Exception e) {
Log.e("DataStore.loadBatchOfHistoricGeocodes", e);
}
return Collections.emptySet();
}
/** Retrieve all stored caches from DB */
@NonNull
public static SearchResult loadCachedInViewport(final Viewport viewport, final CacheType cacheType) {
return loadInViewport(false, viewport, cacheType);
}
/** Retrieve stored caches from DB with listId >= 1 */
@NonNull
public static SearchResult loadStoredInViewport(final Viewport viewport, final CacheType cacheType) {
return loadInViewport(true, viewport, cacheType);
}
/**
* Loads the geocodes of caches in a viewport from CacheCache and/or Database
*
* @param stored {@code true} to query caches stored in the database, {@code false} to also use the CacheCache
* @param viewport the viewport defining the area to scan
* @param cacheType the cache type
* @return the matching caches
*/
@NonNull
private static SearchResult loadInViewport(final boolean stored, final Viewport viewport, final CacheType cacheType) {
final Set<String> geocodes = new HashSet<>();
// if not stored only, get codes from CacheCache as well
if (!stored) {
geocodes.addAll(cacheCache.getInViewport(viewport, cacheType));
}
// viewport limitation
final StringBuilder selection = buildCoordinateWhere(dbTableCaches, viewport);
// cacheType limitation
String[] selectionArgs = null;
if (cacheType != CacheType.ALL) {
selection.append(" and type = ?");
selectionArgs = new String[] { String.valueOf(cacheType.id) };
}
// offline caches only
if (stored) {
selection.append(" and geocode in (select geocode from " + dbTableCachesLists + " where list_id >= " + StoredList.STANDARD_LIST_ID + ")");
}
try {
return new SearchResult(queryToColl(dbTableCaches,
new String[]{"geocode"},
selection.toString(),
selectionArgs,
null,
"500",
geocodes,
GET_STRING_0));
} catch (final Exception e) {
Log.e("DataStore.loadInViewport", e);
}
return new SearchResult();
}
/**
* Remove caches which are not on any list in the background. Once it has been executed once it will not do anything.
* This must be called from the UI thread to ensure synchronization of an internal variable.
*/
public static void cleanIfNeeded(final Context context) {
if (databaseCleaned) {
return;
}
databaseCleaned = true;
Schedulers.io().createWorker().schedule(new Action0() {
@Override
public void call() {
Log.d("Database clean: started");
try {
final int version = Version.getVersionCode(context);
final Set<String> geocodes = new HashSet<>();
if (version != Settings.getVersion()) {
queryToColl(dbTableCaches,
new String[]{"geocode"},
"geocode NOT IN (SELECT distinct (geocode) FROM " + dbTableCachesLists + ")",
null,
null,
null,
geocodes,
GET_STRING_0);
} else {
final long timestamp = System.currentTimeMillis() - DAYS_AFTER_CACHE_IS_DELETED;
final String timestampString = Long.toString(timestamp);
queryToColl(dbTableCaches,
new String[]{"geocode"},
"detailed < ? and detailedupdate < ? and visiteddate < ? and geocode NOT IN (SELECT distinct (geocode) FROM " + dbTableCachesLists + ")",
new String[]{timestampString, timestampString, timestampString},
null,
null,
geocodes,
GET_STRING_0);
}
final Set<String> withoutOfflineLogs = exceptCachesWithOfflineLog(geocodes);
Log.d("Database clean: removing " + withoutOfflineLogs.size() + " geocaches");
removeCaches(withoutOfflineLogs, LoadFlags.REMOVE_ALL);
// This cleanup needs to be kept in place for about one year so that older log images records are
// cleaned. TO BE REMOVED AFTER 2015-03-24.
Log.d("Database clean: removing obsolete log images records");
database.delete(dbTableLogImages, "log_id NOT IN (SELECT _id FROM " + dbTableLogs + ")", null);
// remove non-existing caches from lists
Log.d("Database clean: removing non-existing caches from lists");
database.delete(dbTableCachesLists, "geocode NOT IN (SELECT geocode FROM " + dbTableCaches + ")", null);
// Remove the obsolete "_others" directory where the user avatar used to be stored.
FileUtils.deleteDirectory(LocalStorage.getStorageDir("_others"));
if (version > -1) {
Settings.setVersion(version);
}
} catch (final Exception e) {
Log.w("DataStore.clean", e);
}
Log.d("Database clean: finished");
}
});
}
/**
* remove all geocodes from the given list of geocodes where an offline log exists
*
*/
@NonNull
private static Set<String> exceptCachesWithOfflineLog(@NonNull final Set<String> geocodes) {
if (geocodes.isEmpty()) {
return geocodes;
}
final List<String> geocodesWithOfflineLog = queryToColl(dbTableLogsOffline,
new String[] { "geocode" },
null,
null,
null,
null,
new LinkedList<String>(),
GET_STRING_0);
geocodes.removeAll(geocodesWithOfflineLog);
return geocodes;
}
public static void removeAllFromCache() {
// clean up CacheCache
cacheCache.removeAllFromCache();
}
public static void removeCache(final String geocode, final EnumSet<LoadFlags.RemoveFlag> removeFlags) {
removeCaches(Collections.singleton(geocode), removeFlags);
}
/**
* Drop caches from the tables they are stored into, as well as the cache files
*
* @param geocodes
* list of geocodes to drop from cache
*/
public static void removeCaches(final Set<String> geocodes, final EnumSet<LoadFlags.RemoveFlag> removeFlags) {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
init();
if (removeFlags.contains(RemoveFlag.CACHE)) {
for (final String geocode : geocodes) {
cacheCache.removeCacheFromCache(geocode);
}
}
if (removeFlags.contains(RemoveFlag.DB)) {
// Drop caches from the database
final ArrayList<String> quotedGeocodes = new ArrayList<>(geocodes.size());
for (final String geocode : geocodes) {
quotedGeocodes.add(DatabaseUtils.sqlEscapeString(geocode));
}
final String geocodeList = StringUtils.join(quotedGeocodes.toArray(), ',');
final String baseWhereClause = "geocode in (" + geocodeList + ")";
database.beginTransaction();
try {
database.delete(dbTableCaches, baseWhereClause, null);
database.delete(dbTableAttributes, baseWhereClause, null);
database.delete(dbTableSpoilers, baseWhereClause, null);
database.delete(dbTableLogImages, "log_id IN (SELECT _id FROM " + dbTableLogs + " WHERE " + baseWhereClause + ")", null);
database.delete(dbTableLogs, baseWhereClause, null);
database.delete(dbTableLogCount, baseWhereClause, null);
database.delete(dbTableLogsOffline, baseWhereClause, null);
String wayPointClause = baseWhereClause;
if (!removeFlags.contains(RemoveFlag.OWN_WAYPOINTS_ONLY_FOR_TESTING)) {
wayPointClause += " and type <> 'own'";
}
database.delete(dbTableWaypoints, wayPointClause, null);
database.delete(dbTableTrackables, baseWhereClause, null);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
// Delete cache directories
for (final String geocode : geocodes) {
FileUtils.deleteDirectory(LocalStorage.getStorageDir(geocode));
}
}
}
public static boolean saveLogOffline(final String geocode, final Date date, final LogType type, final String log) {
if (StringUtils.isBlank(geocode)) {
Log.e("DataStore.saveLogOffline: cannot log a blank geocode");
return false;
}
if (type == LogType.UNKNOWN && StringUtils.isBlank(log)) {
Log.e("DataStore.saveLogOffline: cannot log an unknown log type and no message");
return false;
}
init();
final ContentValues values = new ContentValues();
values.put("geocode", geocode);
values.put("updated", System.currentTimeMillis());
values.put("type", type.id);
values.put("log", log);
values.put("date", date.getTime());
if (hasLogOffline(geocode)) {
final int rows = database.update(dbTableLogsOffline, values, "geocode = ?", new String[] { geocode });
return rows > 0;
}
final long id = database.insert(dbTableLogsOffline, null, values);
return id != -1;
}
@Nullable
public static LogEntry loadLogOffline(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return null;
}
init();
final Cursor cursor = database.query(
dbTableLogsOffline,
new String[]{"_id", "type", "log", "date"},
"geocode = ?",
new String[]{geocode},
null,
null,
"_id desc",
"1");
LogEntry log = null;
if (cursor.moveToFirst()) {
log = new LogEntry.Builder()
.setDate(cursor.getLong(3))
.setLogType(LogType.getById(cursor.getInt(1)))
.setLog(cursor.getString(2))
.setId(cursor.getInt(0))
.build();
}
cursor.close();
return log;
}
public static void clearLogOffline(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return;
}
init();
database.delete(dbTableLogsOffline, "geocode = ?", new String[]{geocode});
}
public static void clearLogsOffline(final List<Geocache> caches) {
if (CollectionUtils.isEmpty(caches)) {
return;
}
init();
for (final Geocache cache : caches) {
cache.setLogOffline(false);
}
database.execSQL(String.format("DELETE FROM %s where %s", dbTableLogsOffline, whereGeocodeIn(Geocache.getGeocodes(caches))));
}
public static boolean hasLogOffline(final String geocode) {
if (StringUtils.isBlank(geocode)) {
return false;
}
init();
try {
final SQLiteStatement logCount = PreparedStatement.LOG_COUNT_OF_GEOCODE.getStatement();
synchronized (logCount) {
logCount.bindString(1, geocode);
return logCount.simpleQueryForLong() > 0;
}
} catch (final Exception e) {
Log.e("DataStore.hasLogOffline", e);
}
return false;
}
private static void setVisitDate(final List<String> geocodes, final long visitedDate) {
if (geocodes.isEmpty()) {
return;
}
init();
database.beginTransaction();
try {
final SQLiteStatement setVisit = PreparedStatement.UPDATE_VISIT_DATE.getStatement();
for (final String geocode : geocodes) {
setVisit.bindLong(1, visitedDate);
setVisit.bindString(2, geocode);
setVisit.execute();
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
@NonNull
public static List<StoredList> getLists() {
init();
final Resources res = CgeoApplication.getInstance().getResources();
final List<StoredList> lists = new ArrayList<>();
lists.add(new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatement.COUNT_CACHES_ON_STANDARD_LIST.simpleQueryForLong()));
try {
final String query = "SELECT l._id as _id, l.title as title, COUNT(c.geocode) as count" +
" FROM " + dbTableLists + " l LEFT OUTER JOIN " + dbTableCachesLists + " c" +
" ON l._id + " + customListIdOffset + " = c.list_id" +
" GROUP BY l._id" +
" ORDER BY l.title COLLATE NOCASE ASC";
lists.addAll(getListsFromCursor(database.rawQuery(query, null)));
} catch (final Exception e) {
Log.e("DataStore.readLists", e);
}
return lists;
}
@NonNull
private static List<StoredList> getListsFromCursor(final Cursor cursor) {
final int indexId = cursor.getColumnIndex("_id");
final int indexTitle = cursor.getColumnIndex("title");
final int indexCount = cursor.getColumnIndex("count");
return cursorToColl(cursor, new ArrayList<StoredList>(), new Func1<Cursor, StoredList>() {
@Override
public StoredList call(final Cursor cursor) {
final int count = indexCount != -1 ? cursor.getInt(indexCount) : 0;
return new StoredList(cursor.getInt(indexId) + customListIdOffset, cursor.getString(indexTitle), count);
}
});
}
@NonNull
public static StoredList getList(final int id) {
init();
if (id >= customListIdOffset) {
final Cursor cursor = database.query(
dbTableLists,
new String[]{"_id", "title"},
"_id = ? ",
new String[] { String.valueOf(id - customListIdOffset) },
null,
null,
null);
final List<StoredList> lists = getListsFromCursor(cursor);
if (!lists.isEmpty()) {
return lists.get(0);
}
}
final Resources res = CgeoApplication.getInstance().getResources();
if (id == PseudoList.ALL_LIST.id) {
return new StoredList(PseudoList.ALL_LIST.id, res.getString(R.string.list_all_lists), getAllCachesCount());
}
// fall back to standard list in case of invalid list id
return new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatement.COUNT_CACHES_ON_STANDARD_LIST.simpleQueryForLong());
}
public static int getAllCachesCount() {
return (int) PreparedStatement.COUNT_ALL_CACHES.simpleQueryForLong();
}
/**
* Count all caches in the background.
*
* @return an observable containing a unique element if the caches could be counted, or an error otherwise
*/
public static Observable<Integer> getAllCachesCountObservable() {
return allCachesCountObservable;
}
/**
* Create a new list
*
* @param name
* Name
* @return new listId
*/
public static int createList(final String name) {
int id = -1;
if (StringUtils.isBlank(name)) {
return id;
}
init();
database.beginTransaction();
try {
final ContentValues values = new ContentValues();
values.put("title", name);
values.put("updated", System.currentTimeMillis());
id = (int) database.insert(dbTableLists, null, values);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return id >= 0 ? id + customListIdOffset : -1;
}
/**
* @param listId
* List to change
* @param name
* New name of list
* @return Number of lists changed
*/
public static int renameList(final int listId, final String name) {
if (StringUtils.isBlank(name) || listId == StoredList.STANDARD_LIST_ID) {
return 0;
}
init();
database.beginTransaction();
int count = 0;
try {
final ContentValues values = new ContentValues();
values.put("title", name);
values.put("updated", System.currentTimeMillis());
count = database.update(dbTableLists, values, "_id = " + (listId - customListIdOffset), null);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return count;
}
/**
* Remove a list. Caches in the list are moved to the standard list.
*
* @return true if the list got deleted, false else
*/
public static boolean removeList(final int listId) {
if (listId < customListIdOffset) {
return false;
}
init();
database.beginTransaction();
boolean status = false;
try {
final int cnt = database.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null);
if (cnt > 0) {
// move caches from deleted list to standard list
final SQLiteStatement moveToStandard = PreparedStatement.MOVE_TO_STANDARD_LIST.getStatement();
moveToStandard.bindLong(1, listId);
moveToStandard.execute();
final SQLiteStatement removeAllFromList = PreparedStatement.REMOVE_ALL_FROM_LIST.getStatement();
removeAllFromList.bindLong(1, listId);
removeAllFromList.execute();
status = true;
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return status;
}
public static void moveToList(final Collection<Geocache> caches, final int oldListId, final int newListId) {
if (caches.isEmpty()) {
return;
}
final AbstractList list = AbstractList.getListById(newListId);
if (list == null) {
return;
}
if (!list.isConcrete()) {
return;
}
init();
final SQLiteStatement remove = PreparedStatement.REMOVE_FROM_LIST.getStatement();
final SQLiteStatement add = PreparedStatement.ADD_TO_LIST.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
remove.bindLong(1, oldListId);
remove.bindString(2, cache.getGeocode());
remove.execute();
add.bindLong(1, newListId);
add.bindString(2, cache.getGeocode());
add.execute();
cache.getLists().remove(oldListId);
cache.getLists().add(newListId);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static void removeFromList(final Collection<Geocache> caches, final int oldListId) {
init();
final SQLiteStatement remove = PreparedStatement.REMOVE_FROM_LIST.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
remove.bindLong(1, oldListId);
remove.bindString(2, cache.getGeocode());
remove.execute();
cache.getLists().remove(oldListId);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static void addToList(final Collection<Geocache> caches, final int listId) {
if (caches.isEmpty()) {
return;
}
final AbstractList list = AbstractList.getListById(listId);
if (list == null) {
return;
}
if (!list.isConcrete()) {
return;
}
init();
final SQLiteStatement add = PreparedStatement.ADD_TO_LIST.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
add.bindLong(1, listId);
add.bindString(2, cache.getGeocode());
add.execute();
cache.getLists().add(listId);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static void addToLists(final Collection<Geocache> caches, final Map<String, Set<Integer>> cachesLists) {
if (caches.isEmpty() || cachesLists.isEmpty()) {
return;
}
init();
final SQLiteStatement add = PreparedStatement.ADD_TO_LIST.getStatement();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
final Set<Integer> lists = cachesLists.get(cache.getGeocode());
if (lists.isEmpty()) {
continue;
}
for (final Integer listId : lists) {
add.bindLong(1, listId);
add.bindString(2, cache.getGeocode());
add.execute();
}
cache.getLists().addAll(lists);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
public static boolean isInitialized() {
return database != null;
}
public static boolean removeSearchedDestination(final Destination destination) {
if (destination == null) {
return false;
}
init();
database.beginTransaction();
try {
database.delete(dbTableSearchDestinationHistory, "_id = " + destination.getId(), null);
database.setTransactionSuccessful();
return true;
} catch (final Exception e) {
Log.e("Unable to remove searched destination", e);
} finally {
database.endTransaction();
}
return false;
}
/**
* Load the lazily initialized fields of a cache and return them as partial cache (all other fields unset).
*
*/
@NonNull
public static Geocache loadCacheTexts(final String geocode) {
final Geocache partial = new Geocache();
// in case of database issues, we still need to return a result to avoid endless loops
partial.setDescription(StringUtils.EMPTY);
partial.setShortDescription(StringUtils.EMPTY);
partial.setHint(StringUtils.EMPTY);
partial.setLocation(StringUtils.EMPTY);
init();
try {
final Cursor cursor = database.query(
dbTableCaches,
new String[] { "description", "shortdesc", "hint", "location" },
"geocode = ?",
new String[] { geocode },
null,
null,
null,
"1");
if (cursor.moveToFirst()) {
partial.setDescription(StringUtils.defaultString(cursor.getString(0)));
partial.setShortDescription(StringUtils.defaultString(cursor.getString(1)));
partial.setHint(StringUtils.defaultString(cursor.getString(2)));
partial.setLocation(StringUtils.defaultString(cursor.getString(3)));
}
cursor.close();
} catch (final SQLiteDoneException ignored) {
// Do nothing, it only means we have no information on the cache
} catch (final Exception e) {
Log.e("DataStore.getCacheDescription", e);
}
return partial;
}
/**
* checks if this is a newly created database
*/
public static boolean isNewlyCreatedDatebase() {
return newlyCreatedDatabase;
}
/**
* resets flag for newly created database to avoid asking the user multiple times
*/
public static void resetNewlyCreatedDatabase() {
newlyCreatedDatabase = false;
}
/**
* Creates the WHERE clause for matching multiple geocodes. This automatically converts all given codes to
* UPPERCASE.
*/
@NonNull
private static StringBuilder whereGeocodeIn(final Collection<String> geocodes) {
final StringBuilder whereExpr = new StringBuilder("geocode in (");
final Iterator<String> iterator = geocodes.iterator();
while (true) {
DatabaseUtils.appendEscapedSQLString(whereExpr, StringUtils.upperCase(iterator.next()));
if (!iterator.hasNext()) {
break;
}
whereExpr.append(',');
}
return whereExpr.append(')');
}
/**
* Loads all Waypoints in the coordinate rectangle.
*
*/
@NonNull
public static Set<Waypoint> loadWaypoints(final Viewport viewport, final boolean excludeMine, final boolean excludeDisabled, final CacheType type) {
final StringBuilder where = buildCoordinateWhere(dbTableWaypoints, viewport);
if (excludeMine) {
where.append(" and ").append(dbTableCaches).append(".found == 0");
}
if (excludeDisabled) {
where.append(" and ").append(dbTableCaches).append(".disabled == 0");
where.append(" and ").append(dbTableCaches).append(".archived == 0");
}
if (type != CacheType.ALL) {
where.append(" and ").append(dbTableCaches).append(".type == '").append(type.id).append('\'');
}
final StringBuilder query = new StringBuilder("SELECT ");
for (int i = 0; i < WAYPOINT_COLUMNS.length; i++) {
query.append(i > 0 ? ", " : "").append(dbTableWaypoints).append('.').append(WAYPOINT_COLUMNS[i]).append(' ');
}
query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints)
.append(".geocode == ").append(dbTableCaches).append(".geocode and ").append(where)
.append(" LIMIT " + (Settings.SHOW_WP_THRESHOLD_MAX * 2)); // Hardcoded limit to avoid memory overflow
return cursorToColl(database.rawQuery(query.toString(), null), new HashSet<Waypoint>(), new Func1<Cursor, Waypoint>() {
@Override
public Waypoint call(final Cursor cursor) {
return createWaypointFromDatabaseContent(cursor);
}
});
}
public static void saveChangedCache(final Geocache cache) {
saveCache(cache, cache.inDatabase() ? LoadFlags.SAVE_ALL : EnumSet.of(SaveFlag.CACHE));
}
private enum PreparedStatement {
HISTORY_COUNT("SELECT COUNT(_id) FROM " + dbTableCaches + " WHERE visiteddate > 0"),
MOVE_TO_STANDARD_LIST("UPDATE " + dbTableCachesLists + " SET list_id = " + StoredList.STANDARD_LIST_ID + " WHERE list_id = ? AND geocode NOT IN (SELECT distinct (geocode) FROM " + dbTableCachesLists + " WHERE list_id = " + StoredList.STANDARD_LIST_ID + ")"),
REMOVE_FROM_LIST("DELETE FROM " + dbTableCachesLists + " WHERE list_id = ? AND geocode = ?"),
REMOVE_FROM_ALL_LISTS("DELETE FROM " + dbTableCachesLists + " WHERE geocode = ?"),
REMOVE_ALL_FROM_LIST("DELETE FROM " + dbTableCachesLists + " WHERE list_id = ?"),
UPDATE_VISIT_DATE("UPDATE " + dbTableCaches + " SET visiteddate = ? WHERE geocode = ?"),
INSERT_LOG_IMAGE("INSERT INTO " + dbTableLogImages + " (log_id, title, url, description) VALUES (?, ?, ?, ?)"),
INSERT_LOG_COUNTS("INSERT INTO " + dbTableLogCount + " (geocode, updated, type, count) VALUES (?, ?, ?, ?)"),
INSERT_SPOILER("INSERT INTO " + dbTableSpoilers + " (geocode, updated, url, title, description) VALUES (?, ?, ?, ?, ?)"),
LOG_COUNT_OF_GEOCODE("SELECT count(_id) FROM " + dbTableLogsOffline + " WHERE geocode = ?"),
COUNT_CACHES_ON_STANDARD_LIST("SELECT count(geocode) FROM " + dbTableCachesLists + " WHERE list_id = " + StoredList.STANDARD_LIST_ID),
COUNT_ALL_CACHES("SELECT count(distinct(geocode)) FROM " + dbTableCachesLists + " WHERE list_id >= " + StoredList.STANDARD_LIST_ID),
INSERT_LOG("INSERT INTO " + dbTableLogs + " (geocode, updated, type, author, log, date, found, friend) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),
INSERT_ATTRIBUTE("INSERT INTO " + dbTableAttributes + " (geocode, updated, attribute) VALUES (?, ?, ?)"),
ADD_TO_LIST("INSERT OR REPLACE INTO " + dbTableCachesLists + " (list_id, geocode) VALUES (?, ?)"),
GEOCODE_OFFLINE("SELECT count(list_id) FROM " + dbTableCachesLists + " WHERE geocode = ? AND list_id != " + StoredList.TEMPORARY_LIST.id),
GUID_OFFLINE("SELECT count(list_id) FROM " + dbTableCachesLists + " WHERE geocode = (SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?) AND list_id != " + StoredList.TEMPORARY_LIST.id),
GEOCODE_OF_GUID("SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?"),
GEOCODE_FROM_TITLE("SELECT geocode FROM " + dbTableCaches + " WHERE name = ?"),
INSERT_SEARCH_DESTINATION("INSERT INTO " + dbTableSearchDestinationHistory + " (date, latitude, longitude) VALUES (?, ?, ?)"),
COUNT_TYPE_ALL_LIST("SELECT COUNT(c._id) FROM " + dbTableCaches + " c, " + dbTableCachesLists + " l WHERE c.detailed = 1 AND c.type = ? AND c.geocode = l.geocode AND l.list_id > 0"), // See use of COUNT_TYPE_LIST for synchronization
COUNT_ALL_TYPES_ALL_LIST("SELECT COUNT(c._id) FROM " + dbTableCaches + " c, " + dbTableCachesLists + " l WHERE c.detailed = 1 AND c.geocode = l.geocode AND l.list_id > 0"), // See use of COUNT_TYPE_LIST for synchronization
COUNT_TYPE_LIST("SELECT COUNT(c._id) FROM " + dbTableCaches + " c, " + dbTableCachesLists + " l WHERE c.detailed = 1 AND c.type = ? AND c.geocode = l.geocode AND l.list_id = ?"),
COUNT_ALL_TYPES_LIST("SELECT COUNT(c._id) FROM " + dbTableCaches + " c, " + dbTableCachesLists + " l WHERE c.detailed = 1 AND c.geocode = l.geocode AND l.list_id = ?"), // See use of COUNT_TYPE_LIST for synchronization
CHECK_IF_PRESENT("SELECT COUNT(*) FROM " + dbTableCaches + " WHERE geocode = ?");
private static final List<PreparedStatement> statements = new ArrayList<>();
@Nullable
private volatile SQLiteStatement statement = null; // initialized lazily
final String query;
PreparedStatement(final String query) {
this.query = query;
}
public long simpleQueryForLong() {
return getStatement().simpleQueryForLong();
}
private SQLiteStatement getStatement() {
if (statement == null) {
synchronized (statements) {
if (statement == null) {
init();
statement = database.compileStatement(query);
statements.add(this);
}
}
}
return statement;
}
private static void clearPreparedStatements() {
for (final PreparedStatement preparedStatement : statements) {
final SQLiteStatement statement = preparedStatement.statement;
if (statement != null) {
statement.close();
preparedStatement.statement = null;
}
}
statements.clear();
}
}
public static void saveVisitDate(final String geocode) {
setVisitDate(Collections.singletonList(geocode), System.currentTimeMillis());
}
public static Map<String, Set<Integer>> markDropped(final Collection<Geocache> caches) {
final SQLiteStatement remove = PreparedStatement.REMOVE_FROM_ALL_LISTS.getStatement();
final Map<String, Set<Integer>> oldLists = new HashMap<>();
database.beginTransaction();
try {
for (final Geocache cache : caches) {
oldLists.put(cache.getGeocode(), loadLists(cache.getGeocode()));
remove.bindString(1, cache.getGeocode());
remove.execute();
cache.getLists().clear();
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
return oldLists;
}
@Nullable
public static Viewport getBounds(final String geocode) {
if (geocode == null) {
return null;
}
return getBounds(Collections.singleton(geocode));
}
public static void clearVisitDate(final String[] selected) {
setVisitDate(Arrays.asList(selected), 0);
}
@NonNull
public static SearchResult getBatchOfStoredCaches(final Geopoint coords, final CacheType cacheType, final int listId) {
final Set<String> geocodes = loadBatchOfStoredGeocodes(coords, cacheType, listId);
return new SearchResult(geocodes, getAllStoredCachesCount(cacheType, listId));
}
@NonNull
public static SearchResult getHistoryOfCaches(final boolean detailedOnly, final CacheType cacheType) {
final Set<String> geocodes = loadBatchOfHistoricGeocodes(detailedOnly, cacheType);
return new SearchResult(geocodes, getAllHistoryCachesCount());
}
public static boolean saveWaypoint(final int id, final String geocode, final Waypoint waypoint) {
if (saveWaypointInternal(id, geocode, waypoint)) {
removeCache(geocode, EnumSet.of(RemoveFlag.CACHE));
return true;
}
return false;
}
@NonNull
public static Set<String> getCachedMissingFromSearch(final SearchResult searchResult, final Set<Tile> tiles, final IConnector connector, final int maxZoom) {
// get cached CacheListActivity
final Set<String> cachedGeocodes = new HashSet<>();
for (final Tile tile : tiles) {
cachedGeocodes.addAll(cacheCache.getInViewport(tile.getViewport(), CacheType.ALL));
}
// remove found in search result
cachedGeocodes.removeAll(searchResult.getGeocodes());
// check remaining against viewports
final Set<String> missingFromSearch = new HashSet<>();
for (final String geocode : cachedGeocodes) {
if (connector.canHandle(geocode)) {
final Geocache geocache = cacheCache.getCacheFromCache(geocode);
// TODO: parallel searches seem to have the potential to make some caches be expunged from the CacheCache (see issue #3716).
if (geocache != null && geocache.getCoordZoomLevel() <= maxZoom) {
for (final Tile tile : tiles) {
if (tile.containsPoint(geocache)) {
missingFromSearch.add(geocode);
break;
}
}
}
}
}
return missingFromSearch;
}
@Nullable
public static Cursor findSuggestions(final String searchTerm) {
// require 3 characters, otherwise there are to many results
if (StringUtils.length(searchTerm) < 3) {
return null;
}
init();
final SearchSuggestionCursor resultCursor = new SearchSuggestionCursor();
try {
final String selectionArg = getSuggestionArgument(searchTerm);
findCaches(resultCursor, selectionArg);
findTrackables(resultCursor, selectionArg);
} catch (final Exception e) {
Log.e("DataStore.loadBatchOfStoredGeocodes", e);
}
return resultCursor;
}
private static void findCaches(final SearchSuggestionCursor resultCursor, final String selectionArg) {
final Cursor cursor = database.query(
dbTableCaches,
new String[] { "geocode", "name", "type" },
"geocode IS NOT NULL AND geocode != '' AND (geocode LIKE ? OR name LIKE ? OR owner LIKE ?)",
new String[] { selectionArg, selectionArg, selectionArg },
null,
null,
"name");
while (cursor.moveToNext()) {
final String geocode = cursor.getString(0);
final String cacheName = cursor.getString(1);
final String type = cursor.getString(2);
resultCursor.addCache(geocode, cacheName, type);
}
cursor.close();
}
@NonNull
private static String getSuggestionArgument(final String input) {
return "%" + StringUtils.trim(input) + "%";
}
private static void findTrackables(final MatrixCursor resultCursor, final String selectionArg) {
final Cursor cursor = database.query(
dbTableTrackables,
new String[] { "tbcode", "title" },
"tbcode IS NOT NULL AND tbcode != '' AND (tbcode LIKE ? OR title LIKE ?)",
new String[] { selectionArg, selectionArg },
null,
null,
"title");
while (cursor.moveToNext()) {
final String tbcode = cursor.getString(0);
resultCursor.addRow(new String[] {
String.valueOf(resultCursor.getCount()),
cursor.getString(1),
tbcode,
Intents.ACTION_TRACKABLE,
tbcode,
String.valueOf(R.drawable.trackable_all)
});
}
cursor.close();
}
@NonNull
public static String[] getSuggestions(final String table, final String column, final String input) {
try {
final Cursor cursor = database.rawQuery("SELECT DISTINCT " + column
+ " FROM " + table
+ " WHERE " + column + " LIKE ?"
+ " ORDER BY " + column + " COLLATE NOCASE ASC;", new String[] { getSuggestionArgument(input) });
return cursorToColl(cursor, new LinkedList<String>(), GET_STRING_0).toArray(new String[cursor.getCount()]);
} catch (final RuntimeException e) {
Log.e("cannot get suggestions from " + table + "->" + column + " for input '" + input + "'", e);
return ArrayUtils.EMPTY_STRING_ARRAY;
}
}
@NonNull
public static String[] getSuggestionsOwnerName(final String input) {
return getSuggestions(dbTableCaches, "owner_real", input);
}
@NonNull
public static String[] getSuggestionsTrackableCode(final String input) {
return getSuggestions(dbTableTrackables, "tbcode", input);
}
@NonNull
public static String[] getSuggestionsFinderName(final String input) {
return getSuggestions(dbTableLogs, "author", input);
}
@NonNull
public static String[] getSuggestionsGeocode(final String input) {
return getSuggestions(dbTableCaches, "geocode", input);
}
@NonNull
public static String[] getSuggestionsKeyword(final String input) {
return getSuggestions(dbTableCaches, "name", input);
}
/**
*
* @return list of last caches opened in the details view, ordered by most recent first
*/
@NonNull
public static List<Geocache> getLastOpenedCaches() {
final List<String> geocodes = Settings.getLastOpenedCaches();
final Set<Geocache> cachesSet = loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB);
// order result set by time again
final List<Geocache> caches = new ArrayList<>(cachesSet);
Collections.sort(caches, new Comparator<Geocache>() {
@Override
public int compare(final Geocache lhs, final Geocache rhs) {
final int lhsIndex = geocodes.indexOf(lhs.getGeocode());
final int rhsIndex = geocodes.indexOf(rhs.getGeocode());
return lhsIndex < rhsIndex ? -1 : (lhsIndex == rhsIndex ? 0 : 1);
}
});
return caches;
}
}
|
package ca.corefacility.bioinformatics.irida.pipeline.results.impl.integration;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContextTestExcecutionListener;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import ca.corefacility.bioinformatics.irida.config.data.IridaApiJdbcDataSourceConfig;
import ca.corefacility.bioinformatics.irida.config.services.IridaApiServicesConfig;
import ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission;
import ca.corefacility.bioinformatics.irida.pipeline.results.impl.AnalysisSubmissionSampleProcessorImpl;
import ca.corefacility.bioinformatics.irida.repositories.analysis.submission.AnalysisSubmissionRepository;
import ca.corefacility.bioinformatics.irida.repositories.joins.sample.SampleGenomeAssemblyJoinRepository;
/**
* Tests updating samples with assemblies.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { IridaApiServicesConfig.class,
IridaApiJdbcDataSourceConfig.class })
@ActiveProfiles("it")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DbUnitTestExecutionListener.class,
WithSecurityContextTestExcecutionListener.class })
@DatabaseSetup("/ca/corefacility/bioinformatics/irida/pipeline/results/impl/AnalysisSubmissionSampleProcessorImplIT.xml")
@DatabaseTearDown("/ca/corefacility/bioinformatics/irida/test/integration/TableReset.xml")
public class AnalysisSubmissionSampleProcessorImplIT {
@Autowired
private AnalysisSubmissionSampleProcessorImpl analysisSubmissionSampleProcessorImpl;
@Autowired
private AnalysisSubmissionRepository analysisSubmissionRepository;
@Autowired
private SampleGenomeAssemblyJoinRepository sampleGenomeAssemblyJoinRepository;
@Test
@WithMockUser(username = "fbristow", roles = "USER")
public void testUpdateSamplesSuccess() {
AnalysisSubmission a = analysisSubmissionRepository.findOne(1L);
assertEquals("Should be no join between sample and assembly", 0, sampleGenomeAssemblyJoinRepository.count());
analysisSubmissionSampleProcessorImpl.updateSamples(a);
assertEquals("Should exist a join between sample and assembly", 1, sampleGenomeAssemblyJoinRepository.count());
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "fbristow", roles = "USER")
public void testUpdateFailPermissionNonSampleOwner() {
AnalysisSubmission a = analysisSubmissionRepository.findOne(2L);
analysisSubmissionSampleProcessorImpl.updateSamples(a);
}
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "dr-evil", roles = "USER")
public void testUpdateFailPermissionNonProjectOwner() {
AnalysisSubmission a = analysisSubmissionRepository.findOne(2L);
analysisSubmissionSampleProcessorImpl.updateSamples(a);
}
/**
* Verifies that even if "fbristow" (the project owner) is set to run this
* code, the RunAsUserAspect will switch the user to the owner of the
* analysis submission, a non-project owner who should not have the ability
* to write to the samples (and so should throw an AccessDeniedException
* for this test).
*/
@Test(expected = AccessDeniedException.class)
@WithMockUser(username = "fbristow", roles = "USER")
public void testUpdateSamplesFailAnalysisSubmittedNonProjectOwner() {
AnalysisSubmission a = analysisSubmissionRepository.findOne(3L);
analysisSubmissionSampleProcessorImpl.updateSamples(a);
}
}
|
package org.broad.igv.batch;
import biz.source_code.base64Coder.Base64Coder;
import org.broad.igv.logging.LogManager;
import org.broad.igv.logging.Logger;
import org.broad.igv.Globals;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.oauth.OAuthProvider;
import org.broad.igv.oauth.OAuthUtils;
import org.broad.igv.prefs.Constants;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.util.UIUtilities;
import org.broad.igv.util.HttpUtils;
import org.broad.igv.util.StringUtils;
import java.awt.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.channels.ClosedByInterruptException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class CommandListener implements Runnable {
public static final String OK = "OK";
// when the listener is successfully started, set this to true.
// set this back to false when the listener closes dwm08
private static boolean isListening = false;
public static int currentListenerPort = -1;
private static Logger log = LogManager.getLogger(CommandListener.class);
private static CommandListener listener;
private static final String CRLF = "\r\n";
private int port = -1;
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private Thread listenerThread;
boolean halt = false;
/**
* Different keys which can be used to specify a file to load
*/
public static Set<String> fileParams;
public static Set<String> indexParams;
static {
String[] fps = new String[]{"file", "bigDataURL", "sessionURL", "dataURL"};
fileParams = new LinkedHashSet<String>(Arrays.asList(fps));
fileParams = Collections.unmodifiableSet(fileParams);
indexParams = new HashSet<String>(Arrays.asList("index"));
}
public static synchronized void start() {
start(PreferencesManager.getPreferences().getAsInt(Constants.PORT_NUMBER));
}
public static synchronized void start(int port) {
try {
listener = new CommandListener(port);
listener.listenerThread.start();
} catch (Exception e) {
listener.closeSockets();
listener = null;
log.error(e);
}
}
public static synchronized void halt() {
if (listener != null) {
listener.halt = true;
listener.listenerThread.interrupt();
listener.closeSockets();
listener = null;
}
}
private CommandListener(int port) {
this.port = port;
listenerThread = new Thread(this);
}
/**
* Return true if the listener is currently enabled
*
* @return state of listener
*/
public static boolean isListening() {
return listener != null;
}
/**
* Loop forever, processing client requests synchronously. The server is single threaded.
* dwm08 - set isListening appropriately
*/
public void run() {
try {
CommandExecutor cmdExe = new CommandExecutor(IGV.getInstance());
serverSocket = new ServerSocket(port);
log.info("Listening on port " + port);
currentListenerPort = port;
while (!halt) {
clientSocket = serverSocket.accept();
processClientSession(cmdExe);
if (clientSocket != null) {
try {
clientSocket.close();
clientSocket = null;
// We do NOT set isListening = false here, otherwise logout/login state change falls back to OOB
} catch (IOException e) {
log.error("Error in client socket loop", e);
}
}
}
} catch (java.net.BindException e) {
log.error(e);
currentListenerPort = -1;
listener = null;
} catch (ClosedByInterruptException e) {
log.error(e);
listener = null;
} catch (IOException e) {
listener = null;
if (!halt) {
log.error("IO Error on port socket ", e);
}
}
}
/**
* Process a client session. Loop continuously until client sends the "halt" message, or closes the connection.
*
* @param cmdExe
* @throws IOException
*/
private void processClientSession(CommandExecutor cmdExe) throws IOException {
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while (!halt && (inputLine = in.readLine()) != null) {
String cmd = inputLine;
if (!cmd.contains("/oauthCallback")) {
log.info(cmd);
}
boolean isHTTP = cmd.startsWith("OPTIONS") || cmd.startsWith("HEAD") || cmd.startsWith("GET");
if (isHTTP) {
if (cmd.startsWith("OPTIONS")) {
sendHTTPOptionsResponse(out);
} else {
String result = null;
String command = null;
Map<String, String> params = null;
String[] tokens = inputLine.split(" ");
if (tokens.length < 2) {
result = "ERROR unexpected command line: " + inputLine;
} else {
String[] parts = tokens[1].split("\\?");
command = parts[0];
params = parts.length < 2 ? new HashMap() : parseParameters(parts[1]);
}
// Consume the remainder of the request, if any. This is important to free the connection.
Map<String, String> headers = new HashMap<>();
String nextLine = in.readLine();
while (nextLine != null && nextLine.length() > 0) {
nextLine = in.readLine();
String[] headerTokens = Globals.colonPattern.split(nextLine, 2);
if (headerTokens.length == 2) {
headers.put(headerTokens[0].trim(), headerTokens[1].trim());
}
}
if (cmd.startsWith("HEAD")) {
sendHTTPResponse(out, result, "text/html", "HEAD");
} else {
if (command != null) {
// Detect oauth callback
if (command.equals("/oauthCallback")) {
OAuthProvider provider = OAuthUtils.getInstance().getProviderForState(params.get("state"));
if (params.containsKey("code")) {
provider.setAuthorizationCode(params.get("code"));
} else if (params.containsKey("token")) {
// Very doubtful this is ever called -- its not a normal OAuth flow
log.info("Oauth token received");
provider.setAccessToken(params.get("token"));
}
sendTextResponse(out, "Authorization successful. You may close this tab.");
if (PreferencesManager.getPreferences().getAsBoolean(Constants.PORT_ENABLED) == false) {
// Turn off port
halt();
}
} else {
// Process the request.
result = processGet(command, params, cmdExe); // Send no response if result is "OK".
if ("OK".equals(result)) result = null;
sendTextResponse(out, result);
}
}
}
}
// http sockets are used for one request only => return will close the socket
return;
} else {
// Port command
try {
Globals.setBatch(true);
String finalInputLine = inputLine;
PrintWriter finalOut = out;
UIUtilities.invokeAndWaitOnEventThread(() -> {
final String response = cmdExe.execute(finalInputLine);
finalOut.println(response);
finalOut.flush();
});
} finally {
Globals.setBatch(false);
}
}
}
} catch (IOException e) {
log.error("Error processing client session", e);
} finally {
Globals.setSuppressMessages(false);
Globals.setBatch(false);
if (out != null) out.close();
if (in != null) in.close();
}
}
private void closeSockets() {
if (clientSocket != null) {
try {
clientSocket.close();
clientSocket = null;
} catch (IOException e) {
log.error("Error closing clientSocket", e);
}
}
if (serverSocket != null) {
try {
serverSocket.close();
serverSocket = null;
} catch (IOException e) {
log.error("Error closing server socket", e);
}
}
}
private static final String HTTP_RESPONSE = "HTTP/1.1 200 OK";
private static final String HTTP_NO_RESPONSE = "HTTP/1.1 204 No Response";
private static final String CONNECTION_CLOSE = "Connection: close";
private static final String NO_CACHE = "Cache-Control: no-cache, no-store";
private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin: *";
private void sendTextResponse(PrintWriter out, String result) {
sendHTTPResponse(out, result, "text/html", "GET");
}
private void sendHTTPResponse(PrintWriter out, String result, String contentType, String method) {
out.print(result == null ? HTTP_NO_RESPONSE : HTTP_RESPONSE);
out.print(CRLF);
out.print(ACCESS_CONTROL_ALLOW_ORIGIN);
out.print(CRLF);
if (result != null) {
out.print("Content-Type: " + contentType);
out.print(CRLF);
out.print("Content-Length: " + (result.length()));
out.print(CRLF);
out.print(NO_CACHE);
out.print(CRLF);
out.print(CONNECTION_CLOSE);
out.print(CRLF);
if (!method.equals("HEAD")) {
out.print(CRLF);
out.print(result);
out.print(CRLF);
}
}
out.close();
}
private void sendHTTPOptionsResponse(PrintWriter out) {
out.print(HTTP_NO_RESPONSE);
out.print(CRLF);
out.print(ACCESS_CONTROL_ALLOW_ORIGIN);
out.print(CRLF);
out.println("Access-Control-Allow-Methods: HEAD, GET, OPTIONS");
out.print(CRLF);
out.close();
}
/**
* Process an http get request.
*/
private String processGet(String command, Map<String, String> params, CommandExecutor cmdExe) throws IOException {
String result = OK;
final Frame mainFrame = IGV.getInstance().getMainFrame();
// Trick to force window to front, the setAlwaysOnTop works on a Mac, toFront() does nothing.
mainFrame.toFront();
mainFrame.setAlwaysOnTop(true);
mainFrame.setAlwaysOnTop(false);
if (command.equals("/load")) {
String file = null;
for (String fp : fileParams) {
file = params.get(fp);
if (file != null) break;
}
String genome = params.get("genome");
if (genome == null) {
genome = params.get("db"); // <- UCSC track line param
}
if (genome != null) {
GenomeManager.getInstance().loadGenomeById(genome);
}
if (file != null) {
String mergeValue = params.get("merge");
if (mergeValue != null) mergeValue = URLDecoder.decode(mergeValue, "UTF-8");
// Default for merge is "false" for session files, "true" otherwise
boolean merge;
if (mergeValue != null) {
// Explicit setting
merge = mergeValue.equalsIgnoreCase("true");
} else if (file.endsWith(".xml") || file.endsWith(".php") || file.endsWith(".php3")) {
// Session file
merge = false;
} else {
// Data file
merge = true;
}
String name = params.get("name");
String format = params.get("format");
String locus = params.get("locus");
String index = params.get("index");
String coverage = params.get("coverage");
String sort = params.get("sort");
String sortTag = params.get("sortTag");
boolean dup = "true".equals(params.get("dup"));
result = cmdExe.loadFiles(file, index, coverage, name, format, locus, merge, params, sort, sortTag, dup);
} else {
result = "OK"; // No files, perhaps genome only
}
} else if (command.equals("/reload") || command.equals("/goto")) {
String locus = params.get("locus");
IGV.getInstance().goToLocus(locus);
} else if (command.equals("/execute")) {
String param = StringUtils.decodeURL(params.get("command"));
return cmdExe.execute(param);
} else {
return ("ERROR Unknown command: " + command);
}
return result;
}
/**
* Parse the html parameter string into a set of key-value pairs. Parameter values are
* url decoded with the exception of the "locus" parameter.
*
* @param parameterString
* @return
*/
private Map<String, String> parseParameters(String parameterString) {
// Do a partial decoding now (ampersands only)
parameterString = parameterString.replace("&", "&");
HashMap<String, String> params = new HashMap();
String[] kvPairs = parameterString.split("&");
for (String kvString : kvPairs) {
// Split on the first "=", all others are part of the parameter value
String[] kv = kvString.split("=", 2);
if (kv.length == 1) {
params.put(kv[0], null);
} else {
String key = StringUtils.decodeURL(kv[0]);
//This might look backwards, but it isn't.
//Parameters must be URL encoded, including the file parameter
//CommandExecutor URL-decodes the file parameter sometimes, but not always
//So we URL-decode iff CommandExecutor doesn't
boolean cmdExeWillDecode = (fileParams.contains(key) || indexParams.contains(key)) && CommandExecutor.needsDecode(kv[1]);
String value = cmdExeWillDecode ? kv[1] : StringUtils.decodeURL(kv[1]);
params.put(kv[0], value);
}
}
return params;
}
/**
* Compute a socket key according to the WebSocket RFC. This method is here because this is the only class that uses it.
*
* @param input
* @return
* @throws NoSuchAlgorithmException
*/
static String computeResponseKey(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
java.security.MessageDigest digest = null;
digest = java.security.MessageDigest.getInstance("SHA-1");
digest.reset();
digest.update(input.getBytes("UTF-8"));
return new String(Base64Coder.encode(digest.digest()));
}
}
|
package ca.corefacility.bioinformatics.irida.web.controller.test.integration.sample;
import com.google.common.net.HttpHeaders;
import com.jayway.restassured.response.Response;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.path.json.JsonPath.from;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Integration tests for working with sequence files and samples.
*
* @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
*/
public class SampleSequenceFilesIntegrationTest {
@Test
public void testAddSequenceFileToSample() throws IOException {
String sampleUri = "http://localhost:8080/api/projects/c4893f30-b054-46e5-8ebe-ed1b295dfa38" +
"/samples/07ac0624-8f04-43ba-b45f-e6d65a8bd6ba";
Response response = expect().statusCode(HttpStatus.OK.value()).when().get(sampleUri);
String sampleBody = response.getBody().asString();
String sequenceFileUri = from(sampleBody).getString("resource.links.find{it.rel == 'sample/sequenceFiles'}.href");
// prepare a file for sending to the server
Path sequenceFile = Files.createTempFile(null, null);
Files.write(sequenceFile, ">test read\nACGTACTCATG".getBytes());
Response r = given().contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
.multiPart("file", sequenceFile.toFile()).expect().statusCode(HttpStatus.CREATED.value())
.when().post(sequenceFileUri);
// check that the location and link headers were created:
String location = r.getHeader(HttpHeaders.LOCATION);
String link = r.getHeader(HttpHeaders.LINK);
assertNotNull(location);
assertTrue(location.matches("http://localhost:8080/api/sequenceFiles/[a-f0-9\\-]+"));
assertNotNull(link);
assertTrue(link.matches("<http://localhost:8080/api/projects/[a-f0-9\\-]+/samples/[a-f0-9\\-]+" +
"/sequenceFiles/[a-f0-9\\-]+>; rel=relationship"));
// clean up
Files.delete(sequenceFile);
}
@Test
public void testAddExistingSequenceFileToSample() throws IOException {
// for now, add a sequence file to another sample
String projectUri = "http://localhost:8080/api/projects/c4893f30-b054-46e5-8ebe-ed1b295dfa38";
String sampleUri = projectUri + "/samples/07ac0624-8f04-43ba-b45f-e6d65a8bd6ba";
Response response = expect().statusCode(HttpStatus.OK.value()).when().get(projectUri);
String projectBody = response.getBody().asString();
String sequenceFileUri = from(projectBody).getString("resource.links.find{it.rel == 'project/sequenceFiles'}.href");
// prepare a file for sending to the server
Path sequenceFile = Files.createTempFile(null, null);
Files.write(sequenceFile, ">test read\nACGTACTCATG".getBytes());
Response r = given().contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
.multiPart("file", sequenceFile.toFile()).expect().statusCode(HttpStatus.CREATED.value())
.when().post(sequenceFileUri);
// figure out what the identifier for that sequence file is
String location = r.getHeader(HttpHeaders.LOCATION);
String identifier = location.substring(location.lastIndexOf('/') + 1);
Map<String, String> existingSequenceFile = new HashMap<>();
existingSequenceFile.put("sequenceFileId", identifier);
// now figure out where to post the sequence file to add it to the sample
String sampleBody = expect().statusCode(HttpStatus.OK.value()).when().get(sampleUri).getBody().asString();
sequenceFileUri = from(sampleBody).getString("resource.links.find{it.rel == 'sample/sequenceFiles'}.href");
// add the sequence file to the sample
r = given().body(existingSequenceFile).expect().statusCode(HttpStatus.CREATED.value()).when()
.post(sequenceFileUri);
location = r.getHeader(HttpHeaders.LOCATION);
String link = r.getHeader(HttpHeaders.LINK);
assertNotNull(location);
assertTrue(location.matches("http://localhost:8080/api/sequenceFiles/[a-f0-9\\-]+"));
assertNotNull(link);
assertTrue(link.matches("<http://localhost:8080/api/projects/[0-9a-f\\-]+/samples/[a-f0-9\\-]+" +
"/sequenceFiles/[a-f0-9\\-]+>; rel=relationship"));
}
}
|
package gov.nih.nci.calab.ui.core;
/**
* This class initializes session data to prepopulate the drop-down lists required
* in different view pages.
*
* @author pansu
*/
/* CVS $Id: InitSessionAction.java,v 1.11 2006-04-17 15:51:32 pansu Exp $ */
import gov.nih.nci.calab.dto.administration.AliquotBean;
import gov.nih.nci.calab.dto.administration.ContainerInfoBean;
import gov.nih.nci.calab.dto.security.SecurityBean;
import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean;
import gov.nih.nci.calab.service.administration.ManageAliquotService;
import gov.nih.nci.calab.service.administration.ManageSampleService;
import gov.nih.nci.calab.service.common.LookupService;
import gov.nih.nci.calab.service.search.SearchSampleService;
import gov.nih.nci.calab.service.search.SearchWorkflowService;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
public class InitSessionAction extends AbstractBaseAction {
private static Logger logger = Logger.getLogger(InitSessionAction.class);
public ActionForward executeTask(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
ActionForward forward = null;
String forwardPage = null;
String urlPrefix = request.getContextPath();
try {
DynaActionForm theForm = (DynaActionForm) form;
forwardPage = (String) theForm.get("forwardPage");
// retrieve from sesssion first if available assuming these values
// are not likely to change within the same session. If changed, the
// session should be updated.
LookupService lookupService = new LookupService();
if (forwardPage.equals("useAliquot")) {
String runId = (String) request.getParameter("runId");
session.setAttribute("runId", runId);
setUseAliquotSession(session, lookupService);
} else if (forwardPage.equals("createSample")) {
setCreateSampleSession(session, lookupService);
} else if (forwardPage.equals("createAliquot")) {
setCreateAliquotSession(session, lookupService, urlPrefix);
} else if (forwardPage.equals("searchWorkflow")) {
setSearchWorkflowSession(session, lookupService);
} else if (forwardPage.equals("searchSample")) {
setSearchSampleSession(session, lookupService);
} else if (forwardPage.equals("createRun")) {
setCreateRunSession(session, lookupService);
}
// get user and date information
String creator = "";
if (session.getAttribute("user") != null) {
SecurityBean user = (SecurityBean) session.getAttribute("user");
creator = user.getLoginId();
}
String creationDate = StringUtils.convertDateToString(new Date(),
CalabConstants.DATE_FORMAT);
session.setAttribute("creator", creator);
session.setAttribute("creationDate", creationDate);
forward = mapping.findForward(forwardPage);
} catch (Exception e) {
ActionMessages errors = new ActionMessages();
ActionMessage error = new ActionMessage("error.initSession",
forwardPage);
errors.add("error", error);
saveMessages(request, errors);
logger.error(
"Caught exception loading initial drop-down lists data", e);
forward = mapping.getInputForward();
}
return forward;
}
public boolean loginRequired() {
return true;
}
/**
* Set up session attributes for use aliquot page
*
* @param session
* @param lookupService
*/
private void setUseAliquotSession(HttpSession session,
LookupService lookupService) throws Exception {
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List<AliquotBean> allAliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", allAliquots);
}
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService
.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
}
/**
* Set up session attributes for create sample page
*
* @param session
* @param lookupService
*/
private void setCreateSampleSession(HttpSession session,
LookupService lookupService) {
ManageSampleService mangeSampleService = new ManageSampleService();
// if values don't exist in the database or if no new samples created.
// call the service
if (session.getAttribute("allSampleTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.setAttribute("allSampleTypes", sampleTypes);
}
if (session.getAttribute("allSampleSOPs") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSOPs = mangeSampleService.getAllSampleSOPs();
session.setAttribute("allSampleSOPs", sampleSOPs);
}
if (session.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
}
// clear the form in the session
if (session.getAttribute("createSampleForm") != null
|| session.getAttribute("newSampleCreated") != null) {
session.removeAttribute("createSampleForm");
}
// clear the new sample created flag
session.removeAttribute("newSampleCreated");
}
/**
* Set up session attributes for create aliquot page
*
* @param session
* @param lookupService
*/
private void setCreateAliquotSession(HttpSession session,
LookupService lookupService, String urlPrefix) {
ManageAliquotService manageAliquotService = new ManageAliquotService();
if (session.getAttribute("allSamples") == null
|| session.getAttribute("newSampleCreated") != null) {
List samples = lookupService.getAllSamples();
session.setAttribute("allSamples", samples);
}
if (session.getAttribute("allUnmaskedAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List aliquots = lookupService.getUnmaskedAliquots();
session.setAttribute("allUnmaskedAliquots", aliquots);
}
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
if (session.getAttribute("aliquotCreateMethods") == null) {
List methods = manageAliquotService
.getAliquotCreateMethods(urlPrefix);
session.setAttribute("aliquotCreateMethods", methods);
}
// clear the form in the session
if (session.getAttribute("createAliquotForm") != null) {
session.removeAttribute("createAliquotForm");
}
if (session.getAttribute("aliquotMatrix") != null) {
session.removeAttribute("aliquotMatrix");
}
// clear new aliquot created flag and new sample created flag
session.removeAttribute("newAliquotCreated");
session.removeAttribute("newSampleCreated");
}
/**
* Set up session attributes for search workflow page
*
* @param session
* @param lookupService
*/
private void setSearchWorkflowSession(HttpSession session,
LookupService lookupService) {
SearchWorkflowService searchWorkflowService = new SearchWorkflowService();
if (session.getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.setAttribute("allAssayTypes", assayTypes);
}
if (session.getAttribute("allFileSubmitters") == null) {
List submitters = searchWorkflowService.getAllFileSubmitters();
session.setAttribute("allFileSubmitters", submitters);
}
}
/**
* Set up session attributes for search sample page
*
* @param session
* @param lookupService
*/
private void setSearchSampleSession(HttpSession session,
LookupService lookupService) {
SearchSampleService searchSampleService = new SearchSampleService();
if (session.getAttribute("allSamples") == null
|| session.getAttribute("newSampleCreated") != null) {
List samples = lookupService.getAllSamples();
session.setAttribute("allSamples", samples);
}
if (session.getAttribute("allAliquots") == null
|| session.getAttribute("newAliquotCreated") != null) {
List aliquots = lookupService.getAliquots();
session.setAttribute("allAliquots", aliquots);
}
if (session.getAttribute("allSampleTypes") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleTypes = lookupService.getAllSampleTypes();
session.setAttribute("allSampleTypes", sampleTypes);
}
if (session.getAttribute("allSampleSources") == null
|| session.getAttribute("newSampleCreated") != null) {
List sampleSources = searchSampleService.getAllSampleSources();
session.setAttribute("allSampleSources", sampleSources);
}
if (session.getAttribute("allSourceSampleIds") == null
|| session.getAttribute("newSampleCreated") != null) {
List sourceSampleIds = searchSampleService.getAllSourceSampleIds();
session.setAttribute("allSourceSampleIds", sourceSampleIds);
}
if (session.getAttribute("allSampleSubmitters") == null
|| session.getAttribute("newSampleCreated") != null) {
List submitters = searchSampleService.getAllSampleSubmitters();
session.setAttribute("allSampleSubmitters", submitters);
}
if (session.getAttribute("sampleContainerInfo") == null
|| session.getAttribute("newSampleCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getSampleContainerInfo();
session.setAttribute("sampleContainerInfo", containerInfo);
}
if (session.getAttribute("aliquotContainerInfo") == null
|| session.getAttribute("newAliquotCreated") != null) {
ContainerInfoBean containerInfo = lookupService
.getAliquotContainerInfo();
session.setAttribute("aliquotContainerInfo", containerInfo);
}
// clear new aliquot created flag and new sample created flag
session.removeAttribute("newAliquotCreated");
session.removeAttribute("newSampleCreated");
// clear session attributes created during search sample
session.removeAttribute("samples");
session.removeAttribute("aliquots");
}
/**
* Set up session attributes for create Run
*
* @param session
* @param lookupService
*/
private void setCreateRunSession(HttpSession session,
LookupService lookupService) throws Exception {
ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService();
if (session.getAttribute("allAssayTypes") == null) {
List assayTypes = lookupService.getAllAssayTypes();
session.setAttribute("allAssayTypes", assayTypes);
}
if (session.getAttribute("workflow") == null
|| session.getAttribute("newWorkflowCreated") != null) {
ExecuteWorkflowBean workflowBean = executeWorkflowService
.getExecuteWorkflowBean();
session.setAttribute("workflow", workflowBean);
}
if (session.getAttribute("allAvailableAliquots") == null) {
List allAvailableAliquots = lookupService.getAllAvailableAliquots();
session.setAttribute("allAvailableAliquots", allAvailableAliquots);
}
if (session.getAttribute("allAssignedAliquots") == null) {
List allAssignedAliquots = lookupService.getAllAssignedAliquots();
session.setAttribute("allAssignedAliquots", allAssignedAliquots);
}
if (session.getAttribute("allInFiles") == null) {
List allInFiles = lookupService.getAllInFiles();
session.setAttribute("allInFiles", allInFiles);
}
if (session.getAttribute("allOutFiles") == null) {
List allOutFiles = lookupService.getAllOutFiles();
session.setAttribute("allOutFiles", allOutFiles);
}
if (session.getAttribute("allAssayBeans") == null) {
List allAssayBeans = lookupService.getAllAssayBeans();
session.setAttribute("allAssayBeans", allAssayBeans);
}
}
}
|
package org.cojen.tupl.rows;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
import java.lang.invoke.VarHandle;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.cojen.maker.Label;
import org.cojen.maker.MethodMaker;
import org.cojen.maker.Variable;
import org.cojen.tupl.io.Utils;
/**
* Makes code which converts a value declared as Object to a specific type.
*
* @author Brian S O'Neill
*/
public class ConvertCallSite extends MutableCallSite {
private static final MethodHandle cImplementHandle;
private static final VarHandle cImplementedHandle;
static {
try {
var lookup = MethodHandles.lookup();
cImplementHandle = lookup.findVirtual
(ConvertCallSite.class, "implement",
MethodType.methodType(Object.class, Object.class));
cImplementedHandle = lookup.findVarHandle
(ConvertCallSite.class, "mImplemented", int.class);
} catch (Throwable e) {
throw Utils.rethrow(e);
}
}
// 0: not implemented, 1: being implemented, 2: implemented
private volatile int mImplemented;
private ConvertCallSite(MethodType mt) {
super(mt);
}
/**
* Makes code which converts a value declared as Object to a specific type. If the
* conversion cannot be performed, an exception is thrown at runtime.
*
* @param toType the specific desired "to" type
* @param from variable declared as Object type which contains the "from" value
* @return the "to" value, of type "toType"
*/
static Variable make(MethodMaker mm, Class toType, Variable from) {
return mm.var(ConvertCallSite.class).indy("makeNext").invoke(toType, "_", null, from);
}
/**
* Indy bootstrap method.
*
* @param mt accepts one param, an Object, and returns a non-void toType
*/
public static CallSite makeNext(MethodHandles.Lookup lookup, String name, MethodType mt) {
var cs = new ConvertCallSite(mt);
cs.setTarget(cImplementHandle.bindTo(cs).asType(mt));
return cs;
}
private Object implement(Object obj) {
while (true) {
int state = mImplemented;
if (state >= 2) {
break;
}
if (state == 0 && cImplementedHandle.compareAndSet(this, 0, 1)) {
try {
setTarget(converterFor(obj, type()));
mImplemented = 2;
break;
} catch (Throwable e) {
mImplemented = 0;
throw e;
}
}
Thread.yield();
}
try {
return getTarget().invoke(obj);
} catch (Throwable e) {
throw Utils.rethrow(e);
}
}
private static class CacheKey {
private final Class<?> mFromType, mToType;
CacheKey(Class<?> fromType, Class<?> toType) {
mFromType = fromType;
mToType = toType;
}
@Override
public int hashCode() {
return mFromType.hashCode() * 31 + mToType.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof CacheKey) {
var other = (CacheKey) obj;
return mFromType == other.mFromType && mToType == other.mToType;
}
return false;
}
}
private static final WeakCache<Object, MethodHandle> cCache = new WeakCache<>();
/**
* @param obj defines the "from" type, which can be null
* @param mt defines the "to" type (the return type)
*/
private static MethodHandle converterFor(Object obj, MethodType mt) {
Class<?> toType = mt.returnType();
Class<?> fromType;
Object key;
if (obj == null) {
fromType = null;
key = toType;
} else {
fromType = obj.getClass();
key = new CacheKey(fromType, toType);
}
MethodHandle mh = cCache.get(key);
if (mh == null) {
synchronized (cCache) {
mh = cCache.get(key);
if (mh == null) {
mh = makeConverter(mt, fromType, toType);
cCache.put(key, mh);
}
}
}
return mh;
}
private static MethodHandle makeConverter(MethodType mt, Class<?> fromType, Class<?> toType) {
MethodMaker mm = MethodMaker.begin(MethodHandles.lookup(), "convert", mt);
Label next = mm.label();
Variable from = mm.param(0);
final Variable result;
if (fromType == null) {
if (toType.isPrimitive()) {
result = null;
} else {
from.ifNe(null, next);
result = mm.var(toType).set(null);
}
} else {
from.instanceOf(fromType).ifFalse(next);
if (!toType.isPrimitive() && toType.isAssignableFrom(fromType)) {
result = from.cast(toType);
} else if (toType == String.class) {
result = toString(mm, fromType, from);
} else if (toType == long.class || toType == Long.class) {
result = toLong(mm, fromType, from);
} else if (toType == int.class || toType == Integer.class) {
result = toInt(mm, fromType, from);
} else if (toType == double.class || toType == Double.class) {
result = toDouble(mm, fromType, from);
} else if (toType == float.class || toType == Float.class) {
result = toFloat(mm, fromType, from);
} else if (toType == boolean.class || toType == Boolean.class) {
result = toBoolean(mm, fromType, from);
} else if (toType == BigInteger.class) {
result = toBigInteger(mm, fromType, from);
} else if (toType == BigDecimal.class) {
result = toBigDecimal(mm, fromType, from);
} else if (toType == char.class || toType == Character.class) {
result = toChar(mm, fromType, from);
} else if (toType == byte.class || toType == Byte.class) {
result = toByte(mm, fromType, from);
} else if (toType == short.class || toType == Short.class) {
result = toShort(mm, fromType, from);
} else {
result = null;
}
}
if (result != null) {
mm.return_(result);
} else {
mm.new_(IllegalArgumentException.class,
"Cannot convert " + (fromType == null ? null : fromType.getSimpleName()) +
" to " + toType.getSimpleName()).throw_();
}
next.here();
var indy = mm.var(ConvertCallSite.class).indy("makeNext");
mm.return_(indy.invoke(toType, "_", null, from));
return mm.finish();
}
private static Variable toBoolean(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Boolean.class) {
return from.cast(Boolean.class);
} else if (fromType == String.class) {
return mm.var(ConvertCallSite.class).invoke("stringToBoolean", from.cast(String.class));
} else {
return null;
}
}
private static Variable toByte(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Byte.class) {
return from.cast(Byte.class);
} else if (fromType == Integer.class) {
return mm.var(ConvertCallSite.class).invoke("intToByte", from.cast(Integer.class));
} else if (fromType == Long.class) {
return mm.var(ConvertCallSite.class).invoke("longToByte", from.cast(Long.class));
} else if (fromType == String.class) {
return mm.var(Byte.class).invoke("parseByte", from.cast(String.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToByte", from.cast(Double.class));
} else if (fromType == Float.class) {
return mm.var(ConvertCallSite.class).invoke("floatToByte", from.cast(Float.class));
} else if (fromType == Short.class) {
return mm.var(ConvertCallSite.class).invoke("shortToByte", from.cast(Short.class));
} else if (fromType == BigInteger.class) {
return from.cast(BigInteger.class).invoke("byteValueExact");
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("byteValueExact");
} else {
return null;
}
}
private static Variable toShort(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Short.class) {
return from.cast(Short.class);
} else if (fromType == Integer.class) {
return mm.var(ConvertCallSite.class).invoke("intToShort", from.cast(Integer.class));
} else if (fromType == Long.class) {
return mm.var(ConvertCallSite.class).invoke("longToShort", from.cast(Long.class));
} else if (fromType == String.class) {
return mm.var(Short.class).invoke("parseShort", from.cast(String.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToShort", from.cast(Double.class));
} else if (fromType == Float.class) {
return mm.var(ConvertCallSite.class).invoke("floatToShort", from.cast(Float.class));
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("shortValue");
} else if (fromType == BigInteger.class) {
return from.cast(BigInteger.class).invoke("shortValueExact");
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("shortValueExact");
} else {
return null;
}
}
private static Variable toInt(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Integer.class) {
return from.cast(Integer.class);
} else if (fromType == Long.class) {
return mm.var(Math.class).invoke("toIntExact", from.cast(Long.class));
} else if (fromType == String.class) {
return mm.var(Integer.class).invoke("parseInt", from.cast(String.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToInt", from.cast(Double.class));
} else if (fromType == Float.class) {
return mm.var(ConvertCallSite.class).invoke("floatToInt", from.cast(Float.class));
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("intValue");
} else if (fromType == Short.class) {
return from.cast(Short.class).invoke("intValue");
} else if (fromType == BigInteger.class) {
return from.cast(BigInteger.class).invoke("intValueExact");
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("intValueExact");
} else {
return null;
}
}
private static Variable toLong(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Long.class) {
return from.cast(Long.class);
} else if (fromType == Integer.class) {
return from.cast(Integer.class).invoke("longValue");
} else if (fromType == String.class) {
return mm.var(Long.class).invoke("parseLong", from.cast(String.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToLong", from.cast(Double.class));
} else if (fromType == Float.class) {
return mm.var(ConvertCallSite.class).invoke("floatToLong", from.cast(Float.class));
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("longValue");
} else if (fromType == Short.class) {
return from.cast(Short.class).invoke("longValue");
} else if (fromType == BigInteger.class) {
return from.cast(BigInteger.class).invoke("longValueExact");
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("longValueExact");
} else {
return null;
}
}
private static Variable toFloat(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Float.class) {
return from.cast(Float.class);
} else if (fromType == String.class) {
return mm.var(Float.class).invoke("parseFloat", from.cast(String.class));
} else if (fromType == Integer.class) {
return mm.var(ConvertCallSite.class).invoke("intToFloat", from.cast(Integer.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToFloat", from.cast(Double.class));
} else if (fromType == Long.class) {
return mm.var(ConvertCallSite.class).invoke("longToFloat", from.cast(Long.class));
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("floatValue");
} else if (fromType == Short.class) {
return from.cast(Short.class).invoke("floatValue");
} else if (fromType == BigInteger.class) {
var intVar = from.cast(BigInteger.class).invoke("intValueExact");
return mm.var(ConvertCallSite.class).invoke("intToFloat", intVar);
} else if (fromType == BigDecimal.class) {
return mm.var(ConvertCallSite.class).invoke("bdToFloat", from.cast(BigDecimal.class));
} else {
return null;
}
}
private static Variable toDouble(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Double.class) {
return from.cast(Double.class);
} else if (fromType == String.class) {
return mm.var(Double.class).invoke("parseDouble", from.cast(String.class));
} else if (fromType == Integer.class) {
return from.cast(Integer.class);
} else if (fromType == Long.class) {
return mm.var(ConvertCallSite.class).invoke("longToDouble", from.cast(Long.class));
} else if (fromType == Float.class) {
return from.cast(Float.class).invoke("doubleValue");
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("doubleValue");
} else if (fromType == Short.class) {
return from.cast(Short.class).invoke("doubleValue");
} else if (fromType == BigInteger.class) {
var longVar = from.cast(BigInteger.class).invoke("longValueExact");
return mm.var(ConvertCallSite.class).invoke("longToDouble", longVar);
} else if (fromType == BigDecimal.class) {
return mm.var(ConvertCallSite.class).invoke("bdToDouble", from.cast(BigDecimal.class));
} else {
return null;
}
}
private static Variable toChar(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Character.class) {
return from.cast(Character.class);
} else if (fromType == String.class) {
return mm.var(ConvertCallSite.class).invoke("stringToChar", from.cast(String.class));
} else {
return null;
}
}
private static Variable toString(MethodMaker mm, Class fromType, Variable from) {
return mm.var(String.class).invoke("valueOf", from);
}
private static Variable toBigInteger(MethodMaker mm, Class fromType, Variable from) {
Variable longVar;
if (fromType == Integer.class) {
longVar = from.cast(Integer.class);
} else if (fromType == Long.class) {
longVar = from.cast(Long.class);
} else if (fromType == String.class) {
return mm.new_(BigInteger.class, from.cast(String.class));
} else if (fromType == Double.class) {
longVar = mm.var(ConvertCallSite.class).invoke("doubleToLong", from.cast(Double.class));
} else if (fromType == Float.class) {
longVar = mm.var(ConvertCallSite.class).invoke("floatToLong", from.cast(Float.class));
} else if (fromType == Byte.class) {
longVar = from.cast(Byte.class);
} else if (fromType == Short.class) {
longVar = from.cast(Short.class);
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("toBigIntegerExact");
} else {
return null;
}
return mm.var(BigInteger.class).invoke("valueOf", longVar);
}
private static Variable toBigDecimal(MethodMaker mm, Class fromType, Variable from) {
Variable numVar;
if (fromType == String.class) {
return mm.new_(BigDecimal.class, from.cast(String.class));
} else if (fromType == Integer.class) {
numVar = from.cast(Integer.class);
} else if (fromType == Long.class) {
numVar = from.cast(Long.class);
} else if (fromType == Double.class) {
numVar = from.cast(Double.class);
} else if (fromType == Float.class) {
numVar = from.cast(Float.class);
} else if (fromType == Byte.class) {
numVar = from.cast(Byte.class);
} else if (fromType == Short.class) {
numVar = from.cast(Short.class);
} else if (fromType == BigInteger.class) {
return mm.new_(BigDecimal.class, from.cast(BigInteger.class));
} else {
return null;
}
return mm.var(BigDecimal.class).invoke("valueOf", numVar);
}
// Called by generated code.
public static boolean stringToBoolean(String str) {
if (str.equalsIgnoreCase("false")) {
return false;
}
if (str.equalsIgnoreCase("true")) {
return true;
}
throw new IllegalArgumentException("Cannot convert to Boolean: " + str);
}
// Called by generated code.
public static char stringToChar(String str) {
if (str.length() == 1) {
return str.charAt(0);
}
throw new IllegalArgumentException("Cannot convert to Character: " + str);
}
// Called by generated code.
public static int doubleToInt(double d) {
int i = (int) d;
if ((double) i != d) {
throw loss(Integer.class, d);
}
return i;
}
// Called by generated code.
public static long doubleToLong(double d) {
long i = (int) d;
if ((double) i != d) {
throw loss(Long.class, d);
}
return i;
}
// Called by generated code.
public static float doubleToFloat(double d) {
float f = (float) d;
if ((double) f != d) {
throw loss(Float.class, d);
}
return f;
}
// Called by generated code.
public static byte doubleToByte(double d) {
byte b = (byte) d;
if ((double) b != d) {
throw loss(Byte.class, d);
}
return b;
}
// Called by generated code.
public static short doubleToShort(double d) {
short s = (short) d;
if ((double) s != d) {
throw loss(Short.class, d);
}
return s;
}
// Called by generated code.
public static int floatToInt(float f) {
int i = (int) f;
if ((float) i != f) {
throw loss(Integer.class, f);
}
return i;
}
// Called by generated code.
public static long floatToLong(float f) {
long i = (int) f;
if ((float) i != f) {
throw loss(Long.class, f);
}
return i;
}
// Called by generated code.
public static byte floatToByte(float f) {
byte b = (byte) f;
if ((float) b != f) {
throw loss(Byte.class, f);
}
return b;
}
// Called by generated code.
public static short floatToShort(float f) {
short s = (short) f;
if ((float) s != f) {
throw loss(Short.class, f);
}
return s;
}
// Called by generated code.
public static byte shortToByte(short i) {
byte b = (byte) i;
if ((short) b != i) {
throw loss(Byte.class, i);
}
return b;
}
// Called by generated code.
public static byte intToByte(int i) {
byte b = (byte) i;
if ((int) b != i) {
throw loss(Byte.class, i);
}
return b;
}
// Called by generated code.
public static short intToShort(int i) {
short s = (short) i;
if ((int) s != i) {
throw loss(Short.class, i);
}
return s;
}
// Called by generated code.
public static float intToFloat(int i) {
float f = (float) i;
if ((int) f != i) {
throw loss(Float.class, i);
}
return f;
}
// Called by generated code.
public static byte longToByte(long i) {
byte b = (byte) i;
if ((long) b != i) {
throw loss(Byte.class, i);
}
return b;
}
// Called by generated code.
public static short longToShort(long i) {
short s = (short) i;
if ((long) s != i) {
throw loss(Short.class, i);
}
return s;
}
// Called by generated code.
public static float longToFloat(long i) {
float f = (float) i;
if ((long) f != i) {
throw loss(Float.class, i);
}
return f;
}
// Called by generated code.
public static double longToDouble(long i) {
double d = (double) i;
if ((long) d != i) {
throw loss(Double.class, i);
}
return d;
}
// Called by generated code.
public static float bdToFloat(BigDecimal bd) {
float f = bd.floatValue();
if (BigDecimal.valueOf(f).compareTo(bd) != 0) {
throw loss(Float.class, bd);
}
return f;
}
// Called by generated code.
public static double bdToDouble(BigDecimal bd) {
double d = bd.doubleValue();
if (BigDecimal.valueOf(d).compareTo(bd) != 0) {
throw loss(Double.class, bd);
}
return d;
}
private static ArithmeticException loss(Class to, Object value) {
return new ArithmeticException("Cannot convert to " + to.getSimpleName()
+ " without loss: " + value);
}
}
|
package com.sequenceiq.cloudbreak.cmtemplate.configproviders.nifi;
import static com.sequenceiq.cloudbreak.cmtemplate.configproviders.ConfigUtils.config;
import static com.sequenceiq.cloudbreak.template.VolumeUtils.buildSingleVolumePath;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.springframework.stereotype.Component;
import com.cloudera.api.swagger.model.ApiClusterTemplateConfig;
import com.sequenceiq.cloudbreak.cmtemplate.CmHostGroupRoleConfigProvider;
import com.sequenceiq.cloudbreak.template.TemplatePreparationObject;
import com.sequenceiq.cloudbreak.template.views.HostgroupView;
@Component
public class NifiVolumeConfigProvider implements CmHostGroupRoleConfigProvider {
private static final int FIRST_VOLUME = 1;
private static final int SECOND_VOLUME = 2;
private static final int THIRD_VOLUME = 3;
private static final int FOURTH_VOLUME = 4;
@Override
public List<ApiClusterTemplateConfig> getRoleConfigs(String roleType, HostgroupView hostGroupView, TemplatePreparationObject source) {
if (source.getProductDetailsView().getProducts().stream()
.filter(product -> product.getName().equals("CFM"))
.anyMatch(product -> {
String version = product.getVersion();
return "1.0.0.0".equals(version) || "1.0.1.0".equals(version);
})) {
return List.of();
}
Integer volumeCount = Objects.nonNull(hostGroupView) ? hostGroupView.getVolumeCount() : 0;
int flowFileVolInd = FIRST_VOLUME;
int contentVolInd = SECOND_VOLUME;
int provenanceVolInd = THIRD_VOLUME;
int logDirVolInd = FOURTH_VOLUME;
int databaseVolInd = FOURTH_VOLUME;
if (volumeCount == SECOND_VOLUME) {
flowFileVolInd = FIRST_VOLUME;
provenanceVolInd = FIRST_VOLUME;
databaseVolInd = FIRST_VOLUME;
contentVolInd = SECOND_VOLUME;
logDirVolInd = SECOND_VOLUME;
} else if (volumeCount == THIRD_VOLUME) {
flowFileVolInd = FIRST_VOLUME;
databaseVolInd = FIRST_VOLUME;
provenanceVolInd = SECOND_VOLUME;
contentVolInd = THIRD_VOLUME;
logDirVolInd = THIRD_VOLUME;
}
return List.of(
config("nifi.flowfile.repository.directory", buildSingleVolumePath(flowFileVolInd, volumeCount, "flowfile-repo")),
config("nifi.content.repository.directory.default", buildSingleVolumePath(contentVolInd, volumeCount, "content-repo")),
config("nifi.provenance.repository.directory.default", buildSingleVolumePath(provenanceVolInd, volumeCount, "provenance-repo")),
config("log_dir", buildSingleVolumePath(logDirVolInd, volumeCount, "nifi-log")),
config("nifi.database.directory", buildSingleVolumePath(databaseVolInd, volumeCount, "database-dir"))
);
}
@Override
public String getServiceType() {
return "NIFI";
}
@Override
public Set<String> getRoleTypes() {
return Set.of("NIFI_NODE");
}
}
|
package gov.nih.nci.nautilus.test;
import gov.nih.nci.nautilus.de.ChromosomeNumberDE;
import gov.nih.nci.nautilus.de.CytobandDE;
import gov.nih.nci.nautilus.lookup.AllGeneAliasLookup;
import gov.nih.nci.nautilus.lookup.CytobandLookup;
import gov.nih.nci.nautilus.lookup.LookupManager;
import gov.nih.nci.nautilus.lookup.PatientDataLookup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author Himanso
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class LookupManagerTest extends TestCase {
/**
* @param string
*/
public LookupManagerTest(String string) {
super(string);
}
public static Test suite() {
TestSuite suite = new TestSuite();
//suite.addTest(new LookupManagerTest("testGetCytobandPositions"));
// suite.addTest(new LookupManagerTest("testgetCytobandDEs"));
//suite.addTest(new LookupManagerTest("testGetExpPlatforms"));
//suite.addTest(new LookupManagerTest("testGetPathways"));
//suite.addTest(new LookupManagerTest("testGetPatientData"));
//suite.addTest(new LookupManagerTest("testPatientData"));
// suite.addTest(new LookupManagerTest("testgetChrosomeCDEs"));
suite.addTest(new LookupManagerTest("testgetCytobandDEstoo"));
return suite;
}
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}
/*
* @see TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
public void testGetCytobandPositions() {
try {
CytobandLookup[] cytobands = LookupManager.getCytobandPositions();
assertNotNull(cytobands);
System.out.println("cbEndPos"+
"\tcbStart"+
"\tchromosome"+
"\tcytoband"+
"\tcytobandPositionId"+
"\torganism");
for (int i =0;i<cytobands.length;i++) {
CytobandLookup cytoband = cytobands[i];
System.out.println(cytoband.getCbEndPos()+
"\t"+cytoband.getCbStart()+
"\t"+cytoband.getChromosome()+
"\t"+cytoband.getCytoband()+
"\t"+cytoband.getCytobandPositionId()+
"\t"+cytoband.getOrganism());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testgetCytobandDEs(){
ChromosomeNumberDE[] chromosomes;
try {
chromosomes = LookupManager.getChromosomeDEs();
if(chromosomes != null){
for(int i =0; i < chromosomes.length; i++){
System.out.println("Chr:"+ chromosomes[i].getValueObject());
CytobandDE[] cytobands = LookupManager.getCytobandDEs(chromosomes[i]);
if(cytobands != null){
for(int k = 0; k < cytobands.length; k++){
System.out.println("Cytos:"+ cytobands[k].getValueObject());
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testGetPathways() {
//TODO Implement getPathways().
}
public void testGetPatientData() {
//TODO Implement getPatientData().
}
public void testGetExpPlatforms(){
/*try{
ExpPlatformLookup[] expPlatforms = LookupManager.getExpPlatforms();
assertNotNull(expPlatforms);
for (int i =0;i<expPlatforms.length;i++) {
ExpPlatformLookup platform = expPlatforms[i];
System.out.println("expPlatformName"+ platform.getExpPlatformName()+
"\t expPlatformDesc"+platform.getExpPlatformDesc()+
"\t expPlatformId"+platform.getExpPlatformId());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
public void testPatientData(){
try{
PatientDataLookup[] patientData = LookupManager.getPatientData();
assertNotNull(patientData);
System.out.println("patientID"+
"\t survival"+
"\t censor");
for (int i =0;i<patientData.length;i++) {
PatientDataLookup patient = patientData[i];
System.out.println(patient.getSampleId()+
"\t"+patient.getSurvivalLength()+
"\t"+patient.getCensoringStatus());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testgetChrosomeCDEs(){
ChromosomeNumberDE[] chromosomes;
try {
chromosomes = LookupManager.getChromosomeDEs();
TreeSet chrNum = new TreeSet();
TreeSet chrStr = new TreeSet();
Collection returnColl = new ArrayList();
if(chromosomes != null){
for(int i =0; i < chromosomes.length; i++){
String x = chromosomes[i].getValueObject();
try {
chrNum.add(new Integer(x));
}catch(NumberFormatException ex){
chrStr.add(x);
}
}
}
for (Iterator iter = chrNum.iterator(); iter.hasNext();) {
returnColl.add(((Integer)iter.next()).toString());
}
for (Iterator iter = chrStr.iterator(); iter.hasNext();) {
returnColl.add(iter.next());
}
for (Iterator iter = returnColl.iterator(); iter.hasNext();) {
String m = (String) iter.next();
System.out.println(m);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testgetCytobandDEstoo(){
String[] chrNumber = {"1","2"};
System.out.println(chrNumber.toString());
for (int i = 0; i < chrNumber.length; i++) {
try {
CytobandDE[] cytobands = LookupManager.getCytobandDEs(new ChromosomeNumberDE(chrNumber[i]));
if(cytobands != null){
for(int k = 0; k < cytobands.length; k++){
System.out.println("CHR "+chrNumber[i]+" Cytos:"+ cytobands[k].getValueObject());
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void testGeneSymbolAlias(){
try{
List symbols = new ArrayList();
symbols.add("P53");
symbols.add("p53");
symbols.add("tp53");
symbols.add("TP53");
symbols.add("NAT2");
symbols.add("nat2");
symbols.add("EGFR");
System.out.println("Entered Symbol"+"\tAccepted Symbol"+"\tGene Name");
for (Iterator iter = symbols.iterator(); iter.hasNext();) {
String symbol = (String) iter.next();
System.out.print("user Input: "+symbol+"\n");
if(!LookupManager.isGeneSymbolFound(symbol)){
AllGeneAliasLookup[] allGeneAlias = LookupManager.searchGeneKeyWord(symbol);
if(allGeneAlias != null){
for(int i =0; i < allGeneAlias.length ; i++){
AllGeneAliasLookup alias = allGeneAlias[i];
System.out.println(alias.getAlias()+"\t"+alias.getApprovedSymbol()+"\t"+alias.getApprovedName()+"\n");
}
}
}
else{
System.out.println(symbol+" found! \n");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package gov.nih.nci.evs.reportwriter.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.*;
import org.apache.poi.hssf.usermodel.*;
import gov.nih.nci.evs.reportwriter.utils.*;
import gov.nih.nci.evs.reportwriter.bean.*;
/**
* @author EVS Team (Kim Ong, David Yee)
* @version 1.0
*/
public final class FileServlet extends HttpServlet {
protected final Logger logger = Logger.getLogger(FileServlet.class);
// private SearchSessionBean searchService = null;
/**
* Validates the Init and Context parameters, configures authentication URL
*
* @throws ServletException if the init parameters are invalid or any other
* problems occur during initialisation
*/
public void init() throws ServletException {
}
/**
* Route the user to the execute method
*
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
execute(request, response);
}
/**
* Route the user to the execute method
*
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
execute(request, response);
}
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
*
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public void sendErrorResponse(HttpServletRequest request,
HttpServletResponse response, String message) throws IOException,
ServletException {
HttpSession session = request.getSession(false);
if (session != null) {
session.setAttribute("message", message);
String nextJSP = "/pages/message.jsf";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}
}
// String description = "Text (tab delimited)";
// description = "Microsoft Office Excel";
public void sendResponse(HttpServletResponse response,
StandardReport standardReport) throws IOException, ServletException {
// processing download
String fullPathName = standardReport.getPathName();
ReportFormat rf = standardReport.getFormat();
String format = rf.getDescription();
response.setContentType("text/html");
// String line_br = "\n";
String line_br = "\r\n";
response.setHeader("Cache-Control", "no-cache");
if (format.indexOf("Excel") != -1) {
String contentType = "application/vnd.ms-excel";
response.setContentType(contentType);
line_br = "";
}
File file = new File(fullPathName);
String filename = file.getName();
// HKR, GForge# 19467 - wrong placement of '\' in header.
response.addHeader("Content-Disposition", "attachment;filename=\""
+ filename + "\"");
System.out.println("Full path name =" + fullPathName);
System.out.println("File name =" + filename);
if (format.indexOf("Excel") == -1) {
try {
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
String s = "";
while (dis.available() != 0) {
String line = dis.readLine();
s = s + line + line_br;
}
PrintWriter out = response.getWriter();
out.write(s);
out.flush();
out.close();
} catch (Exception e) {
}
} catch (Exception e) {
}
} else if (format.indexOf("Excel") != -1) {
try {
InputStream myxls = new FileInputStream(fullPathName);
HSSFWorkbook wb = new HSSFWorkbook(myxls);
try {
wb.write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
return;
} catch (Exception e) {
// LogUtils.log(logger, Level.ERROR, e);
}
}
}
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// <td class="dataCellText"><a
// href="<%=request.getContextPath() %>/fileServlet?template=<%=templateId%>&format=<%=formatId%>"
// ><%=template%> (<%=formatDescription%>)</a></td>
// Get ReportFormat from database
String formatId = request.getParameter("format");
String templateId = request.getParameter("template");
ReportFormat reportFormat = null;
StandardReportTemplate standardReportTemplate = null;
String message = "Format ID " + formatId + " not found.";
try {
reportFormat = null;
String FQName = "gov.nih.nci.evs.reportwriter.bean.ReportFormat";
String methodName = "setId";
int format_id = Integer.parseInt(formatId);
SDKClientUtil sdkclientutil = new SDKClientUtil();
Object reportFormat_obj =
sdkclientutil.search(FQName, methodName, format_id);
if (reportFormat_obj == null) {
sendErrorResponse(request, response, message);
return;
} else {
reportFormat = (ReportFormat) reportFormat_obj;
}
// Get StandardReportTemplate from database
message = "Template ID " + templateId + " not found.";
try {
// Get all
// gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate
// Find ov.nih.nci.evs.reportwriter.bean.StandardReport with
// matched template and format
// Find the fullpath of the StandardReport
// Check ReportStatus (send not available or pending approval
// message as needed)
FQName =
"gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate";
methodName = "setId";
int template_id = Integer.parseInt(templateId);
Object standardReportTemplate_obj =
sdkclientutil.search(FQName, methodName, template_id);
if (standardReportTemplate_obj == null) {
sendErrorResponse(request, response, message);
}
standardReportTemplate =
(StandardReportTemplate) standardReportTemplate_obj;
// Search for the matched StandardReport in the database (by
// template and format)
FQName = "gov.nih.nci.evs.reportwriter.bean.StandardReport";
message = "The selected report is not available for download.";
Object[] objs = sdkclientutil.search(FQName);
if (objs == null || objs.length == 0) {
sendErrorResponse(request, response, message);
} else {
for (int i = 0; i < objs.length; i++) {
StandardReport standardReport =
(StandardReport) objs[i];
StandardReportTemplate srt =
standardReport.getTemplate();
int i1 = srt.getId().intValue();
int i2 = standardReportTemplate.getId().intValue();
if (i1 == i2) {
ReportFormat rf = standardReport.getFormat();
if (rf != null && rf.getId() == format_id) {
HttpSession session = request.getSession(false);
Boolean isAdmin =
(Boolean) session.getAttribute("isAdmin");
if (isAdmin != null
&& isAdmin.equals(Boolean.TRUE)) {
sendResponse(response, standardReport);
} else {
// Check if the report has been approved:
ReportStatus rs =
standardReport.getStatus();
if (rs != null) {
String approved = "APPROVED";
if (approved.equals(rs.getLabel())) {
sendResponse(response,
standardReport);
} else {
sendErrorResponse(request,
response,
"The selected report has not yet been approved.");
}
} else {
sendErrorResponse(request, response,
"The selected report has not yet been approved.");
}
}
}
}
}
}
} catch (Exception ex) {
sendErrorResponse(request, response, message);
ex.printStackTrace();
}
} catch (Exception ex) {
sendErrorResponse(request, response, message);
ex.printStackTrace();
}
}
}
|
package gov.nih.nci.ncicb.cadsr.loader.ui;
import gov.nih.nci.ncicb.cadsr.loader.*;
import gov.nih.nci.ncicb.cadsr.loader.parser.ElementWriter;
import gov.nih.nci.ncicb.cadsr.loader.parser.ParserException;
import gov.nih.nci.ncicb.cadsr.loader.ui.tree.*;
import gov.nih.nci.ncicb.cadsr.loader.ui.event.*;
import gov.nih.nci.ncicb.cadsr.loader.util.*;
import gov.nih.nci.ncicb.cadsr.loader.ui.util.*;
import gov.nih.nci.ncicb.cadsr.loader.validator.*;
import java.awt.Component;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.io.File;
import javax.swing.*;
import java.util.*;
import gov.nih.nci.ncicb.cadsr.domain.*;
import org.apache.log4j.Logger;
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
/**
* The main Frame containing other frames
*
* @author <a href="mailto:chris.ludet@oracle.com">Christophe Ludet</a>
*/
public class MainFrame extends JFrame
implements ViewChangeListener, CloseableTabbedPaneListener,
PropertyChangeListener
{
private JMenuBar mainMenuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem saveAsMenuItem = new JMenuItem("Save As");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private JMenu editMenu = new JMenu("Edit");
private JMenuItem findMenuItem = new JMenuItem("Find");
private JMenuItem prefMenuItem = new JMenuItem("Preferences");
private JMenu elementMenu = new JMenu("Element");
private JMenuItem applyMenuItem = new JMenuItem("Apply");
private JMenuItem applyToAllMenuItem = new JMenuItem("Apply to All");
private JMenuItem previewReuseMenuItem = new JMenuItem("Preview DE Reuse");
private JMenu runMenu = new JMenu("Run");
private JMenuItem validateMenuItem = new JMenuItem("Validate");
private JMenuItem defaultsMenuItem = new JMenuItem("Defaults");
private JMenuItem validateConceptsMenuItem = new JMenuItem("Validate Concepts");
private JMenu helpMenu = new JMenu("Help");
private JMenuItem aboutMenuItem = new JMenuItem("About");
private JMenuItem indexMenuItem = new JMenuItem("SIW on GForge");
private JSplitPane jSplitPane1 = new JSplitPane();
private JSplitPane jSplitPane2 = new JSplitPane();
private JTabbedPane jTabbedPane1 = new JTabbedPane();
private CloseableTabbedPane viewTabbedPane = new CloseableTabbedPane();
private DEReuseDialog reuseDialog;
private NavigationPanel navigationPanel;
private ErrorPanel errorPanel = null;
private JPanel logPanel;
private MainFrame _this = this;
private JLabel infoLabel = new JLabel(" ");
// private Map<String, UMLElementViewPanel> viewPanels = new HashMap();
private Map<String, NodeViewPanel> viewPanels = new HashMap();
private AssociationViewPanel associationViewPanel = null;
private ValueDomainViewPanel vdViewPanel = null;
private PackageViewPanel packageViewPanel = null;
private ReviewTracker ownerTracker, curatorTracker;
private RunMode runMode = null;
private String saveFilename = "";
private ElementWriter xmiWriter = null;
private static Logger logger = Logger.getLogger(MainFrame.class);
public MainFrame()
{
}
public void init() {
UserSelections selections = UserSelections.getInstance();
runMode = (RunMode)(selections.getProperty("MODE"));
// if(runMode.equals(RunMode.Curator))
curatorTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator);
ownerTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner);
saveFilename = (String)selections.getProperty("FILENAME");
this.reuseDialog = BeansAccessor.getDEReuseDialog();
jbInit();
}
public void exit() {
if(!ChangeTracker.getInstance().isEmpty()) {
int result = JOptionPane.showConfirmDialog((JFrame) null, "Would you like to save your file before quitting?");
switch(result) {
case JOptionPane.YES_OPTION:
saveMenuItem.doClick();
break;
case JOptionPane.NO_OPTION:
break;
case JOptionPane.CANCEL_OPTION:
return;
}
System.exit(0);
}
else
System.exit(0);
}
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("APPLY")) {
applyMenuItem.setEnabled((Boolean)evt.getNewValue());
applyToAllMenuItem.setEnabled((Boolean)evt.getNewValue());
if((Boolean)evt.getNewValue() == true)
infoLabel.setText("Unsaved Changes");
else
infoLabel.setText("Changes Applied");
} else if(evt.getPropertyName().equals("EXPORT_ERRORS")) {
infoLabel.setText("Export Errors Complete");
} else if(evt.getPropertyName().equals("EXPORT_ERRORS_FAILED")) {
infoLabel.setText("Export Errors Failed !");
}
}
/**
* Set the working title on the frame window.
*
* @param file_ null to use the current file name or !null to change the current file name as with
* a "Save As"
*/
public void setWorkingTitle(String file_)
{
if (file_ != null && file_.length() > 0)
saveFilename = file_;
this.setTitle(PropertyAccessor.getProperty("siw.title") + " - " + saveFilename + " - " + runMode.getTitleName());
}
private void jbInit() {
this.getContentPane().setLayout(new BorderLayout());
this.setSize(new Dimension(830, 650));
this.setJMenuBar(mainMenuBar);
this.setIconImage(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("siw-logo3_2.gif")).getImage());
setWorkingTitle(null);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane1.setDividerLocation(160);
jSplitPane2.setDividerLocation(400);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane2.setOneTouchExpandable(true);
fileMenu.add(saveMenuItem);
fileMenu.add(saveAsMenuItem);
fileMenu.addSeparator();
fileMenu.add(findMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
mainMenuBar.add(fileMenu);
editMenu.add(findMenuItem);
editMenu.add(prefMenuItem);
mainMenuBar.add(editMenu);
applyMenuItem.setEnabled(false);
applyToAllMenuItem.setEnabled(false);
previewReuseMenuItem.setEnabled(false);
elementMenu.add(applyMenuItem);
elementMenu.add(applyToAllMenuItem);
// not in this release. re-add to get feature
// elementMenu.add(previewReuseMenuItem);
mainMenuBar.add(elementMenu);
if(runMode.equals(RunMode.Reviewer)) {
// runMenu.add(defaultsMenuItem);
runMenu.add(validateConceptsMenuItem);
mainMenuBar.add(runMenu);
}
if(runMode.equals(RunMode.Curator)) {
runMenu.add(validateConceptsMenuItem);
mainMenuBar.add(runMenu);
}
helpMenu.add(indexMenuItem);
helpMenu.addSeparator();
helpMenu.add(aboutMenuItem);
mainMenuBar.add(helpMenu);
errorPanel = new ErrorPanel(TreeBuilder.getInstance().getRootNode());
errorPanel.addPropertyChangeListener(this);
jTabbedPane1.addTab("Errors", errorPanel);
Icon closeIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("close-tab.gif"));
viewTabbedPane.setCloseIcons(closeIcon, closeIcon, closeIcon);
viewTabbedPane.addCloseableTabbedPaneListener(this);
jTabbedPane1.addTab("Log", logPanel);
jSplitPane2.add(jTabbedPane1, JSplitPane.BOTTOM);
jSplitPane2.add(viewTabbedPane, JSplitPane.TOP);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
navigationPanel = new NavigationPanel();
jSplitPane1.add(navigationPanel, JSplitPane.LEFT);
navigationPanel.addViewChangeListener(this);
this.getContentPane().add(jSplitPane1, BorderLayout.CENTER);
this.getContentPane().add(infoLabel, BorderLayout.SOUTH);
exitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
_this.exit();
}
});
defaultsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
UmlDefaultsPanel dp = new UmlDefaultsPanel(_this);
dp.show();
UIUtil.putToCenter(dp);
}
});
findMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
SearchDialog sd = new SearchDialog(_this);
UIUtil.putToCenter(sd);
sd.addSearchListener(navigationPanel);
sd.setVisible(true);
}
});
findMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
final PreferenceDialog pd = new PreferenceDialog(_this);
prefMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
pd.updatePreferences();
UIUtil.putToCenter(pd);
pd.setVisible(true);
}
});
saveMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
xmiWriter.setOutput(saveFilename);
try {
xmiWriter.write(ElementsLists.getInstance());
infoLabel.setText("File Saved");
} catch (Throwable e){
JOptionPane.showMessageDialog(_this, "There was an error saving your File. Please contact support.", "Error Saving File", JOptionPane.ERROR_MESSAGE);
infoLabel.setText("Save Failed!!");
logger.error(e);
e.printStackTrace();
} // end of try-catch
}
});
saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
saveAsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String saveDir = UserPreferences.getInstance().getRecentDir();
JFileChooser chooser = new JFileChooser(saveDir);
String extension = null;
String fileType = (String)UserSelections.getInstance().getProperty("FILE_TYPE");
if(fileType.equals("ARGO"))
extension = "uml";
else if(fileType.equals("EA"))
extension = "xmi";
chooser.setFileFilter(new InputFileFilter(extension));
int returnVal = chooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String filePath = chooser.getSelectedFile().getAbsolutePath();
if(!filePath.endsWith(extension))
filePath = filePath + "." + extension;
UserPreferences.getInstance().setRecentDir(filePath);
xmiWriter.setOutput(filePath);
setWorkingTitle(filePath);
try {
xmiWriter.write(ElementsLists.getInstance());
infoLabel.setText("File Saved");
} catch (Throwable e){
JOptionPane.showMessageDialog(_this, "There was an error saving your File. Please contact support.", "Error Saving File", JOptionPane.ERROR_MESSAGE);
infoLabel.setText("Save Failed!!");
} // end of try-catch
}
}
});
validateMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
ValidationItems.getInstance().clear();
Validator validator = new UMLValidator();
validator.validate();
ElementsLists elements = ElementsLists.getInstance();
TreeBuilder tb = TreeBuilder.getInstance();
tb.init();
tb.buildTree(elements);
errorPanel.update(tb.getRootNode());
}
});
validateConceptsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
int n = JOptionPane.showConfirmDialog(_this,
"This process may take some time. Would you like to continue? ",
"Validate Concepts", JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION) {
ValidateConceptsDialog vcd = new ValidateConceptsDialog(_this);
vcd.addSearchListener(navigationPanel);
vcd.setVisible(true);
}
}
});
applyMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UMLElementViewPanel viewPanel =
(UMLElementViewPanel)viewTabbedPane
.getSelectedComponent();
try {
viewPanel.apply(false);
} catch (ApplyException e){
infoLabel.setText("Changes were not applied!");
} // end of try-catch
}
});
applyToAllMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UMLElementViewPanel viewPanel =
(UMLElementViewPanel)viewTabbedPane
.getSelectedComponent();
try {
viewPanel.apply(true);
} catch (ApplyException e){
infoLabel.setText("Changes were not applied!");
} // end of try-catch
}
});
previewReuseMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UMLElementViewPanel viewPanel =
(UMLElementViewPanel)viewTabbedPane
.getSelectedComponent();
// update dialog with current node
reuseDialog.init(viewPanel.getConceptEditorPanel().getNode());
UIUtil.putToCenter(reuseDialog);
reuseDialog.setVisible(true);
}
});
previewReuseMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
aboutMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
new AboutPanel();
}
});
indexMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String errMsg = "Error attempting to launch web browser";
String osName = System.getProperty("os.name");
String url = "http://gforge.nci.nih.gov/projects/siw/";
try {
if (osName.startsWith("Mac OS")) {
Class fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class[] {String.class});
openURL.invoke(null, new Object[] {url});
}
else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else { //assume Unix or Linux
String[] browsers = {
"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(
new String[] {"which", browsers[count]}).waitFor() == 0)
browser = browsers[count];
if (browser == null)
throw new Exception("Could not find web browser");
else
Runtime.getRuntime().exec(new String[] {browser, url});
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, errMsg + ":\n" + e.getLocalizedMessage());
}
}
});
}
public void viewChanged(ViewChangeEvent event) {
previewReuseMenuItem.setEnabled(false);
if(event.getType() == ViewChangeEvent.VIEW_CONCEPTS
|| event.getType() == ViewChangeEvent.VIEW_VALUE_MEANING
|| event.getType() == ViewChangeEvent.VIEW_INHERITED) {
UMLNode node = (UMLNode)event.getViewObject();
// If concept is already showing, just bring it up front
if(viewPanels.containsKey(node.getFullPath())) {
NodeViewPanel pa = viewPanels.get(node.getFullPath());
viewTabbedPane.setSelectedComponent((JPanel)pa);
return;
}
if (node instanceof AttributeNode) {
DataElement de = (DataElement)node.getUserObject();
if (StringUtil.isEmpty(de.getPublicId())) {
previewReuseMenuItem.setEnabled(true);
}
}
// if we ask for new tab, or no tab yet, or it's an assoc or a VD.
// then open a new tab.
if((event.getInNewTab() == true) || (viewPanels.size() == 0)
|| viewTabbedPane.getSelectedComponent() instanceof AssociationViewPanel
|| viewTabbedPane.getSelectedComponent() instanceof ValueDomainViewPanel) {
newTab(event, node);
} else { // if not, update current tab.
NodeViewPanel viewPanel = (NodeViewPanel)
viewTabbedPane.getSelectedComponent();
viewTabbedPane.remove(viewTabbedPane.getSelectedIndex());
viewPanels.remove(viewPanel.getName());
newTab(event, node);
}
} else if(event.getType() == ViewChangeEvent.VIEW_ASSOCIATION) {
UMLNode node = (UMLNode)event.getViewObject();
if(associationViewPanel == null) {
associationViewPanel = new AssociationViewPanel(node);
associationViewPanel.addPropertyChangeListener(this);
associationViewPanel.addReviewListener(navigationPanel);
associationViewPanel.addReviewListener(ownerTracker);
associationViewPanel.addReviewListener(curatorTracker);
associationViewPanel.addElementChangeListener(ChangeTracker.getInstance());
associationViewPanel.addNavigationListener(navigationPanel);
navigationPanel.addNavigationListener(associationViewPanel);
viewTabbedPane.addTab("Association", associationViewPanel);
associationViewPanel.setName("Association");
infoLabel.setText("Association");
associationViewPanel.addCustomPropertyChangeListener(this);
} else
associationViewPanel.update(node);
viewTabbedPane.setSelectedComponent(associationViewPanel);
} else if(event.getType() == ViewChangeEvent.VIEW_VALUE_DOMAIN) {
UMLNode node = (UMLNode)event.getViewObject();
// if(vdViewPanel == null) {
// // vdViewPanel = new ValueDomainViewPanel((ValueDomain)node.getUserObject());
// vdViewPanel.update((ValueDomain)node.getUserObject());
// viewTabbedPane.addTab("ValueDomain", vdViewPanel);
// vdViewPanel.setName("ValueDomain");
// infoLabel.setText("ValueDomain");
// else
viewTabbedPane.remove(vdViewPanel);
viewTabbedPane.addTab("ValueDomain", vdViewPanel);
vdViewPanel.update((ValueDomain)node.getUserObject());
infoLabel.setText("ValueDomain");
viewTabbedPane.setSelectedComponent(vdViewPanel);
} else if(event.getType() == ViewChangeEvent.VIEW_PACKAGE) {
UMLNode node = (UMLNode)event.getViewObject();
if(!viewPanels.containsValue(packageViewPanel))
packageViewPanel = null;
if(node.getUserObject() == null)
return;
if(packageViewPanel == null) {
packageViewPanel = new PackageViewPanel(node);
// show only the last 15 chars of the package in tab title
String disp = node.getFullPath();
if(disp.length() > 15)
disp = disp.substring(disp.length() - 15);
viewTabbedPane.addTab(disp, packageViewPanel);
packageViewPanel.setName("Package");
infoLabel.setText(node.getFullPath());
}
else
packageViewPanel.updateNode(node);
viewTabbedPane.setSelectedComponent(packageViewPanel);
}
}
private void newTab(ViewChangeEvent event, UMLNode node) {
String tabTitle = node.getDisplay();
if(node instanceof AttributeNode) {
if(event.getType() == ViewChangeEvent.VIEW_INHERITED)
tabTitle = node.getParent().getParent().getDisplay()
+ "." + tabTitle;
else
tabTitle = node.getParent().getDisplay()
+ "." + tabTitle;
}
NodeViewPanel viewPanel = null;
if(event.getType() == ViewChangeEvent.VIEW_INHERITED) {
viewPanel = new InheritedAttributeViewPanel(node);
} else {
viewPanel = new UMLElementViewPanel(node);
}
viewPanel.addPropertyChangeListener(this);
viewPanel.addReviewListener(navigationPanel);
viewPanel.addReviewListener(ownerTracker);
viewPanel.addReviewListener(curatorTracker);
viewPanel.addElementChangeListener(ChangeTracker.getInstance());
viewPanel.addNavigationListener(navigationPanel);
navigationPanel.addNavigationListener(viewPanel);
viewTabbedPane.addTab(tabTitle, (JPanel)viewPanel);
viewTabbedPane.setSelectedComponent((JPanel)viewPanel);
viewPanel.setName(node.getFullPath());
viewPanels.put(viewPanel.getName(), viewPanel);
infoLabel.setText(tabTitle);
}
public boolean closeTab(int index) {
Component c = viewTabbedPane.getComponentAt(index);
if(c.equals(associationViewPanel))
associationViewPanel = null;
if(c.equals(vdViewPanel))
vdViewPanel = null;
if(c.equals(packageViewPanel))
packageViewPanel = null;
viewPanels.remove(c.getName());
return true;
}
public void setXmiWriter(ElementWriter writer) {
this.xmiWriter = writer;
}
public void setLogTab(JPanel panel) {
this.logPanel = panel;
}
public void setValueDomainViewPanel(ValueDomainViewPanel vdViewPanel) {
this.vdViewPanel = vdViewPanel;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.editors.schematic.figures;
import java.util.List;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.ReportFigureUtilities;
import org.eclipse.birt.report.designer.internal.ui.layout.ReportItemConstraint;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FigureUtilities;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.draw2d.text.FlowBox;
import org.eclipse.draw2d.text.FlowFigure;
import org.eclipse.draw2d.text.FlowPage;
import org.eclipse.draw2d.text.ParagraphTextLayout;
import org.eclipse.swt.graphics.Font;
import com.ibm.icu.text.BreakIterator;
/**
* A Figure with an embedded TextFlow within a FlowPage that contains text.
*
*
*/
public class LabelFigure extends ReportElementFigure
{
private static final Dimension ZERO_DIMENSION = new Dimension( );
private TextFlow label;
private FlowPage flowPage;
private String display;
private Dimension recommendSize = new Dimension();
private boolean isFixLayout;
/**
* Creates a new LabelFigure with a default MarginBorder size 3 and a
* FlowPage containing a TextFlow with the style WORD_WRAP_SOFT.
*/
public LabelFigure( )
{
this( 1 );
}
/**
* @return
*/
public String getDisplay( )
{
return display;
}
/**
* Creates a new LabelFigure with a MarginBorder that is the given size and
* a FlowPage containing a TextFlow with the style WORD_WRAP_HARD.
*
* @param borderSize
* the size of the MarginBorder
*/
public LabelFigure( int borderSize )
{
setBorder( new MarginBorder( borderSize ) );
label = new TextFlow( ) {
public void postValidate( )
{
if ( DesignChoiceConstants.DISPLAY_BLOCK.equals( display )
|| DesignChoiceConstants.DISPLAY_INLINE.equals( display ) )
{
List list = getFragments( );
FlowBox box;
int left = Integer.MAX_VALUE, top = left;
int bottom = Integer.MIN_VALUE;
for ( int i = 0; i < list.size( ); i++ )
{
box = (FlowBox) list.get( i );
left = Math.min( left, box.getX( ) );
top = Math.min( top, box.getBaseline( )
- box.getAscent( ) );
bottom = Math.max( bottom, box.getBaseline( )
+ box.getDescent( ) );
}
int width = LabelFigure.this.getClientArea( ).width;
if (isFixLayout)
{
int maxWidth = calcMaxSegment( )-getInsets( ).getWidth( );
width = Math.max( width, maxWidth);
}
setBounds( new Rectangle( left,
top,
width,
Math.max( LabelFigure.this.getClientArea( ).height,
bottom - top ) ) );
if (isFixLayout( ))
{
Figure child = (Figure)getParent( );
Rectangle rect = child.getBounds( );
child.setBounds( new Rectangle(rect.x, rect.y, width, rect.height) );
}
list = getChildren( );
for ( int i = 0; i < list.size( ); i++ )
{
( (FlowFigure) list.get( i ) ).postValidate( );
}
}
else
{
super.postValidate( );
}
}
};
label.setLayoutManager( new ParagraphTextLayout( label,
ParagraphTextLayout.WORD_WRAP_SOFT ) );
flowPage = new FlowPage( );
flowPage.add( label );
setLayoutManager( new StackLayout( ) );
add( flowPage );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.draw2d.IFigure#getPreferredSize(int, int)
*/
private Dimension getPreferredSize( int wHint, int hHint, boolean isFix, boolean forceWidth, boolean forceHeight )
{
int rx = recommendSize != null ? recommendSize.width : 0;
int ry = recommendSize != null ? recommendSize.height : 0;
rx = getRealRecommendSizeX( rx, wHint );
Dimension dim = null;
if(isFix)
{
int tempHint = wHint;
int maxWidth = calcMaxSegment( );
if (wHint < maxWidth && !forceWidth)
{
tempHint = maxWidth;
}
dim = super.getPreferredSize( tempHint <= 0 ? -1 : tempHint, hHint );
}
// only when display is block, use passed in wHint
else if ( DesignChoiceConstants.DISPLAY_BLOCK.equals( display ) )
{
dim = super.getPreferredSize( rx == 0 ? wHint : rx, hHint );
}
else
{
dim = super.getPreferredSize( rx == 0 ? -1 : rx, hHint );
//fix bug 271116.
if (rx == 0 && wHint > 0 && dim.width > wHint)
{
dim = super.getPreferredSize( wHint, hHint );
}
}
return new Dimension( Math.max( dim.width, rx ), Math.max( dim.height,
ry ) );
}
public Dimension getPreferredSize( int wHint, int hHint )
{
return getPreferredSize( wHint, hHint, false , false, false);
}
public Dimension getMinimumSize( int wHint, int hHint )
{
return getMinimumSize( wHint, hHint, false, false, false );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.draw2d.Figure#getMinimumSize(int, int)
*/
private Dimension getMinimumSize( int wHint, int hHint,boolean isFix, boolean forceWidth, boolean forceHeight )
{
if ( DesignChoiceConstants.DISPLAY_NONE.equals( display ) )
{
return ZERO_DIMENSION;
}
int rx = recommendSize != null ? recommendSize.width : 0;
int ry = recommendSize != null ? recommendSize.height : 0;
rx = getRealRecommendSizeX( rx, wHint );
if ( wHint == -1 && hHint == -1 )
{
int maxWidth = calcMaxSegment( );
// use recommend size if specified, otherwise use max segment size
Dimension dim = super.getMinimumSize( rx == 0 ? maxWidth : rx, -1 );
dim.height = Math.max( dim.height,
Math.max( getInsets( ).getHeight( ), ry ) );
return dim;
}
Dimension dim;
// return the true minimum size with minimum width;
if(isFix)
{
int tempHint = wHint;
int maxWidth = calcMaxSegment( );
if (wHint < maxWidth && !forceWidth)
{
tempHint = maxWidth;
}
dim = super.getMinimumSize( tempHint <= 0 ? -1 : tempHint, hHint );
return new Dimension( Math.max( dim.width, rx ), Math.max( dim.height,
ry ) );
}
else
{
dim = super.getMinimumSize( rx == 0 ? -1 : rx, hHint );
}
if ( dim.width < wHint )
{
return new Dimension( Math.max( dim.width, rx ),
Math.max( dim.height, ry ) );
}
dim = super.getMinimumSize( wHint, hHint );
return new Dimension( Math.max( dim.width, rx ), Math.max( dim.height,
ry ) );
}
private int getRealRecommendSizeX( int rx, int wHint )
{
if ( rx > 0 || wHint == -1 )
{
return rx;
}
if ( getParent( ) != null && getParent( ).getLayoutManager( ) != null )
{
ReportItemConstraint constraint = (ReportItemConstraint) getParent( ).getLayoutManager( )
.getConstraint( this );
if ( constraint != null
&& constraint.getMeasure( ) != 0
&& DesignChoiceConstants.UNITS_PERCENTAGE.equals( constraint.getUnits( ) ) )
{
// compute real percentag recommend size
rx = (int) constraint.getMeasure( ) * wHint / 100;;
}
}
return rx;
}
private int calcMaxSegment( )
{
String text = label.getText( );
char[] chars = text.toCharArray( );
int position = 0;
int maxWidth = 0;
for ( int i = 0; i < chars.length; i++ )
{
if ( canBreakAfter( chars[i] ) )
{
int tempMaxWidth;
String st = text.substring( position, i + 1 );
tempMaxWidth = FigureUtilities.getStringExtents( st, getFont( ) ).width;
if ( tempMaxWidth > maxWidth )
{
maxWidth = tempMaxWidth;
}
position = i;
}
}
String st = text.substring( position, chars.length );
int tempMaxWidth = FigureUtilities.getStringExtents( st, getFont( ) ).width;
if ( tempMaxWidth > maxWidth )
{
maxWidth = tempMaxWidth;
}
return maxWidth + getInsets( ).getWidth( ) ;
}
static final BreakIterator LINE_BREAK = BreakIterator.getLineInstance( );
static boolean canBreakAfter( char c )
{
boolean result = Character.isWhitespace( c ) || c == '-';
if ( !result && ( c < 'a' || c > 'z' ) )
{
// chinese characters and such would be caught in here
// LINE_BREAK is used here because INTERNAL_LINE_BREAK might be in
// use
LINE_BREAK.setText( c + "a" ); //$NON-NLS-1$
result = LINE_BREAK.isBoundary( 1 );
}
return result;
}
private static int getMinimumFontSize( Font ft )
{
if ( ft != null && ft.getFontData( ).length > 0 )
{
return ft.getFontData( )[0].getHeight( );
}
return 0;
}
/**
* Since Eclipse TextFlow figure ignore the trailing /r/n for calculating
* the client size, we must append the extra size ourselves.
*
* @return dimension for the client area used by the editor.
*/
public Rectangle getEditorArea( )
{
Rectangle rect = getClientArea( ).getCopy( );
String s = getText( );
int count = 0;
if ( s != null && s.length( ) > 1 )
{
for ( int i = s.length( ) - 2; i >= 0; i -= 2 )
{
if ( "\r\n".equals( s.substring( i, i + 2 ) ) ) //$NON-NLS-1$
{
count++;
}
else
{
break;
}
}
}
int hh = getMinimumFontSize( getFont( ) );
rect.height += count * hh + ( ( count == 0 ) ? 0 : ( hh / 2 ) );
return rect;
}
/**
* Sets the recommended size.
*
* @param recommendSize
*/
public void setRecommendSize( Dimension recommendSize )
{
this.recommendSize = recommendSize;
}
/**Gets the recommended size.
* @return
*/
public Dimension getRecommendSize( )
{
return recommendSize;
}
/**
* Sets the display property of the Label.
*
* @param display
* the display property. this should be one of the following:
* DesignChoiceConstants.DISPLAY_BLOCK |
* DesignChoiceConstants.DISPLAY_INLINE |
* DesignChoiceConstants.DISPLAY_NONE
*/
public void setDisplay( String display )
{
// if the display equals none, as the block
if ( DesignChoiceConstants.DISPLAY_NONE.equals( display ) )
{
this.display = DesignChoiceConstants.DISPLAY_BLOCK ;
}
else
{
this.display = display;
}
}
/**
* Returns the text inside the TextFlow.
*
* @return the text flow inside the text.
*/
public String getText( )
{
return label.getText( );
}
/**
* Sets the text of the TextFlow to the given value.
*
* @param newText
* the new text value.
*/
public void setText( String newText )
{
if ( newText == null )
{
newText = "";//$NON-NLS-1$
}
label.setText( newText );
}
/**
* Sets the over-line style of the text.
*
* @param textOverline
* The textOverline to set.
*/
public void setTextOverline( String textOverline )
{
label.setTextOverline( textOverline );
}
/**
* Sets the line-through style of the text.
*
* @param textLineThrough
* The textLineThrough to set.
*/
public void setTextLineThrough( String textLineThrough )
{
label.setTextLineThrough( textLineThrough );
}
/**
* Sets the underline style of the text.
*
* @param textUnderline
* The textUnderline to set.
*/
public void setTextUnderline( String textUnderline )
{
label.setTextUnderline( textUnderline );
}
/**
* Sets the horizontal text alignment style.
*
* @param textAlign
* The textAlign to set.
*/
public void setTextAlign( String textAlign )
{
label.setTextAlign( textAlign );
}
/**
* Gets the horizontal text alignment style.
*
* @return The textAlign.
*/
public String getTextAlign( )
{
return label.getTextAlign( );
}
/**
* Sets the vertical text alignment style.
*
* @param verticalAlign
* The verticalAlign to set.
*/
public void setVerticalAlign( String verticalAlign )
{
label.setVerticalAlign( verticalAlign );
}
/**
* Sets the toolTip text for this figure.
*
* @param toolTip
*/
public void setToolTipText( String toolTip )
{
if ( toolTip != null )
{
setToolTip( ReportFigureUtilities.createToolTipFigure( toolTip,
this.getDirection( ),
this.getTextAlign( ) ) );
}
else
{
setToolTip( null );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.draw2d.Figure#setFont(org.eclipse.swt.graphics.Font)
*/
public void setFont( Font f )
{
super.setFont( f );
label.setFont( f );
}
/**
* @param specialPREFIX
*/
public void setSpecialPREFIX( String specialPREFIX )
{
label.setSpecialPREFIX( specialPREFIX );
}
/**
* Gets the direction property of the Label.
*
* @return the Label direction.
*
* @author bidi_hcg
*/
public String getDirection( )
{
return label.getDirection( );
}
/**
* Sets the direction property of the Label.
*
* @param direction
* the direction property. this should be one of the following:
* DesignChoiceConstants.BIDI_DIRECTION_LTR |
* DesignChoiceConstants.BIDI_DIRECTION_RTL
*
* @author bidi_hcg
*/
public void setDirection( String direction )
{
label.setDirection( direction );
}
@Override
public Dimension getFixPreferredSize( int w, int h )
{
int width = 0;
int height = 0;
if (recommendSize.width > 0)
{
width = recommendSize.width;
}
else
{
if (recommendSize.height > 0)
{
width = getPreferredSize( w, recommendSize.height, true, false, true).width;
}
else
{
width = getPreferredSize( w, h, true, false, false ).width;
}
}
if (recommendSize.height > 0)
{
height = recommendSize.height;
}
else
{
if (recommendSize.width > 0)
{
int maxWidth = calcMaxSegment( );
height = getPreferredSize( Math.max( maxWidth, recommendSize.width ), h, true, true, false ).height;
}
else
{
height = getPreferredSize( w, h, true, false, false ).height;
}
}
return new Dimension(width, height);
}
@Override
public Dimension getFixMinimumSize( int w, int h )
{
int width = 0;
int height = 0;
if (recommendSize.width > 0)
{
width = recommendSize.width;
}
else
{
if (recommendSize.height > 0)
{
width = getMinimumSize( w, recommendSize.height, true, false, true).width;
}
else
{
width = getMinimumSize( w, h, true, false, false ).width;
}
}
if (recommendSize.height > 0)
{
height = recommendSize.height;
}
else
{
if (recommendSize.width > 0)
{
int maxWidth = calcMaxSegment( );
height = getMinimumSize( Math.max( maxWidth, recommendSize.width ), h, true, true, false ).height;
}
else
{
height = getMinimumSize( w, h, true, false, false ).height;
}
}
return new Dimension(width, height);
}
public boolean isFixLayout( )
{
return isFixLayout;
}
public void setFixLayout( boolean isFixLayout )
{
this.isFixLayout = isFixLayout;
}
}
|
package com.gimranov.zandy.app;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.gimranov.zandy.app.data.Database;
import com.gimranov.zandy.app.data.Item;
import com.gimranov.zandy.app.data.ItemAdapter;
import com.gimranov.zandy.app.data.ItemCollection;
import com.gimranov.zandy.app.task.APIEvent;
import com.gimranov.zandy.app.task.APIRequest;
import com.gimranov.zandy.app.task.ZoteroAPITask;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class ItemActivity extends ListActivity {
private static final String TAG = "com.gimranov.zandy.app.ItemActivity";
static final int DIALOG_VIEW = 0;
static final int DIALOG_NEW = 1;
static final int DIALOG_SORT = 2;
static final int DIALOG_IDENTIFIER = 3;
static final int DIALOG_PROGRESS = 6;
/**
* Allowed sort orderings
*/
static final String[] SORTS = {
"item_year, item_title",
"item_creator, item_year",
"item_title, item_year",
"timestamp ASC, item_title"
};
/**
* Strings providing the names of each ordering, respectively
*/
static final int[] SORT_NAMES = {
R.string.sort_year_title,
R.string.sort_creator_year,
R.string.sort_title_year,
R.string.sort_modified_title
};
private String collectionKey;
private String query;
private Database db;
private ProgressDialog mProgressDialog;
private ProgressThread progressThread;
public String sortBy = "item_year, item_title";
final Handler syncHandler = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG,"received message: "+msg.arg1);
refreshView();
if (msg.arg1 == APIRequest.UPDATED_DATA) {
refreshView();
return;
}
if (msg.arg1 == APIRequest.QUEUED_MORE) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.sync_queued_more, msg.arg2),
Toast.LENGTH_SHORT).show();
return;
}
if (msg.arg1 == APIRequest.BATCH_DONE) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.sync_complete),
Toast.LENGTH_SHORT).show();
return;
}
if (msg.arg1 == APIRequest.ERROR_UNKNOWN) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.sync_error),
Toast.LENGTH_SHORT).show();
return;
}
}
};
protected Bundle b = new Bundle();
/**
* Refreshes the current list adapter
*/
private void refreshView() {
ItemAdapter adapter = (ItemAdapter) getListAdapter();
Cursor newCursor = prepareCursor();
adapter.changeCursor(newCursor);
adapter.notifyDataSetChanged();
Log.d(TAG, "refreshing view on request");
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new Database(this);
setContentView(R.layout.items);
prepareAdapter();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// If we have a click on an item, do something...
ItemAdapter adapter = (ItemAdapter) parent.getAdapter();
Cursor cur = adapter.getCursor();
// Place the cursor at the selected item
if (cur.moveToPosition(position)) {
// and load an activity for the item
Item item = Item.load(cur);
Log.d(TAG, "Loading item data with key: "+item.getKey());
// We create and issue a specified intent with the necessary data
Intent i = new Intent(getBaseContext(), ItemDataActivity.class);
i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey());
i.putExtra("com.gimranov.zandy.app.itemDbId", item.dbId);
startActivity(i);
} else {
// failed to move cursor-- show a toast
TextView tvTitle = (TextView)view.findViewById(R.id.item_title);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.cant_open_item, tvTitle.getText()),
Toast.LENGTH_SHORT).show();
}
}
});
}
protected void onResume() {
ItemAdapter adapter = (ItemAdapter) getListAdapter();
adapter.changeCursor(prepareCursor());
super.onResume();
}
public void onDestroy() {
ItemAdapter adapter = (ItemAdapter) getListAdapter();
Cursor cur = adapter.getCursor();
if(cur != null) cur.close();
if (db != null) db.close();
super.onDestroy();
}
private void prepareAdapter() {
ItemAdapter adapter = new ItemAdapter(this, prepareCursor());
setListAdapter(adapter);
}
private Cursor prepareCursor() {
Cursor cursor;
// Be ready for a search
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
cursor = getCursor(query);
this.setTitle(getResources().getString(R.string.search_results, query));
} else if (query != null) {
cursor = getCursor(query);
this.setTitle(getResources().getString(R.string.search_results, query));
} else if (intent.getStringExtra("com.gimranov.zandy.app.tag") != null) {
String tag = intent.getStringExtra("com.gimranov.zandy.app.tag");
Query q = new Query();
q.set("tag", tag);
cursor = getCursor(q);
this.setTitle(getResources().getString(R.string.tag_viewing_items, tag));
} else {
collectionKey = intent.getStringExtra("com.gimranov.zandy.app.collectionKey");
if (collectionKey != null) {
ItemCollection coll = ItemCollection.load(collectionKey, db);
cursor = getCursor(coll);
this.setTitle(coll.getTitle());
} else {
cursor = getCursor();
this.setTitle(getResources().getString(R.string.all_items));
}
}
return cursor;
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_NEW:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getResources().getString(R.string.item_type))
// XXX i18n
.setItems(Item.ITEM_TYPES_EN, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int pos) {
Item item = new Item(getBaseContext(), Item.ITEM_TYPES[pos]);
item.dirty = APIRequest.API_DIRTY;
item.save(db);
if (collectionKey != null) {
ItemCollection coll = ItemCollection.load(collectionKey, db);
if (coll != null) {
coll.loadChildren(db);
coll.add(item);
coll.saveChildren(db);
}
}
Log.d(TAG, "Loading item data with key: "+item.getKey());
// We create and issue a specified intent with the necessary data
Intent i = new Intent(getBaseContext(), ItemDataActivity.class);
i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey());
startActivity(i);
}
});
AlertDialog dialog = builder.create();
return dialog;
case DIALOG_SORT:
// We generate the sort name list for our current locale
String[] sorts = new String[SORT_NAMES.length];
for (int j = 0; j < SORT_NAMES.length; j++) {
sorts[j] = getResources().getString(SORT_NAMES[j]);
}
AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
builder2.setTitle(getResources().getString(R.string.set_sort_order))
.setItems(sorts, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int pos) {
Cursor cursor;
setSortBy(SORTS[pos]);
if (collectionKey != null)
cursor = getCursor(ItemCollection.load(collectionKey, db));
else if (query != null)
cursor = getCursor(query);
else
cursor = getCursor();
ItemAdapter adapter = (ItemAdapter) getListAdapter();
adapter.changeCursor(cursor);
Log.d(TAG, "Re-sorting by: "+SORTS[pos]);
}
});
AlertDialog dialog2 = builder2.create();
return dialog2;
case DIALOG_PROGRESS:
Log.d(TAG, "_____________________dialog_progress");
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage(getResources().getString(R.string.identifier_looking_up));
return mProgressDialog;
case DIALOG_IDENTIFIER:
final EditText input = new EditText(this);
input.setHint(getResources().getString(R.string.identifier_hint));
final ItemActivity current = this;
dialog = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.identifier_message))
.setView(input)
.setPositiveButton(getResources().getString(R.string.menu_search), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
// run search
Bundle c = new Bundle();
c.putString("mode", "isbn");
c.putString("identifier", value.toString());
removeDialog(DIALOG_PROGRESS);
ItemActivity.this.b = c;
showDialog(DIALOG_PROGRESS);
}
}).setNeutralButton(getResources().getString(R.string.scan), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
IntentIntegrator integrator = new IntentIntegrator(current);
integrator.initiateScan();
}
}).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// do nothing
}
}).create();
return dialog;
default:
return null;
}
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case DIALOG_PROGRESS:
Log.d(TAG, "_____________________dialog_progress_prepare");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.zotero_menu, menu);
// Turn on sort item
MenuItem sort = menu.findItem(R.id.do_sort);
sort.setEnabled(true);
sort.setVisible(true);
// Turn on search item
MenuItem search = menu.findItem(R.id.do_search);
search.setEnabled(true);
search.setVisible(true);
// Turn on identifier item
MenuItem identifier = menu.findItem(R.id.do_identifier);
identifier.setEnabled(true);
identifier.setVisible(true);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.do_sync:
if (!ServerCredentials.check(getBaseContext())) {
Toast.makeText(getBaseContext(), getResources().getString(R.string.sync_log_in_first),
Toast.LENGTH_SHORT).show();
return true;
}
APIEvent mEvent = new APIEvent() {
private int updates = 0;
@Override
public void onComplete(APIRequest request) {
Message msg = syncHandler.obtainMessage();
msg.arg1 = APIRequest.UPDATED_DATA;
syncHandler.sendMessage(msg);
Log.d(TAG, "fired oncomplete");
}
@Override
public void onUpdate(APIRequest request) {
updates++;
if (updates % 10 == 0) {
Message msg = syncHandler.obtainMessage();
msg.arg1 = APIRequest.UPDATED_DATA;
syncHandler.sendMessage(msg);
} else {
// do nothing
}
}
@Override
public void onError(APIRequest request, Exception exception) {
Log.e(TAG, "APIException caught", exception);
Message msg = syncHandler.obtainMessage();
msg.arg1 = APIRequest.ERROR_UNKNOWN;
syncHandler.sendMessage(msg);
}
@Override
public void onError(APIRequest request, int error) {
Log.e(TAG, "API error caught");
Message msg = syncHandler.obtainMessage();
msg.arg1 = APIRequest.ERROR_UNKNOWN;
syncHandler.sendMessage(msg);
}
};
// Get credentials
ServerCredentials cred = new ServerCredentials(getBaseContext());
// Make this a collection-specific sync, preceding by de-dirtying
Item.queue(db);
ArrayList<APIRequest> list = new ArrayList<APIRequest>();
APIRequest[] templ = {};
for (Item i : Item.queue) {
Log.d(TAG, "Adding dirty item to sync: "+i.getTitle());
list.add(cred.prep(APIRequest.update(i)));
}
if (collectionKey == null) {
Log.d(TAG, "Adding sync request for all items");
APIRequest req = APIRequest.fetchItems(false, cred);
req.setHandler(mEvent);
list.add(req);
} else {
Log.d(TAG, "Adding sync request for collection: " + collectionKey);
APIRequest req = APIRequest.fetchItems(collectionKey, true, cred);
req.setHandler(mEvent);
list.add(req);
}
APIRequest[] reqs = list.toArray(templ);
ZoteroAPITask task = new ZoteroAPITask(getBaseContext());
task.setHandler(syncHandler);
task.execute(reqs);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sync_started),
Toast.LENGTH_SHORT).show();
return true;
case R.id.do_new:
removeDialog(DIALOG_NEW);
showDialog(DIALOG_NEW);
return true;
case R.id.do_identifier:
removeDialog(DIALOG_IDENTIFIER);
showDialog(DIALOG_IDENTIFIER);
return true;
case R.id.do_search:
onSearchRequested();
return true;
case R.id.do_prefs:
Intent i = new Intent(getBaseContext(), SettingsActivity.class);
Log.d(TAG, "Intent for class: "+i.getClass().toString());
startActivity(i);
return true;
case R.id.do_sort:
removeDialog(DIALOG_SORT);
showDialog(DIALOG_SORT);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* Sorting */
public void setSortBy(String sort) {
this.sortBy = sort;
}
/* Handling the ListView and keeping it up to date */
public Cursor getCursor() {
Cursor cursor = db.query("items", Database.ITEMCOLS, null, null, null, null, this.sortBy, null);
if (cursor == null) {
Log.e(TAG, "cursor is null");
}
return cursor;
}
public Cursor getCursor(ItemCollection parent) {
String[] args = { parent.dbId };
Cursor cursor = db.rawQuery("SELECT item_title, item_type, item_content, etag, dirty, " +
"items._id, item_key, item_year, item_creator, timestamp, item_children " +
" FROM items, itemtocollections WHERE items._id = item_id AND collection_id=? ORDER BY "+this.sortBy,
args);
if (cursor == null) {
Log.e(TAG, "cursor is null");
}
return cursor;
}
public Cursor getCursor(String query) {
String[] args = { "%"+query+"%", "%"+query+"%" };
Cursor cursor = db.rawQuery("SELECT item_title, item_type, item_content, etag, dirty, " +
"_id, item_key, item_year, item_creator, timestamp, item_children " +
" FROM items WHERE item_title LIKE ? OR item_creator LIKE ?" +
" ORDER BY "+this.sortBy,
args);
if (cursor == null) {
Log.e(TAG, "cursor is null");
}
return cursor;
}
public Cursor getCursor(Query query) {
return query.query(db);
}
/* Thread and helper to run lookups */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
Log.d(TAG, "_____________________on_activity_result");
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
Bundle b = new Bundle();
b.putString("mode", "isbn");
b.putString("identifier", scanResult.getContents());
if (scanResult != null
&& scanResult.getContents() != null) {
Log.d(TAG, b.getString("identifier"));
progressThread = new ProgressThread(handler, b);
progressThread.start();
this.b = b;
removeDialog(DIALOG_PROGRESS);
showDialog(DIALOG_PROGRESS);
} else {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.identifier_scan_failed),
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.identifier_scan_failed),
Toast.LENGTH_SHORT).show();
}
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG, "______________________handle_message");
if (ProgressThread.STATE_DONE == msg.arg2) {
Bundle data = msg.getData();
String itemKey = data.getString("itemKey");
if (itemKey != null) {
if (collectionKey != null) {
Item item = Item.load(itemKey, db);
ItemCollection coll = ItemCollection.load(collectionKey, db);
coll.add(item);
coll.saveChildren(db);
}
mProgressDialog.dismiss();
mProgressDialog = null;
Log.d(TAG, "Loading new item data with key: "+itemKey);
// We create and issue a specified intent with the necessary data
Intent i = new Intent(getBaseContext(), ItemDataActivity.class);
i.putExtra("com.gimranov.zandy.app.itemKey", itemKey);
startActivity(i);
}
return;
}
if (ProgressThread.STATE_PARSING == msg.arg2) {
mProgressDialog.setMessage(getResources().getString(R.string.identifier_processing));
return;
}
if (ProgressThread.STATE_ERROR == msg.arg2) {
dismissDialog(DIALOG_PROGRESS);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.identifier_lookup_failed),
Toast.LENGTH_SHORT).show();
progressThread.setState(ProgressThread.STATE_DONE);
return;
}
}
};
private class ProgressThread extends Thread {
Handler mHandler;
Bundle arguments;
final static int STATE_DONE = 5;
final static int STATE_FETCHING = 1;
final static int STATE_PARSING = 6;
final static int STATE_ERROR = 7;
int mState;
ProgressThread(Handler h, Bundle b) {
mHandler = h;
arguments = b;
Log.d(TAG, "_____________________thread_constructor");
}
public void run() {
Log.d(TAG, "_____________________thread_run");
mState = STATE_FETCHING;
// Setup
String identifier = arguments.getString("identifier");
String mode = arguments.getString("mode");
URL url;
String urlstring;
String response = "";
if ("isbn".equals(mode)) {
urlstring = "http://xisbn.worldcat.org/webservices/xid/isbn/"
+ identifier
+ "?method=getMetadata&fl=*&format=json&count=1";
} else {
urlstring = "";
}
try {
Log.d(TAG, "Fetching from: "+urlstring);
url = new URL(urlstring);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 16000);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
while (mState == STATE_FETCHING
&& (current = bis.read()) != -1) {
baf.append((byte) current);
}
response = new String(baf.toByteArray());
Log.d(TAG, response);
} catch (IOException e) {
Log.e(TAG, "Error: ",e);
}
Message msg = mHandler.obtainMessage();
msg.arg2 = STATE_PARSING;
mHandler.sendMessage(msg);
// This is OCLC-specific logic
try {
JSONObject result = new JSONObject(response);
if (!result.getString("stat").equals("ok")) {
Log.e(TAG, "Error response received");
msg = mHandler.obtainMessage();
msg.arg2 = STATE_ERROR;
mHandler.sendMessage(msg);
return;
}
result = result.getJSONArray("list").getJSONObject(0);
String form = result.getJSONArray("form").getString(0);
String type;
if ("AA".equals(form)) type = "audioRecording";
else if ("VA".equals(form)) type = "videoRecording";
else if ("FA".equals(form)) type = "film";
else type = "book";
// TODO Fix this
type = "book";
Item item = new Item(getBaseContext(), type);
JSONObject content = item.getContent();
if (result.has("lccn")) {
String lccn = "LCCN: " + result.getJSONArray("lccn").getString(0);
content.put("extra", lccn);
}
if (result.has("isbn")) {
content.put("ISBN", result.getJSONArray("isbn").getString(0));
}
content.put("title", result.optString("title", ""));
content.put("place", result.optString("city", ""));
content.put("edition", result.optString("ed", ""));
content.put("language", result.optString("lang", ""));
content.put("publisher", result.optString("publisher", ""));
content.put("date", result.optString("year", ""));
item.setTitle(result.optString("title", ""));
item.setYear(result.optString("year", ""));
String author = result.optString("author", "");
item.setCreatorSummary(author);
JSONArray array = new JSONArray();
JSONObject member = new JSONObject();
member.accumulate("creatorType", "author");
member.accumulate("name", author);
array.put(member);
content.put("creators", array);
item.setContent(content);
item.save(db);
msg = mHandler.obtainMessage();
Bundle data = new Bundle();
data.putString("itemKey", item.getKey());
msg.setData(data);
msg.arg2 = STATE_DONE;
mHandler.sendMessage(msg);
return;
} catch (JSONException e) {
Log.e(TAG, "exception parsing response", e);
msg = mHandler.obtainMessage();
msg.arg2 = STATE_ERROR;
mHandler.sendMessage(msg);
return;
}
}
public void setState(int state) {
mState = state;
}
}
}
|
package org.goldenorb.conf;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.goldenorb.Vertex;
import org.goldenorb.io.input.VertexBuilder;
import org.goldenorb.io.output.VertexWriter;
public class OrbConfiguration extends Configuration {
public static final String ORB_CLUSTER_BASEPORT = "goldenOrb.cluster.baseport";
public static final String ORB_CLUSTER_NAME = "goldenOrb.cluster.name";
public static final String ORB_JOB_NUMBER = "goldenOrb.jobNumber";
public static final String ORB_ZOOKEEPER_QUORUM = "goldenOrb.zookeeper.quorum";
public static final String ORB_ZOOKEEPER_PORT = "goldenOrb.zookeeper";
public static final String ORB_LAUNCHER = "goldenOrb.orb.launcher";
public static final String ORB_PARTITIONS_PER_MACHINE = "goldenOrb.orb.partitionsPerMachine";
public static final String ORB_PARTITION_VERTEX_THREADS = "goldenOrb.orb.partition.vertex.threads";
public static final String ORB_PARTITION_MESSAGEHANDLER_THREADS = "goldenOrb.orb.partition.messagehandlers.threads";
public static final String ORB_LAUNCHER_NETWORKDEVICE = "goldenOrb.orb.launcher.networkDevice";
public static final String ORB_VERTEX_CLASS = "goldenOrb.vertexClass";
public static final String ORB_MESSAGE_CLASS = "goldenOrb.messageClass";
public static final String ORB_VERTEX_INPUT_FORMAT_CLASS = "goldenOrb.vertexInputFormatClass";
public static final String ORB_VERTEX_OUTPUT_FORMAT_CLASS = "goldenOrb.vertexOutputFormatClass";
public static final String ORB_JOB_NAME = "goldenOrb.job.name";
public static final String ORB_ERROR_OUTPUT_STREAM = "goldenOrb.error.output.stream";
public static final String ORB_SYSTEM_OUTPUT_STREAM = "goldenOrb.system.output.stream";
public static final String ORB_PARTITION_JAVAOPTS = "goldenOrb.partition.javaopts";
public static final String ORB_FS_DEFAULT_NAME = "fs.default.name";
public static final String ORB_FILE_INPUT_FORMAT_CLASS = "mapreduce.inputformat.class";
public static final String ORB_FILE_OUTPUT_FORMAT_CLASS = "mapreduce.outputformat.class";
public static final String ORB_FILE_INPUT_DIR = "mapred.input.dir";
public static final String ORB_FILE_OUTPUT_DIR = "mapred.output.dir";
public static final String ORB_CLASS_PATHS = "orb.class.paths";
public static final String ORB_TRACKER_PORT = "orb.tracker.port";
public static final String ORB_PARTITION_MANAGEMENT_BASEPORT = "goldenOrb.orb.partitionManagement.baseport";
public OrbConfiguration() {
}
public OrbConfiguration(boolean loadDefaults) {
super(loadDefaults);
if (loadDefaults) this.addOrbResources((Configuration) this);
else {
// need the file to load if not defaults
}
}
private static Configuration addOrbResources(Configuration conf) {
conf.addDefaultResource("orb-default.xml");
conf.addDefaultResource("orb-site.xml");
return conf;
}
public Class<?> getMessageClass() throws ClassNotFoundException {
return Class.forName(this.get(this.ORB_MESSAGE_CLASS));
}
public void setMessageClass(Class<?> messageClass) {
this.set(this.ORB_MESSAGE_CLASS, messageClass.getCanonicalName());
}
public Class<? extends VertexWriter> getVertexOutputFormatClass() {
return (Class<? extends VertexWriter>) this.getClass(this.ORB_VERTEX_OUTPUT_FORMAT_CLASS,
VertexWriter.class);
}
public void setVertexOutputFormatClass(Class<?> vertexOutputFormatClass) {
this.set(this.ORB_VERTEX_OUTPUT_FORMAT_CLASS, vertexOutputFormatClass.getCanonicalName());
}
public String getFileOutputPath() {
return this.get(this.ORB_FILE_OUTPUT_DIR);
}
public void setFileOutputPath(String fileOutputPath) {
this.set(this.ORB_FILE_OUTPUT_DIR, fileOutputPath);
}
public String getFileInputPath() {
return this.get(this.ORB_FILE_INPUT_DIR);
}
public void setFileInputPath(String fileInputPath) {
this.set(this.ORB_FILE_INPUT_DIR, fileInputPath);
}
public String getJobNumber() {
return this.get(this.ORB_JOB_NUMBER);
}
public void setJobNumber(String jobNumber) {
this.set(this.ORB_JOB_NUMBER, jobNumber);
}
public Class<? extends Vertex> getVertexClass() {
return (Class<? extends Vertex>) this.getClass(this.ORB_VERTEX_CLASS, Vertex.class);
}
public void setVertexClass(Class<?> vertexClass) {
this.set(this.ORB_VERTEX_CLASS, vertexClass.getCanonicalName());
}
public Class<? extends InputFormat> getFileInputFormatClass() {
return (Class<? extends InputFormat>) this.getClass(this.ORB_VERTEX_CLASS, InputFormat.class);
}
public void setFileInputFormatClass(Class<?> fileInputFormatClass) {
this.set(this.ORB_FILE_INPUT_FORMAT_CLASS, fileInputFormatClass.getCanonicalName());
}
public Class<? extends OutputFormat> getFileOutputFormatClass() {
return (Class<? extends OutputFormat>) this.getClass(this.ORB_FILE_OUTPUT_FORMAT_CLASS,
OutputFormat.class);
}
public void setFileOutputFormatClass(Class<?> fileOutputFormatClass) {
this.set(this.ORB_FILE_OUTPUT_FORMAT_CLASS, fileOutputFormatClass.getName());
}
public Class<? extends VertexBuilder> getVertexInputFormatClass() {
return (Class<? extends VertexBuilder>) this.getClass(this.ORB_VERTEX_INPUT_FORMAT_CLASS,
VertexBuilder.class);
}
public void setVertexInputFormatClass(Class<?> vertexInputFormatClass) {
this.set(this.ORB_VERTEX_INPUT_FORMAT_CLASS, vertexInputFormatClass.getName());
}
public int getNumberOfPartitionsPerMachine() {
return Integer.parseInt(this.get(this.ORB_PARTITIONS_PER_MACHINE));
}
public void setNumberOfPartitionsPerMachine(int numberOfPartitionsPerMachine) {
this.set(this.ORB_PARTITIONS_PER_MACHINE, Integer.toString(numberOfPartitionsPerMachine));
}
public int getNumberOfVertexThreads() {
return Integer.parseInt(this.get(this.ORB_PARTITION_VERTEX_THREADS));
}
public void setNumberOfVertexThreads(int numberOfVertexThreads) {
this.set(this.ORB_PARTITIONS_PER_MACHINE, Integer.toString(numberOfVertexThreads));
}
public int getNumberOfMessageHandlers() {
return Integer.parseInt(this.get(this.ORB_PARTITION_MESSAGEHANDLER_THREADS));
}
public void setNumberOfMessageHandlers(int i) {
this.set(this.ORB_PARTITION_MESSAGEHANDLER_THREADS, Integer.toString(i));
}
public String getOrbClusterName() {
return new String(this.get(this.ORB_CLUSTER_NAME));
}
public void setOrbClusterName(String orbClusterName) {
this.set(this.ORB_CLUSTER_NAME, orbClusterName);
}
public String getOrbJobName() {
return new String(this.get(this.ORB_JOB_NAME));
}
public void setOrbJobName(String orbJobName) {
this.set(this.ORB_JOB_NAME, orbJobName);
}
public String getOrbZooKeeperQuorum() {
return new String(this.get(this.ORB_ZOOKEEPER_QUORUM));
}
public void setOrbZooKeeperQuorum(String orbZooKeeperQuorum) {
this.set(this.ORB_ZOOKEEPER_QUORUM, orbZooKeeperQuorum);
}
public String getOrbLauncherNetworkDevice() {
return new String(this.get(this.ORB_LAUNCHER_NETWORKDEVICE));
}
public void setOrbLauncherNetworkDevice(String orbLauncherNetworkDevice) {
this.set(this.ORB_LAUNCHER_NETWORKDEVICE, orbLauncherNetworkDevice);
}
public String getOrbPartitionJavaopts() {
return new String(this.get(this.ORB_PARTITION_JAVAOPTS));
}
public void setOrbPartitionJavaopts(String orbPartitionJavaopts) {
this.set(this.ORB_PARTITION_JAVAOPTS, orbPartitionJavaopts);
}
public String getNameNode() {
return new String(this.get(this.ORB_FS_DEFAULT_NAME));
}
public void setNameNode(String orbFsDefaultName) {
this.set(this.ORB_FS_DEFAULT_NAME, orbFsDefaultName);
}
public int getOrbBasePort() {
return this.getInt(this.ORB_CLUSTER_BASEPORT, 30616);
}
public void setOrbBasePort(int orbBasePort) {
this.setInt(this.ORB_CLUSTER_BASEPORT, orbBasePort);
}
public void setOrbClassPaths(String[] orbClassPaths) {
this.setStrings(this.ORB_CLASS_PATHS, orbClassPaths);
}
public String[] getOrbClassPaths() {
return this.getStrings(this.ORB_CLASS_PATHS);
}
public void setOrbClassPaths(String string) {
this.set(this.ORB_CLASS_PATHS, string);
}
public String getNetworkInterface() {
// TODO Add as actual property.
return "eth0";
}
public int getOrbTrackerPort() {
return Integer.parseInt(this.get(this.ORB_TRACKER_PORT));
}
public void setOrbTrackerPort(int numberOfPartitionsPerMachine) {
this.set(this.ORB_TRACKER_PORT, Integer.toString(numberOfPartitionsPerMachine));
}
public long getJobHeartbeatTimeout() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean equals(Object rhs) {
return this.getJobNumber().equals(((OrbConfiguration) rhs).getJobNumber());
}
public int getOrbPartitionManagementBaseport() {
return this.getInt(this.ORB_PARTITION_MANAGEMENT_BASEPORT, 40616);
}
public void setOrbPartitionManagementBaseport(int orbPartitionManagementBaseport) {
this.setInt(this.ORB_PARTITION_MANAGEMENT_BASEPORT, orbPartitionManagementBaseport);
}
}
|
package ie.lero.evoting.test.data;
// December 2009
// Dermot Cochran and Joseph R. Kiniry
// Lero Graduate School of Software Engineering, Ireland
// CASL, University College Dublin, Ireland
// IT University of Copenhagen, Denmark
import election.tally.AbstractBallotCounting;
import election.tally.AbstractCountStatus;
import election.tally.Ballot;
import election.tally.BallotBox;
import election.tally.BallotCounting;
import election.tally.Candidate;
import election.tally.CandidateStatus;
import election.tally.Constituency;
import election.tally.CountConfiguration;
import election.tally.Decision;
import election.tally.DecisionStatus;
import election.tally.ElectionStatus;
public class TestDataGenerator {
private static int abstractBallotCounting_count = 0;
private static int abstractCountStatus_count = 0;
private static int ballot_count = 0;
private static int ballotBox_count = 0;
private static int ballotCounting_count = 0;
private static int candidate_count = 0;
private static int constituency_count = 0;
private static int decision_count = 0;
//@ requires 0 <= n;
public static AbstractBallotCounting getAbstractBallotCounting(int n) {
if (abstractBallotCounting_count == 0 || n == 0) {
abstractBallotCounting_count++;
final AbstractBallotCounting ballotCounting = new BallotCounting();
return ballotCounting;
} else if (n < 10) {
final AbstractBallotCounting ballotCounting = new BallotCounting();
ballotCounting.setup(getConstituency(n));
return ballotCounting;
} else if (n < 20) {
final AbstractBallotCounting ballotCounting = new BallotCounting();
ballotCounting.setup(getConstituency(n - 10));
ballotCounting.load(getBallotBox(n - 10));
return ballotCounting;
} else if (n < 30) {
final AbstractBallotCounting ballotCounting = new BallotCounting();
ballotCounting.setup(getConstituency(n - 20));
ballotCounting.load(getBallotBox(n - 20));
ballotCounting.count();
return ballotCounting;
}
throw new java.util.NoSuchElementException();
}
public static byte[] getByteArray() {
final byte[] bytes = {
DecisionStatus.DEEM_ELECTED,
DecisionStatus.EXCLUDE,
DecisionStatus.NO_DECISION,
ElectionStatus.COUNTING,
ElectionStatus.EMPTY,
ElectionStatus.FINISHED,
ElectionStatus.LOADING,
ElectionStatus.PRECOUNT,
ElectionStatus.PRELOAD,
ElectionStatus.SETTING_UP,
AbstractCountStatus.ALL_SEATS_FILLED,
AbstractCountStatus.CANDIDATE_ELECTED,
AbstractCountStatus.CANDIDATE_EXCLUDED,
AbstractCountStatus.CANDIDATES_HAVE_QUOTA,
AbstractCountStatus.END_OF_COUNT,
AbstractCountStatus.LAST_SEAT_BEING_FILLED,
AbstractCountStatus.MORE_CONTINUING_CANDIDATES_THAN_REMAINING_SEATS,
AbstractCountStatus.NO_SEATS_FILLED_YET,
AbstractCountStatus.NO_SURPLUS_AVAILABLE,
AbstractCountStatus.ONE_CONTINUING_CANDIDATE_PER_REMAINING_SEAT,
AbstractCountStatus.ONE_OR_MORE_SEATS_REMAINING,
AbstractCountStatus.READY_FOR_NEXT_ROUND_OF_COUNTING,
AbstractCountStatus.READY_TO_COUNT,
AbstractCountStatus.READY_TO_MOVE_BALLOTS,
AbstractCountStatus.SURPLUS_AVAILABLE,
CandidateStatus.CONTINUING,
CandidateStatus.ELECTED,
CandidateStatus.ELIMINATED
};
return bytes;
}
//@ requires 0 <= n;
public static Constituency getConstituency(int n) {
if (constituency_count == 0 || n == 0) {
constituency_count++;
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(1, 5);
constituency.setNumberOfCandidates(2);
return constituency;
} else if (n <= 3) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(n, 3);
constituency.setNumberOfCandidates(n + 1);
return constituency;
} else if (n <= 5) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(n, 5);
constituency.setNumberOfCandidates(n + 2);
} else if (n == 6) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(1, 4);
constituency.setNumberOfCandidates(n);
} else if (n == 7) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(2, 4);
constituency.setNumberOfCandidates(n);
} else if (n == 8) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(3, 4);
constituency.setNumberOfCandidates(n);
} else if (n == 9) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(4, 4);
constituency.setNumberOfCandidates(n);
} else if (n == 10) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(2, 5);
constituency.setNumberOfCandidates(n);
} else if (n == 11) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(3, 5);
constituency.setNumberOfCandidates(n);
} else if (n == 12) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(5, 5);
constituency.setNumberOfCandidates(Candidate.MAX_CANDIDATES);
} else if (n == 13) {
final Constituency constituency = new Constituency();
constituency.setNumberOfSeats(4, 4);
constituency.setNumberOfCandidates(Candidate.MAX_CANDIDATES - 1);
}
throw new java.util.NoSuchElementException();
}
//@ requires 0 <= n;
public static Ballot getBallot(int n) {
if (ballot_count == 0 || n == 0) {
ballot_count++;
int[] list = new int[0];
return new Ballot(list);
} else if (n <= Candidate.MAX_CANDIDATES) {
int[] list = new int[n];
for (int preference = 0; preference < n; preference++) {
list[preference] = Candidate.getUniqueID();
}
return new Ballot(list);
}
throw new java.util.NoSuchElementException();
}
//@ requires 0 <= n;
public static Candidate getCandidate(int n) {
if (candidate_count == 0 || n == 0) {
candidate_count++;
return new Candidate();
} else if (n == 1) {
Candidate candidate1 = new Candidate();
candidate1.addVote(20000, 0);
candidate1.declareElected();
return candidate1;
} else if (n == 2) {
Candidate candidate2 = new Candidate();
candidate2.declareEliminated();
return candidate2;
} else if (n == 3) {
Candidate candidate3 = new Candidate();
candidate3.addVote(10000, 0);
candidate3.addVote(500, 1);
return candidate3;
}
throw new java.util.NoSuchElementException();
}
//@ requires 0 <= n;
public static BallotBox getBallotBox(int n) {
if (ballotBox_count == 0 || n == 0) {
ballotBox_count++;
final BallotBox emptyBallotBox = new BallotBox();
return emptyBallotBox;
} else if (n == 1) {
final BallotBox oneBallotInBox = new BallotBox();
Candidate firstCandidate = new Candidate();
int[] list = new int[1];
list[0] = firstCandidate.getCandidateID();
oneBallotInBox.accept(list);
return oneBallotInBox;
} else if (n == 2) {
final BallotBox twoBallotsInBox = new BallotBox();
Candidate firstCandidate = new Candidate();
Candidate secondCandidate = new Candidate();
int[] list = new int[2];
list[0] = firstCandidate.getCandidateID();
list[1] = secondCandidate.getCandidateID();
twoBallotsInBox.accept(list);
list[0] = secondCandidate.getCandidateID();
list[1] = firstCandidate.getCandidateID();
twoBallotsInBox.accept(list);
return twoBallotsInBox;
}
throw new java.util.NoSuchElementException();
}
public static int[] getIntArray() {
final int[] integers = {
AbstractBallotCounting.NONE_FOUND_YET,
Ballot.MAX_BALLOTS,
Ballot.NONTRANSFERABLE,
Candidate.MAX_CANDIDATES,
Candidate.NO_CANDIDATE,
CountConfiguration.MAXCOUNT,
CountConfiguration.MAXVOTES,
Decision.MAX_DECISIONS
};
return integers;
}
public static long[] getLongArray() {
final long[] longs = new long[0];
return longs;
}
//@ requires 0 <= n;
public static Decision getDecision(int n) {
if (decision_count == 0 || n == 0) {
decision_count++;
return new Decision();
}
else if (n == 1) {
Decision decision = new Decision();
decision.setCandidate(Candidate.getUniqueID());
decision.setCountNumber(n);
decision.setDecisionType(DecisionStatus.DEEM_ELECTED);
return decision;
}
else if (n == 2) {
Decision decision = new Decision();
decision.setCandidate(Candidate.getUniqueID());
decision.setCountNumber(n);
decision.setDecisionType(DecisionStatus.EXCLUDE);
return decision;
}
else if (n == 3) {
Decision decision = new Decision();
decision.setCandidate(Candidate.getUniqueID());
decision.setCountNumber(n);
decision.setDecisionType(DecisionStatus.NO_DECISION);
return decision;
}
throw new java.util.NoSuchElementException();
}
//@ requires 0 <= n;
public static BallotCounting getBallotCounting(int n) {
if (ballotCounting_count == 0 || n == 0) {
ballotCounting_count++;
return new BallotCounting();
}
else if (n <= AbstractCountStatus.SURPLUS_AVAILABLE) {
BallotCounting ballotCounting = new BallotCounting();
ballotCounting.updateCountStatus(n);
return ballotCounting;
}
throw new java.util.NoSuchElementException();
}
public static Object[] getIntArrayAsObject() {
final Object[] intArray = new Object[0];
return intArray;
}
//@ requires 0 <= n;
public static AbstractCountStatus getAbstractCountStatus(int n) {
if (abstractCountStatus_count == 0 || n == 0) {
abstractCountStatus_count++;
BallotCounting ballotCounting = new BallotCounting();
return ballotCounting.getCountStatus();
}
else if (n <= AbstractCountStatus.SURPLUS_AVAILABLE) {
BallotCounting ballotCounting = new BallotCounting();
AbstractCountStatus countStatus = ballotCounting.getCountStatus();
countStatus.changeState(n);
return countStatus;
}
throw new java.util.NoSuchElementException();
}
}
|
package com.mychess.mychess;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
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.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.mychess.mychess.Chess.Chess;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.ArrayList;
public class Juego extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
Servicio mService;
boolean mBound = false;
ImageView casillas[][] = new ImageView[8][8];
ImageView origen;
ImageView destino;
TextView tiempo;
Tiempo tiempoMovimiento;
int cOrigen;
int cDestino;
int fOrigen;
int fDestino;
boolean enroqueBlanco = true;
boolean enroqueNegro = true;
boolean jugadaLocal = false;// sirve para difenciar entre una jugada local y una remota
Chess chess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
inicializarCasillas();
setOnclickListener();
setDefaultColor();
tiempo = (TextView) findViewById(R.id.textView18);
tiempoMovimiento = new Tiempo();
tiempoMovimiento.iniciar();
/* inicializcion del nuevo juego*/
chess = new Chess();
chess.newGame();
new SocketServidor().conectar();
RecibirMovimientos recibirMovimientos = new RecibirMovimientos();
recibirMovimientos.execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(jugadaLocal) {
SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(Juego.this);
Speech speech = new Speech();
speechRecognizer.setRecognitionListener(speech);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechRecognizer.startListening(intent);
}else
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, Servicio.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Servicio.LocalBinder binder = (Servicio.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mBound = false;
}
};
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.juego, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.jugar) {
// Handle the camera action
} else if (id == R.id.amigos) {
Intent intent = new Intent(Juego.this, Amigos.class);
startActivity(intent);
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void inicializarCasillas() {
casillas[0][0] = (ImageView) findViewById(R.id.a8);
casillas[0][1] = (ImageView) findViewById(R.id.a7);
casillas[0][2] = (ImageView) findViewById(R.id.a6);
casillas[0][3] = (ImageView) findViewById(R.id.a5);
casillas[0][4] = (ImageView) findViewById(R.id.a4);
casillas[0][5] = (ImageView) findViewById(R.id.a3);
casillas[0][6] = (ImageView) findViewById(R.id.a2);
casillas[0][7] = (ImageView) findViewById(R.id.a1);
casillas[1][0] = (ImageView) findViewById(R.id.b8);
casillas[1][1] = (ImageView) findViewById(R.id.b7);
casillas[1][2] = (ImageView) findViewById(R.id.b6);
casillas[1][3] = (ImageView) findViewById(R.id.b5);
casillas[1][4] = (ImageView) findViewById(R.id.b4);
casillas[1][5] = (ImageView) findViewById(R.id.b3);
casillas[1][6] = (ImageView) findViewById(R.id.b2);
casillas[1][7] = (ImageView) findViewById(R.id.b1);
casillas[2][0] = (ImageView) findViewById(R.id.c8);
casillas[2][1] = (ImageView) findViewById(R.id.c7);
casillas[2][2] = (ImageView) findViewById(R.id.c6);
casillas[2][3] = (ImageView) findViewById(R.id.c5);
casillas[2][4] = (ImageView) findViewById(R.id.c4);
casillas[2][5] = (ImageView) findViewById(R.id.c3);
casillas[2][6] = (ImageView) findViewById(R.id.c2);
casillas[2][7] = (ImageView) findViewById(R.id.c1);
casillas[3][0] = (ImageView) findViewById(R.id.d8);
casillas[3][1] = (ImageView) findViewById(R.id.d7);
casillas[3][2] = (ImageView) findViewById(R.id.d6);
casillas[3][3] = (ImageView) findViewById(R.id.d5);
casillas[3][4] = (ImageView) findViewById(R.id.d4);
casillas[3][5] = (ImageView) findViewById(R.id.d3);
casillas[3][6] = (ImageView) findViewById(R.id.d2);
casillas[3][7] = (ImageView) findViewById(R.id.d1);
casillas[4][0] = (ImageView) findViewById(R.id.e8);
casillas[4][1] = (ImageView) findViewById(R.id.e7);
casillas[4][2] = (ImageView) findViewById(R.id.e6);
casillas[4][3] = (ImageView) findViewById(R.id.e5);
casillas[4][4] = (ImageView) findViewById(R.id.e4);
casillas[4][5] = (ImageView) findViewById(R.id.e3);
casillas[4][6] = (ImageView) findViewById(R.id.e2);
casillas[4][7] = (ImageView) findViewById(R.id.e1);
casillas[5][0] = (ImageView) findViewById(R.id.f8);
casillas[5][1] = (ImageView) findViewById(R.id.f7);
casillas[5][2] = (ImageView) findViewById(R.id.f6);
casillas[5][3] = (ImageView) findViewById(R.id.f5);
casillas[5][4] = (ImageView) findViewById(R.id.f4);
casillas[5][5] = (ImageView) findViewById(R.id.f3);
casillas[5][6] = (ImageView) findViewById(R.id.f2);
casillas[5][7] = (ImageView) findViewById(R.id.f1);
casillas[6][0] = (ImageView) findViewById(R.id.g8);
casillas[6][1] = (ImageView) findViewById(R.id.g7);
casillas[6][2] = (ImageView) findViewById(R.id.g6);
casillas[6][3] = (ImageView) findViewById(R.id.g5);
casillas[6][4] = (ImageView) findViewById(R.id.g4);
casillas[6][5] = (ImageView) findViewById(R.id.g3);
casillas[6][6] = (ImageView) findViewById(R.id.g2);
casillas[6][7] = (ImageView) findViewById(R.id.g1);
casillas[7][0] = (ImageView) findViewById(R.id.h8);
casillas[7][1] = (ImageView) findViewById(R.id.h7);
casillas[7][2] = (ImageView) findViewById(R.id.h6);
casillas[7][3] = (ImageView) findViewById(R.id.h5);
casillas[7][4] = (ImageView) findViewById(R.id.h4);
casillas[7][5] = (ImageView) findViewById(R.id.h3);
casillas[7][6] = (ImageView) findViewById(R.id.h2);
casillas[7][7] = (ImageView) findViewById(R.id.h1);
}
private void setDefaultColor() {
boolean dark = true;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (dark)
casillas[i][j].setBackgroundColor(Color.parseColor("#7986CB"));
else
casillas[i][j].setBackgroundColor(Color.parseColor("#C5CAE9"));
dark = !dark;
}
dark = !dark;
}
}
private void setOnclickListener() {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
casillas[i][j].setOnClickListener(this);
}
}
}
private int[] getPosition(int id) {
int position[] = {-1, -1};
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (id == casillas[i][j].getId()) {
position[0] = i;
position[1] = j;
return position;//si el click fue en una casilla se retorna la posicion
}
}
}
return position;//si el click no fue en una casilla se devuelven valores negativos en la posicion
}
private boolean validarCoordenadas(String coordenadas) {
final String columnas = "abcdefgh";
final String filas = "87654321";
cOrigen = columnas.indexOf(coordenadas.charAt(0));
cDestino = columnas.indexOf(coordenadas.charAt(2));
fOrigen = filas.indexOf(coordenadas.charAt(1));
fDestino = filas.indexOf(coordenadas.charAt(3));
if(cOrigen == -1 || cDestino == -1 || fOrigen == -1 || fDestino == -1)
return false;
return true;
}
private void procesarResultados(ArrayList<String> listaCoordenadas) {
String coordenadas;
for (int i = 0; i < listaCoordenadas.size(); ++i) {
coordenadas = listaCoordenadas.get(i).replace(" ", "").toLowerCase();
if (coordenadas.length() == 4) {
if (validarCoordenadas(coordenadas)) {
validarMovimiento(coordenadas);
break;
}
}
}
}
private void enviarMovimiento(String coordendas) {
DataOutputStream out = null;
try {
out = new DataOutputStream(SocketServidor.getSocket().getOutputStream());
out.writeUTF(coordendas);
tiempoMovimiento.reiniciar();
} catch (IOException e) {
e.printStackTrace();
}
}
private void validarMovimiento(String coordenadas){
switch (chess.mover(coordenadas.substring(0,2),coordenadas.substring(2,4)))
{
case 2:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 3:
moverPieza(1,coordenadas);
break;
case 4:
Toast.makeText(Juego.this, "movimiento no valido", Toast.LENGTH_SHORT).show();
break;
case 0:
moverPieza(2,coordenadas);
break;
}
}
private void moverPieza(int n,String coordenada){
if(jugadaLocal){
enviarMovimiento(crearCoordenada());
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}else{
validarCoordenadas(coordenada);
casillas[cDestino][fDestino].setImageDrawable(casillas[cOrigen][fOrigen].getDrawable());
casillas[cOrigen][fOrigen].setImageDrawable(null);
}
jugadaLocal = !jugadaLocal;
if(n == 1){
Toast.makeText(Juego.this, "Jaque Mate", Toast.LENGTH_SHORT).show();
}
}
private String crearCoordenada() {
String coordenada = "";
final String columnas = "abcdefgh";
final String filas = "87654321";
coordenada += columnas.charAt(cOrigen);
coordenada += filas.charAt(fOrigen);
coordenada += columnas.charAt(cDestino);
coordenada += filas.charAt(fDestino);
return coordenada;
}
@Override
public void onClick(View v) {
if(jugadaLocal) {
int position[] = getPosition(v.getId());
if (position[0] != -1) {//si el valor es negativo indica que el click no se realizo en una casilla
if (origen == null) {
origen = casillas[position[0]][position[1]];
cOrigen = position[0];
fOrigen = position[1];
} else {
origen = null;
cDestino = position[0];
fDestino = position[1];
validarMovimiento(crearCoordenada());
}
}
}else{
Toast.makeText(Juego.this, "No es su turno", Toast.LENGTH_SHORT).show();
}
}
class Speech implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle results) {
ArrayList<String> listaPalabras = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
procesarResultados(listaPalabras);
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
}
class Tiempo {
CountDown countDown;
public void iniciar() {
countDown = new CountDown(60000, 1000);
countDown.start();
}
public void detener() {
countDown.cancel();
}
public void reiniciar() {
tiempo.setText("60");
tiempo.setTextColor(Color.WHITE);
countDown.cancel();
}
class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
long time = millisUntilFinished / 1000;
tiempo.setText(String.valueOf(time));
if (time == 15)
tiempo.setTextColor(Color.RED);
}
@Override
public void onFinish() {
}
}
}
class RecibirMovimientos extends AsyncTask<Void, String, Boolean> {
Socket socket;
protected Boolean doInBackground(Void... params) {
socket = SocketServidor.getSocket();
boolean continuar = true;
while (continuar) {
try {
Thread.sleep(250);
InputStream fromServer = SocketServidor.getSocket().getInputStream();
DataInputStream in = new DataInputStream(fromServer);
publishProgress(in.readUTF());
} catch (Exception ex) {
}
}
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
validarMovimiento(values[0]);
Toast.makeText(Juego.this, values[0], Toast.LENGTH_SHORT).show();
tiempoMovimiento.iniciar();
}
}
}
|
package org.jeo.android.graphics;
import static org.jeo.map.Carto.*;
import java.util.ArrayList;
import java.util.List;
import org.jeo.data.VectorData;
import org.jeo.data.mem.MemVector;
import org.jeo.feature.Feature;
import org.jeo.feature.ListFeature;
import org.jeo.feature.Schema;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.index.quadtree.Quadtree;
/**
* Stores {@link Label} objects in a spatial index dealing with label overlapping.
*
* @author Justin Deoliveira, OpenGeo
*
* TODO: use prepared geometries for overlap computation
*/
public class LabelIndex {
Quadtree idx;
public LabelIndex() {
idx = new Quadtree();
}
/**
* Queries the index for labels that overlap the specified label.
*/
public List<Label> query(Label label) {
List<Label> labels = new ArrayList<Label>();
for (Label close : (List<Label>)idx.query(label.bounds())) {
if (close.shape().intersects(label.shape())) {
labels.add(close);
}
}
return labels;
}
/**
* Inserts a label into the index taking into account overlapping labels.
* <p>
* When a label overlap occurs the conflict is resolved by first comparing the user defined
* priority of the label, obtained from {@link Label#priority()}. If the priority of the
* incoming label is less (or no priority specified) than labels currently in the index, the
* incoming label is discarded and not added to the index. If the incoming label is deemed
* higher priority then any conflicting labels are removed from the underlying index.
* </p>
*
* @return True if the label was added to the index, otherwise false.
*/
public boolean insert(Label label) {
boolean add = true;
if (!allowOverlap(label)) {
for (Label overlap : query(label)) {
// conflict, examine priority
if (label.priority().compareTo(overlap.priority()) > 0) {
// kick out existing label
idx.remove(overlap.bounds(), overlap);
}
else {
// existing label one, ignore this one
add = false;
break;
}
}
}
if (add) {
idx.insert(label.bounds(), label);
}
return add;
}
/**
* Returns all the labels in the index.
*/
public Iterable<Label> all() {
return idx.queryAll();
}
/**
* Returns the labels in the index as a vector dataset.
* <p>
* The resulting feature geometry is {@link Label#shape()} and has a "text" attribute coming
* from {@link Label#getText()}.
* </p>
*/
public VectorData features() {
MemVector mem = new MemVector(Schema.build("labels")
.field("geometry", Polygon.class).field("text", String.class).schema());
for (Label l : all()) {
Feature f = new ListFeature(null, null, mem.getSchema());
f.put(l.shape());
f.put("text", l.getText());
mem.add(f);
}
return mem;
}
boolean allowOverlap(Label label) {
return label.getRule().bool(label.getFeature(), TEXT_ALLOW_OVERLAP, false);
}
}
|
package ij.process;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.type.numeric.RealType;
public abstract class SingleCursorRoiOperation<T extends RealType<T>>
{
Image<T> image;
int[] origin, span;
protected SingleCursorRoiOperation(Image<T> image, int[] origin, int[] span)
{
this.image = image;
this.origin = origin.clone();
this.span = span.clone();
ImageUtils.verifyDimensions(image.getDimensions(), origin, span);
}
public Image<T> getImage() { return image; }
public int[] getOrigin() { return origin; }
public int[] getSpan() { return span; }
public abstract void beforeIteration(RealType<?> type);
public abstract void insideIteration(RealType<?> sample);
public abstract void afterIteration();
}
|
package org.postgresql;
import java.sql.*;
import java.util.Properties;
import java.util.Vector;
import org.postgresql.core.Encoding;
import org.postgresql.fastpath.Fastpath;
import org.postgresql.largeobject.LargeObjectManager;
public interface PGConnection
{
/**
* This method returns any notifications that have been received
* since the last call to this method.
* Returns null if there have been no notifications.
* @since 7.3
*/
public PGNotification[] getNotifications();
/**
* This returns the LargeObject API for the current connection.
* @since 7.3
*/
public LargeObjectManager getLargeObjectAPI() throws SQLException;
/**
* This returns the Fastpath API for the current connection.
* @since 7.3
*/
public Fastpath getFastpathAPI() throws SQLException;
/*
* This allows client code to add a handler for one of org.postgresql's
* more unique data types.
*
* <p><b>NOTE:</b> This is not part of JDBC, but an extension.
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* ...
* ((org.postgresql.PGConnection)myconn).addDataType("mytype","my.class.name");
* ...
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* <p>The handling class must extend org.postgresql.util.PGobject
*
* @see org.postgresql.util.PGobject
*/
public void addDataType(String type, String name);
/** @deprecated */
public Encoding getEncoding() throws SQLException;
/** @deprecated */
public int getSQLType(String pgTypeName) throws SQLException;
/** @deprecated */
public int getSQLType(int oid) throws SQLException;
/** @deprecated */
public String getPGType(int oid) throws SQLException;
/** @deprecated */
public int getPGType(String typeName) throws SQLException;
/** @deprecated */
public Object getObject(String type, String value) throws SQLException;
}
|
package com.intellij.xml.refactoring;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.refactoring.actions.BaseRefactoringAction;
import com.intellij.refactoring.rename.RenameHandler;
import com.intellij.xml.XmlElementDescriptor;
import com.intellij.xml.impl.schema.AnyXmlElementDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class XmlTagRenameHandler implements RenameHandler {
private static final Logger LOG = Logger.getInstance("#com.intellij.xml.refactoring.XmlTagRenameHandler");
public boolean isAvailableOnDataContext(final DataContext dataContext) {
final PsiElement element = getElement(dataContext);
//noinspection ConstantConditions
return PlatformPatterns.psiElement().withParent(XmlTag.class).accepts(element) &&
isDeclarationOutOfProjectOrAbsent(element.getProject(), dataContext);
}
public boolean isRenaming(final DataContext dataContext) {
return isAvailableOnDataContext(dataContext);
}
private static boolean isInplaceRenameAvailable(final Editor editor) {
return editor.getSettings().isVariableInplaceRenameEnabled();
}
private static boolean isDeclarationOutOfProjectOrAbsent(@NotNull final Project project, final DataContext context) {
final PsiElement[] elements = BaseRefactoringAction.getPsiElementArray(context);
return elements.length == 0 || elements.length == 1 && shoulBeRenamedInplace(project, elements);
}
private static boolean shoulBeRenamedInplace(Project project, PsiElement[] elements) {
boolean inProject = PsiManager.getInstance(project).isInProject(elements[0]);
if (inProject && elements[0] instanceof XmlTag) {
XmlElementDescriptor descriptor = ((XmlTag)elements[0]).getDescriptor();
return descriptor instanceof AnyXmlElementDescriptor;
}
return !inProject;
}
@Nullable
private static Editor getEditor(@Nullable DataContext context) {
return PlatformDataKeys.EDITOR.getData(context);
}
@Nullable
private static PsiElement getElement(@Nullable final DataContext context) {
if (context != null) {
final Editor editor = getEditor(context);
if (editor != null) {
final int offset = editor.getCaretModel().getOffset();
final PsiFile file = LangDataKeys.PSI_FILE.getData(context);
if (file instanceof XmlFile) {
return file.getViewProvider().findElementAt(offset);
}
}
}
return null;
}
private void invoke(@Nullable final Editor editor, @NotNull final PsiElement element, @Nullable final DataContext context) {
if (!isRenaming(context)) {
return;
}
FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.rename");
if (isInplaceRenameAvailable(editor)) {
XmlTagInplaceRenamer.rename(editor, (XmlTag)element.getParent());
}
else {
XmlTagRenameDialog.renameXmlTag(editor, element, (XmlTag)element.getParent());
}
}
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, @Nullable final DataContext dataContext) {
if (!isRenaming(dataContext)) {
return;
}
final PsiElement element = getElement(dataContext);
assert element != null;
invoke(editor, element, dataContext);
}
public void invoke(@NotNull final Project project, @NotNull final PsiElement[] elements, @Nullable final DataContext dataContext) {
PsiElement element = elements.length == 1 ? elements[0] : null;
if (element == null) {
element = getElement(dataContext);
}
LOG.assertTrue(element != null);
invoke(getEditor(dataContext), element, dataContext);
}
}
|
package bdv.img.n5;
import bdv.AbstractViewerSetupImgLoader;
import bdv.ViewerImgLoader;
import bdv.cache.CacheControl;
import bdv.cache.SharedQueue;
import bdv.img.cache.SimpleCacheArrayLoader;
import bdv.img.cache.VolatileGlobalCellCache;
import bdv.util.ConstantRandomAccessible;
import bdv.util.MipmapTransforms;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.IntFunction;
import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription;
import mpicbg.spim.data.generic.sequence.BasicViewSetup;
import mpicbg.spim.data.generic.sequence.ImgLoaderHint;
import mpicbg.spim.data.sequence.MultiResolutionImgLoader;
import mpicbg.spim.data.sequence.MultiResolutionSetupImgLoader;
import mpicbg.spim.data.sequence.VoxelDimensions;
import net.imglib2.Dimensions;
import net.imglib2.FinalDimensions;
import net.imglib2.FinalInterval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.Volatile;
import net.imglib2.cache.volatiles.CacheHints;
import net.imglib2.cache.volatiles.LoadingStrategy;
import net.imglib2.img.basictypeaccess.volatiles.array.VolatileByteArray;
import net.imglib2.img.basictypeaccess.volatiles.array.VolatileDoubleArray;
import net.imglib2.img.basictypeaccess.volatiles.array.VolatileFloatArray;
import net.imglib2.img.basictypeaccess.volatiles.array.VolatileIntArray;
import net.imglib2.img.basictypeaccess.volatiles.array.VolatileLongArray;
import net.imglib2.img.basictypeaccess.volatiles.array.VolatileShortArray;
import net.imglib2.img.cell.CellGrid;
import net.imglib2.img.cell.CellImg;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.type.NativeType;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.integer.IntType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.integer.ShortType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedIntType;
import net.imglib2.type.numeric.integer.UnsignedLongType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.type.volatiles.VolatileByteType;
import net.imglib2.type.volatiles.VolatileDoubleType;
import net.imglib2.type.volatiles.VolatileFloatType;
import net.imglib2.type.volatiles.VolatileIntType;
import net.imglib2.type.volatiles.VolatileLongType;
import net.imglib2.type.volatiles.VolatileShortType;
import net.imglib2.type.volatiles.VolatileUnsignedByteType;
import net.imglib2.type.volatiles.VolatileUnsignedIntType;
import net.imglib2.type.volatiles.VolatileUnsignedLongType;
import net.imglib2.type.volatiles.VolatileUnsignedShortType;
import net.imglib2.util.Cast;
import net.imglib2.util.Intervals;
import net.imglib2.view.Views;
import org.janelia.saalfeldlab.n5.DataBlock;
import org.janelia.saalfeldlab.n5.DataType;
import org.janelia.saalfeldlab.n5.DatasetAttributes;
import org.janelia.saalfeldlab.n5.N5FSReader;
import org.janelia.saalfeldlab.n5.N5Reader;
import static bdv.img.n5.BdvN5Format.DATA_TYPE_KEY;
import static bdv.img.n5.BdvN5Format.DOWNSAMPLING_FACTORS_KEY;
import static bdv.img.n5.BdvN5Format.getPathName;
public class N5ImageLoader implements ViewerImgLoader, MultiResolutionImgLoader
{
private final File n5File;
// TODO: it would be good if this would not be needed
// find available setups from the n5
private final AbstractSequenceDescription< ?, ?, ? > seq;
/**
* Maps setup id to {@link SetupImgLoader}.
*/
private final Map< Integer, SetupImgLoader > setupImgLoaders = new HashMap<>();
public N5ImageLoader( final File n5File, final AbstractSequenceDescription< ?, ?, ? > sequenceDescription )
{
this.n5File = n5File;
this.seq = sequenceDescription;
}
public File getN5File()
{
return n5File;
}
private volatile boolean isOpen = false;
private SharedQueue createdSharedQueue;
private VolatileGlobalCellCache cache;
private N5Reader n5;
private int requestedNumFetcherThreads = -1;
private SharedQueue requestedSharedQueue;
@Override
public synchronized void setNumFetcherThreads( final int n )
{
requestedNumFetcherThreads = n;
}
@Override
public void setCreatedSharedQueue( final SharedQueue createdSharedQueue )
{
requestedSharedQueue = createdSharedQueue;
}
private void open()
{
if ( !isOpen )
{
synchronized ( this )
{
if ( isOpen )
return;
try
{
this.n5 = new N5FSReader( n5File.getAbsolutePath() );
int maxNumLevels = 0;
final List< ? extends BasicViewSetup > setups = seq.getViewSetupsOrdered();
for ( final BasicViewSetup setup : setups )
{
final int setupId = setup.getId();
final SetupImgLoader setupImgLoader = createSetupImgLoader( setupId );
setupImgLoaders.put( setupId, setupImgLoader );
maxNumLevels = Math.max( maxNumLevels, setupImgLoader.numMipmapLevels() );
}
final int numFetcherThreads = requestedNumFetcherThreads >= 0
? requestedNumFetcherThreads
: Math.max( 1, Runtime.getRuntime().availableProcessors() );
final SharedQueue queue = requestedSharedQueue != null
? requestedSharedQueue
: ( createdSharedQueue = new SharedQueue( numFetcherThreads, maxNumLevels ) );
cache = new VolatileGlobalCellCache( queue );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
isOpen = true;
}
}
}
/**
* Clear the cache. Images that were obtained from
* this loader before {@link #close()} will stop working. Requesting images
* after {@link #close()} will cause the n5 to be reopened (with a
* new cache).
*/
public void close()
{
if ( isOpen )
{
synchronized ( this )
{
if ( !isOpen )
return;
if ( createdSharedQueue != null )
createdSharedQueue.shutdown();
cache.clearCache();
createdSharedQueue = null;
isOpen = false;
}
}
}
@Override
public SetupImgLoader getSetupImgLoader( final int setupId )
{
open();
return setupImgLoaders.get( setupId );
}
private < T extends NativeType< T >, V extends Volatile< T > & NativeType< V > > SetupImgLoader< T, V > createSetupImgLoader( final int setupId ) throws IOException
{
final String pathName = getPathName( setupId );
final DataType dataType = n5.getAttribute( pathName, DATA_TYPE_KEY, DataType.class );
switch ( dataType )
{
case UINT8:
return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedByteType(), new VolatileUnsignedByteType() ) );
case UINT16:
return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedShortType(), new VolatileUnsignedShortType() ) );
case UINT32:
return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedIntType(), new VolatileUnsignedIntType() ) );
case UINT64:
return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedLongType(), new VolatileUnsignedLongType() ) );
case INT8:
return Cast.unchecked( new SetupImgLoader<>( setupId, new ByteType(), new VolatileByteType() ) );
case INT16:
return Cast.unchecked( new SetupImgLoader<>( setupId, new ShortType(), new VolatileShortType() ) );
case INT32:
return Cast.unchecked( new SetupImgLoader<>( setupId, new IntType(), new VolatileIntType() ) );
case INT64:
return Cast.unchecked( new SetupImgLoader<>( setupId, new LongType(), new VolatileLongType() ) );
case FLOAT32:
return Cast.unchecked( new SetupImgLoader<>( setupId, new FloatType(), new VolatileFloatType() ) );
case FLOAT64:
return Cast.unchecked( new SetupImgLoader<>( setupId, new DoubleType(), new VolatileDoubleType() ) );
}
return null;
}
@Override
public CacheControl getCacheControl()
{
open();
return cache;
}
public class SetupImgLoader< T extends NativeType< T >, V extends Volatile< T > & NativeType< V > >
extends AbstractViewerSetupImgLoader< T, V >
implements MultiResolutionSetupImgLoader< T >
{
private final int setupId;
private final double[][] mipmapResolutions;
private final AffineTransform3D[] mipmapTransforms;
public SetupImgLoader( final int setupId, final T type, final V volatileType ) throws IOException
{
super( type, volatileType );
this.setupId = setupId;
final String pathName = getPathName( setupId );
mipmapResolutions = n5.getAttribute( pathName, DOWNSAMPLING_FACTORS_KEY, double[][].class );
mipmapTransforms = new AffineTransform3D[ mipmapResolutions.length ];
for ( int level = 0; level < mipmapResolutions.length; level++ )
mipmapTransforms[ level ] = MipmapTransforms.getMipmapTransformDefault( mipmapResolutions[ level ] );
}
@Override
public RandomAccessibleInterval< V > getVolatileImage( final int timepointId, final int level, final ImgLoaderHint... hints )
{
return prepareCachedImage( timepointId, level, LoadingStrategy.BUDGETED, volatileType );
}
@Override
public RandomAccessibleInterval< T > getImage( final int timepointId, final int level, final ImgLoaderHint... hints )
{
return prepareCachedImage( timepointId, level, LoadingStrategy.BLOCKING, type );
}
@Override
public Dimensions getImageSize( final int timepointId, final int level )
{
try
{
final String pathName = getPathName( setupId, timepointId, level );
final DatasetAttributes attributes = n5.getDatasetAttributes( pathName );
return new FinalDimensions( attributes.getDimensions() );
}
catch( Exception e )
{
return null;
}
}
@Override
public double[][] getMipmapResolutions()
{
return mipmapResolutions;
}
@Override
public AffineTransform3D[] getMipmapTransforms()
{
return mipmapTransforms;
}
@Override
public int numMipmapLevels()
{
return mipmapResolutions.length;
}
@Override
public VoxelDimensions getVoxelSize( final int timepointId )
{
return null;
}
/**
* Create a {@link CellImg} backed by the cache.
*/
private < T extends NativeType< T > > RandomAccessibleInterval< T > prepareCachedImage( final int timepointId, final int level, final LoadingStrategy loadingStrategy, final T type )
{
try
{
final String pathName = getPathName( setupId, timepointId, level );
final DatasetAttributes attributes = n5.getDatasetAttributes( pathName );
final long[] dimensions = attributes.getDimensions();
final int[] cellDimensions = attributes.getBlockSize();
final CellGrid grid = new CellGrid( dimensions, cellDimensions );
final int priority = numMipmapLevels() - 1 - level;
final CacheHints cacheHints = new CacheHints( loadingStrategy, priority, false );
final SimpleCacheArrayLoader< ? > loader = createCacheArrayLoader( n5, pathName );
return cache.createImg( grid, timepointId, setupId, level, cacheHints, loader, type );
}
catch ( IOException e )
{
System.err.println( String.format(
"image data for timepoint %d setup %d level %d could not be found.",
timepointId, setupId, level ) );
return Views.interval(
new ConstantRandomAccessible<>( type.createVariable(), 3 ),
new FinalInterval( 1, 1, 1 ) );
}
}
}
private static class N5CacheArrayLoader< T, A > implements SimpleCacheArrayLoader< A >
{
private final N5Reader n5;
private final String pathName;
private final DatasetAttributes attributes;
private final IntFunction< T > createPrimitiveArray;
private final Function< T, A > createVolatileArrayAccess;
N5CacheArrayLoader( final N5Reader n5, final String pathName, final DatasetAttributes attributes,
final IntFunction< T > createPrimitiveArray,
final Function< T, A > createVolatileArrayAccess )
{
this.n5 = n5;
this.pathName = pathName;
this.attributes = attributes;
this.createPrimitiveArray = createPrimitiveArray;
this.createVolatileArrayAccess = createVolatileArrayAccess;
}
@Override
public A loadArray( final long[] gridPosition, final int[] cellDimensions ) throws IOException
{
final DataBlock< T > dataBlock = Cast.unchecked( n5.readBlock( pathName, attributes, gridPosition ) );
if ( dataBlock != null && Arrays.equals( dataBlock.getSize(), cellDimensions ) )
{
return createVolatileArrayAccess.apply( dataBlock.getData() );
}
else
{
final T data = createPrimitiveArray.apply( ( int ) Intervals.numElements( cellDimensions ) );
if ( dataBlock != null )
{
final T src = dataBlock.getData();
final int[] srcDims = dataBlock.getSize();
final int[] pos = new int[ srcDims.length ];
final int[] size = new int[ srcDims.length ];
Arrays.setAll( size, d -> Math.min( srcDims[ d ], cellDimensions[ d ] ) );
ndArrayCopy( src, srcDims, pos, data, cellDimensions, pos, size );
}
return createVolatileArrayAccess.apply( data );
}
}
}
public static SimpleCacheArrayLoader< ? > createCacheArrayLoader( final N5Reader n5, final String pathName ) throws IOException
{
final DatasetAttributes attributes = n5.getDatasetAttributes( pathName );
switch ( attributes.getDataType() )
{
case UINT8:
case INT8:
return new N5CacheArrayLoader<>( n5, pathName, attributes, byte[]::new, data -> new VolatileByteArray( data, true ) );
case UINT16:
case INT16:
return new N5CacheArrayLoader<>( n5, pathName, attributes, short[]::new, data -> new VolatileShortArray( data, true ) );
case UINT32:
case INT32:
return new N5CacheArrayLoader<>( n5, pathName, attributes, int[]::new, data -> new VolatileIntArray( data, true ) );
case UINT64:
case INT64:
return new N5CacheArrayLoader<>( n5, pathName, attributes, long[]::new, data -> new VolatileLongArray( data, true ) );
case FLOAT32:
return new N5CacheArrayLoader<>( n5, pathName, attributes, float[]::new, data -> new VolatileFloatArray( data, true ) );
case FLOAT64:
return new N5CacheArrayLoader<>( n5, pathName, attributes, double[]::new, data -> new VolatileDoubleArray( data, true ) );
default:
throw new IllegalArgumentException();
}
}
/**
* Like `System.arrayCopy()` but for flattened nD arrays.
*
* @param src
* the (flattened) source array.
* @param srcSize
* dimensions of the source array.
* @param srcPos
* starting position in the source array.
* @param dest
* the (flattened destination array.
* @param destSize
* dimensions of the source array.
* @param destPos
* starting position in the destination data.
* @param size
* the number of array elements to be copied.
*/
// TODO: This will be moved to a new imglib2-blk artifact later. Re-use it from there when that happens.
private static < T > void ndArrayCopy(
final T src, final int[] srcSize, final int[] srcPos,
final T dest, final int[] destSize, final int[] destPos,
final int[] size)
{
final int n = srcSize.length;
int srcStride = 1;
int destStride = 1;
int srcOffset = 0;
int destOffset = 0;
for ( int d = 0; d < n; ++d )
{
srcOffset += srcStride * srcPos[ d ];
srcStride *= srcSize[ d ];
destOffset += destStride * destPos[ d ];
destStride *= destSize[ d ];
}
ndArrayCopy( n - 1, src, srcSize, srcOffset, dest, destSize, destOffset, size );
}
private static <T> void ndArrayCopy(
final int d,
final T src, final int[] srcSize, final int srcPos,
final T dest, final int[] destSize, final int destPos,
final int[] size)
{
if ( d == 0 )
System.arraycopy( src, srcPos, dest, destPos, size[ d ] );
else
{
int srcStride = 1;
int destStride = 1;
for ( int dd = 0; dd < d; ++dd )
{
srcStride *= srcSize[ dd ];
destStride *= destSize[ dd ];
}
final int w = size[ d ];
for ( int x = 0; x < w; ++x )
{
ndArrayCopy( d - 1,
src, srcSize, srcPos + x * srcStride,
dest, destSize, destPos + x * destStride,
size );
}
}
}
}
|
package org.eclipse.smarthome.io.transport.mqtt;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttClientPersistence;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
import org.eclipse.smarthome.config.core.ConfigConstants;
import org.eclipse.smarthome.io.transport.mqtt.internal.ClientCallback;
import org.eclipse.smarthome.io.transport.mqtt.internal.MqttActionAdapterCallback;
import org.eclipse.smarthome.io.transport.mqtt.internal.TopicSubscribers;
import org.eclipse.smarthome.io.transport.mqtt.reconnect.AbstractReconnectStrategy;
import org.eclipse.smarthome.io.transport.mqtt.reconnect.PeriodicReconnectStrategy;
import org.eclipse.smarthome.io.transport.mqtt.sslcontext.AcceptAllCertificatesSSLContext;
import org.eclipse.smarthome.io.transport.mqtt.sslcontext.SSLContextProvider;
import org.osgi.service.cm.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An MQTTBrokerConnection represents a single client connection to a MQTT broker.
*
* When a connection to an MQTT broker is lost, it will try to reconnect every 60 seconds.
*
* @author David Graeff - All operations are async now. More flexible sslContextProvider and reconnectStrategy added.
* @author Davy Vanherbergen
* @author Markus Rathgeb - added connection state callback
*/
@NonNullByDefault
public class MqttBrokerConnection {
final Logger logger = LoggerFactory.getLogger(MqttBrokerConnection.class);
public static final int DEFAULT_KEEPALIVE_INTERVAL = 60;
public static final int DEFAULT_QOS = 0;
/**
* MQTT transport protocols
*/
public enum Protocol {
TCP,
WEBSOCKETS
};
/// Connection parameters
protected final Protocol protocol;
protected final String host;
protected final int port;
protected final boolean secure;
protected final String clientId;
private @Nullable String user;
private @Nullable String password;
/// Configuration variables
private int qos = DEFAULT_QOS;
private boolean retain = false;
private @Nullable MqttWillAndTestament lastWill;
private @Nullable Path persistencePath;
protected @Nullable AbstractReconnectStrategy reconnectStrategy;
private SSLContextProvider sslContextProvider = new AcceptAllCertificatesSSLContext();
private int keepAliveInterval = DEFAULT_KEEPALIVE_INTERVAL;
/// Runtime variables
protected @Nullable MqttAsyncClient client;
protected @Nullable MqttClientPersistence dataStore;
protected boolean isConnecting = false;
protected final List<MqttConnectionObserver> connectionObservers = new CopyOnWriteArrayList<>();
protected final Map<String, TopicSubscribers> subscribers = new HashMap<>();
// Connection timeout handling
protected final AtomicReference<@Nullable ScheduledFuture<?>> timeoutFuture = new AtomicReference<>(null);
protected @Nullable ScheduledExecutorService timeoutExecutor;
private int timeout = 1200; /* Connection timeout in milliseconds */
/**
* Create a IMqttActionListener object for being used as a callback for a connection attempt.
* The callback will interact with the {@link AbstractReconnectStrategy} as well as inform registered
* {@link MqttConnectionObserver}s.
*/
@NonNullByDefault({})
public class ConnectionCallback implements IMqttActionListener {
private final MqttBrokerConnection connection;
private final Runnable cancelTimeoutFuture;
private CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
public ConnectionCallback(MqttBrokerConnection mqttBrokerConnectionImpl) {
this.connection = mqttBrokerConnectionImpl;
this.cancelTimeoutFuture = mqttBrokerConnectionImpl::cancelTimeoutFuture;
}
@Override
public void onSuccess(IMqttToken asyncActionToken) {
cancelTimeoutFuture.run();
connection.isConnecting = false;
if (connection.reconnectStrategy != null) {
connection.reconnectStrategy.connectionEstablished();
}
List<CompletableFuture<Boolean>> futures = new ArrayList<>();
connection.subscribers.forEach((topic, subscriberList) -> {
futures.add(connection.subscribeRaw(topic));
});
// As soon as all subscriptions are performed, turn the connection future complete.
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).thenRun(() -> {
future.complete(true);
connection.connectionObservers
.forEach(o -> o.connectionStateChanged(connection.connectionState(), null));
});
}
@Override
public void onFailure(@Nullable IMqttToken token, @Nullable Throwable error) {
cancelTimeoutFuture.run();
final Throwable throwable = (token != null && token.getException() != null) ? token.getException() : error;
final MqttConnectionState connectionState = connection.connectionState();
future.complete(false);
connection.connectionObservers.forEach(o -> o.connectionStateChanged(connectionState, throwable));
// If we tried to connect via start(), use the reconnect strategy to try it again
if (connection.isConnecting) {
connection.isConnecting = false;
if (connection.reconnectStrategy != null) {
connection.reconnectStrategy.lostConnection();
}
}
}
public CompletableFuture<Boolean> createFuture() {
future = new CompletableFuture<Boolean>();
return future;
}
}
/** Client callback object */
protected ClientCallback clientCallback = new ClientCallback(this, connectionObservers, subscribers);
/** Connection callback object */
protected ConnectionCallback connectionCallback;
/** Action callback object */
protected IMqttActionListener actionCallback = new MqttActionAdapterCallback();
public MqttBrokerConnection(String host, @Nullable Integer port, boolean secure, @Nullable String clientId) {
this(Protocol.TCP, host, port, secure, clientId);
}
public MqttBrokerConnection(Protocol protocol, String host, @Nullable Integer port, boolean secure,
@Nullable String clientId) {
this.protocol = protocol;
this.host = host;
this.secure = secure;
String newClientID = clientId;
if (newClientID == null) {
newClientID = MqttClient.generateClientId();
} else if (newClientID.length() > 65535) {
throw new IllegalArgumentException("Client ID cannot be longer than 65535 characters");
}
if (port != null && (port <= 0 || port > 65535)) {
throw new IllegalArgumentException("Port is not within a valid range");
}
this.port = port != null ? port : (secure ? 8883 : 1883);
this.clientId = newClientID;
setReconnectStrategy(new PeriodicReconnectStrategy());
connectionCallback = new ConnectionCallback(this);
}
/**
* Set the reconnect strategy. The implementor will be called when the connection
* state to the MQTT broker changed.
*
* The reconnect strategy will not be informed if the initial connection to the broker
* timed out. You need a timeout executor additionally, see {@link #setTimeoutExecutor(Executor)}.
*
* @param reconnectStrategy The reconnect strategy. May not be null.
*/
public void setReconnectStrategy(AbstractReconnectStrategy reconnectStrategy) {
this.reconnectStrategy = reconnectStrategy;
reconnectStrategy.setBrokerConnection(this);
}
/**
* @return Return the reconnect strategy
*/
public @Nullable AbstractReconnectStrategy getReconnectStrategy() {
return this.reconnectStrategy;
}
/**
* Set a timeout executor. If none is set, you will not be notified of connection timeouts, this
* also includes a non-firing reconnect strategy. The default executor is none.
*
* @param executor One timer will be created when a connection attempt happens
* @param timeoutInMS Timeout in milliseconds
*/
public void setTimeoutExecutor(@Nullable ScheduledExecutorService executor, int timeoutInMS) {
timeoutExecutor = executor;
this.timeout = timeoutInMS;
}
/**
* Get the MQTT broker protocol
*/
public Protocol getProtocol() {
return protocol;
}
/**
* Get the MQTT broker host
*/
public String getHost() {
return host;
}
/**
* Get the MQTT broker port
*/
public int getPort() {
return port;
}
/**
* Return true if this is or will be an encrypted connection to the broker
*/
public boolean isSecure() {
return secure;
}
/**
* Set the optional user name and optional password to use when connecting to the MQTT broker.
* The connection needs to be restarted for the new settings to take effect.
*
* @param user Name to use for connection.
* @param password The password
*/
public void setCredentials(@Nullable String user, @Nullable String password) {
this.user = user;
this.password = password;
}
/**
* @return connection password.
*/
public @Nullable String getPassword() {
return password;
}
/**
* @return optional user name for the MQTT connection.
*/
public @Nullable String getUser() {
return user;
}
/**
* @return quality of service level.
*/
public int getQos() {
return qos;
}
/**
* Set quality of service. Valid values are 0, 1, 2 and mean
* "at most once", "at least once" and "exactly once" respectively.
* The connection needs to be restarted for the new settings to take effect.
*
* @param qos level.
*/
public void setQos(int qos) {
if (qos >= 0 && qos <= 2) {
this.qos = qos;
} else {
throw new IllegalArgumentException("The quality of service parameter must be >=0 and <=2.");
}
}
/**
* @return true if newly messages sent to the broker should be retained by the broker.
*/
public boolean isRetain() {
return retain;
}
/**
* Set whether newly published messages should be retained by the broker.
*
* @param retain true to retain.
*/
public void setRetain(boolean retain) {
this.retain = retain;
}
/**
* Return the last will object or null if there is none.
*/
public @Nullable MqttWillAndTestament getLastWill() {
return lastWill;
}
/**
* Set the last will object.
*
* @param lastWill The last will object or null.
* @param applyImmediately If true, the connection will stopped and started for the new last-will to take effect
* immediately.
* @throws MqttException
* @throws ConfigurationException
*/
public void setLastWill(@Nullable MqttWillAndTestament lastWill, boolean applyImmediately)
throws ConfigurationException, MqttException {
this.lastWill = lastWill;
if (applyImmediately) {
stop();
start();
}
}
/**
* Set the last will object.
* The connection needs to be restarted for the new settings to take effect.
*
* @param lastWill The last will object or null.
*/
public void setLastWill(@Nullable MqttWillAndTestament lastWill) {
this.lastWill = lastWill;
}
public void setPersistencePath(final @Nullable Path persistencePath) {
this.persistencePath = persistencePath;
}
/**
* Get client id to use when connecting to the broker.
*
* @return value clientId to use.
*/
public String getClientId() {
return clientId;
}
/**
* Returns the connection state
*/
public MqttConnectionState connectionState() {
if (isConnecting) {
return MqttConnectionState.CONNECTING;
}
return (client != null && client.isConnected()) ? MqttConnectionState.CONNECTED
: MqttConnectionState.DISCONNECTED;
}
/**
* Set the keep alive interval. The default interval is 60 seconds. If no heartbeat is received within this
* timeframe, the connection will be considered dead. Set this to a higher value on systems which may not always be
* able to process the heartbeat in time.
*
* @param keepAliveInterval interval in seconds
*/
public void setKeepAliveInterval(int keepAliveInterval) {
if (keepAliveInterval <= 0) {
throw new IllegalArgumentException("Keep alive cannot be <=0");
}
this.keepAliveInterval = keepAliveInterval;
}
/**
* Return the keep alive internal in seconds
*/
public int getKeepAliveInterval() {
return keepAliveInterval;
}
/**
* Return the ssl context provider.
*/
public SSLContextProvider getSSLContextProvider() {
return sslContextProvider;
}
/**
* Set the ssl context provider. The default provider is {@see AcceptAllCertifcatesSSLContext}.
*
* @return The ssl context provider. Should not be null, but the ssl context will in fact
* only be used if a ssl:// url is given.
*/
public void setSSLContextProvider(SSLContextProvider sslContextProvider) {
this.sslContextProvider = sslContextProvider;
}
/**
* Return true if there are subscribers registered via {@link #subscribe(String, MqttMessageSubscriber)}.
* Call {@link #unsubscribe(String, MqttMessageSubscriber)} or {@link #unsubscribeAll()} if necessary.
*/
public boolean hasSubscribers() {
return !subscribers.isEmpty();
}
/**
* Add a new message consumer to this connection. Multiple subscribers with the same
* topic are allowed. This method will not protect you from adding a subscriber object
* multiple times!
*
* @param consumer Consumer to add
* @throws MqttException If connected and the subscribe fails, this exception is thrown.
*/
public CompletableFuture<Boolean> subscribe(String topic, MqttMessageSubscriber subscriber) {
CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
synchronized (subscribers) {
TopicSubscribers subscriberList = subscribers.getOrDefault(topic, new TopicSubscribers(topic));
subscribers.put(topic, subscriberList);
subscriberList.add(subscriber);
}
MqttAsyncClient client = this.client;
if (client != null && client.isConnected()) {
try {
client.subscribe(topic, qos, future, actionCallback);
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
future.completeExceptionally(e);
}
}
return future;
}
/**
* Subscribes to a topic on the given connection, but does not alter the subscriber list.
*
*/
protected CompletableFuture<Boolean> subscribeRaw(String topic) {
logger.trace("subscribeRaw message consumer for topic '{}' from broker '{}'", topic, host);
CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
try {
MqttAsyncClient client = this.client;
if (client != null && client.isConnected()) {
client.subscribe(topic, qos, future, actionCallback);
} else {
future.complete(false);
}
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
logger.info("Error subscribing to topic {}", topic, e);
future.completeExceptionally(e);
}
return future;
}
/**
* Remove a previously registered consumer from this connection.
*
* @param subscriber to remove.
*/
@SuppressWarnings({ "null", "unused" })
public CompletableFuture<Boolean> unsubscribe(String topic, MqttMessageSubscriber subscriber) {
synchronized (subscribers) {
final @Nullable List<MqttMessageSubscriber> list = subscribers.get(topic);
if (list == null) {
return CompletableFuture.completedFuture(true);
}
list.remove(subscriber);
if (!list.isEmpty()) {
return CompletableFuture.completedFuture(true);
}
// Remove from subscriber list
subscribers.remove(topic);
// No more subscribers to this topic. Unsubscribe topic on the broker
MqttAsyncClient client = this.client;
if (client != null) {
return unsubscribeRaw(client, topic);
} else {
return CompletableFuture.completedFuture(false);
}
}
}
/**
* Unsubscribes a topic on the given connection, but does not alter the subscriber list.
*
* @param client The client connection
* @param topic The topic to unsubscribe from
* @return Completes with true if successful. Exceptionally otherwise.
*/
protected CompletableFuture<Boolean> unsubscribeRaw(MqttAsyncClient client, String topic) {
logger.trace("Unsubscribing message consumer for topic '{}' from broker '{}'", topic, host);
CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
try {
if (client.isConnected()) {
client.unsubscribe(topic, future, actionCallback);
} else {
future.complete(false);
}
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
logger.info("Error unsubscribing topic from broker", e);
future.completeExceptionally(e);
}
return future;
}
/**
* Add a new connection observer to this connection.
*
* @param connectionObserver The connection observer that should be added.
*/
public synchronized void addConnectionObserver(MqttConnectionObserver connectionObserver) {
connectionObservers.add(connectionObserver);
}
/**
* Remove a previously registered connection observer from this connection.
*
* @param connectionObserver The connection observer that should be removed.
*/
public synchronized void removeConnectionObserver(MqttConnectionObserver connectionObserver) {
connectionObservers.remove(connectionObserver);
}
/**
* Return true if there are connection observers registered via addConnectionObserver().
*/
public boolean hasConnectionObservers() {
return !connectionObservers.isEmpty();
}
/**
* Create a MqttConnectOptions object using the fields of this MqttBrokerConnection instance.
* Package local, for testing.
*/
MqttConnectOptions createMqttOptions() throws ConfigurationException {
MqttConnectOptions options = new MqttConnectOptions();
if (!StringUtils.isBlank(user)) {
options.setUserName(user);
}
if (!StringUtils.isBlank(password) && password != null) {
options.setPassword(password.toCharArray());
}
if (secure) {
options.setSocketFactory(sslContextProvider.getContext().getSocketFactory());
}
if (lastWill != null) {
MqttWillAndTestament lastWill = this.lastWill; // Make eclipse happy
options.setWill(lastWill.getTopic(), lastWill.getPayload(), lastWill.getQos(), lastWill.isRetain());
}
options.setKeepAliveInterval(keepAliveInterval);
return options;
}
/**
* This will establish a connection to the MQTT broker and if successful, notify all
* publishers and subscribers that the connection has become active. This method will
* do nothing if there is already an active connection.
*
* @return Returns a future that completes with true if already connected or connecting,
* completes with false if a connection timeout has happened and completes exceptionally otherwise.
*/
public CompletableFuture<Boolean> start() {
// We don't want multiple concurrent threads to start a connection
synchronized (this) {
if (connectionState() != MqttConnectionState.DISCONNECTED) {
logger.debug("Connection already running");
return CompletableFuture.completedFuture(true);
}
// Perform the connection attempt
isConnecting = true;
connectionObservers.forEach(o -> o.connectionStateChanged(MqttConnectionState.CONNECTING, null));
}
// Ensure the reconnect strategy is started
if (reconnectStrategy != null) {
reconnectStrategy.start();
}
// Close client if there is still one existing
if (client != null) {
try {
client.close();
} catch (org.eclipse.paho.client.mqttv3.MqttException ignore) {
}
client = null;
}
CompletableFuture<Boolean> future = connectionCallback.createFuture();
StringBuilder serverURI = new StringBuilder();
switch (protocol) {
case TCP:
serverURI.append(secure ? "ssl://" : "tcp://");
break;
case WEBSOCKETS:
serverURI.append(secure ? "wss:
break;
default:
future.completeExceptionally(new ConfigurationException("protocol", "Protocol unknown"));
return future;
}
serverURI.append(host);
serverURI.append(":");
serverURI.append(port);
// Storage
Path persistencePath = this.persistencePath;
if (persistencePath == null) {
persistencePath = Paths.get(ConfigConstants.getUserDataFolder()).resolve("mqtt").resolve(host);
}
try {
persistencePath = Files.createDirectories(persistencePath);
} catch (IOException e) {
future.completeExceptionally(new MqttException(e));
return future;
}
MqttDefaultFilePersistence _dataStore = new MqttDefaultFilePersistence(persistencePath.toString());
// Create the client
MqttAsyncClient _client;
try {
_client = createClient(serverURI.toString(), clientId, _dataStore);
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
future.completeExceptionally(new MqttException(e));
return future;
}
// Assign to object
this.client = _client;
this.dataStore = _dataStore;
// Connect
_client.setCallback(clientCallback);
try {
_client.connect(createMqttOptions(), null, connectionCallback);
logger.info("Starting MQTT broker connection to '{}' with clientid {} and file store '{}'", host,
getClientId(), persistencePath);
} catch (org.eclipse.paho.client.mqttv3.MqttException | ConfigurationException e) {
future.completeExceptionally(new MqttException(e));
return future;
}
// Connect timeout
ScheduledExecutorService executor = timeoutExecutor;
if (executor != null) {
final ScheduledFuture<?> timeoutFuture = this.timeoutFuture.getAndSet(executor.schedule(
() -> connectionCallback.onFailure(null, new TimeoutException()), timeout, TimeUnit.MILLISECONDS));
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
}
return future;
}
/**
* Encapsulates the creation of the paho MqttAsyncClient
*
* @param serverURI A paho uri like ssl://host:port, tcp://host:port, ws[s]://host:port
* @param clientId the mqtt client ID
* @param dataStore The datastore to save qos!=0 messages until they are delivered.
* @return Returns a valid MqttAsyncClient
* @throws org.eclipse.paho.client.mqttv3.MqttException
*/
protected MqttAsyncClient createClient(String serverURI, String clientId, MqttClientPersistence dataStore)
throws org.eclipse.paho.client.mqttv3.MqttException {
return new MqttAsyncClient(serverURI, clientId, dataStore);
}
/**
* After a successful disconnect, the underlying library objects need to be closed and connection observers want to
* be notified.
*
* @param v A passthrough boolean value
* @return Returns the value of the parameter v.
*/
protected boolean finalizeStopAfterDisconnect(boolean v) {
if (client != null) {
try {
client.close();
} catch (Exception ignore) {
}
}
client = null;
if (dataStore != null) {
try {
dataStore.close();
} catch (Exception ignore) {
}
dataStore = null;
}
connectionObservers.forEach(o -> o.connectionStateChanged(MqttConnectionState.DISCONNECTED, null));
return v;
}
/**
* Unsubscribe from all topics
*
* @return Returns a future that completes as soon as all subscriptions have been canceled.
*/
public CompletableFuture<Void> unsubscribeAll() {
MqttAsyncClient client = this.client;
List<CompletableFuture<Boolean>> futures = new ArrayList<>();
if (client != null) {
subscribers.forEach((topic, subList) -> {
futures.add(unsubscribeRaw(client, topic));
});
subscribers.clear();
}
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
}
/**
* Unsubscribes from all subscribed topics, stops the reconnect strategy, disconnect and close the client.
*
* You can re-establish a connection calling {@link #start()} again. Do not call start, before the closing process
* has finished completely.
*
* @return Returns a future that completes as soon as the disconnect process has finished.
*/
public CompletableFuture<Boolean> stop() {
MqttAsyncClient client = this.client;
if (client == null) {
return CompletableFuture.completedFuture(true);
}
logger.trace("Closing the MQTT broker connection '{}'", host);
// Abort a connection attempt
isConnecting = false;
// Cancel the timeout future. If stop is called we can safely assume there is no interest in a connection
// anymore.
cancelTimeoutFuture();
// Stop the reconnect strategy
if (reconnectStrategy != null) {
reconnectStrategy.stop();
}
CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
// Close connection
if (client.isConnected()) {
// We need to thread change here. Because paho does not allow to disconnect within a callback method
unsubscribeAll().thenRunAsync(() -> {
try {
client.disconnect(100, future, actionCallback);
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
logger.debug("Error while closing connection to broker", e);
future.complete(false);
}
});
} else {
future.complete(true);
}
return future.thenApply(this::finalizeStopAfterDisconnect);
}
/**
* Publish a message to the broker with the given QoS and retained flag.
*
* @param topic The topic
* @param payload The message payload
* @param qos The quality of service for this message
* @param retain Set to true to retain the message on the broker
* @param listener A listener to be notified of success or failure of the delivery.
*/
public void publish(String topic, byte[] payload, int qos, boolean retain, MqttActionCallback listener) {
MqttAsyncClient client_ = client;
if (client_ == null) {
listener.onFailure(topic, new MqttException(0));
return;
}
try {
IMqttDeliveryToken deliveryToken = client_.publish(topic, payload, qos, retain, listener, actionCallback);
logger.debug("Publishing message {} to topic '{}'", deliveryToken.getMessageId(), topic);
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
listener.onFailure(topic, new MqttException(e));
}
}
/**
* Publish a message to the broker.
*
* @param topic The topic
* @param payload The message payload
* @param listener A listener to be notified of success or failure of the delivery.
*/
public void publish(String topic, byte[] payload, MqttActionCallback listener) {
publish(topic, payload, qos, retain, listener);
}
/**
* Publish a message to the broker.
*
* @param topic The topic
* @param payload The message payload
* @return Returns a future that completes with a result of true if the publishing succeeded and completes
* exceptionally on an error or with a result of false if no broker connection is established.
*/
public CompletableFuture<Boolean> publish(String topic, byte[] payload) {
return publish(topic, payload, qos, retain);
}
/**
* Publish a message to the broker with the given QoS and retained flag.
*
* @param topic The topic
* @param payload The message payload
* @param qos The quality of service for this message
* @param retain Set to true to retain the message on the broker
* @param listener An optional listener to be notified of success or failure of the delivery.
* @return Returns a future that completes with a result of true if the publishing succeeded and completes
* exceptionally on an error or with a result of false if no broker connection is established.
*/
public CompletableFuture<Boolean> publish(String topic, byte[] payload, int qos, boolean retain) {
MqttAsyncClient client = this.client;
if (client == null) {
return CompletableFuture.completedFuture(false);
}
// publish message asynchronously
CompletableFuture<Boolean> f = new CompletableFuture<Boolean>();
try {
client.publish(topic, payload, qos, retain, f, actionCallback);
} catch (org.eclipse.paho.client.mqttv3.MqttException e) {
f.completeExceptionally(new MqttException(e));
}
return f;
}
/**
* The connection process is limited by a timeout, realized with a {@link CompletableFuture}. Cancel that future
* now, if it exists.
*/
protected void cancelTimeoutFuture() {
final ScheduledFuture<?> timeoutFuture = this.timeoutFuture.getAndSet(null);
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
}
}
|
package org.jlib.core.digital;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Digital representation of an object, for instance, a digit of a digital
* clock. A DigitalObject is formed by DigitalElements which may be set active
* or inactive. The set of DigitalElements forming a DigitalObject is only
* restricted by the number of existing instances of the DigitalElement
* interface. Commonly, this class is parameterized by an enumeration type
* defining the DigitalElements forming the DigitalObjects.
*
* @author Igor Akkerman
*/
public abstract class DigitalObject
implements Cloneable {
/** Set of DigitalElements set active in this Digit */
private Set<DigitalElement> activeDigitalElements;
/**
* Creates a new DigitalObject in which no DigitalElements are set active
* initially.
*/
protected DigitalObject() {
super();
activeDigitalElements = new HashSet<DigitalElement>();
}
public boolean isDigitalElementActive(DigitalElement digitalElement)
throws IllegalDigitalElementException {
assertDigitalElementLegal(digitalElement);
return activeDigitalElements.contains(digitalElement);
}
public void setDigitalElementActive(DigitalElement digitalElement, boolean active)
throws IllegalDigitalElementException {
assertDigitalElementLegal(digitalElement);
if (active)
activeDigitalElements.add(digitalElement);
else
activeDigitalElements.remove(digitalElement);
}
/**
* Returns the Collection of the active DigitalElements in this DigitalObject.
*
* @return Set of the active DigitalElements in this DigitalObject; the
* returned Set is an unmodifiable view on the actual Set
*/
public Collection<DigitalElement> getActiveDigitalElements() {
return Collections.unmodifiableSet(activeDigitalElements);
}
public void setActiveDigitalElements(Collection<? extends DigitalElement> activeDigitalElements)
throws IllegalDigitalElementException {
this.activeDigitalElements.clear();
for (DigitalElement activeDigitalElement : activeDigitalElements)
setDigitalElementActive(activeDigitalElement, true);
}
public abstract Collection<? extends DigitalElement> getLegalDigitalElements();
private void assertDigitalElementLegal(DigitalElement digitalElement)
throws IllegalDigitalElementException {
if (!getLegalDigitalElements().contains(digitalElement))
throw new IllegalDigitalElementException(this, digitalElement);
}
// @see java.lang.Object#clone()
@Override
public DigitalObject clone() {
try {
DigitalObject newDigit = (DigitalObject) super.clone();
newDigit.activeDigitalElements = new HashSet<DigitalElement>();
newDigit.setActiveDigitalElements(activeDigitalElements);
return newDigit;
}
catch (CloneNotSupportedException exception) {
// impossible to occur here
throw new RuntimeException(exception);
}
}
// @see java.lang.Object#equals(java.lang.Object)
@Override
public boolean equals(Object otherObject) {
if (!(otherObject instanceof DigitalObject))
return false;
DigitalObject otherDigitalObject = (DigitalObject) otherObject;
return activeDigitalElements.equals(otherDigitalObject.activeDigitalElements);
}
// @see java.lang.Object#hashCode()
@Override
public int hashCode() {
return activeDigitalElements.hashCode();
}
// @see java.lang.Object#toString()
@Override
public String toString() {
return getClass().getSimpleName() + activeDigitalElements;
}
}
|
package net.mcft.copy.core.base;
import java.util.List;
import net.mcft.copy.core.misc.BlockLocation;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraftforge.common.util.ForgeDirection;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public abstract class TileEntityBase extends TileEntity {
private String customName = null;
private boolean brokenInCreative = false;
/** Returns the custom name of the tile entity, usually from being . */
public String getCustomName() { return customName; }
/** Returns if a custom name can be set on this tile entity. */
public boolean canSetCustomName() { return false; }
/** Sets the custom name of this tile entity, if it can be set. */
public void setCustomName(String title) { if (canSetCustomName()) customName = title; }
/** Sends a block event for this tile entity. Will cause receiveClientEvent
* to be called for players tracking the tile entity with those values. */
public void sendEvent(int event, int value) {
worldObj.addBlockEvent(xCoord, yCoord, zCoord, getBlockType(), event, value);
}
/** Returns if the tile entity is valid and in range to be accessed by the player. */
public boolean isUsable(EntityPlayer player) {
return (!player.isDead && !isInvalid() &&
(BlockLocation.get(this).getTileEntity() == this) &&
(player.getDistanceSq(xCoord, yCoord, zCoord) <= 64));
}
// Actions passed from blocks
/** Called when a block is placed by a player. May set data of the
* tile entity from the item stack, like storing the custom name. */
public void onBlockPlaced(EntityLivingBase entity, ItemStack stack,
ForgeDirection side, float hitX, float hitY, float hitZ) {
if (stack.hasDisplayName())
setCustomName(stack.getDisplayName());
}
/** Called then the block is activated (default: right click).
* Returns if an action happened (causes hand to animate) */
public boolean onBlockActivated(EntityPlayer player, ForgeDirection side,
float hitX, float hitY, float hitZ) { return false; }
/** Returns which (default: middle mouse). */
public ItemStack onPickBlock(ItemStack defaultBlock, MovingObjectPosition target) { return defaultBlock; }
/** Called when a block is attempted to be broken by a player.
* Returns if the block should actually be broken. */
public final boolean onBlockBreak(EntityPlayer player) {
brokenInCreative = player.capabilities.isCreativeMode;
return onBlockBreak(player, brokenInCreative);
}
/** Called when a block is attempted to be broken by a player.
* Returns if the block should actually be broken. */
public boolean onBlockBreak(EntityPlayer player, boolean brokenInCreative) {
return true;
}
/** Called after the block is destroyed, drops contents etc. */
public final void onBlockDestroyed() {
onBlockDestroyed(brokenInCreative);
brokenInCreative = false;
}
/** Called after the block is destroyed, drops contents etc. */
public void onBlockDestroyed(boolean brokenInCreative) { }
/** Called when the block drops as an item, allows modification of items dropped. */
public void getBlockDrops(List<ItemStack> drops, int fortune) { }
/** Called before the tile entity is being rendered as an item,
* allows setting values in the tile entity, which is then rendered. */
@SideOnly(Side.CLIENT)
public void onRenderAsItem(ItemStack stack) { }
// Saving, loading and syncing
/** Returns if this tile entity has a "description packet". */
public boolean hasDescriptionPacket() { return false; }
/** Handles writing data to both the save and description packet. */
public void write(NBTTagCompound compound) { }
/** Handles read data from both the save and description packet. */
public void read(NBTTagCompound compound) { }
/** Handles writing data to the save. */
public void writeToSave(NBTTagCompound compound) { }
/** Handles read data from the save. */
public void readFromSave(NBTTagCompound compound) { }
/** Handles writing data to the description packet, to be sent to the client. */
public void writeToDescriptionPacket(NBTTagCompound compound) { }
/** Handles read data from the description packet, sent from the server. */
public void readFromDescriptionPacket(NBTTagCompound compound) { }
@Override
public final void writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
write(compound);
writeToSave(compound);
}
@Override
public final void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
read(compound);
readFromSave(compound);
}
@Override
public final Packet getDescriptionPacket() {
if (!hasDescriptionPacket()) return null;
NBTTagCompound compound = new NBTTagCompound();
write(compound);
writeToDescriptionPacket(compound);
return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 0, compound);
}
@Override
public final void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) {
if (!hasDescriptionPacket()) return;
NBTTagCompound compound = packet.func_148857_g();
read(compound);
readFromDescriptionPacket(compound);
}
}
|
package info.ajaxplorer.client.http;
import info.ajaxplorer.client.model.Node;
import info.ajaxplorer.client.model.Server;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import org.apache.http.cookie.Cookie;
import org.w3c.dom.Document;
public class AjxpAPI {
String SECURE_TOKEN;
String server_url;
String content_php = "?";
Document xml_registry;
private AjxpAPI() {
RestStateHolder stateHolder = RestStateHolder.getInstance();
if(stateHolder.isServerSet()){
this.setServer(stateHolder.getServer());
}
stateHolder.registerStateListener(new RestStateHolder.ServerStateListener() {
public void onServerChange(Server newServer, Server oldServer) {
AjxpAPI.this.setServer(newServer);
}
});
}
private static AjxpAPI instance;
public static AjxpAPI getInstance(){
if(instance == null) instance = new AjxpAPI();
return instance;
}
public static URI returnUriFromString(String url) throws URISyntaxException{
URI uri = null;
try {
uri = new URI(url);
return uri;
} catch (Exception e) {
e.printStackTrace();
}
return uri;
}
private String getAPIUrl() {
String url = server_url.concat(content_php);
return url;
}
public URI getAPIUri() throws URISyntaxException{
return AjxpAPI.returnUriFromString(this.getAPIUrl().concat("&get_action=ping"));
}
/**
* Ping the server to make sure secure token is up-to-date
* Then append secure_token and Cookie value as ajxp_sessid parameter
* @param uri
* @param rest RestRequest to perform ping operation
* @return RESTFul Url that can be used by an external client (no need to cookie)
*/
public String pingAndRestifyUri(URI uri, boolean skipPing, RestRequest rest) throws URISyntaxException{
if(!skipPing && rest != null) {
rest.getStatusCodeForRequest(getAPIUri());
}
String url = uri.toString().concat("&secure_token="+RestStateHolder.getInstance().getSECURE_TOKEN());
Iterator<Cookie> it = AjxpHttpClient.getCookies(uri).iterator();
while(it.hasNext()){
Cookie cook = it.next();
if(cook.getName().equals("AjaXplorer")){
url = url.concat("&ajxp_sessid=" + cook.getValue());
}else{
url = url.concat("&AJXP_COOK_"+cook.getName() + "=" + cook.getValue());
}
}
return url;
}
public void enrichConnexionWithCookies(URLConnection connexion){
try{
URI uri = new URI(connexion.getURL().toString());
List<Cookie> cookies = AjxpHttpClient.getCookies(uri);
String cookieString = "";
for (int i=0;i<cookies.size();i++) {
String cs = "";
if (i>0) {
cs += "; ";
}
cs += cookies.get(i).getName();
cs += "=";
cs += cookies.get(i).getValue();
cookieString+= cs;
}
connexion.setRequestProperty("Cookie", cookieString);
}catch(Exception e){
}
}
private String getGetActionUrl(String action) {
return this.getGetActionUrl(action, true);
}
private String getGetActionUrl(String action, boolean appendRepositoryId) {
if(!appendRepositoryId){
return this.getAPIUrl().concat("get_action=").concat(action)
.concat("&");
}else{
return this.getAPIUrl().concat("get_action=").concat(action)
.concat("&tmp_repository_id="+RestStateHolder.getInstance().getRepository().getPropertyValue("repository_id")+"&");
}
}
public URI getGetActionUri(String action) throws URISyntaxException{
return AjxpAPI.returnUriFromString(this.getGetActionUrl(action));
}
public URI getGetSecureTokenUri() throws URISyntaxException{
return AjxpAPI.returnUriFromString(this.getGetActionUrl("get_boot_conf", false));
}
public URI getGetLoginSeedUri() throws URISyntaxException{
return AjxpAPI.returnUriFromString(this.getGetActionUrl("get_seed", false));
}
public URI makeLoginUri(String userid, String password, String seed) throws URISyntaxException{
String base = this.getGetActionUrl("login", false).concat("userid="+userid+"&password="+password+"&login_seed="+seed);
return AjxpAPI.returnUriFromString(base);
}
public URI getGetXmlRegistryUri() throws URISyntaxException{
return AjxpAPI.returnUriFromString(this.getGetActionUrl("get_xml_registry", false).concat("xPath=user/repositories"));
}
private String getLsRepositoryUrl() throws URISyntaxException{
String ret = getGetActionUrl("ls");
return ret.concat("dir=%2F");
}
public URI getLsRepositoryUri() throws URISyntaxException{
return returnUriFromString(getLsRepositoryUrl());
}
public URI getLsDirectoryUri(Node directory) throws URISyntaxException{
return returnUriFromString(getDirectoryUrl(directory));
}
private String getDirectoryUrl(Node directory) {
if (directory == null)
return "";
String url ="";
String path = directory.getPath();
if(directory.getResourceType().equals(Node.NODE_TYPE_REPOSITORY)){
path = "/";
}
try {
url = getGetActionUrl("ls") + "options=al&dir="
+ java.net.URLEncoder.encode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}
public Document getXmlRegistry() {
return xml_registry;
}
public void setXmlRegistry(Document xmlRegistry) {
xml_registry = xmlRegistry;
}
public URI getSwitchRepositoryUri(String id) throws URISyntaxException{
return returnUriFromString(getSwitchRepositoryUrl(id));
}
private String getSwitchRepositoryUrl(String id) {
return getGetActionUrl("switch_repository", false).concat(
"repository_id=" + id);
}
protected void setServer (Server s) {
if (s!=null) {
this.server_url = s.getUrl();
this.content_php = s.isLegacyServer()?"content.php?":"?";
}
}
public URI getRawContentUri(String file) throws URISyntaxException{
String ret=getGetActionUrl("get_content");
try{
String url = ret+"file="+java.net.URLEncoder.encode(file, "UTF-8");
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getSetRawContentPostUri(String file) throws URISyntaxException{
String ret=getGetActionUrl("put_content");
try{
String url = ret+"file="+java.net.URLEncoder.encode(file, "UTF-8");
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getDeleteUri(String path) throws URISyntaxException{
String url=getGetActionUrl("delete");
try{
url = url.concat("dir="+java.net.URLEncoder.encode(RestStateHolder.getInstance().getDirectory().getPath(), "UTF-8"));
url = url.concat("&file="+java.net.URLEncoder.encode(path, "UTF-8"));
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getUploadUri(String targetFolder) throws URISyntaxException{
String url=getGetActionUrl("upload");
try{
url = url.concat("dir="+java.net.URLEncoder.encode(targetFolder, "UTF-8"));
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getDownloadUri(String file) throws URISyntaxException{
String ret=getGetActionUrl("download");
try{
String url = ret+"file="+java.net.URLEncoder.encode(file, "UTF-8");
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getMediaStreamUri(String file) throws URISyntaxException{
String ret=getGetActionUrl("get_content");
try{
String url = ret+"file="+java.net.URLEncoder.encode(file, "UTF-8");
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getImageDataUri(String file, boolean getThumb, int thumbDimension) throws URISyntaxException{
String ret=getGetActionUrl("preview_data_proxy");
try{
String url = ret+"file="+java.net.URLEncoder.encode(file, "UTF-8");
if(getThumb){
url = url.concat("&get_thumb=true");
if(thumbDimension != -1){
url = url.concat("&dimension="+thumbDimension);
}
}
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getMkdirUri(String file) throws URISyntaxException{
String url=getGetActionUrl("mkdir");
try{
url = url.concat("dir="+java.net.URLEncoder.encode(RestStateHolder.getInstance().getDirectory().getPath(), "UTF-8"));
url = url+"&dirname="+java.net.URLEncoder.encode(file, "UTF-8");
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getMkfileUri(String file) throws URISyntaxException{
String url=getGetActionUrl("mkfile");
try{
url = url.concat("dir="+java.net.URLEncoder.encode(RestStateHolder.getInstance().getDirectory().getPath(), "UTF-8"));
url = url+"&filename="+java.net.URLEncoder.encode(file, "UTF-8");
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getRenameUri(Node targetNode, String newName) throws URISyntaxException{
String url=getGetActionUrl("rename");
try{
url = url.concat("file="+java.net.URLEncoder.encode(targetNode.getPath(), "UTF-8"));
url = url+"&filename_new="+java.net.URLEncoder.encode(newName, "UTF-8");
return returnUriFromString(url);
}catch(UnsupportedEncodingException e){
e.printStackTrace();
return null;
}
}
public URI getMoveUri( Node from, Node to) throws URISyntaxException{
try{
String ret=getGetActionUrl("move");
ret += "file="+java.net.URLEncoder.encode(from.getPath(), "UTF-8");
ret += "&dir="+java.net.URLEncoder.encode(from.getParent().getPath(), "UTF-8");
ret += "&dest_node="+java.net.URLEncoder.encode(to.getPath(), "UTF-8");
ret += "&dest="+java.net.URLEncoder.encode(to.getPath(), "UTF-8");
ret += "&dest_repository_id="+RestStateHolder.getInstance().getRepository().getPropertyValue("repository_id");
return returnUriFromString(ret);
}catch(UnsupportedEncodingException e){
return null;
}
}
}
|
package io.cloudchaser.murmur.types;
import static io.cloudchaser.murmur.types.MurmurType.CHARACTER;
import static io.cloudchaser.murmur.types.MurmurType.DECIMAL;
import static io.cloudchaser.murmur.types.MurmurType.INTEGER;
/**
*
* @author Mihail K
* @since 0.1
**/
public class MurmurCharacter extends MurmurObject {
private final char value;
public MurmurCharacter(int value) {
super(CHARACTER);
this.value = (char)value;
}
public long getValue() {
return value;
}
@Override
public Object toJavaObject() {
return value;
}
@Override
public boolean isCompatible(Class<?> type) {
return type.isAssignableFrom(char.class) ||
type.isAssignableFrom(Character.class);
}
@Override
public Object getAsJavaType(Class<?> type) {
// Java char type.
if(type.isAssignableFrom(char.class) ||
type.isAssignableFrom(Character.class)) {
return value;
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurInteger asInteger() {
return MurmurInteger.create(value);
}
@Override
public MurmurDecimal asDecimal() {
return MurmurDecimal.create(value);
}
@Override
public MurmurString asString() {
return new MurmurString(Character.toString(value));
}
@Override
public MurmurObject opPositive() {
return new MurmurCharacter(+value);
}
@Override
public MurmurObject opNegative() {
return new MurmurCharacter(-value);
}
@Override
public MurmurObject opIncrement() {
return new MurmurCharacter(value + 1);
}
@Override
public MurmurObject opDecrement() {
return new MurmurCharacter(value - 1);
}
@Override
public MurmurObject opPlus(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value + ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opPlus(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opPlus(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opMinus(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value - ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opMinus(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opMinus(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opMultiply(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value * ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opMultiply(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opMultiply(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opDivide(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value / ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opDivide(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opDivide(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opModulo(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value % ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opModulo(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opModulo(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opShiftLeft(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value << ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opShiftLeft(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opShiftRight(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value >> ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opShiftRight(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLessThan(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return MurmurBoolean.create(
value < ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opLessThan(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opLessThan(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opGreaterThan(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return MurmurBoolean.create(
value > ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opGreaterThan(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opGreaterThan(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLessOrEqual(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return MurmurBoolean.create(
value <= ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opLessOrEqual(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opLessOrEqual(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opGreaterOrEqual(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return MurmurBoolean.create(
value >= ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opGreaterOrEqual(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opGreaterOrEqual(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opEquals(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return MurmurBoolean.create(
value == ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opEquals(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opEquals(other);
}
// Not equal.
return MurmurBoolean.FALSE;
}
@Override
public MurmurObject opNotEquals(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return MurmurBoolean.create(
value != ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opNotEquals(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opNotEquals(other);
}
// Not equal.
return MurmurBoolean.TRUE;
}
@Override
public MurmurObject opBitNot() {
return new MurmurCharacter(~value);
}
@Override
public MurmurObject opBitAnd(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value & ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opBitAnd(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opBitAnd(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opBitXor(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value ^ ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opBitXor(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opBitXor(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opBitOr(MurmurObject other) {
// Check for supported operation.
if(other.getType() == CHARACTER) {
return new MurmurCharacter(
value | ((MurmurCharacter)other).value);
} else if(other.getType() == INTEGER) {
return asInteger().opBitOr(other);
} else if(other.getType() == DECIMAL) {
return asDecimal().opBitOr(other);
}
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLogicalNot() {
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLogicalAnd(MurmurObject other) {
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opLogicalOr(MurmurObject other) {
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opIndex(MurmurObject other) {
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public MurmurObject opConcat(MurmurObject other) {
// Unsupported.
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
return Long.hashCode(value);
}
@Override
public boolean equals(Object o) {
if(!(o instanceof MurmurCharacter)) return false;
return ((MurmurCharacter)o).value == value;
}
@Override
public String toString() {
return "MurmurChararcter{value=" + value + '}';
}
}
|
package ch.openech.xml;
import java.io.IOException;
import java.io.Writer;
import java.time.temporal.Temporal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.minimalj.metamodel.model.MjEntity;
import org.minimalj.model.properties.Properties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.repository.sql.EmptyObjects;
import org.minimalj.util.StringUtils;
import org.w3c.dom.Element;
import ch.ech.ech0010.Country;
import ch.openech.xml.write.IndentingXMLStreamWriter;
public class EchWriter implements AutoCloseable {
public static final String XMLSchema_URI = "http:
private final Writer writer;
private XMLStreamWriter xmlStreamWriter;
private XsdModel xsdModel;
public EchWriter(Writer writer) {
this.writer = writer;
XMLOutputFactory factory = XMLOutputFactory.newInstance();
try {
xmlStreamWriter = new IndentingXMLStreamWriter(factory.createXMLStreamWriter(writer));
xmlStreamWriter.writeStartDocument("UTF-8", "1.0");
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
public void writeDocument(Object object) throws XMLStreamException {
Class<?> clazz = object.getClass();
xsdModel = getXsdModel(clazz);
String rootElementName = StringUtils.lowerFirstChar(clazz.getSimpleName());
Element rootElement = xsdModel.getRootElement(rootElementName);
xmlStreamWriter.writeStartElement(xsdModel.getPrefix(), rootElement.getAttribute("name"), xsdModel.getNamespace());
setPrefixs(xsdModel);
writeNamespaces(xsdModel);
writeElementContent(object, rootElement);
xmlStreamWriter.writeEndElement();
}
private XsdModel getXsdModel(Class<?> clazz) {
String packageName = clazz.getPackage().getName();
String namespace = EchSchemas.getNamespaceByPackage(packageName);
XsdModel xsdModel = EchSchemas.getXsdModel(namespace);
if (xsdModel == null) {
throw new IllegalArgumentException(namespace + " for " + packageName + " not found");
}
return xsdModel;
}
private void setPrefixs(XsdModel xsdModel) throws XMLStreamException {
xmlStreamWriter.setPrefix("xsi", XMLSchema_URI);
for (Map.Entry<String, String> entry : xsdModel.getNamespaceByPrefix().entrySet()) {
xmlStreamWriter.setPrefix(entry.getKey(), entry.getValue());
}
}
private void writeNamespaces(XsdModel xsdModel) throws XMLStreamException {
xmlStreamWriter.writeNamespace("xsi", XMLSchema_URI);
for (Map.Entry<String, String> entry : xsdModel.getNamespaceByPrefix().entrySet()) {
xmlStreamWriter.writeNamespace(entry.getKey(), entry.getValue());
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void writeElement(Object object, Element element) {
if (object instanceof Collection) {
((Collection) object).forEach(listItem -> writeElement(listItem, element));
} else if (object != null) {
try {
if (!EmptyObjects.isEmpty(object)) {
String name = element.getAttribute("name");
if (xsdModel.isQualifiedElements()) {
String namespace = element.getOwnerDocument().getDocumentElement().getAttribute("targetNamespace");
xmlStreamWriter.writeStartElement(namespace, name);
} else {
xmlStreamWriter.writeStartElement(name);
}
writeElementContent(object, element);
xmlStreamWriter.writeEndElement();
}
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
}
// Elemente haben entweder einen Type (spezifiziert mit dem Attribute "type).
// Oder sie enthalten selber einen simple oder complex - Type.
private void writeElementContent(Object object, Element element) throws XMLStreamException {
String type = element.getAttribute("type");
if (!StringUtils.isEmpty(type)) {
MjEntity entity = xsdModel.findEntity(type);
if (entity.isPrimitiv() || entity.isEnumeration()) {
if (object.getClass().isEnum() && object.toString().startsWith("_")) {
xmlStreamWriter.writeCharacters(object.toString().substring(1));
} else {
xmlStreamWriter.writeCharacters(object.toString());
}
} else {
Element typeElement = xsdModel.findElement(type);
List<Element> attributes = XsdModel.getList(typeElement, "attribute");
if (attributes != null) {
for (Element attribute : attributes) {
String attributeName = attribute.getAttribute("name");
Object value = Properties.getProperty(object.getClass(), attributeName).getValue(object);
xmlStreamWriter.writeAttribute(attributeName, value.toString());
}
}
writeElements(object, typeElement);
}
}
Element simpleType = XsdModel.get(element, "simpleType");
if (simpleType != null) {
if (object instanceof Country) {
// in der Destination wird AddressInformation statt eine spezielle Klasse
// verwendet. Damit hat country aber die falsche Klasse, das wird hier
// geradegebogen.
xmlStreamWriter.writeCharacters(((Country) object).countryIdISO2);
} else {
xmlStreamWriter.writeCharacters(object.toString());
}
return;
}
Element complexType = XsdModel.get(element, "complexType");
if (complexType != null) {
writeElements(object, complexType);
return;
}
}
private void writeElements(Object object, Element element) {
XsdModel.forEachChild(element, new ElementWriter(object));
}
private class ElementWriter implements Consumer<Element> {
private final Object object;
public ElementWriter(Object object) {
this.object = object;
}
@Override
public void accept(Element element) {
if (element.getLocalName().equals("complexContent")) {
Element extension = XsdModel.get(element, "extension");
if (extension != null) {
String base = extension.getAttribute("base");
Element baseType = xsdModel.findElement(base);
writeElements(object, baseType);
writeElements(object, extension);
}
Element restriction = XsdModel.get(element, "restriction");
if (restriction != null) {
// base is ignored
writeElement(object, restriction);
}
return;
}
if (element.getLocalName().equals("element")) {
String name = element.getAttribute("name");
if (!StringUtils.isEmpty(name)) {
PropertyInterface property = Properties.getProperty(object.getClass(), name);
if (property != null) {
Object value = property.getValue(object);
if (!EmptyObjects.isEmpty(value)) {
writeElement(value, element);
}
} else {
System.out.println("Not found: " + name + " on " + object.getClass().getSimpleName());
}
} else {
// wahrscheinlich ref="extension"
}
return;
}
if (element.getLocalName().equals("choice")) {
XsdModel.forEachChild(element, new ElementWriter(object));
return;
}
if (element.getLocalName().equals("sequence")) {
XsdModel.forEachChild(element, new ElementWriter(object));
return;
}
}
}
@Override
public void close() throws XMLStreamException, IOException {
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.flush();
writer.flush();
}
}
|
/* Package Definition */
package org.keylimebox.mail;
/* Imports */
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.mail.Part;
/* Class Definition / Implementation */
/* CLASS: EmailAttachment */
/**
* A simple wrapper for an email attachment.
* <p>
* @author etiennel
* @since Dec 7, 2014
*/
@SuppressWarnings ("nls")
public class EmailAttachment
{
/* Protected Attributes */
/* Private Attributes */
/* ATTRIBUTE: part */
/**
* The part.
*/
private Part part;
/* ATTRIBUTE: partNumber */
/**
* The part number.
*/
private int partNumber;
/* Class Attributes */
/* Constants */
/* Variables */
/* Static initializer */
/* Constructors */
/* OPERATION: EmailAttachment */
/**
* The constructor for this class.
*
* <p>
* @param aPart
* @param aPartNumber
* <p>
* @since Dec 7, 2014
*/
public EmailAttachment (Part aPart, int aPartNumber)
{
part = aPart;
partNumber = aPartNumber;
}
/* Attribute Get Operations */
/* OPERATION: getPartNumber */
/**
* The part number within the email.
* <p>
* @return
* <p>
* @since Dec 7, 2014
*/
public int getPartNumber ()
{
return (partNumber);
}
/* OPERATION: getFileName */
/**
* The attachment's file name if possible.
* <p>
* @return
* <p>
* @since Dec 7, 2014
*/
public String getFileName ()
{
try {
return ((part.getFileName () == null) ? "No name" : part.getFileName ());
}
catch (Throwable myThrowable) {
return "Error getting filename: " + myThrowable.getMessage ();
}
}
/* OPERATION: getType */
/**
* The attachment's content type.
* <p>
* @return
* <p>
* @since Dec 7, 2014
*/
public String getType ()
{
try {
if (part.getContentType () == null) {
return "blank content type";
}
else {
return part.getContentType ();
}
}
catch (Throwable myThrowable) {
return "Error getting content type: " + myThrowable.getMessage ();
}
}
public boolean isType (String aType)
{
try {
return part.isMimeType (aType);
}
catch (Throwable myThrowable) {
myThrowable.printStackTrace ();
return false;
}
}
/* OPERATION: getDescription */
/**
* The attachment's description (if any).
* <p>
* @return
* <p>
* @since Dec 7, 2014
*/
public String getDescription ()
{
try {
return Utils.nullAsBlank (part.getDescription ());
}
catch (Throwable myThrowable) {
return "Error getting description: " + myThrowable.getMessage ();
}
}
/* OPERATION: getDisposition */
/**
* The attachment's disposition (if any).
* <p>
* @return
* <p>
* @since Dec 7, 2014
*/
public String getDisposition ()
{
try {
return Utils.nullAsBlank (part.getDisposition ());
}
catch (Throwable myThrowable) {
return "Error getting disposition: " + myThrowable.getMessage ();
}
}
/* OPERATION: getAsBytes */
/**
* Returns the attachment itself as a byte array.
* <p>
* @return
* <p>
* @since Dec 8, 2014
*/
public byte[] getAsBytes ()
{
try {
InputStream myInputStream = part.getInputStream ();
ByteArrayOutputStream myOutputStream = new ByteArrayOutputStream ();
int myReads = myInputStream.read ();
while (myReads != -1) {
myOutputStream.write (myReads);
myReads = myInputStream.read ();
}
return myOutputStream.toByteArray ();
}
catch (Throwable myThrowable) {
throw new RuntimeException ("Unable to retrieve the attachment bytes: " + myThrowable.getMessage ());
}
}
/* Attribute Set Operations */
/* Private Operations */
/* Protected Operations */
/* Package Operations */
/* Public Operations */
/* Abstract Operations (definitions) */
/* Abstract Operations (implementations) */
/* Class (static) Operations */
}
// EOF EmailAttachment.java
|
package org.pentaho.di.ui.trans.steps.uniquerowsbyhashset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.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.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.uniquerowsbyhashset.UniqueRowsByHashSetMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class UniqueRowsByHashSetDialog extends BaseStepDialog implements StepDialogInterface
{
private static Class<?> PKG = UniqueRowsByHashSetMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private UniqueRowsByHashSetMeta input;
private Label wlFields;
private TableView wFields;
private FormData fdlFields, fdFields;
private Label wlStoreValues;
private Button wStoreValues;
private FormData fdlStoreValues, fdStoreValues;
private Map<String, Integer> inputFields;
private ColumnInfo[] colinf;
private Label wlRejectDuplicateRow;
private Button wRejectDuplicateRow;
private FormData fdlRejectDuplicateRow, fdRejectDuplicateRow;
private Label wlErrorDesc;
private TextVar wErrorDesc;
private FormData fdlErrorDesc, fdErrorDesc;
private Group wSettings;
private FormData fdSettings;
public UniqueRowsByHashSetDialog(Shell parent, Object in, TransMeta transMeta, String sname)
{
super(parent, (BaseStepMeta)in, transMeta, sname);
input=(UniqueRowsByHashSetMeta)in;
inputFields =new HashMap<String, Integer>();
}
public String open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX);
props.setLook(shell);
setShellImage(shell, input);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.Shell.Title")); //$NON-NLS-1$
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
wlStepname=new Label(shell, SWT.RIGHT);
wlStepname.setText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.Stepname.Label")); //$NON-NLS-1$
props.setLook(wlStepname);
fdlStepname=new FormData();
fdlStepname.left = new FormAttachment(0, 0);
fdlStepname.right= new FormAttachment(middle, -margin);
fdlStepname.top = new FormAttachment(0, margin);
wlStepname.setLayoutData(fdlStepname);
wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wStepname.setText(stepname);
props.setLook(wStepname);
wStepname.addModifyListener(lsMod);
fdStepname=new FormData();
fdStepname.left = new FormAttachment(middle, 0);
fdStepname.top = new FormAttachment(0, margin);
fdStepname.right= new FormAttachment(100, 0);
wStepname.setLayoutData(fdStepname);
// START OF Settings GROUP //
wSettings = new Group(shell, SWT.SHADOW_NONE);
props.setLook(wSettings);
wSettings.setText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.Settings.Label"));
FormLayout SettingsgroupLayout = new FormLayout();
SettingsgroupLayout.marginWidth = 10;
SettingsgroupLayout.marginHeight = 10;
wSettings.setLayout(SettingsgroupLayout);
wlStoreValues=new Label(wSettings, SWT.RIGHT);
wlStoreValues.setText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.StoreValues.Label")); //$NON-NLS-1$
props.setLook(wlStoreValues);
fdlStoreValues=new FormData();
fdlStoreValues.left = new FormAttachment(0, 0);
fdlStoreValues.top = new FormAttachment(wStepname, margin);
fdlStoreValues.right= new FormAttachment(middle, -margin);
wlStoreValues.setLayoutData(fdlStoreValues);
wStoreValues=new Button(wSettings, SWT.CHECK );
props.setLook(wStoreValues);
wStoreValues.setToolTipText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.StoreValues.ToolTip",Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
fdStoreValues=new FormData();
fdStoreValues.left = new FormAttachment(middle, 0);
fdStoreValues.top = new FormAttachment(wStepname, margin);
wStoreValues.setLayoutData(fdStoreValues);
wStoreValues.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
}
}
);
wlRejectDuplicateRow=new Label(wSettings, SWT.RIGHT);
wlRejectDuplicateRow.setText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.RejectDuplicateRow.Label")); //$NON-NLS-1$
props.setLook(wlRejectDuplicateRow);
fdlRejectDuplicateRow=new FormData();
fdlRejectDuplicateRow.left = new FormAttachment(0, 0);
fdlRejectDuplicateRow.top = new FormAttachment(wStoreValues, margin);
fdlRejectDuplicateRow.right= new FormAttachment(middle, -margin);
wlRejectDuplicateRow.setLayoutData(fdlRejectDuplicateRow);
wRejectDuplicateRow=new Button(wSettings, SWT.CHECK );
props.setLook(wRejectDuplicateRow);
wRejectDuplicateRow.setToolTipText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.RejectDuplicateRow.ToolTip",Const.CR)); //$NON-NLS-1$ //$NON-NLS-2$
fdRejectDuplicateRow=new FormData();
fdRejectDuplicateRow.left = new FormAttachment(middle, 0);
fdRejectDuplicateRow.top = new FormAttachment(wStoreValues, margin);
wRejectDuplicateRow.setLayoutData(fdRejectDuplicateRow);
wRejectDuplicateRow.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
input.setChanged();
setErrorDesc();
}
}
);
wlErrorDesc=new Label(wSettings, SWT.LEFT);
wlErrorDesc.setText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.ErrorDescription.Label")); //$NON-NLS-1$
props.setLook(wlErrorDesc);
fdlErrorDesc=new FormData();
fdlErrorDesc.left = new FormAttachment(wRejectDuplicateRow, margin);
fdlErrorDesc.top = new FormAttachment(wStoreValues, margin);
wlErrorDesc.setLayoutData(fdlErrorDesc);
wErrorDesc=new TextVar(transMeta, wSettings, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wErrorDesc);
wErrorDesc.addModifyListener(lsMod);
fdErrorDesc=new FormData();
fdErrorDesc.left = new FormAttachment(wlErrorDesc, margin);
fdErrorDesc.top = new FormAttachment(wStoreValues, margin);
fdErrorDesc.right= new FormAttachment(100, 0);
wErrorDesc.setLayoutData(fdErrorDesc);
fdSettings = new FormData();
fdSettings.left = new FormAttachment(0, margin);
fdSettings.top = new FormAttachment(wStepname, margin);
fdSettings.right = new FormAttachment(100, -margin);
wSettings.setLayoutData(fdSettings);
// / END OF Settings GROUP
// Some buttons
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$
wGet=new Button(shell, SWT.PUSH);
wGet.setText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.Get.Button")); //$NON-NLS-1$
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$
fdOK=new FormData();
setButtonPositions(new Button[] { wOK, wCancel , wGet} , margin, null);
wlFields=new Label(shell, SWT.NONE);
wlFields.setText(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.Fields.Label")); //$NON-NLS-1$
props.setLook(wlFields);
fdlFields=new FormData();
fdlFields.left = new FormAttachment(0, 0);
fdlFields.top = new FormAttachment(wSettings, margin);
wlFields.setLayoutData(fdlFields);
final int FieldsRows=input.getCompareFields()==null?0:input.getCompareFields().length;
colinf=new ColumnInfo[]
{
new ColumnInfo(BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.ColumnInfo.Fieldname"),ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] { "" }, false), //$NON-NLS-1$
};
wFields=new TableView(transMeta, shell,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props
);
fdFields=new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(wlFields, margin);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom = new FormAttachment(wOK, -2*margin);
wFields.setLayoutData(fdFields);
// Search the fields in the background
final Runnable runnable = new Runnable()
{
public void run()
{
StepMeta stepMeta = transMeta.findStep(stepname);
if (stepMeta!=null)
{
try
{
RowMetaInterface row = transMeta.getPrevStepFields(stepMeta);
// Remember these fields...
for (int i=0;i<row.size();i++)
{
inputFields.put(row.getValueMeta(i).getName(), Integer.valueOf(i));
}
setComboBoxes();
}
catch(KettleException e)
{
logError(BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"));
}
}
}
};
new Thread(runnable).start();
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
wCancel.addListener(SWT.Selection, lsCancel);
wGet.addListener(SWT.Selection, lsGet );
wOK.addListener (SWT.Selection, lsOK );
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
// Set the shell size, based upon previous time...
setSize();
getData();
setErrorDesc();
input.setChanged(changed);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return stepname;
}
private void setErrorDesc()
{
wlErrorDesc.setEnabled(wRejectDuplicateRow.getSelection());
wErrorDesc.setEnabled(wRejectDuplicateRow.getSelection());
}
protected void setComboBoxes()
{
// Something was changed in the row.
final Map<String, Integer> fields = new HashMap<String, Integer>();
// Add the currentMeta fields...
fields.putAll(inputFields);
Set<String> keySet = fields.keySet();
List<String> entries = new ArrayList<String>(keySet);
String fieldNames[] = (String[]) entries.toArray(new String[entries.size()]);
Const.sortStrings(fieldNames);
colinf[0].setComboValues(fieldNames);
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
wStoreValues.setSelection(input.getStoreValues());
wRejectDuplicateRow.setSelection(input.isRejectDuplicateRow());
if (input.getErrorDescription()!=null) wErrorDesc.setText(input.getErrorDescription());
for (int i=0;i<input.getCompareFields().length;i++)
{
TableItem item = wFields.table.getItem(i);
if (input.getCompareFields()[i]!=null) item.setText(1, input.getCompareFields()[i]);
}
wFields.setRowNums();
wFields.optWidth(true);
wStepname.selectAll();
}
private void cancel()
{
stepname=null;
input.setChanged(changed);
dispose();
}
private void ok()
{
if (Const.isEmpty(wStepname.getText())) return;
int nrfields = wFields.nrNonEmpty();
input.allocate(nrfields);
for (int i=0;i<nrfields;i++)
{
TableItem item = wFields.getNonEmpty(i);
input.getCompareFields()[i] = item.getText(1);
}
stepname = wStepname.getText(); // return value
input.setStoreValues( wStoreValues.getSelection() );
input.setRejectDuplicateRow(wRejectDuplicateRow.getSelection());
input.setErrorDescription(wErrorDesc.getText());
dispose();
}
private void get()
{
try
{
RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if (r!=null && !r.isEmpty())
{
BaseStepDialog.getFieldsFromPrevious(r, wFields, 1, new int[] { 1 }, new int[] {}, -1, -1, null);
}
}
catch(KettleException ke)
{
new ErrorDialog(shell, BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.FailedToGetFields.DialogTitle"), BaseMessages.getString(PKG, "UniqueRowsByHashSetDialog.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
|
package io.github.secondflight.Parkour.Main;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
public class Parkour extends JavaPlugin implements Listener{
public final Logger logger = Logger.getLogger("Minecraft");
public Parkour plugin;
public static Map<String, Course> courses = new HashMap<String, Course>();
public static Map<Player, Integer> startTime = new HashMap<Player, Integer>();
public static Map<Player, Course> currentCourse = new HashMap<Player, Course>();
public void onEnable() {
plugin = this;
PluginDescriptionFile pdfFile = this.getDescription();
this.logger.info(pdfFile.getName() + " has been Enabled.");
getServer().getPluginManager().registerEvents(this, this);
getConfig().options().copyDefaults(true);
saveConfig();
configToMap();
}
public void onDisable() {
}
@EventHandler
public void clickEvent (PlayerInteractEvent event) {
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Block b = event.getClickedBlock();
Player p = event.getPlayer();
for (String s : courses.keySet()) {
Course course = courses.get(s);
if (!(course.start == null)) {
if (b.equals(course.start)) {
storeTime(p);
currentCourse.put(p, course);
p.sendMessage(ChatColor.GREEN + "Go!");
}
}
if (!(course.end == null)) {
if (b.equals(course.end)) {
if (startTime.containsKey(p)) {
if (currentCourse.get(p).name.equalsIgnoreCase(s)) {
Date d = new Date();
int total = (int) d.getTime() - startTime.get(p);
p.sendMessage(ChatColor.GREEN + "Your time was " + msToString(total, ChatColor.GREEN));
if (getConfig().get("highscores." + event.getPlayer().getUniqueId() + "." + course.name) != null) {
if (getConfig().getInt("highscores." + event.getPlayer().getUniqueId() + "." + course.name) >= total) {
p.sendMessage(ChatColor.GREEN + "You beat your previous best of " + msToString(getConfig().getInt("highscores." + event.getPlayer().getUniqueId() + "." + course.name), ChatColor.GREEN) + ChatColor.GREEN + "!");
getConfig().set("highscores." + event.getPlayer().getUniqueId() + "." + course.name, total);
saveConfig();
} else {
p.sendMessage(ChatColor.RED + "You did not beat your previous best. Your best time on this course is " + msToString(getConfig().getInt("highscores." + event.getPlayer().getUniqueId() + "." + course.name), ChatColor.RED) + ChatColor.RED + ".");
}
} else {
getConfig().set("highscores." + event.getPlayer().getUniqueId() + "." + course.name, total);
saveConfig();
}
} else {
p.sendMessage(ChatColor.RED + "You are no longer in parkour mode.");
}
clearTime(p);
currentCourse.remove(p);
}
}
}
}
}
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(sender instanceof Player) {
Player player = (Player) sender;
if (command.getName().equalsIgnoreCase("parkour") && args.length == 3 && args[0].equalsIgnoreCase("new")) {
boolean error = false;
try {
Integer.parseInt(args[2]);
} catch (Exception ex) {
error = true;
}
if (!error) {
if ((!(getConfig().get("courses") == null) && !(getConfig().getConfigurationSection("courses").getKeys(false).contains(args[1]))) || getConfig().get("courses") == null) {
getConfig().set("courses." + args[1] + ".world", player.getWorld().getName());
getConfig().set("courses." + args[1] + ".points", Integer.parseInt(args[2]));
configToMap();
saveConfig();
player.sendMessage("A new course has been created. Do " + ChatColor.RED + "/parkour edit " + args[1] + ChatColor.WHITE + " to continue.");
} else {
player.sendMessage(ChatColor.RED + "There is already a parkour end sign with that name!");
player.sendMessage("");
player.sendMessage(" If you would like to make a new course with this name, please remove the old one first by using " + ChatColor.RED + "/parkour remove [name] " + ChatColor.WHITE + "or" + ChatColor.RED + " /parkour remove [index]" + ChatColor.WHITE + ". Note: You can also edit an existing parkour course by using " + ChatColor.RED + "/parkour edit [name] " + ChatColor.WHITE + "or" + ChatColor.RED + " /parkour edit [index]" + ChatColor.WHITE + ".");
}
} else {
player.sendMessage(ChatColor.RED + "Invalid arguments - [points] must be a number.");
player.sendMessage("");
player.sendMessage(ChatColor.RED + "Usage: /parkour new [name] [points]");
player.sendMessage("See " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info.");
}
} else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("new") && !(args.length == 3)) {
player.sendMessage(ChatColor.RED + "Usage: /parkour new [name] [points]");
player.sendMessage("See " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info.");
}
if (command.getName().equalsIgnoreCase("parkour") && (args.length == 1 || args.length == 2) && args[0].equalsIgnoreCase("list")) {
if (!(getConfig().get("courses") == null)) {
if (getConfig().getConfigurationSection("courses").getKeys(false).size() > 0) {
player.sendMessage("Here are the active parkour courses:");
player.sendMessage("");
if (args.length == 2 && args[1].equalsIgnoreCase("debug")) {
for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) {
player.sendMessage(ChatColor.YELLOW + "Name: " + ChatColor.WHITE + s);
player.sendMessage("Start X: " + getConfig().get("courses." + s + ".start.x"));
player.sendMessage("Start Y: " + getConfig().get("courses." + s + ".start.y"));
player.sendMessage("Start Z: " + getConfig().get("courses." + s + ".start.z"));
player.sendMessage("End X: " + getConfig().get("courses." + s + ".end.x"));
player.sendMessage("End Y: " + getConfig().get("courses." + s + ".end.y"));
player.sendMessage("End Z: " + getConfig().get("courses." + s + ".end.z"));
player.sendMessage("World: " + getConfig().get("courses." + s + ".world"));
player.sendMessage("Point value: " + getConfig().get("courses." + s + ".points"));
if (Bukkit.getServer().getWorld(getConfig().getString("courses." + s + ".world")).getBlockAt(getConfig().getInt("courses." + s + ".start.x"), getConfig().getInt("courses." + s + ".start.y"), getConfig().getInt("courses." + s + ".start.z")).getType() == Material.AIR) {
player.sendMessage(ChatColor.RED + "WARNING: There is no block at the start location, making it inaccessable.");
player.sendMessage("This can be fixed by placing a block, such as a sign, at the location. You can teleport to this location by using " + ChatColor.RED + "/parkour tp " + s + ChatColor.WHITE + ".");
}
if (Bukkit.getServer().getWorld(getConfig().getString("courses." + s + ".world")).getBlockAt(getConfig().getInt("courses." + s + ".end.x"), getConfig().getInt("courses." + s + ".end.y"), getConfig().getInt("courses." + s + ".end.z")).getType() == Material.AIR) {
player.sendMessage(ChatColor.RED + "WARNING: There is no block at the end location, making it inaccessable.");
player.sendMessage("This can be fixed by placing a block, such as a sign, at the location. You can teleport to this location by using " + ChatColor.RED + "/parkour tp " + s + ChatColor.WHITE + ".");
}
player.sendMessage("");
}
} else if (args.length == 1) {
for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) {
player.sendMessage(s);
}
}
}else {
player.sendMessage("There are no parkour end points in the config right now.");
player.sendMessage("See " + ChatColor.RED + "/parkour new" + ChatColor.WHITE + " to add one.");
}
} else {
player.sendMessage("There are no parkour end points in the config right now.");
player.sendMessage("See " + ChatColor.RED + "/parkour new" + ChatColor.WHITE + " to add one.");
}
} else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("list") && !(args.length == 1)) {
player.sendMessage(ChatColor.RED + "Usage: /parkour list");
player.sendMessage("Use " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info.");
}
if (command.getName().equalsIgnoreCase("parkour") && args.length == 2 && args[0].equalsIgnoreCase("tp")) {
if (!(getConfig().get("courses") == null)) {
if (getConfig().getConfigurationSection("courses").getKeys(false).size() > 0) {
boolean error = true;
for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) {
if (s.equals(args[1])) {
error = false;
break;
}
}
if (!error) {
if (startTime.containsKey(player)) {
clearTime(player);
currentCourse.remove(player);
player.sendMessage(ChatColor.RED + "You are no longer in parkour mode.");
}
player.teleport (new Location(Bukkit.getServer().getWorld(getConfig().getString("courses." + args[1] + ".world")), (double) getConfig().getInt("courses." + args[1] + ".start.x") + 0.5, (double) getConfig().getInt("courses." + args[1] + ".start.y"), (double) getConfig().getInt("courses." + args[1] + ".start.z") + 0.5));
} else {
player.sendMessage(ChatColor.RED + "Invalid course name.");
player.sendMessage("You can use " + ChatColor.RED + "/parkour list" + ChatColor.WHITE + " to get all the active courses and their names.");
}
} else {
player.sendMessage(ChatColor.RED + "There are no active parkour courses to teleport to.");
player.sendMessage("You can use " + ChatColor.RED + "/parkour new [name] [point value]" + ChatColor.WHITE + " to make a new one.");
}
} else {
player.sendMessage(ChatColor.RED + "There are no active parkour courses to teleport to.");
player.sendMessage("You can use " + ChatColor.RED + "/parkour new [name] [point value]" + ChatColor.WHITE + " to make a new one.");
}
} else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("tp") && !(args.length == 2)) {
player.sendMessage(ChatColor.RED + "Usage: /parkour tp [course name]");
player.sendMessage("You can use " + ChatColor.RED + "/parkour list" + ChatColor.WHITE + " to get all the active courses and their names.");
player.sendMessage("Use " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info.");
}
if (command.getName().equalsIgnoreCase("parkour") && args.length == 2 && args[0].equalsIgnoreCase("remove")) {
if (!(getConfig().get("courses") == null)) {
if (getConfig().getConfigurationSection("courses").getKeys(false).size() > 0) {
boolean error = true;
for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) {
if (s.equals(args[1])) {
error = false;
break;
}
}
if (!error) {
getConfig().getConfigurationSection("courses").set(args[1], null);
courses.remove(args[1]);
saveConfig();
player.sendMessage("Course '" + args[1] + "' has successfully been removed.");
} else {
player.sendMessage(ChatColor.RED + "Invalid course name.");
player.sendMessage("You can use " + ChatColor.RED + "/parkour list" + ChatColor.WHITE + " to get all the active courses and their names.");
}
} else {
player.sendMessage(ChatColor.RED + "There are no active parkour courses to remove.");
}
} else {
player.sendMessage(ChatColor.RED + "There are no active parkour courses to remove.");
}
} else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("remove") && !(args.length == 2)) {
player.sendMessage(ChatColor.RED + "Usage: /parkour remove [course name]");
player.sendMessage("Use " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info.");
}
if (command.getName().equalsIgnoreCase("parkour") && args.length > 2 && args[0].equalsIgnoreCase("edit")) {
if (!(getConfig().get("courses") == null)) {
if (getConfig().getConfigurationSection("courses").getKeys(false).size() > 0) {
boolean error = true;
for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) {
if (s.equals(args[1])) {
error = false;
break;
}
}
if (!error) {
if (args[2].equalsIgnoreCase("setstart")) {
getConfig().set("courses." + args[1] + ".start.x", player.getLocation().getBlockX());
getConfig().set("courses." + args[1] + ".start.y", player.getLocation().getBlockY());
getConfig().set("courses." + args[1] + ".start.z", player.getLocation().getBlockZ());
configToMap();
saveConfig();
player.sendMessage(ChatColor.GREEN + "The start point for '" + args[1] + "' has been set to your current location.");
} else if (args[2].equalsIgnoreCase("setend")) {
getConfig().set("courses." + args[1] + ".end.x", player.getLocation().getBlockX());
getConfig().set("courses." + args[1] + ".end.y", player.getLocation().getBlockY());
getConfig().set("courses." + args[1] + ".end.z", player.getLocation().getBlockZ());
configToMap();
saveConfig();
player.sendMessage(ChatColor.GREEN + "The end point for '" + args[1] + "' has been set to your current location.");
} else if (args.length == 4 && args[2].equalsIgnoreCase("setname")) {
getConfig().set("courses." + args[1] + ".end.x", args[3]);
}
} else {
player.sendMessage(ChatColor.RED + "Invalid course name.");
player.sendMessage("You can use " + ChatColor.RED + "/parkour list" + ChatColor.WHITE + " to get all the active courses and their names.");
}
} else {
player.sendMessage(ChatColor.RED + "There are no active parkour courses to edit.");
}
} else {
player.sendMessage(ChatColor.RED + "There are no active parkour courses to edit.");
}
} else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("edit") && !(args.length > 2)) {
//TODO: usage
player.sendMessage(ChatColor.RED + "Usage: /parkour edit [course name] [action]");
player.sendMessage("Use " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info.");
}
if (command.getName().equalsIgnoreCase("parkour") && args.length == 1 && args[0].equalsIgnoreCase("help")) {
player.sendMessage("Use " + ChatColor.RED + "/parkour help [command]" + ChatColor.WHITE + " to get detailed help for a sepcific command.");
player.sendMessage("");
player.sendMessage("/parkour new [name] [point value]");
player.sendMessage(" Creates a new parkour course with the given name and point value.");
player.sendMessage("");
player.sendMessage("/parkour edit [name] setstart");
player.sendMessage(" Sets the start location for the given parkour course to whatever block your feet are at.");
player.sendMessage("");
player.sendMessage("/parkour edit [name] setend");
player.sendMessage(" Sets the end location for the given parkour course to whatever block your feet are at.");
player.sendMessage("");
player.sendMessage("/parkour edit [name] setname [new name]");
player.sendMessage(" Sets the name of the given parkour course to the given new name.");
player.sendMessage(" " + ChatColor.RED + ChatColor.BOLD + "WARNING! This will break player high scores for this course! Tread with caution.");
player.sendMessage("");
player.sendMessage("/parkour remove [name]");
player.sendMessage(" Removes the given parkour course.");
player.sendMessage(" " + ChatColor.YELLOW + ChatColor.ITALIC + "Note: This does not remove player high scores for the given course name.");
player.sendMessage("");
player.sendMessage("/parkour tp [name]");
player.sendMessage(" Teleports you to the given course's start.");
player.sendMessage("");
player.sendMessage("/parkour list");
player.sendMessage(" Lists the registered parkour courses, along with some useful info about each one.");
player.sendMessage(" " + ChatColor.ITALIC + "Note: You can add the 'debug' argument at the end of the command to have it display extra information.");
}
if (command.getName().equalsIgnoreCase("test")) {
// test goes here lel
}
}
return false;
}
public void configToMap () {
if (!(getConfig().get("courses") == null)) {
for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) {
Course course = new Course (s, getConfig().getInt("courses." + s + ".points"));
if (!(getConfig().get("courses." + s + ".start.x") == null)) {
course.start = Bukkit.getServer().getWorld(getConfig().getString("courses." + s + ".world")).getBlockAt(getConfig().getInt("courses." + s + ".start.x"), getConfig().getInt("courses." + s + ".start.y"), getConfig().getInt("courses." + s + ".start.z"));
}
if (!(getConfig().get("courses." + s + ".end.x") == null)) {
course.end = Bukkit.getServer().getWorld(getConfig().getString("courses." + s + ".world")).getBlockAt(getConfig().getInt("courses." + s + ".end.x"), getConfig().getInt("courses." + s + ".end.y"), getConfig().getInt("courses." + s + ".end.z"));
}
courses.put(course.name, course);
}
}
}
public void storeTime (Player player) {
startTime.put(player, (int) new Date().getTime());
}
public void clearTime (Player player) {
startTime.remove(player);
}
public String msToString (int total, ChatColor color) {
int hours = (int) Math.floor(total / 3600000);
int minutes = (int) Math.floor((total - (hours * 3600000)) / 60000);
int seconds = (int) Math.floor((total - (hours * 3600000) - (minutes * 60000)) / 1000);
int ms = (int) Math.floor((total - (hours * 3600000) - (minutes * 60000) - (seconds * 1000)));
String gc = color + ":" + ChatColor.WHITE;
String time;
if (!(hours == 0)) {
time = (ChatColor.WHITE + Integer.toString(hours) + gc + String.format("%02d", minutes) + gc + String.format("%02d", seconds) + gc + String.format("%03d", ms));
} else {
time = (ChatColor.WHITE + String.format("%02d", minutes) + gc + String.format("%02d", seconds) + gc + String.format("%03d", ms));
}
return time;
}
}
|
package com.akm.http;
import com.akm.http.exception.HttpServiceException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTP request service.
*
* @author Amir
* @since 0.1
*/
public final class HttpService {
private static final Logger LOGGER = LoggerFactory
.getLogger(HttpService.class);
/**
* Performs an HTTP GET request to the given url using the specified headers and parameters. If
* the request is successful an {@link HttpResponse} is returned.
*
* @param url the url to send the request
* @param headers the map of headers to set
* @param parameters the map of parameters to set
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
public HttpResponse get(final String url, final Map<String, String> headers,
final Map<String, String> parameters) throws HttpServiceException {
return doRequest(HttpGetCallable.class, url, headers, parameters, null);
}
/**
* Performs an HTTP DELETE request to the given url using the specified headers and parameters. If
* the request is successful an {@link HttpResponse} is returned.
*
* @param url the url to send the request
* @param headers the map of headers to set
* @param parameters the map of parameters to set
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
public HttpResponse delete(final String url,
final Map<String, String> headers,
final Map<String, String> parameters) throws HttpServiceException {
return doRequest(HttpDeleteCallable.class, url, headers, parameters, null);
}
/**
* Performs an HTTP HEAD request to the given url using the specified headers and parameters. If
* the request is successful an {@link HttpResponse} is returned.
*
* @param url the url to send the request
* @param headers the map of headers to set
* @param parameters the map of parameters to set
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
public HttpResponse head(final String url,
final Map<String, String> headers,
final Map<String, String> parameters) throws HttpServiceException {
return doRequest(HttpHeadCallable.class, url, headers, parameters, null);
}
/**
* Performs an HTTP OPTIONS request to the given url using the specified headers and parameters.
* If the request is successful an {@link HttpResponse} is returned.
*
* @param url the url to send the request
* @param headers the map of headers to set
* @param parameters the map of parameters to set
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
public HttpResponse options(final String url,
final Map<String, String> headers,
final Map<String, String> parameters) throws HttpServiceException {
return doRequest(HttpOptionsCallable.class, url, headers, parameters, null);
}
/**
* Performs an HTTP TRACE request to the given url using the specified headers and parameters. If
* the request is successful an {@link HttpResponse} is returned.
*
* @param url the url to send the request
* @param headers the map of headers to set
* @param parameters the map of parameters to set
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
public HttpResponse trace(final String url,
final Map<String, String> headers,
final Map<String, String> parameters) throws HttpServiceException {
return doRequest(HttpTraceCallable.class, url, headers, parameters, null);
}
/**
* Performs an HTTP POST request to the given url using the specified headers, parameters, and body.
* If the request is successful an {@link HttpResponse} is returned.
*
* @param url the url to send the request
* @param headers the map of headers for the request
* @param parameters the map of parameters to send
* @param body the request body, as a string
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
public HttpResponse post(final String url,
final Map<String, String> headers,
final Map<String, String> parameters, final String body) throws HttpServiceException {
return doRequest(HttpPostCallable.class, url, headers, parameters, body);
}
/**
* Performs an HTTP PUT request to the given url using the specified headers, parameters, and body.
* If the request is successful an {@link HttpResponse} is returned.
*
* @param url the url to send the request
* @param headers the map of headers for the request
* @param parameters the map of parameters to send
* @param body the request body, as a string
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
public HttpResponse put(final String url, final Map<String, String> headers,
final Map<String, String> parameters, final String body) throws HttpServiceException {
return doRequest(HttpPutCallable.class, url, headers, parameters, body);
}
/**
* Performs an HTTP PATCH request to the given url using the specified headers, parameters, and body.
* If the request is successful an {@link HttpResponse} is returned.
*
* @param url the url to send the request
* @param headers the map of headers for the request
* @param parameters the map of parameters to send
* @param body the request body, as a string
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
public HttpResponse patch(final String url,
final Map<String, String> headers,
final Map<String, String> parameters, final String body) throws HttpServiceException {
return doRequest(HttpPatchCallable.class, url, headers, parameters, body);
}
/**
* Executes the given {@link AbstractHttpCallable} class using reflection.
*
* @param clazz the class of the AbstractHttpCallable implementation
* @param url the url to send the request
* @param headers the map of headers for the request
* @param parameters the map of parameters to send
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
private <T extends AbstractHttpCallable> HttpResponse doRequest(
final Class<T> clazz, final String url,
final Map<String, String> headers,
final Map<String, String> parameters, final String body) throws HttpServiceException {
final T callable = getHttpCallable(clazz, url, headers, parameters, body);
return execute(callable);
}
/**
* Creates and submits a new {@link AbstractHttpCallable}, returning the result.
*
* @param callable the AbstractHttpCallable to execute
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while executing the request
*/
private HttpResponse execute(final AbstractHttpCallable callable)
throws HttpServiceException {
final ExecutorService executor = Executors.newSingleThreadExecutor();
final Future<HttpResponse> future = executor.submit(callable);
executor.shutdown();
HttpResponse resp;
try {
resp = future.get();
} catch (InterruptedException | ExecutionException e) {
final StringBuilder sb = new StringBuilder(
"unable to execute http request");
final Throwable t = e.getCause();
if (t != null) {
sb.append(" with cause ").append(t);
}
LOGGER.error(sb.toString(), e);
throw new HttpServiceException(sb.toString(), e);
}
return resp;
}
/**
* Uses reflection to instantiate the appropriate {@link AbstractHttpCallable} using the given
* class and constructor arguments.
*
* @param clazz the class of the AbstractHttpCallable implementation
* @param url the url to send the request
* @param headers the map of headers for the request
* @param parameters the map of parameters to send
*
* @return the HttpResponse
*
* @throws HttpServiceException if any errors occur while instantiating the class
*/
private <T extends AbstractHttpCallable> T getHttpCallable(
final Class<T> clazz, final String url,
final Map<String, String> headers,
final Map<String, String> parameters, final String body) throws HttpServiceException {
try {
if (body == null) {
final Constructor<T> constructor = clazz
.getConstructor(String.class, Map.class, Map.class);
return constructor.newInstance(url, headers, parameters);
} else {
final Constructor<T> constructor = clazz
.getConstructor(String.class, Map.class, Map.class, String.class);
return constructor.newInstance(url, headers, parameters, body);
}
} catch (NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
throw new HttpServiceException(String.format(
"unable to instantiate class %s with error %s",
clazz.getName(), e), e);
}
}
}
|
package org.kohsuke.github;
import java.io.IOException;
/**
* Builder pattern for creating a {@link GHRelease}
*
* @see GHRepository#createRelease(String)
*/
public class GHReleaseBuilder {
private final GHRepository repo;
private final Requester builder;
public GHReleaseBuilder(GHRepository ghRepository, String tag) {
this.repo = ghRepository;
this.builder = new Requester(repo.root);
builder.with("tag_name", tag);
}
/**
* @param body The release notes body.
*/
public GHReleaseBuilder body(String body) {
builder.with("body", body);
return this;
}
public GHReleaseBuilder commitish(String commitish) {
builder.with("target_commitish", commitish);
return this;
}
/**
* Optional.
*
* @param draft {@code true} to create a draft (unpublished) release, {@code false} to create a published one.
* Default is {@code false}.
*/
public GHReleaseBuilder draft(boolean draft) {
builder.with("draft", draft);
return this;
}
/**
* @param name the name of the release
*/
public GHReleaseBuilder name(String name) {
builder.with("name", name);
return this;
}
/**
* Optional
*
* @param prerelease {@code true} to identify the release as a prerelease. {@code false} to identify the release
* as a full release. Default is {@code false}.
*/
public GHReleaseBuilder prerelease(boolean prerelease) {
builder.with("prerelease", prerelease);
return this;
}
public GHRelease create() throws IOException {
return builder.to(repo.getApiTailUrl("releases"), GHRelease.class).wrap(repo);
}
}
|
package edu.wpi.first.wpilib.plugins.core.installer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JOptionPane;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.omg.CORBA.Environment;
import edu.wpi.first.wpilib.plugins.core.WPILibCore;
public abstract class AbstractInstaller {
protected File installLocation;
protected String version;
public AbstractInstaller(String version) {
this.installLocation = new File(WPILibCore.getDefault().getWPILibBaseDir()
+ File.separator + getFeatureName() + File.separator + version);
this.version = version;
}
/**
* @return The name of the feature being installed.
*/
protected abstract String getFeatureName();
/**
* Update the installed version to the latest version.
* @param version The latest version installed.
*/
protected abstract void updateInstalledVersion(String version);
/**
* @return The input stream to the zip file being installed.
*/
protected abstract InputStream getInstallResourceStream();
public void installIfNecessary() {
System.out.println("Installing "+getFeatureName()+" if necessary");
try {
System.out.println("Install Location: "
+ installLocation.getCanonicalPath());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!isInstalled()) {
System.out.println("Install necessary");
try {
install();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
updateInstalledVersion(version);
System.out.println("Installed");
}
/**
* This function has been updated to guarantee that the wpilib folder date
* is older than the jar file being run, which ensures up to date tools.
*
* @return True for is there and newer, false otherwise.
*/
public boolean isInstalled() {
if(installLocation.exists())
{
File coreJar = new File(AbstractInstaller.class.getProtectionDomain()
.getCodeSource().getLocation().getPath());
if(installLocation.lastModified() <= coreJar.lastModified())
{
return false;
}
else return true;
}
else return false;
}
/**
* This function will delete an old wpilib subfolder if necessary and then copy
* the resource stream to the intended directory.
*
* @throws IOException if bad things happen ...
*/
public void install() throws IOException {
if(installLocation.exists()) {
if(!removeFileHandler(installLocation, true)) {
JOptionPane.showMessageDialog(null,
String.format("Could not update the old wpilib folder.%n"
+ "Please close any WPILib tools and restart Eclipse."));
}
else
removeFileHandler(installLocation, false);
}
installLocation.mkdirs();
final String osName = System.getProperty("os.name");
if (osName.startsWith("Mac OS X") || osName.startsWith("Linux")) { // Unix-like OSes must preserve the executable bit; call unzip
InputStream zip = getInstallResourceStream();
File tmpFile = File.createTempFile(getFeatureName()+"-", ".zip");
FileOutputStream fout = new FileOutputStream(tmpFile);
copyStreams(zip, fout);
zip.close();
fout.close();
String[] cmd = {"unzip", tmpFile.getAbsolutePath(), "-d", installLocation.getAbsolutePath()};
System.out.println("unzip "+tmpFile.getAbsolutePath()+" -d "+installLocation.getAbsolutePath());
try {
InputStream is = DebugPlugin.exec(cmd, installLocation).getInputStream();
copyStreams(is, System.out);
} catch (CoreException e) {
e.printStackTrace();
}
} else {
ZipInputStream zip = new ZipInputStream(getInstallResourceStream());
ZipEntry entry = zip.getNextEntry();
while (entry != null) {
System.out.println("\tZipEntry " + entry + ": " + entry.getSize());
File f = new File(installLocation, entry.getName());
if (entry.isDirectory()) {
f.mkdirs();
} else {
FileOutputStream fo = new FileOutputStream(f);
copyStreams(zip, fo);
fo.close();
}
zip.closeEntry();
entry = zip.getNextEntry();
}
zip.close();
}
}
private static void copyStreams(InputStream source, OutputStream destination) throws IOException {
byte[] buffer = new byte[1024];
int len;
while((len = source.read(buffer)) >= 0){
destination.write(buffer,0,len);
}
}
/**
* Recursively remove all of the files and folders described by this file handler.
*
* @param file The file to remove
* @param testRun True to just test if the files can be deleted
* @return True if this and all subFiles were removed, false otherwise.
*/
private static boolean removeFileHandler(File file, boolean testRun) {
// if normal files (data files and the like)
if(file.isFile()) {
if(testRun) return file.getParentFile().canWrite();
else return file.delete();
}
// if folders
else if(file.isDirectory()) {
for(File f : file.listFiles()) {
if(!removeFileHandler(f, testRun))
return false;
}
if(testRun) return file.getParentFile().canWrite();
else return file.delete();
}
// I'm not sure what to do if the file is not normal or a directory ...
else return false;
}
}
|
package net.sf.mzmine.taskcontrol;
import java.util.logging.Logger;
public class TaskSequence implements TaskListener, Runnable {
public enum TaskSequenceStatus {
WAITING, RUNNING, ERROR, CANCELED, FINISHED
};
private Logger logger = Logger.getLogger(this.getClass().getName());
private Task tasks[];
private TaskListener taskListener;
private TaskSequenceListener sequenceListener;
private TaskController taskController;
private int finishedTasks = 0;
private TaskSequenceStatus status = TaskSequenceStatus.WAITING;
/**
* @param tasks
* @param taskController
*/
public TaskSequence(Task[] tasks, TaskListener taskListener,
TaskController taskController) {
this(tasks, taskListener, null, taskController);
}
/**
* @param tasks
* @param taskController
*/
public TaskSequence(Task[] tasks, TaskListener taskListener,
TaskSequenceListener sequenceListener, TaskController taskController) {
this.tasks = tasks;
this.taskListener = taskListener;
this.sequenceListener = sequenceListener;
this.taskController = taskController;
}
public TaskSequenceStatus getStatus() {
return status;
}
public void taskStarted(Task task) {
if (taskListener != null)
taskListener.taskStarted(task);
}
public synchronized void taskFinished(Task task) {
if (taskListener != null)
taskListener.taskFinished(task);
if (task.getStatus() == Task.TaskStatus.ERROR) {
status = TaskSequenceStatus.ERROR;
} else if (task.getStatus() == Task.TaskStatus.CANCELED) {
status = TaskSequenceStatus.CANCELED;
}
finishedTasks++;
if (finishedTasks == tasks.length) {
if (status == TaskSequenceStatus.RUNNING)
status = TaskSequenceStatus.FINISHED;
if (sequenceListener != null)
sequenceListener.taskSequenceFinished(this);
}
logger.finest("Task sequence: finished " + finishedTasks + "/" + tasks.length + " tasks, status " + status);
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
logger.finest("Starting " + tasks.length + " task sequence");
status = TaskSequenceStatus.RUNNING;
for (Task t : tasks) {
taskController.addTask(t, this);
}
}
public String toString() {
return "Task sequence: " + tasks;
}
}
|
package io.flutter.actions;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.util.Computable;
import com.jetbrains.lang.dart.ide.runner.ObservatoryConnector;
import io.flutter.run.daemon.FlutterApp;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
abstract public class FlutterAppAction extends DumbAwareAction {
private static final Logger LOG = Logger.getInstance(FlutterAppAction.class);
private final ObservatoryConnector myConnector;
private final Computable<Boolean> myIsApplicable;
private FlutterApp.State myAppState;
private final FlutterApp.StateListener myListener = new FlutterApp.StateListener() {
@Override
public void stateChanged(FlutterApp.State newState) {
myAppState = newState;
getTemplatePresentation().setEnabled(myIsApplicable.compute() && isRunning());
}
};
private boolean myIsListening = false;
public FlutterAppAction(ObservatoryConnector connector, String text, String description, Icon icon, Computable<Boolean> isApplicable, @NotNull String actionId) {
super(text, description, icon);
myConnector = connector;
myIsApplicable = isApplicable;
registerAction(actionId);
}
private void registerAction(@NotNull String actionId) {
final ActionManager actionManager = ActionManager.getInstance();
final AnAction action = actionManager.getAction(actionId);
// New debug sessions create new actions, requiring us to overwrite existing ones in the registry.
// TODO(pq): consider moving actions to our own registry for lookup.
if (action != null) {
actionManager.unregisterAction(actionId);
}
actionManager.registerAction(actionId, this);
}
@Override
public void update(@NotNull final AnActionEvent e) {
final boolean isConnected = myIsApplicable.compute();
e.getPresentation().setEnabled(isConnected && isRunning());
if (isConnected) {
if (!myIsListening) {
getApp().addStateListener(myListener);
myIsListening = true;
}
}
else {
if (myIsListening) {
getApp().removeStateListener(myListener);
myIsListening = false;
}
}
}
FlutterApp getApp() {
return myConnector.getApp();
}
void ifReadyThen(Runnable x) {
if (myConnector.isConnectionReady() && isRunning()) {
x.run();
}
}
private boolean isRunning() {
return myAppState == FlutterApp.State.STARTED;
}
}
|
package org.xins.types.standard;
import org.xins.types.Type;
import org.xins.types.TypeValueException;
import org.xins.util.BooleanConstants;
import org.xins.util.MandatoryArgumentChecker;
/**
* Standard type <em>_boolean</em>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>)
*/
public final class Boolean extends Type {
// Class fields
/**
* The only instance of this class. This field is never <code>null</code>.
*/
public final static Boolean SINGLETON = new Boolean();
// Class functions
public static boolean fromStringForRequired(String string)
throws IllegalArgumentException, TypeValueException {
if ("true".equals(string)) {
return true;
} else if ("false".equals(string)) {
return false;
} else if (string == null) {
throw new IllegalArgumentException("string == null");
} else {
throw new TypeValueException(SINGLETON, string);
}
}
/**
* Converts the specified string value to a <code>java.lang.Boolean</code>
* value.
*
* @param string
* the string to convert, can be <code>null</code>.
*
* @return
* the {@link java.lang.Boolean}, or <code>null</code> if
* <code>string == null</code>.
*
* @throws TypeValueException
* if the specified string does not represent a valid value for this
* type.
*/
public static java.lang.Boolean fromStringForOptional(String string)
throws TypeValueException {
if ("true".equals(string)) {
return BooleanConstants.TRUE;
} else if ("false".equals(string)) {
return BooleanConstants.FALSE;
} else if (string == null) {
return null;
} else {
throw new TypeValueException(SINGLETON, string);
}
}
/**
* Converts the specified <code>Boolean</code> to a string.
*
* @param value
* the value to convert, can be <code>null</code>.
*
* @return
* the textual representation of the value, or <code>null</code> if and
* only if <code>value == null</code>.
*/
public static String toString(java.lang.Boolean value) {
if (value == null) {
return null;
} else {
return toString(value.booleanValue());
}
}
/**
* Converts the specified <code>boolean</code> to a string.
*
* @param value
* the value to convert.
*
* @return
* the textual representation of the value, never <code>null</code>.
*/
public static String toString(boolean value) {
return value ? "true" : "false";
}
// Constructors
/**
* Constructs a new <code>Boolean</code>.
* This constructor is private, the field {@link #SINGLETON} should be
* used.
*/
private Boolean() {
super("boolean", java.lang.Boolean.class);
}
// Fields
// Methods
protected boolean isValidValueImpl(String value) {
return "true".equals(value) || "false".equals(value);
}
protected Object fromStringImpl(String string) {
return "true".equals(string) ? BooleanConstants.TRUE : BooleanConstants.FALSE;
}
public final String toString(Object value)
throws IllegalArgumentException, ClassCastException, TypeValueException {
MandatoryArgumentChecker.check("value", value);
java.lang.Boolean b = (java.lang.Boolean) value;
return b.booleanValue() ? "true" : "false";
}
}
|
package com.codeski.nbt.tags;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
public abstract class NBT<T> {
/**
* The <code>Charset</code> to use for reading a <code>String</code> from an NBT file.
*/
public static final Charset CHARSET = Charset.forName("UTF-8");
/**
* Constants representing the types defined by the NBT specification.
*/
public static final int END = 0, BYTE = 1, SHORT = 2, INTEGER = 3, LONG = 4, FLOAT = 5, DOUBLE = 6, BYTE_ARRAY = 7, STRING = 8, LIST = 9, COMPOUND = 10, INTEGER_ARRAY = 11;
/**
* The name of this named binary tag.
*/
protected String name;
/**
* The payload of this named binary tag.
*/
protected T payload;
protected NBT(String name, T payload) {
this.name = name;
this.payload = payload;
}
/**
* Compares this object to the specified object.
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof NBT<?>))
return false;
NBT<?> that = (NBT<?>) obj;
return this.getName() == null && that.getName() == null || this.getName().equals(that.getName()) && this.getPayload().equals(that.getPayload());
}
/**
* Get the length of this tag in bytes as an <code>Integer</code>. Includes its type and name if it's not in a list.
*/
public abstract int getLength();
/**
* Get the name of this tag as a <code>String</code>. This will be <code>null</code> if this tag is in a list.
*/
public String getName() {
return name;
}
/**
* Get the payload of this tag as the type specified in its subclass.
*/
public T getPayload() {
return this.payload;
}
/**
* Get the type of this tag as a <code>Byte</code>.
*/
public abstract byte getType();
/**
* Replaces the name of this tag with the <code>String</code> specified.
*/
public void setName(String name) {
this.name = name;
}
/**
* Replaces the payload of this tag with the <code>Object</code> specified.
*/
public void setPayload(T payload) {
this.payload = payload;
}
/**
* Returns a <code>String</code> object representing this tag's value as JSON.
*/
public String toJSON() {
if (this.getName() != null)
return "\"" + this.getName() + "\": " + (this instanceof NBTString ? "\"" + this.getPayload() + "\"" : this.getPayload());
else
return this instanceof NBTString ? "\"" + this.getPayload() + "\"" : this.getPayload().toString();
}
/**
* Returns a <code>Byte[]</code> representing this tag's value as NBT.
*/
public byte[] toNBT() {
ByteBuffer bytes = ByteBuffer.allocate(this.getLength());
if (this.getName() != null)
this.writeName(bytes);
this.writePayload(bytes);
return bytes.array();
}
/**
* Returns a <code>String</code> object representing this tag's value.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
if (this.getName() != null)
return this.getClass().getSimpleName() + " Name:\"" + this.getName() + "\" Payload:" + this.getPayload();
else
return this.getClass().getSimpleName() + " Payload:" + this.getPayload();
}
/**
* Returns a <code>String</code> object representing this tag's value as XML.
*/
public String toXML() {
if (this.getName() != null)
return "<" + this.getClass().getSimpleName() + " name=\"" + this.getName() + "\" payload=\"" + this.getPayload() + "\" />";
else
return "<" + this.getClass().getSimpleName() + " payload=\"" + this.getPayload() + "\" />";
}
private void writeName(ByteBuffer bytes) {
bytes.put(this.getType());
byte[] name = this.getName().getBytes(NBT.CHARSET);
bytes.putShort((short) name.length);
bytes.put(name);
}
protected abstract void writePayload(ByteBuffer bytes);
}
|
package org.lantern.http;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.lantern.Censored;
import org.lantern.JsonUtils;
import org.lantern.LanternClientConstants;
import org.lantern.LanternUtils;
import org.lantern.LogglyHelper;
import org.lantern.MessageKey;
import org.lantern.Messages;
import org.lantern.NativeUtils;
import org.lantern.SecurityUtils;
import org.lantern.event.Events;
import org.lantern.event.ResetEvent;
import org.lantern.oauth.RefreshToken;
import org.lantern.state.FriendsHandler;
import org.lantern.state.InternalState;
import org.lantern.state.JsonModelModifier;
import org.lantern.state.LocationChangedEvent;
import org.lantern.state.Modal;
import org.lantern.state.Mode;
import org.lantern.state.Model;
import org.lantern.state.ModelIo;
import org.lantern.state.ModelService;
import org.lantern.state.SyncPath;
import org.lantern.util.Desktop;
import org.lantern.util.GatewayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class InteractionServlet extends HttpServlet {
private final InternalState internalState;
// XXX DRY: these are also defined in lantern-ui/app/js/constants.js
private enum Interaction {
GET,
GIVE,
CONTINUE,
SETTINGS,
CLOSE,
RESET,
SET,
PROXIEDSITES,
CANCEL,
LANTERNFRIENDS,
RETRY,
REQUESTINVITE,
CONTACT,
ABOUT,
SPONSOR,
ACCEPT,
UNEXPECTEDSTATERESET,
UNEXPECTEDSTATEREFRESH,
URL,
EXCEPTION,
FRIEND,
UPDATEAVAILABLE,
CHANGELANG,
REJECT,
ROUTERCONFIG
}
// modals the user can switch to from other modals
private static final Set<Modal> switchModals = new HashSet<Modal>();
static {
switchModals.add(Modal.about);
switchModals.add(Modal.sponsor);
switchModals.add(Modal.contact);
switchModals.add(Modal.settings);
switchModals.add(Modal.proxiedSites);
switchModals.add(Modal.lanternFriends);
switchModals.add(Modal.updateAvailable);
}
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* Generated serialization ID.
*/
private static final long serialVersionUID = -8820179746803371322L;
private final ModelService modelService;
private final Model model;
private final ModelIo modelIo;
private final Censored censored;
private final LogglyHelper logglyHelper;
private final FriendsHandler friender;
private final Messages msgs;
private RefreshToken refreshToken;
@Inject
public InteractionServlet(final Model model,
final ModelService modelService,
final InternalState internalState,
final ModelIo modelIo,
final Censored censored, final LogglyHelper logglyHelper,
final FriendsHandler friender,
final Messages msgs,
final RefreshToken refreshToken) {
this.model = model;
this.modelService = modelService;
this.internalState = internalState;
this.modelIo = modelIo;
this.censored = censored;
this.logglyHelper = logglyHelper;
this.friender = friender;
this.msgs = msgs;
this.refreshToken = refreshToken;
Events.register(this);
}
@Override
protected void doGet(final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException,
IOException {
processRequest(req, resp);
}
@Override
protected void doPost(final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException,
IOException {
processRequest(req, resp);
}
protected void processRequest(final HttpServletRequest req,
final HttpServletResponse resp) {
LanternUtils.addCSPHeader(resp);
final String uri = req.getRequestURI();
log.debug("Received URI: {}", uri);
final String interactionStr = StringUtils.substringAfterLast(uri, "/");
if (StringUtils.isBlank(interactionStr)) {
log.debug("blank interaction");
HttpUtils.sendClientError(resp, "blank interaction");
return;
}
log.debug("Headers: "+HttpUtils.getRequestHeaders(req));
if (!"XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
log.debug("invalid X-Requested-With");
HttpUtils.sendClientError(resp, "invalid X-Requested-With");
return;
}
if (!SecurityUtils.constantTimeEquals(model.getXsrfToken(),
req.getHeader("X-XSRF-TOKEN"))) {
log.debug("X-XSRF-TOKEN wrong: got {} expected {}", req.getHeader("X-XSRF-TOKEN"), model.getXsrfToken());
HttpUtils.sendClientError(resp, "invalid X-XSRF-TOKEN");
return;
}
final int cl = req.getContentLength();
String json = "";
if (cl > 0) {
try {
json = IOUtils.toString(req.getInputStream());
} catch (final IOException e) {
log.error("Could not parse json?");
}
}
log.debug("Body: '"+json+"'");
final Interaction inter =
Interaction.valueOf(interactionStr.toUpperCase());
if (inter == Interaction.CLOSE) {
if (handleClose(json)) {
return;
}
}
if (inter == Interaction.ROUTERCONFIG) {
log.debug("Got router config request!!");
try {
GatewayUtil.openGateway();
} catch (IOException e) {
log.error("Could not open gateway?", e);
} catch (InterruptedException e) {
log.error("Could not open gateway?", e);
}
}
if (inter == Interaction.URL) {
final String url = JsonUtils.getValueFromJson("url", json);
if (!StringUtils.startsWith(url, "http:
!StringUtils.startsWith(url, "https:
log.error("http(s) url expected, got {}", url);
HttpUtils.sendClientError(resp, "http(s) urls only");
return;
}
NativeUtils.openUri(url);
return;
}
final Modal modal = this.model.getModal();
log.debug("processRequest: modal = {}, inter = {}, mode = {}",
modal, inter, this.model.getSettings().getMode());
if (handleExceptionInteractions(modal, inter, json)) {
return;
}
Modal switchTo = null;
try {
// XXX a map would make this more robust
switchTo = Modal.valueOf(interactionStr);
} catch (IllegalArgumentException e) { }
if (switchTo != null && switchModals.contains(switchTo)) {
if (!switchTo.equals(modal)) {
if (!switchModals.contains(modal)) {
this.internalState.setLastModal(modal);
}
Events.syncModal(model, switchTo);
}
return;
}
switch (modal) {
case welcome:
this.model.getSettings().setMode(Mode.unknown);
switch (inter) {
case GET:
log.debug("Setting get mode");
handleSetModeWelcome(Mode.get);
break;
case GIVE:
log.debug("Setting give mode");
handleSetModeWelcome(Mode.give);
break;
}
break;
case authorize:
log.debug("Processing authorize modal...");
this.internalState.setModalCompleted(Modal.authorize);
this.internalState.advanceModal(null);
break;
case finished:
this.internalState.setCompletedTo(Modal.finished);
switch (inter) {
case CONTINUE:
log.debug("Processing continue");
this.model.setShowVis(true);
Events.sync(SyncPath.SHOWVIS, true);
this.internalState.setModalCompleted(Modal.finished);
this.internalState.advanceModal(null);
break;
case SET:
log.debug("Processing set in finished modal...applying JSON\n{}",
json);
applyJson(json);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp,
"Interaction not handled for modal: "+modal+
" and interaction: "+inter);
break;
}
break;
case firstInviteReceived:
log.error("Processing invite received...");
break;
case lanternFriends:
this.internalState.setCompletedTo(Modal.lanternFriends);
switch (inter) {
case FRIEND:
this.friender.addFriend(email(json));
break;
case REJECT:
this.friender.removeFriend(email(json));
break;
case CONTINUE:
// This dialog always passes continue as of this writing and
// not close.
case CLOSE:
log.debug("Processing continue/close for friends dialog");
if (this.model.isSetupComplete()) {
Events.syncModal(model, Modal.none);
} else {
this.internalState.setModalCompleted(Modal.lanternFriends);
this.internalState.advanceModal(null);
}
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp,
"Interaction not handled for modal: "+modal+
" and interaction: "+inter);
break;
}
break;
case none:
break;
case notInvited:
switch (inter) {
case RETRY:
log.debug("Switching to authorize modal");
// We need to kill all the existing oauth tokens.
resetOauth();
Events.syncModal(model, Modal.authorize);
break;
// not currently implemented:
//case REQUESTINVITE:
// Events.syncModal(model, Modal.requestInvite);
// break;
default:
log.error("Unexpected interaction: " + inter);
break;
}
break;
case proxiedSites:
this.internalState.setCompletedTo(Modal.proxiedSites);
switch (inter) {
case CONTINUE:
if (this.model.isSetupComplete()) {
Events.syncModal(model, Modal.none);
} else {
this.internalState.setModalCompleted(Modal.proxiedSites);
this.internalState.advanceModal(null);
}
break;
case LANTERNFRIENDS:
log.debug("Processing lanternFriends from proxiedSites");
Events.syncModal(model, Modal.lanternFriends);
break;
case SET:
if (!model.getSettings().isSystemProxy()) {
this.msgs.info(MessageKey.MANUAL_PROXY);
}
applyJson(json);
break;
case SETTINGS:
log.debug("Processing settings from proxiedSites");
Events.syncModal(model, Modal.settings);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp, "unexpected interaction for proxied sites");
break;
}
break;
case requestInvite:
log.info("Processing request invite");
switch (inter) {
case CANCEL:
this.internalState.setModalCompleted(Modal.requestInvite);
this.internalState.advanceModal(Modal.notInvited);
break;
case CONTINUE:
applyJson(json);
this.internalState.setModalCompleted(Modal.proxiedSites);
//TODO: need to do something here
this.internalState.advanceModal(null);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp, "unexpected interaction for request invite");
break;
}
break;
case requestSent:
log.debug("Process request sent");
break;
case settings:
switch (inter) {
case GET:
log.debug("Setting get mode");
// Only deal with a mode change if the mode has changed!
if (modelService.getMode() == Mode.give) {
// Break this out because it's set in the subsequent
// setMode call
final boolean everGet = model.isEverGetMode();
this.modelService.setMode(Mode.get);
if (!everGet) {
// need to do more setup to switch to get mode from
// give mode
model.setSetupComplete(false);
model.setModal(Modal.proxiedSites);
Events.syncModel(model);
} else {
// This primarily just triggers a setup complete event,
// which triggers connecting to proxies, setting up
// the local system proxy, etc.
model.setSetupComplete(true);
}
}
break;
case GIVE:
log.debug("Setting give mode");
this.modelService.setMode(Mode.give);
break;
case CLOSE:
log.debug("Processing settings close");
Events.syncModal(model, Modal.none);
break;
case SET:
log.debug("Processing set in setting...applying JSON\n{}", json);
applyJson(json);
break;
case RESET:
log.debug("Processing reset");
Events.syncModal(model, Modal.confirmReset);
break;
case PROXIEDSITES:
log.debug("Processing proxied sites in settings");
Events.syncModal(model, Modal.proxiedSites);
break;
case LANTERNFRIENDS:
log.debug("Processing friends in settings");
Events.syncModal(model, Modal.lanternFriends);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp,
"Interaction not handled for modal: "+modal+
" and interaction: "+inter);
break;
}
break;
case settingsLoadFailure:
switch (inter) {
case RETRY:
maybeSubmitToLoggly(json);
if (!modelIo.reload()) {
this.msgs.error(MessageKey.LOAD_SETTINGS_ERROR);
}
Events.syncModal(model, model.getModal());
break;
case RESET:
maybeSubmitToLoggly(json);
backupSettings();
Events.syncModal(model, Modal.welcome);
break;
default:
maybeSubmitToLoggly(json);
log.error("Did not handle interaction {} for modal {}", inter, modal);
break;
}
break;
case systemProxy:
this.internalState.setCompletedTo(Modal.systemProxy);
switch (inter) {
case CONTINUE:
log.debug("Processing continue in systemProxy", json);
applyJson(json);
Events.sync(SyncPath.SYSTEMPROXY, model.getSettings().isSystemProxy());
this.internalState.setModalCompleted(Modal.systemProxy);
this.internalState.advanceModal(null);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp, "error setting system proxy pref");
break;
}
break;
case updateAvailable:
switch (inter) {
case CLOSE:
Events.syncModal(model, this.internalState.getLastModal());
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
break;
}
break;
case authorizeLater:
log.error("Did not handle interaction {} for modal {}", inter, modal);
break;
case confirmReset:
log.debug("Handling confirm reset interaction");
switch (inter) {
case CANCEL:
log.debug("Processing cancel");
Events.syncModal(model, Modal.settings);
break;
case RESET:
handleReset();
Events.syncModel(this.model);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp,
"Interaction not handled for modal: "+modal+
" and interaction: "+inter);
}
break;
case about: // fall through on purpose
case sponsor:
switch (inter) {
case CLOSE:
Events.syncModal(model, this.internalState.getLastModal());
break;
default:
HttpUtils.sendClientError(resp, "invalid interaction "+inter);
}
break;
case contact:
switch(inter) {
case CONTINUE:
maybeSubmitToLoggly(json, true);
// fall through because this should be done in both cases:
case CANCEL:
Events.syncModal(model, this.internalState.getLastModal());
break;
default:
maybeSubmitToLoggly(json, true);
HttpUtils.sendClientError(resp, "invalid interaction "+inter);
}
break;
case giveModeForbidden:
if (inter == Interaction.CONTINUE) {
// need to do more setup to switch to get mode from give mode
model.getSettings().setMode(Mode.get);
model.setSetupComplete(false);
this.internalState.advanceModal(null);
Events.syncModal(model, Modal.proxiedSites);
Events.sync(SyncPath.SETUPCOMPLETE, false);
}
break;
default:
log.error("No matching modal for {}", modal);
}
this.modelIo.write();
}
private void resetOauth() {
log.debug("Resetting oauth...");
this.refreshToken.reset();
this.model.getSettings().setRefreshToken("");
this.model.getSettings().setAccessToken("");
this.model.getSettings().setExpiryTime(0L);
}
private String email(final String json) {
return JsonUtils.getValueFromJson("email", json).toLowerCase();
}
private void backupSettings() {
try {
File backup = new File(Desktop.getDesktopPath(), "lantern-model-backup");
FileUtils.copyFile(LanternClientConstants.DEFAULT_MODEL_FILE, backup);
} catch (final IOException e) {
log.warn("Could not backup model file.");
}
}
private boolean handleExceptionInteractions(
final Modal modal, final Interaction inter, final String json) {
boolean handled = false;
switch(inter) {
case EXCEPTION:
handleException(json);
handled = true;
break;
case UNEXPECTEDSTATERESET:
log.debug("Handling unexpected state reset.");
backupSettings();
handleReset();
Events.syncModel(this.model);
// fall through because this should be done in both cases:
case UNEXPECTEDSTATEREFRESH:
log.debug("Handling unexpected state refresh.");
maybeSubmitToLoggly(json);
handled = true;
break;
}
return handled;
}
/**
* Used to submit user feedback from contact form as well as bug reports
* during e.g. settingsLoadFailure or unexpectedState describing what
* happened
*
* @param json JSON with user's message + contextual information. If blank
* (can happen when user chooses not to notify developers) we do nothing.
* @param showNotification whether to show a success or failure notification
* upon submit
*/
private void maybeSubmitToLoggly(String json, boolean showNotification) {
if (StringUtils.isBlank(json)) return;
try {
logglyHelper.submit(json);
if (showNotification) {
this.msgs.info(MessageKey.CONTACT_THANK_YOU);
}
} catch(Exception e) {
if (showNotification) {
this.msgs.error(MessageKey.CONTACT_ERROR, e);
}
log.error("Could not submit: {}\n {}",
e.getMessage(), json);
}
}
private void maybeSubmitToLoggly(String json) {
maybeSubmitToLoggly(json, false);
}
private void handleException(final String json) {
log.error("Exception from UI:\n{}", json);
}
private boolean handleClose(String json) {
if (StringUtils.isBlank(json)) {
return false;
}
Map<String, Object> map;
try {
map = JsonUtils.OBJECT_MAPPER.readValue(json, Map.class);
final String notification = (String) map.get("notification");
model.closeNotification(Integer.parseInt(notification));
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
return true;
} catch (JsonParseException e) {
log.warn("Exception closing notifications {}", e);
} catch (JsonMappingException e) {
log.warn("Exception closing notifications {}", e);
} catch (IOException e) {
log.warn("Exception closing notifications {}", e);
}
return false;
}
private void handleSetModeWelcome(final Mode mode) {
this.model.setModal(Modal.authorize);
this.internalState.setModalCompleted(Modal.welcome);
this.modelService.setMode(mode);
Events.syncModal(model);
}
private void applyJson(final String json) {
final JsonModelModifier mod = new JsonModelModifier(modelService);
mod.applyJson(json);
}
private void handleReset() {
// This posts the reset event to any classes that need to take action,
// avoiding coupling this class to those classes.
Events.eventBus().post(new ResetEvent());
if (LanternClientConstants.DEFAULT_MODEL_FILE.isFile()) {
try {
FileUtils.forceDelete(LanternClientConstants.DEFAULT_MODEL_FILE);
} catch (final IOException e) {
log.warn("Could not delete model file?");
}
}
resetOauth();
final Model base = new Model(model.getCountryService());
model.setEverGetMode(false);
model.setLaunchd(base.isLaunchd());
model.setModal(base.getModal());
model.setNodeId(base.getNodeId());
model.setProfile(base.getProfile());
model.setNproxiedSitesMax(base.getNproxiedSitesMax());
//we need to keep clientID and clientSecret, because they are application-level settings
String clientID = model.getSettings().getClientID();
String clientSecret = model.getSettings().getClientSecret();
model.setSettings(base.getSettings());
model.getSettings().setClientID(clientID);
model.getSettings().setClientSecret(clientSecret);
model.setSetupComplete(base.isSetupComplete());
model.setShowVis(base.isShowVis());
//model.setFriends(base.getFriends());
model.clearNotifications();
modelIo.write();
}
@Subscribe
public void onLocationChanged(final LocationChangedEvent e) {
Events.sync(SyncPath.LOCATION, e.getNewLocation());
if (censored.isCountryCodeCensored(e.getNewCountry())) {
if (!censored.isCountryCodeCensored(e.getOldCountry())) {
//moving from uncensored to censored
if (model.getSettings().getMode() == Mode.give) {
Events.syncModal(model, Modal.giveModeForbidden);
}
}
}
}
}
|
package net.ssehub.kernel_haven.config;
import java.io.File;
import java.util.List;
import java.util.regex.Pattern;
/**
* A single setting in the configuration. This holds the property key and other useful information. Instances of
* this are registered in a {@link Configuration} object. After that, the values can accessed through this instance of
* this class. It is recommended to create <code>public static final</code> instances of this class.
*
* @param <T> The that the data should be represented as.
*
* @author Adam
*/
public class Setting<T> {
/**
* The type of setting. At register time, checks are done to verify that the value specified in the properties
* is a valid instance of this type. This type also specifies the return type, and thus the generic of this instance
* should be set accordingly.
*/
public static enum Type {
/**
* A string value. Generic should be {@link String}.
*/
STRING,
/**
* A integer value. Generic should be {@link Integer}.
*/
INTEGER,
/**
* A {@link File} pointing to an existing directory. Generic should be {@link File}.
*/
DIRECTORY,
/**
* A {@link File} pointing to an existing file. Generic should be {@link File}.
*/
FILE,
/**
* A {@link File} without any restrictions. Generic should be {@link File}.
*/
PATH,
/**
* A boolean value. Generic should be {@link Boolean}.
*/
BOOLEAN,
/**
* A regular expression. Generic should be {@link Pattern}.
*/
REGEX,
/**
* A comma separated list of strings. Generic should be {@link List} with generic String.
*/
STRING_LIST,
/**
* A list of strings. Each value has its own key, based on the key of the setting and a suffix with a number:
* <code><key>.<number></code> The number starts with 0 and increases by 1 for each successive
* element in the list. Generic should be {@link List} with generic String.
* <br />
* The mandatory or default value attributes have no effect on this type of setting.
*/
SETTING_LIST,
/**
* A value of a Java enum. <b>Do not create a {@link Setting} with this</b>, but rather use the
* {@link EnumSetting} class.
*/
ENUM,
}
private String key;
private Type type;
private boolean mandatory;
private String defaultValue;
private String description;
/**
* Creates a new setting.
*
* @param key The key in the properties file.
* @param type The type of setting. The generic should be set accordingly. Based on this type, checks are done at
* register time (and possibly exceptions thrown).
* @param mandatory Whether this setting is mandatory. If this is <code>true</code>, the properties file does not
* contain this key, and the default value is <code>null</code>, then an exception is thrown when the setting
* is registered.
* @param defaultValue The default value to use if the key is not specified in the properties. May be
* <code>null</code>, in which case no default value is used.
* @param description The description of this setting. Currently not used, but should be provided for documentation
* purposes.
*/
public Setting(String key, Type type, boolean mandatory, String defaultValue, String description) {
this.key = key;
this.type = type;
this.mandatory = mandatory;
this.defaultValue = defaultValue;
this.description = description;
}
/**
* The key of this setting.
*
* @return The key that this setting is specified as in the properties.
*/
public String getKey() {
return key;
}
/**
* The type of setting. This influences the data type that values are represented in Java (and thus should be
* reflected by the generic of this instance).
*
* @return The type of setting.
*/
public Type getType() {
return type;
}
/**
* Whether this is a mandatory setting.
*
* @return Whether this setting is mandatory or not.
*/
public boolean isMandatory() {
return mandatory;
}
/**
* The default value to be used if the key is not specified in the properties.
*
* @return The default value; <code>null</code> if no default value should be used.
*/
public String getDefaultValue() {
return defaultValue;
}
/**
* The description of this setting. Can be used to explain the user what this setting is supposed to configure.
*
* @return The description text. May contain line breaks.
*/
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Setting(" + key + ")";
}
}
|
package org.innovateuk.ifs.interview.transactional;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.interview.domain.InterviewAssignment;
import org.innovateuk.ifs.interview.domain.InterviewAssignmentMessageOutcome;
import org.innovateuk.ifs.interview.repository.InterviewAssignmentRepository;
import org.innovateuk.ifs.interview.resource.InterviewAssignmentState;
import org.innovateuk.ifs.interview.workflow.configuration.InterviewAssignmentWorkflowHandler;
import org.innovateuk.ifs.invite.resource.*;
import org.innovateuk.ifs.notifications.resource.Notification;
import org.innovateuk.ifs.notifications.resource.NotificationTarget;
import org.innovateuk.ifs.notifications.resource.SystemNotificationSource;
import org.innovateuk.ifs.notifications.resource.UserNotificationTarget;
import org.innovateuk.ifs.notifications.service.NotificationTemplateRenderer;
import org.innovateuk.ifs.notifications.service.senders.NotificationSender;
import org.innovateuk.ifs.user.domain.Organisation;
import org.innovateuk.ifs.user.domain.ProcessRole;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.repository.OrganisationRepository;
import org.innovateuk.ifs.user.resource.Role;
import org.innovateuk.ifs.workflow.domain.ActivityState;
import org.innovateuk.ifs.workflow.domain.ActivityType;
import org.innovateuk.ifs.workflow.repository.ActivityStateRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
import static org.innovateuk.ifs.util.MapFunctions.asMap;
/**
* Service for managing {@link InterviewAssignment}s.
*/
@Service
@Transactional
public class InterviewAssignmentInviteServiceImpl implements InterviewAssignmentInviteService {
@Autowired
private ApplicationRepository applicationRepository;
@Autowired
private ActivityStateRepository activityStateRepository;
@Autowired
private InterviewAssignmentRepository interviewAssignmentRepository;
@Autowired
private OrganisationRepository organisationRepository;
@Autowired
private NotificationTemplateRenderer renderer;
@Autowired
private SystemNotificationSource systemNotificationSource;
@Autowired
private NotificationSender notificationSender;
@Autowired
private InterviewAssignmentWorkflowHandler interviewAssignmentWorkflowHandler;
enum Notifications {
INVITE_APPLICANT_GROUP_TO_INTERVIEW
}
@Override
public ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable) {
final Page<Application> pagedResult =
applicationRepository.findSubmittedApplicationsNotOnInterviewPanel(competitionId, pageable);
return serviceSuccess(new AvailableApplicationPageResource(
pagedResult.getTotalElements(),
pagedResult.getTotalPages(),
simpleMap(pagedResult.getContent(), this::mapToAvailableApplicationResource),
pagedResult.getNumber(),
pagedResult.getSize()
));
}
@Override
@Transactional
public ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable) {
final Page<InterviewAssignment> pagedResult =
interviewAssignmentRepository.findByTargetCompetitionIdAndActivityStateState(
competitionId, InterviewAssignmentState.CREATED.getBackingState(), pageable);
return serviceSuccess(new InterviewAssignmentStagedApplicationPageResource(
pagedResult.getTotalElements(),
pagedResult.getTotalPages(),
simpleMap(pagedResult.getContent(), this::mapToPanelCreatedInviteResource),
pagedResult.getNumber(),
pagedResult.getSize()
));
}
@Override
public ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId) {
return serviceSuccess(
simpleMap(
applicationRepository.findSubmittedApplicationsNotOnInterviewPanel(competitionId),
Application::getId
)
);
}
@Override
public ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites) {
long competitionId = stagedInvites.get(0).getCompetitionId();
final List<InterviewAssignment> assignedApplications =
interviewAssignmentRepository
.findByTargetCompetitionIdAndActivityStateState(
competitionId, InterviewAssignmentState.CREATED.getBackingState());
List<Long> assignedApplicationIds = assignedApplications.stream()
.map(
interviewAssignment -> interviewAssignment
.getTarget()
.getId()
).collect(Collectors.toList());
stagedInvites.stream()
.filter(invite -> assignedApplicationIds.contains(invite.getApplicationId()) == false)
.forEach(invite -> {
getApplication(invite.getApplicationId()).andOnSuccess(this::assignApplicationToCompetition);
});
return serviceSuccess();
}
@Override
public ServiceResult<Void> unstageApplication(long applicationId) {
interviewAssignmentRepository.deleteByTargetIdAndActivityStateState(applicationId, InterviewAssignmentState.CREATED.getBackingState());
return serviceSuccess();
}
@Override
public ServiceResult<Void> unstageApplications(long competitionId) {
interviewAssignmentRepository.deleteByTargetCompetitionIdAndActivityStateState(competitionId, InterviewAssignmentState.CREATED.getBackingState());
return serviceSuccess();
}
public ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate() {
NotificationTarget notificationTarget = new UserNotificationTarget("", "");
return renderer.renderTemplate(systemNotificationSource, notificationTarget, "invite_applicants_to_interview_panel_text.txt",
Collections.emptyMap()).andOnSuccessReturn(content -> new ApplicantInterviewInviteResource(content));
}
@Override
public ServiceResult<Void> sendInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource) {
List<InterviewAssignment> interviewAssignments = interviewAssignmentRepository.findByTargetCompetitionIdAndActivityStateState(
competitionId, InterviewAssignmentState.CREATED.getBackingState());
final ActivityState awaitingFeedbackActivityState = activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_INTERVIEW_PANEL, InterviewAssignmentState.AWAITING_FEEDBACK_RESPONSE.getBackingState());
ServiceResult<Void> result = serviceSuccess();
for (InterviewAssignment assignment : interviewAssignments) {
if (result.isSuccess()) {
result = sendInvite(assessorInviteSendResource, assignment, awaitingFeedbackActivityState);
}
}
return result;
}
private ServiceResult<Void> sendInvite(AssessorInviteSendResource assessorInviteSendResource, InterviewAssignment assignment, ActivityState awaitingFeedbackActivityState) {
User user = assignment.getParticipant().getUser();
NotificationTarget recipient = new UserNotificationTarget(user.getName(), user.getEmail());
Notification notification = new Notification(
systemNotificationSource,
recipient,
Notifications.INVITE_APPLICANT_GROUP_TO_INTERVIEW,
asMap(
"subject", assessorInviteSendResource.getSubject(),
"name", user.getName(),
"competitionName", assignment.getTarget().getCompetition().getName(),
"applicationId", assignment.getTarget().getId(),
"applicationTitle", assignment.getTarget().getName(),
"message", assessorInviteSendResource.getContent()
));
return notificationSender.sendNotification(notification).andOnSuccessReturnVoid(() -> {
InterviewAssignmentMessageOutcome outcome = new InterviewAssignmentMessageOutcome();
outcome.setAssessmentInterviewPanel(assignment);
outcome.setMessage(assessorInviteSendResource.getContent());
outcome.setSubject(assessorInviteSendResource.getSubject());
interviewAssignmentWorkflowHandler.notifyInterviewPanel(assignment, outcome);
});
}
private ServiceResult<Application> getApplication(long applicationId) {
return find(applicationRepository.findOne(applicationId), notFoundError(Application.class, applicationId));
}
private AvailableApplicationResource mapToAvailableApplicationResource(Application application) {
return getOrganisation(application.getLeadOrganisationId())
.andOnSuccessReturn(
leadOrganisation ->
new AvailableApplicationResource(application.getId(), application.getName(), leadOrganisation.getName()
)
).getSuccess();
}
private InterviewAssignmentStagedApplicationResource mapToPanelCreatedInviteResource(InterviewAssignment panelInvite) {
final Application application = panelInvite.getTarget();
return getOrganisation(panelInvite.getParticipant().getOrganisationId())
.andOnSuccessReturn(leadOrganisation ->
new InterviewAssignmentStagedApplicationResource(
panelInvite.getId(),
application.getId(),
application.getName(),
leadOrganisation.getName()
)
).getSuccess();
}
private ServiceResult<Organisation> getOrganisation(long organisationId) {
return find(organisationRepository.findOne(organisationId), notFoundError(Organisation.class, organisationId));
}
private ServiceResult<InterviewAssignment> assignApplicationToCompetition(Application application) {
final ActivityState createdActivityState = activityStateRepository.findOneByActivityTypeAndState(ActivityType.ASSESSMENT_INTERVIEW_PANEL, InterviewAssignmentState.CREATED.getBackingState());
final ProcessRole pr = new ProcessRole(application.getLeadApplicant(), application.getId(), Role.INTERVIEW_LEAD_APPLICANT, application.getLeadOrganisationId());
final InterviewAssignment panel = new InterviewAssignment(application, pr, createdActivityState);
interviewAssignmentRepository.save(panel);
return serviceSuccess(panel);
}
}
|
package com.ctrip.zeus.support;
import com.ctrip.zeus.dal.core.*;
import com.ctrip.zeus.model.entity.*;
public class C {
public static App toApp(AppDo d) {
return new App()
.setAppId(d.getAppId())
.setName(d.getName());
}
public static AppServer toAppServer(AppServerDo d) {
return new AppServer()
.setEnable(d.isEnable())
.setFailTimeout(d.getFailTimeout())
.setHealthy(d.isHealthy())
.setMaxFails(d.getMaxFails())
.setPort(d.getPort())
.setWeight(d.getWeight());
}
public static AppSlb toAppSlb(AppSlbDo d) {
return new AppSlb()
.setPath(d.getPath());
}
public static Domain toDomain(SlbDomainDo d) {
return new Domain()
.setName(d.getName());
}
public static HealthCheck toHealthCheck(AppHealthCheckDo d) {
return new HealthCheck()
.setFails(d.getFails())
.setIntervals(d.getIntervals())
.setPasses(d.getPasses())
.setUri(d.getUri());
}
public static LoadBalancingMethod toLoadBalancingMethod(AppLoadBalancingMethodDo d) {
return new LoadBalancingMethod()
.setType(d.getType())
.setValue(d.getValue());
}
public static Server toServer(ServerDo d) {
return new Server()
.setHostName(d.getHostName())
.setIp(d.getIp())
.setUp(d.isUp());
}
public static Slb toSlb(SlbDo d) {
return new Slb()
.setName(d.getName())
.setNginxBin(d.getNginxBin())
.setNginxConf(d.getNginxConf())
.setNginxWorkerProcesses(d.getNginxWorkerProcesses())
.setStatus(d.getStatus());
}
public static SlbServer toSlbServer(SlbServerDo d) {
return new SlbServer()
.setEnable(d.isEnable())
.setHostName(d.getHostName())
.setIp(d.getIp());
}
public static Vip toVip(SlbVipDo d) {
return new Vip()
.setIp(d.getIp());
}
public static VirtualServer toVirtualServer(SlbVirtualServerDo d) {
return new VirtualServer()
.setPort(d.getPort())
.setName(d.getName())
.setSsl(d.isIsSsl());
}
/*Entity to Do*/
public static AppDo toAppDo(App e) {
return new AppDo().setAppId(e.getAppId())
.setName(e.getName());
}
public static AppServerDo toAppServerDo(AppServer e) {
return new AppServerDo()
.setIp(e.getServer().getIp())
.setEnable(e.getEnable())
.setFailTimeout(e.getFailTimeout())
.setHealthy(e.getHealthy())
.setMaxFails(e.getMaxFails())
.setPort(e.getPort())
.setWeight(e.getWeight());
}
public static AppSlbDo toAppSlbDo(AppSlb e) {
return new AppSlbDo()
.setSlbName(e.getSlbName())
.setSlbVirtualServerName(e.getVirtualServer().getName())
.setPath(e.getPath());
}
public static SlbDomainDo toSlbDomainDo(Domain e) {
return new SlbDomainDo()
.setName(e.getName());
}
public static AppHealthCheckDo toAppHealthCheckDo(HealthCheck e) {
return new AppHealthCheckDo()
.setUri(e.getUri())
.setIntervals(e.getIntervals())
.setFails(e.getFails())
.setPasses(e.getPasses());
}
public static AppLoadBalancingMethodDo toAppLoadBalancingMethodDo(LoadBalancingMethod e) {
return new AppLoadBalancingMethodDo()
.setType(e.getType())
.setValue(e.getValue());
}
public static ServerDo toServerDo(Server e) {
return new ServerDo()
.setHostName(e.getHostName())
.setIp(e.getIp())
.setUp(e.getUp());
}
public static SlbDo toSlbDo(Slb e) {
return new SlbDo()
.setName(e.getName())
.setNginxBin(e.getNginxBin())
.setNginxConf(e.getNginxConf())
.setNginxWorkerProcesses(e.getNginxWorkerProcesses())
.setStatus(e.getStatus());
}
public static SlbServerDo toSlbServerDo(SlbServer e) {
return new SlbServerDo()
.setHostName(e.getHostName())
.setIp(e.getIp())
.setEnable(e.getEnable());
}
public static SlbVipDo toSlbVipDo(Vip e) {
return new SlbVipDo()
.setIp(e.getIp());
}
public static SlbVirtualServerDo toSlbVirtualServerDo(VirtualServer e) {
return new SlbVirtualServerDo()
.setPort(e.getPort())
.setIsSsl(e.isSsl())
.setName(e.getName());
}
}
|
package org.lightmare.utils;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Utility class to work with {@link Collection} instances
*
* @author Levan
* @since 0.0.81-SNAPSHOT
*/
public abstract class CollectionUtils {
// First index of array
public static final int FIRST_INDEX = 0;
// Second index of array
public static final int SECOND_INDEX = 1;
// Index of not existing data in collection
public static final int NOT_EXISTING_INDEX = -1;
// Length of empty array
public static final int EMPTY_ARRAY_LENGTH = 0;
// Empty array of objects
public static final Object[] EMPTY_ARRAY = {};
/**
* Checks if passed {@link Collection} instance is not empty
*
* @param collection
* @return <code>boolean</code>
*/
public static boolean notEmpty(Collection<?> collection) {
return !collection.isEmpty();
}
/**
* Checks passed {@link Collection} instance on null and on emptiness
* returns true if it is not null and is not empty
*
* @param collection
* @return <code></code>
*/
public static boolean valid(Collection<?> collection) {
return collection != null && !collection.isEmpty();
}
/**
* Checks passed {@link Map} instance on null and emptiness returns true if
* it is not null and is not empty
*
* @param map
* @return <code>boolean</code>
*/
public static boolean valid(Map<?, ?> map) {
return map != null && !map.isEmpty();
}
/**
* Checks if passed {@link Map} instance is null or is empty
*
* @param map
* @return <code>boolean</code>
*/
public static boolean invalid(Map<?, ?> map) {
return !valid(map);
}
/**
* Checks if passed {@link Collection} instance is null or is empty
*
* @param collection
* @return <code>boolean</code>
*/
public static boolean invalid(Collection<?> collection) {
return !valid(collection);
}
/**
* Checks if there is null or empty {@link Collection} instance is passed
* collections
*
* @param collections
* @return <code>boolean</code>
*/
public static boolean invalidAll(Collection<?>... collections) {
return !valid(collections);
}
public static boolean validAll(Map<?, ?>... maps) {
boolean avaliable = ObjectUtils.notNull(maps);
if (avaliable) {
Map<?, ?> map;
for (int i = FIRST_INDEX; i < maps.length && avaliable; i++) {
map = maps[i];
avaliable = avaliable && valid(map);
}
}
return avaliable;
}
public static boolean valid(Object[] array) {
return array != null && array.length > EMPTY_ARRAY_LENGTH;
}
public static boolean invalid(Object[] array) {
return !valid(array);
}
public static boolean validAll(Collection<?>... collections) {
boolean avaliable = ObjectUtils.notNull(collections);
if (avaliable) {
Collection<?> collection;
for (int i = FIRST_INDEX; i < collections.length && avaliable; i++) {
collection = collections[i];
avaliable = avaliable && valid(collection);
}
}
return avaliable;
}
public static boolean validAll(Object[]... arrays) {
boolean avaliable = ObjectUtils.notNull(arrays);
if (avaliable) {
Object[] collection;
int length = arrays.length;
for (int i = FIRST_INDEX; i < length && avaliable; i++) {
collection = arrays[i];
avaliable = avaliable && valid(collection);
}
}
return avaliable;
}
/**
* Gets value from passed {@link Map} as other {@link Map} instance
*
* @param key
* @param from
* @return {@link Map}<K,V>
*/
public static <K, V> Map<K, V> getAsMap(Object key, Map<?, ?> from) {
Map<K, V> result;
if (valid(from)) {
Object objectValue = from.get(key);
if (objectValue instanceof Map) {
result = ObjectUtils.cast(objectValue);
} else {
result = null;
}
} else {
result = null;
}
return result;
}
/**
* Gets values from passed {@link Map} as other {@link Map} instance
* recursively by passed keys array
*
* @param from
* @param keys
* @return {@link Map}
*/
public static Map<?, ?> getAsMap(Map<?, ?> from, Object... keys) {
Map<?, ?> result = from;
int length = keys.length;
Object key;
for (int i = FIRST_INDEX; i < length && ObjectUtils.notNull(result); i++) {
key = keys[i];
result = getAsMap(key, result);
}
return result;
}
/**
* Gets values from passed {@link Map} as other {@link Map} instance
* recursively by passed keys array and for first key get value from last
* {@link Map} instance
*
* @param from
* @param keys
* @return <code>V</code>
*/
public static <V> V getSubValue(Map<?, ?> from, Object... keys) {
V value;
int length = keys.length - 1;
Object[] subKeys = new Object[length];
Object key = keys[length];
for (int i = FIRST_INDEX; i < length; i++) {
subKeys[i] = keys[i];
}
Map<?, ?> result = getAsMap(from, subKeys);
if (valid(result)) {
value = ObjectUtils.cast(result.get(key));
} else {
value = null;
}
return value;
}
private <K, V> void putIfAbscent(Map<K, V> map, K key, V value) {
boolean contained = map.containsKey(key);
if (ObjectUtils.notTrue(contained)) {
map.put(key, value);
}
}
/**
* Creates new {@link Set} from passed {@link Collection} instance
*
* @param collection
* @return {@link Set}<code><T></code>
*/
public static <T> Set<T> translateToSet(Collection<T> collection) {
Set<T> set;
if (valid(collection)) {
set = new HashSet<T>(collection);
} else {
set = Collections.emptySet();
}
return set;
}
/**
* Creates new {@link Set} from passed array instance
*
* @param array
* @return {@link Set}<code><T></code>
*/
public static <T> Set<T> translateToSet(T[] array) {
List<T> collection;
if (valid(array)) {
collection = Arrays.asList(array);
} else {
collection = null;
}
return translateToSet(collection);
}
/**
* Creates new {@link List} from passed {@link Collection} instance
*
* @param collection
* @return {@link List}<code><T></code>
*/
public static <T> List<T> translateToList(Collection<T> collection) {
List<T> list;
if (valid(collection)) {
list = new ArrayList<T>(collection);
} else {
list = Collections.emptyList();
}
return list;
}
private static <T> T[] toArray(Class<T> type, int size) {
Object arrayObject = Array.newInstance(type, size);
T[] array = ObjectUtils.cast(arrayObject);
return array;
}
/**
* Checks if passed {@link Object} is array
*
* @param data
* @return <code>boolean</code>
*/
public static boolean isArray(final Object data) {
boolean valid = (data instanceof Object[] || data instanceof boolean[]
|| data instanceof byte[] || data instanceof short[]
|| data instanceof char[] || data instanceof int[]
|| data instanceof long[] || data instanceof float[] || data instanceof double[]);
return valid;
}
/**
* Checks if passed {@link Object} is {@link Object} types array
*
* @param data
* @return <code>boolean</code>
*/
public static boolean isObjectArray(final Object data) {
boolean valid = (data instanceof Object[]);
return valid;
}
/**
* Checks if passed {@link Object} is primitive types array
*
* @param data
* @return <code>boolean</code>
*/
public static boolean isPrimitiveArray(final Object data) {
boolean valid = (data instanceof boolean[] || data instanceof byte[]
|| data instanceof short[] || data instanceof char[]
|| data instanceof int[] || data instanceof long[]
|| data instanceof float[] || data instanceof double[]);
return valid;
}
/**
* Converts passed {@link Collection} to array of appropriated {@link Class}
* type
*
* @param collection
* @param type
* @return <code>T[]</code>
*/
public static <T> T[] toArray(Collection<T> collection, Class<T> type) {
T[] array;
if (ObjectUtils.notNull(collection)) {
array = toArray(type, collection.size());
array = collection.toArray(array);
} else {
array = null;
}
return array;
}
/**
* Creates empty array of passed type
*
* @param type
* @return <code>T[]</code>
*/
public static <T> T[] emptyArray(Class<T> type) {
T[] empty = toArray(type, EMPTY_ARRAY_LENGTH);
return empty;
}
/**
* Peaks first element from list
*
* @param list
* @return T
*/
private static <T> T getFirstFromList(List<T> list) {
T value;
if (valid(list)) {
value = list.get(FIRST_INDEX);
} else {
value = null;
}
return value;
}
/**
* Peaks first element from collection
*
* @param collection
* @return T
*/
public static <T> T getFirst(Collection<T> collection) {
T value;
if (valid(collection)) {
if (collection instanceof List) {
value = getFirstFromList(((List<T>) collection));
} else {
Iterator<T> iterator = collection.iterator();
value = iterator.next();
}
} else {
value = null;
}
return value;
}
/**
* Peaks first element from array
*
* @param collection
* @return T
*/
public static <T> T getFirst(T[] values) {
T value;
if (valid(values)) {
value = values[FIRST_INDEX];
} else {
value = null;
}
return value;
}
}
|
package it.unimi.dsi.sux4j.mph;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.zip.GZIPInputStream;
import org.apache.commons.math3.random.RandomGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.Parameter;
import com.martiansoftware.jsap.SimpleJSAP;
import com.martiansoftware.jsap.Switch;
import com.martiansoftware.jsap.UnflaggedOption;
import com.martiansoftware.jsap.stringparsers.FileStringParser;
import com.martiansoftware.jsap.stringparsers.ForNameStringParser;
import it.unimi.dsi.Util;
import it.unimi.dsi.big.io.FileLinesByteArrayCollection;
import it.unimi.dsi.bits.BitVector;
import it.unimi.dsi.bits.BitVectors;
import it.unimi.dsi.bits.Fast;
import it.unimi.dsi.bits.LongArrayBitVector;
import it.unimi.dsi.bits.TransformationStrategies;
import it.unimi.dsi.bits.TransformationStrategy;
import it.unimi.dsi.fastutil.Size64;
import it.unimi.dsi.fastutil.io.BinIO;
import it.unimi.dsi.fastutil.longs.AbstractLongBigList;
import it.unimi.dsi.fastutil.longs.LongBigList;
import it.unimi.dsi.fastutil.longs.LongBigLists;
import it.unimi.dsi.fastutil.longs.LongIterable;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongList;
import it.unimi.dsi.fastutil.objects.AbstractObject2LongFunction;
import it.unimi.dsi.io.FastBufferedReader;
import it.unimi.dsi.io.FileLinesCollection;
import it.unimi.dsi.io.LineIterator;
import it.unimi.dsi.io.OfflineIterable;
import it.unimi.dsi.io.OfflineIterable.OfflineIterator;
import it.unimi.dsi.lang.MutableString;
import it.unimi.dsi.logging.ProgressLogger;
import it.unimi.dsi.sux4j.bits.Rank;
import it.unimi.dsi.sux4j.bits.Rank16;
import it.unimi.dsi.sux4j.io.ChunkedHashStore;
import it.unimi.dsi.sux4j.io.ChunkedHashStore.Chunk;
import it.unimi.dsi.sux4j.io.ChunkedHashStore.DuplicateException;
import it.unimi.dsi.sux4j.mph.solve.Linear3SystemSolver;
import it.unimi.dsi.util.XorShift1024StarRandomGenerator;
import it.unimi.dsi.util.concurrent.ReorderingBlockingQueue;
/** An immutable function stored quasi-succinctly using the
* {@linkplain Linear3SystemSolver Genuzio-Ottaviano-Vigna method to solve <b>F</b><sub>2</sub>-linear systems}.
*
* <p>Instances of this class store a function from keys to values. Keys are provided by an {@linkplain Iterable iterable object} (whose iterators
* must return elements in a consistent order), whereas values are provided by a {@link LongIterable}. If you do nost specify
* values, each key will be assigned its rank (e.g., its position in iteration order starting from zero).
*
* <P>For convenience, this class provides a main method that reads from
* standard input a (possibly <code>gzip</code>'d) sequence of newline-separated strings, and
* writes a serialised function mapping each element of the list to its position, or to a given list of values.
*
* <h3>Signing</h3>
*
* <p>Optionally, it is possible to {@linkplain Builder#signed(int) <em>sign</em>} a {@link GOV3Function}.
* Signing {@linkplain Builder#signed(int) is possible if no list of values has been specified} (otherwise, there
* is no way to associate a key with its signature). A <var>w</var>-bit signature will
* be associated with each key, so that {@link #getLong(Object)} will return a {@linkplain #defaultReturnValue() default return value} (by default, -1) on strings that are not
* in the original key set. As usual, false positives are possible with probability 2<sup>-<var>w</var></sup>.
*
* <p>If you're not interested in the rank of a key, but just to know whether the key was in the original set,
* you can {@linkplain Builder#dictionary(int) turn the function into a dictionary}. In this case, the value associated
* by the function with a key is exactly its signature, which means that the only space used by the function is
* that occupied by signatures: this is one of the fastest and most compact way of storing a static dictionary.
* In this case, the only returned value is one, and the {@linkplain #defaultReturnValue() default return value} is set to zero.
*
* <h2>Building a function</h2>
*
* <p>This class provides a great amount of flexibility when creating a new function; such flexibility is exposed through the {@linkplain Builder builder}.
* To exploit the various possibilities, you must understand some details of the construction.
*
* <p>In a first phase, we build a {@link ChunkedHashStore} containing hashes of the keys. By default,
* the store will associate each hash with the rank of the key. If you {@linkplain Builder#values(LongIterable, int) specify values},
* the store will associate with each hash the corresponding value.
*
* <p>However, if you further require an {@linkplain Builder#indirect() indirect}
* construction the store will associate again each hash with the rank of the corresponding key, and access randomly the values
* (which must be either a {@link LongList} or a {@link LongBigList}). Indirect construction is useful only in complex, multi-layer
* hashes (such as an {@link LcpMonotoneMinimalPerfectHashFunction}) in which we want to reuse a checked {@link ChunkedHashStore}.
* Storing values in the {@link ChunkedHashStore}
* is extremely scalable because the values must just be a {@link LongIterable} that
* will be scanned sequentially during the store construction. On the other hand, if you have already a store that
* associates ordinal positions, and you want to build a new function for which a {@link LongList} or {@link LongBigList} of values needs little space (e.g.,
* because it is described implicitly), you can opt for an {@linkplain Builder#indirect() indirect} construction using the already built store.
*
* <p>Note that if you specify a store it will be used before building a new one (possibly because of a {@link it.unimi.dsi.sux4j.io.ChunkedHashStore.DuplicateException DuplicateException}),
* with obvious benefits in terms of performance. If the store is not checked, and a {@link it.unimi.dsi.sux4j.io.ChunkedHashStore.DuplicateException DuplicateException} is
* thrown, the constructor will try to rebuild the store, but this requires, of course, that the keys, and possibly the values, are available.
* Note that it is your responsibility to pass a correct store.
*
* <h2>Implementation Details</h2>
*
* <p>The detail of the data structure
* can be found in “Fast Scalable Construction of (Minimal Perfect Hash) Functions”, by
* Marco Genuzio, Giuseppe Ottaviano and Sebastiano Vigna,
* <i>15th International Symposium on Experimental Algorithms — SEA 2016</i>,
* Lecture Notes in Computer Science, Springer, 2016. We generate a random 3-regular linear system on <b>F</b><sub>2</sub>, where
* the known term of the <var>k</var>-th equation is the output value for the <var>k</var>-th key.
* Then, we {@linkplain Linear3SystemSolver solve} it and store the solution. Since the system must have ≈10% more variables than equations to be solvable,
* an <var>r</var>-bit {@link GOV3Function} on <var>n</var> keys requires 1.1<var>rn</var>
* bits.
*
* <p>Optionally, you may require a <em>{@linkplain Builder#compacted() compacted}</em> function, that is, a
* function storing nonzero values
* in a separate array and using a {@linkplain Rank ranked} marker array to record the positions of nonzero values.
* In this case, the function requires just (1.1 + <var>r</var>)<var>n</var> bits (plus the bits that are necessary for the
* {@linkplain Rank ranking structure}; the current implementation uses {@link Rank16}), but has slightly slower lookups.
*
* @see GOV4Function
* @author Sebastiano Vigna
* @since 4.0.0
*/
public class GOV3Function<T> extends AbstractObject2LongFunction<T> implements Serializable, Size64 {
private static final long serialVersionUID = 1L;
private static final long[] END_OF_SOLUTION_QUEUE = new long[0];
private static final Chunk END_OF_CHUNK_QUEUE = new Chunk();
private static final Logger LOGGER = LoggerFactory.getLogger( GOV3Function.class );
private static final boolean ASSERTS = false;
private static final boolean DEBUG = false;
/** The local seed is generated using this step, so to be easily embeddable in {@link #offsetAndSeed}. */
private static final long SEED_STEP = 1L << 56;
/** The lowest 56 bits of {@link #offsetAndSeed} contain the number of keys stored up to the given chunk. */
private static final long OFFSET_MASK = -1L >>> 8;
/** The ratio between variables and equations. */
public static double C = 1.09 + 0.01;
/** Fixed-point representation of {@link #C}. */
private static int C_TIMES_256 = (int)Math.floor( C * 256 );
/** A builder class for {@link GOV3Function}. */
public static class Builder<T> {
protected Iterable<? extends T> keys;
protected TransformationStrategy<? super T> transform;
protected int signatureWidth;
protected File tempDir;
protected ChunkedHashStore<T> chunkedHashStore;
protected LongIterable values;
protected int outputWidth = -1;
protected boolean indirect;
protected boolean compacted;
/** Whether {@link #build()} has already been called. */
protected boolean built;
/** Specifies the keys of the function; if you have specified a {@link #store(ChunkedHashStore) ChunkedHashStore}, it can be {@code null}.
*
* @param keys the keys of the function.
* @return this builder.
*/
public Builder<T> keys( final Iterable<? extends T> keys ) {
this.keys = keys;
return this;
}
/** Specifies the transformation strategy for the {@linkplain #keys(Iterable) keys of the function}; the strategy can be {@linkplain TransformationStrategies raw}.
*
* @param transform a transformation strategy for the {@linkplain #keys(Iterable) keys of the function}.
* @return this builder.
*/
public Builder<T> transform( final TransformationStrategy<? super T> transform ) {
this.transform = transform;
return this;
}
/** Specifies that the resulting {@link GOV3Function} should be signed using a given number of bits per element;
* in this case, you cannot specify {@linkplain #values(LongIterable, int) values}.
*
* @param signatureWidth a signature width, or 0 for no signature (a negative value will have the same effect of {@link #dictionary(int)} with the opposite argument).
* @return this builder.
*/
public Builder<T> signed( final int signatureWidth ) {
this.signatureWidth = signatureWidth;
return this;
}
/** Specifies that the resulting {@link GOV3Function} should be a dictionary: the output value will be a signature,
* and {@link GOV3Function#getLong(Object)} will return 1 or 0 depending on whether the argument was in the key set or not;
* in this case, you cannot specify {@linkplain #values(LongIterable, int) values}.
*
* <p>Note that checking against a signature has the usual probability of a false positive.
*
* @param signatureWidth a signature width, or 0 for no signature (a negative value will have the same effect of {@link #signed(int)} with the opposite argument).
* @return this builder.
*/
public Builder<T> dictionary( final int signatureWidth ) {
this.signatureWidth = - signatureWidth;
return this;
}
/** Specifies a temporary directory for the {@link #store(ChunkedHashStore) ChunkedHashStore}.
*
* @param tempDir a temporary directory for the {@link #store(ChunkedHashStore) ChunkedHashStore} files, or {@code null} for the standard temporary directory.
* @return this builder.
*/
public Builder<T> tempDir( final File tempDir ) {
this.tempDir = tempDir;
return this;
}
public Builder<T> store( final ChunkedHashStore<T> chunkedHashStore ) {
this.chunkedHashStore = chunkedHashStore;
return this;
}
public Builder<T> store( final ChunkedHashStore<T> chunkedHashStore, final int outputWidth ) {
this.chunkedHashStore = chunkedHashStore;
this.outputWidth = outputWidth;
return this;
}
/** Specifies the values assigned to the {@linkplain #keys(Iterable) keys}.
*
* <p>Contrarily to {@link #values(LongIterable)}, this method does not require a complete scan of the value
* to determine the output width.
*
* @param values values to be assigned to each element, in the same order of the {@linkplain #keys(Iterable) keys}.
* @param outputWidth the bit width of the output of the function, which must be enough to represent all {@code values}.
* @return this builder.
* @see #values(LongIterable)
*/
public Builder<T> values( final LongIterable values, final int outputWidth ) {
this.values = values;
this.outputWidth = outputWidth;
return this;
}
/** Specifies the values assigned to the {@linkplain #keys(Iterable) keys}; the output width of the function will
* be the minimum width needed to represent all values.
*
* <p>Contrarily to {@link #values(LongIterable, int)}, this method requires a complete scan of the value
* to determine the output width.
*
* @param values values to be assigned to each element, in the same order of the {@linkplain #keys(Iterable) keys}.
* @return this builder.
* @see #values(LongIterable,int)
*/
public Builder<T> values( final LongIterable values ) {
this.values = values;
int outputWidth = 0;
for( LongIterator i = values.iterator(); i.hasNext(); ) outputWidth = Math.max( outputWidth, Fast.length( i.nextLong() ) );
this.outputWidth = outputWidth;
return this;
}
/** Specifies that the function construction must be indirect: a provided {@linkplain #store(ChunkedHashStore) store} contains
* indices that must be used to access the {@linkplain #values(LongIterable, int) values}.
*
* <p>If you specify this option, the provided values <strong>must</strong> be a {@link LongList} or a {@link LongBigList}.
*
* @return this builder.
*/
public Builder<T> indirect() {
this.indirect = true;
return this;
}
/** Specifies that the function must be <em>compacted</em>.
*
* @return this builder.
*/
public Builder<T> compacted() {
this.compacted = true;
return this;
}
public GOV3Function<T> build() throws IOException {
if ( built ) throw new IllegalStateException( "This builder has been already used" );
built = true;
if ( transform == null ) {
if ( chunkedHashStore != null ) transform = chunkedHashStore.transform();
else throw new IllegalArgumentException( "You must specify a TransformationStrategy, either explicitly or via a given ChunkedHashStore" );
}
return new GOV3Function<T>( keys, transform, signatureWidth, values, outputWidth, indirect, compacted, tempDir, chunkedHashStore );
}
}
/** The logarithm of the desired chunk size. */
public final static int LOG2_CHUNK_SIZE = 10;
/** The shift for chunks. */
private final int chunkShift;
/** The number of keys. */
protected final long n;
/** The number of variables. */
protected final long m;
/** The data width. */
protected final int width;
/** The seed used to generate the initial hash triple. */
protected final long globalSeed;
/** A long containing the start offset of each chunk in the lower 56 bits, and the local seed of each chunk in the upper 8 bits. */
protected final long[] offsetAndSeed;
/** The final magick—the list of modulo-3 values that define the output of the minimal hash function. */
protected final LongBigList data;
/** Optionally, a {@link #rank} structure built on this bit array is used to mark positions containing non-zero value; indexing in {@link #data} is
* made by ranking if this field is non-{@code null}. */
protected final LongArrayBitVector marker;
/** The ranking structure on {@link #marker}. */
protected final Rank16 rank;
/** The transformation strategy to turn objects of type <code>T</code> into bit vectors. */
protected final TransformationStrategy<? super T> transform;
/** The mask to compare signatures, or zero for no signatures. */
protected final long signatureMask;
/** The signatures. */
protected final LongBigList signatures;
/** Creates a new function for the given keys and values.
*
* @param keys the keys in the domain of the function, or {@code null}.
* @param transform a transformation strategy for the keys.
* @param signatureWidth a positive number for a signature width, 0 for no signature, a negative value for a self-signed function; if nonzero, {@code values} must be {@code null} and {@code width} must be -1.
* @param values values to be assigned to each element, in the same order of the iterator returned by <code>keys</code>; if {@code null}, the
* assigned value will the the ordinal number of each element.
* @param dataWidth the bit width of the <code>values</code>, or -1 if <code>values</code> is {@code null}.
* @param indirect if true, <code>chunkedHashStore</code> contains ordinal positions, and <code>values</code> is a {@link LongIterable} that
* must be accessed to retrieve the actual values.
* @param compacted if true, the coefficients will be compacted.
* @param tempDir a temporary directory for the store files, or {@code null} for the standard temporary directory.
* @param chunkedHashStore a chunked hash store containing the keys associated with their ranks (if there are no values, or {@code indirect} is true)
* or values, or {@code null}; the store
* can be unchecked, but in this case <code>keys</code> and <code>transform</code> must be non-{@code null}.
*/
@SuppressWarnings("resource")
protected GOV3Function( final Iterable<? extends T> keys , final TransformationStrategy<? super T> transform , int signatureWidth , final LongIterable values , final int dataWidth , final boolean indirect , final boolean compacted , final File tempDir , ChunkedHashStore<T> chunkedHashStore ) throws IOException {
this.transform = transform;
if ( signatureWidth != 0 && values != null ) throw new IllegalArgumentException( "You cannot sign a function if you specify its values" );
if ( signatureWidth != 0 && dataWidth != -1 ) throw new IllegalArgumentException( "You cannot specify a signature width and a data width" );
final ProgressLogger pl = new ProgressLogger( LOGGER );
pl.displayLocalSpeed = true;
pl.displayFreeMemory = true;
final RandomGenerator r = new XorShift1024StarRandomGenerator();
pl.itemsName = "keys";
final boolean givenChunkedHashStore = chunkedHashStore != null;
if ( ! givenChunkedHashStore ) {
if ( keys == null ) throw new IllegalArgumentException( "If you do not provide a chunked hash store, you must provide the keys" );
chunkedHashStore = new ChunkedHashStore<T>( transform, tempDir, - Math.min( signatureWidth, 0 ), pl );
chunkedHashStore.reset( r.nextLong() );
if ( values == null || indirect ) chunkedHashStore.addAll( keys.iterator() );
else chunkedHashStore.addAll( keys.iterator(), values != null ? values.iterator() : null );
}
n = chunkedHashStore.size();
defRetValue = signatureWidth < 0 ? 0 : -1; // Self-signed maps get zero as default resturn value.
if ( n == 0 ) {
m = globalSeed = chunkShift = width = 0;
data = null;
marker = null;
rank = null;
offsetAndSeed = null;
signatureMask = 0;
signatures = null;
if ( ! givenChunkedHashStore ) chunkedHashStore.close();
return;
}
int log2NumChunks = Math.max( 0, Fast.mostSignificantBit( n >> LOG2_CHUNK_SIZE ) );
chunkShift = chunkedHashStore.log2Chunks( log2NumChunks );
final int numChunks = 1 << log2NumChunks;
LOGGER.debug( "Number of chunks: " + numChunks );
offsetAndSeed = new long[ numChunks + 1 ];
width = signatureWidth < 0 ? -signatureWidth : dataWidth == -1 ? Fast.ceilLog2( n ) : dataWidth;
// Candidate data; might be discarded for compaction.
final OfflineIterable<BitVector,LongArrayBitVector> offlineData = new OfflineIterable<BitVector, LongArrayBitVector>( BitVectors.OFFLINE_SERIALIZER, LongArrayBitVector.getInstance() );
int duplicates = 0;
for(;;) {
LOGGER.debug( "Generating GOV function with " + width + " output bits..." );
pl.expectedUpdates = numChunks;
pl.itemsName = "chunks";
pl.start( "Analysing chunks... " );
final AtomicLong unsolvable = new AtomicLong();
try {
final int numberOfThreads = Runtime.getRuntime().availableProcessors();
final ArrayBlockingQueue<Chunk> chunkQueue = new ArrayBlockingQueue<>(numberOfThreads * 128);
final ReorderingBlockingQueue<long[]> queue = new ReorderingBlockingQueue<>(numberOfThreads * 128);
final ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads + 2);
final ExecutorCompletionService<Void> executorCompletionService = new ExecutorCompletionService<>(executorService);
executorCompletionService.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
final LongArrayBitVector dataBitVector = LongArrayBitVector.getInstance();
final LongBigList data = dataBitVector.asLongBigList( width );
for(;;) {
final long[] solution = queue.take();
if (solution == END_OF_SOLUTION_QUEUE) return null;
data.size(0);
for(long l : solution) data.add(l);
offlineData.add(dataBitVector);
}
}
});
final ChunkedHashStore<T> chs = chunkedHashStore;
executorCompletionService.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
final Iterator<Chunk> iterator = chs.iterator();
for(int i = 0; iterator.hasNext(); i++) {
Chunk chunk = new Chunk(iterator.next());
assert i == chunk.index();
final int chunkLength = C_TIMES_256 * chunk.size() >>> 8;
synchronized(offsetAndSeed) {
offsetAndSeed[ i + 1 ] = offsetAndSeed[ i ] + chunkLength;
}
chunkQueue.put(chunk);
}
for(int i = numberOfThreads; i-- != 0;) chunkQueue.put(END_OF_CHUNK_QUEUE);
return null;
}
});
final AtomicInteger activeThreads = new AtomicInteger(numberOfThreads);
for(int i = numberOfThreads; i-- != 0; ) executorCompletionService.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
long chunkTime = 0, outputTime = 0;
for(;;) {
long start = System.nanoTime();
final Chunk chunk = chunkQueue.take();
chunkTime += System.nanoTime() - start;
if (chunk == END_OF_CHUNK_QUEUE) {
if (activeThreads.decrementAndGet() == 0) queue.put(END_OF_SOLUTION_QUEUE, numChunks);
LOGGER.info("Queue waiting time: " + Util.format(chunkTime / 1E9) + "s");
LOGGER.info("Output waiting time: " + Util.format(outputTime / 1E9) + "s");
return null;
}
long seed = 0;
final Linear3SystemSolver<BitVector> solver =
new Linear3SystemSolver<BitVector>(C_TIMES_256 * chunk.size() >>> 8, chunk.size());
for(;;) {
final boolean solved = solver.generateAndSolve( chunk, seed, new AbstractLongBigList() {
private final LongBigList valueList = indirect ? ( values instanceof LongList ? LongBigLists.asBigList( (LongList)values ) : (LongBigList)values ) : null;
@Override
public long size64() {
return chunk.size();
}
@Override
public long getLong( final long index ) {
return indirect ? valueList.getLong( chunk.data( index ) ) : chunk.data( index );
}
});
unsolvable.addAndGet(solver.unsolvable);
if ( solved ) break;
seed += SEED_STEP;
if ( seed == 0 ) throw new AssertionError( "Exhausted local seeds" );
}
synchronized (offsetAndSeed) {
offsetAndSeed[ chunk.index() ] |= seed;
}
start = System.nanoTime();
queue.put(solver.solution, chunk.index());
outputTime += System.nanoTime() - start;
synchronized(pl) {
pl.update();
}
}
}
});
try {
for(int i = numberOfThreads + 2; i
executorCompletionService.take().get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
if (cause instanceof DuplicateException) throw (DuplicateException)cause;
if (cause instanceof IOException) throw (IOException)cause;
throw new RuntimeException(cause);
}
executorService.shutdown();
LOGGER.info( "Unsolvable systems: " + unsolvable.get() + "/" + numChunks + " (" + Util.format( 100.0 * unsolvable.get() / numChunks ) + "%)");
pl.done();
break;
}
catch( DuplicateException e ) {
if ( keys == null ) throw new IllegalStateException( "You provided no keys, but the chunked hash store was not checked" );
if ( duplicates++ > 3 ) throw new IllegalArgumentException( "The input list contains duplicates" );
LOGGER.warn( "Found duplicate. Recomputing triples..." );
chunkedHashStore.reset( r.nextLong() );
pl.itemsName = "keys";
if ( values == null || indirect ) chunkedHashStore.addAll( keys.iterator() );
else chunkedHashStore.addAll( keys.iterator(), values != null ? values.iterator() : null );
}
}
if ( DEBUG ) System.out.println( "Offsets: " + Arrays.toString( offsetAndSeed ) );
globalSeed = chunkedHashStore.seed();
// Check for compaction
long nonZero = 0;
m = offsetAndSeed[ offsetAndSeed.length - 1 ];
{
final OfflineIterator<BitVector, LongArrayBitVector> iterator = offlineData.iterator();
while( iterator.hasNext() ) {
final LongBigList data = iterator.next().asLongBigList( width );
for( long i = 0; i < data.size64(); i++ ) if ( data.getLong( i ) != 0 ) nonZero++;
}
iterator.close();
}
if ( compacted ) {
LOGGER.info( "Compacting..." );
marker = LongArrayBitVector.ofLength( m );
final LongBigList newData = LongArrayBitVector.getInstance().asLongBigList( width );
newData.size( nonZero );
nonZero = 0;
final OfflineIterator<BitVector, LongArrayBitVector> iterator = offlineData.iterator();
long j = 0;
while( iterator.hasNext() ) {
final LongBigList data = iterator.next().asLongBigList( width );
for( long i = 0; i < data.size64(); i++, j++ ) {
final long value = data.getLong( i );
if ( value != 0 ) {
marker.set( j );
newData.set( nonZero++, value );
}
}
}
iterator.close();
rank = new Rank16( marker );
if ( ASSERTS ) {
final OfflineIterator<BitVector, LongArrayBitVector> iterator2 = offlineData.iterator();
long k = 0;
while( iterator2.hasNext() ) {
final LongBigList data = iterator2.next().asLongBigList( width );
for( long i = 0; i < data.size64(); i++, k++ ) {
final long value = data.getLong( i );
assert ( value != 0 ) == marker.getBoolean( k );
if ( value != 0 ) assert value == newData.getLong( rank.rank( k ) ) : value + " != " + newData.getLong( rank.rank( k ) );
}
}
iterator2.close();
}
this.data = newData;
}
else {
final LongArrayBitVector dataBitVector = LongArrayBitVector.getInstance( m * width );
this.data = dataBitVector.asLongBigList( width );
OfflineIterator<BitVector, LongArrayBitVector> iterator = offlineData.iterator();
while( iterator.hasNext() ) dataBitVector.append( iterator.next() );
iterator.close();
marker = null;
rank = null;
}
offlineData.close();
LOGGER.info( "Completed." );
LOGGER.debug( "Forecast bit cost per element: " + ( marker == null ? C * width : C + width + 0.126 ) );
LOGGER.info( "Actual bit cost per element: " + (double)numBits() / n );
if ( signatureWidth > 0 ) {
signatureMask = -1L >>> Long.SIZE - signatureWidth;
signatures = chunkedHashStore.signatures( signatureWidth, pl );
}
else if ( signatureWidth < 0 ) {
signatureMask = -1L >>> Long.SIZE + signatureWidth;
signatures = null;
}
else {
signatureMask = 0;
signatures = null;
}
if ( ! givenChunkedHashStore ) chunkedHashStore.close();
}
@SuppressWarnings("unchecked")
public long getLong( final Object o ) {
if ( n == 0 ) return defRetValue;
final int[] e = new int[ 3 ];
final long[] h = new long[ 3 ];
Hashes.spooky4( transform.toBitVector( (T)o ), globalSeed, h );
final int chunk = chunkShift == Long.SIZE ? 0 : (int)( h[ 0 ] >>> chunkShift );
final long chunkOffset = offsetAndSeed[ chunk ] & OFFSET_MASK;
Linear3SystemSolver.tripleToEquation( h, offsetAndSeed[ chunk ] & ~OFFSET_MASK, (int)( ( offsetAndSeed[ chunk + 1 ] & OFFSET_MASK ) - chunkOffset ), e );
if ( e[ 0 ] == -1 ) return defRetValue;
final long e0 = e[ 0 ] + chunkOffset, e1 = e[ 1 ] + chunkOffset, e2 = e[ 2 ] + chunkOffset;
final long result = rank == null ?
data.getLong( e0 ) ^ data.getLong( e1 ) ^ data.getLong( e2 ) :
( marker.getBoolean( e0 ) ? data.getLong( rank.rank( e0 ) ) : 0 ) ^
( marker.getBoolean( e1 ) ? data.getLong( rank.rank( e1 ) ) : 0 ) ^
( marker.getBoolean( e2 ) ? data.getLong( rank.rank( e2 ) ) : 0 );
if ( signatureMask == 0 ) return result;
if ( signatures != null ) return result >= n || ( ( signatures.getLong( result ) ^ h[ 0 ] ) & signatureMask ) != 0 ? defRetValue : result;
else return ( ( result ^ h[ 0 ] ) & signatureMask ) != 0 ? defRetValue : 1;
}
/** Low-level access to the output of this function.
*
* <p>This method makes it possible to build several kind of functions on the same {@link ChunkedHashStore} and
* then retrieve the resulting values by generating a single triple of hashes. The method
* {@link TwoStepsGOV3Function#getLong(Object)} is a good example of this technique.
*
* @param triple a triple generated as documented in {@link ChunkedHashStore}.
* @return the output of the function.
*/
public long getLongByTriple( final long[] triple ) {
if ( n == 0 ) return defRetValue;
final int[] e = new int[ 3 ];
final int chunk = chunkShift == Long.SIZE ? 0 : (int)( triple[ 0 ] >>> chunkShift );
final long chunkOffset = offsetAndSeed[ chunk ] & OFFSET_MASK;
Linear3SystemSolver.tripleToEquation( triple, offsetAndSeed[ chunk ] & ~OFFSET_MASK, (int)( ( offsetAndSeed[ chunk + 1 ] & OFFSET_MASK ) - chunkOffset ), e );
final long e0 = e[ 0 ] + chunkOffset, e1 = e[ 1 ] + chunkOffset, e2 = e[ 2 ] + chunkOffset;
if ( e0 == -1 ) return defRetValue;
final long result = rank == null ?
data.getLong( e0 ) ^ data.getLong( e1 ) ^ data.getLong( e2 ) :
( marker.getBoolean( e0 ) ? data.getLong( rank.rank( e0 ) ) : 0 ) ^
( marker.getBoolean( e1 ) ? data.getLong( rank.rank( e1 ) ) : 0 ) ^
( marker.getBoolean( e2 ) ? data.getLong( rank.rank( e2 ) ) : 0 );
if ( signatureMask == 0 ) return result;
if ( signatures != null ) return result >= n || signatures.getLong( result ) != ( triple[ 0 ] & signatureMask ) ? defRetValue : result;
else return ( ( result ^ triple[ 0 ] ) & signatureMask ) != 0 ? defRetValue : 1;
}
/** Returns the number of keys in the function domain.
*
* @return the number of the keys in the function domain.
*/
public long size64() {
return n;
}
@Deprecated
public int size() {
return n > Integer.MAX_VALUE ? -1 : (int)n;
}
/** Returns the number of bits used by this structure.
*
* @return the number of bits used by this structure.
*/
public long numBits() {
if ( n == 0 ) return 0;
return ( marker != null ? rank.numBits() + marker.length() : 0 ) + ( data != null ? data.size64() : 0 ) * width + offsetAndSeed.length * (long)Long.SIZE;
}
public boolean containsKey( final Object o ) {
return true;
}
public static void main( final String[] arg ) throws NoSuchMethodException, IOException, JSAPException {
final SimpleJSAP jsap = new SimpleJSAP( GOV3Function.class.getName(), "Builds a GOV function mapping a newline-separated list of strings to their ordinal position, or to specific values.",
new Parameter[] {
new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The string file encoding." ),
new FlaggedOption( "tempDir", FileStringParser.getParser(), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'T', "temp-dir", "A directory for temporary files." ),
new Switch( "iso", 'i', "iso", "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)." ),
new Switch( "utf32", JSAP.NO_SHORTFLAG, "utf-32", "Use UTF-32 internally (handles surrogate pairs)." ),
new Switch( "byteArray", 'b', "byte-array", "Create a function on byte arrays (no character encoding)." ),
new FlaggedOption( "signatureWidth", JSAP.INTEGER_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 's', "signature-width", "If specified, the signature width in bits; if negative, the generated function will be a dictionary." ),
new Switch( "compacted", 'c', "compacted", "Whether the resulting function should be compacted." ),
new Switch( "zipped", 'z', "zipped", "The string list is compressed in gzip format." ),
new FlaggedOption( "values", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'v', "values", "A binary file in DataInput format containing a long for each string (otherwise, the values will be the ordinal positions of the strings)." ),
new UnflaggedOption( "function", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised GOV function." ),
new UnflaggedOption( "stringFile", JSAP.STRING_PARSER, "-", JSAP.NOT_REQUIRED, JSAP.NOT_GREEDY, "The name of a file containing a newline-separated list of strings, or - for standard input; in the first case, strings will not be loaded into core memory." ),
});
JSAPResult jsapResult = jsap.parse( arg );
if ( jsap.messagePrinted() ) return;
final String functionName = jsapResult.getString( "function" );
final String stringFile = jsapResult.getString( "stringFile" );
final Charset encoding = (Charset)jsapResult.getObject( "encoding" );
final File tempDir = jsapResult.getFile( "tempDir" );
final boolean byteArray = jsapResult.getBoolean( "byteArray" );
final boolean zipped = jsapResult.getBoolean( "zipped" );
final boolean compacted = jsapResult.getBoolean( "compacted" );
final boolean iso = jsapResult.getBoolean( "iso" );
final boolean utf32 = jsapResult.getBoolean( "utf32" );
final int signatureWidth = jsapResult.getInt( "signatureWidth", 0 );
if ( byteArray ) {
if ( "-".equals( stringFile ) ) throw new IllegalArgumentException( "Cannot read from standard input when building byte-array functions" );
if ( iso || utf32 || jsapResult.userSpecified( "encoding" ) ) throw new IllegalArgumentException( "Encoding options are not available when building byte-array functions" );
final Collection<byte[]> collection= new FileLinesByteArrayCollection( stringFile, zipped );
BinIO.storeObject( new GOV3Function<byte[]>( collection, TransformationStrategies.rawByteArray(), signatureWidth, null, -1, false, compacted, tempDir, null ), functionName );
}
else {
final Collection<MutableString> collection;
if ( "-".equals( stringFile ) ) {
final ProgressLogger pl = new ProgressLogger( LOGGER );
pl.displayLocalSpeed = true;
pl.displayFreeMemory = true;
pl.start( "Loading strings..." );
collection = new LineIterator( new FastBufferedReader( new InputStreamReader( zipped ? new GZIPInputStream( System.in ) : System.in, encoding ) ), pl ).allLines();
pl.done();
}
else collection = new FileLinesCollection( stringFile, encoding.toString(), zipped );
final TransformationStrategy<CharSequence> transformationStrategy = iso
? TransformationStrategies.rawIso()
: utf32
? TransformationStrategies.rawUtf32()
: TransformationStrategies.rawUtf16();
if ( jsapResult.userSpecified( "values" ) ) {
final String values = jsapResult.getString( "values" );
int dataWidth = 0;
for( LongIterator i = BinIO.asLongIterator( values ); i.hasNext(); ) dataWidth = Math.max( dataWidth, Fast.length( i.nextLong() ) );
BinIO.storeObject( new GOV3Function<CharSequence>( collection, transformationStrategy, signatureWidth, BinIO.asLongIterable( values ), dataWidth, false, compacted, tempDir, null ), functionName );
}
else BinIO.storeObject( new GOV3Function<CharSequence>( collection, transformationStrategy, signatureWidth, null, -1, false, compacted, tempDir, null ), functionName );
}
LOGGER.info( "Completed." );
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc.depot;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.samskivert.jdbc.depot.Key.WhereCondition;
import com.samskivert.jdbc.depot.annotation.Computed;
import com.samskivert.jdbc.depot.clause.DeleteClause;
import com.samskivert.jdbc.depot.clause.FieldDefinition;
import com.samskivert.jdbc.depot.clause.FieldOverride;
import com.samskivert.jdbc.depot.clause.ForUpdate;
import com.samskivert.jdbc.depot.clause.FromOverride;
import com.samskivert.jdbc.depot.clause.GroupBy;
import com.samskivert.jdbc.depot.clause.InsertClause;
import com.samskivert.jdbc.depot.clause.Join;
import com.samskivert.jdbc.depot.clause.Limit;
import com.samskivert.jdbc.depot.clause.OrderBy;
import com.samskivert.jdbc.depot.clause.SelectClause;
import com.samskivert.jdbc.depot.clause.UpdateClause;
import com.samskivert.jdbc.depot.clause.Where;
import com.samskivert.jdbc.depot.expression.ColumnExp;
import com.samskivert.jdbc.depot.expression.ExpressionVisitor;
import com.samskivert.jdbc.depot.expression.FunctionExp;
import com.samskivert.jdbc.depot.expression.LiteralExp;
import com.samskivert.jdbc.depot.expression.SQLExpression;
import com.samskivert.jdbc.depot.expression.ValueExp;
import com.samskivert.jdbc.depot.operator.Conditionals.Exists;
import com.samskivert.jdbc.depot.operator.Conditionals.In;
import com.samskivert.jdbc.depot.operator.Conditionals.IsNull;
import com.samskivert.jdbc.depot.operator.Conditionals.FullTextMatch;
import com.samskivert.jdbc.depot.operator.Logic.Not;
import com.samskivert.jdbc.depot.operator.SQLOperator.BinaryOperator;
import com.samskivert.jdbc.depot.operator.SQLOperator.MultiOperator;
/**
* Implements the base functionality of the SQL-building pass of {@link SQLBuilder}. Dialectal
* subclasses of this should be created and returned from {@link SQLBuilder#getBuildVisitor()}.
*
* This class is intimately paired with {#link BindVisitor}.
*/
public abstract class BuildVisitor implements ExpressionVisitor
{
public String getQuery ()
{
return _builder.toString();
}
public void visit (FromOverride override)
throws Exception
{
_builder.append(" from " );
List<Class<? extends PersistentRecord>> from = override.getFromClasses();
for (int ii = 0; ii < from.size(); ii++) {
if (ii > 0) {
_builder.append(", ");
}
appendTableName(from.get(ii));
_builder.append(" as ");
appendTableAbbreviation(from.get(ii));
}
}
public void visit (FieldDefinition definition)
throws Exception
{
definition.getDefinition().accept(this);
if (_enableAliasing) {
_builder.append(" as ");
appendIdentifier(definition.getField());
}
}
public void visit (WhereCondition<? extends PersistentRecord> whereCondition)
throws Exception
{
Class<? extends PersistentRecord> pClass = whereCondition.getPersistentClass();
String[] keyFields = Key.getKeyFields(pClass);
List<Comparable> values = whereCondition.getValues();
for (int ii = 0; ii < keyFields.length; ii ++) {
if (ii > 0) {
_builder.append(" and ");
}
// A Key's WHERE clause must mirror what's actually retrieved for the persistent
// object, so we turn on overrides here just as we do when expanding SELECT fields
boolean saved = _enableOverrides;
_enableOverrides = true;
appendRhsColumn(pClass, keyFields[ii]);
_enableOverrides = saved;
_builder.append(values.get(ii) == null ? " is null " : " = ? ");
}
}
public void visit (Key key)
throws Exception
{
_builder.append(" where ");
key.condition.accept(this);
}
public void visit (MultiKey<? extends PersistentRecord> key)
throws Exception
{
_builder.append(" where ");
boolean first = true;
for (Map.Entry<String, Comparable> entry : key.getSingleFieldsMap().entrySet()) {
if (first) {
first = false;
} else {
_builder.append(" and ");
}
// A MultiKey's WHERE clause must mirror what's actually retrieved for the persistent
// object, so we turn on overrides here just as we do when expanding SELECT fields
boolean saved = _enableOverrides;
_enableOverrides = true;
appendRhsColumn(key.getPersistentClass(), entry.getKey());
_enableOverrides = saved;
_builder.append(entry.getValue() == null ? " is null " : " = ? ");
}
if (!first) {
_builder.append(" and ");
}
appendRhsColumn(key.getPersistentClass(), key.getMultiField());
_builder.append(" in (");
Comparable[] values = key.getMultiValues();
for (int ii = 0; ii < values.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
_builder.append("?");
}
_builder.append(")");
}
public void visit (FunctionExp functionExp)
throws Exception
{
_builder.append(functionExp.getFunction());
_builder.append("(");
SQLExpression[] arguments = functionExp.getArguments();
for (int ii = 0; ii < arguments.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
arguments[ii].accept(this);
}
_builder.append(")");
}
public void visit (MultiOperator multiOperator)
throws Exception
{
SQLExpression[] conditions = multiOperator.getConditions();
for (int ii = 0; ii < conditions.length; ii++) {
if (ii > 0) {
_builder.append(" ").append(multiOperator.operator()).append(" ");
}
_builder.append("(");
conditions[ii].accept(this);
_builder.append(")");
}
}
public void visit (BinaryOperator binaryOperator)
throws Exception
{
_builder.append('(');
binaryOperator.getLeftHandSide().accept(this);
_builder.append(binaryOperator.operator());
binaryOperator.getRightHandSide().accept(this);
_builder.append(')');
}
public void visit (IsNull isNull)
throws Exception
{
isNull.getColumn().accept(this);
_builder.append(" is null");
}
public void visit (In in)
throws Exception
{
in.getColumn().accept(this);
_builder.append(" in (");
Comparable[] values = in.getValues();
for (int ii = 0; ii < values.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
_builder.append("?");
}
_builder.append(")");
}
public abstract void visit (FullTextMatch match)
throws Exception;
public void visit (ColumnExp columnExp)
throws Exception
{
appendRhsColumn(columnExp.getPersistentClass(), columnExp.getField());
}
public void visit (Not not)
throws Exception
{
_builder.append(" not (");
not.getCondition().accept(this);
_builder.append(")");
}
public void visit (GroupBy groupBy)
throws Exception
{
_builder.append(" group by ");
SQLExpression[] values = groupBy.getValues();
for (int ii = 0; ii < values.length; ii++) {
if (ii > 0) {
_builder.append(", ");
}
values[ii].accept(this);
}
}
public void visit (ForUpdate forUpdate)
throws Exception
{
_builder.append(" for update ");
}
public void visit (OrderBy orderBy)
throws Exception
{
_builder.append(" order by ");
SQLExpression[] values = orderBy.getValues();
OrderBy.Order[] orders = orderBy.getOrders();
for (int ii = 0; ii < values.length; ii++) {
if (ii > 0) {
_builder.append(", ");
}
values[ii].accept(this);
_builder.append(" ").append(orders[ii]);
}
}
public void visit (Where where)
throws Exception
{
_builder.append(" where ");
where.getCondition().accept(this);
}
public void visit (Join join)
throws Exception
{
switch (join.getType()) {
case INNER:
_builder.append(" inner join " );
break;
case LEFT_OUTER:
_builder.append(" left outer join " );
break;
case RIGHT_OUTER:
_builder.append(" right outer join " );
break;
}
appendTableName(join.getJoinClass());
_builder.append(" as ");
appendTableAbbreviation(join.getJoinClass());
_builder.append(" on ");
join.getJoinCondition().accept(this);
}
public void visit (Limit limit)
throws Exception
{
_builder.append(" limit ? offset ? ");
}
public void visit (LiteralExp literalExp)
throws Exception
{
_builder.append(literalExp.getText());
}
public void visit (ValueExp valueExp)
throws Exception
{
_builder.append("?");
}
public void visit (Exists<? extends PersistentRecord> exists)
throws Exception
{
_builder.append("exists ");
exists.getSubClause().accept(this);
}
public void visit (SelectClause<? extends PersistentRecord> selectClause)
throws Exception
{
Class<? extends PersistentRecord> pClass = selectClause.getPersistentClass();
boolean isInner = _innerClause;
_innerClause = true;
if (isInner) {
_builder.append("(");
}
_builder.append("select ");
if (_definitions.containsKey(pClass)) {
throw new IllegalArgumentException(
"Can not yet nest SELECTs on the same persistent record.");
}
Map<String, FieldDefinition> definitionMap = new HashMap<String, FieldDefinition>();
for (FieldDefinition definition : selectClause.getFieldDefinitions()) {
definitionMap.put(definition.getField(), definition);
}
_definitions.put(pClass, definitionMap);
try {
// iterate over the fields we're filling in and figure out whence each one comes
boolean skip = true;
// while expanding column names in the SELECT query, do aliasing and expansion
_enableAliasing = _enableOverrides = true;
for (String field : selectClause.getFields()) {
if (!skip) {
_builder.append(", ");
}
skip = false;
int len = _builder.length();
appendRhsColumn(pClass, field);
// if nothing was added, don't add a comma
if (_builder.length() == len) {
skip = true;
}
}
// then stop
_enableAliasing = _enableOverrides = false;
if (selectClause.getFromOverride() != null) {
selectClause.getFromOverride().accept(this);
} else {
Computed computed = _types.getMarshaller(pClass).getComputed();
Class<? extends PersistentRecord> tClass;
if (computed != null && !PersistentRecord.class.equals(computed.shadowOf())) {
tClass = computed.shadowOf();
} else if (_types.getTableName(pClass) != null) {
tClass = pClass;
} else {
throw new SQLException("Query on @Computed entity with no FromOverrideClause.");
}
_builder.append(" from ");
appendTableName(tClass);
_builder.append(" as ");
appendTableAbbreviation(tClass);
}
for (Join clause : selectClause.getJoinClauses()) {
clause.accept(this);
}
if (selectClause.getWhereClause() != null) {
selectClause.getWhereClause().accept(this);
}
if (selectClause.getGroupBy() != null) {
selectClause.getGroupBy().accept(this);
}
if (selectClause.getOrderBy() != null) {
selectClause.getOrderBy().accept(this);
}
if (selectClause.getLimit() != null) {
selectClause.getLimit().accept(this);
}
if (selectClause.getForUpdate() != null) {
selectClause.getForUpdate().accept(this);
}
} finally {
_definitions.remove(pClass);
}
if (isInner) {
_builder.append(")");
}
}
public void visit (UpdateClause<? extends PersistentRecord> updateClause)
throws Exception
{
if (updateClause.getWhereClause() == null) {
throw new SQLException("I dare not currently perform UPDATE without a WHERE clause.");
}
Class<? extends PersistentRecord> pClass = updateClause.getPersistentClass();
_innerClause = true;
_builder.append("update ");
appendTableName(pClass);
_builder.append(" as ");
appendTableAbbreviation(pClass);
_builder.append(" set ");
String[] fields = updateClause.getFields();
Object pojo = updateClause.getPojo();
SQLExpression[] values = updateClause.getValues();
for (int ii = 0; ii < fields.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
appendLhsColumn(pClass, fields[ii]);
_builder.append(" = ");
if (pojo != null) {
_builder.append("?");
} else {
values[ii].accept(this);
}
}
updateClause.getWhereClause().accept(this);
}
public void visit (DeleteClause<? extends PersistentRecord> deleteClause)
throws Exception
{
_builder.append("delete from ");
appendTableName(deleteClause.getPersistentClass());
_builder.append(" as ");
appendTableAbbreviation(deleteClause.getPersistentClass());
_builder.append(" ");
deleteClause.getWhereClause().accept(this);
}
public void visit (InsertClause<? extends PersistentRecord> insertClause)
throws Exception
{
Class<? extends PersistentRecord> pClass = insertClause.getPersistentClass();
DepotMarshaller marsh = _types.getMarshaller(pClass);
_innerClause = true;
String[] fields = marsh.getColumnFieldNames();
_builder.append("insert into ");
appendTableName(insertClause.getPersistentClass());
_builder.append(" (");
for (int ii = 0; ii < fields.length; ii ++) {
if (ii > 0) {
_builder.append(", ");
}
appendLhsColumn(pClass, fields[ii]);
}
_builder.append(") values(");
Set<String> idFields = insertClause.getIdentityFields();
for (int ii = 0; ii < fields.length; ii++) {
if (ii > 0) {
_builder.append(", ");
}
if (idFields.contains(fields[ii])) {
_builder.append("DEFAULT");
} else {
_builder.append("?");
}
}
_builder.append(")");
}
protected abstract void appendIdentifier (String field);
protected void appendTableName (Class<? extends PersistentRecord> type)
{
appendIdentifier(_types.getTableName(type));
}
protected void appendTableAbbreviation (Class<? extends PersistentRecord> type)
{
appendIdentifier(_types.getTableAbbreviation(type));
}
// Constructs a name used for assignment in e.g. INSERT/UPDATE. This is the SQL
// equivalent of an lvalue; something that can appear to the left of an equals sign.
// We do not prepend this identifier with a table abbreviation, nor do we expand
// field overrides, shadowOf declarations, or the like: it is just a column name.
protected void appendLhsColumn (Class<? extends PersistentRecord> type, String field)
throws Exception
{
DepotMarshaller dm = _types.getMarshaller(type);
FieldMarshaller fm = dm.getFieldMarshaller(field);
if (dm == null) {
throw new IllegalArgumentException(
"Unknown field on persistent record [record=" + type + ", field=" + field + "]");
}
appendIdentifier(fm.getColumnName());
}
// Appends an expression for the given field on the given persistent record; this can
// appear in a SELECT list, in WHERE clauses, etc, etc.
protected void appendRhsColumn (Class<? extends PersistentRecord> type, String field)
throws Exception
{
DepotMarshaller dm = _types.getMarshaller(type);
FieldMarshaller fm = dm.getFieldMarshaller(field);
if (dm == null) {
throw new IllegalArgumentException(
"Unknown field on persistent record [record=" + type + ", field=" + field + "]");
}
Map<String, FieldDefinition> fieldOverrides = _definitions.get(type);
if (fieldOverrides != null) {
// first, see if there's a field override
FieldDefinition override = fieldOverrides.get(field);
if (override != null) {
boolean useOverride;
if (override instanceof FieldOverride) {
if (fm.getComputed() != null || dm.getComputed() != null) {
throw new IllegalArgumentException(
"FieldOverride cannot be used on @Computed field: " + field);
}
useOverride = _enableOverrides;
} else if (fm.getComputed() == null && dm.getComputed() == null) {
throw new IllegalArgumentException(
"FieldDefinition must not be used on concrete field: " + field);
} else {
useOverride = true;
}
if (useOverride) {
// If a FieldOverride's target is in turn another FieldOverride, the second
// one is ignored. As an example, when creating ItemRecords from CloneRecords,
// we make Item.itemId = Clone.itemId. We also make Item.parentId = Item.itemId
// and would be dismayed to find Item.parentID = Item.itemId = Clone.itemId.
boolean saved = _enableOverrides;
_enableOverrides = false;
override.accept(this);
_enableOverrides = saved;
return;
}
}
}
Computed entityComputed = dm.getComputed();
// figure out the class we're selecting from unless we're otherwise overriden:
// for a concrete record, simply use the corresponding table; for a computed one,
// default to the shadowed concrete record, or null if there isn't one
Class<? extends PersistentRecord> tableClass;
if (entityComputed == null) {
tableClass = type;
} else if (!PersistentRecord.class.equals(entityComputed.shadowOf())) {
tableClass = entityComputed.shadowOf();
} else {
tableClass = null;
}
// handle the field-level @Computed annotation, if there is one
Computed fieldComputed = fm.getComputed();
if (fieldComputed != null) {
// check if the computed field has a literal SQL definition
if (fieldComputed.fieldDefinition().length() > 0) {
_builder.append(fieldComputed.fieldDefinition());
if (_enableAliasing) {
_builder.append(" as ");
appendIdentifier(field);
}
return;
}
// or if we can simply ignore the field
if (!fieldComputed.required()) {
return;
}
// else see if there's an overriding shadowOf definition
if (fieldComputed.shadowOf() != null) {
tableClass = fieldComputed.shadowOf();
}
}
// if we get this far we hopefully have a table to select from
if (tableClass != null) {
appendTableAbbreviation(tableClass);
_builder.append(".");
appendIdentifier(fm.getColumnName());
return;
}
// else owie
throw new IllegalArgumentException(
"Persistent field has no definition [class=" + type + ", field=" + field + "]");
}
protected BuildVisitor (DepotTypes types)
{
_types = types;
}
protected DepotTypes _types;
/** A StringBuilder to hold the constructed SQL. */
protected StringBuilder _builder = new StringBuilder();
/** A mapping of field overrides per persistent record. */
protected Map<Class<? extends PersistentRecord>, Map<String, FieldDefinition>> _definitions=
new HashMap<Class<? extends PersistentRecord>, Map<String,FieldDefinition>>();
/** A flag that's set to true for inner SELECT's */
protected boolean _innerClause = false;
protected boolean _enableOverrides = false;
protected boolean _enableAliasing = false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.